Full Code of Soluto/oidc-server-mock for AI

main 06a84eb15a53 cached
80 files
118.2 KB
32.8k tokens
64 symbols
1 requests
Download .txt
Repository: Soluto/oidc-server-mock
Branch: main
Commit: 06a84eb15a53
Files: 80
Total size: 118.2 KB

Directory structure:
gitextract_w8n89fhc/

├── .commitlintrc.yml
├── .editorconfig
├── .gitattributes
├── .github/
│   └── workflows/
│       ├── pr.yaml
│       └── tag.yaml
├── .gitignore
├── .husky/
│   ├── commit-msg
│   └── pre-commit
├── .lintstagedrc
├── .nvmrc
├── .prettierignore
├── .prettierrc
├── .vscode/
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── LICENSE
├── README.md
├── Tiltfile
├── e2e/
│   ├── config/
│   │   ├── api-resources.yaml
│   │   ├── clients.json
│   │   ├── identity-resources.json
│   │   ├── server-options.json
│   │   └── users.yaml
│   ├── docker-compose.override.yml
│   ├── docker-compose.yml
│   ├── helpers/
│   │   ├── authorization-endpoint.ts
│   │   ├── endpoints.ts
│   │   ├── grants.ts
│   │   ├── index.ts
│   │   ├── introspect-endpoint.ts
│   │   ├── token-endpoint.ts
│   │   └── user-info-endpoint.ts
│   ├── https/
│   │   └── aspnetapp.pfx
│   ├── jest.config.ts
│   ├── package.json
│   ├── tests/
│   │   ├── __snapshots__/
│   │   │   └── base-path.spec.ts.snap
│   │   ├── base-path.spec.ts
│   │   ├── custom-endpoints/
│   │   │   ├── __snapshots__/
│   │   │   │   └── user-management.spec.ts.snap
│   │   │   └── user-management.spec.ts
│   │   └── flows/
│   │       ├── __snapshots__/
│   │       │   ├── authorization-code-pkce.e2e-spec.ts.snap
│   │       │   ├── authorization-code.e2e-spec.ts.snap
│   │       │   ├── client-credentials-flow.spec.ts.snap
│   │       │   ├── implicit-flow.e2e-spec.ts.snap
│   │       │   └── password-flow.spec.ts.snap
│   │       ├── authorization-code-pkce.e2e-spec.ts
│   │       ├── authorization-code.e2e-spec.ts
│   │       ├── client-credentials-flow.spec.ts
│   │       ├── implicit-flow.e2e-spec.ts
│   │       └── password-flow.spec.ts
│   ├── tsconfig.json
│   ├── types/
│   │   ├── api-resource.ts
│   │   ├── claim.ts
│   │   ├── client.ts
│   │   ├── index.ts
│   │   └── user.ts
│   └── utils/
│       ├── jwt-payload-serializer.js
│       └── jwt-serializer.js
├── eslint.config.js
├── package.json
├── pnpm-workspace.yaml
├── src/
│   ├── .dockerignore
│   ├── Config.cs
│   ├── Controllers/
│   │   ├── HealthController.cs
│   │   └── UserController.cs
│   ├── Dockerfile
│   ├── Helpers/
│   │   ├── AspNetServicesHelper.cs
│   │   ├── MergeHelper.cs
│   │   └── OptionsHelper.cs
│   ├── JsonConverters/
│   │   └── ClaimJsonConverter.cs
│   ├── Middlewares/
│   │   └── BasePathMiddleware.cs
│   ├── OpenIdConnectServerMock.csproj
│   ├── Program.cs
│   ├── Services/
│   │   ├── CorsPolicyService.cs
│   │   └── ProfileService.cs
│   ├── Validation/
│   │   └── RedirectUriValidator.cs
│   ├── YamlConverters/
│   │   ├── ClaimYamlConverter.cs
│   │   └── SecretYamlConverter.cs
│   ├── getui.sh
│   └── tempkey.rsa
└── tsconfig.json

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

================================================
FILE: .commitlintrc.yml
================================================
extends:
  - '@commitlint/config-conventional'


================================================
FILE: .editorconfig
================================================
root = true

[*]
indent_style = space
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.{ts,js,json,yaml,yml}]
indent_size = 2

[*.cs]
indent_size = 4


================================================
FILE: .gitattributes
================================================
*.sh text eol=lf


================================================
FILE: .github/workflows/pr.yaml
================================================
name: PR

on:
  pull_request:
    paths-ignore:
      - README.md

  workflow_dispatch:

concurrency:
  group: pr-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

env:
  TILT_VERSION: 'v0.34.2'

jobs:
  tests:
    name: Tests
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup Tilt
        run: curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/${TILT_VERSION}/scripts/install.sh | bash

      - name: Setup pnpm
        uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version-file: .nvmrc
          cache: pnpm

      - name: Run npm install
        run: pnpm install --frozen-lockfile

      - name: Install playwright dependencies
        run: pnpm --filter e2e exec playwright install --with-deps chromium

      - name: Eslint
        run: pnpm run lint

      - name: Run Tests
        run: pnpm run tilt:ci


================================================
FILE: .github/workflows/tag.yaml
================================================
name: Build and push new version

on:
  create:

env:
  TILT_VERSION: 'v0.34.2'

jobs:
  build_push_docker:
    name: Build and Push Docker image
    if: ${{ startsWith(github.ref, 'refs/tags/v') }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Login to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - id: get_version
        name: Format docker image tag
        uses: battila7/get-version-action@v2

      - id: repository_owner
        name: Format repository owner
        uses: ASzc/change-string-case-action@v6
        with:
          string: ${{ github.repository_owner }}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and export to Docker
        uses: docker/build-push-action@v6
        with:
          load: true
          context: ./src
          file: ./src/Dockerfile
          tags: ghcr.io/${{ steps.repository_owner.outputs.lowercase }}/oidc-server-mock:${{ steps.get_version.outputs.version-without-v }}-test

      - name: Setup Tilt
        run: curl -fsSL https://raw.githubusercontent.com/tilt-dev/tilt/${TILT_VERSION}/scripts/install.sh | bash

      - name: Setup pnpm
        uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version-file: .nvmrc
          cache: pnpm

      - name: Run npm install
        run: pnpm install --frozen-lockfile

      - name: Install playwright dependencies
        run: pnpm --filter e2e exec playwright install --with-deps chromium

      - name: Run Tests
        run: pnpm run tilt:ci
        env:
          IMAGE_TAG: ${{ steps.get_version.outputs.version-without-v }}-test

      - name: Build and push new docker image
        uses: docker/build-push-action@v6
        with:
          push: true
          context: ./src
          file: ./src/Dockerfile
          platforms: linux/amd64,linux/arm64
          tags: |
            ghcr.io/${{ steps.repository_owner.outputs.lowercase }}/oidc-server-mock:latest
            ghcr.io/${{ steps.repository_owner.outputs.lowercase }}/oidc-server-mock:${{ steps.get_version.outputs.version-without-v }}
          labels: |
            org.opencontainers.image.source=${{ github.event.repository.html_url }}

  build_push_nuget:
    name: Build and Push Nuget package
    if: ${{ startsWith(github.ref, 'refs/tags/v') }}
    runs-on: ubuntu-latest
    permissions:
      packages: write
      contents: read
    defaults:
      run:
        working-directory: src
    env:
      NUGET_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      dotnet-version: '8.0'
    steps:
      - uses: actions/checkout@v4

      - name: Download UI
        run: ./getui.sh

      - name: Setup .NET Core SDK ${{ env.dotnet-version }}
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: ${{ env.dotnet-version }}
          source-url: https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json

      - name: Install dependencies
        run: dotnet restore

      - id: get_version
        name: Format nuget package version
        uses: battila7/get-version-action@v2

      - name: Build Nuget package
        run: |
          dotnet pack --no-restore --configuration Release \
            /p:VersionPrefix=${{ steps.get_version.outputs.version-without-v }} \
            /p:RepositoryCommit=${{ github.sha }}

      - name: Push Nuget package
        run: dotnet nuget push bin/Release/*.nupkg -k ${{ env.NUGET_AUTH_TOKEN }}


================================================
FILE: .gitignore
================================================
# TypeScript project
node_modules
dist

# .Net project
bin
obj

# Docker
.docker

# UI
src/Pages
src/wwwroot

# Runtime data
keys
tempkey.jwk


================================================
FILE: .husky/commit-msg
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no-install commitlint --edit "$1"


================================================
FILE: .husky/pre-commit
================================================
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx lint-staged
npx pretty-quick --staged


================================================
FILE: .lintstagedrc
================================================
"**/*.js":
  - prettier --write
"**/*.ts":
  - bash -c "tsc --noEmit"
  - eslint --fix
  - prettier --write
"**/*.{json,yaml,yml,md}":
  - prettier --write



================================================
FILE: .nvmrc
================================================
v22


================================================
FILE: .prettierignore
================================================
**/node_modules
**/dist
coverage


================================================
FILE: .prettierrc
================================================
{
  "printWidth": 120,
  "singleQuote": true,
  "arrowParens": "avoid"
}


================================================
FILE: .vscode/launch.json
================================================
{
   // 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/bin/Debug/netcoreapp3.1/OpenIdConnectServerMock.dll",
            "args": [],
            "cwd": "${workspaceFolder}/src",
            "stopAtEntry": false,
            // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
            "serverReadyAction": {
                "action": "openExternally",
                "pattern": "^\\s*Now listening on:\\s+(https?://\\S+)"
            },
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "sourceFileMap": {
                "/Views": "${workspaceFolder}/Views"
            }
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:pickProcess}"
        }
    ]
}

================================================
FILE: .vscode/settings.json
================================================
{
  "editor.formatOnPaste": false,
  "editor.formatOnSave": true,
  "editor.detectIndentation": false,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[properties]": {
    "editor.defaultFormatter": "foxundermoon.shell-format"
  },
  "[dotenv]": {
    "editor.defaultFormatter": "foxundermoon.shell-format"
  },
  "files.eol": "\n",
  "eslint.workingDirectories": [
    {
      "mode": "auto"
    }
  ],
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true,
  "[dockerfile]": {
    "editor.defaultFormatter": "ms-azuretools.vscode-docker"
  }
}


================================================
FILE: .vscode/tasks.json
================================================
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/src/OpenIdConnectServerMock.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/src/OpenIdConnectServerMock.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "${workspaceFolder}/src/OpenIdConnectServerMock.csproj",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# OpenId Connect Server Mock

![Run Tests badge](https://github.com/Soluto/oidc-server-mock/workflows/Run%20Tests/badge.svg)

This project allows you to run configurable mock server with OpenId Connect functionality.

## Important

> Free for development, testing and personal projects. For production you need to purchase [Duende IdentityServer license](https://duendesoftware.com/products/identityserver).

## Simple Configuration

The image is stored in `github` registry. Use the following to pull the image:

```bash
docker pull ghcr.io/soluto/oidc-server-mock:latest
```

This is the sample of using the server in `docker-compose` configuration:

```yaml
services:
  oidc-server-mock:
    container_name: oidc-server-mock
    image: ghcr.io/soluto/oidc-server-mock:latest
    ports:
      - '4011:80'
    environment:
      ASPNETCORE_ENVIRONMENT: Development
      SERVER_OPTIONS_INLINE: |
        {
          "AccessTokenJwtType": "JWT",
          "Discovery": {
            "ShowKeySet": true
          },
          "Authentication": {
            "CookieSameSiteMode": "Lax",
            "CheckSessionCookieSameSiteMode": "Lax"
          }
        }
      LOGIN_OPTIONS_INLINE: |
        {
          "AllowRememberLogin": false
        }
      LOGOUT_OPTIONS_INLINE: |
        {
          "AutomaticRedirectAfterSignOut": true
        }
      API_SCOPES_INLINE: |
        - Name: some-app-scope-1
        - Name: some-app-scope-2
      API_RESOURCES_INLINE: |
        - Name: some-app
          Scopes:
            - some-app-scope-1
            - some-app-scope-2
      USERS_CONFIGURATION_INLINE: |
        [
          {
            "SubjectId":"1",
            "Username":"User1",
            "Password":"pwd",
            "Claims": [
              {
                "Type": "name",
                "Value": "Sam Tailor",
                "ValueType": "string"
              },
              {
                "Type": "email",
                "Value": "sam.tailor@gmail.com",
                "ValueType": "string"
              },
              {
                "Type": "some-api-resource-claim",
                "Value": "Sam's Api Resource Custom Claim",
                "ValueType": "string"
              },
              {
                "Type": "some-api-scope-claim",
                "Value": "Sam's Api Scope Custom Claim",
                "ValueType": "string"
              },
              {
                "Type": "some-identity-resource-claim",
                "Value": "Sam's Identity Resource Custom Claim",
                "ValueType": "string"
              }
            ]
          }
        ]
      CLIENTS_CONFIGURATION_PATH: /tmp/config/clients-config.json
      ASPNET_SERVICES_OPTIONS_INLINE: |
        {
          "ForwardedHeadersOptions": {
            "ForwardedHeaders" : "All"
          }
        }
    volumes:
      - .:/tmp/config:ro
```

When `clients-config.json` is as following:

```json
[
  {
    "ClientId": "implicit-mock-client",
    "Description": "Client for implicit flow",
    "AllowedGrantTypes": ["implicit"],
    "AllowAccessTokensViaBrowser": true,
    "RedirectUris": ["http://localhost:3000/auth/oidc", "http://localhost:4004/auth/oidc"],
    "AllowedScopes": ["openid", "profile", "email"],
    "IdentityTokenLifetime": 3600,
    "AccessTokenLifetime": 3600
  },
  {
    "ClientId": "client-credentials-mock-client",
    "ClientSecrets": ["client-credentials-mock-client-secret"],
    "Description": "Client for client credentials flow",
    "AllowedGrantTypes": ["client_credentials"],
    "AllowedScopes": ["some-app-scope-1"],
    "ClientClaimsPrefix": "",
    "Claims": [
      {
        "Type": "string_claim",
        "Value": "string_claim_value",
        "ValueType": "string"
      },
      {
        "Type": "json_claim",
        "Value": "[\"value1\", \"value2\"]",
        "ValueType": "json"
      }
    ]
  }
]
```

This is the sample of using the server in `Dockerfile` configuration:

```
# Use the base image
FROM ghcr.io/soluto/oidc-server-mock:0.8.6

# Set environment variables
# additional configuration can be found in the readme
# https://github.com/Soluto/oidc-server-mock/blob/master/README.md?plain=1#L145
ENV ASPNETCORE_ENVIRONMENT=Development
ENV SERVER_OPTIONS_INLINE="{ \
  \"AccessTokenJwtType\": \"JWT\", \
  \"Discovery\": { \
    \"ShowKeySet\": true \
  }, \
  \"Authentication\": { \
    \"CookieSameSiteMode\": \"Lax\", \
    \"CheckSessionCookieSameSiteMode\": \"Lax\" \
  } \
}"
ENV USERS_CONFIGURATION_INLINE="[ \
  { \
    \"SubjectId\": \"1\", \
    \"Username\": \"User1\", \
    \"Password\": \"pwd\", \
    \"Claims\": [ \
      { \
        \"Type\": \"name\", \
        \"Value\": \"Sam Tailor\", \
        \"ValueType\": \"string\" \
      }, \
      { \
        \"Type\": \"email\", \
        \"Value\": \"sam.tailor@gmail.com\", \
        \"ValueType\": \"string\" \
      }, \
      { \
        \"Type\": \"some-api-resource-claim\", \
        \"Value\": \"Sam's Api Resource Custom Claim\", \
        \"ValueType\": \"string\" \
      }, \
      { \
        \"Type\": \"some-api-scope-claim\", \
        \"Value\": \"Sam's Api Scope Custom Claim\", \
        \"ValueType\": \"string\" \
      }, \
      { \
        \"Type\": \"some-identity-resource-claim\", \
        \"Value\": \"Sam's Identity Resource Custom Claim\", \
        \"ValueType\": \"string\" \
      } \
    ] \
  } \
]"
ENV CLIENTS_CONFIGURATION_INLINE="[ \
  { \
    \"ClientId\": \"some-client-di\", \
    \"ClientSecrets\": [\"some-client-Secret\"], \
    \"Description\": \"Client for authorization code flow\", \
    \"AllowedGrantTypes\": [\"authorization_code\"], \
    \"RequirePkce\": false, \
    \"AllowAccessTokensViaBrowser\": true, \
    \"RedirectUris\": [\"http://some-callback-url"], \
    \"AllowedScopes\": [\"openid\", \"profile\", \"email\"], \
    \"IdentityTokenLifetime\": 3600, \
    \"AccessTokenLifetime\": 3600, \
    \"RequireClientSecret\": false \
  } \
]"
ENV ASPNET_SERVICES_OPTIONS_INLINE="{ \
  \"ForwardedHeadersOptions\": { \
    \"ForwardedHeaders\": \"All\" \
  } \
}"

# Expose the port
EXPOSE 80

# Command to run the application
CMD ["dotnet", "Soluto.OidcServerMock.dll"]
```

Clients configuration should be provided. Test user configuration is optional (used for implicit flow only).

There are two ways to provide configuration for supported scopes, clients and users. You can either provide it inline as environment variable:

- `SERVER_OPTIONS_INLINE`
- `LOGIN_OPTIONS_INLINE`
- `LOGOUT_OPTIONS_INLINE`
- `API_SCOPES_INLINE`
- `USERS_CONFIGURATION_INLINE`
- `CLIENTS_CONFIGURATION_INLINE`
- `API_RESOURCES_INLINE`
- `IDENTITY_RESOURCES_INLINE`

  or mount volume and provide the path to configuration json as environment variable:

- `SERVER_OPTIONS_PATH`
- `LOGIN_OPTIONS_PATH`
- `LOGOUT_OPTIONS_PATH`
- `API_SCOPES_PATH`
- `USERS_CONFIGURATION_PATH`
- `CLIENTS_CONFIGURATION_PATH`
- `API_RESOURCES_PATH`
- `IDENTITY_RESOURCES_PATH`

The configuration format can be Yaml or JSON both for inline or file path options.

In order to be able to override standard identity resources set `OVERRIDE_STANDARD_IDENTITY_RESOURCES` env var to `True`.

## Base path

The server can be configured to run with base path. So all the server endpoints will be also available with some prefix segment.
For example `http://localhost:8080/my-base-path/.well-known/openid-configuration` and `http://localhost:8080/my-base-path/connect/token`.
Just set `BasePath` property in `ASPNET_SERVICES_OPTIONS_INLINE/PATH` env var.

## Custom endpoints

### User management

Users can be added (in future also removed and altered) via `user management` endpoint.

- Create new user: `POST` request to `/api/v1/user` path.
  The request body should be the `User` object. Just as in `USERS_CONFIGURATION`.
  The response is subjectId as sent in request.

- Get user: `GET` request to `/api/v1/user/{subjectId}` path.
  The response is `User` object

- Update user `PUT` request to `/api/v1/user` path. (**Not implemented yet**)
  The request body should be the `User` object. Just as in `USERS_CONFIGURATION`.
  The response is subjectId as sent in request.

  > If user doesn't exits it will be created.

- Delete user: `DELETE` request to `/api/v1/user/{subjectId}` path. (**Not implemented yet**)
  The response is `User` object

## HTTPS

To use `https` protocol with the server just add the following environment variables to the `docker run`/`docker-compose up` command, expose ports and mount volume containing the pfx file:

```yaml
environment:
  ASPNETCORE_URLS: https://+:443;http://+:80
  ASPNETCORE_Kestrel__Certificates__Default__Password: <password for pfx file>
  ASPNETCORE_Kestrel__Certificates__Default__Path: /path/to/pfx/file
volumes:
  - ./local/path/to/pfx/file:/path/to/pfx/file:ro
ports:
  - 8080:80
  - 8443:443
```

---

## Cookie SameSite mode

Since Aug 2020 Chrome has a new [secure-by-default model](https://blog.chromium.org/2019/10/developers-get-ready-for-new.html) for cookies, enabled by a new cookie classification system. Other browsers will join in near future.

There are two ways to use `oidc-server-mock` with this change.

1. Run the container with HTTPS enabled (see above).
2. Change cookies `SameSite` mode from default `None` to `Lax`. To do so just add the following to `SERVER_OPTIONS_INLINE` (or the file at `SERVER_OPTIONS_PATH`):

```javascript
{
  // Existing configuration
  // ...
  "Authentication": {
    "CookieSameSiteMode": "Lax",
    "CheckSessionCookieSameSiteMode": "Lax"
  }
}
```

## Contributing

### Requirements

1. [Docker](https://www.docker.com/) (version 18.09 or higher)

2. [NodeJS](https://nodejs.org/en/) (version 10.0.0 or higher)

### Getting started

1. Clone the repo:

   ```sh
   git clone git@github.com:Soluto/oidc-server-mock.git
   ```

2. Install `npm` packages (run from `/e2e` folder):

   ```sh
   npm install
   ```

   > Note: During the build of Docker image UI source code is fetched from [github](https://github.com/IdentityServer/IdentityServer4.Quickstart.UI/tree/main). If you experience some issues on project compile step of Docker build or on runtime try to change the branch or commit in the [script](./src/getmain.sh).

3. Run tests:

   ```sh
   npm run test
   ```

## Used by

1. [Tweek](https://github.com/Soluto/tweek) blackbox [tests](https://github.com/Soluto/tweek-blackbox).

2. [Stitch](https://github.com/Soluto/Stitch) e2e tests.


================================================
FILE: Tiltfile
================================================
dockerComps = ['./e2e/docker-compose.yml']

imageTag = os.getenv('IMAGE_TAG', '')
if imageTag == '':
    docker_build('oidc-server-mock', './src')
else:
    dockerComps.append( './e2e/docker-compose.override.yml')

docker_compose(dockerComps)

dc_resource('oidc-server-mock')
local_resource('tests', cmd='npm run test --workspace=e2e', resource_deps=['oidc-server-mock'])


================================================
FILE: e2e/config/api-resources.yaml
================================================
- Name: some-app
  Scopes:
    - some-app-scope-1
    - some-app-scope-2
  ApiSecrets:
    - some-app-secret-1
  UserClaims:
    - some-app-user-custom-claim


================================================
FILE: e2e/config/clients.json
================================================
[
  {
    "ClientId": "implicit-flow-client-id",
    "Description": "Client for implicit flow",
    "AllowedGrantTypes": ["implicit"],
    "AllowAccessTokensViaBrowser": true,
    "RedirectUris": ["https://*.google.com"],
    "AllowedScopes": ["openid", "profile", "email", "some-custom-identity", "some-app-scope-1"],
    "IdentityTokenLifetime": 3600,
    "AccessTokenLifetime": 3600
  },
  {
    "ClientId": "client-credentials-flow-client-id",
    "ClientSecrets": ["client-credentials-flow-client-secret"],
    "Description": "Client for client credentials flow",
    "AllowedGrantTypes": ["client_credentials"],
    "AllowedScopes": ["some-app-scope-1"],
    "ClientClaimsPrefix": "",
    "Claims": [
      {
        "Type": "string_claim",
        "Value": "string_claim_value",
        "ValueType": "string"
      },
      {
        "Type": "json_claim",
        "Value": "[\"value1\", \"value2\"]",
        "ValueType": "json"
      }
    ]
  },
  {
    "ClientId": "password-flow-client-id",
    "ClientSecrets": ["password-flow-client-secret"],
    "Description": "Client for password flow",
    "AllowedGrantTypes": ["password"],
    "AllowedScopes": ["openid", "profile", "email", "some-custom-identity", "some-app-scope-1"],
    "ClientClaimsPrefix": "",
    "Claims": [
      {
        "Type": "string_claim",
        "Value": "string_claim_value",
        "ValueType": "string"
      },
      {
        "Type": "json_claim",
        "Value": "[\"value1\", \"value2\"]",
        "ValueType": "json"
      }
    ],
    "RequireClientSecret": false
  },
  {
    "ClientId": "authorization-code-client-id",
    "ClientSecrets": ["authorization-code-client-secret"],
    "Description": "Client for authorization code flow",
    "AllowedGrantTypes": ["authorization_code"],
    "AllowAccessTokensViaBrowser": true,
    "RedirectUris": ["https://*.google.com"],
    "RequirePkce": false,
    "AllowedScopes": ["openid", "profile", "email", "some-custom-identity", "some-app-scope-1"],
    "IdentityTokenLifetime": 3600,
    "AccessTokenLifetime": 3600,
    "RequireClientSecret": false
  },
  {
    "ClientId": "authorization-code-with-pkce-client-id",
    "ClientSecrets": ["authorization-code-with-pkce-client-secret"],
    "Description": "Client for authorization code flow",
    "AllowedGrantTypes": ["authorization_code"],
    "AllowAccessTokensViaBrowser": true,
    "RedirectUris": ["https://*.google.com"],
    "AllowedScopes": ["openid", "profile", "email", "some-custom-identity", "some-app-scope-1"],
    "IdentityTokenLifetime": 3600,
    "AccessTokenLifetime": 3600,
    "RequireClientSecret": false
  }
]


================================================
FILE: e2e/config/identity-resources.json
================================================
[
  {
    "Name": "some-custom-identity",
    "ClaimTypes": ["some-custom-identity-user-claim"]
  }
]


================================================
FILE: e2e/config/server-options.json
================================================
{
  "AccessTokenJwtType": "JWT",
  "Discovery": {
    "ShowKeySet": true
  }
}

================================================
FILE: e2e/config/users.yaml
================================================
[
  { 'SubjectId': 'simple_user', 'Username': 'simple_user', 'Password': 'pwd' },
  {
    'SubjectId': 'user_with_standard_claims',
    'Username': 'user_with_standard_claims',
    'Password': 'pwd',
    'Claims':
      [
        { 'Type': 'name', 'Value': 'John Smith', 'ValueType': 'string' },
        { 'Type': 'email', 'Value': 'john.smith@gmail.com', 'ValueType': 'emailaddress' },
        { 'Type': 'email_verified', 'Value': 'true', 'ValueType': 'boolean' },
      ],
  },
  {
    'SubjectId': 'user_with_custom_identity_claims',
    'Username': 'user_with_custom_identity_claims',
    'Password': 'pwd',
    'Claims':
      [
        { 'Type': 'name', 'Value': 'Jack Sparrow', 'ValueType': 'string' },
        { 'Type': 'email', 'Value': 'jack.sparrow@gmail.com', 'ValueType': 'emailaddress' },
        { 'Type': 'some-custom-identity-user-claim', 'Value': "Jack's Custom User Claim", 'ValueType': 'string' },
      ],
  },
  {
    'SubjectId': 'user_with_custom_api_resource_claims',
    'Username': 'user_with_custom_api_resource_claims',
    'Password': 'pwd',
    'Claims':
      [
        { 'Type': 'name', 'Value': 'Sam Tailor', 'ValueType': 'string' },
        { 'Type': 'email', 'Value': 'sam.tailor@gmail.com', 'ValueType': 'emailaddress' },
        { 'Type': 'some-app-user-custom-claim', 'Value': "Sam's Custom User Claim", 'ValueType': 'string' },
        {
          'Type': 'some-app-scope-1-custom-user-claim',
          'Value': "Sam's Scope Custom User Claim",
          'ValueType': 'string',
        },
      ],
  },
  {
    'SubjectId': 'user_with_all_claim_types',
    'Username': 'user_with_all_claim_types',
    'Password': 'pwd',
    'Claims':
      [
        { 'Type': 'name', 'Value': 'Oliver Hunter', 'ValueType': 'string' },
        { 'Type': 'email', 'Value': 'oliver.hunter@gmail.com', 'ValueType': 'emailaddress' },
        { 'Type': 'some-app-user-custom-claim', 'Value': "Oliver's Custom User Claim", 'ValueType': 'string' },
        {
          'Type': 'some-app-scope-1-custom-user-claim',
          'Value': "Oliver's Scope Custom User Claim",
          'ValueType': 'string',
        },
        { 'Type': 'some-custom-identity-user-claim', 'Value': "Oliver's Custom User Claim", 'ValueType': 'string' },
      ],
  },
]


================================================
FILE: e2e/docker-compose.override.yml
================================================
services:
  oidc-server-mock:
    image: ghcr.io/soluto/oidc-server-mock:${IMAGE_TAG}


================================================
FILE: e2e/docker-compose.yml
================================================
services:
  oidc-server-mock:
    container_name: oidc-server-mock
    image: oidc-server-mock
    environment:
      ASPNETCORE_ENVIRONMENT: Development
      ASPNETCORE_URLS: https://+:443;http://+:80
      ASPNETCORE_Kestrel__Certificates__Default__Password: oidc-server-mock-pwd
      ASPNETCORE_Kestrel__Certificates__Default__Path: /https/aspnetapp.pfx
      SERVER_OPTIONS_PATH: /config/server-options.json
      LOGIN_OPTIONS_INLINE: |
        {
          "AllowRememberLogin": false
        }
      LOGOUT_OPTIONS_INLINE: |
        {
          "AutomaticRedirectAfterSignOut": true
        }
      API_RESOURCES_PATH: /config/api-resources.yaml
      API_SCOPES_INLINE: |
        - Name: some-app-scope-1
          UserClaims:
            - some-app-scope-1-custom-user-claim
        - Name: some-app-scope-2
      USERS_CONFIGURATION_PATH: /config/users.yaml
      CLIENTS_CONFIGURATION_PATH: /config/clients.json
      IDENTITY_RESOURCES_PATH: /config/identity-resources.json
      ASPNET_SERVICES_OPTIONS_INLINE: |
        {
          "BasePath": "/some-base-path"
        }
    volumes:
      - ./config:/config:ro
      - ./https:/https:ro
    ports:
      - 8080:80
      - 8443:443


================================================
FILE: e2e/helpers/authorization-endpoint.ts
================================================
import { expect } from '@jest/globals';
import { Page } from 'playwright-chromium';

import { User } from '../types';
import { oidcAuthorizeUrl } from './endpoints';

const authorizationEndpoint = async (
  page: Page,
  parameters: URLSearchParams,
  user: User,
  redirect_uri: string,
): Promise<URL> => {
  const url = `${oidcAuthorizeUrl.href}?${parameters.toString()}`;
  const response = await page.goto(url);
  expect(response.ok()).toBe(true);

  await page.waitForSelector('[id=Input_Username]');
  await page.type('[id=Input_Username]', user.Username);
  await page.type('[id=Input_Password]', user.Password);
  await page.keyboard.press('Enter');
  await page.waitForURL(url => url.origin === redirect_uri);
  const redirectedUrl = new URL(page.url());
  return redirectedUrl;
};

export default authorizationEndpoint;


================================================
FILE: e2e/helpers/endpoints.ts
================================================
import { from, logger } from 'env-var';
import * as dotenv from 'dotenv';
import { URL } from 'node:url';
dotenv.config();
const env = from(process.env, undefined, logger);

export const oidcBaseUrl = env.get('OIDC_BASE_URL').required().asUrlObject();
export const basePath = 'some-base-path';

export const oidcTokenUrl = new URL('/connect/token', oidcBaseUrl);
export const oidcTokenUrlWithBasePath = new URL(`/${basePath}/connect/token`, oidcBaseUrl);
export const oidcAuthorizeUrl = new URL('connect/authorize', oidcBaseUrl);
export const oidcIntrospectionUrl = new URL('/connect/introspect', oidcBaseUrl);
export const oidcUserInfoUrl = new URL('/connect/userinfo', oidcBaseUrl);
export const oidcGrantsUrl = new URL('/grants', oidcBaseUrl);
export const oidcUserManagementUrl = new URL('/api/v1/user', oidcBaseUrl);
export const oidcDiscoveryEndpoint = new URL('/.well-known/openid-configuration', oidcBaseUrl);
export const oidcDiscoveryEndpointWithBasePath = new URL(`/${basePath}/.well-known/openid-configuration`, oidcBaseUrl);


================================================
FILE: e2e/helpers/grants.ts
================================================
import { expect } from '@jest/globals';
import { Page } from 'playwright-chromium';

import { User } from '../types';
import { oidcGrantsUrl } from './endpoints';

const grantsEndpoint = async (page: Page, user: User): Promise<void> => {
  const response = await page.goto(oidcGrantsUrl.href);
  expect(response.ok()).toBe(true);

  await page.waitForSelector('[id=Input_Username]');
  await page.type('[id=Input_Username]', user.Username);
  await page.type('[id=Input_Password]', user.Password);
  await page.keyboard.press('Enter');
  await page.waitForNavigation();
  expect(await page.content()).toMatchSnapshot();
};

export default grantsEndpoint;


================================================
FILE: e2e/helpers/index.ts
================================================
export { default as authorizationEndpoint } from './authorization-endpoint';
export { default as grants } from './grants';
export { default as introspectEndpoint } from './introspect-endpoint';
export { default as tokenEndpoint } from './token-endpoint';
export { default as userInfoEndpoint } from './user-info-endpoint';


================================================
FILE: e2e/helpers/introspect-endpoint.ts
================================================
import { expect } from '@jest/globals';
import { ApiResource } from 'e2e/types';
import * as fs from 'fs/promises';
import path from 'path';

import * as yaml from 'yaml';
import { oidcIntrospectionUrl } from './endpoints';

const introspectEndpoint = async (
  token: string,
  apiResourceId: string,
  snapshotPropertyMatchers: Record<string, unknown> = {},
): Promise<void> => {
  const apiResources = yaml.parse(
    await fs.readFile(path.join(process.cwd(), './config/api-resources.yaml'), { encoding: 'utf8' }),
  ) as ApiResource[];
  const apiResource = apiResources.find(aR => aR.Name === apiResourceId);
  expect(apiResource).toBeDefined();
  const auth = Buffer.from(`${apiResource.Name}:${apiResource.ApiSecrets?.[0]}`).toString('base64');
  const headers = {
    Authorization: `Basic ${auth}`,
    'Content-Type': 'application/x-www-form-urlencoded',
  };
  const requestBody = new URLSearchParams({
    token,
  });

  const response = await fetch(oidcIntrospectionUrl, {
    method: 'POST',
    body: requestBody,
    headers,
  });

  expect(response.ok).toBe(true);
  const result = (await response.json()) as unknown;
  expect(result).toMatchSnapshot(snapshotPropertyMatchers);
};

export default introspectEndpoint;


================================================
FILE: e2e/helpers/token-endpoint.ts
================================================
import { expect } from '@jest/globals';
import { decode as decodeJWT } from 'jws';
import { oidcTokenUrl } from './endpoints';

const tokenEndpoint = async (
  parameters: URLSearchParams,
  snapshotPropertyMatchers: Record<string, unknown> = {},
): Promise<string> => {
  const response = await fetch(oidcTokenUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: parameters.toString(),
  });
  expect(response.ok).toBe(true);
  const result = (await response.json()) as { access_token: string };
  expect(result.access_token).toBeDefined();
  const token = result.access_token;
  const decodedToken = decodeJWT(token);

  expect(decodedToken).toMatchSnapshot(snapshotPropertyMatchers);
  return token;
};

export default tokenEndpoint;


================================================
FILE: e2e/helpers/user-info-endpoint.ts
================================================
import { expect } from '@jest/globals';
import { oidcUserInfoUrl } from './endpoints';

const userInfoEndpoint = async (
  token: string,
  snapshotPropertyMatchers: Record<string, unknown> = {},
): Promise<void> => {
  const response = await fetch(oidcUserInfoUrl, {
    headers: { authorization: `Bearer ${token}` },
  });
  expect(response.ok).toBe(true);
  const result = (await response.json()) as unknown;
  expect(result).toMatchSnapshot(snapshotPropertyMatchers);
};

export default userInfoEndpoint;


================================================
FILE: e2e/jest.config.ts
================================================
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
  projects: [
    {
      displayName: 'Backend Tests',
      preset: 'ts-jest',
      rootDir: '.',
      snapshotSerializers: ['<rootDir>/utils/jwt-serializer.js', '<rootDir>/utils/jwt-payload-serializer.js'],
      testMatch: ['<rootDir>/tests/**/*.spec.ts'],
      testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/', '<rootDir>/tests/*.e2e-spec.ts'],
      testEnvironment: 'node',
    },
    {
      displayName: 'Frontend Tests',
      preset: 'jest-playwright-preset',
      rootDir: '.',
      snapshotSerializers: ['<rootDir>/utils/jwt-serializer.js', '<rootDir>/utils/jwt-payload-serializer.js'],
      testMatch: ['<rootDir>/tests/**/*.e2e-spec.ts'],
      testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/dist/'],
      transform: {
        '^.+\\.ts$': 'ts-jest',
      },
      testEnvironment: 'node',
    },
  ],
  testTimeout: 60000,
};

export default config;


================================================
FILE: e2e/package.json
================================================
{
  "name": "e2e",
  "version": "1.0.0",
  "scripts": {
    "test": "NODE_TLS_REJECT_UNAUTHORIZED=0 jest --runInBand --ci --config jest.config.ts"
  },
  "license": "MIT",
  "engines": {
    "node": ">=20.0.0"
  },
  "dependencies": {
    "chance": "^1.1.12",
    "dotenv": "^16.5.0",
    "env-var": "^7.5.0",
    "jws": "^4.0.0",
    "playwright-chromium": "^1.52.0",
    "wait-on": "^8.0.3",
    "yaml": "^2.7.1"
  },
  "devDependencies": {
    "@jest/types": "^29.6.3",
    "@types/chance": "^1.1.6",
    "@types/jest": "^29.5.14",
    "@types/jws": "^3.2.10",
    "@types/node": "^22.15.3",
    "@types/wait-on": "^5.3.4",
    "jest": "^29.7.0",
    "jest-playwright-preset": "^4.0.0",
    "ts-jest": "^29.3.2",
    "ts-node": "^10.9.2",
    "typescript": "^5.8.3"
  }
}


================================================
FILE: e2e/tests/__snapshots__/base-path.spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Base path Discovery Endpoint 1`] = `
{
  "access-control-allow-origin": "https://google.com",
  "content-type": "application/json; charset=UTF-8",
  "date": Any<String>,
  "server": "Kestrel",
  "transfer-encoding": "chunked",
}
`;


================================================
FILE: e2e/tests/base-path.spec.ts
================================================
import { describe, test, beforeAll, expect } from '@jest/globals';

import clients from '../config/clients.json';
import type { Client } from '../types';
import { oidcDiscoveryEndpointWithBasePath, oidcTokenUrlWithBasePath } from 'e2e/helpers/endpoints';

describe('Base path', () => {
  let client: Client | undefined;

  beforeAll(() => {
    client = clients.find(c => c.ClientId === 'client-credentials-flow-client-id');
    expect(client).toBeDefined();
  });

  test('Discovery Endpoint', async () => {
    const response = await fetch(oidcDiscoveryEndpointWithBasePath, {
      headers: {
        origin: 'https://google.com',
      },
    });
    expect(response.ok).toBe(true);
    const result = (await response.json()) as unknown;
    expect(result).toHaveProperty('token_endpoint', oidcTokenUrlWithBasePath.href);
    expect(Object.fromEntries(response.headers.entries())).toMatchSnapshot({ date: expect.any(String) });
  });

  test('Token Endpoint', async () => {
    if (!client) throw new Error('Client not found');

    const parameters = new URLSearchParams({
      client_id: client.ClientId,
      client_secret: client.ClientSecrets?.[0] ?? '',
      grant_type: 'client_credentials',
      scope: client.AllowedScopes.join(' '),
    });

    const response = await fetch(oidcTokenUrlWithBasePath, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: parameters.toString(),
    });
    expect(response.ok).toBe(true);
    const result = (await response.json()) as { access_token: string };
    expect(result.access_token).toBeDefined();
  });
});


================================================
FILE: e2e/tests/custom-endpoints/__snapshots__/user-management.spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`User management Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": {
    "inverse": false
  },
  "idp": "local",
  "some-app-user-custom-claim": {
    "inverse": false
  },
  "some-app-scope-1-custom-user-claim": {
    "inverse": false
  },
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`User management Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": {
    "inverse": false
  },
  "idp": "local",
  "some-app-user-custom-claim": {
    "inverse": false
  },
  "some-app-scope-1-custom-user-claim": {
    "inverse": false
  }
}
`;

exports[`User management UserInfo Endpoint 1`] = `
{
  "email": Any<String>,
  "name": Any<String>,
  "some-custom-identity-user-claim": Any<String>,
  "sub": Any<String>,
}
`;


================================================
FILE: e2e/tests/custom-endpoints/user-management.spec.ts
================================================
import { describe, test, beforeAll, expect } from '@jest/globals';
import Chance from 'chance';

import clients from '../../config/clients.json';
import { introspectEndpoint, tokenEndpoint, userInfoEndpoint } from '../../helpers';
import { Client, User } from '../../types';
import { oidcUserManagementUrl } from 'e2e/helpers/endpoints';

describe('User management', () => {
  const chance = new Chance();
  const subjectId = chance.guid({ version: 4 });
  const firstName = chance.first();
  const lastName = chance.last();
  const username = `${firstName}_${lastName}`;
  const password = chance.string({ length: 8 });
  const email = chance.email();

  let client: Client | undefined;
  let token: string;

  beforeAll(() => {
    client = clients.find(c => c.ClientId === 'password-flow-client-id');
  });

  test('Get user from configuration', async () => {
    const configUserId = 'user_with_all_claim_types';
    const configUsername = 'user_with_all_claim_types';
    const response = await fetch(`${oidcUserManagementUrl.href}/${configUserId}`);
    expect(response.status).toBe(200);
    const receivedUser = (await response.json()) as User;
    expect(receivedUser).toHaveProperty('username', configUsername);
  });

  test('Create user', async () => {
    const user: User = {
      SubjectId: subjectId,
      Username: username,
      Password: password,
      Claims: [
        {
          Type: 'name',
          Value: `${firstName} ${lastName}`,
        },
        {
          Type: 'email',
          Value: email,
        },
        {
          Type: 'some-app-user-custom-claim',
          Value: `${firstName}'s Custom User Claim`,
        },
        {
          Type: 'some-app-scope-1-custom-user-claim',
          Value: `${firstName}'s Scope Custom User Claim`,
        },
        {
          Type: 'some-custom-identity-user-claim',
          Value: `${firstName}'s Custom User Claim`,
        },
      ],
    };
    const response = await fetch(oidcUserManagementUrl, {
      method: 'POST',
      body: JSON.stringify(user),
      headers: { 'Content-Type': 'application/json' },
    });
    expect(response.status).toBe(200);
    const result = (await response.json()) as unknown;
    expect(result).toEqual(subjectId);
  });

  test('Get user', async () => {
    const response = await fetch(`${oidcUserManagementUrl.href}/${subjectId}`);
    expect(response.status).toBe(200);
    const receivedUser = (await response.json()) as User;
    expect(receivedUser).toHaveProperty('username', username);
    expect(receivedUser).toHaveProperty('isActive', true);
  });

  test('Token Endpoint', async () => {
    const parameters = new URLSearchParams({
      client_id: client.ClientId,
      username: username,
      password: password,
      grant_type: 'password',
      scope: client.AllowedScopes.join(' '),
    });

    token = await tokenEndpoint(parameters, {
      payload: {
        sub: expect.any(String) as unknown,
        ['some-app-user-custom-claim']: expect.any(String) as unknown,
        ['some-app-scope-1-custom-user-claim']: expect.any(String) as unknown,
      },
    });
  });

  test('UserInfo Endpoint', async () => {
    await userInfoEndpoint(token, {
      sub: expect.any(String),
      name: expect.any(String),
      email: expect.any(String),
      ['some-custom-identity-user-claim']: expect.any(String) as unknown,
    });
  }, 10000);

  test('Introspection Endpoint', async () => {
    await introspectEndpoint(token, 'some-app', {
      sub: expect.any(String),
      ['some-app-user-custom-claim']: expect.any(String) as unknown,
      ['some-app-scope-1-custom-user-claim']: expect.any(String) as unknown,
    });
  });
});


================================================
FILE: e2e/tests/flows/__snapshots__/authorization-code-pkce.e2e-spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Authorization Code Flow (with PKCE) - simple_user - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "simple_user",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow (with PKCE) - simple_user - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "simple_user",
  "idp": "local"
}
`;

exports[`Authorization Code Flow (with PKCE) - simple_user - UserInfo Endpoint 1`] = `
{
  "sub": "simple_user",
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_all_claim_types - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_all_claim_types - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_all_claim_types - UserInfo Endpoint 1`] = `
{
  "email": "oliver.hunter@gmail.com",
  "name": "Oliver Hunter",
  "some-custom-identity-user-claim": "Oliver's Custom User Claim",
  "sub": "user_with_all_claim_types",
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_api_resource_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_api_resource_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_api_resource_claims - UserInfo Endpoint 1`] = `
{
  "email": "sam.tailor@gmail.com",
  "name": "Sam Tailor",
  "sub": "user_with_custom_api_resource_claims",
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_identity_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_identity_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_custom_identity_claims - UserInfo Endpoint 1`] = `
{
  "email": "jack.sparrow@gmail.com",
  "name": "Jack Sparrow",
  "some-custom-identity-user-claim": "Jack's Custom User Claim",
  "sub": "user_with_custom_identity_claims",
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_standard_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_standard_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-with-pkce-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local"
}
`;

exports[`Authorization Code Flow (with PKCE) - user_with_standard_claims - UserInfo Endpoint 1`] = `
{
  "email": "john.smith@gmail.com",
  "email_verified": "true",
  "name": "John Smith",
  "sub": "user_with_standard_claims",
}
`;


================================================
FILE: e2e/tests/flows/__snapshots__/authorization-code.e2e-spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Authorization Code Flow - simple_user - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-client-id",
  "sub": "simple_user",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow - simple_user - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-client-id",
  "sub": "simple_user",
  "idp": "local"
}
`;

exports[`Authorization Code Flow - simple_user - UserInfo Endpoint 1`] = `
{
  "sub": "simple_user",
}
`;

exports[`Authorization Code Flow - user_with_all_claim_types - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow - user_with_all_claim_types - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim"
}
`;

exports[`Authorization Code Flow - user_with_all_claim_types - UserInfo Endpoint 1`] = `
{
  "email": "oliver.hunter@gmail.com",
  "name": "Oliver Hunter",
  "some-custom-identity-user-claim": "Oliver's Custom User Claim",
  "sub": "user_with_all_claim_types",
}
`;

exports[`Authorization Code Flow - user_with_custom_api_resource_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow - user_with_custom_api_resource_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim"
}
`;

exports[`Authorization Code Flow - user_with_custom_api_resource_claims - UserInfo Endpoint 1`] = `
{
  "email": "sam.tailor@gmail.com",
  "name": "Sam Tailor",
  "sub": "user_with_custom_api_resource_claims",
}
`;

exports[`Authorization Code Flow - user_with_custom_identity_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow - user_with_custom_identity_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local"
}
`;

exports[`Authorization Code Flow - user_with_custom_identity_claims - UserInfo Endpoint 1`] = `
{
  "email": "jack.sparrow@gmail.com",
  "name": "Jack Sparrow",
  "some-custom-identity-user-claim": "Jack's Custom User Claim",
  "sub": "user_with_custom_identity_claims",
}
`;

exports[`Authorization Code Flow - user_with_standard_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "authorization-code-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Authorization Code Flow - user_with_standard_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "authorization-code-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local"
}
`;

exports[`Authorization Code Flow - user_with_standard_claims - UserInfo Endpoint 1`] = `
{
  "email": "john.smith@gmail.com",
  "email_verified": "true",
  "name": "John Smith",
  "sub": "user_with_standard_claims",
}
`;


================================================
FILE: e2e/tests/flows/__snapshots__/client-credentials-flow.spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Client Credentials Flow Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "client_id": "client-credentials-flow-client-id",
  "string_claim": "string_claim_value",
  "json_claim": [
    "value1",
    "value2"
  ],
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Client Credentials Flow Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "some-app-scope-1"
  ],
  "client_id": "client-credentials-flow-client-id",
  "string_claim": "string_claim_value",
  "json_claim": [
    "value1",
    "value2"
  ]
}
`;


================================================
FILE: e2e/tests/flows/__snapshots__/implicit-flow.e2e-spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Implicit Flow - simple_user - Authorization Endpoint (id_token only) 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "implicit-flow-client-id",
  "amr": [
    "pwd"
  ],
  "nonce": "xyz",
  "sub": "simple_user",
  "idp": "local"
}
`;

exports[`Implicit Flow - simple_user - Authorization Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "implicit-flow-client-id",
  "sub": "simple_user",
  "idp": "local"
}
`;

exports[`Implicit Flow - simple_user - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "implicit-flow-client-id",
  "sub": "simple_user",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Implicit Flow - simple_user - UserInfo Endpoint 1`] = `
{
  "sub": "simple_user",
}
`;

exports[`Implicit Flow - user_with_all_claim_types - Authorization Endpoint (id_token only) 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "implicit-flow-client-id",
  "amr": [
    "pwd"
  ],
  "nonce": "xyz",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "name": "Oliver Hunter",
  "email": "oliver.hunter@gmail.com",
  "some-custom-identity-user-claim": "Oliver's Custom User Claim"
}
`;

exports[`Implicit Flow - user_with_all_claim_types - Authorization Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim"
}
`;

exports[`Implicit Flow - user_with_all_claim_types - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Implicit Flow - user_with_all_claim_types - UserInfo Endpoint 1`] = `
{
  "email": "oliver.hunter@gmail.com",
  "name": "Oliver Hunter",
  "some-custom-identity-user-claim": "Oliver's Custom User Claim",
  "sub": "user_with_all_claim_types",
}
`;

exports[`Implicit Flow - user_with_custom_api_resource_claims - Authorization Endpoint (id_token only) 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "implicit-flow-client-id",
  "amr": [
    "pwd"
  ],
  "nonce": "xyz",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "name": "Sam Tailor",
  "email": "sam.tailor@gmail.com"
}
`;

exports[`Implicit Flow - user_with_custom_api_resource_claims - Authorization Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim"
}
`;

exports[`Implicit Flow - user_with_custom_api_resource_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Implicit Flow - user_with_custom_api_resource_claims - UserInfo Endpoint 1`] = `
{
  "email": "sam.tailor@gmail.com",
  "name": "Sam Tailor",
  "sub": "user_with_custom_api_resource_claims",
}
`;

exports[`Implicit Flow - user_with_custom_identity_claims - Authorization Endpoint (id_token only) 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "implicit-flow-client-id",
  "amr": [
    "pwd"
  ],
  "nonce": "xyz",
  "sub": "user_with_custom_identity_claims",
  "idp": "local",
  "name": "Jack Sparrow",
  "email": "jack.sparrow@gmail.com",
  "some-custom-identity-user-claim": "Jack's Custom User Claim"
}
`;

exports[`Implicit Flow - user_with_custom_identity_claims - Authorization Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local"
}
`;

exports[`Implicit Flow - user_with_custom_identity_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Implicit Flow - user_with_custom_identity_claims - UserInfo Endpoint 1`] = `
{
  "email": "jack.sparrow@gmail.com",
  "name": "Jack Sparrow",
  "some-custom-identity-user-claim": "Jack's Custom User Claim",
  "sub": "user_with_custom_identity_claims",
}
`;

exports[`Implicit Flow - user_with_standard_claims - Authorization Endpoint (id_token only) 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "implicit-flow-client-id",
  "amr": [
    "pwd"
  ],
  "nonce": "xyz",
  "sub": "user_with_standard_claims",
  "idp": "local",
  "name": "John Smith",
  "email": "john.smith@gmail.com",
  "email_verified": "true"
}
`;

exports[`Implicit Flow - user_with_standard_claims - Authorization Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "openid",
    "profile",
    "email",
    "some-custom-identity",
    "some-app-scope-1"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local"
}
`;

exports[`Implicit Flow - user_with_standard_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "implicit-flow-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Implicit Flow - user_with_standard_claims - UserInfo Endpoint 1`] = `
{
  "email": "john.smith@gmail.com",
  "email_verified": "true",
  "name": "John Smith",
  "sub": "user_with_standard_claims",
}
`;


================================================
FILE: e2e/tests/flows/__snapshots__/password-flow.spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Password Flow - simple_user - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": "simple_user",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Password Flow - simple_user - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": "simple_user",
  "idp": "local"
}
`;

exports[`Password Flow - simple_user - UserInfo Endpoint 1`] = `
{
  "sub": "simple_user",
}
`;

exports[`Password Flow - user_with_all_claim_types - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Password Flow - user_with_all_claim_types - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": "user_with_all_claim_types",
  "idp": "local",
  "some-app-user-custom-claim": "Oliver's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Oliver's Scope Custom User Claim"
}
`;

exports[`Password Flow - user_with_all_claim_types - UserInfo Endpoint 1`] = `
{
  "email": "oliver.hunter@gmail.com",
  "name": "Oliver Hunter",
  "some-custom-identity-user-claim": "Oliver's Custom User Claim",
  "sub": "user_with_all_claim_types",
}
`;

exports[`Password Flow - user_with_custom_api_resource_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Password Flow - user_with_custom_api_resource_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": "user_with_custom_api_resource_claims",
  "idp": "local",
  "some-app-user-custom-claim": "Sam's Custom User Claim",
  "some-app-scope-1-custom-user-claim": "Sam's Scope Custom User Claim"
}
`;

exports[`Password Flow - user_with_custom_api_resource_claims - UserInfo Endpoint 1`] = `
{
  "email": "sam.tailor@gmail.com",
  "name": "Sam Tailor",
  "sub": "user_with_custom_api_resource_claims",
}
`;

exports[`Password Flow - user_with_custom_identity_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Password Flow - user_with_custom_identity_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": "user_with_custom_identity_claims",
  "idp": "local"
}
`;

exports[`Password Flow - user_with_custom_identity_claims - UserInfo Endpoint 1`] = `
{
  "email": "jack.sparrow@gmail.com",
  "name": "Jack Sparrow",
  "some-custom-identity-user-claim": "Jack's Custom User Claim",
  "sub": "user_with_custom_identity_claims",
}
`;

exports[`Password Flow - user_with_standard_claims - Introspection Endpoint 1`] = `
{
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "amr": "pwd",
  "client_id": "password-flow-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local",
  "active": true,
  "scope": "some-app-scope-1"
}
`;

exports[`Password Flow - user_with_standard_claims - Token Endpoint 1`] = `
{
  "alg": "RS256",
  "typ": "JWT",
  "iss": "https://localhost:8443",
  "aud": "some-app",
  "scope": [
    "email",
    "openid",
    "profile",
    "some-app-scope-1",
    "some-custom-identity"
  ],
  "amr": [
    "pwd"
  ],
  "client_id": "password-flow-client-id",
  "sub": "user_with_standard_claims",
  "idp": "local"
}
`;

exports[`Password Flow - user_with_standard_claims - UserInfo Endpoint 1`] = `
{
  "email": "john.smith@gmail.com",
  "email_verified": "true",
  "name": "John Smith",
  "sub": "user_with_standard_claims",
}
`;


================================================
FILE: e2e/tests/flows/authorization-code-pkce.e2e-spec.ts
================================================
import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';
import * as crypto from 'crypto';
import * as fs from 'fs';
import path from 'path';

import { Browser, BrowserContext, chromium, Page } from 'playwright-chromium';
import * as yaml from 'yaml';

import clients from '../../config/clients.json';
import { authorizationEndpoint, introspectEndpoint, tokenEndpoint, userInfoEndpoint } from '../../helpers';
import type { Client, User } from '../../types';

const users = yaml.parse(
  fs.readFileSync(path.join(process.cwd(), './config/users.yaml'), { encoding: 'utf8' }),
) as User[];

const testCases: User[] = users
  .map(u => ({
    ...u,
    toString: function () {
      return (this as User).SubjectId;
    },
  }))
  .sort((u1, u2) => (u1.SubjectId < u2.SubjectId ? -1 : 1));

const base64URLEncode = (buffer: Buffer) =>
  buffer.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');

const sha256 = (buffer: crypto.BinaryLike) => crypto.createHash('sha256').update(buffer).digest();

describe('Authorization Code Flow (with PKCE)', () => {
  let codeVerifier: string;
  let code: string;
  let token: string;

  let browser: Browser;
  let context: BrowserContext;
  let page: Page;
  let client: Client | undefined;

  beforeAll(async () => {
    browser = await chromium.launch();
    client = clients.find(c => c.ClientId === 'authorization-code-with-pkce-client-id');
    expect(client).toBeDefined();
  });

  beforeEach(async () => {
    context = await browser.newContext({ ignoreHTTPSErrors: true });
    page = await context.newPage();
  });

  afterEach(async () => {
    await page.close();
    await context.close();
  });

  afterAll(async () => {
    await browser.close();
  });

  describe.each(testCases)('- %s -', (user: User) => {
    test('Authorization Endpoint', async () => {
      codeVerifier = base64URLEncode(crypto.randomBytes(32));

      const codeChallenge = base64URLEncode(sha256(codeVerifier));

      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        scope: client.AllowedScopes.join(' '),
        response_type: 'code',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        code_challenge: codeChallenge,
        code_challenge_method: 'S256',
        state: 'abc',
        nonce: 'xyz',
      });
      const redirectedUrl = await authorizationEndpoint(page, parameters, user, parameters.get('redirect_uri'));
      expect(redirectedUrl.searchParams.has('code')).toBeTruthy();
      code = redirectedUrl.searchParams.get('code');
    });

    test('Token Endpoint', async () => {
      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        code,
        grant_type: 'authorization_code',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        code_verifier: codeVerifier,
        scope: client.AllowedScopes.join(' '),
      });

      token = await tokenEndpoint(parameters);
    });

    test('UserInfo Endpoint', async () => {
      await userInfoEndpoint(token);
    });

    test('Introspection Endpoint', async () => {
      await introspectEndpoint(token, 'some-app');
    });
  });
});


================================================
FILE: e2e/tests/flows/authorization-code.e2e-spec.ts
================================================
import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';
import * as fs from 'fs';
import path from 'path';

import { Browser, BrowserContext, chromium, Page } from 'playwright-chromium';
import * as yaml from 'yaml';

import clients from '../../config/clients.json';
import { authorizationEndpoint, introspectEndpoint, tokenEndpoint, userInfoEndpoint } from '../../helpers';
import type { Client, User } from '../../types';

const users = yaml.parse(
  fs.readFileSync(path.join(process.cwd(), './config/users.yaml'), { encoding: 'utf8' }),
) as User[];

const testCases: User[] = users
  .map(u => ({
    ...u,
    toString: function () {
      return (this as User).SubjectId;
    },
  }))
  .sort((u1, u2) => (u1.SubjectId < u2.SubjectId ? -1 : 1));

describe('Authorization Code Flow', () => {
  let code: string;
  let token: string;

  let browser: Browser;
  let context: BrowserContext;
  let page: Page;
  let client: Client | undefined;

  beforeAll(async () => {
    browser = await chromium.launch();
    client = clients.find(c => c.ClientId === 'authorization-code-client-id');
    expect(client).toBeDefined();
  });

  beforeEach(async () => {
    context = await browser.newContext({ ignoreHTTPSErrors: true });
    page = await context.newPage();
  });

  afterEach(async () => {
    await page.close();
    await context.close();
  });

  afterAll(async () => {
    await browser.close();
  });

  describe.each(testCases)('- %s -', (user: User) => {
    test('Authorization Endpoint', async () => {
      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        scope: client.AllowedScopes.join(' '),
        response_type: 'code',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        state: 'abc',
        nonce: 'xyz',
      });
      const redirectedUrl = await authorizationEndpoint(page, parameters, user, parameters.get('redirect_uri'));
      expect(redirectedUrl.searchParams.has('code')).toBeTruthy();
      code = redirectedUrl.searchParams.get('code');
    });

    test('Token Endpoint', async () => {
      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        code,
        grant_type: 'authorization_code',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        scope: client.AllowedScopes.join(' '),
      });

      token = await tokenEndpoint(parameters);
    });

    test('UserInfo Endpoint', async () => {
      await userInfoEndpoint(token);
    });

    test('Introspection Endpoint', async () => {
      await introspectEndpoint(token, 'some-app');
    });
  });
});


================================================
FILE: e2e/tests/flows/client-credentials-flow.spec.ts
================================================
import { describe, test, beforeAll, expect } from '@jest/globals';

import clients from '../../config/clients.json';
import { introspectEndpoint, tokenEndpoint } from '../../helpers';
import type { Client } from '../../types';

describe('Client Credentials Flow', () => {
  let client: Client | undefined;
  let token: string;

  beforeAll(() => {
    client = clients.find(c => c.ClientId === 'client-credentials-flow-client-id');
    expect(client).toBeDefined();
  });

  test('Token Endpoint', async () => {
    if (!client) throw new Error('Client not found');

    const parameters = new URLSearchParams({
      client_id: client.ClientId,
      client_secret: client.ClientSecrets?.[0] ?? '',
      grant_type: 'client_credentials',
      scope: client.AllowedScopes.join(' '),
    });

    token = await tokenEndpoint(parameters);
  });

  test('Introspection Endpoint', async () => {
    await introspectEndpoint(token, 'some-app');
  });
});


================================================
FILE: e2e/tests/flows/implicit-flow.e2e-spec.ts
================================================
import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';

import * as fs from 'fs';
import path from 'path';

import { decode as decodeJWT } from 'jws';
import { Browser, BrowserContext, chromium, Page } from 'playwright-chromium';
import * as yaml from 'yaml';

import clients from '../../config/clients.json';
import { authorizationEndpoint, introspectEndpoint, userInfoEndpoint } from '../../helpers';
import type { Client, User } from '../../types';

const users = yaml.parse(
  fs.readFileSync(path.join(process.cwd(), './config/users.yaml'), { encoding: 'utf8' }),
) as User[];

const testCases: User[] = users
  .map(u => ({
    ...u,
    toString: function () {
      return (this as User).SubjectId;
    },
  }))
  .sort((u1, u2) => (u1.SubjectId < u2.SubjectId ? -1 : 1));

describe('Implicit Flow', () => {
  let token: string;

  let browser: Browser;
  let context: BrowserContext;
  let page: Page;
  let client: Client | undefined;

  beforeAll(async () => {
    browser = await chromium.launch();
    client = clients.find(c => c.ClientId === 'implicit-flow-client-id');
    expect(client).toBeDefined();
  });

  beforeEach(async () => {
    context = await browser.newContext({ ignoreHTTPSErrors: true });
    page = await context.newPage();
  });

  afterEach(async () => {
    await page.close();
    await context.close();
  });

  afterAll(async () => {
    await browser.close();
  });

  describe.each(testCases)('- %s -', (user: User) => {
    test('Authorization Endpoint', async () => {
      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        scope: client.AllowedScopes.join(' '),
        response_type: 'id_token token',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        state: 'abc',
        nonce: 'xyz',
      });

      const redirectedUrl = await authorizationEndpoint(page, parameters, user, parameters.get('redirect_uri'));
      const hash = redirectedUrl.hash.slice(1);
      const query = new URLSearchParams(hash);

      const tokenParameter = query.get('access_token');
      expect(typeof tokenParameter).toBe('string');
      token = tokenParameter;
      const decodedAccessToken = decodeJWT(token);
      expect(decodedAccessToken).toMatchSnapshot();
    });

    test('UserInfo Endpoint', async () => {
      await userInfoEndpoint(token);
    });

    test('Introspection Endpoint', async () => {
      await introspectEndpoint(token, 'some-app');
    });

    test('Authorization Endpoint (id_token only)', async () => {
      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        scope: 'openid profile email some-custom-identity',
        response_type: 'id_token',
        redirect_uri: client.RedirectUris?.[0].replace('*', 'www'),
        state: 'abc',
        nonce: 'xyz',
      });
      const redirectedUrl = await authorizationEndpoint(page, parameters, user, parameters.get('redirect_uri'));
      const hash = redirectedUrl.hash.slice(1);
      const query = new URLSearchParams(hash);

      const tokenParameter = query.get('id_token');
      expect(typeof tokenParameter).toBe('string');
      token = tokenParameter;
      const decodedAccessToken = decodeJWT(token);
      expect(decodedAccessToken).toMatchSnapshot();
    });
  });
});


================================================
FILE: e2e/tests/flows/password-flow.spec.ts
================================================
import { describe, test, beforeAll, expect } from '@jest/globals';

import * as fs from 'fs';
import path from 'path';

import * as yaml from 'yaml';

import clients from '../../config/clients.json';
import { introspectEndpoint, tokenEndpoint, userInfoEndpoint } from '../../helpers';
import type { Client, User } from '../../types';

const users = yaml.parse(
  fs.readFileSync(path.join(process.cwd(), './config/users.yaml'), { encoding: 'utf8' }),
) as User[];

const testCases: User[] = users
  .map(u => ({
    ...u,
    toString: function () {
      return (this as User).SubjectId;
    },
  }))
  .sort((u1, u2) => (u1.SubjectId < u2.SubjectId ? -1 : 1));

describe('Password Flow', () => {
  let client: Client | undefined;
  let token: string;

  beforeAll(() => {
    client = clients.find(c => c.ClientId === 'password-flow-client-id');
    expect(client).toBeDefined();
  });

  describe.each(testCases)('- %s -', (user: User) => {
    test('Token Endpoint', async () => {
      if (!client) throw new Error('Client not found');

      const parameters = new URLSearchParams({
        client_id: client.ClientId,
        username: user.Username,
        password: user.Password,
        grant_type: 'password',
        scope: client.AllowedScopes.join(' '),
      });

      token = await tokenEndpoint(parameters);
    });

    test('UserInfo Endpoint', async () => {
      await userInfoEndpoint(token);
    });

    test('Introspection Endpoint', async () => {
      await introspectEndpoint(token, 'some-app');
    });
  });
});


================================================
FILE: e2e/tsconfig.json
================================================
{
  "extends": "../tsconfig.json",
  "exclude": ["node_modules"]
}


================================================
FILE: e2e/types/api-resource.ts
================================================
export default interface ApiResource {
  Name: string;
  Scopes?: string[];
  ApiSecrets?: string[];
}


================================================
FILE: e2e/types/claim.ts
================================================
export default interface Claim {
  Type: string;
  Value: string;
  ValueType?: string;
}


================================================
FILE: e2e/types/client.ts
================================================
import type Claim from './claim';

export default interface Client {
  ClientId: string;
  ClientSecrets?: string[];
  Description?: string;
  AllowedGrantTypes: string[];
  AllowedScopes: string[];
  RedirectUris?: string[];
  AllowAccessTokensViaBrowser?: boolean;
  AccessTokenLifetime?: number;
  IdentityTokenLifetime?: number;
  Claims?: Claim[];
  ClientClaimsPrefix?: string;
}


================================================
FILE: e2e/types/index.ts
================================================
export { default as ApiResource } from './api-resource';
export { default as Claim } from './claim';
export { default as Client } from './client';
export { default as User } from './user';


================================================
FILE: e2e/types/user.ts
================================================
import type Claim from './claim';

export default interface User {
  SubjectId: string;
  Username: string;
  Password: string;
  Claims?: Claim[];
}


================================================
FILE: e2e/utils/jwt-payload-serializer.js
================================================
module.exports = {
  test(argument) {
    return argument.iat && argument.exp && argument.nbf;
  },
  print(value) {
    const { exp, iat, jti, nbf, auth_time, sid, at_hash, ...payload } = value;
    return JSON.stringify(payload, undefined, 2);
  },
};


================================================
FILE: e2e/utils/jwt-serializer.js
================================================
module.exports = {
  test(argument) {
    return argument.header && argument.payload && argument.signature;
  },
  print(value) {
    const { alg, typ } = value.header;
    const { exp, iat, jti, nbf, auth_time, sid, at_hash, ...payload } = value.payload;
    return JSON.stringify({ alg, typ, ...payload }, undefined, 2);
  },
};


================================================
FILE: eslint.config.js
================================================
import js from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier';
import globals from 'globals';
import tseslint from 'typescript-eslint';

export default tseslint.config(
  { ignores: ['dist'] },
  {
    files: ['**/*.{ts,tsx}'],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser,
      parserOptions: {
        project: ['./tsconfig.json'],
        tsconfigRootDir: import.meta.dirname,
      },
    },
    extends: [js.configs.recommended, ...tseslint.configs.recommendedTypeChecked],
    settings: {
      node: {
        allowModules: ['jest-playwright-preset', 'wait-on'],
        tryExtensions: ['.ts', '.json', '.node'],
      },
    },
    ignores: ['**/node_modules/**', '**/dist/**', '**/coverage/**'],
  },
  eslintConfigPrettier,
);


================================================
FILE: package.json
================================================
{
  "name": "oidc-server-mock",
  "version": "1.0.0",
  "private": true,
  "license": "MIT",
  "type": "module",
  "engines": {
    "node": ">=20.0.0"
  },
  "scripts": {
    "tilt:up": "tilt up",
    "tilt:down": "tilt down",
    "tilt:ci": "tilt ci",
    "lint": "eslint .",
    "format": "prettier --write **/*.ts",
    "prepare": "husky"
  },
  "workspaces": [
    "e2e"
  ],
  "devDependencies": {
    "@commitlint/cli": "^19.8.0",
    "@commitlint/config-conventional": "^19.8.0",
    "@eslint/js": "^9.26.0",
    "@jest/globals": "^29.7.0",
    "eslint": "^9.26.0",
    "eslint-config-prettier": "^10.1.2",
    "eslint-plugin-prettier": "^5.2.6",
    "globals": "^16.0.0",
    "husky": "^9.1.7",
    "lint-staged": "^15.5.1",
    "prettier": "^3.5.3",
    "prettier-plugin-packagejson": "^2.5.10",
    "pretty-quick": "^4.1.1",
    "typescript": "^5.8.3",
    "typescript-eslint": "^8.31.1"
  },
  "packageManager": "pnpm@10.10.0"
}


================================================
FILE: pnpm-workspace.yaml
================================================
packages:
  - e2e


================================================
FILE: src/.dockerignore
================================================
bin/
obj/

Pages
wwwroot

keys/
tempkey.jwk

Dockerfile
.dockerignore


================================================
FILE: src/Config.cs
================================================
using Duende.IdentityServer.Configuration;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Test;
using OpenIdConnectServer.Helpers;
using OpenIdConnectServer.YamlConverters;
using YamlDotNet.Serialization;

namespace OpenIdConnectServer
{
    public static class Config
    {
        public static AspNetServicesOptions GetAspNetServicesOptions()
        {
            string aspNetServicesOptionsStr = Environment.GetEnvironmentVariable("ASPNET_SERVICES_OPTIONS_INLINE");
            if (string.IsNullOrWhiteSpace(aspNetServicesOptionsStr))
            {
                var aspNetServicesOptionsPath = Environment.GetEnvironmentVariable("ASPNET_SERVICES_OPTIONS_PATH");
                if (string.IsNullOrWhiteSpace(aspNetServicesOptionsPath))
                {
                    return new AspNetServicesOptions();
                }
                aspNetServicesOptionsStr = File.ReadAllText(aspNetServicesOptionsPath);
            }
            var aspNetServicesOptions = DeserializeObject<AspNetServicesOptions>(aspNetServicesOptionsStr);
            return aspNetServicesOptions;
        }

        public static IdentityServerOptions GetServerOptions()
        {
            string serverOptionsStr = Environment.GetEnvironmentVariable("SERVER_OPTIONS_INLINE");
            if (string.IsNullOrWhiteSpace(serverOptionsStr))
            {
                var serverOptionsFilePath = Environment.GetEnvironmentVariable("SERVER_OPTIONS_PATH");
                if (string.IsNullOrWhiteSpace(serverOptionsFilePath))
                {
                    return new IdentityServerOptions();
                }
                serverOptionsStr = File.ReadAllText(serverOptionsFilePath);
            }
            var serverOptions = DeserializeObject<IdentityServerOptions>(serverOptionsStr);
            return serverOptions;
        }

        public static void ConfigureOptions<T>(string optionsName)
        {
            string optionsStr = Environment.GetEnvironmentVariable($"{optionsName.ToUpper()}_OPTIONS_INLINE");
            if (string.IsNullOrWhiteSpace(optionsStr))
            {
                var optionsFilePath = Environment.GetEnvironmentVariable($"{optionsName.ToUpper()}_OPTIONS_PATH");
                if (string.IsNullOrWhiteSpace(optionsFilePath))
                {
                    return;
                }
                optionsStr = File.ReadAllText(optionsFilePath);
            }
            OptionsHelper.ConfigureOptions<T>(optionsStr);
        }

        public static IEnumerable<string> GetServerCorsAllowedOrigins()
        {
            string allowedOriginsStr = Environment.GetEnvironmentVariable("SERVER_CORS_ALLOWED_ORIGINS_INLINE");
            if (string.IsNullOrWhiteSpace(allowedOriginsStr))
            {
                var allowedOriginsFilePath = Environment.GetEnvironmentVariable("SERVER_CORS_ALLOWED_ORIGINS_PATH");
                if (string.IsNullOrWhiteSpace(allowedOriginsFilePath))
                {
                    return null;
                }
                allowedOriginsStr = File.ReadAllText(allowedOriginsFilePath);
            }
            var allowedOrigins = DeserializeObject<IEnumerable<string>>(allowedOriginsStr);
            return allowedOrigins;
        }

        public static IEnumerable<ApiScope> GetApiScopes()
        {
            string apiScopesStr = Environment.GetEnvironmentVariable("API_SCOPES_INLINE");
            if (string.IsNullOrWhiteSpace(apiScopesStr))
            {
                var apiScopesFilePath = Environment.GetEnvironmentVariable("API_SCOPES_PATH");
                if (string.IsNullOrWhiteSpace(apiScopesFilePath))
                {
                    return new List<ApiScope>();
                }
                apiScopesStr = File.ReadAllText(apiScopesFilePath);
            }
            var apiScopes = DeserializeObject<IEnumerable<ApiScope>>(apiScopesStr);
            return apiScopes;
        }

        public static IEnumerable<ApiResource> GetApiResources()
        {
            string apiResourcesStr = Environment.GetEnvironmentVariable("API_RESOURCES_INLINE");
            if (string.IsNullOrWhiteSpace(apiResourcesStr))
            {
                var apiResourcesFilePath = Environment.GetEnvironmentVariable("API_RESOURCES_PATH");
                if (string.IsNullOrWhiteSpace(apiResourcesFilePath))
                {
                    return new List<ApiResource>();
                }
                apiResourcesStr = File.ReadAllText(apiResourcesFilePath);
            }
            var apiResources = DeserializeObject<IEnumerable<ApiResource>>(apiResourcesStr);
            return apiResources;
        }

        public static IEnumerable<Client> GetClients()
        {
            string configStr = Environment.GetEnvironmentVariable("CLIENTS_CONFIGURATION_INLINE");
            if (string.IsNullOrWhiteSpace(configStr))
            {
                var configFilePath = Environment.GetEnvironmentVariable("CLIENTS_CONFIGURATION_PATH");
                if (string.IsNullOrWhiteSpace(configFilePath))
                {
                    throw new ArgumentNullException("You must set either CLIENTS_CONFIGURATION_INLINE or CLIENTS_CONFIGURATION_PATH env variable");
                }
                configStr = File.ReadAllText(configFilePath);
            }
            var configClients = DeserializeObject<IEnumerable<Client>>(configStr);
            return configClients;
        }

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            IEnumerable<IdentityResource> identityResources = new List<IdentityResource>();
            var overrideStandardResources = Environment.GetEnvironmentVariable("OVERRIDE_STANDARD_IDENTITY_RESOURCES");
            if (string.IsNullOrEmpty(overrideStandardResources) || Boolean.Parse(overrideStandardResources) != true)
            {
                var standardResources = new List<IdentityResource>
                {
                    new IdentityResources.OpenId(),
                    new IdentityResources.Profile(),
                    new IdentityResources.Email()
                };
                identityResources = identityResources.Union(standardResources);
            }
            return identityResources.Union(GetCustomIdentityResources());
        }

        public static List<TestUser> GetUsers()
        {
            string configStr = Environment.GetEnvironmentVariable("USERS_CONFIGURATION_INLINE");
            if (string.IsNullOrWhiteSpace(configStr))
            {
                var configFilePath = Environment.GetEnvironmentVariable("USERS_CONFIGURATION_PATH");
                if (string.IsNullOrWhiteSpace(configFilePath))
                {
                    return new List<TestUser>();
                }
                configStr = File.ReadAllText(configFilePath);
            }
            var configUsers = DeserializeObject<List<TestUser>>(configStr);
            return configUsers;
        }

        private static IEnumerable<IdentityResource> GetCustomIdentityResources()
        {
            string identityResourcesStr = Environment.GetEnvironmentVariable("IDENTITY_RESOURCES_INLINE");
            if (string.IsNullOrWhiteSpace(identityResourcesStr))
            {
                var identityResourcesFilePath = Environment.GetEnvironmentVariable("IDENTITY_RESOURCES_PATH");
                if (string.IsNullOrWhiteSpace(identityResourcesFilePath))
                {
                    return new List<IdentityResource>();
                }
                identityResourcesStr = File.ReadAllText(identityResourcesFilePath);
            }

            var identityResourceConfig = DeserializeObject<IdentityResourceConfig[]>(identityResourcesStr);
            return identityResourceConfig.Select(c => new IdentityResource(c.Name, c.ClaimTypes));
        }

        private static T DeserializeObject<T>(string value)
        {
            var deserializer = new DeserializerBuilder()
                .WithTypeConverter(new ClaimYamlConverter())
                .WithTypeConverter(new SecretYamlConverter())
                .Build();
            return deserializer.Deserialize<T>(value);
        }

        private class IdentityResourceConfig
        {
            public string Name { get; set; }
            public IEnumerable<string> ClaimTypes { get; set; }
        }
    }
}


================================================
FILE: src/Controllers/HealthController.cs
================================================
using Microsoft.AspNetCore.Mvc;

namespace OpenIdConnectServer.Controllers
{
    public class HealthController : Controller
    {
        [HttpGet("/health")]
        public IActionResult Get()
        {
            return Ok();
        }
    }
}

================================================
FILE: src/Controllers/UserController.cs
================================================
using System.Collections.Generic;
using System.Reflection;
using System.Security.Claims;
using Duende.IdentityServer.Test;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace OpenIdConnectServer.Controllers
{
  [Route("api/v1/user")]
    public class UserController: Controller
    {
        private readonly TestUserStore _usersStore;
        private readonly ILogger Logger;

        public UserController(TestUserStore userStore, ILogger<UserController> logger)
        {
            _usersStore = userStore;
            Logger = logger;
        }

        [HttpGet("{subjectId}")]
        public IActionResult GetUser([FromRoute]string subjectId)
        {
            var user = _usersStore.FindBySubjectId(subjectId);
            Logger.LogDebug("User found: {subjectId}", subjectId);
            return Json(user);
        }

        [HttpPost]
        public IActionResult AddUser([FromBody]TestUser user)
        {
            var claims = new List<Claim>(user.Claims);
            claims.Add(new Claim(ClaimTypes.Name, user.Username));
            var newUser =_usersStore.AutoProvisionUser("Alex", user.SubjectId, new List<Claim>(user.Claims));
            newUser.SubjectId = user.SubjectId;
            newUser.Username = user.Username;
            newUser.Password = user.Password;
            newUser.ProviderName = string.Empty;
            newUser.ProviderSubjectId = string.Empty;

            Logger.LogDebug("New user added: {user}", user.SubjectId);

            return Json(user.SubjectId);
        }
    }
}


================================================
FILE: src/Dockerfile
================================================
# Stage 1: Build

FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS source
ARG TARGETARCH

ARG target="Release"

RUN apk add --no-cache unzip curl bash

WORKDIR /src

COPY ./getui.sh ./getui.sh
RUN ./getui.sh

COPY ./OpenIdConnectServerMock.csproj ./OpenIdConnectServerMock.csproj
RUN dotnet restore -a $TARGETARCH

COPY . .

RUN dotnet publish -a $TARGETARCH --no-restore -c $target -o obj/docker/publish

RUN cp -r /src/obj/docker/publish /OpenIdConnectServerMock

# Stage 2: Release
FROM  --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS release

ARG target="Release"

RUN apk add --no-cache curl
RUN if [ $target = "Debug" ]; then apk add --no-cache bash unzip && curl -sSL https://aka.ms/getvsdbgsh | bash /dev/stdin -v latest -l /vsdbg; fi

COPY --from=source /OpenIdConnectServerMock /OpenIdConnectServerMock
WORKDIR /OpenIdConnectServerMock

ENV ASPNETCORE_ENVIRONMENT=Development

EXPOSE 80
EXPOSE 443

HEALTHCHECK --start-period=2s --interval=1s --timeout=100ms --retries=10 \
    CMD curl -k --location https://localhost/health || exit 1

ENTRYPOINT ["dotnet", "OpenIdConnectServerMock.dll" ]


================================================
FILE: src/Helpers/AspNetServicesHelper.cs
================================================
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using AspNetCorsOptions = Microsoft.AspNetCore.Cors.Infrastructure.CorsOptions;

namespace OpenIdConnectServer.Helpers
{
    public class AspNetServicesOptions
    {
        public AspNetCorsOptions? Cors { get; set; }

        public IDictionary<string, AuthenticationOptions>? Authentication { get; set; }
        public SessionOptions? Session { get; set; }

        public ForwardedHeadersOptions? ForwardedHeadersOptions { get; set; }

        public string? BasePath { get; set; }
    }

    public class AuthenticationOptions
    {
        public CookieAuthenticationOptions? CookieAuthenticationOptions { get; set; }
    }

    public static class AspNetServicesHelper
    {
        public static void ConfigureAspNetServices(IServiceCollection services, AspNetServicesOptions config)
        {
            if (config.Authentication != null)
            {
                ConfigureAuthenticationOptions(services, config.Authentication);
            }

            if (config.Session != null)
            {
                ConfigureSessionOptions(services, config.Session);
            }
        }

        public static void UseAspNetServices(IApplicationBuilder app, AspNetServicesOptions config)
        {
            if (config.Cors != null)
            {
                app.UseCors();
            }

            if (config.ForwardedHeadersOptions != null)
            {
                config.ForwardedHeadersOptions.KnownNetworks.Clear();
                config.ForwardedHeadersOptions.KnownProxies.Clear();
                app.UseForwardedHeaders(config.ForwardedHeadersOptions);
            }
        }

        public static void ConfigureAuthenticationOptions(IServiceCollection services, IDictionary<string, AuthenticationOptions> config)
        {
            foreach (var schemaConfig in config)
            {
                var builder = services.AddAuthentication(schemaConfig.Key);
                ConfigureAuthenticationOptionsForScheme(builder, schemaConfig.Value);
            }
        }

        private static void ConfigureAuthenticationOptionsForScheme(AuthenticationBuilder builder, AuthenticationOptions schemaConfig)
        {
            builder.AddCookie(options => {
                MergeHelper.Merge(schemaConfig.CookieAuthenticationOptions, options);
            });
        }

        private static void ConfigureSessionOptions(IServiceCollection services, SessionOptions config)
        {
            services.AddSession(options => {
                MergeHelper.Merge(config, options);
            });
        }

        private static void ConfigureCors(IServiceCollection services, AspNetCorsOptions corsConfig)
        {
            services.AddCors(options =>
                {
                    MergeHelper.Merge(corsConfig, options);
                }
            );
        }
    }
}


================================================
FILE: src/Helpers/MergeHelper.cs
================================================
namespace OpenIdConnectServer.Helpers
{
    public static class MergeHelper
    {
        public static void Merge<T>(T source, T target)
        {
            Type t = typeof(T);

            var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

            foreach (var prop in properties)
            {
                var value = prop.GetValue(source, null);
                if (value != null)
                {
                    prop.SetValue(target, value, null);
                }
            }
        }
    }
}


================================================
FILE: src/Helpers/OptionsHelper.cs
================================================
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace OpenIdConnectServer.Helpers
{
    public class OptionsHelper
    {
        public static void ConfigureOptions<T>(string optionsStr)
        {
            var options = JsonConvert.DeserializeObject<JObject>(optionsStr);
            var targetFields = typeof(T).GetFields();
            var jValueValueProp = typeof(JValue).GetProperty(nameof(JValue.Value));
            Array.ForEach(targetFields, k => {
                if (options != null && options.ContainsKey(k.Name)) {
                    var fieldJValue = options[k.Name] as JValue;
                    var fieldValue = jValueValueProp?.GetValue(fieldJValue);
                    k.SetValue(null, fieldValue);
                }
            });
        }
    }
}


================================================
FILE: src/JsonConverters/ClaimJsonConverter.cs
================================================
using System.Security.Claims;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace OpenIdConnectServer.JsonConverters
{
    public class ClaimJsonConverter : JsonConverter<Claim>
    {
        public override void WriteJson(JsonWriter writer, Claim value, JsonSerializer serializer)
        {
            throw new NotSupportedException();
        }

        public override Claim ReadJson(JsonReader reader, Type objectType, Claim existingValue, bool hasExistingValue,
            JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var type = jObject["Type"].Value<string>();
            var value = jObject["Value"].Value<string>();
            var valueType = jObject.ContainsKey("ValueType") ? jObject["ValueType"].Value<string>() : ClaimValueTypes.String;
            return new Claim(type, value, valueType);
        }

        public override bool CanRead => true;
        public override bool CanWrite => false;
    }
}


================================================
FILE: src/Middlewares/BasePathMiddleware.cs
================================================
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Configuration;
using Duende.IdentityServer.Services;

#pragma warning disable 1591

namespace OpenIdConnectServer.Middlewares
{
    public class BasePathMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IdentityServerOptions _options;

        public BasePathMiddleware(RequestDelegate next, IdentityServerOptions options)
        {
            _next = next;
            _options = options;
        }

        public async Task Invoke(HttpContext context)
        {
            var basePath = Config.GetAspNetServicesOptions().BasePath;
            var request = context.Request;
            if(request.Path.Value?.Length > basePath.Length)
            {
                request.Path = request.Path.Value.Substring(basePath.Length);
                context.RequestServices.GetRequiredService<IServerUrls>().BasePath = basePath;
            }
            await _next(context);
        }
    }
}


================================================
FILE: src/OpenIdConnectServerMock.csproj
================================================
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>

    <IsPackable>true</IsPackable>
    <Description>Configurable mock server with OpenId Connect functionality</Description>
    <VersionPrefix>0.11.1</VersionPrefix>
    <PackageProjectUrl>https://github.com/Soluto/oidc-server-mock</PackageProjectUrl>
    <PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
    <PackageTags>OIDC</PackageTags>
    <RepositoryUrl>https://github.com/Soluto/oidc-server-mock</RepositoryUrl>
    <RepositoryType>git</RepositoryType>
    <PackAsTool>true</PackAsTool>
    <ToolCommandName>oidc-mock</ToolCommandName>
    <IncludeContentInPack>false</IncludeContentInPack>
  </PropertyGroup>

  <ItemGroup>
    <Content Remove="keys\**" />
    <Content Remove="wwwroot\**" />
    <EmbeddedResource Include="wwwroot\**" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Duende.IdentityServer" Version="7.2.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.11" />
    <PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="8.0.11" />
    <PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
    <PackageReference Include="YamlDotNet" Version="15.3.0" />
  </ItemGroup>

</Project>


================================================
FILE: src/Program.cs
================================================
using Duende.IdentityServer.Hosting;
using Microsoft.Extensions.FileProviders;
using OpenIdConnectServer;
using OpenIdConnectServer.Helpers;
using OpenIdConnectServer.JsonConverters;
using OpenIdConnectServer.Middlewares;
using OpenIdConnectServer.Services;
using OpenIdConnectServer.Validation;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.SystemConsole.Themes;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information)
    .MinimumLevel.Override("System", LogEventLevel.Warning)
    .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code)
    .CreateLogger();

var builder = WebApplication.CreateBuilder(args);

// Configure Serilog
builder.Host.UseSerilog();

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services
    .AddControllersWithViews()
    .AddNewtonsoftJson(options =>
        {
            options.SerializerSettings.Converters.Add(new ClaimJsonConverter());
        });

builder.Services
    .AddIdentityServer(options =>
        {
            var configuredOptions = Config.GetServerOptions();
            MergeHelper.Merge(configuredOptions, options);
        })
    .AddDeveloperSigningCredential()
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryApiScopes(Config.GetApiScopes())
    .AddInMemoryClients(Config.GetClients())
    .AddTestUsers(Config.GetUsers())
    .AddRedirectUriValidator<RedirectUriValidator>()
    .AddProfileService<ProfileService>()
    .AddCorsPolicyService<CorsPolicyService>();

var app = builder.Build();

app.UsePathBase(Config.GetAspNetServicesOptions().BasePath);

var aspNetServicesOptions = Config.GetAspNetServicesOptions();
AspNetServicesHelper.ConfigureAspNetServices(builder.Services, aspNetServicesOptions);
AspNetServicesHelper.UseAspNetServices(app, aspNetServicesOptions);

// Config.ConfigureOptions<IdentityServerHost.Pages.Login.LoginOptions>("LOGIN");
// Config.ConfigureOptions<IdentityServerHost.Pages.Logout.LogoutOptions>("LOGOUT");

app.UseDeveloperExceptionPage();

app.UseIdentityServer();

app.UseHttpsRedirection();

var manifestEmbeddedProvider = new ManifestEmbeddedFileProvider(typeof(Program).Assembly, "wwwroot");
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = manifestEmbeddedProvider
});

app.UseRouting();
app.UseAuthorization();
app.MapDefaultControllerRoute();
app.MapRazorPages();

app.Run();


================================================
FILE: src/Services/CorsPolicyService.cs
================================================
using System.Text.RegularExpressions;
using Duende.IdentityServer.Services;

namespace OpenIdConnectServer.Services
{
    public class CorsPolicyService : ICorsPolicyService
    {
        public Task<bool> IsOriginAllowedAsync(string origin)
        {
            var allowedOrigins = Config.GetServerCorsAllowedOrigins();
            if (allowedOrigins != null && allowedOrigins.Count() > 0)
            {
                return Task.FromResult(allowedOrigins.Any(allowedOrigin =>
                    Regex.Match(origin, Regex.Escape(allowedOrigin).Replace("\\*", "[a-zA-Z0-9.]+?")).Success));
            }
            return Task.FromResult(true);
        }
    }
}


================================================
FILE: src/Services/ProfileService.cs
================================================
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Test;

namespace OpenIdConnectServer.Services
{
    internal class ProfileService : IProfileService
  {
    private readonly TestUserStore _userStore;
    private readonly ILogger Logger;

    public ProfileService(TestUserStore userStore, ILogger<ProfileService> logger)
    {
        _userStore = userStore;
        Logger = logger;
    }

    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var subjectId = context.Subject.GetSubjectId();
        Logger.LogDebug("Getting profile data for subjectId: {subjectId}", subjectId);
        var user = this._userStore.FindBySubjectId(subjectId);
        if (user != null)
        {
            Logger.LogDebug("The user was found in store");
            var claims = context.FilterClaims(user.Claims);
            context.AddRequestedClaims(claims);
        }
        return Task.CompletedTask;
    }

    public Task IsActiveAsync(IsActiveContext context)
    {
        var subjectId = context.Subject.GetSubjectId();
        Logger.LogDebug("Checking if the user is active for subjectId: {subject}", subjectId);
        var user = this._userStore.FindBySubjectId(subjectId);
        context.IsActive = user?.IsActive ?? false;
        Logger.LogDebug("The user is active: {isActive}", context.IsActive);
        return Task.CompletedTask;
    }
  }
}


================================================
FILE: src/Validation/RedirectUriValidator.cs
================================================
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Validation;
using System.Text.RegularExpressions;

namespace OpenIdConnectServer.Validation
{
    internal class RedirectUriValidator : IRedirectUriValidator
    {
        protected bool Validate(string requestedUri, ICollection<string> allowedUris) =>
            allowedUris.Any(allowedUri => Regex.Match(requestedUri, Regex.Escape(allowedUri).Replace("\\*", "[a-zA-Z0-9.]+?")).Success);

        public Task<bool> IsPostLogoutRedirectUriValidAsync(string requestedUri, Client client)
        {
            return Task.FromResult(Validate(requestedUri, client.PostLogoutRedirectUris));
        }

        public Task<bool> IsRedirectUriValidAsync(string requestedUri, Client client)
        {
            return Task.FromResult(Validate(requestedUri, client.RedirectUris));
        }
    }
}


================================================
FILE: src/YamlConverters/ClaimYamlConverter.cs
================================================
using System.Security.Claims;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

namespace OpenIdConnectServer.YamlConverters
{
    public class ClaimYamlConverter : IYamlTypeConverter
    {
        public bool Accepts(Type type)
        {
            return type == typeof(Claim);
        }

#nullable enable
        public void WriteYaml(IEmitter emitter, object? value, Type type)
        {
            throw new NotSupportedException();
        }
#nullable disable


        public object ReadYaml(IParser parser, Type type)
        {
            if (parser.Current.GetType() != typeof(MappingStart)) // You could also use parser.Accept<MappingStart>()
            {
                throw new InvalidDataException("Invalid YAML content.");
            }
            string claimType = "", claimValue = "", claimValueType = "";

            parser.MoveNext(); // move on from the map start

            do
            {
                var scalar = parser.Consume<Scalar>();
                switch (scalar.Value)
                {
                    case "Type":
                        claimType = parser.Consume<Scalar>().Value;
                        break;

                    case "Value":
                        claimValue = parser.Consume<Scalar>().Value;
                        break;

                    case "ValueType":
                        claimValueType = parser.Consume<Scalar>().Value;
                        break;
                }
            } while (parser.Current.GetType() != typeof(MappingEnd));

            parser.MoveNext(); // skip the mapping end (or crash)

            if (string.IsNullOrEmpty(claimType)) throw new InvalidDataException("Type is required property of Claim");
            if (string.IsNullOrEmpty(claimValue)) throw new InvalidDataException("Value is required property of Claim");
            if (string.IsNullOrEmpty(claimValueType)) claimValueType = ClaimValueTypes.String;
            return new Claim(claimType, claimValue, claimValueType);
        }

    }
}


================================================
FILE: src/YamlConverters/SecretYamlConverter.cs
================================================
using Duende.IdentityServer.Models;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

namespace OpenIdConnectServer.YamlConverters
{
    public class SecretYamlConverter : IYamlTypeConverter //<Claim>
    {
        public bool Accepts(Type type)
        {
            return type == typeof(Secret);
        }

        public void WriteYaml(IEmitter emitter, object value, Type type)
        {
            throw new NotSupportedException();
        }

        public object ReadYaml(IParser parser, Type type)
        {
            string s = parser.Consume<Scalar>().Value;
            return new Secret(s.Sha256());
        }
    }
}


================================================
FILE: src/getui.sh
================================================
#!/usr/bin/env bash

set -e

TAG="6.3.0"

git clone -n --depth=1 --filter=tree:0 \
  -b is-7.2.2 --single-branch \
  https://github.com/DuendeSoftware/products
cd products
git sparse-checkout set --no-cone /identity-server/hosts/main
git checkout

cd -

[[ -d Pages ]] || mkdir Pages
[[ -d wwwroot ]] || mkdir wwwroot

cp -r ./products/identity-server/hosts/main/Pages/* Pages
cp -r ./products/identity-server/hosts/main/wwwroot/* wwwroot

rm -rf products


================================================
FILE: src/tempkey.rsa
================================================
{"KeyId":"73239b28fa5e71f10e0f478fb4d25d01","Parameters":{"D":"prsrSaYh19e1aP81scihMxY2ibjG61GZd53on0LbRm21vwAlhzNcY9BAx8Y9xEFpNIqAhO6R2VLqD+PSPvO+y7IojXemeDcmEoLJQKuzGvVQfxBmDYQ3GUChs7F4hkTqnVs32VXHF08ValDBd/1/nmgSi0fsvFx71kcArp7Qx61yUmoaN+nLEzE8csQjipFzlXcH/yHMdIWooP2rqPVP5cLv7WIcIvDVZNiAwEVSY1KiGARHNsWbEm5HtJTK66I15Zp0dZp4oVXVZJIZye78Pjo5X0vmGm7F/x+cc6WTHsFtDUP31NPxv7b5umqnoUYxUyM1wdYy6TYmghXh59TNnQ==","DP":"5lfdYu8v+rINrLorfha7fdglzjk9OOT30kniQbnsds0EYgs8IeyPPf1GAmJKPyOobcDM+kWQKlvvgCPdk9IgsDRgmZycdVwKggtQpQzkJrIOcJe3h8L+hPLSlcXE5yTY3+qXn+mmloDSale5G4fd3M/dhAe5dAugJDCsLC16EM0=","DQ":"000qbMhWiCYORQ8wZIT7g/rDxcswx6GxmcBr7k6TSYISWynlqPctytGm0tQZZoiFXXtvhlMDCFas2pRbST3FZSKMgccjuBu0in29y/xrpbL70zQSHEmvQNKhWS6lwlLN17jlGEFGQpakpKuT6Qdx6dhfvWE2QQyxEdD2TQwr+QU=","Exponent":"AQAB","InverseQ":"kPvqNF07ozNcO/y+gA6kOj03ExEWmNUKjNvqMrmydsY2XBBaqEbZcj+GC2J3jGljPzJsG3dNLl4p01zR8prwk5nkaIgBZWzbBp/J68c1tw+hD/NQJiIEFgnI4t7Jwr235J8bKVFgl0gqdVYLxdNIrOQVRwrBAXhFR4YRs8tQ1Ww=","Modulus":"zAD8Egjll/WgBekLAI+MvPm0JnsI7HMrKzK8E2IBKaq5+HeVZY/mzIiUWnDoI4RHAyrXzqJBZDkornUxJoRtSwbvpdeOZvJk9XS3kLh3Ior5LAl82jNrgDw8G4aG/4sUnWx3EUkOMf5Zi1hCr56c2brO4Pqh/rcjgotVjfhg9Sne4v86+NaaUCDuGXbfS7cJtquSva2Lk63R/FwFcj2RBXTojRbpiCRKDJoESrBnlPNJBYmySFzEmN1B95VfIZQ9s7fwUC6tWr5G6QDDpwBa+JnCaHC6GyYKskfAkzF9+dFXGghpXPjOnp/bXqZRyibVWUQBA29ugmATGyRS/zANSQ==","P":"6LnaI7YJVlHy2FoT+IaqBY4twiEeHvc7xbEaDcxK3Kb4LJRKR4/8ABS6PxlxN73KSNPVIuPaxn+b1e1ApuR+hXZclElN6+fo0Wnl1+ib+9NIGVh9uINuQoNre+agRFyqixuJnKlJjqrL7OAV7KJKIrSO4dhRoWmGXXl0OwwwJEc=","Q":"4GfNELaLgXEjTK1tYF+2fmMuBmrf2EBsCiFtQZjgYYbudQ2m2osIqXP44h5Vlbmb4bQBPDiOntvnvsInkO0E9x0jGvz+k/9KBofjKtARRCty4Rf94KMQmImatgRLG3ko8F8rI+TQM35/zVtXubCLdY0gycisyJBw1M5+OGmS2e8="}}

================================================
FILE: tsconfig.json
================================================
{
  "compilerOptions": {
    "baseUrl": "./",
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "./dist",
    "resolveJsonModule": true,
    "rootDir": ".",
    "target": "ES2022"
  },
  "include": ["e2e/**/*.ts"],
  "exclude": ["e2e/node_modules/**/*", "e2e/dist/**/*"]
}
Download .txt
gitextract_w8n89fhc/

├── .commitlintrc.yml
├── .editorconfig
├── .gitattributes
├── .github/
│   └── workflows/
│       ├── pr.yaml
│       └── tag.yaml
├── .gitignore
├── .husky/
│   ├── commit-msg
│   └── pre-commit
├── .lintstagedrc
├── .nvmrc
├── .prettierignore
├── .prettierrc
├── .vscode/
│   ├── launch.json
│   ├── settings.json
│   └── tasks.json
├── LICENSE
├── README.md
├── Tiltfile
├── e2e/
│   ├── config/
│   │   ├── api-resources.yaml
│   │   ├── clients.json
│   │   ├── identity-resources.json
│   │   ├── server-options.json
│   │   └── users.yaml
│   ├── docker-compose.override.yml
│   ├── docker-compose.yml
│   ├── helpers/
│   │   ├── authorization-endpoint.ts
│   │   ├── endpoints.ts
│   │   ├── grants.ts
│   │   ├── index.ts
│   │   ├── introspect-endpoint.ts
│   │   ├── token-endpoint.ts
│   │   └── user-info-endpoint.ts
│   ├── https/
│   │   └── aspnetapp.pfx
│   ├── jest.config.ts
│   ├── package.json
│   ├── tests/
│   │   ├── __snapshots__/
│   │   │   └── base-path.spec.ts.snap
│   │   ├── base-path.spec.ts
│   │   ├── custom-endpoints/
│   │   │   ├── __snapshots__/
│   │   │   │   └── user-management.spec.ts.snap
│   │   │   └── user-management.spec.ts
│   │   └── flows/
│   │       ├── __snapshots__/
│   │       │   ├── authorization-code-pkce.e2e-spec.ts.snap
│   │       │   ├── authorization-code.e2e-spec.ts.snap
│   │       │   ├── client-credentials-flow.spec.ts.snap
│   │       │   ├── implicit-flow.e2e-spec.ts.snap
│   │       │   └── password-flow.spec.ts.snap
│   │       ├── authorization-code-pkce.e2e-spec.ts
│   │       ├── authorization-code.e2e-spec.ts
│   │       ├── client-credentials-flow.spec.ts
│   │       ├── implicit-flow.e2e-spec.ts
│   │       └── password-flow.spec.ts
│   ├── tsconfig.json
│   ├── types/
│   │   ├── api-resource.ts
│   │   ├── claim.ts
│   │   ├── client.ts
│   │   ├── index.ts
│   │   └── user.ts
│   └── utils/
│       ├── jwt-payload-serializer.js
│       └── jwt-serializer.js
├── eslint.config.js
├── package.json
├── pnpm-workspace.yaml
├── src/
│   ├── .dockerignore
│   ├── Config.cs
│   ├── Controllers/
│   │   ├── HealthController.cs
│   │   └── UserController.cs
│   ├── Dockerfile
│   ├── Helpers/
│   │   ├── AspNetServicesHelper.cs
│   │   ├── MergeHelper.cs
│   │   └── OptionsHelper.cs
│   ├── JsonConverters/
│   │   └── ClaimJsonConverter.cs
│   ├── Middlewares/
│   │   └── BasePathMiddleware.cs
│   ├── OpenIdConnectServerMock.csproj
│   ├── Program.cs
│   ├── Services/
│   │   ├── CorsPolicyService.cs
│   │   └── ProfileService.cs
│   ├── Validation/
│   │   └── RedirectUriValidator.cs
│   ├── YamlConverters/
│   │   ├── ClaimYamlConverter.cs
│   │   └── SecretYamlConverter.cs
│   ├── getui.sh
│   └── tempkey.rsa
└── tsconfig.json
Download .txt
SYMBOL INDEX (64 symbols across 19 files)

FILE: e2e/types/api-resource.ts
  type ApiResource (line 1) | interface ApiResource {

FILE: e2e/types/claim.ts
  type Claim (line 1) | interface Claim {

FILE: e2e/types/client.ts
  type Client (line 3) | interface Client {

FILE: e2e/types/user.ts
  type User (line 3) | interface User {

FILE: e2e/utils/jwt-payload-serializer.js
  method test (line 2) | test(argument) {
  method print (line 5) | print(value) {

FILE: e2e/utils/jwt-serializer.js
  method test (line 2) | test(argument) {
  method print (line 5) | print(value) {

FILE: src/Config.cs
  class Config (line 10) | public static class Config
    method GetAspNetServicesOptions (line 12) | public static AspNetServicesOptions GetAspNetServicesOptions()
    method GetServerOptions (line 28) | public static IdentityServerOptions GetServerOptions()
    method ConfigureOptions (line 44) | public static void ConfigureOptions<T>(string optionsName)
    method GetServerCorsAllowedOrigins (line 59) | public static IEnumerable<string> GetServerCorsAllowedOrigins()
    method GetApiScopes (line 75) | public static IEnumerable<ApiScope> GetApiScopes()
    method GetApiResources (line 91) | public static IEnumerable<ApiResource> GetApiResources()
    method GetClients (line 107) | public static IEnumerable<Client> GetClients()
    method GetIdentityResources (line 123) | public static IEnumerable<IdentityResource> GetIdentityResources()
    method GetUsers (line 140) | public static List<TestUser> GetUsers()
    method GetCustomIdentityResources (line 156) | private static IEnumerable<IdentityResource> GetCustomIdentityResources()
    method DeserializeObject (line 173) | private static T DeserializeObject<T>(string value)
    class IdentityResourceConfig (line 182) | private class IdentityResourceConfig

FILE: src/Controllers/HealthController.cs
  class HealthController (line 5) | public class HealthController : Controller
    method Get (line 7) | [HttpGet("/health")]

FILE: src/Controllers/UserController.cs
  class UserController (line 10) | [Route("api/v1/user")]
    method UserController (line 16) | public UserController(TestUserStore userStore, ILogger<UserController>...
    method GetUser (line 22) | [HttpGet("{subjectId}")]
    method AddUser (line 30) | [HttpPost]

FILE: src/Helpers/AspNetServicesHelper.cs
  class AspNetServicesOptions (line 7) | public class AspNetServicesOptions
  class AuthenticationOptions (line 19) | public class AuthenticationOptions
  class AspNetServicesHelper (line 24) | public static class AspNetServicesHelper
    method ConfigureAspNetServices (line 26) | public static void ConfigureAspNetServices(IServiceCollection services...
    method UseAspNetServices (line 39) | public static void UseAspNetServices(IApplicationBuilder app, AspNetSe...
    method ConfigureAuthenticationOptions (line 54) | public static void ConfigureAuthenticationOptions(IServiceCollection s...
    method ConfigureAuthenticationOptionsForScheme (line 63) | private static void ConfigureAuthenticationOptionsForScheme(Authentica...
    method ConfigureSessionOptions (line 70) | private static void ConfigureSessionOptions(IServiceCollection service...
    method ConfigureCors (line 77) | private static void ConfigureCors(IServiceCollection services, AspNetC...

FILE: src/Helpers/MergeHelper.cs
  class MergeHelper (line 3) | public static class MergeHelper
    method Merge (line 5) | public static void Merge<T>(T source, T target)

FILE: src/Helpers/OptionsHelper.cs
  class OptionsHelper (line 6) | public class OptionsHelper
    method ConfigureOptions (line 8) | public static void ConfigureOptions<T>(string optionsStr)

FILE: src/JsonConverters/ClaimJsonConverter.cs
  class ClaimJsonConverter (line 7) | public class ClaimJsonConverter : JsonConverter<Claim>
    method WriteJson (line 9) | public override void WriteJson(JsonWriter writer, Claim value, JsonSer...
    method ReadJson (line 14) | public override Claim ReadJson(JsonReader reader, Type objectType, Cla...

FILE: src/Middlewares/BasePathMiddleware.cs
  class BasePathMiddleware (line 9) | public class BasePathMiddleware
    method BasePathMiddleware (line 14) | public BasePathMiddleware(RequestDelegate next, IdentityServerOptions ...
    method Invoke (line 20) | public async Task Invoke(HttpContext context)

FILE: src/Services/CorsPolicyService.cs
  class CorsPolicyService (line 6) | public class CorsPolicyService : ICorsPolicyService
    method IsOriginAllowedAsync (line 8) | public Task<bool> IsOriginAllowedAsync(string origin)

FILE: src/Services/ProfileService.cs
  class ProfileService (line 8) | internal class ProfileService : IProfileService
    method ProfileService (line 13) | public ProfileService(TestUserStore userStore, ILogger<ProfileService>...
    method GetProfileDataAsync (line 19) | public Task GetProfileDataAsync(ProfileDataRequestContext context)
    method IsActiveAsync (line 33) | public Task IsActiveAsync(IsActiveContext context)

FILE: src/Validation/RedirectUriValidator.cs
  class RedirectUriValidator (line 7) | internal class RedirectUriValidator : IRedirectUriValidator
    method Validate (line 9) | protected bool Validate(string requestedUri, ICollection<string> allow...
    method IsPostLogoutRedirectUriValidAsync (line 12) | public Task<bool> IsPostLogoutRedirectUriValidAsync(string requestedUr...
    method IsRedirectUriValidAsync (line 17) | public Task<bool> IsRedirectUriValidAsync(string requestedUri, Client ...

FILE: src/YamlConverters/ClaimYamlConverter.cs
  class ClaimYamlConverter (line 8) | public class ClaimYamlConverter : IYamlTypeConverter
    method Accepts (line 10) | public bool Accepts(Type type)
    method WriteYaml (line 16) | public void WriteYaml(IEmitter emitter, object? value, Type type)
    method ReadYaml (line 23) | public object ReadYaml(IParser parser, Type type)

FILE: src/YamlConverters/SecretYamlConverter.cs
  class SecretYamlConverter (line 8) | public class SecretYamlConverter : IYamlTypeConverter //<Claim>
    method Accepts (line 10) | public bool Accepts(Type type)
    method WriteYaml (line 15) | public void WriteYaml(IEmitter emitter, object value, Type type)
    method ReadYaml (line 20) | public object ReadYaml(IParser parser, Type type)
Condensed preview — 80 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (133K chars).
[
  {
    "path": ".commitlintrc.yml",
    "chars": 47,
    "preview": "extends:\n  - '@commitlint/config-conventional'\n"
  },
  {
    "path": ".editorconfig",
    "chars": 181,
    "preview": "root = true\n\n[*]\nindent_style = space\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n[*.{t"
  },
  {
    "path": ".gitattributes",
    "chars": 17,
    "preview": "*.sh text eol=lf\n"
  },
  {
    "path": ".github/workflows/pr.yaml",
    "chars": 929,
    "preview": "name: PR\n\non:\n  pull_request:\n    paths-ignore:\n      - README.md\n\n  workflow_dispatch:\n\nconcurrency:\n  group: pr-${{ gi"
  },
  {
    "path": ".github/workflows/tag.yaml",
    "chars": 3690,
    "preview": "name: Build and push new version\n\non:\n  create:\n\nenv:\n  TILT_VERSION: 'v0.34.2'\n\njobs:\n  build_push_docker:\n    name: Bu"
  },
  {
    "path": ".gitignore",
    "chars": 142,
    "preview": "# TypeScript project\nnode_modules\ndist\n\n# .Net project\nbin\nobj\n\n# Docker\n.docker\n\n# UI\nsrc/Pages\nsrc/wwwroot\n\n# Runtime "
  },
  {
    "path": ".husky/commit-msg",
    "chars": 93,
    "preview": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpx --no-install commitlint --edit \"$1\"\n"
  },
  {
    "path": ".husky/pre-commit",
    "chars": 95,
    "preview": "#!/usr/bin/env sh\n. \"$(dirname -- \"$0\")/_/husky.sh\"\n\nnpx lint-staged\nnpx pretty-quick --staged\n"
  },
  {
    "path": ".lintstagedrc",
    "chars": 157,
    "preview": "\"**/*.js\":\n  - prettier --write\n\"**/*.ts\":\n  - bash -c \"tsc --noEmit\"\n  - eslint --fix\n  - prettier --write\n\"**/*.{json,"
  },
  {
    "path": ".nvmrc",
    "chars": 4,
    "preview": "v22\n"
  },
  {
    "path": ".prettierignore",
    "chars": 33,
    "preview": "**/node_modules\n**/dist\ncoverage\n"
  },
  {
    "path": ".prettierrc",
    "chars": 73,
    "preview": "{\n  \"printWidth\": 120,\n  \"singleQuote\": true,\n  \"arrowParens\": \"avoid\"\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "chars": 1445,
    "preview": "{\n   // Use IntelliSense to find out which attributes exist for C# debugging\n   // Use hover for the description of the "
  },
  {
    "path": ".vscode/settings.json",
    "chars": 760,
    "preview": "{\n  \"editor.formatOnPaste\": false,\n  \"editor.formatOnSave\": true,\n  \"editor.detectIndentation\": false,\n  \"editor.default"
  },
  {
    "path": ".vscode/tasks.json",
    "chars": 1268,
    "preview": "{\n    \"version\": \"2.0.0\",\n    \"tasks\": [\n        {\n            \"label\": \"build\",\n            \"command\": \"dotnet\",\n      "
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 10447,
    "preview": "# OpenId Connect Server Mock\n\n![Run Tests badge](https://github.com/Soluto/oidc-server-mock/workflows/Run%20Tests/badge."
  },
  {
    "path": "Tiltfile",
    "chars": 372,
    "preview": "dockerComps = ['./e2e/docker-compose.yml']\n\nimageTag = os.getenv('IMAGE_TAG', '')\nif imageTag == '':\n    docker_build('o"
  },
  {
    "path": "e2e/config/api-resources.yaml",
    "chars": 158,
    "preview": "- Name: some-app\n  Scopes:\n    - some-app-scope-1\n    - some-app-scope-2\n  ApiSecrets:\n    - some-app-secret-1\n  UserCla"
  },
  {
    "path": "e2e/config/clients.json",
    "chars": 2628,
    "preview": "[\n  {\n    \"ClientId\": \"implicit-flow-client-id\",\n    \"Description\": \"Client for implicit flow\",\n    \"AllowedGrantTypes\":"
  },
  {
    "path": "e2e/config/identity-resources.json",
    "chars": 102,
    "preview": "[\n  {\n    \"Name\": \"some-custom-identity\",\n    \"ClaimTypes\": [\"some-custom-identity-user-claim\"]\n  }\n]\n"
  },
  {
    "path": "e2e/config/server-options.json",
    "chars": 78,
    "preview": "{\n  \"AccessTokenJwtType\": \"JWT\",\n  \"Discovery\": {\n    \"ShowKeySet\": true\n  }\n}"
  },
  {
    "path": "e2e/config/users.yaml",
    "chars": 2265,
    "preview": "[\n  { 'SubjectId': 'simple_user', 'Username': 'simple_user', 'Password': 'pwd' },\n  {\n    'SubjectId': 'user_with_standa"
  },
  {
    "path": "e2e/docker-compose.override.yml",
    "chars": 86,
    "preview": "services:\n  oidc-server-mock:\n    image: ghcr.io/soluto/oidc-server-mock:${IMAGE_TAG}\n"
  },
  {
    "path": "e2e/docker-compose.yml",
    "chars": 1198,
    "preview": "services:\n  oidc-server-mock:\n    container_name: oidc-server-mock\n    image: oidc-server-mock\n    environment:\n      AS"
  },
  {
    "path": "e2e/helpers/authorization-endpoint.ts",
    "chars": 831,
    "preview": "import { expect } from '@jest/globals';\nimport { Page } from 'playwright-chromium';\n\nimport { User } from '../types';\nim"
  },
  {
    "path": "e2e/helpers/endpoints.ts",
    "chars": 1038,
    "preview": "import { from, logger } from 'env-var';\nimport * as dotenv from 'dotenv';\nimport { URL } from 'node:url';\ndotenv.config("
  },
  {
    "path": "e2e/helpers/grants.ts",
    "chars": 655,
    "preview": "import { expect } from '@jest/globals';\nimport { Page } from 'playwright-chromium';\n\nimport { User } from '../types';\nim"
  },
  {
    "path": "e2e/helpers/index.ts",
    "chars": 323,
    "preview": "export { default as authorizationEndpoint } from './authorization-endpoint';\nexport { default as grants } from './grants"
  },
  {
    "path": "e2e/helpers/introspect-endpoint.ts",
    "chars": 1237,
    "preview": "import { expect } from '@jest/globals';\nimport { ApiResource } from 'e2e/types';\nimport * as fs from 'fs/promises';\nimpo"
  },
  {
    "path": "e2e/helpers/token-endpoint.ts",
    "chars": 802,
    "preview": "import { expect } from '@jest/globals';\nimport { decode as decodeJWT } from 'jws';\nimport { oidcTokenUrl } from './endpo"
  },
  {
    "path": "e2e/helpers/user-info-endpoint.ts",
    "chars": 509,
    "preview": "import { expect } from '@jest/globals';\nimport { oidcUserInfoUrl } from './endpoints';\n\nconst userInfoEndpoint = async ("
  },
  {
    "path": "e2e/jest.config.ts",
    "chars": 995,
    "preview": "import type { Config } from '@jest/types';\n\nconst config: Config.InitialOptions = {\n  projects: [\n    {\n      displayNam"
  },
  {
    "path": "e2e/package.json",
    "chars": 775,
    "preview": "{\n  \"name\": \"e2e\",\n  \"version\": \"1.0.0\",\n  \"scripts\": {\n    \"test\": \"NODE_TLS_REJECT_UNAUTHORIZED=0 jest --runInBand --c"
  },
  {
    "path": "e2e/tests/__snapshots__/base-path.spec.ts.snap",
    "chars": 285,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Base path Discovery Endpoint 1`] = `\n{\n  \"access-control-allow-orig"
  },
  {
    "path": "e2e/tests/base-path.spec.ts",
    "chars": 1638,
    "preview": "import { describe, test, beforeAll, expect } from '@jest/globals';\n\nimport clients from '../config/clients.json';\nimport"
  },
  {
    "path": "e2e/tests/custom-endpoints/__snapshots__/user-management.spec.ts.snap",
    "chars": 1137,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`User management Introspection Endpoint 1`] = `\n{\n  \"iss\": \"https://"
  },
  {
    "path": "e2e/tests/custom-endpoints/user-management.spec.ts",
    "chars": 3694,
    "preview": "import { describe, test, beforeAll, expect } from '@jest/globals';\nimport Chance from 'chance';\n\nimport clients from '.."
  },
  {
    "path": "e2e/tests/flows/__snapshots__/authorization-code-pkce.e2e-spec.ts.snap",
    "chars": 5708,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Authorization Code Flow (with PKCE) - simple_user - Introspection E"
  },
  {
    "path": "e2e/tests/flows/__snapshots__/authorization-code.e2e-spec.ts.snap",
    "chars": 5428,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Authorization Code Flow - simple_user - Introspection Endpoint 1`] "
  },
  {
    "path": "e2e/tests/flows/__snapshots__/client-credentials-flow.spec.ts.snap",
    "chars": 697,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Client Credentials Flow Introspection Endpoint 1`] = `\n{\n  \"iss\": \""
  },
  {
    "path": "e2e/tests/flows/__snapshots__/implicit-flow.e2e-spec.ts.snap",
    "chars": 7242,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Implicit Flow - simple_user - Authorization Endpoint (id_token only"
  },
  {
    "path": "e2e/tests/flows/__snapshots__/password-flow.spec.ts.snap",
    "chars": 5228,
    "preview": "// Jest Snapshot v1, https://goo.gl/fbAQLP\n\nexports[`Password Flow - simple_user - Introspection Endpoint 1`] = `\n{\n  \"i"
  },
  {
    "path": "e2e/tests/flows/authorization-code-pkce.e2e-spec.ts",
    "chars": 3224,
    "preview": "import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';\nimport * as crypto f"
  },
  {
    "path": "e2e/tests/flows/authorization-code.e2e-spec.ts",
    "chars": 2658,
    "preview": "import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';\nimport * as fs from "
  },
  {
    "path": "e2e/tests/flows/client-credentials-flow.spec.ts",
    "chars": 952,
    "preview": "import { describe, test, beforeAll, expect } from '@jest/globals';\n\nimport clients from '../../config/clients.json';\nimp"
  },
  {
    "path": "e2e/tests/flows/implicit-flow.e2e-spec.ts",
    "chars": 3338,
    "preview": "import { describe, test, beforeAll, afterAll, beforeEach, afterEach, expect } from '@jest/globals';\n\nimport * as fs from"
  },
  {
    "path": "e2e/tests/flows/password-flow.spec.ts",
    "chars": 1545,
    "preview": "import { describe, test, beforeAll, expect } from '@jest/globals';\n\nimport * as fs from 'fs';\nimport path from 'path';\n\n"
  },
  {
    "path": "e2e/tsconfig.json",
    "chars": 67,
    "preview": "{\n  \"extends\": \"../tsconfig.json\",\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "e2e/types/api-resource.ts",
    "chars": 103,
    "preview": "export default interface ApiResource {\n  Name: string;\n  Scopes?: string[];\n  ApiSecrets?: string[];\n}\n"
  },
  {
    "path": "e2e/types/claim.ts",
    "chars": 90,
    "preview": "export default interface Claim {\n  Type: string;\n  Value: string;\n  ValueType?: string;\n}\n"
  },
  {
    "path": "e2e/types/client.ts",
    "chars": 386,
    "preview": "import type Claim from './claim';\n\nexport default interface Client {\n  ClientId: string;\n  ClientSecrets?: string[];\n  D"
  },
  {
    "path": "e2e/types/index.ts",
    "chars": 189,
    "preview": "export { default as ApiResource } from './api-resource';\nexport { default as Claim } from './claim';\nexport { default as"
  },
  {
    "path": "e2e/types/user.ts",
    "chars": 150,
    "preview": "import type Claim from './claim';\n\nexport default interface User {\n  SubjectId: string;\n  Username: string;\n  Password: "
  },
  {
    "path": "e2e/utils/jwt-payload-serializer.js",
    "chars": 254,
    "preview": "module.exports = {\n  test(argument) {\n    return argument.iat && argument.exp && argument.nbf;\n  },\n  print(value) {\n   "
  },
  {
    "path": "e2e/utils/jwt-serializer.js",
    "chars": 331,
    "preview": "module.exports = {\n  test(argument) {\n    return argument.header && argument.payload && argument.signature;\n  },\n  print"
  },
  {
    "path": "eslint.config.js",
    "chars": 797,
    "preview": "import js from '@eslint/js';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport globals from 'globals';\ni"
  },
  {
    "path": "package.json",
    "chars": 940,
    "preview": "{\n  \"name\": \"oidc-server-mock\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"engi"
  },
  {
    "path": "pnpm-workspace.yaml",
    "chars": 18,
    "preview": "packages:\n  - e2e\n"
  },
  {
    "path": "src/.dockerignore",
    "chars": 70,
    "preview": "bin/\nobj/\n\nPages\nwwwroot\n\nkeys/\ntempkey.jwk\n\nDockerfile\n.dockerignore\n"
  },
  {
    "path": "src/Config.cs",
    "chars": 8391,
    "preview": "using Duende.IdentityServer.Configuration;\nusing Duende.IdentityServer.Models;\nusing Duende.IdentityServer.Test;\nusing O"
  },
  {
    "path": "src/Controllers/HealthController.cs",
    "chars": 246,
    "preview": "using Microsoft.AspNetCore.Mvc;\n\nnamespace OpenIdConnectServer.Controllers\n{\n    public class HealthController : Control"
  },
  {
    "path": "src/Controllers/UserController.cs",
    "chars": 1558,
    "preview": "using System.Collections.Generic;\nusing System.Reflection;\nusing System.Security.Claims;\nusing Duende.IdentityServer.Tes"
  },
  {
    "path": "src/Dockerfile",
    "chars": 1151,
    "preview": "# Stage 1: Build\n\nFROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS source\nARG TARGETARCH\n\nARG t"
  },
  {
    "path": "src/Helpers/AspNetServicesHelper.cs",
    "chars": 2931,
    "preview": "using Microsoft.AspNetCore.Authentication;\nusing Microsoft.AspNetCore.Authentication.Cookies;\nusing AspNetCorsOptions = "
  },
  {
    "path": "src/Helpers/MergeHelper.cs",
    "chars": 550,
    "preview": "namespace OpenIdConnectServer.Helpers\n{\n    public static class MergeHelper\n    {\n        public static void Merge<T>(T "
  },
  {
    "path": "src/Helpers/OptionsHelper.cs",
    "chars": 782,
    "preview": "using Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace OpenIdConnectServer.Helpers\n{\n    public class OptionsHelp"
  },
  {
    "path": "src/JsonConverters/ClaimJsonConverter.cs",
    "chars": 983,
    "preview": "using System.Security.Claims;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Linq;\n\nnamespace OpenIdConnectServer.JsonConv"
  },
  {
    "path": "src/Middlewares/BasePathMiddleware.cs",
    "chars": 1002,
    "preview": "using Duende.IdentityServer.Extensions;\nusing Duende.IdentityServer.Configuration;\nusing Duende.IdentityServer.Services;"
  },
  {
    "path": "src/OpenIdConnectServerMock.csproj",
    "chars": 1465,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk.Web\">\n\n  <PropertyGroup>\n    <TargetFramework>net8.0</TargetFramework>\n    <Nullable>ena"
  },
  {
    "path": "src/Program.cs",
    "chars": 2807,
    "preview": "using Duende.IdentityServer.Hosting;\nusing Microsoft.Extensions.FileProviders;\nusing OpenIdConnectServer;\nusing OpenIdC"
  },
  {
    "path": "src/Services/CorsPolicyService.cs",
    "chars": 669,
    "preview": "using System.Text.RegularExpressions;\nusing Duende.IdentityServer.Services;\n\nnamespace OpenIdConnectServer.Services\n{\n  "
  },
  {
    "path": "src/Services/ProfileService.cs",
    "chars": 1474,
    "preview": "using Duende.IdentityServer.Extensions;\nusing Duende.IdentityServer.Models;\nusing Duende.IdentityServer.Services;\nusing "
  },
  {
    "path": "src/Validation/RedirectUriValidator.cs",
    "chars": 858,
    "preview": "using Duende.IdentityServer.Models;\nusing Duende.IdentityServer.Validation;\nusing System.Text.RegularExpressions;\n\nnames"
  },
  {
    "path": "src/YamlConverters/ClaimYamlConverter.cs",
    "chars": 2058,
    "preview": "using System.Security.Claims;\nusing YamlDotNet.Core;\nusing YamlDotNet.Core.Events;\nusing YamlDotNet.Serialization;\n\nname"
  },
  {
    "path": "src/YamlConverters/SecretYamlConverter.cs",
    "chars": 671,
    "preview": "using Duende.IdentityServer.Models;\nusing YamlDotNet.Core;\nusing YamlDotNet.Core.Events;\nusing YamlDotNet.Serialization;"
  },
  {
    "path": "src/getui.sh",
    "chars": 456,
    "preview": "#!/usr/bin/env bash\n\nset -e\n\nTAG=\"6.3.0\"\n\ngit clone -n --depth=1 --filter=tree:0 \\\n  -b is-7.2.2 --single-branch \\\n  htt"
  },
  {
    "path": "src/tempkey.rsa",
    "chars": 1689,
    "preview": "{\"KeyId\":\"73239b28fa5e71f10e0f478fb4d25d01\",\"Parameters\":{\"D\":\"prsrSaYh19e1aP81scihMxY2ibjG61GZd53on0LbRm21vwAlhzNcY9BAx"
  },
  {
    "path": "tsconfig.json",
    "chars": 324,
    "preview": "{\n  \"compilerOptions\": {\n    \"baseUrl\": \"./\",\n    \"esModuleInterop\": true,\n    \"module\": \"commonjs\",\n    \"moduleResoluti"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the Soluto/oidc-server-mock GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 80 files (118.2 KB), approximately 32.8k tokens, and a symbol index with 64 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!