[
  {
    "path": ".dockerignore",
    "content": "**\n!release-packages\n!ci\n"
  },
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nindent_style = space\ntrim_trailing_whitespace = true\nindent_size = 2\n"
  },
  {
    "path": ".git-blame-ignore-revs",
    "content": "# Prettier 3.4.2\n9b0340a09276f93c054d705d1b9a5f24cc5dbc97"
  },
  {
    "path": ".gitattributes",
    "content": "*.afdesign filter=lfs diff=lfs merge=lfs -text\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "* @coder/code-server\n\nci/helm-chart/ @Matthew-Beckett @alexgorbatchev\n\ndocs/install.md @GNUxeava\n\nsrc/node/i18n/locales/zh-cn.json @zhaozhiming\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "content": "name: Bug report\ndescription: File a bug report\nlabels: [\"bug\", \"triage\"]\nbody:\n  - type: checkboxes\n    attributes:\n      label: Is there an existing issue for this?\n      description: Please search to see if an issue already exists for the bug you encountered.\n      options:\n        - label: I have searched the existing issues\n          required: true\n\n  - type: textarea\n    attributes:\n      label: OS/Web Information\n      description: |\n        examples:\n          - **Web Browser**: Chrome\n          - **Local OS**: macOS\n          - **Remote OS**: Ubuntu\n          - **Remote Architecture**: amd64\n          - **`code-server --version`**: 4.0.1\n\n        Please do not just put \"latest\" for the version.\n      value: |\n        - Web Browser:\n        - Local OS:\n        - Remote OS:\n        - Remote Architecture:\n        - `code-server --version`:\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Steps to Reproduce\n      description: |\n        Please describe exactly how to reproduce the bug. For example:\n        1. Open code-server in Firefox\n        2. Install extension `foo.bar` from the extensions sidebar\n        3. Run command `foo.bar.baz`\n      value: |\n        1.\n        2.\n        3.\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Expected\n      description: What should happen?\n    validations:\n      required: true\n\n  - type: textarea\n    attributes:\n      label: Actual\n      description: What actually happens?\n    validations:\n      required: true\n\n  - type: textarea\n    id: logs\n    attributes:\n      label: Logs\n      description: Run code-server with the --verbose flag and then paste any relevant logs from the server, from the browser console and/or the browser network tab. For issues with installation, include installation logs (i.e. output of `npm install -g code-server`).\n      render: shell\n\n  - type: textarea\n    attributes:\n      label: Screenshot/Video\n      description: Please include a screenshot, gif or screen recording of your issue.\n    validations:\n      required: false\n\n  - type: dropdown\n    attributes:\n      label: Does this bug reproduce in native VS Code?\n      description: If the bug reproduces in native VS Code, submit the issue upstream instead (https://github.com/microsoft/vscode).\n      options:\n        - Yes, this is also broken in native VS Code\n        - No, this works as expected in native VS Code\n        - This cannot be tested in native VS Code\n        - I did not test native VS Code\n    validations:\n      required: true\n\n  - type: dropdown\n    attributes:\n      label: Does this bug reproduce in VS Code web?\n      description: If the bug reproduces in VS Code web, submit the issue upstream instead (https://github.com/microsoft/vscode). You can run VS Code web with `code serve-web` (this is not the same as vscode.dev).\n      options:\n        - Yes, this is also broken in VS Code web\n        - No, this works as expected in VS Code web\n        - This cannot be tested in VS Code web\n        - I did not test VS Code web\n    validations:\n      required: true\n\n  - type: dropdown\n    attributes:\n      label: Does this bug reproduce in GitHub Codespaces?\n      description: If the bug reproduces in GitHub Codespaces, submit the issue upstream instead (https://github.com/microsoft/vscode).\n      options:\n        - Yes, this is also broken in GitHub Codespaces\n        - No, this works as expected in GitHub Codespaces\n        - This cannot be tested in GitHub Codespaces\n        - I did not test GitHub Codespaces\n    validations:\n      required: true\n\n  - type: checkboxes\n    attributes:\n      label: Are you accessing code-server over a secure context?\n      description: code-server relies on service workers (which only work in secure contexts) for many features. Double-check that you are using a secure context like HTTPS or localhost.\n      options:\n        - label: I am using a secure context.\n          required: false\n\n  - type: textarea\n    attributes:\n      label: Notes\n      description: Please include any addition notes that will help us resolve this issue.\n    validations:\n      required: false\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: Question?\n    url: https://github.com/coder/code-server/discussions/new?category_id=22503114\n    about: Ask the community for help on our GitHub Discussions board\n  - name: code-server Slack Community\n    about: Need immediate help or just want to talk? Hop in our Slack. Note - this Slack is not actively monitored by code-server maintainers.\n    url: https://cdr.co/join-community\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/doc.md",
    "content": "---\nname: Documentation improvement\nabout: Suggest a documentation improvement\nlabels: \"docs\"\n---\n\n## What is your suggestion?\n\n## How will this improve the docs?\n\n## Are you interested in submitting a PR for this?\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea to improve code-server\nlabels: enhancement\n---\n\n## What is your suggestion?\n\n## Why do you want this feature?\n\n## Are there any workarounds to get this functionality today?\n\n## Are you interested in submitting a PR for this?\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!--\nPlease link to the issue this PR solves.\nIf there is no existing issue, please first create one unless the fix is minor.\n\nPlease make sure the base of your PR is the default branch!\n-->\n\nFixes #\n"
  },
  {
    "path": ".github/codecov.yml",
    "content": "codecov:\n  require_ci_to_pass: yes\n  allow_coverage_offsets: True\n\ncoverage:\n  precision: 2\n  round: down\n  range: \"40...70\"\n  status:\n    patch: off\n  notify:\n    slack:\n      default:\n        url: secret:v1::tXC7VwEIKYjNU8HRgRv2GdKOSCt5UzpykKZb+o1eCDqBgb2PEqwE3A26QUPYMLo4BO2qtrJhFIvwhUvlPwyzDCNGoNiuZfXr0UeZZ0y1TcZu672R/NBNMwEPO/e1Ye0pHxjzKHnuH7HqbjFucox/RBQLtiL3J56SWGE3JtbkC6o=\n        threshold: 1%\n        only_pulls: false\n        branches:\n          - \"main\"\n\nparsers:\n  gcov:\n    branch_detection:\n      conditional: yes\n      loop: yes\n      method: no\n      macro: no\n\ncomment:\n  layout: \"reach,diff,flags,files,footer\"\n  behavior: default\n  require_changes: no\n"
  },
  {
    "path": ".github/codeql-config.yml",
    "content": "name: \"code-server CodeQL config\"\n"
  },
  {
    "path": ".github/dependabot.yaml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: \"monthly\"\n      time: \"06:00\"\n      timezone: \"America/Chicago\"\n    labels: []\n    commit-message:\n      prefix: \"chore\"\n\n  - package-ecosystem: \"npm\"\n    directory: \"/\"\n    schedule:\n      interval: \"monthly\"\n      time: \"06:00\"\n      timezone: \"America/Chicago\"\n    commit-message:\n      prefix: \"chore\"\n    labels: []\n    ignore:\n      # Ignore patch updates for all dependencies\n      - dependency-name: \"*\"\n        update-types:\n          - version-update:semver-patch\n      # Ignore major updates to Node.js types, because they need to\n      # correspond to the Node.js engine version\n      - dependency-name: \"@types/node\"\n        update-types:\n          - version-update:semver-major\n"
  },
  {
    "path": ".github/semantic.yaml",
    "content": "###############################################################################\n# This file configures \"Semantic Pull Requests\", which is documented here:\n# https://github.com/zeke/semantic-pull-requests\n###############################################################################\n\n# Scopes are optionally supplied after a 'type'. For example, in\n#\n# feat(docs): autostart ui\n#\n# '(docs)' is the scope. Scopes are used to signify where the change occurred.\nscopes:\n  # docs: changes to the code-server documentation.\n  - docs\n\n  # vendor: changes to vendored dependencies.\n  - vendor\n\n  # deps: changes to code-server's dependencies.\n  - deps\n\n  # cs: changes to code specific to code-server.\n  - cs\n\n  # cli: changes to the command-line interface.\n  - cli\n\n# We only check that the PR title is semantic. The PR title is automatically\n# applied to the \"Squash & Merge\" flow as the suggested commit message, so this\n# should suffice unless someone drastically alters the message in that flow.\ntitleOnly: true\n\n# Types are the 'tag' types in a commit or PR title. For example, in\n#\n# chore: fix thing\n#\n# 'chore' is the type.\ntypes:\n  # A build of any kind.\n  - build\n\n  # A user-facing change that corrects a defect in code-server.\n  - fix\n\n  # Any code task that is ignored for changelog purposes. Examples include\n  # devbin scripts and internal-only configurations.\n  - chore\n\n  # Any work performed on CI.\n  - ci\n\n  # Work that directly implements or supports the implementation of a feature.\n  - feat\n\n  # A refactor changes code structure without any behavioral change.\n  - refactor\n\n  # A git revert for any style of commit.\n  - revert\n\n  # Adding tests of any kind. Should be separate from feature or fix\n  # implementations. For example, if a commit adds a fix + test, it's a fix\n  # commit. If a commit is simply bumping coverage, it's a test commit.\n  - test\n\n  # A new release.\n  - release\n"
  },
  {
    "path": ".github/stale.yml",
    "content": "# Number of days of inactivity before an issue becomes stale\ndaysUntilStale: 180\n# Number of days of inactivity before a stale issue is closed\ndaysUntilClose: 5\n# Label to apply when stale.\nstaleLabel: stale\n# Comment to post when marking an issue as stale. Set to `false` to disable\nmarkComment: >\n  This issue has been automatically marked as stale because it has not had\n  recent activity. It will be closed if no activity occurs in the next 5 days.\n# Comment to post when closing a stale issue. Set to `false` to disable\ncloseComment: false\n"
  },
  {
    "path": ".github/workflows/build.yaml",
    "content": "name: Build\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n    branches:\n      - main\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes, and serialize builds in branches.\n# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-concurrency-to-cancel-any-in-progress-job-or-run\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\n# Note: if: success() is used in several jobs -\n# this ensures that it only executes if all previous jobs succeeded.\n\n# if: steps.cache-node-modules.outputs.cache-hit != 'true'\n# will skip running `npm install` if it successfully fetched from cache\n\njobs:\n  changes:\n    runs-on: ubuntu-latest\n    outputs:\n      ci: ${{ steps.filter.outputs.ci }}\n      code: ${{ steps.filter.outputs.code }}\n      deps: ${{ steps.filter.outputs.deps }}\n      docs: ${{ steps.filter.outputs.docs }}\n      helm: ${{ steps.filter.outputs.helm }}\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n      - name: Check changed files\n        uses: dorny/paths-filter@v3\n        id: filter\n        with:\n          filters: |\n            ci:\n              - \".github/**\"\n              - \"ci/**\"\n            docs:\n              - \"docs/**\"\n              - \"README.md\"\n              - \"CHANGELOG.md\"\n            helm:\n              - \"ci/helm-chart/**\"\n            code:\n              - \"src/**\"\n              - \"test/**\"\n            deps:\n              - \"lib/**\"\n              - \"patches/**\"\n              - \"package-lock.json\"\n              - \"test/package-lock.json\"\n      - id: debug\n        run: |\n          echo \"${{ toJSON(steps.filter )}}\"\n\n  prettier:\n    name: Run prettier check\n    runs-on: ubuntu-22.04\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - run: npx prettier --check .\n\n  doctoc:\n    name: Doctoc markdown files\n    runs-on: ubuntu-22.04\n    needs: changes\n    if: needs.changes.outputs.docs == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - run: npm run doctoc\n\n  lint-helm:\n    name: Lint Helm chart\n    runs-on: ubuntu-22.04\n    needs: changes\n    if: needs.changes.outputs.helm == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - uses: azure/setup-helm@v4\n        with:\n          token: ${{ secrets.GITHUB_TOKEN }}\n      - run: helm plugin install https://github.com/instrumenta/helm-kubeval\n      - run: helm kubeval ci/helm-chart\n\n  lint-ts:\n    name: Lint TypeScript files\n    runs-on: ubuntu-22.04\n    needs: changes\n    if: needs.changes.outputs.code == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - run: npm run lint:ts\n\n  lint-actions:\n    name: Lint GitHub Actions\n    runs-on: ubuntu-latest\n    needs: changes\n    if: needs.changes.outputs.ci == 'true'\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n      - name: Check workflow files\n        run: |\n          bash <(curl https://raw.githubusercontent.com/rhysd/actionlint/main/scripts/download-actionlint.bash) 1.7.9\n          ./actionlint -color -shellcheck= -ignore \"softprops/action-gh-release\"\n        shell: bash\n\n  test-unit:\n    name: Run unit tests\n    runs-on: ubuntu-22.04\n    needs: changes\n    if: needs.changes.outputs.code == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - run: npm run test:unit\n      - uses: codecov/codecov-action@v5\n        if: success()\n        with:\n          token: ${{ secrets.CODECOV_TOKEN }}\n\n  build:\n    name: Build code-server\n    runs-on: ubuntu-22.04\n    env:\n      CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}\n      DISABLE_V8_COMPILE_CACHE: 1\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          submodules: true\n      - run: sudo apt update && sudo apt install -y libkrb5-dev\n      - uses: awalsh128/cache-apt-pkgs-action@latest\n        with:\n          packages: quilt\n          version: 1.0\n      - run: quilt push -a\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - run: npm run build\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n      # Get Code's git hash.  When this changes it means the content is\n      # different and we need to rebuild.\n      - name: Get latest lib/vscode rev\n        id: vscode-rev\n        run: echo \"rev=$(git rev-parse HEAD:./lib/vscode)\" >> $GITHUB_OUTPUT\n      # We need to rebuild when we have a new version of Code, when any of\n      # the patches changed, or when the code-server version changes (since\n      # it gets embedded into the code).  Use VSCODE_CACHE_VERSION to\n      # force a rebuild.\n      - name: Fetch prebuilt Code package from cache\n        id: cache-vscode\n        uses: actions/cache@v4\n        with:\n          path: lib/vscode-reh-web-*\n          key: vscode-reh-package-${{ secrets.VSCODE_CACHE_VERSION }}-${{ steps.vscode-rev.outputs.rev }}-${{ hashFiles('patches/*.diff', 'ci/build/build-vscode.sh') }}\n      - name: Build vscode\n        env:\n          VERSION: \"0.0.0\"\n        if: steps.cache-vscode.outputs.cache-hit != 'true'\n        run: |\n          pushd lib/vscode\n          npm ci\n          popd\n          npm run build:vscode\n      # The release package does not contain any native modules\n      # and is neutral to architecture/os/libc version.\n      - run: npm run release\n        if: success()\n      # https://github.com/actions/upload-artifact/issues/38\n      - run: tar -czf package.tar.gz release\n      - uses: actions/upload-artifact@v7\n        with:\n          name: npm-package\n          path: ./package.tar.gz\n\n  test-e2e:\n    name: Run e2e tests\n    runs-on: ubuntu-22.04\n    needs: [changes, build]\n    if: needs.changes.outputs.code == 'true' || needs.changes.outputs.deps == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - run: sudo apt update && sudo apt install -y libkrb5-dev\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - uses: actions/download-artifact@v8\n        with:\n          name: npm-package\n      - run: tar -xzf package.tar.gz\n      - run: cd release && npm install --unsafe-perm --omit=dev\n      - name: Install Playwright OS dependencies\n        run: |\n          ./test/node_modules/.bin/playwright install-deps\n          ./test/node_modules/.bin/playwright install\n      - run: CODE_SERVER_TEST_ENTRY=./release npm run test:e2e\n      - uses: actions/upload-artifact@v7\n        if: always()\n        with:\n          name: failed-test-videos\n          path: ./test/test-results\n      - run: rm -rf ./release ./test/test-results\n\n  test-e2e-proxy:\n    name: Run e2e tests behind proxy\n    runs-on: ubuntu-22.04\n    needs: [changes, build]\n    if: needs.changes.outputs.code == 'true' || needs.changes.outputs.deps == 'true'\n    steps:\n      - uses: actions/checkout@v6\n      - run: sudo apt update && sudo apt install -y libkrb5-dev\n      - uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n      - uses: actions/download-artifact@v8\n        with:\n          name: npm-package\n      - run: tar -xzf package.tar.gz\n      - run: cd release && npm install --unsafe-perm --omit=dev\n      - name: Install Playwright OS dependencies\n        run: |\n          ./test/node_modules/.bin/playwright install-deps\n          ./test/node_modules/.bin/playwright install\n      - name: Cache Caddy\n        uses: actions/cache@v4\n        id: caddy-cache\n        with:\n          path: |\n            ~/.cache/caddy\n          key: cache-caddy-2.5.2\n      - name: Install Caddy\n        env:\n          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n        if: steps.caddy-cache.outputs.cache-hit != 'true'\n        run: |\n          gh release download v2.5.2 --repo caddyserver/caddy --pattern \"caddy_2.5.2_linux_amd64.tar.gz\"\n          mkdir -p ~/.cache/caddy\n          tar -xzf caddy_2.5.2_linux_amd64.tar.gz --directory ~/.cache/caddy\n      - run: ~/.cache/caddy/caddy start --config ./ci/Caddyfile\n      - run: CODE_SERVER_TEST_ENTRY=./release npm run test:e2e:proxy\n      - run: ~/.cache/caddy/caddy stop --config ./ci/Caddyfile\n        if: always()\n\n      - uses: actions/upload-artifact@v7\n        if: always()\n        with:\n          name: failed-test-videos-proxy\n          path: ./test/test-results\n"
  },
  {
    "path": ".github/workflows/installer.yaml",
    "content": "name: Installer integration\n\non:\n  push:\n    branches:\n      - main\n    paths:\n      - \"install.sh\"\n      - \".github/workflows/installer.yaml\"\n  pull_request:\n    branches:\n      - main\n    paths:\n      - \"install.sh\"\n      - \".github/workflows/installer.yaml\"\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes, and serialize builds in branches.\n# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-concurrency-to-cancel-any-in-progress-job-or-run\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\npermissions:\n  contents: read\n\njobs:\n  ubuntu:\n    name: Test installer on Ubuntu\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install code-server\n        run: ./install.sh\n\n      - name: Test code-server was installed globally\n        run: code-server --help\n\n  alpine:\n    name: Test installer on Alpine\n    runs-on: ubuntu-latest\n    container: \"alpine:3.17\"\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install curl\n        run: apk add curl\n\n      - name: Add user\n        run: adduser coder --disabled-password\n\n      # Standalone should work without root.\n      - name: Test standalone to a non-existent prefix\n        run: su coder -c \"./install.sh --method standalone --prefix /tmp/does/not/yet/exist\"\n\n      # We do not actually have Alpine standalone builds so running code-server\n      # will not work.\n      - name: Test code-server was installed to prefix\n        run: test -f /tmp/does/not/yet/exist/bin/code-server\n\n  macos:\n    name: Test installer on macOS\n    runs-on: macos-latest\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install code-server\n        run: ./install.sh\n\n      - name: Test code-server was installed globally\n        run: code-server --help\n"
  },
  {
    "path": ".github/workflows/publish.yaml",
    "content": "name: Publish code-server\n\non:\n  # Shows the manual trigger in GitHub UI\n  # helpful as a back-up in case the GitHub Actions Workflow fails\n  workflow_dispatch:\n    inputs:\n      version:\n        description: The version to publish (include \"v\", i.e. \"v4.9.1\").\n        type: string\n        required: true\n\n  release:\n    types: [released]\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes, and serialize builds in branches.\n# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-concurrency-to-cancel-any-in-progress-job-or-run\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n  npm:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code-server\n        uses: actions/checkout@v6\n\n      - name: Install Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n\n      - name: Download npm package from release artifacts\n        uses: robinraju/release-downloader@v1.12\n        with:\n          repository: \"coder/code-server\"\n          tag: ${{ github.event.inputs.version || github.ref_name }}\n          fileName: \"package.tar.gz\"\n          out-file-path: \"release-npm-package\"\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ github.event.inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - run: npm run publish:npm\n        env:\n          VERSION: ${{ env.VERSION }}\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}\n          NPM_ENVIRONMENT: \"production\"\n\n  aur:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    env:\n      GH_TOKEN: ${{ secrets.HOMEBREW_GITHUB_API_TOKEN }}\n\n    steps:\n      # We need to checkout code-server so we can get the version\n      - name: Checkout code-server\n        uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n          path: \"./code-server\"\n\n      - name: Checkout code-server-aur repo\n        uses: actions/checkout@v6\n        with:\n          repository: \"cdrci/code-server-aur\"\n          token: ${{ secrets.HOMEBREW_GITHUB_API_TOKEN }}\n          ref: \"master\"\n\n      - name: Merge in master\n        run: |\n          git remote add upstream https://github.com/coder/code-server-aur.git\n          git fetch upstream\n          git merge upstream/master\n\n      - name: Configure git\n        run: |\n          git config --global user.name cdrci\n          git config --global user.email opensource@coder.com\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ github.event.inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - name: Validate package\n        uses: heyhusen/archlinux-package-action@v3.0.0\n        env:\n          VERSION: ${{ env.VERSION }}\n        with:\n          pkgver: ${{ env.VERSION }}\n          updpkgsums: true\n          srcinfo: true\n\n      - name: Open PR\n        # We need to git push -u otherwise gh will prompt\n        # asking where to push the branch.\n        env:\n          VERSION: ${{ env.VERSION }}\n        run: |\n          git checkout -b update-version-${{ env.VERSION }}\n          git add .\n          git commit -m \"chore: updating version to ${{ env.VERSION }}\"\n          git push -u origin $(git branch --show)\n          gh pr create --repo coder/code-server-aur --title \"chore: bump version to ${{ env.VERSION }}\" --body \"PR opened by @$GITHUB_ACTOR\" --assignee $GITHUB_ACTOR\n\n  docker:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code-server\n        uses: actions/checkout@v6\n\n      - name: Set up QEMU\n        uses: docker/setup-qemu-action@v3\n\n      - name: Set up Docker Buildx\n        uses: docker/setup-buildx-action@v3\n\n      - name: Login to Docker Hub\n        uses: docker/login-action@v3\n        with:\n          username: ${{ secrets.DOCKER_USERNAME }}\n          password: ${{ secrets.DOCKER_PASSWORD }}\n\n      - name: Login to GHCR\n        uses: docker/login-action@v3\n        with:\n          registry: ghcr.io\n          username: ${{ github.actor }}\n          password: ${{ secrets.GITHUB_TOKEN }}\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ github.event.inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - name: Download deb artifacts\n        uses: robinraju/release-downloader@v1.12\n        with:\n          repository: \"coder/code-server\"\n          tag: v${{ env.VERSION }}\n          fileName: \"*.deb\"\n          out-file-path: \"release-packages\"\n\n      - name: Download rpm artifacts\n        uses: robinraju/release-downloader@v1.12\n        with:\n          repository: \"coder/code-server\"\n          tag: v${{ env.VERSION }}\n          fileName: \"*.rpm\"\n          out-file-path: \"release-packages\"\n\n      - name: Publish to Docker\n        run: ./ci/steps/docker-buildx-push.sh\n        env:\n          VERSION: ${{ env.VERSION }}\n          GITHUB_TOKEN: ${{ github.token }}\n"
  },
  {
    "path": ".github/workflows/release.yaml",
    "content": "name: Draft release\n\non:\n  workflow_dispatch:\n    inputs:\n      version:\n        description: The version to publish (include \"v\", i.e. \"v4.9.1\").\n        type: string\n        required: true\n\npermissions:\n  contents: write # For creating releases.\n  discussions: write #  For creating a discussion.\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n  package-linux-cross:\n    name: ${{ matrix.prefix }}\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    needs: npm-version\n    container: \"python:3.8-slim-buster\"\n    strategy:\n      matrix:\n        include:\n          - prefix: x86_64-linux-gnu\n            npm_arch: x64\n            apt_arch: amd64\n            package_arch: amd64\n          - prefix: aarch64-linux-gnu\n            npm_arch: arm64\n            apt_arch: arm64\n            package_arch: arm64\n          - prefix: arm-linux-gnueabihf\n            npm_arch: armv7l\n            apt_arch: armhf\n            package_arch: armv7l\n\n    env:\n      AR: ${{ format('{0}-ar', matrix.prefix) }}\n      AS: ${{ format('{0}-as', matrix.prefix) }}\n      CC: ${{ format('{0}-gcc', matrix.prefix) }}\n      CPP: ${{ format('{0}-cpp', matrix.prefix) }}\n      CXX: ${{ format('{0}-g++', matrix.prefix) }}\n      FC: ${{ format('{0}-gfortran', matrix.prefix) }}\n      LD: ${{ format('{0}-ld', matrix.prefix) }}\n      STRIP: ${{ format('{0}-strip', matrix.prefix) }}\n      PKG_CONFIG_PATH: ${{ format('/usr/lib/{0}/pkgconfig', matrix.prefix) }}\n      TARGET_ARCH: ${{ matrix.apt_arch }}\n      npm_config_arch: ${{ matrix.npm_arch }}\n      PKG_ARCH: ${{ matrix.package_arch }}\n      # Not building from source results in an x86_64 argon2, as if\n      # npm_config_arch is being ignored.\n      npm_config_build_from_source: true\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n\n      - name: Install cross-compiler and system dependencies\n        run: |\n          sed -i 's/deb\\.debian\\.org/archive.debian.org/g' /etc/apt/sources.list\n          dpkg --add-architecture $TARGET_ARCH\n          apt update && apt install -y --no-install-recommends \\\n            crossbuild-essential-$TARGET_ARCH \\\n            libx11-dev:$TARGET_ARCH \\\n            libx11-xcb-dev:$TARGET_ARCH \\\n            libxkbfile-dev:$TARGET_ARCH \\\n            libsecret-1-dev:$TARGET_ARCH \\\n            libkrb5-dev:$TARGET_ARCH \\\n            ca-certificates \\\n            curl wget rsync gettext-base\n\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n\n      - name: Install nfpm\n        run: |\n          mkdir -p ~/.local/bin\n          curl -sSfL https://github.com/goreleaser/nfpm/releases/download/v2.3.1/nfpm_2.3.1_`uname -s`_`uname -m`.tar.gz | tar -C ~/.local/bin -zxv nfpm\n          echo \"$HOME/.local/bin\" >> $GITHUB_PATH\n\n      - name: Download npm package\n        uses: actions/download-artifact@v8\n        with:\n          name: npm-release-package\n\n      - run: tar -xzf package.tar.gz\n      - run: npm run release:standalone\n\n      - name: Replace node with cross-compile equivalent\n        run: |\n          node_version=$(node --version)\n          wget https://nodejs.org/dist/${node_version}/node-${node_version}-linux-${npm_config_arch}.tar.xz\n          tar -xf node-${node_version}-linux-${npm_config_arch}.tar.xz node-${node_version}-linux-${npm_config_arch}/bin/node --strip-components=2\n          mv ./node ./release-standalone/lib/node\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - env:\n          VERSION: ${{ env.VERSION }}\n        run: npm run package $PKG_ARCH\n\n      - uses: softprops/action-gh-release@v1\n        with:\n          draft: true\n          discussion_category_name: \"📣 Announcements\"\n          files: ./release-packages/*\n\n  package-macos-amd64:\n    name: x86-64 macOS build\n    runs-on: macos-15-intel\n    timeout-minutes: 15\n    needs: npm-version\n    env:\n      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n\n      - name: Install nfpm\n        run: |\n          mkdir -p ~/.local/bin\n          curl -sSfL https://github.com/goreleaser/nfpm/releases/download/v2.3.1/nfpm_2.3.1_`uname -s`_`uname -m`.tar.gz | tar -C ~/.local/bin -zxv nfpm\n          echo \"$HOME/.local/bin\" >> $GITHUB_PATH\n\n      # The version of node-gyp we use depends on distutils but it was removed\n      # in Python 3.12.  It seems to be fixed in the latest node-gyp so when we\n      # next update Node we can probably remove this.  For now, install\n      # setuptools since it contains distutils.\n      - run: brew install python-setuptools\n\n      - name: Download npm package\n        uses: actions/download-artifact@v8\n        with:\n          name: npm-release-package\n\n      - run: tar -xzf package.tar.gz\n      - run: npm run release:standalone\n      - run: npm run test:native\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - name: Build packages with nfpm\n        env:\n          VERSION: ${{ env.VERSION }}\n        run: npm run package\n\n      - uses: softprops/action-gh-release@v1\n        with:\n          draft: true\n          discussion_category_name: \"📣 Announcements\"\n          files: ./release-packages/*\n\n  package-macos-arm64:\n    name: arm64 macOS build\n    runs-on: macos-latest\n    timeout-minutes: 15\n    needs: npm-version\n    env:\n      GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n          cache: npm\n          cache-dependency-path: |\n            package-lock.json\n            test/package-lock.json\n\n      - run: SKIP_SUBMODULE_DEPS=1 npm ci\n\n      - name: Install nfpm\n        run: |\n          mkdir -p ~/.local/bin\n          curl -sSfL https://github.com/goreleaser/nfpm/releases/download/v2.3.1/nfpm_2.3.1_`uname -s`_`uname -m`.tar.gz | tar -C ~/.local/bin -zxv nfpm\n          echo \"$HOME/.local/bin\" >> $GITHUB_PATH\n\n      # The version of node-gyp we use depends on distutils but it was removed\n      # in Python 3.12.  It seems to be fixed in the latest node-gyp so when we\n      # next update Node we can probably remove this.  For now, install\n      # setuptools since it contains distutils.\n      - run: brew install python-setuptools\n\n      - name: Download npm package\n        uses: actions/download-artifact@v8\n        with:\n          name: npm-release-package\n\n      - run: tar -xzf package.tar.gz\n      - run: npm run release:standalone\n      - run: npm run test:native\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - name: Build packages with nfpm\n        env:\n          VERSION: ${{ env.VERSION }}\n        run: npm run package\n\n      - uses: softprops/action-gh-release@v1\n        with:\n          draft: true\n          discussion_category_name: \"📣 Announcements\"\n          files: ./release-packages/*\n\n  npm-package:\n    name: Upload npm package\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    needs: npm-version\n    steps:\n      - name: Download npm package\n        uses: actions/download-artifact@v8\n        with:\n          name: npm-release-package\n\n      - uses: softprops/action-gh-release@v1\n        with:\n          draft: true\n          discussion_category_name: \"📣 Announcements\"\n          files: ./package.tar.gz\n\n  npm-version:\n    name: Modify package.json version\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    steps:\n      - name: Download artifacts\n        uses: dawidd6/action-download-artifact@v16\n        id: download\n        with:\n          branch: ${{ github.ref }}\n          workflow: build.yaml\n          workflow_conclusion: completed\n          name: npm-package\n          check_artifacts: false\n          if_no_artifact_found: fail\n\n      - run: tar -xzf package.tar.gz\n\n      # Strip out the v (v4.9.1 -> 4.9.1).\n      - name: Get and set VERSION\n        run: |\n          TAG=\"${{ inputs.version || github.ref_name }}\"\n          echo \"VERSION=${TAG#v}\" >> $GITHUB_ENV\n\n      - name: Modify version\n        env:\n          VERSION: ${{ env.VERSION }}\n        run: |\n          echo \"Updating version in root package.json\"\n          npm version --prefix release \"$VERSION\"\n\n          echo \"Updating version in lib/vscode/product.json\"\n          tmp=$(mktemp)\n          jq \".codeServerVersion = \\\"$VERSION\\\"\" release/lib/vscode/product.json > \"$tmp\" && mv \"$tmp\" release/lib/vscode/product.json\n          # Ensure it has the same permissions as before\n          chmod 644 release/lib/vscode/product.json\n\n      - run: tar -czf package.tar.gz release\n\n      - name: Upload npm package artifact\n        uses: actions/upload-artifact@v7\n        with:\n          name: npm-release-package\n          path: ./package.tar.gz\n"
  },
  {
    "path": ".github/workflows/scripts.yaml",
    "content": "name: Script unit tests\n\non:\n  push:\n    branches:\n      - main\n    paths:\n      - \"**.sh\"\n      - \"**.bats\"\n  pull_request:\n    branches:\n      - main\n    paths:\n      - \"**.sh\"\n      - \"**.bats\"\n\npermissions:\n  actions: none\n  checks: none\n  contents: read\n  deployments: none\n  issues: none\n  packages: none\n  pull-requests: none\n  repository-projects: none\n  security-events: none\n  statuses: none\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes, and serialize builds in branches.\n# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-concurrency-to-cancel-any-in-progress-job-or-run\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n  test:\n    name: Run script unit tests\n    runs-on: ubuntu-latest\n    # This runs on Alpine to make sure we're testing with actual sh.\n    container: \"alpine:3.17\"\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install test utilities\n        run: apk add bats checkbashisms\n\n      - name: Check Bashisms\n        run: checkbashisms ./install.sh\n\n      - name: Run script unit tests\n        run: ./ci/dev/test-scripts.sh\n\n  lint:\n    name: Lint shell files\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Install lint utilities\n        run: sudo apt install shellcheck\n\n      - name: Lint shell files\n        run: ./ci/dev/lint-scripts.sh\n"
  },
  {
    "path": ".github/workflows/security.yaml",
    "content": "name: Security\n\non:\n  push:\n    branches: [main]\n    paths:\n      - \"package.json\"\n  pull_request:\n    paths:\n      - \"package.json\"\n  schedule:\n    # Runs every Monday morning PST\n    - cron: \"17 15 * * 1\"\n\n# Cancel in-progress runs for pull requests when developers push additional\n# changes, and serialize builds in branches.\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: ${{ github.event_name == 'pull_request' }}\n\njobs:\n  audit:\n    name: Audit node modules\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Install Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version-file: .node-version\n\n      - name: Audit npm for vulnerabilities\n        run: npm audit\n        if: success()\n\n  trivy-scan-repo:\n    name: Scan repo with Trivy\n    permissions:\n      contents: read # for actions/checkout to fetch code\n      security-events: write # for github/codeql-action/upload-sarif to upload SARIF results\n    runs-on: ubuntu-22.04\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Run Trivy vulnerability scanner in repo mode\n        uses: aquasecurity/trivy-action@97e0b3872f55f89b95b2f65b3dbab56962816478\n        with:\n          scan-type: \"fs\"\n          scan-ref: \".\"\n          ignore-unfixed: true\n          format: \"template\"\n          template: \"@/contrib/sarif.tpl\"\n          output: \"trivy-repo-results.sarif\"\n          severity: \"HIGH,CRITICAL\"\n\n      - name: Upload Trivy scan results to GitHub Security tab\n        uses: github/codeql-action/upload-sarif@v4\n        with:\n          sarif_file: \"trivy-repo-results.sarif\"\n\n  codeql-analyze:\n    permissions:\n      actions: read # for github/codeql-action/init to get workflow details\n      contents: read # for actions/checkout to fetch code\n      security-events: write # for github/codeql-action/autobuild to send a status report\n    name: Analyze with CodeQL\n    runs-on: ubuntu-22.04\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      # Initializes the CodeQL tools for scanning.\n      - name: Initialize CodeQL\n        uses: github/codeql-action/init@v4\n        with:\n          config-file: ./.github/codeql-config.yml\n          languages: javascript\n\n      - name: Autobuild\n        uses: github/codeql-action/autobuild@v4\n\n      - name: Perform CodeQL Analysis\n        uses: github/codeql-action/analyze@v4\n"
  },
  {
    "path": ".github/workflows/trivy-docker.yaml",
    "content": "name: Trivy Nightly Docker Scan\n\non:\n  # Run scans if the workflow is modified, in order to test the\n  # workflow itself. This results in some spurious notifications,\n  # but seems okay for testing.\n  pull_request:\n    branches:\n      - main\n    paths:\n      - .github/workflows/trivy-docker.yaml\n\n  # Run scans against master whenever changes are merged.\n  push:\n    branches:\n      - main\n    paths:\n      - .github/workflows/trivy-docker.yaml\n\n  schedule:\n    # Run at 10:15 am UTC (3:15am PT/5:15am CT)\n    # Run at 0 minutes 0 hours of every day.\n    - cron: \"15 10 * * *\"\n\n  workflow_dispatch:\n\npermissions:\n  actions: none\n  checks: none\n  contents: read\n  deployments: none\n  issues: none\n  packages: none\n  pull-requests: none\n  repository-projects: none\n  security-events: write\n  statuses: none\n\n# Cancel in-progress runs for pull requests when developers push\n# additional changes, and serialize builds in branches.\n# https://docs.github.com/en/actions/using-jobs/using-concurrency#example-using-concurrency-to-cancel-any-in-progress-job-or-run\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  trivy-scan-image:\n    runs-on: ubuntu-22.04\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n\n      - name: Run Trivy vulnerability scanner in image mode\n        uses: aquasecurity/trivy-action@97e0b3872f55f89b95b2f65b3dbab56962816478\n        with:\n          image-ref: \"docker.io/codercom/code-server:latest\"\n          ignore-unfixed: true\n          format: \"sarif\"\n          output: \"trivy-image-results.sarif\"\n          severity: \"HIGH,CRITICAL\"\n\n      - name: Upload Trivy scan results to GitHub Security tab\n        uses: github/codeql-action/upload-sarif@v4\n        with:\n          sarif_file: \"trivy-image-results.sarif\"\n"
  },
  {
    "path": ".gitignore",
    "content": ".tsbuildinfo\n.cache\n/out*/\nrelease/\nrelease-npm-package/\nrelease-standalone/\nrelease-packages/\nrelease-gcp/\nrelease-images/\nnode_modules\n/plugins\n/lib/coder-cloud-agent\n.home\ncoverage\n**/.DS_Store\n\n# Code packages itself here.\n/lib/vscode-reh-web-*\n\n# Failed e2e test videos are saved here\ntest/test-results\n\n# Quilt's internal data.\n/.pc\n/patches/*.diff~\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"lib/vscode\"]\n\tpath = lib/vscode\n\turl = https://github.com/microsoft/vscode\n"
  },
  {
    "path": ".node-version",
    "content": "22.22.0\n"
  },
  {
    "path": ".prettierignore",
    "content": "lib/vscode\nlib/vscode-reh-web-linux-x64\nrelease-standalone\nrelease-packages\nrelease\nhelm-chart\ntest/scripts\ntest/e2e/extensions/test-extension\n.pc\npackage-lock.json\n"
  },
  {
    "path": ".prettierrc.yaml",
    "content": "printWidth: 120\nsemi: false\ntrailingComma: all\narrowParens: always\nsingleQuote: false\nuseTabs: false\n"
  },
  {
    "path": ".tours/contributing.tour",
    "content": "{\n  \"$schema\": \"https://aka.ms/codetour-schema\",\n  \"title\": \"Contributing\",\n  \"steps\": [\n    {\n      \"directory\": \"src\",\n      \"line\": 1,\n      \"description\": \"Hello world! code-server's source code lives here in `src` (see the explorer). It's broadly arranged into browser code, Node code, and code shared between both.\"\n    },\n    {\n      \"file\": \"src/node/entry.ts\",\n      \"line\": 157,\n      \"description\": \"code-server begins execution here. CLI arguments are parsed, special flags like --help are handled, then the HTTP server is started.\"\n    },\n    {\n      \"file\": \"src/node/cli.ts\",\n      \"line\": 28,\n      \"description\": \"This describes all of the code-server CLI options and how they will be parsed.\"\n    },\n    {\n      \"file\": \"src/node/cli.ts\",\n      \"line\": 233,\n      \"description\": \"Here's the actual CLI parser.\"\n    },\n    {\n      \"file\": \"src/node/settings.ts\",\n      \"line\": 1,\n      \"description\": \"code-server maintains a settings file that is read and written here.\"\n    },\n    {\n      \"file\": \"src/node/app.ts\",\n      \"line\": 11,\n      \"description\": \"The core of code-server are HTTP and web socket servers which are created here. They provide authentication, file access, an API, and serve web-based applications like VS Code.\"\n    },\n    {\n      \"file\": \"src/node/wsRouter.ts\",\n      \"line\": 38,\n      \"description\": \"This is an analog to Express's Router that handles web socket routes.\"\n    },\n    {\n      \"file\": \"src/node/http.ts\",\n      \"line\": 1,\n      \"description\": \"This file provides various HTTP utility functions.\"\n    },\n    {\n      \"file\": \"src/node/coder_cloud.ts\",\n      \"line\": 9,\n      \"description\": \"The cloud agent spawned here provides the --link functionality.\"\n    },\n    {\n      \"file\": \"src/node/heart.ts\",\n      \"line\": 7,\n      \"description\": \"code-server's heart beats to indicate recent activity.\\n\\nAlso documented here: [https://github.com/coder/code-server/blob/main/docs/FAQ.md#heartbeat-file](https://github.com/coder/code-server/blob/main/docs/FAQ.md#heartbeat-file)\"\n    },\n    {\n      \"file\": \"src/node/socket.ts\",\n      \"line\": 13,\n      \"description\": \"We pass sockets to child processes, however we can't pass TLS sockets so when code-server is handling TLS (via --cert) we use this to create a proxy that can be passed to the child.\"\n    },\n    {\n      \"directory\": \"src/node/routes\",\n      \"line\": 1,\n      \"description\": \"code-server's routes live here in `src/node/routes` (see the explorer).\"\n    },\n    {\n      \"file\": \"src/node/routes/index.ts\",\n      \"line\": 123,\n      \"description\": \"The architecture of code-server allows it to be extended with applications via plugins. Each application is registered at its own route and handles requests at and below that route. Currently we have only VS Code (although it is not yet actually split out into a plugin).\"\n    },\n    {\n      \"file\": \"src/node/plugin.ts\",\n      \"line\": 103,\n      \"description\": \"The previously mentioned plugins are loaded here.\"\n    },\n    {\n      \"file\": \"src/node/routes/apps.ts\",\n      \"line\": 12,\n      \"description\": \"This provides a list of the applications registered with code-server.\"\n    },\n    {\n      \"file\": \"src/node/routes/domainProxy.ts\",\n      \"line\": 18,\n      \"description\": \"code-server provides a built-in proxy to help in developing web-based applications. This is the code for the domain-based proxy.\\n\\nAlso documented here: [https://github.com/coder/code-server/blob/main/docs/FAQ.md#how-do-i-securely-access-web-services](https://github.com/coder/code-server/blob/main/docs/FAQ.md#how-do-i-securely-access-web-services)\"\n    },\n    {\n      \"file\": \"src/node/routes/pathProxy.ts\",\n      \"line\": 19,\n      \"description\": \"Here is the path-based version of the proxy.\\n\\nAlso documented here: [https://github.com/coder/code-server/blob/main/docs/FAQ.md#how-do-i-securely-access-web-services](https://github.com/coder/code-server/blob/main/docs/FAQ.md#how-do-i-securely-access-web-services)\"\n    },\n    {\n      \"file\": \"src/node/proxy.ts\",\n      \"line\": 4,\n      \"description\": \"Both the domain and path proxy use the single proxy instance created here.\"\n    },\n    {\n      \"file\": \"src/node/routes/health.ts\",\n      \"line\": 5,\n      \"description\": \"A simple endpoint that lets you see if code-server is up.\\n\\nAlso documented here: [https://github.com/coder/code-server/blob/main/docs/FAQ.md#healthz-endpoint](https://github.com/coder/code-server/blob/main/docs/FAQ.md#healthz-endpoint)\"\n    },\n    {\n      \"file\": \"src/node/routes/login.ts\",\n      \"line\": 46,\n      \"description\": \"code-server supports a password-based login here.\"\n    },\n    {\n      \"file\": \"src/node/routes/static.ts\",\n      \"line\": 16,\n      \"description\": \"This serves static assets. Anything under the code-server directory can be fetched. Anything outside requires authentication.\"\n    },\n    {\n      \"file\": \"src/node/routes/update.ts\",\n      \"line\": 10,\n      \"description\": \"This endpoint lets you query for the latest code-server version. It's used to power the update popup you see in VS Code.\"\n    },\n    {\n      \"file\": \"src/node/routes/vscode.ts\",\n      \"line\": 15,\n      \"description\": \"This is the endpoint that serves VS Code's HTML, handles VS Code's websockets, and handles a few VS Code-specific endpoints for fetching static files.\"\n    },\n    {\n      \"file\": \"src/node/vscode.ts\",\n      \"line\": 13,\n      \"description\": \"The actual VS Code spawn and initialization is handled here. VS Code runs in a separate child process. We communicate via IPC and by passing it web sockets.\"\n    },\n    {\n      \"file\": \"src/browser/serviceWorker.ts\",\n      \"line\": 1,\n      \"description\": \"The service worker only exists to provide PWA functionality.\"\n    },\n    {\n      \"directory\": \"src/browser/pages\",\n      \"line\": 1,\n      \"description\": \"HTML, CSS, and JavaScript for each page lives in here `src/browser/pages` (see the explorer). Currently our HTML uses a simple search and replace template system with variables that {{LOOK_LIKE_THIS}}.\"\n    },\n    {\n      \"file\": \"src/browser/pages/vscode.html\",\n      \"line\": 1,\n      \"description\": \"The VS Code HTML is based off VS Code's own `workbench.html`.\"\n    },\n    {\n      \"directory\": \"src/browser/media\",\n      \"line\": 1,\n      \"description\": \"Static images and the manifest live here in `src/browser/media` (see the explorer).\"\n    },\n    {\n      \"directory\": \"lib/vscode\",\n      \"line\": 1,\n      \"description\": \"code-server makes use of VS Code's frontend web/remote support. Most of the modifications implement the remote server since that portion of the code is closed source and not released with VS Code.\\n\\nWe also have a few bug fixes and have added some features (like client-side extensions). See [https://github.com/coder/code-server/blob/main/docs/CONTRIBUTING.md#modifications-to-vs-code](https://github.com/coder/code-server/blob/main/docs/CONTRIBUTING.md#modifications-to-vs-code) for a list.\\n\\nWe make an effort to keep the modifications as few as possible.\"\n    }\n  ]\n}\n"
  },
  {
    "path": ".tours/start-development.tour",
    "content": "{\n  \"$schema\": \"https://aka.ms/codetour-schema\",\n  \"title\": \"Start Development\",\n  \"steps\": [\n    {\n      \"file\": \"package.json\",\n      \"line\": 31,\n      \"description\": \"## Commands\\n\\nTo start developing, make sure you have Node 16+ and the [required dependencies](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites) installed. Then, run the following commands:\\n\\n1. Install dependencies:\\n>> npm\\n\\n3. Start development mode (and watch for changes):\\n>> npm run watch\"\n    },\n    {\n      \"file\": \"src/node/app.ts\",\n      \"line\": 68,\n      \"description\": \"## Visit the web server\\n\\nIf all goes well, you should see something like this in your terminal. code-server should be live in development mode.\\n\\n---\\n```bash\\n[2020-12-09T21:03:37.156Z] info  code-server 3.7.4 development\\n[2020-12-09T21:03:37.157Z] info  Using user-data-dir ~/.local/share/code-server\\n[2020-12-09T21:03:37.165Z] info  Using config file ~/.config/code-server/config.yaml\\n[2020-12-09T21:03:37.165Z] info  HTTP server listening on http://127.0.0.1:8080 \\n[2020-12-09T21:03:37.165Z] info    - Authentication is enabled\\n[2020-12-09T21:03:37.165Z] info      - Using password from ~/.config/code-server/config.yaml\\n[2020-12-09T21:03:37.165Z] info    - Not serving HTTPS\\n```\\n\\n---\\n\\nIf you have the default configuration, you can access it at [http://localhost:8080](http://localhost:8080).\"\n    },\n    {\n      \"file\": \"src/browser/pages/login.html\",\n      \"line\": 26,\n      \"description\": \"## Make a change\\n\\nThis is the login page, let's make a change and see it update on our web server! Perhaps change the text :)\\n\\n```html\\n<div class=\\\"sub\\\">Modifying the login page 👨🏼‍💻</div>\\n```\\n\\nReminder, you can likely preview at [http://localhost:8080](http://localhost:8080)\"\n    },\n    {\n      \"file\": \"src/node/app.ts\",\n      \"line\": 62,\n      \"description\": \"## That's it!\\n\\n\\nThat's all there is to it! When this tour ends, your terminal session may stop, but just use `npm run watch` to start developing from here on out!\\n\\n\\nIf you haven't already, be sure to check out these resources:\\n- [Tour: Contributing](command:codetour.startTourByTitle?[\\\"Contributing\\\"])\\n- [Docs: FAQ.md](https://github.com/coder/code-server/blob/main/docs/FAQ.md)\\n- [Docs: CONTRIBUTING.md](https://github.com/coder/code-server/blob/main/docs/CONTRIBUTING.md)\\n- [Community: GitHub Discussions](https://github.com/coder/code-server/discussions)\\n- [Community: Slack](https://community.coder.com)\"\n    }\n  ]\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n<!-- Example:\n\n## [9.99.999] - 9090-09-09\n\nCode v99.99.999\n\n### Changed\n### Added\n### Deprecated\n### Removed\n### Fixed\n### Security\n\n-->\n\n## Unreleased\n\n## [4.109.5](https://github.com/coder/code-server/releases/tag/v4.109.5) - 2026-03-02\n\nCode v1.109.5\n\n### Changed\n\n- Update to Code 1.109.5\n\n## [4.109.2](https://github.com/coder/code-server/releases/tag/v4.109.2) - 2026-02-12\n\nCode v1.109.2\n\n### Changed\n\n- Update to Code 1.109.2\n\n## [4.109.0](https://github.com/coder/code-server/releases/tag/v4.109.0) - 2026-02-12\n\nCode v1.109.0\n\n### Changed\n\n- Update to Code 1.109.0\n\n## [4.108.2](https://github.com/coder/code-server/releases/tag/v4.108.2) - 2026-01-26\n\nCode v1.108.2\n\n### Changed\n\n- Update to Code 1.108.2\n\n## [4.108.1](https://github.com/coder/code-server/releases/tag/v4.108.1) - 2026-01-16\n\nCode v1.108.1\n\n### Changed\n\n- Update to Code 1.108.1\n\n## [4.108.0](https://github.com/coder/code-server/releases/tag/v4.108.0) - 2026-01-12\n\nCode v1.108.0\n\n### Changed\n\n- Update to Code 1.108.0\n\n## [4.107.1](https://github.com/coder/code-server/releases/tag/v4.107.1) - 2026-01-09\n\nCode v1.107.1\n\n### Changed\n\n- Update to Code 1.107.1\n\n## [4.107.0](https://github.com/coder/code-server/releases/tag/v4.107.0) - 2026-12-17\n\nCode v1.107.0\n\n### Changed\n\n- Update to Code 1.107.0\n\n### Added\n\n- New `--cookie-suffix` flag that can be used to add a suffix to the cookie when\n  using the built-in password authentication. You can use this to avoid\n  collisions with other instances of code-server.\n- Support a new property `authorizationHeaderToken` on the extension gallery\n  configuration. This will be added to marketplace requests as a bearer token\n  using the `Authorization` header.\n\n## [4.106.3](https://github.com/coder/code-server/releases/tag/v4.106.3) - 2025-12-01\n\nCode v1.106.3\n\n### Changed\n\n- Update to Code 1.106.3\n\n## [4.106.2](https://github.com/coder/code-server/releases/tag/v4.106.2) - 2025-11-19\n\nCode v1.106.2\n\n### Changed\n\n- Update to Code 1.106.2\n\n## [4.106.0](https://github.com/coder/code-server/releases/tag/v4.106.0) - 2025-11-19\n\nCode v1.106.0\n\n### Changed\n\n- Update to Code 1.106.0\n\n## [4.105.1](https://github.com/coder/code-server/releases/tag/v4.105.1) - 2025-10-20\n\nCode v1.105.1\n\n### Changed\n\n- Update to Code 1.105.1\n\n## [4.105.0](https://github.com/coder/code-server/releases/tag/v4.105.0) - 2025-10-17\n\nCode v1.105.0\n\n### Changed\n\n- Update to Code 1.105.0\n\n## [4.104.3](https://github.com/coder/code-server/releases/tag/v4.104.3) - 2025-10-07\n\nCode v1.104.3\n\n### Changed\n\n- Update to Code 1.104.3.\n\n## [4.104.2](https://github.com/coder/code-server/releases/tag/v4.104.2) - 2025-09-26\n\nCode v1.104.2\n\n### Changed\n\n- Update to Code 1.104.2.\n\n## [4.104.1](https://github.com/coder/code-server/releases/tag/v4.104.1) - 2025-09-19\n\nCode v1.104.1\n\n### Changed\n\n- Update to Code 1.104.1.\n\n## [4.104.0](https://github.com/coder/code-server/releases/tag/v4.104.0) - 2025-09-15\n\nCode v1.104.0\n\n### Fixed\n\n- Fix \"extension not found\" errors from Open VSX when trying to install the\n  latest version of an extension.\n\n### Changed\n\n- Update to Code 1.104.0.\n\n## [4.103.2](https://github.com/coder/code-server/releases/tag/v4.103.2) - 2025-08-25\n\nCode v1.103.2\n\n### Changed\n\n- Update to Code 1.103.2.\n\n## [4.103.1](https://github.com/coder/code-server/releases/tag/v4.103.1) - 2025-08-15\n\nCode v1.103.1\n\n### Changed\n\n- Update to Code 1.103.1.\n\n## [4.103.0](https://github.com/coder/code-server/releases/tag/v4.103.0) - 2025-08-12\n\nCode v1.103.0\n\n### Changed\n\n- Update to Code 1.103.0.\n\n## [4.102.2](https://github.com/coder/code-server/releases/tag/v4.102.2) - 2025-07-24\n\nCode v1.102.2\n\n### Changed\n\n- Update to Code 1.102.2.\n\n## [4.102.1](https://github.com/coder/code-server/releases/tag/v4.102.1) - 2025-07-17\n\nCode v1.102.1\n\n### Changed\n\n- Update to Code 1.102.1.\n\n## [4.102.0](https://github.com/coder/code-server/releases/tag/v4.102.0) - 2025-07-16\n\nCode v1.102.0\n\n### Changed\n\n- Update to Code 1.102.0.\n\n### Added\n\n- Custom strings can be configured using the `--i18n` flag set to a JSON\n  file. This can be used for either translation (and can be used alongside\n  `--locale`) or for customizing the strings. See\n  [./src/node/i18n/locales/en.json](./src/node/i18n/locales/en.json) for the\n  available keys.\n\n## [4.101.2](https://github.com/coder/code-server/releases/tag/v4.101.2) - 2025-06-25\n\nCode v1.101.2\n\n### Changed\n\n- Update to Code 1.101.2.\n\n### Fixed\n\n- Fix web views not loading due to 401 when requesting the service worker.\n\n## [4.101.1](https://github.com/coder/code-server/releases/tag/v4.101.1) - 2025-06-20\n\nCode v1.101.1\n\n### Changed\n\n- Update to Code 1.101.1.\n\n## [4.101.0](https://github.com/coder/code-server/releases/tag/v4.101.0) - 2025-06-20\n\nCode v1.101.0\n\n### Changed\n\n- Update to Code 1.101.0.\n\n## [4.100.3](https://github.com/coder/code-server/releases/tag/v4.100.3) - 2025-06-03\n\nCode v1.100.3\n\n### Changed\n\n- Update to Code 1.100.3.\n\n## [4.100.2](https://github.com/coder/code-server/releases/tag/v4.100.2) - 2025-05-15\n\nCode v1.100.2\n\n### Changed\n\n- Update to Code 1.100.2.\n\n## [4.100.1](https://github.com/coder/code-server/releases/tag/v4.100.1) - 2025-05-13\n\nCode v1.100.1\n\n### Changed\n\n- Update to Code 1.100.1.\n\n## [4.100.0](https://github.com/coder/code-server/releases/tag/v4.100.0) - 2025-05-12\n\nCode v1.100.0\n\n### Added\n\n- Trusted domains for links can now be set at run-time by configuring\n  `linkProtectionTrustedDomains` in the `lib/vscode/product.json` file or via\n  the `--link-protection-trusted-domains` flag.\n\n### Changed\n\n- Update to Code 1.100.0.\n- Disable extension signature verification, which previously was skipped by\n  default (the package used for verification is not available to OSS builds of\n  VS Code) but now reportedly throws hard errors making it impossible to install\n  extensions.\n\n### Fixed\n\n- Flags with repeatable options now work via the config file.\n\n## [4.99.4](https://github.com/coder/code-server/releases/tag/v4.99.4) - 2025-05-02\n\nCode v1.99.3\n\n### Security\n\n- Validate that ports in the path proxy are numbers, to prevent proxying to\n  arbitrary domains.\n\n## [4.99.3](https://github.com/coder/code-server/releases/tag/v4.99.3) - 2025-04-17\n\nCode v1.99.3\n\n### Added\n\n- Added `--skip-auth-preflight` flag to let preflight requests through the\n  proxy.\n\n### Changed\n\n- Update to Code 1.99.3.\n\n## [4.99.2](https://github.com/coder/code-server/releases/tag/v4.99.2) - 2025-04-10\n\nCode v1.99.2\n\n### Changed\n\n- Update to Code 1.99.2.\n\n## [4.99.1](https://github.com/coder/code-server/releases/tag/v4.99.1) - 2025-04-08\n\nCode v1.99.1\n\n### Changed\n\n- Update to Code 1.99.1.\n\n## [4.99.0](https://github.com/coder/code-server/releases/tag/v4.99.0) - 2025-04-07\n\nCode v1.99.0\n\n### Changed\n\n- Update to Code 1.99.0.\n\n## [4.98.0](https://github.com/coder/code-server/releases/tag/v4.98.0) - 2025-03-07\n\nCode v1.98.0\n\n### Changed\n\n- Update to Code 1.98.0.\n\n## [4.97.2](https://github.com/coder/code-server/releases/tag/v4.96.4) - 2025-02-18\n\nCode v1.97.2\n\n### Added\n\n- Added back macOS amd64 builds.\n\n### Changed\n\n- Update to Code 1.97.2.\n- Softened dark mode login page colors.\n\n## [4.96.4](https://github.com/coder/code-server/releases/tag/v4.96.4) - 2025-01-20\n\nCode v1.96.4\n\n### Changed\n\n- Update to Code 1.96.4.\n\n## [4.96.2](https://github.com/coder/code-server/releases/tag/v4.96.2) - 2024-12-20\n\nCode v1.96.2\n\n### Changed\n\n- Update to Code 1.96.2.\n\n## [4.96.1](https://github.com/coder/code-server/releases/tag/v4.96.1) - 2024-12-18\n\nCode v1.96.1\n\n### Added\n\n- Dark color scheme for login and error pages.\n\n### Changed\n\n- Update to Code 1.96.1.\n\n## [4.95.3](https://github.com/coder/code-server/releases/tag/v4.95.3) - 2024-11-18\n\nCode v1.95.3\n\n### Changed\n\n- Update to Code 1.95.3.\n\n## [4.95.2](https://github.com/coder/code-server/releases/tag/v4.95.2) - 2024-11-12\n\nCode v1.95.2\n\n### Changed\n\n- Update to Code 1.95.2.\n\n## [4.95.1](https://github.com/coder/code-server/releases/tag/v4.95.1) - 2024-11-06\n\nCode v1.95.1\n\n### Changed\n\n- Update to Code 1.95.1.\n\n## [4.93.1](https://github.com/coder/code-server/releases/tag/v4.93.1) - 2024-09-23\n\nCode v1.93.1\n\n### Changed\n\n- Updated to Code 1.93.1.\n\n### Added\n\n- Added `--abs-proxy-base-path` flag for when code-server is not at the root.\n\n## [4.92.2](https://github.com/coder/code-server/releases/tag/v4.92.2) - 2024-08-19\n\nCode v1.92.2\n\n### Breaking changes\n\n- Dropped a patch that changed the compile target from es2022 to es2020 because\n  it no longer works with the way VS Code uses static properties. This may break\n  older browsers, so those browsers will either have to be updated or use an\n  older version of code-server.\n\n### Changed\n\n- Updated to Code 1.92.2.\n\n## [4.91.0](https://github.com/coder/code-server/releases/tag/v4.91.0) - 2024-07-10\n\nCode v1.91.0\n\n### Changed\n\n- Updated to Code 1.91.0.\n\n## [4.90.3](https://github.com/coder/code-server/releases/tag/v4.90.3) - 2024-06-21\n\nCode v1.90.2\n\n### Changed\n\n- Updated to Code 1.90.2.\n\n### Fixed\n\n- When the log gets rotated it will no longer incorrectly be moved to a new\n  directory created in the current working directory named with a date.\n  Instead, the file itself is prepended with the date and kept in the same\n  directory, as originally intended.\n\n## [4.90.2](https://github.com/coder/code-server/releases/tag/v4.90.2) - 2024-06-14\n\nCode v1.90.1\n\n### Changed\n\n- Updated to Code 1.90.1.\n\n## [4.90.1](https://github.com/coder/code-server/releases/tag/v4.90.1) - 2024-06-12\n\nCode v1.90.0\n\n### Fixed\n\n- Cache a call to get CPU information used in telemetry that could result in a\n  lack responsiveness if it was particularly slow.\n\n## [4.90.0](https://github.com/coder/code-server/releases/tag/v4.90.0) - 2024-06-11\n\nCode v1.90.0\n\n### Changed\n\n- Updated to Code 1.90.0.\n- Updated Node to 20.11.1.\n\n### Added\n\n- Send contents to the clipboard in the integrated terminal by piping to\n  `code-server --stdin-to-clipboard` or `code-server -c`.\n\n  You may want to make this an alias:\n\n  ```\n  alias xclip=\"code-server --stdin-to-clipboard\"\n  echo -n \"hello world\" | xclip\n  ```\n\n## [4.89.1](https://github.com/coder/code-server/releases/tag/v4.89.1) - 2024-04-14\n\nCode v1.89.1\n\n### Changed\n\n- Updated to Code 1.89.1.\n\n## [4.89.0](https://github.com/coder/code-server/releases/tag/v4.89.0) - 2024-04-08\n\nCode v1.89.0\n\n### Changed\n\n- Updated to Code 1.89.0.\n\n## [4.23.1](https://github.com/coder/code-server/releases/tag/v4.23.1) - 2024-04-15\n\nCode v1.88.1\n\n### Changed\n\n- Updated to Code 1.88.1.\n\n## [4.23.0](https://github.com/coder/code-server/releases/tag/v4.23.0) - 2024-04-08\n\nCode v1.88.0\n\n### Changed\n\n- Updated to Code 1.88.0.\n- Updated Node to 18.18.2.\n\n### Fixed\n\n- Fix masking the exit code when failing to install extensions on the command\n  line outside the integrated terminal. Installing extensions inside the\n  integrated terminal still masks the exit code and is an upstream bug.\n\n## [4.22.1](https://github.com/coder/code-server/releases/tag/v4.22.1) - 2024-03-14\n\nCode v1.87.2\n\n### Changed\n\n- Updated to Code 1.87.2.\n- Enable keep-alive for proxy agent.\n\n## [4.22.0](https://github.com/coder/code-server/releases/tag/v4.22.0) - 2024-03-03\n\nCode v1.87.0\n\n### Changed\n\n- Updated to Code 1.87.0.\n\n## [4.21.2](https://github.com/coder/code-server/releases/tag/v4.21.2) - 2024-02-28\n\nCode v1.86.2\n\n### Changed\n\n- Updated to Code 1.86.2.\n\n## [4.21.1](https://github.com/coder/code-server/releases/tag/v4.21.1) - 2024-02-09\n\nCode v1.86.1\n\n### Changed\n\n- Updated to Code 1.86.1.\n- Updated to Node 18.17.1.\n\n### Added\n\n- Docker images for Fedora and openSUSE.\n\n## [4.21.0](https://github.com/coder/code-server/releases/tag/v4.21.0) - 2024-02-05\n\nCode v1.86.0\n\n### Changed\n\n- Updated to Code 1.86.0.\n\n## [4.20.1](https://github.com/coder/code-server/releases/tag/v4.20.1) - 2024-01-22\n\nCode v1.85.2\n\n### Changed\n\n- Updated to Code 1.85.2.\n\n### Fixed\n\n- Query variables are no longer double-encoded when going over the path proxy.\n\n## [4.20.0](https://github.com/coder/code-server/releases/tag/v4.20.0) - 2023-12-21\n\nCode v1.85.1\n\n### Added\n\n- New flag `--disable-file-uploads` to disable uploading files to the remote by\n  drag and drop and to disable opening local files via the \"show local\" button\n  in the file open prompt. Note that you can still open local files by drag and\n  dropping the file onto the editor pane.\n- Added `wget` to the release image.\n\n### Changed\n\n- Updated to Code 1.85.1.\n- The `--disable-file-downloads` flag will now disable the \"show local\" button\n  in the file save prompt as well.\n- Debian release image updated to use Bookworm.\n\n## [4.19.1](https://github.com/coder/code-server/releases/tag/v4.19.1) - 2023-11-29\n\nCode v1.84.2\n\n### Fixed\n\n- Fixed an issue where parts of the editor would not load (like the file\n  explorer, source control, etc) when using a workspace file.\n\n## [4.19.0](https://github.com/coder/code-server/releases/tag/v4.19.0) - 2023-11-18\n\nCode v1.84.2\n\n### Changed\n\n- Updated to Code 1.84.2.\n\n## [4.18.0](https://github.com/coder/code-server/releases/tag/v4.18.0) - 2023-10-20\n\nCode v1.83.1\n\n### Changed\n\n- Updated to Code 1.83.1.\n\n## [4.17.1](https://github.com/coder/code-server/releases/tag/v4.17.1) - 2023-09-29\n\nCode v1.82.2\n\n### Fixed\n\n- Make secret storage persistent. For example, logging in with GitHub should\n  persist between browser refreshes and code-server restarts.\n- Issues with argon2 on arm builds should be fixed now.\n\n## [4.17.0](https://github.com/coder/code-server/releases/tag/v4.17.0) - 2023-09-22\n\nCode v1.82.2\n\n### Added\n\n- Japanese locale.\n- `CODE_SERVER_HOST` environment variable.\n\n### Changed\n\n- Update to Code 1.82.2. This includes an update to Node 18, which also means\n  that the minimum glibc is now 2.28. If you need to maintain a lower glibc then\n  you can take a version of Node 18 that is compiled with a lower glibc and use\n  that to build code-server (or at a minimum rebuild the native modules).\n- Display paths to config files in full rather than abbreviated. If you have\n  trouble with the password not working please update and make sure the\n  displayed config paths are what you expect.\n\n### Fixed\n\n- Fix some dependency issues for the standalone arm64 and armv7l releases. If\n  you had issues with missing or failing modules please try these new builds.\n\n## [4.16.1](https://github.com/coder/code-server/releases/tag/v4.16.1) - 2023-07-31\n\nCode v1.80.2\n\n### Changed\n\n- Updated to Code 1.80.2.\n\n## [4.16.0](https://github.com/coder/code-server/releases/tag/v4.16.0) - 2023-07-28\n\nCode v1.80.1\n\n### Added\n\n- `--disable-proxy` flag. This disables the domain and path proxies but it does\n  not disable the ports panel in Code. That can be disabled by using\n  `remote.autoForwardPorts=false` in your settings.\n\n## [4.15.0](https://github.com/coder/code-server/releases/tag/v4.15.0) - 2023-07-21\n\nCode v1.80.1\n\n### Changed\n\n- Updated to Code 1.80.1.\n\n### Added\n\n- `--trusted-origin` flag for specifying origins that you trust but do not\n  control (for example a reverse proxy).\n\nCode v1.79.2\n\n## [4.14.1](https://github.com/coder/code-server/releases/tag/v4.14.1) - 2023-06-26\n\nCode v1.79.2\n\n### Security\n\n- Remove extra write permissions on the Node binary bundled with the linux-amd64\n  tarball. If you extract the tar without a umask this could mean the Node\n  binary would be unexpectedly writable.\n\n### Fixed\n\n- Inability to launch multiple instances of code-server for different users.\n\n### Added\n\n- `--session-socket` CLI flag to configure the location of the session socket.\n  By default it will be placed in `<user data dir>/code-server-ipc.sock`.\n\n## [4.14.0](https://github.com/coder/code-server/releases/tag/v4.14.0) - 2023-06-16\n\nCode v1.79.2\n\n### Added\n\n- `--domain-proxy` now supports `{{port}}` and `{{host}}` template variables.\n\n### Changed\n\n- Updated to Code 1.79.2\n- Files opened from an external terminal will now open in the most closely\n  related window rather than in the last opened window.\n\n## [4.13.0](https://github.com/coder/code-server/releases/tag/v4.13.0) - 2023-05-19\n\nCode v1.78.2\n\n### Changed\n\n- Updated to Code 1.78.2.\n\n### Fixed\n\n- Proxying files that contain non-ASCII characters.\n- Origin check when X-Forwarded-Host contains comma-separated hosts.\n\n## [4.12.0](https://github.com/coder/code-server/releases/tag/v4.12.0) - 2023-04-21\n\nCode v1.77.3\n\n### Changed\n\n- Updated to Code 1.77.3\n- Ports panel will use domain-based proxy (instead of the default path-based\n  proxy) when set via --proxy-domain.\n- Apply --app-name to the PWA title.\n\n### Added\n\n- Thai translation for login page.\n- Debug logs around the origin security check. If you are getting forbidden\n  errors on web sockets please run code-server with `--log debug` to see why the\n  requests are being blocked.\n\n## [4.11.0](https://github.com/coder/code-server/releases/tag/v4.11.0) - 2023-03-16\n\nCode v1.76.1\n\n### Changed\n\n- Updated to Code 1.76.1\n\n## [4.10.1](https://github.com/coder/code-server/releases/tag/v4.10.1) - 2023-03-04\n\nCode v1.75.1\n\n### Security\n\nAdded an origin check to web sockets to prevent cross-site hijacking attacks on\nusers using older or niche browser that do not support SameSite cookies and\nattacks across sub-domains that share the same root domain.\n\nThe check requires the host header to be set so if you use a reverse proxy\nensure it forwards that information otherwise web sockets will be blocked.\n\n## [4.10.0](https://github.com/coder/code-server/releases/tag/v4.10.0) - 2023-02-15\n\nCode v1.75.1\n\n### Changed\n\n- Updated to Code 1.75.1\n\n### Removed\n\n- Removed `--link` (was deprecated over thirteen months ago in 4.0.1).\n\n## [4.9.1](https://github.com/coder/code-server/releases/tag/v4.9.1) - 2022-12-15\n\nCode v1.73.1\n\n### Changed\n\n- Updated a couple steps in the build and release process to ensure we're using\n  `npm` and `yarn` consistently depending on the step.\n\n### Fixed\n\n- Fixed an issue with code-server version not displaying in the Help > About window.\n- Fixed terminal not loading on macOS clients.\n\n## [4.9.0](https://github.com/coder/code-server/releases/tag/v4.9.0) - 2022-12-06\n\nCode v1.73.1\n\n### Changed\n\n- Upgraded to Code 1.73.1\n\n### Added\n\n- `/security.txt` added as a route with info on our security policy information thanks to @ghuntley\n\n### Fixed\n\n- Installing on majaro images should now work thanks to @MrPeacockNLB for\n  adding the `--noconfirm` flag in `install.sh`\n\n### Known Issues\n\n- `--cert` on Ubuntu 22.04: OpenSSL v3 is used which breaks `pem` meaning the\n  `--cert` feature will not work. [Reference](https://github.com/adobe/fetch/pull/318#issuecomment-1306070259)\n\n## [4.8.3](https://github.com/coder/code-server/releases/tag/v4.8.3) - 2022-11-07\n\nCode v1.72.1\n\n### Added\n\n- install script now supports arch-like (i.e. manjaro, endeavourous, etc.)\n  architectures\n\n### Changed\n\n- Updated text in the Getting Started page.\n\n## [4.8.2](https://github.com/coder/code-server/releases/tag/v4.8.2) - 2022-11-02\n\nCode v1.72.1\n\n### Added\n\n- New text in the Getting Started page with info about\n  `coder/coder`. This is enabled by default but can be disabled by passing the CLI\n  flag `--disable-getting-started-override` or setting\n  `CS_DISABLE_GETTING_STARTED_OVERRIDE=1` or\n  `CS_DISABLE_GETTING_STARTED_OVERRIDE=true`.\n\n## [4.8.1](https://github.com/coder/code-server/releases/tag/v4.8.1) - 2022-10-28\n\nCode v1.72.1\n\n### Fixed\n\n- Fixed CSP error introduced in 4.8.0 that caused issues with webviews and most\n  extensions.\n\n## [4.8.0](https://github.com/coder/code-server/releases/tag/v4.8.0) - 2022-10-24\n\nCode v1.72.1\n\n### Added\n\n- Support for the Ports panel which leverages code-server's built-in proxy. It\n  also uses `VSCODE_PROXY_URI` where `{{port}}` is replace when forwarding a port.\n  Example: `VSCODE_PROXY_URI=https://{{port}}.kyle.dev` would forward an\n  application running on localhost:3000 to https://3000.kyle.dev\n- Support for `--disable-workspace-trust` CLI flag\n- Support for `--goto` flag to open file @ line:column\n- Added Ubuntu-based images for Docker releases. If you run into issues with\n  `PATH` being overwritten in Docker please try the Ubuntu image as this is a\n  problem in the Debian base image.\n\n### Changed\n\n- Updated Code to 1.72.1\n\n### Fixed\n\n- Enabled `BROWSER` environment variable\n- Patched `asExternalUri` to work so now extensions run inside code-server can use it\n\n## [4.7.1](https://github.com/coder/code-server/releases/tag/v4.7.1) - 2022-09-30\n\nCode v1.71.2\n\n### Changed\n\n- Updated Code to 1.71.2\n\n### Fixed\n\n- Fixed install script not upgrading code-server when already installed on RPM-based machines\n- Fixed install script failing to gain root permissions on FreeBSD\n\n## [4.7.0](https://github.com/coder/code-server/releases/tag/v4.7.0) - 2022-09-09\n\nCode v1.71.0\n\n### Changed\n\n- Updated Code to 1.71.0\n\n### Removed\n\n- Dropped heartbeat patch because it was implemented upstream\n\n### Fixed\n\n- Add flags --unsafe-perm --legacy-peer-deps in `npm-postinstall.sh` which ensures installing with npm works correctly\n\n## [4.6.1](https://github.com/coder/code-server/releases/tag/v4.6.1) - 2022-09-31\n\nCode v1.70.2\n\n### Changed\n\n- Updated Code to 1.70.2\n- Updated `argon2` to 0.29.0 which should fix issues on FreeBSD\n- Updated docs to suggest using `npm` instead of `yarn`\n\n### Removed\n\n- Dropped database migration patch affected to 4.0.2 versions and earlier.\n\n### Fixed\n\n- Fixed preservation of `process.execArgv` which means you can pass `--prof` to profile code-server\n\n## [4.6.0](https://github.com/coder/code-server/releases/tag/v4.6.0) - 2022-08-17\n\nCode v1.70.1\n\n### Changed\n\n- Updated Code to 1.70.1.\n\n### Added\n\n- Added a heartbeat to sockets. This should prevent them from getting closed by\n  reverse proxy timeouts when idle like NGINX's default 60-second timeout.\n\n### Fixed\n\n- Fixed logout option appearing even when authentication is disabled.\n\n## [4.5.2](https://github.com/coder/code-server/releases/tag/v4.5.2) - 2022-08-15\n\nCode v1.68.1\n\n### Security\n\n- Fixed the proxy route not performing authentication. For example if you were\n  to run a development HTTP server using `python -m http.server 8000` then it\n  would be accessible at `my.domain/proxy/8000/` without any authentication.\n\n  If all of the following apply to you please update as soon as possible:\n  - You run code-server with the built-in password authentication.\n  - You run unprotected HTTP services on ports accessible by code-server.\n\n### Changed\n\n- Invoking `code-server` in the integrated terminal will now use the script that\n  comes with upstream Code. This means flags like `--wait` will be\n  automatically supported now. However the upstream script only has the ability\n  to interact with the running code-server and cannot spawn new instances. If\n  you need to spawn a new code-server from the integrated terminal please\n  specify the full path to code-server's usual script (for example\n  `/usr/bin/code-server`).\n\n### Fixed\n\n- Invoking `code-server` in the integrated terminal will now work instead of\n  erroring about not finding Node.\n\n## [4.5.1](https://github.com/coder/code-server/releases/tag/v4.5.1) - 2022-07-18\n\nCode v1.68.1\n\n### Changed\n\n- We now use `release/v<0.0.0>` for the release branch name so it doesn't\n  conflict with the tag name\n- Added `.prettierignore` to ignore formatting files in `lib/vscode`\n\n### Added\n\n- Allow more comprehensive affinity config in Helm chart\n- Added custom message in Homebrew PR to make sure code-server maintainers are\n  tagged\n- Allow setting `priorityClassName` via Helm chart\n- Added troubleshooting docs to `CONTRIBUTING.md`\n\n### Fixed\n\n- Removed default memory limit which was set via `NODE_OPTIONS`\n- Changed output in pipe to make it easier to debug code-server when doing live\n  edits\n- Fixed display-language patch to use correct path which broke in 4.5.0\n- Fixed multiple code-server windows opening when using the code-server CLI in\n  the Integrated Terminal\n- Fixed Integrated Terminal not working when web base was not the root path\n\n### Security\n\n- Updated `glob-parent` version in dependencies\n\n## [4.5.0](https://github.com/coder/code-server/releases/tag/v4.5.0) - 2022-06-29\n\nCode v1.68.1\n\n### Changed\n\n- Updated codecov to use codecov uploader\n- Moved integration tests to Jest\n- Fixed docker release to only download .deb\n- Upgraded to Code 1.68.1\n- Install `nfpm` from GitHub\n- Upgraded to TypeScript 4.6\n\n### Added\n\n- Added tests for `open`, `isWsl`, `handlePasswordValidation`\n- Provided alternate image registry to dockerhub\n- Allowed users to have scripts run on container with `ENTRYPOINTD` environment\n  variable\n\n### Fixed\n\n- Fixed open CLI command to work on macOS\n\n## [4.4.0](https://github.com/coder/code-server/releases/tag/v4.4.0) - 2022-05-06\n\nCode v1.66.2\n\n### Changed\n\n- Refactored methods in `Heart` class and made `Heart.beat()` async to make\n  testing easier.\n- Upgraded to Code 1.66.2.\n\n### Added\n\n- Added back telemetry patch which was removed in the Code reachitecture.\n- Added support to use `true` for `CS_DISABLE_FILE_DOWNLOADS` environment\n  variable. This means you can disable file downloads by setting\n  `CS_DISABLE_FILE_DOWNLOADS` to `true` or `1`.\n- Added tests for `Heart` class.\n\n### Fixed\n\n- Fixed installation issue in AUR after LICENSE rename.\n- Fixed issue with listening on IPv6 addresses.\n- Fixed issue with Docker publish action not being able to find artifacts. Now\n  it downloads the release assets from the release.\n\n## [4.3.0](https://github.com/coder/code-server/releases/tag/v4.3.0) - 2022-04-14\n\nCode v1.65.2\n\n### Changed\n\n- Excluded .deb files from release Docker image which drops the compressed and\n  uncompressed size by 58% and 34%.\n- Upgraded to Code 1.65.2.\n\n### Added\n\n- Added a new CLI flag called `--disable-file-downloads` which allows you to\n  disable the \"Download...\" option that shows in the UI when right-clicking on a\n  file. This can also set by running `CS_DISABLE_FILE_DOWNLOADS=1`.\n- Aligned the dependencies for binary and npm release artifacts.\n\n### Fixed\n\n- Fixed the code-server version from not displaying in the Help > About dialog.\n- Fixed issues with the TypeScript and JavaScript Language Features Extension\n  failing to activate.\n- Fixed missing files in ipynb extension.\n- Fixed the homebrew release workflow.\n- Fixed the Docker release workflow from not always publishing version tags.\n\n## [4.2.0](https://github.com/coder/code-server/releases/tag/v4.2.0) - 2022-03-22\n\nCode v1.64.2\n\n### Added\n\n- Added tests for `handleArgsSocketCatchError`, `setDefaults` and\n  `optionDescriptions`.\n\n### Changed\n\n- We switched from using the fork `coder/vscode` to a submodule of\n  `microsoft/vscode` + patches managed by `quilt` for how Code sits inside the\n  code-server codebase.\n- Upgraded to Code 1.64.2.\n\n### Fixed\n\n- Update popup notification through `--disable-update-check` is now fixed.\n- Fixed PWA icons not loading on iPad\n- Fixed the homebrew release process. Our `cdrci` bot should now automatically\n  update the version as part of the release pipeline.\n- Fixed titleBar color setting being ignored in PWA.\n\n### Security\n\n- Updated to `minimist-list`.\n- Updated `cloud-agent` to `v0.2.4` which uses `nhooyr.io/webscoket` `v1.8.7`.\n\n## [4.1.0](https://github.com/coder/code-server/releases/tag/v4.1.0) - 2022-03-03\n\nCode v1.63.0\n\n### Added\n\n- Support for injecting GitHub token into Code so extensions can make use of it.\n  This can be done with the `GITHUB_TOKEN` environment variable or `github-auth`\n  in the config file.\n- New flag `--socket-mode` allows setting the mode (file permissions) of the\n  socket created when using `--socket`.\n- The version of Code bundled with code-server now appears when using the\n  `--version` flag. For example: `4.0.2 5cdfe74686aa73e023f8354a9a6014eb30caa7dd with Code 1.63.0`.\n  If you have been parsing this flag for the version you might want to use\n  `--version --json` instead as doing that will be more stable.\n\n### Changed\n\n- The workspace or folder passed on the CLI will now use the same redirect\n  method that the last opened workspace or folder uses. This means if you use\n  something like `code-server /path/to/dir` you will now get a query parameter\n  added (like so: `my-domain.tld?folder=/path/to/dir`), making it easier to edit\n  by hand and making it consistent with the last opened and menu open behaviors.\n- The folder/workspace query parameter no longer has encoded slashes, making\n  them more readable and editable by hand. This was only affecting the last\n  opened behavior, not opens from the menu.\n\n### Fixed\n\n- Fix web sockets not connecting when using `--cert`.\n- Prevent workspace state collisions when opening a workspace that shares the\n  same file path with another workspace on a different machine that shares the\n  same domain. This was causing files opened in one workspace to be \"re-\"opened\n  in the other workspace when the other workspace is opened.\n- Pin the Express version which should make installing from npm work again.\n- Propagate signals to code-server in the Docker image which means it should\n  stop more quickly and gracefully.\n- Fix missing argon binaries in the standalone releases on arm machines.\n\n## [4.0.2](https://github.com/coder/code-server/releases/tag/v4.0.2) - 2022-01-27\n\nCode v1.63.0\n\n### Fixed\n\n- Unset the `BROWSER` environment variable. This fixes applications that hard\n  exit when trying to spawn the helper script `BROWSER` points to because the\n  file is missing. While we do include the script now we are leaving the\n  variable omitted because the script does not work yet.\n\n## [4.0.1](https://github.com/coder/code-server/releases/tag/v4.0.1) - 2022-01-04\n\nCode v1.63.0\n\ncode-server has been rebased on upstream's newly open-sourced server\nimplementation (#4414).\n\n### Changed\n\n- Web socket compression has been made the default (when supported). This means\n  the `--enable` flag will no longer take `permessage-deflate` as an option.\n- The static endpoint can no longer reach outside code-server. However the\n  vscode-remote-resource endpoint still can.\n- OpenVSX has been made the default marketplace.\n- The last opened folder/workspace is no longer stored separately in the\n  settings file (we rely on the already-existing query object instead).\n- The marketplace override environment variables `SERVICE_URL` and `ITEM_URL`\n  have been replaced with a single `EXTENSIONS_GALLERY` variable that\n  corresponds to `extensionsGallery` in Code's `product.json`.\n\n### Added\n\n- `VSCODE_PROXY_URI` env var for use in the terminal and extensions.\n\n### Removed\n\n- Extra extension directories have been removed. The `--extra-extensions-dir`\n  and `--extra-builtin-extensions-dir` flags will no longer be accepted.\n- The `--install-source` flag has been removed.\n\n### Deprecated\n\n- `--link` is now deprecated (#4562).\n\n### Security\n\n- We fixed a XSS vulnerability by escaping HTML from messages in the error page (#4430).\n\n## [3.12.0](https://github.com/coder/code-server/releases/tag/v3.12.0) - 2021-09-15\n\nCode v1.60.0\n\n### Changed\n\n- Upgrade Code to 1.60.0.\n\n### Fixed\n\n- Fix logout when using a base path (#3608).\n\n## [3.11.1](https://github.com/coder/code-server/releases/tag/v3.11.1) - 2021-08-06\n\nUndocumented (see releases page).\n\n## [3.11.0](https://github.com/coder/code-server/releases/tag/v3.11.0) - 2021-06-14\n\nUndocumented (see releases page).\n\n## [3.10.2](https://github.com/coder/code-server/releases/tag/v3.10.2) - 2021-05-21\n\nCode v1.56.1\n\n### Added\n\n- Support `extraInitContainers` in helm chart values (#3393).\n\n### Changed\n\n- Change `extraContainers` to support templating in helm chart (#3393).\n\n### Fixed\n\n- Fix \"Open Folder\" on welcome page (#3437).\n\n## [3.10.1](https://github.com/coder/code-server/releases/tag/v3.10.1) - 2021-05-17\n\nCode v1.56.1\n\n### Fixed\n\n- Check the logged user instead of $USER (#3330).\n- Fix broken node_modules.asar symlink in npm package (#3355).\n- Update cloud agent to fix version issue (#3342).\n\n### Changed\n\n- Use xdgBasedir.runtime instead of tmp (#3304).\n\n## [3.10.0](https://github.com/coder/code-server/releases/tag/v3.10.0) - 2021-05-10\n\nCode v1.56.0\n\n### Changed\n\n- Update to Code 1.56.0 (#3269).\n- Minor connections refactor (#3178). Improves connection stability.\n- Use ptyHostService (#3308). This brings us closer to upstream Code.\n\n### Added\n\n- Add flag for toggling permessage-deflate (#3286). The default is off so\n  compression will no longer be used by default. Use the --enable flag to\n  toggle it back on.\n\n### Fixed\n\n- Make rate limiter not count against successful logins (#3141).\n- Refactor logout (#3277). This fixes logging out in some scenarios.\n- Make sure directories exist (#3309). This fixes some errors on startup.\n\n### Security\n\n- Update dependencies with CVEs (#3223).\n\n## Previous versions\n\nThis was added with `3.10.0`, which means any previous versions are not\ndocumented in the changelog.\n\nTo see those, please visit the [Releases page](https://github.com/coder/code-server/releases).\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License\n\nCopyright (c) 2019 Coder Technologies Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "ThirdPartyNotices.txt",
    "content": "code-server\n\nTHIRD-PARTY SOFTWARE NOTICES AND INFORMATION\nDo Not Translate or Localize\n\n1.\tMicrosoft/vscode version 1.47.0 (https://github.com/Microsoft/vscode)\n\n%% Microsoft/vscode NOTICES AND INFORMATION BEGIN HERE\n=========================================\nMIT License \n\n\nCopyright (c) 2015 - present Microsoft Corporation \n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: \n\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. \n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  "
  },
  {
    "path": "ci/Caddyfile",
    "content": "{\n\tadmin    localhost:4444\n}\n:8000 {\n\t@portLocalhost path_regexp port ^/([0-9]+)\\/ide\n        handle @portLocalhost {\n\t\turi strip_prefix {re.port.1}/ide\n                reverse_proxy localhost:{re.port.1}\n        }\n\n\thandle {\n                respond \"Bad hostname\" 400\n        }\n\n}\n"
  },
  {
    "path": "ci/README.md",
    "content": "# ci\n\nThis directory contains scripts used for code-server's continuous integration infrastructure.\n\nSome of these scripts contain more detailed documentation and options\nin header comments.\n\nAny file or directory in this subdirectory should be documented here.\n\n- [./ci/lib.sh](./lib.sh)\n  - Contains code duplicated across these scripts.\n\n## dev\n\nThis directory contains scripts used for the development of code-server.\n\n- [./ci/dev/image](./dev/image)\n  - See [./docs/CONTRIBUTING.md](../docs/CONTRIBUTING.md) for docs on the development container.\n- [./ci/dev/fmt.sh](./dev/fmt.sh) (`npm run fmt`)\n  - Runs formatters.\n- [./ci/dev/lint.sh](./dev/lint.sh) (`npm run lint`)\n  - Runs linters.\n- [./ci/dev/test-unit.sh](./dev/test-unit.sh) (`npm run test:unit`)\n  - Runs unit tests.\n- [./ci/dev/test-e2e.sh](./dev/test-e2e.sh) (`npm run test:e2e`)\n  - Runs end-to-end tests.\n- [./ci/dev/watch.ts](./dev/watch.ts) (`npm run watch`)\n  - Starts a process to build and launch code-server and restart on any code changes.\n  - Example usage in [./docs/CONTRIBUTING.md](../docs/CONTRIBUTING.md).\n- [./ci/dev/gen_icons.sh](./dev/gen_icons.sh) (`npm run icons`)\n  - Generates the various icons from a single `.svg` favicon in\n    `src/browser/media/favicon.svg`.\n  - Requires [imagemagick](https://imagemagick.org/index.php)\n\n## build\n\nThis directory contains the scripts used to build and release code-server.\nYou can disable minification by setting `MINIFY=`.\n\n- [./ci/build/build-code-server.sh](./build/build-code-server.sh) (`npm run build`)\n  - Builds code-server into `./out` and bundles the frontend into `./dist`.\n- [./ci/build/build-vscode.sh](./build/build-vscode.sh) (`npm run build:vscode`)\n  - Builds vscode into `./lib/vscode/out-vscode`.\n- [./ci/build/build-release.sh](./build/build-release.sh) (`npm run release`)\n  - Bundles the output of the above two scripts into a single node module at `./release`.\n- [./ci/build/clean.sh](./build/clean.sh) (`npm run clean`)\n  - Removes all build artifacts.\n  - Useful to do a clean build.\n- [./ci/build/code-server.sh](./build/code-server.sh)\n  - Copied into standalone releases to run code-server with the bundled node binary.\n- [./ci/build/test-standalone-release.sh](./build/test-standalone-release.sh) (`npm run test:standalone-release`)\n  - Ensures code-server in the `./release-standalone` directory works by installing an extension.\n- [./ci/build/build-packages.sh](./build/build-packages.sh) (`npm run package`)\n  - Packages `./release-standalone` into a `.tar.gz` archive in `./release-packages`.\n  - If on linux, [nfpm](https://github.com/goreleaser/nfpm) is used to generate `.deb` and `.rpm`.\n- [./ci/build/nfpm.yaml](./build/nfpm.yaml)\n  - Used to configure [nfpm](https://github.com/goreleaser/nfpm) to generate `.deb` and `.rpm`.\n- [./ci/build/code-server-nfpm.sh](./build/code-server-nfpm.sh)\n  - Entrypoint script for code-server for `.deb` and `.rpm`.\n- [./ci/build/code-server.service](./build/code-server.service)\n  - systemd user service packaged into the `.deb` and `.rpm`.\n- [./ci/build/release-github-draft.sh](./build/release-github-draft.sh) (`npm run release:github-draft`)\n  - Uses [gh](https://github.com/cli/cli) to create a draft release with a template description.\n- [./ci/build/release-github-assets.sh](./build/release-github-assets.sh) (`npm run release:github-assets`)\n  - Downloads the release-package artifacts for the current commit from CI.\n  - Uses [gh](https://github.com/cli/cli) to upload the artifacts to the release\n    specified in `package.json`.\n- [./ci/build/npm-postinstall.sh](./build/npm-postinstall.sh)\n  - Post install script for the npm package.\n  - Bundled by`npm run release`.\n\n## release-image\n\nThis directory contains the release docker container image.\n\n- [./ci/steps/build-docker-buildx-push.sh](./steps/docker-buildx-push.sh)\n  - Builds the release containers with tags `codercom/code-server-$ARCH:$VERSION` for amd64 and arm64 with `docker buildx` and pushes them.\n  - Assumes debian releases are ready in `./release-packages`.\n\n## images\n\nThis directory contains the images for CI.\n\n## steps\n\nThis directory contains the scripts used in CI.\nHelps avoid clobbering the CI configuration.\n\n- [./steps/fmt.sh](./steps/fmt.sh)\n  - Runs `npm run fmt`.\n- [./steps/lint.sh](./steps/lint.sh)\n  - Runs `npm run lint`.\n- [./steps/test-unit.sh](./steps/test-unit.sh)\n  - Runs `npm run test:unit`.\n- [./steps/test-integration.sh](./steps/test-integration.sh)\n  - Runs `npm run test:integration`.\n- [./steps/test-e2e.sh](./steps/test-e2e.sh)\n  - Runs `npm run test:e2e`.\n- [./steps/release.sh](./steps/release.sh)\n  - Runs the release process.\n  - Generates the npm package at `./release`.\n- [./steps/release-packages.sh](./steps/release-packages.sh)\n  - Takes the output of the previous script and generates a standalone release and\n    release packages into `./release-packages`.\n- [./steps/publish-npm.sh](./steps/publish-npm.sh)\n  - Grabs the `npm-package` release artifact for the current commit and publishes it on npm.\n- [./steps/docker-buildx-push.sh](./steps/docker-buildx-push.sh)\n  - Builds the docker image and then pushes it.\n- [./steps/push-docker-manifest.sh](./steps/push-docker-manifest.sh)\n  - Loads all images in `./release-images` and then builds and pushes a multi architecture\n    docker manifest for the amd64 and arm64 images to `codercom/code-server:$VERSION` and\n    `codercom/code-server:latest`.\n"
  },
  {
    "path": "ci/build/build-code-server.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Builds code-server into out and the frontend into dist.\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n\n  tsc\n\n  # If out/node/entry.js does not already have the shebang,\n  # we make sure to add it and make it executable.\n  if ! grep -q -m1 \"^#!/usr/bin/env node\" out/node/entry.js; then\n    sed -i.bak \"1s;^;#!/usr/bin/env node\\n;\" out/node/entry.js && rm out/node/entry.js.bak\n    chmod +x out/node/entry.js\n  fi\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/build-lib.sh",
    "content": "#!/usr/bin/env bash\n\n# This is a library which contains functions used inside ci/build\n#\n# We separated it into it's own file so that we could easily unit test\n# these functions and helpers.\n\n# On some CPU architectures (notably node/uname \"armv7l\", default on Raspberry Pis),\n# different package managers have different labels for the same CPU (deb=armhf, rpm=armhfp).\n# This function returns the overriden arch on platforms\n# with alternate labels, or the same arch otherwise.\nget_nfpm_arch() {\n  local PKG_FORMAT=\"${1:-}\"\n  local ARCH=\"${2:-}\"\n\n  case \"$ARCH\" in\n    armv7l)\n      if [ \"$PKG_FORMAT\" = \"deb\" ]; then\n        echo armhf\n      elif [ \"$PKG_FORMAT\" = \"rpm\" ]; then\n        echo armhfp\n      fi\n      ;;\n    *)\n      echo \"$ARCH\"\n      ;;\n  esac\n}\n"
  },
  {
    "path": "ci/build/build-packages.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Given a platform-specific release found in ./release-standalone, generate an\n# compressed archives and bundles (as appropriate for the platform) named after\n# the platform's architecture and OS and place them in ./release-packages and\n# ./release-gcp.\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n  source ./ci/lib.sh\n  source ./ci/build/build-lib.sh\n\n  # Allow us to override architecture\n  # we use this for our Linux ARM64 cross compile builds\n  if [ \"$#\" -eq 1 ] && [ \"$1\" ]; then\n    ARCH=$1\n  fi\n\n  mkdir -p release-packages\n\n  release_archive\n\n  if [[ $OS == \"linux\" ]]; then\n    release_nfpm\n  fi\n}\n\nrelease_archive() {\n  local release_name=\"code-server-$VERSION-$OS-$ARCH\"\n  if [[ $OS == \"linux\" ]]; then\n    tar -czf \"release-packages/$release_name.tar.gz\" --owner=0 --group=0 --transform \"s/^\\.\\/release-standalone/$release_name/\" ./release-standalone\n  else\n    tar -czf \"release-packages/$release_name.tar.gz\" -s \"/^release-standalone/$release_name/\" release-standalone\n  fi\n\n  echo \"done (release-packages/$release_name)\"\n\n  release_gcp\n}\n\nrelease_gcp() {\n  mkdir -p \"release-gcp/$VERSION\"\n  cp \"release-packages/$release_name.tar.gz\" \"./release-gcp/$VERSION/$OS-$ARCH.tar.gz\"\n  mkdir -p \"release-gcp/latest\"\n  cp \"./release-packages/$release_name.tar.gz\" \"./release-gcp/latest/$OS-$ARCH.tar.gz\"\n}\n\n# Generates deb and rpm packages.\nrelease_nfpm() {\n  local nfpm_config\n\n  export NFPM_ARCH\n\n  PKG_FORMAT=\"deb\"\n  NFPM_ARCH=\"$(get_nfpm_arch $PKG_FORMAT \"$ARCH\")\"\n  nfpm_config=\"$(envsubst < ./ci/build/nfpm.yaml)\"\n  echo \"Building deb\"\n  echo \"$nfpm_config\" | head --lines=4\n  nfpm pkg -f <(echo \"$nfpm_config\") --target \"release-packages/code-server_${VERSION}_${NFPM_ARCH}.deb\"\n\n  PKG_FORMAT=\"rpm\"\n  NFPM_ARCH=\"$(get_nfpm_arch $PKG_FORMAT \"$ARCH\")\"\n  nfpm_config=\"$(envsubst < ./ci/build/nfpm.yaml)\"\n  echo \"Building rpm\"\n  echo \"$nfpm_config\" | head --lines=4\n  nfpm pkg -f <(echo \"$nfpm_config\") --target \"release-packages/code-server-$VERSION-$NFPM_ARCH.rpm\"\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/build-release.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Once both code-server and VS Code have been built, use this script to copy\n# them into a single directory (./release), prepare the package.json and\n# product.json, and add shrinkwraps.  This results in a generic NPM package that\n# we published to NPM and also use to compile platform-specific packages.\n\n# MINIFY controls whether minified VS Code is bundled. It must match the value\n# used when VS Code was built.\nMINIFY=\"${MINIFY-true}\"\n\n# node_modules are not copied by default.  Set KEEP_MODULES=1 to copy them.\nKEEP_MODULES=\"${KEEP_MODULES-0}\"\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n\n  source ./ci/lib.sh\n\n  VSCODE_SRC_PATH=\"lib/vscode\"\n  VSCODE_OUT_PATH=\"$RELEASE_PATH/lib/vscode\"\n\n  create_shrinkwraps\n\n  mkdir -p \"$RELEASE_PATH\"\n\n  bundle_code_server\n  bundle_vscode\n\n  rsync ./docs/README.md \"$RELEASE_PATH\"\n  rsync LICENSE \"$RELEASE_PATH\"\n  rsync ./lib/vscode/ThirdPartyNotices.txt \"$RELEASE_PATH\"\n}\n\nbundle_code_server() {\n  rsync out \"$RELEASE_PATH\"\n\n  # For source maps and images.\n  mkdir -p \"$RELEASE_PATH/src/browser\"\n  rsync src/browser/media/ \"$RELEASE_PATH/src/browser/media\"\n  mkdir -p \"$RELEASE_PATH/src/browser/pages\"\n  rsync src/browser/pages/*.html \"$RELEASE_PATH/src/browser/pages\"\n  rsync src/browser/pages/*.css \"$RELEASE_PATH/src/browser/pages\"\n  rsync src/browser/robots.txt \"$RELEASE_PATH/src/browser\"\n\n  # Adds the commit to package.json\n  jq --slurp '(.[0] | del(.scripts,.jest,.devDependencies)) * .[1]' package.json <(\n    cat << EOF\n  {\n    \"commit\": \"$(git rev-parse HEAD)\",\n    \"scripts\": {\n      \"postinstall\": \"sh ./postinstall.sh\"\n    }\n  }\nEOF\n  ) > \"$RELEASE_PATH/package.json\"\n  mv npm-shrinkwrap.json \"$RELEASE_PATH\"\n\n  rsync ci/build/npm-postinstall.sh \"$RELEASE_PATH/postinstall.sh\"\n\n  if [ \"$KEEP_MODULES\" = 1 ]; then\n    rsync node_modules/ \"$RELEASE_PATH/node_modules\"\n  fi\n}\n\nbundle_vscode() {\n  mkdir -p \"$VSCODE_OUT_PATH\"\n\n  local rsync_opts=()\n  if [[ ${DEBUG-} = 1 ]]; then\n    rsync_opts+=(-vh)\n  fi\n\n  # Some extensions have a .gitignore which excludes their built source from the\n  # npm package so exclude any .gitignore files.\n  rsync_opts+=(--exclude .gitignore)\n\n  # Exclude Node as we will add it ourselves for the standalone and will not\n  # need it for the npm package.\n  rsync_opts+=(--exclude /node)\n\n  # Exclude Node modules.\n  if [[ $KEEP_MODULES = 0 ]]; then\n    rsync_opts+=(--exclude node_modules)\n  fi\n\n  rsync \"${rsync_opts[@]}\" ./lib/vscode-reh-web-*/ \"$VSCODE_OUT_PATH\"\n\n  # Merge the package.json for the web/remote server so we can include\n  # dependencies, since we want to ship this via NPM.\n  jq --slurp '.[0] * .[1]' \\\n    \"$VSCODE_SRC_PATH/remote/package.json\" \\\n    \"$VSCODE_OUT_PATH/package.json\" > \"$VSCODE_OUT_PATH/package.json.merged\"\n  mv \"$VSCODE_OUT_PATH/package.json.merged\" \"$VSCODE_OUT_PATH/package.json\"\n  cp \"$VSCODE_SRC_PATH/remote/npm-shrinkwrap.json\" \"$VSCODE_OUT_PATH/npm-shrinkwrap.json\"\n\n  # Include global extension dependencies as well.\n  rsync \"$VSCODE_SRC_PATH/extensions/package.json\" \"$VSCODE_OUT_PATH/extensions/package.json\"\n  cp \"$VSCODE_SRC_PATH/extensions/npm-shrinkwrap.json\" \"$VSCODE_OUT_PATH/extensions/npm-shrinkwrap.json\"\n  rsync \"$VSCODE_SRC_PATH/extensions/postinstall.mjs\" \"$VSCODE_OUT_PATH/extensions/postinstall.mjs\"\n}\n\ncreate_shrinkwraps() {\n  # package-lock.json files (used to ensure deterministic versions of\n  # dependencies) are not packaged when publishing to the NPM registry.\n  #\n  # To ensure deterministic dependency versions (even when code-server is\n  # installed with NPM), we create an npm-shrinkwrap.json file from the\n  # currently installed node_modules. This ensures the versions used from\n  # development (that the package-lock.json guarantees) are also the ones\n  # installed by end-users.  These will include devDependencies, but those will\n  # be ignored when installing globally (for code-server), and because we use\n  # --omit=dev (for VS Code).\n\n  # We first generate the shrinkwrap file for code-server itself - which is the\n  # current directory.\n  cp package-lock.json package-lock.json.temp\n  npm shrinkwrap\n  mv package-lock.json.temp package-lock.json\n\n  # Then the shrinkwrap files for the bundled VS Code.\n  pushd \"$VSCODE_SRC_PATH/remote/\"\n  cp package-lock.json package-lock.json.temp\n  npm shrinkwrap\n  mv package-lock.json.temp package-lock.json\n  popd\n\n  pushd \"$VSCODE_SRC_PATH/extensions/\"\n  cp package-lock.json package-lock.json.temp\n  npm shrinkwrap\n  mv package-lock.json.temp package-lock.json\n  popd\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/build-standalone-release.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Once we have an NPM package, use this script to copy it to a separate\n# directory (./release-standalone) and install the dependencies.  This new\n# directory can then be packaged as a platform-specific release.\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n\n  source ./ci/lib.sh\n\n  rsync \"$RELEASE_PATH/\" \"$RELEASE_PATH-standalone\"\n  RELEASE_PATH+=-standalone\n\n  # Package managers may shim their own \"node\" wrapper into the PATH, so run\n  # node and ask it for its true path.\n  local node_path\n  node_path=\"$(node -p process.execPath)\"\n\n  mkdir -p \"$RELEASE_PATH/bin\"\n  mkdir -p \"$RELEASE_PATH/lib\"\n  rsync ./ci/build/code-server.sh \"$RELEASE_PATH/bin/code-server\"\n  rsync \"$node_path\" \"$RELEASE_PATH/lib/node\"\n\n  chmod 755 \"$RELEASE_PATH/lib/node\"\n\n  pushd \"$RELEASE_PATH\"\n  npm install --unsafe-perm --omit=dev\n  # Code deletes some files from the extension node_modules directory which\n  # leaves broken symlinks in the corresponding .bin directory.  nfpm will fail\n  # on these broken symlinks so clean them up.\n  rm -fr \"./lib/vscode/extensions/node_modules/.bin\"\n  popd\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/build-vscode.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Builds vscode into lib/vscode/out-vscode.\n\n# MINIFY controls whether a minified version of vscode is built.\nMINIFY=${MINIFY-true}\n\ndelete-bin-script() {\n  rm -f \"lib/vscode-reh-web-linux-x64/bin/$1\"\n}\n\ncopy-bin-script() {\n  local script=\"$1\"\n  local dest=\"lib/vscode-reh-web-linux-x64/bin/$script\"\n  cp \"lib/vscode/resources/server/bin/$script\" \"$dest\"\n  sed -i.bak \"s/@@VERSION@@/$(vscode_version)/g\" \"$dest\"\n  sed -i.bak \"s/@@COMMIT@@/$BUILD_SOURCEVERSION/g\" \"$dest\"\n  sed -i.bak \"s/@@APPNAME@@/code-server/g\" \"$dest\"\n\n  # Fix Node path on Darwin and Linux.\n  # We do not want expansion here; this text should make it to the file as-is.\n  # shellcheck disable=SC2016\n  sed -i.bak 's/^ROOT=\\(.*\\)$/VSROOT=\\1\\nROOT=\"$(dirname \"$(dirname \"$VSROOT\")\")\"/g' \"$dest\"\n  sed -i.bak 's/ROOT\\/out/VSROOT\\/out/g' \"$dest\"\n  # We do not want expansion here; this text should make it to the file as-is.\n  # shellcheck disable=SC2016\n  sed -i.bak 's/$ROOT\\/node/${NODE_EXEC_PATH:-$ROOT\\/lib\\/node}/g' \"$dest\"\n\n  # Fix Node path on Windows.\n  sed -i.bak 's/^set ROOT_DIR=\\(.*\\)$/set ROOT_DIR=%~dp0..\\\\..\\\\..\\\\..\\r\\nset VSROOT_DIR=\\1/g' \"$dest\"\n  sed -i.bak 's/%ROOT_DIR%\\\\out/%VSROOT_DIR%\\\\out/g' \"$dest\"\n\n  chmod +x \"$dest\"\n  rm \"$dest.bak\"\n}\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n\n  source ./ci/lib.sh\n\n  # Set the commit Code will embed into the product.json.  We need to do this\n  # since Code tries to get the commit from the `.git` directory which will fail\n  # as it is a submodule.\n  #\n  # Also, we use code-server's commit rather than VS Code's otherwise it would\n  # not update when only our patch files change, and that will cause caching\n  # issues where the browser keeps using outdated code.\n  export BUILD_SOURCEVERSION\n  BUILD_SOURCEVERSION=$(git rev-parse HEAD)\n\n  pushd lib/vscode\n\n  if [[ ! ${VERSION-} ]]; then\n    echo \"VERSION not set. Please set before running this script:\"\n    echo \"VERSION='0.0.0' npm run build:vscode\"\n    exit 1\n  fi\n\n  # Add the date, our name, links, enable telemetry (this just makes telemetry\n  # available; telemetry can still be disabled by flag or setting), and\n  # configure trusted extensions (since some, like github.copilot-chat, never\n  # ask to be trusted and this is the only way to get auth working).\n  #\n  # This needs to be done before building as Code will read this file and embed\n  # it into the client-side code.\n  git checkout product.json             # Reset in case the script exited early.\n  cp product.json product.original.json # Since jq has no inline edit.\n  jq --slurp '.[0] * .[1]' product.original.json <(\n    cat << EOF\n  {\n    \"enableTelemetry\": true,\n    \"quality\": \"stable\",\n    \"codeServerVersion\": \"$VERSION\",\n    \"nameShort\": \"code-server\",\n    \"nameLong\": \"code-server\",\n    \"applicationName\": \"code-server\",\n    \"dataFolderName\": \".code-server\",\n    \"win32MutexName\": \"codeserver\",\n    \"licenseUrl\": \"https://github.com/coder/code-server/blob/main/LICENSE\",\n    \"win32DirName\": \"code-server\",\n    \"win32NameVersion\": \"code-server\",\n    \"win32AppUserModelId\": \"coder.code-server\",\n    \"win32ShellNameShort\": \"c&ode-server\",\n    \"darwinBundleIdentifier\": \"com.coder.code.server\",\n    \"linuxIconName\": \"com.coder.code.server\",\n    \"reportIssueUrl\": \"https://github.com/coder/code-server/issues/new\",\n    \"documentationUrl\": \"https://go.microsoft.com/fwlink/?LinkID=533484#vscode\",\n    \"keyboardShortcutsUrlMac\": \"https://go.microsoft.com/fwlink/?linkid=832143\",\n    \"keyboardShortcutsUrlLinux\": \"https://go.microsoft.com/fwlink/?linkid=832144\",\n    \"keyboardShortcutsUrlWin\": \"https://go.microsoft.com/fwlink/?linkid=832145\",\n    \"introductoryVideosUrl\": \"https://go.microsoft.com/fwlink/?linkid=832146\",\n    \"tipsAndTricksUrl\": \"https://go.microsoft.com/fwlink/?linkid=852118\",\n    \"newsletterSignupUrl\": \"https://www.research.net/r/vsc-newsletter\",\n    \"linkProtectionTrustedDomains\": [\n      \"https://open-vsx.org\"\n    ],\n    \"trustedExtensionAuthAccess\": [\n      \"vscode.git\", \"vscode.github\",\n      \"github.vscode-pull-request-github\",\n      \"github.copilot\", \"github.copilot-chat\"\n    ],\n    \"aiConfig\": {\n      \"ariaKey\": \"code-server\"\n    }\n  }\nEOF\n  ) > product.json\n\n  # Any platform here works since we will do our own packaging.  We have to do\n  # this because we have an NPM package that could be installed on any platform.\n  # The correct platform dependencies and scripts will be installed as part of\n  # the post-install during `npm install` or when building a standalone release.\n  node --max-old-space-size=16384 --optimize-for-size \\\n       ./node_modules/gulp/bin/gulp.js \\\n       \"vscode-reh-web-linux-x64${MINIFY:+-min}\"\n\n  # Reset so if you develop after building you will not be stuck with the wrong\n  # commit (the dev client will use `oss-dev` but the dev server will still use\n  # product.json which will have `stable-$commit`).\n  git checkout product.json\n\n  popd\n\n  pushd lib/vscode-reh-web-linux-x64\n  # Make sure Code took the version we set in the environment variable.  Not\n  # having a version will break display languages.\n  if ! jq -e .commit product.json; then\n    echo \"'commit' is missing from product.json\"\n    exit 1\n  fi\n  popd\n\n  # These provide a `code-server` command in the integrated terminal to open\n  # files in the current instance.\n  delete-bin-script remote-cli/code-server\n  copy-bin-script remote-cli/code-darwin.sh\n  copy-bin-script remote-cli/code-linux.sh\n  copy-bin-script remote-cli/code.cmd\n\n  # These provide a way for terminal applications to open browser windows.\n  delete-bin-script helpers/browser.sh\n  copy-bin-script helpers/browser-darwin.sh\n  copy-bin-script helpers/browser-linux.sh\n  copy-bin-script helpers/browser.cmd\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/clean.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"${0}\")/../..\"\n  source ./ci/lib.sh\n\n  git clean -Xffd\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/build/code-server-nfpm.sh",
    "content": "#!/usr/bin/env sh\n\nexec /usr/lib/code-server/bin/code-server \"$@\"\n"
  },
  {
    "path": "ci/build/code-server-user.service",
    "content": "[Unit]\nDescription=code-server\nAfter=network.target\n\n[Service]\nType=exec\nExecStart=/usr/bin/code-server\nRestart=always\n\n[Install]\nWantedBy=default.target\n"
  },
  {
    "path": "ci/build/code-server.sh",
    "content": "#!/bin/sh\nset -eu\n\n# This script is intended to be bundled into the standalone releases.\n# Runs code-server with the bundled node binary.\n\n_realpath() {\n  # See https://github.com/coder/code-server/issues/1537 on why no realpath or readlink -f.\n\n  script=\"$1\"\n  cd \"$(dirname \"$script\")\"\n\n  while [ -L \"$(basename \"$script\")\" ]; do\n    script=\"$(readlink \"$(basename \"$script\")\")\"\n    cd \"$(dirname \"$script\")\"\n  done\n\n  echo \"$PWD/$(basename \"$script\")\"\n}\n\nroot() {\n  script=\"$(_realpath \"$0\")\"\n  bin_dir=\"$(dirname \"$script\")\"\n  dirname \"$bin_dir\"\n}\n\nROOT=\"$(root)\"\nexec \"$ROOT/lib/node\" \"$ROOT\" \"$@\"\n"
  },
  {
    "path": "ci/build/code-server@.service",
    "content": "[Unit]\nDescription=code-server\nAfter=network.target\n\n[Service]\nType=exec\nExecStart=/usr/bin/code-server\nRestart=always\nUser=%i\n\n[Install]\nWantedBy=default.target\n"
  },
  {
    "path": "ci/build/nfpm.yaml",
    "content": "name: \"code-server\"\narch: \"${NFPM_ARCH}\"\nplatform: \"linux\"\nversion: \"v${VERSION}\"\nsection: \"devel\"\npriority: \"optional\"\nmaintainer: \"Joe Previte <joe@coder.com>\"\ndescription: |\n  Run VS Code in the browser.\nvendor: \"Coder\"\nhomepage: \"https://github.com/coder/code-server\"\nlicense: \"MIT\"\n\ncontents:\n  - src: ./ci/build/code-server-nfpm.sh\n    dst: /usr/bin/code-server\n\n  - src: ./ci/build/code-server@.service\n    dst: /usr/lib/systemd/system/code-server@.service\n\n  - src: ./ci/build/code-server-user.service\n    dst: /usr/lib/systemd/user/code-server.service\n\n  - src: ./release-standalone/*\n    dst: /usr/lib/code-server\n"
  },
  {
    "path": "ci/build/npm-postinstall.sh",
    "content": "#!/usr/bin/env sh\nset -eu\n\n# Copied from ../lib.sh except we do not rename Darwin and we do not need to\n# detect Alpine.\nos() {\n  osname=$(uname | tr '[:upper:]' '[:lower:]')\n  case $osname in\n    cygwin* | mingw*) osname=\"windows\" ;;\n  esac\n  echo \"$osname\"\n}\n\n# Create a symlink at $2 pointing to $1 on any platform.  Anything that\n# currently exists at $2 will be deleted.\nsymlink() {\n  source=\"$1\"\n  dest=\"$2\"\n  rm -rf \"$dest\"\n  case $OS in\n    windows) mklink /J \"$dest\" \"$source\" ;;\n    *) ln -s \"$source\" \"$dest\" ;;\n  esac\n}\n\n# VS Code bundles some modules into an asar which is an archive format that\n# works like tar. It then seems to get unpacked into node_modules.asar.\n#\n# I don't know why they do this but all the dependencies they bundle already\n# exist in node_modules so just symlink it. We have to do this since not only\n# Code itself but also extensions will look specifically in this directory for\n# files (like the ripgrep binary or the oniguruma wasm).\nsymlink_asar() {\n  symlink node_modules node_modules.asar\n}\n\n# Make a symlink at bin/$1/$3 pointing to the platform-specific version of the\n# script in $2.  The extension of the link will be .cmd for Windows otherwise it\n# will be whatever is in $4 (or no extension if $4 is not set).\nsymlink_bin_script() {\n  oldpwd=\"$(pwd)\"\n  cd \"bin/$1\"\n  source=\"$2\"\n  dest=\"$3\"\n  ext=\"${4-}\"\n  case $OS in\n    windows) symlink \"$source.cmd\" \"$dest.cmd\" ;;\n    darwin | macos) symlink \"$source-darwin.sh\" \"$dest$ext\" ;;\n    *) symlink \"$source-linux.sh\" \"$dest$ext\" ;;\n  esac\n  cd \"$oldpwd\"\n}\n\ncommand_exists() {\n  if [ ! \"$1\" ]; then return 1; fi\n  command -v \"$@\" > /dev/null\n}\n\nis_root() {\n  if command_exists id && [ \"$(id -u)\" = 0 ]; then\n    return 0\n  fi\n  return 1\n}\n\nOS=\"$(os)\"\n\nmain() {\n  # Grabs the major version of node from $npm_config_user_agent which looks like\n  # yarn/1.21.1 npm/? node/v14.2.0 darwin x64\n  major_node_version=$(echo \"$npm_config_user_agent\" | sed -n 's/.*node\\/v\\([^.]*\\).*/\\1/p')\n\n  if [ -n \"${FORCE_NODE_VERSION:-}\" ]; then\n    echo \"WARNING: Overriding required Node.js version to v$FORCE_NODE_VERSION\"\n    echo \"This could lead to broken functionality, and is unsupported.\"\n    echo \"USE AT YOUR OWN RISK!\"\n  fi\n\n  if [ \"$major_node_version\" -ne \"${FORCE_NODE_VERSION:-22}\" ]; then\n    echo \"ERROR: code-server currently requires node v22.\"\n    if [ -n \"$FORCE_NODE_VERSION\" ]; then\n      echo \"However, you have overrided the version check to use v$FORCE_NODE_VERSION.\"\n    fi\n    echo \"We have detected that you are on node v$major_node_version\"\n    echo \"You can override this version check by setting \\$FORCE_NODE_VERSION,\"\n    echo \"but configurations that do not use the same node version are unsupported.\"\n    exit 1\n  fi\n\n  # Under npm, if we are running as root, we need --unsafe-perm otherwise\n  # post-install scripts will not have sufficient permissions to do their thing.\n  if is_root; then\n    case \"${npm_config_user_agent-}\" in npm*)\n      if [ \"${npm_config_unsafe_perm-}\" != \"true\" ]; then\n        echo \"Please pass --unsafe-perm to npm to install code-server\"\n        echo \"Otherwise post-install scripts will not have permissions to run\"\n        echo \"See https://docs.npmjs.com/misc/config#unsafe-perm\"\n        echo \"See https://stackoverflow.com/questions/49084929/npm-sudo-global-installation-unsafe-perm\"\n        exit 1\n      fi\n      ;;\n    esac\n  fi\n\n  if ! vscode_install; then\n    echo \"You may not have the required dependencies to build the native modules.\"\n    echo \"Please see https://github.com/coder/code-server/blob/main/docs/npm.md\"\n    exit 1\n  fi\n\n  if [ -n \"${FORCE_NODE_VERSION:-}\" ]; then\n    echo \"WARNING: The required Node.js version was overriden to v$FORCE_NODE_VERSION\"\n    echo \"This could lead to broken functionality, and is unsupported.\"\n    echo \"USE AT YOUR OWN RISK!\"\n  fi\n}\n\ninstall_with_yarn_or_npm() {\n  echo \"User agent: ${npm_config_user_agent-none}\"\n  # For development we enforce npm, but for installing the package as an\n  # end-user we want to keep using whatever package manager is in use.\n  case \"${npm_config_user_agent-}\" in\n    npm*)\n      if ! npm install --unsafe-perm --omit=dev; then\n        return 1\n      fi\n      ;;\n    yarn*)\n      if ! yarn --production --frozen-lockfile --no-default-rc; then\n        return 1\n      fi\n      ;;\n    *)\n      echo \"Could not determine which package manager is being used to install code-server\"\n      exit 1\n      ;;\n  esac\n  return 0\n}\n\nvscode_install() {\n  echo 'Installing Code dependencies...'\n  cd lib/vscode\n  if ! install_with_yarn_or_npm; then\n    return 1\n  fi\n\n  symlink_asar\n  symlink_bin_script remote-cli code code-server\n  symlink_bin_script helpers browser browser .sh\n\n  cd extensions\n  if ! install_with_yarn_or_npm; then\n    return 1\n  fi\n\n  return 0\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/doctoc.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n\n  doctoc --title '# FAQ' docs/FAQ.md > /dev/null\n  doctoc --title '# Setup Guide' docs/guide.md > /dev/null\n  doctoc --title '# Install' docs/install.md > /dev/null\n  doctoc --title '# npm Install Requirements' docs/npm.md > /dev/null\n  doctoc --title '# Contributing' docs/CONTRIBUTING.md > /dev/null\n  doctoc --title '# Maintaining' docs/MAINTAINING.md > /dev/null\n  doctoc --title '# Contributor Covenant Code of Conduct' docs/CODE_OF_CONDUCT.md > /dev/null\n  doctoc --title '# iPad' docs/ipad.md > /dev/null\n  doctoc --title '# Termux' docs/termux.md > /dev/null\n\n  if [[ ${CI-} && $(git ls-files --other --modified --exclude-standard) ]]; then\n    echo \"Files need generation or are formatted incorrectly:\"\n    git -c color.ui=always status | grep --color=no '\\[31m'\n    echo \"Please run the following locally:\"\n    echo \"  npm run doctoc\"\n    exit 1\n  fi\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/gen_icons.sh",
    "content": "#!/bin/sh\nset -eu\n\n# Generate icons from a single favicon.svg.  favicon.svg should have no fill\n# colors set.\nmain() {\n  cd src/browser/media\n\n  # We need .ico for backwards compatibility.  The other two are the only icon\n  # sizes required by Chrome and we use them for stuff like apple-touch-icon as\n  # well.  https://web.dev/add-manifest/\n  #\n  # This should be enough and we can always add more if there are problems.\n  #\n  # -quiet to avoid https://github.com/ImageMagick/ImageMagick/issues/884\n  # -background defaults to white but we want it transparent.\n  # -density somehow makes the image both sharper and smaller in file size.\n  #\n  # https://imagemagick.org/script/command-line-options.php#background\n  convert -quiet -background transparent \\\n          -resize 256x256 -density 256x256 \\\n          favicon.svg favicon.ico\n\n  # Generate PWA icons.  There should be enough padding to support masking.\n  convert -quiet -border 60x60 -bordercolor white -background white \\\n          -resize 192x192 -density 192x192 \\\n          favicon.svg pwa-icon-maskable-192.png\n  convert -quiet -border 160x160 -bordercolor white -background white \\\n          -resize 512x512 -density 512x512 \\\n          favicon.svg pwa-icon-maskable-512.png\n\n  # Generate non-maskable PWA icons.\n  magick pwa-icon-maskable-192.png \\\n         \\( +clone -threshold 101% -fill white -draw \"roundRectangle 0,0 %[fx:int(w)],%[fx:int(h)] 50,50\" \\) \\\n         -channel-fx \"| gray=>alpha\" \\\n         pwa-icon-192.png\n  magick pwa-icon-maskable-512.png \\\n         \\( +clone -threshold 101% -fill white -draw \"roundRectangle 0,0 %[fx:int(w)],%[fx:int(h)] 100,100\" \\) \\\n         -channel-fx \"| gray=>alpha\" \\\n         pwa-icon-512.png\n\n  # The following adds dark mode support for the favicon as\n  # favicon-dark-support.svg There is no similar capability for pwas or .ico so\n  # we can only add support to the svg.\n  favicon_dark_style=\"<style>@media (prefers-color-scheme: dark) {* { fill: white; }}</style>\"\n  cp favicon.svg favicon-dark-support.svg\n  sed \"s%<path%$favicon_dark_style\\n  <path%\" favicon.svg > favicon-dark-support.svg\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/lint-scripts.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n  shellcheck -e SC2046,SC2164,SC2154,SC1091,SC1090,SC2002 $(git ls-files '*.sh' | grep -v 'lib/vscode')\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/postinstall.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Install dependencies in $1.\ninstall-deps() {\n  local args=()\n  if [[ ${CI-} ]]; then\n    args+=(ci)\n  else\n    args+=(install)\n  fi\n  # If there is no package.json then npm will look upward and end up installing\n  # from the root resulting in an infinite loop (this can happen if you have not\n  # checked out the submodule yet for example).\n  if [[ ! -f \"$1/package.json\" ]]; then\n    echo \"$1/package.json is missing; did you run git submodule update --init?\"\n    exit 1\n  fi\n  pushd \"$1\"\n  echo \"Installing dependencies for $PWD\"\n  npm \"${args[@]}\"\n  popd\n}\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n  source ./ci/lib.sh\n\n  install-deps test\n  install-deps test/e2e/extensions/test-extension\n  # We don't need these when running the integration tests\n  # so you can pass SKIP_SUBMODULE_DEPS\n  if [[ ! ${SKIP_SUBMODULE_DEPS-} ]]; then\n    install-deps lib/vscode\n  fi\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/preinstall.js",
    "content": "if (process.env.npm_execpath.includes(\"yarn\")) {\n  throw new Error(\"`yarn` is no longer supported; please use `npm install` instead\")\n}\n"
  },
  {
    "path": "ci/dev/test-e2e.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nhelp() {\n  echo >&2 \"  You can build with 'npm run watch' or you can build a release\"\n  echo >&2 \"  For example: 'npm run build && npm run build:vscode && KEEP_MODULES=1 npm run release'\"\n  echo >&2 \"  Then 'CODE_SERVER_TEST_ENTRY=./release npm run test:e2e'\"\n  echo >&2 \"  You can manually run that release with 'node ./release'\"\n}\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n\n  source ./ci/lib.sh\n\n  pushd test/e2e/extensions/test-extension\n  echo \"Building test extension\"\n  npm run build\n  popd\n\n  local dir=\"$PWD\"\n  if [[ ! ${CODE_SERVER_TEST_ENTRY-} ]]; then\n    echo \"Set CODE_SERVER_TEST_ENTRY to test another build of code-server\"\n  else\n    pushd \"$CODE_SERVER_TEST_ENTRY\"\n    dir=\"$PWD\"\n    popd\n  fi\n\n  echo \"Testing build in '$dir'\"\n\n  # Simple sanity checks to see that we've built. There could still be things\n  # wrong (native modules version issues, incomplete build, etc).\n  if [[ ! -d $dir/out ]]; then\n    echo >&2 \"No code-server build detected\"\n    help\n    exit 1\n  fi\n\n  if [[ ! -d $dir/lib/vscode/out ]]; then\n    echo >&2 \"No VS Code build detected\"\n    help\n    exit 1\n  fi\n\n  cd test\n  ./node_modules/.bin/playwright test \"$@\"\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/test-integration.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nhelp() {\n  echo >&2 \"  You can build the standalone release with 'npm run release:standalone'\"\n  echo >&2 \"  Or you can pass in a custom path.\"\n  echo >&2 \"  CODE_SERVER_PATH='/var/tmp/coder/code-server/bin/code-server' npm run test:integration\"\n}\n\n# Make sure a code-server release works. You can pass in the path otherwise it\n# will look for release-standalone in the current directory.\n#\n# This is to make sure we don't have Node version errors or any other\n# compilation-related errors.\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n\n  source ./ci/lib.sh\n\n  local path=\"$RELEASE_PATH-standalone/bin/code-server\"\n  if [[ ! ${CODE_SERVER_PATH-} ]]; then\n    echo \"Set CODE_SERVER_PATH to test another build of code-server\"\n  else\n    path=\"$CODE_SERVER_PATH\"\n  fi\n\n  echo \"Running tests with code-server binary: '$path'\"\n\n  if [[ ! -f $path ]]; then\n    echo >&2 \"No code-server build detected\"\n    echo >&2 \"Looked in $path\"\n    help\n    exit 1\n  fi\n\n  CODE_SERVER_PATH=\"$path\" ./test/node_modules/.bin/jest \"$@\" --coverage=false --testRegex \"./test/integration\" --testPathIgnorePatterns \"./test/integration/fixtures\"\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/test-native.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nhelp() {\n  echo >&2 \"  You can build the standalone release with 'npm run release:standalone'\"\n  echo >&2 \"  Or you can pass in a custom path.\"\n  echo >&2 \"  CODE_SERVER_PATH='/var/tmp/coder/code-server/bin/code-server' npm run test:integration\"\n}\n\n# Make sure a code-server release works. You can pass in the path otherwise it\n# will look for release-standalone in the current directory.\n#\n# This is to make sure we don't have Node version errors or any other\n# compilation-related errors.\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n\n  source ./ci/lib.sh\n\n  local path=\"$RELEASE_PATH-standalone/bin/code-server\"\n  if [[ ! ${CODE_SERVER_PATH-} ]]; then\n    echo \"Set CODE_SERVER_PATH to test another build of code-server\"\n  else\n    path=\"$CODE_SERVER_PATH\"\n  fi\n\n  echo \"Running tests with code-server binary: '$path'\"\n\n  if [[ ! -f $path ]]; then\n    echo >&2 \"No code-server build detected\"\n    echo >&2 \"Looked in $path\"\n    help\n    exit 1\n  fi\n\n  CODE_SERVER_PATH=\"$path\" ./test/node_modules/.bin/jest \"$@\" --coverage=false --testRegex \"./test/integration/help.test.ts\"\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/test-scripts.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n  bats ./test/scripts\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/test-unit.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n\n  source ./ci/lib.sh\n\n  # We must keep jest in a sub-directory. See ../../test/package.json for more\n  # information. We must also run it from the root otherwise coverage will not\n  # include our source files.\n  ./test/node_modules/.bin/jest \"$@\" --testRegex \"./test/unit/.*ts\"\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/dev/watch.ts",
    "content": "import { spawn, ChildProcess } from \"child_process\"\nimport * as path from \"path\"\nimport { onLine, OnLineCallback } from \"../../src/node/util\"\n\ninterface DevelopmentCompilers {\n  [key: string]: ChildProcess | undefined\n  vscode: ChildProcess\n  vscodeWebExtensions: ChildProcess\n  codeServer: ChildProcess\n  plugins: ChildProcess | undefined\n}\n\nclass Watcher {\n  private rootPath = path.resolve(process.cwd())\n  private readonly paths = {\n    /** Path to uncompiled VS Code source. */\n    vscodeDir: path.join(this.rootPath, \"lib/vscode\"),\n    pluginDir: process.env.PLUGIN_DIR,\n  }\n\n  //#region Web Server\n\n  /** Development web server. */\n  private webServer: ChildProcess | undefined\n\n  private reloadWebServer = (): void => {\n    if (this.webServer) {\n      this.webServer.kill()\n    }\n\n    // Pass CLI args, save for `node` and the initial script name.\n    const args = process.argv.slice(2)\n    this.webServer = spawn(\"node\", [path.join(this.rootPath, \"out/node/entry.js\"), ...args])\n    onLine(this.webServer, (line) => console.log(\"[code-server]\", line))\n    const { pid } = this.webServer\n\n    this.webServer.on(\"exit\", () => console.log(\"[code-server]\", `Web process ${pid} exited`))\n\n    console.log(\"\\n[code-server]\", `Spawned web server process ${pid}`)\n  }\n\n  //#endregion\n\n  //#region Compilers\n\n  private readonly compilers: DevelopmentCompilers = {\n    codeServer: spawn(\"tsc\", [\"--watch\", \"--pretty\", \"--preserveWatchOutput\"], { cwd: this.rootPath }),\n    vscode: spawn(\"npm\", [\"run\", \"watch\"], { cwd: this.paths.vscodeDir }),\n    vscodeWebExtensions: spawn(\"npm\", [\"run\", \"watch-web\"], { cwd: this.paths.vscodeDir }),\n    plugins: this.paths.pluginDir\n      ? spawn(\"npm\", [\"run\", \"build\", \"--watch\"], { cwd: this.paths.pluginDir })\n      : undefined,\n  }\n\n  public async initialize(): Promise<void> {\n    for (const event of [\"SIGINT\", \"SIGTERM\"]) {\n      process.on(event, () => this.dispose(0))\n    }\n\n    for (const [processName, devProcess] of Object.entries(this.compilers)) {\n      if (!devProcess) continue\n\n      devProcess.on(\"exit\", (code) => {\n        console.log(`[${processName}]`, \"Terminated unexpectedly\")\n        this.dispose(code)\n      })\n\n      if (devProcess.stderr) {\n        devProcess.stderr.on(\"data\", (d: string | Uint8Array) => process.stderr.write(d))\n      }\n    }\n\n    onLine(this.compilers.vscode, this.parseVSCodeLine)\n    onLine(this.compilers.codeServer, this.parseCodeServerLine)\n\n    if (this.compilers.plugins) {\n      onLine(this.compilers.plugins, this.parsePluginLine)\n    }\n  }\n\n  //#endregion\n\n  //#region Line Parsers\n\n  private parseVSCodeLine: OnLineCallback = (strippedLine, originalLine) => {\n    if (!strippedLine.length) return\n\n    console.log(\"[Code OSS]\", originalLine)\n\n    if (strippedLine.includes(\"Finished compilation with\")) {\n      console.log(\"[Code OSS] ✨ Finished compiling! ✨\", \"(Refresh your web browser ♻️)\")\n      this.reloadWebServer()\n    }\n  }\n\n  private parseCodeServerLine: OnLineCallback = (strippedLine, originalLine) => {\n    if (!strippedLine.length) return\n\n    console.log(\"[Compiler][code-server]\", originalLine)\n\n    if (strippedLine.includes(\"Watching for file changes\")) {\n      console.log(\"[Compiler][code-server]\", \"Finished compiling!\", \"(Refresh your web browser ♻️)\")\n      this.reloadWebServer()\n    }\n  }\n\n  private parsePluginLine: OnLineCallback = (strippedLine, originalLine) => {\n    if (!strippedLine.length) return\n\n    console.log(\"[Compiler][Plugin]\", originalLine)\n\n    if (strippedLine.includes(\"Watching for file changes...\")) {\n      this.reloadWebServer()\n    }\n  }\n\n  //#endregion\n\n  //#region Utilities\n\n  private dispose(code: number | null): void {\n    for (const [processName, devProcess] of Object.entries(this.compilers)) {\n      console.log(`[${processName}]`, \"Killing...\\n\")\n      devProcess?.removeAllListeners()\n      devProcess?.kill()\n    }\n    process.exit(typeof code === \"number\" ? code : 0)\n  }\n\n  //#endregion\n}\n\nasync function main(): Promise<void> {\n  try {\n    const watcher = new Watcher()\n    await watcher.initialize()\n  } catch (error: any) {\n    console.error(error.message)\n    process.exit(1)\n  }\n}\n\nmain()\n"
  },
  {
    "path": "ci/helm-chart/.helmignore",
    "content": "# Patterns to ignore when building packages.\n# This supports shell glob matching, relative path matching, and\n# negation (prefixed with !). Only one pattern per line.\n.DS_Store\n# Common VCS dirs\n.git/\n.gitignore\n.bzr/\n.bzrignore\n.hg/\n.hgignore\n.svn/\n# Common backup files\n*.swp\n*.bak\n*.tmp\n*.orig\n*~\n# Various IDEs\n.project\n.idea/\n*.tmproj\n.vscode/\n"
  },
  {
    "path": "ci/helm-chart/Chart.yaml",
    "content": "apiVersion: v2\nname: code-server\ndescription: A Helm chart for coder/code-server\n\n# A chart can be either an 'application' or a 'library' chart.\n#\n# Application charts are a collection of templates that can be packaged into versioned archives\n# to be deployed.\n#\n# Library charts provide useful utilities or functions for the chart developer. They're included as\n# a dependency of application charts to inject those utilities and functions into the rendering\n# pipeline. Library charts do not define any templates and therefore cannot be deployed.\ntype: application\n\n# This is the chart version. This version number should be incremented each time you make changes\n# to the chart and its templates, including the app version.\n# Versions are expected to follow Semantic Versioning (https://semver.org/)\nversion: 3.33.0\n\n# This is the version number of the application being deployed. This version number should be\n# incremented each time you make changes to the application. Versions are not expected to\n# follow Semantic Versioning. They should reflect the version the application is using.\nappVersion: 4.109.5\n"
  },
  {
    "path": "ci/helm-chart/templates/NOTES.txt",
    "content": "1. Get the application URL by running these commands:\n{{- if .Values.ingress.enabled }}\n{{- range $host := .Values.ingress.hosts }}\n  {{- range .paths }}\n  http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }}\n  {{- end }}\n{{- end }}\n{{- else if contains \"NodePort\" .Values.service.type }}\n  export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath=\"{.spec.ports[0].nodePort}\" services {{ include \"code-server.fullname\" . }})\n  export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath=\"{.items[0].status.addresses[0].address}\")\n  echo http://$NODE_IP:$NODE_PORT\n{{- else if contains \"LoadBalancer\" .Values.service.type }}\n     NOTE: It may take a few minutes for the LoadBalancer IP to be available.\n           You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include \"code-server.fullname\" . }}'\n  export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include \"code-server.fullname\" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}')\n  echo http://$SERVICE_IP:{{ .Values.service.port }}\n{{- else if contains \"ClusterIP\" .Values.service.type }}\n  echo \"Visit http://127.0.0.1:8080 to use your application\"\n  kubectl port-forward --namespace {{ .Release.Namespace }} service/{{ include \"code-server.fullname\" . }} 8080:http\n{{- end }}\n\nAdministrator credentials:\n\n  Password: echo $(kubectl get secret --namespace {{ .Release.Namespace }} {{ template \"code-server.fullname\" . }} -o jsonpath=\"{.data.password}\" | base64 --decode)\n"
  },
  {
    "path": "ci/helm-chart/templates/_helpers.tpl",
    "content": "{{/* vim: set filetype=mustache: */}}\n{{/*\nExpand the name of the chart.\n*/}}\n{{- define \"code-server.name\" -}}\n{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix \"-\" -}}\n{{- end -}}\n\n{{/*\nCreate a default fully qualified app name.\nWe truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).\nIf release name contains chart name it will be used as a full name.\n*/}}\n{{- define \"code-server.fullname\" -}}\n{{- if .Values.fullnameOverride -}}\n{{- .Values.fullnameOverride | trunc 63 | trimSuffix \"-\" -}}\n{{- else -}}\n{{- $name := default .Chart.Name .Values.nameOverride -}}\n{{- if contains $name .Release.Name -}}\n{{- .Release.Name | trunc 63 | trimSuffix \"-\" -}}\n{{- else -}}\n{{- printf \"%s-%s\" .Release.Name $name | trunc 63 | trimSuffix \"-\" -}}\n{{- end -}}\n{{- end -}}\n{{- end -}}\n\n{{/*\nCreate chart name and version as used by the chart label.\n*/}}\n{{- define \"code-server.chart\" -}}\n{{- printf \"%s-%s\" .Chart.Name .Chart.Version | replace \"+\" \"_\" | trunc 63 | trimSuffix \"-\" -}}\n{{- end -}}\n\n{{/*\nCommon labels\n*/}}\n{{- define \"code-server.labels\" -}}\nhelm.sh/chart: {{ include \"code-server.chart\" . }}\n{{ include \"code-server.selectorLabels\" . }}\n{{- if .Chart.AppVersion }}\napp.kubernetes.io/version: {{ .Chart.AppVersion | quote }}\n{{- end }}\napp.kubernetes.io/managed-by: {{ .Release.Service }}\n{{- end }}\n\n{{/*\nSelector labels\n*/}}\n{{- define \"code-server.selectorLabels\" -}}\napp.kubernetes.io/name: {{ include \"code-server.name\" . }}\napp.kubernetes.io/instance: {{ .Release.Name }}\n{{- end }}\n\n{{/*\nCreate the name of the service account to use\n*/}}\n{{- define \"code-server.serviceAccountName\" -}}\n{{- if .Values.serviceAccount.create -}}\n    {{ default (include \"code-server.fullname\" .) .Values.serviceAccount.name }}\n{{- else -}}\n    {{ default \"default\" .Values.serviceAccount.name }}\n{{- end -}}\n{{- end -}}\n"
  },
  {
    "path": "ci/helm-chart/templates/deployment.yaml",
    "content": "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: {{ include \"code-server.fullname\" . }}\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\n  {{- if .Values.annotations }}\n  annotations: {{- toYaml .Values.annotations | nindent 4 }}\n  {{- end }}\nspec:\n  replicas: {{ .Values.replicaCount | default 1 }}\n  strategy:\n    type: Recreate\n  selector:\n    matchLabels:\n      {{- include \"code-server.selectorLabels\" . | nindent 6 }}\n  template:\n    metadata:\n      labels:\n        {{- include \"code-server.selectorLabels\" . | nindent 8 }}\n      {{- if .Values.podAnnotations }}\n      annotations: {{- toYaml .Values.podAnnotations | nindent 8 }}\n      {{- end }}\n    spec:\n      imagePullSecrets: {{- toYaml .Values.imagePullSecrets | nindent 8 }}\n      {{- if .Values.hostnameOverride }}\n      hostname: {{ .Values.hostnameOverride }}\n      {{- end }}\n      {{- if .Values.priorityClassName }}\n      priorityClassName: {{ .Values.priorityClassName }}\n      {{- end }}\n      {{- if .Values.securityContext.enabled }}\n      securityContext:\n        fsGroup: {{ .Values.securityContext.fsGroup }}\n      {{- end }}\n      {{- if or (and .Values.volumePermissions.enabled .Values.persistence.enabled) .Values.extraInitContainers }}\n      initContainers:\n      {{- if and .Values.volumePermissions.enabled .Values.persistence.enabled }}\n      - name: init-chmod-data\n        image: busybox:latest\n        imagePullPolicy: IfNotPresent\n        command:\n          - sh\n          - -c\n          - |\n            chown -R {{ .Values.securityContext.runAsUser }}:{{ .Values.securityContext.fsGroup }} /home/coder\n        securityContext:\n          runAsUser: {{ .Values.volumePermissions.securityContext.runAsUser }}\n        volumeMounts:\n        - name: data\n          mountPath: /home/coder\n      {{- end }}\n{{- if .Values.extraInitContainers }}\n{{ tpl .Values.extraInitContainers . | indent 6}}\n{{- end }}\n      {{- end }}\n      containers:\n{{- if .Values.extraContainers }}\n{{ tpl .Values.extraContainers . | indent 8}}\n{{- end }}\n        - name: {{ .Chart.Name }}\n          image: \"{{ .Values.image.repository }}:{{ .Values.image.tag }}\"\n          imagePullPolicy: {{ .Values.image.pullPolicy }}\n          {{- if .Values.securityContext.enabled }}\n          securityContext:\n            runAsUser: {{ .Values.securityContext.runAsUser }}\n          {{- end }}\n          {{- if .Values.lifecycle.enabled }}\n          lifecycle:\n            {{- if .Values.lifecycle.postStart }}\n            postStart:\n              {{ toYaml .Values.lifecycle.postStart | nindent 14 }}\n            {{- end }}\n            {{- if .Values.lifecycle.preStop }}\n            preStop:\n              {{ toYaml .Values.lifecycle.preStop | nindent 14 }}\n            {{- end }}\n          {{- end }}\n          env:\n        {{- if .Values.extraVars }}\n{{ toYaml .Values.extraVars | indent 10 }}\n        {{- end }}\n          - name: PASSWORD\n            valueFrom:\n              secretKeyRef:\n              {{- if .Values.existingSecret }}\n                name: {{ .Values.existingSecret }}\n              {{- else }}\n                name: {{ template \"code-server.fullname\" . }}\n              {{- end }}\n                key: password\n        {{- if .Values.extraArgs }}\n          args:\n{{ toYaml .Values.extraArgs | indent 10 }}\n        {{- end }}\n          volumeMounts:\n          - name: data\n            mountPath: /home/coder\n          {{- range .Values.extraConfigmapMounts }}\n          - name: {{ .name }}\n            mountPath: {{ .mountPath }}\n            subPath: {{ .subPath | default \"\" }}\n            readOnly: {{ .readOnly }}\n          {{- end }}\n          {{- range .Values.extraSecretMounts }}\n          - name: {{ .name }}\n            mountPath: {{ .mountPath }}\n            subPath: {{ .subPath | default \"\" }}\n            readOnly: {{ .readOnly }}\n          {{- end }}\n          {{- range .Values.extraVolumeMounts }}\n          - name: {{ .name }}\n            mountPath: {{ .mountPath }}\n            subPath: {{ .subPath | default \"\" }}\n            readOnly: {{ .readOnly }}\n          {{- end }}\n          ports:\n            - name: http\n              containerPort: 8080\n              protocol: TCP\n          {{- range .Values.extraPorts }}\n            - name: {{ .name }}\n              containerPort: {{ .port }}\n              protocol: {{ .protocol }}\n          {{- end }}\n          {{- if ne .Values.livenessProbe.enabled false }}\n          livenessProbe:\n            httpGet:\n              path: /healthz\n              port: http\n          {{- end }}\n          {{- if ne .Values.readinessProbe.enabled false }}\n          readinessProbe:\n            httpGet:\n              path: /healthz\n              port: http\n          {{- end }}\n          resources:\n            {{- toYaml .Values.resources | nindent 12 }}\n      {{- with .Values.nodeSelector }}\n      nodeSelector:\n        {{- toYaml . | nindent 8 }}\n      {{- end }}\n    {{- with .Values.affinity }}\n      affinity:\n        {{- tpl . $ | nindent 8 }}\n    {{- end }}\n    {{- with .Values.tolerations }}\n      tolerations:\n        {{- toYaml . | nindent 8 }}\n    {{- end }}\n      serviceAccountName: {{ template \"code-server.serviceAccountName\" . }}\n      volumes:\n      - name: data\n      {{- if .Values.persistence.enabled }}\n        {{- if not .Values.persistence.hostPath }}\n        persistentVolumeClaim:\n          claimName: {{ .Values.persistence.existingClaim | default (include \"code-server.fullname\" .) }}\n        {{- else }}\n        hostPath:\n          path: {{ .Values.persistence.hostPath }}\n          type: Directory\n        {{- end -}}\n      {{- else }}\n        emptyDir: {}\n      {{- end -}}\n      {{- range .Values.extraSecretMounts }}\n      - name: {{ .name }}\n        secret:\n          secretName: {{ .secretName }}\n          defaultMode: {{ .defaultMode }}\n      {{- end }}\n      {{- range .Values.extraConfigmapMounts }}\n      - name: {{ .name }}\n        configMap:\n          name: {{ .configMap }}\n          defaultMode: {{ .defaultMode }}\n      {{- end }}\n      {{- range .Values.extraVolumeMounts }}\n      - name: {{ .name }}\n        {{- if .existingClaim }}\n        persistentVolumeClaim:\n          claimName: {{ .existingClaim }}\n        {{- else if .hostPath }}\n        hostPath:\n          path: {{ .hostPath }}\n          type: Directory\n        {{- else }}\n        emptyDir:\n          {{- toYaml .emptyDir | nindent 10 }}\n        {{- end }}\n      {{- end }}\n"
  },
  {
    "path": "ci/helm-chart/templates/ingress.yaml",
    "content": "{{- if .Values.ingress.enabled -}}\n{{- $fullName := include \"code-server.fullname\" . -}}\n{{- $svcPort := .Values.service.port -}}\n{{- if semverCompare \">=1.19-0\" $.Capabilities.KubeVersion.GitVersion -}}\napiVersion: networking.k8s.io/v1\n{{- else if semverCompare \">=1.14-0\" .Capabilities.KubeVersion.GitVersion -}}\napiVersion: networking.k8s.io/v1beta1\n{{- else -}}\napiVersion: extensions/v1beta1\n{{- end }}\nkind: Ingress\nmetadata:\n  name: {{ $fullName }}\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\n  {{- with .Values.ingress.annotations }}\n  annotations:\n    {{- toYaml . | nindent 4 }}\n  {{- end }}\nspec:\n  {{- if .Values.ingress.ingressClassName }}\n  ingressClassName: {{ .Values.ingress.ingressClassName }}\n  {{- end }}\n  {{- if .Values.ingress.tls }}\n  tls:\n    {{- range .Values.ingress.tls }}\n    - hosts:\n        {{- range .hosts }}\n        - {{ . | quote }}\n        {{- end }}\n      secretName: {{ .secretName }}\n    {{- end }}\n  {{- end }}\n  rules:\n  {{- if semverCompare \">=1.19-0\" $.Capabilities.KubeVersion.GitVersion -}}\n    {{- range .Values.ingress.hosts }}\n    - host: {{ .host | quote }}\n      http:\n        paths:\n          {{- range .paths }}\n          - path: {{ . }}\n            pathType: Prefix\n            backend:\n              service:\n                name: {{ $fullName }}\n                port: \n                  number: {{ $svcPort }}\n          {{- end }}\n    {{- end }}\n  {{- else -}}\n    {{- range .Values.ingress.hosts }}\n    - host: {{ .host | quote }}\n      http:\n        paths:\n          {{- range .paths }}\n          - path: {{ . }}\n            backend:\n              serviceName: {{ $fullName }}\n              servicePort: {{ $svcPort }}\n          {{- end }}\n    {{- end }}\n  {{- end }}\n{{- end }}"
  },
  {
    "path": "ci/helm-chart/templates/pvc.yaml",
    "content": "{{- if and (and .Values.persistence.enabled (not .Values.persistence.existingClaim)) (not .Values.persistence.hostPath) }}\nkind: PersistentVolumeClaim\napiVersion: v1\nmetadata:\n  name: {{ include \"code-server.fullname\" . }}\n  namespace: {{ .Release.Namespace }}\n{{- with .Values.persistence.annotations  }}\n  annotations:\n{{ toYaml . | indent 4 }}\n{{- end }}\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\nspec:\n  accessModes:\n    - {{ .Values.persistence.accessMode | quote }}\n  resources:\n    requests:\n      storage: {{ .Values.persistence.size | quote }}\n{{- if .Values.persistence.storageClass }}\n{{- if (eq \"-\" .Values.persistence.storageClass) }}\n  storageClassName: \"\"\n{{- else }}\n  storageClassName: \"{{ .Values.persistence.storageClass }}\"\n{{- end }}\n{{- end }}\n{{- end }}\n"
  },
  {
    "path": "ci/helm-chart/templates/secrets.yaml",
    "content": "{{- if not .Values.existingSecret }}\napiVersion: v1\nkind: Secret\nmetadata:\n  name: {{ include \"code-server.fullname\" . }}\n  annotations:\n    \"helm.sh/hook\": \"pre-install\"\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\ntype: Opaque\ndata:\n  {{- if .Values.password }}\n  password: \"{{ .Values.password | b64enc }}\"\n  {{- else }}\n  password: \"{{ randAlphaNum 24 | b64enc }}\"\n  {{- end }}\n{{- end }}\n"
  },
  {
    "path": "ci/helm-chart/templates/service.yaml",
    "content": "apiVersion: v1\nkind: Service\nmetadata:\n  name: {{ include \"code-server.fullname\" . }}\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\nspec:\n  type: {{ .Values.service.type }}\n  ports:\n    - port: {{ .Values.service.port }}\n      targetPort: http\n      protocol: TCP\n      name: http\n  {{- range .Values.extraPorts }}\n    - port: {{ .port }}\n      targetPort: {{ .port }}\n      protocol: {{ .protocol }}\n      name: {{ .name }}\n  {{- end }}\n  selector:\n    app.kubernetes.io/name: {{ include \"code-server.name\" . }}\n    app.kubernetes.io/instance: {{ .Release.Name }}\n"
  },
  {
    "path": "ci/helm-chart/templates/serviceaccount.yaml",
    "content": "{{- if or .Values.serviceAccount.create -}}\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\n  name: {{ template \"code-server.serviceAccountName\" . }}\n{{- end -}}\n"
  },
  {
    "path": "ci/helm-chart/templates/tests/test-connection.yaml",
    "content": "apiVersion: v1\nkind: Pod\nmetadata:\n  name: \"{{ include \"code-server.fullname\" . }}-test-connection\"\n  labels:\n    {{- include \"code-server.labels\" . | nindent 4 }}\n  annotations:\n    \"helm.sh/hook\": test\nspec:\n  containers:\n    - name: wget\n      image: busybox\n      command: ['wget']\n      args:  ['{{ include \"code-server.fullname\" . }}:{{ .Values.service.port }}/healthz']\n  restartPolicy: Never\n"
  },
  {
    "path": "ci/helm-chart/values.yaml",
    "content": "# Default values for code-server.\n# This is a YAML-formatted file.\n# Declare variables to be passed into your templates.\n\nreplicaCount: 1\n\nimage:\n  repository: codercom/code-server\n  tag: '4.109.5'\n  pullPolicy: Always\n\n# Specifies one or more secrets to be used when pulling images from a\n# private container repository\n# https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry\nimagePullSecrets: []\n#  - name: registry-creds\n\nnameOverride: \"\"\nfullnameOverride: \"\"\nhostnameOverride: \"\"\n\n# The existing secret to use for code-server authentication in the frontend. the password is stored in the secret under the key `password`\n# existingSecret: \"\"\n\nserviceAccount:\n  # Specifies whether a service account should be created\n  create: true\n  # Annotations to add to the service account\n  annotations: {}\n  # The name of the service account to use.\n  # If not set and create is true, a name is generated using the fullname template\n  name: \"\"\n\n# Specifies annotations for deployment\nannotations: {}\n\npodAnnotations: {}\n\npodSecurityContext: {}\n  # fsGroup: 2000\n\npriorityClassName: \"\"\n\nservice:\n  type: ClusterIP\n  port: 8080\n\ningress:\n  enabled: false\n  #annotations:\n  #  kubernetes.io/tls-acme: \"true\"\n  #hosts:\n  #  - host: code-server.example.loc\n  #    paths:\n  #      - /\n  ingressClassName: \"\"\n  #tls:\n  #  - secretName: code-server\n  #    hosts:\n  #      - code-server.example.loc\n\n# Optional additional arguments\nextraArgs: []\n  # These are the arguments normally passed to code-server; run\n  # code-server --help for a list of available options.\n  #\n  # Each argument and parameter must have its own entry; if you use\n  # --param value on the command line, then enter it here as:\n  #\n  # - --param\n  # - value\n  #\n  # If you receive an error like \"Unknown option --param value\", it may be\n  # because both the parameter and value are specified as a single argument,\n  # rather than two separate arguments (e.g. \"- --param value\" on a line).\n\n# Optional additional environment variables\nextraVars: []\n#  - name: DISABLE_TELEMETRY\n#    value: \"true\"\n# if dind is desired:\n#  - name: DOCKER_HOST\n#    value: \"tcp://localhost:2376\"\n\n##\n## Init containers parameters:\n## volumePermissions: Change the owner of the persist volume mountpoint to RunAsUser:fsGroup\n##\nvolumePermissions:\n  enabled: true\n  securityContext:\n    runAsUser: 0\n\n## Pod Security Context\n## ref: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/\n##\nsecurityContext:\n  enabled: true\n  fsGroup: 1000\n  runAsUser: 1000\n\nresources: {}\n  # We usually recommend not to specify default resources and to leave this as a conscious\n  # choice for the user. This also increases chances charts run on environments with little\n  # resources, such as Minikube. If you do want to specify resources, uncomment the following\n  # lines, adjust them as necessary, and remove the curly braces after 'resources:'.\n  # limits:\n  #   cpu: 100m\n  #   memory: 128Mi\n  # requests:\n  #  cpu: 100m\n  #  memory: 1000Mi\n\nlivenessProbe:\n  enabled: true\n\nreadinessProbe:\n  enabled: true\n\nnodeSelector: {}\n\ntolerations: []\n\naffinity: {}\n\n## Persist data to a persistent volume\npersistence:\n  enabled: true\n  ## code-server data Persistent Volume Storage Class\n  ## If defined, storageClassName: <storageClass>\n  ## If set to \"-\", storageClassName: \"\", which disables dynamic provisioning\n  ## If undefined (the default) or set to null, no storageClassName spec is\n  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on\n  ##   GKE, AWS & OpenStack)\n  ##\n  # storageClass: \"-\"\n  accessMode: ReadWriteOnce\n  size: 10Gi\n  annotations: {}\n  # existingClaim: \"\"\n  # hostPath: /data\n\nlifecycle:\n  enabled: false\n  # postStart:\n  #  exec:\n  #    command:\n  #      - /bin/bash\n  #      - -c\n  #      - curl -s -L SOME_SCRIPT | bash\n\n  # for dind, the following may be helpful\n  # postStart:\n  #   exec:\n  #     command:\n  #       - /bin/sh\n  #       - -c\n  #       - |\n  #         sudo apt-get update \\\n  #           && sudo apt-get install -y docker.io\n\n## Enable an Specify container in extraContainers.\n## This is meant to allow adding code-server dependencies, like docker-dind.\nextraContainers: |\n# If docker-dind is used, DOCKER_HOST env is mandatory to set in \"extraVars\"\n# - name: docker-dind\n#   image: docker:28.3.2-dind\n#   imagePullPolicy: IfNotPresent\n#   resources:\n#     requests:\n#       cpu: 1\n#       ephemeral-storage: \"50Gi\"\n#       memory: 10Gi\n#   securityContext:\n#     privileged: true\n#     procMount: Default\n#   env:\n#     - name: DOCKER_TLS_CERTDIR\n#       value: \"\" # disable TLS setup\n#   command:\n#     - dockerd\n#     - --host=unix:///var/run/docker.sock\n#     - --host=tcp://0.0.0.0:2376\n\n\nextraInitContainers: |\n# - name: customization\n#   image: {{ .Values.image.repository }}:{{ .Values.image.tag }}\n#   imagePullPolicy: IfNotPresent\n#   env:\n#     - name: SERVICE_URL\n#       value: https://open-vsx.org/vscode/gallery\n#     - name: ITEM_URL\n#       value: https://open-vsx.org/vscode/item\n#   command:\n#     - sh\n#     - -c\n#     - |\n#       code-server --install-extension ms-python.python\n#       code-server --install-extension golang.Go\n#   volumeMounts:\n#     - name: data\n#       mountPath: /home/coder\n\n## Additional code-server secret mounts\nextraSecretMounts: []\n  # - name: secret-files\n  #   mountPath: /etc/secrets\n  #   subPath: private.key # (optional)\n  #   secretName: code-server-secret-files\n  #   readOnly: true\n\n## Additional code-server volume mounts\nextraVolumeMounts: []\n  # - name: extra-volume\n  #   mountPath: /mnt/volume\n  #   readOnly: true\n  #   existingClaim: volume-claim\n  #   hostPath: \"\"\n  #   emptyDir: {}\n\nextraConfigmapMounts: []\n  # - name: certs-configmap\n  #   mountPath: /etc/code-server/ssl/\n  #   subPath: certificates.crt # (optional)\n  #   configMap: certs-configmap\n  #   readOnly: true\n\nextraPorts: []\n  # - name: minecraft\n  #   port: 25565\n  #   protocol: tcp\n"
  },
  {
    "path": "ci/lib.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\npushd() {\n  builtin pushd \"$@\" > /dev/null\n}\n\npopd() {\n  builtin popd > /dev/null\n}\n\nvscode_version() {\n  jq -r .version lib/vscode/package.json\n}\n\nos() {\n  osname=$(uname | tr '[:upper:]' '[:lower:]')\n  case $osname in\n    linux)\n      # Alpine's ldd doesn't have a version flag but if you use an invalid flag\n      # (like --version) it outputs the version to stderr and exits with 1.\n      # TODO: Better to check /etc/os-release; see ../install.sh.\n      ldd_output=$(ldd --version 2>&1 || true)\n      if echo \"$ldd_output\" | grep -iq musl; then\n        osname=\"alpine\"\n      fi\n      ;;\n    darwin) osname=\"macos\" ;;\n    cygwin* | mingw*) osname=\"windows\" ;;\n  esac\n  echo \"$osname\"\n}\n\narch() {\n  cpu=\"$(uname -m)\"\n  case \"$cpu\" in\n    aarch64) cpu=arm64 ;;\n    x86_64) cpu=amd64 ;;\n  esac\n  echo \"$cpu\"\n}\n\nrsync() {\n  command rsync -a --del \"$@\"\n}\n\nARCH=\"$(arch)\"\nexport ARCH\nOS=$(os)\nexport OS\n\n# RELEASE_PATH is the destination directory for the release from the root.\n# Defaults to release\nRELEASE_PATH=\"${RELEASE_PATH-release}\"\n"
  },
  {
    "path": "ci/release-image/Dockerfile",
    "content": "# syntax=docker/dockerfile:experimental\n\nARG BASE=debian:12\nFROM scratch AS packages\nCOPY release-packages/code-server*.deb /tmp/\n\nFROM $BASE\n\nRUN apt-get update \\\n  && apt-get install -y \\\n    curl \\\n    dumb-init \\\n    git \\\n    git-lfs \\\n    htop \\\n    locales \\\n    lsb-release \\\n    man-db \\\n    nano \\\n    openssh-client \\\n    procps \\\n    sudo \\\n    vim-tiny \\\n    wget \\\n    zsh \\\n  && git lfs install \\\n  && rm -rf /var/lib/apt/lists/*\n\n# https://wiki.debian.org/Locale#Manually\nRUN sed -i \"s/# en_US.UTF-8/en_US.UTF-8/\" /etc/locale.gen \\\n  && locale-gen\nENV LANG=en_US.UTF-8\n\nRUN if grep -q 1000 /etc/passwd; then \\\n    userdel -r \"$(id -un 1000)\"; \\\n  fi \\\n  && adduser --gecos '' --disabled-password coder \\\n  && echo \"coder ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/nopasswd\n\nRUN ARCH=\"$(dpkg --print-architecture)\" \\\n  && curl -fsSL \"https://github.com/boxboat/fixuid/releases/download/v0.6.0/fixuid-0.6.0-linux-$ARCH.tar.gz\" | tar -C /usr/local/bin -xzf - \\\n  && chown root:root /usr/local/bin/fixuid \\\n  && chmod 4755 /usr/local/bin/fixuid \\\n  && mkdir -p /etc/fixuid \\\n  && printf \"user: coder\\ngroup: coder\\n\" > /etc/fixuid/config.yml\n\nCOPY ci/release-image/entrypoint.sh /usr/bin/entrypoint.sh\nRUN --mount=from=packages,src=/tmp,dst=/tmp/packages dpkg -i /tmp/packages/code-server*$(dpkg --print-architecture).deb\n\n# Allow users to have scripts run on container startup to prepare workspace.\n# https://github.com/coder/code-server/issues/5177\nENV ENTRYPOINTD=${HOME}/entrypoint.d\n\nEXPOSE 8080\n# This way, if someone sets $DOCKER_USER, docker-exec will still work as\n# the uid will remain the same. note: only relevant if -u isn't passed to\n# docker-run.\nUSER 1000\nENV USER=coder\nWORKDIR /home/coder\nENTRYPOINT [\"/usr/bin/entrypoint.sh\", \"--bind-addr\", \"0.0.0.0:8080\", \".\"]\n"
  },
  {
    "path": "ci/release-image/Dockerfile.fedora",
    "content": "# syntax=docker/dockerfile:experimental\n\nARG BASE=fedora:39\nFROM scratch AS packages\nCOPY release-packages/code-server*.rpm /tmp/\n\nFROM $BASE\n\nRUN dnf update -y \\\n    && dnf install -y \\\n    curl \\\n    git \\\n    git-lfs \\\n    htop \\\n    nano \\\n    openssh-clients \\\n    procps \\\n    wget \\\n    zsh \\\n    dumb-init \\\n    glibc-langpack-en \\\n    && rm -rf /var/cache/dnf\nRUN git lfs install\n\nENV LANG=en_US.UTF-8\nRUN echo 'LANG=\"en_US.UTF-8\"' > /etc/locale.conf\n\nRUN useradd -u 1000 coder && echo \"coder ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/nopasswd\n\nRUN ARCH=\"$(uname -m | sed 's/x86_64/amd64/g' | sed 's/aarch64/arm64/g')\" \\\n  && curl -fsSL \"https://github.com/boxboat/fixuid/releases/download/v0.6.0/fixuid-0.6.0-linux-$ARCH.tar.gz\" | tar -C /usr/local/bin -xzf - \\\n  && chown root:root /usr/local/bin/fixuid \\\n  && chmod 4755 /usr/local/bin/fixuid \\\n  && mkdir -p /etc/fixuid \\\n  && printf \"user: coder\\ngroup: coder\\n\" > /etc/fixuid/config.yml\n\nCOPY ci/release-image/entrypoint.sh /usr/bin/entrypoint.sh\nRUN --mount=from=packages,src=/tmp,dst=/tmp/packages rpm -i /tmp/packages/code-server*$(uname -m | sed 's/x86_64/amd64/g' | sed 's/aarch64/arm64/g').rpm\n\n# Allow users to have scripts run on container startup to prepare workspace.\n# https://github.com/coder/code-server/issues/5177\nENV ENTRYPOINTD=${HOME}/entrypoint.d\n\nEXPOSE 8080\n# This way, if someone sets $DOCKER_USER, docker-exec will still work as\n# the uid will remain the same. note: only relevant if -u isn't passed to\n# docker-run.\nUSER 1000\nENV USER=coder\nWORKDIR /home/coder\nENTRYPOINT [\"/usr/bin/entrypoint.sh\", \"--bind-addr\", \"0.0.0.0:8080\", \".\"]\n"
  },
  {
    "path": "ci/release-image/Dockerfile.opensuse",
    "content": "# syntax=docker/dockerfile:experimental\n\nARG BASE=opensuse/tumbleweed\nFROM scratch AS packages\nCOPY release-packages/code-server*.rpm /tmp/\n\nFROM $BASE\n\nRUN zypper dup -y \\\n    && zypper in -y \\\n    curl \\\n    git \\\n    git-lfs \\\n    htop \\\n    nano \\\n    openssh-clients \\\n    procps \\\n    wget \\\n    zsh \\\n    sudo \\\n    catatonit \\\n    && rm -rf /var/cache/zypp /var/cache/zypper\nRUN git lfs install\n\nENV LANG=en_US.UTF-8\nRUN echo 'LANG=\"en_US.UTF-8\"' > /etc/locale.conf\n\nRUN useradd -u 1000 coder && echo \"coder ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/nopasswd\n\nRUN ARCH=\"$(uname -m | sed 's/x86_64/amd64/g' | sed 's/aarch64/arm64/g')\" \\\n  && curl -fsSL \"https://github.com/boxboat/fixuid/releases/download/v0.6.0/fixuid-0.6.0-linux-$ARCH.tar.gz\" | tar -C /usr/local/bin -xzf - \\\n  && chown root:root /usr/local/bin/fixuid \\\n  && chmod 4755 /usr/local/bin/fixuid \\\n  && mkdir -p /etc/fixuid \\\n  && printf \"user: coder\\ngroup: coder\\n\" > /etc/fixuid/config.yml\n\nCOPY ci/release-image/entrypoint-catatonit.sh /usr/bin/entrypoint-catatonit.sh\nRUN --mount=from=packages,src=/tmp,dst=/tmp/packages rpm -i /tmp/packages/code-server*$(uname -m | sed 's/x86_64/amd64/g' | sed 's/aarch64/arm64/g').rpm\n\n# Allow users to have scripts run on container startup to prepare workspace.\n# https://github.com/coder/code-server/issues/5177\nENV ENTRYPOINTD=${HOME}/entrypoint.d\n\nEXPOSE 8080\n# This way, if someone sets $DOCKER_USER, docker-exec will still work as\n# the uid will remain the same. note: only relevant if -u isn't passed to\n# docker-run.\nUSER 1000\nENV USER=coder\nWORKDIR /home/coder\nENTRYPOINT [\"/usr/bin/entrypoint-catatonit.sh\", \"--bind-addr\", \"0.0.0.0:8080\", \".\"]\n"
  },
  {
    "path": "ci/release-image/docker-bake.hcl",
    "content": "# Use this file from the top of the repo, with `-f ci/release-image/docker-bake.hcl`\n\n# Uses env var VERSION if set;\n# normally, this is set by ci/lib.sh\nvariable \"VERSION\" {\n    default = \"latest\"\n}\n\nvariable \"DOCKER_REGISTRY\" {\n    default = \"docker.io/codercom/code-server\"\n}\n\nvariable \"GITHUB_REGISTRY\" {\n    default = \"ghcr.io/coder/code-server\"\n}\n\ngroup \"default\" {\n    targets = [\n        \"code-server-debian-12\",\n        \"code-server-ubuntu-focal\",\n        \"code-server-ubuntu-noble\",\n        \"code-server-fedora-39\",\n        \"code-server-opensuse-tumbleweed\",\n    ]\n}\n\nfunction \"prepend_hyphen_if_not_null\" {\n    params = [tag]\n    result = notequal(\"\",\"${tag}\") ? \"-${tag}\" : \"${tag}\"\n}\n\n# use empty tag (tag=\"\") to generate default tags\nfunction \"gen_tags\" {\n    params = [registry, tag]\n    result = notequal(\"\",\"${registry}\") ? [\n        notequal(\"\", \"${tag}\") ? \"${registry}:${tag}\" : \"${registry}:latest\",\n        notequal(\"latest\",VERSION) ? \"${registry}:${VERSION}${prepend_hyphen_if_not_null(tag)}\" : \"\",\n    ] : []\n}\n\n# helper function to generate tags for docker registry and github registry.\n# set (DOCKER|GITHUB)_REGISTRY=\"\" to disable corresponding registry\nfunction \"gen_tags_for_docker_and_ghcr\" {\n    params = [tag]\n    result = concat(\n        gen_tags(\"${DOCKER_REGISTRY}\", \"${tag}\"),\n        gen_tags(\"${GITHUB_REGISTRY}\", \"${tag}\"),\n    )\n}\n\ntarget \"code-server-debian-12\" {\n    dockerfile = \"ci/release-image/Dockerfile\"\n    tags = concat(\n        gen_tags_for_docker_and_ghcr(\"\"),\n        gen_tags_for_docker_and_ghcr(\"debian\"),\n        gen_tags_for_docker_and_ghcr(\"bookworm\"),\n    )\n    platforms = [\"linux/amd64\", \"linux/arm64\"]\n}\n\ntarget \"code-server-ubuntu-focal\" {\n    dockerfile = \"ci/release-image/Dockerfile\"\n    tags = concat(\n        gen_tags_for_docker_and_ghcr(\"ubuntu\"),\n        gen_tags_for_docker_and_ghcr(\"focal\"),\n    )\n    args = {\n        BASE = \"ubuntu:focal\"\n    }\n    platforms = [\"linux/amd64\", \"linux/arm64\"]\n}\n\ntarget \"code-server-ubuntu-noble\" {\n    dockerfile = \"ci/release-image/Dockerfile\"\n    tags = concat(\n        gen_tags_for_docker_and_ghcr(\"noble\"),\n    )\n    args = {\n        BASE = \"ubuntu:noble\"\n    }\n    platforms = [\"linux/amd64\", \"linux/arm64\"]\n}\n\ntarget \"code-server-fedora-39\" {\n    dockerfile = \"ci/release-image/Dockerfile.fedora\"\n    tags = concat(\n        gen_tags_for_docker_and_ghcr(\"fedora\"),\n        gen_tags_for_docker_and_ghcr(\"39\"),\n    )\n    args = {\n        BASE = \"fedora:39\"\n    }\n    platforms = [\"linux/amd64\", \"linux/arm64\"]\n}\n\ntarget \"code-server-opensuse-tumbleweed\" {\n    dockerfile = \"ci/release-image/Dockerfile.opensuse\"\n    tags = concat(\n        gen_tags_for_docker_and_ghcr(\"opensuse\"),\n        gen_tags_for_docker_and_ghcr(\"tumbleweed\"),\n    )\n    args = {\n        BASE = \"opensuse/tumbleweed\"\n    }\n    platforms = [\"linux/amd64\", \"linux/arm64\"]\n}\n"
  },
  {
    "path": "ci/release-image/entrypoint-catatonit.sh",
    "content": "#!/bin/sh\nset -eu\n\n# We do this first to ensure sudo works below when renaming the user.\n# Otherwise the current container UID may not exist in the passwd database.\neval \"$(fixuid -q)\"\n\nif [ \"${DOCKER_USER-}\" ]; then\n  USER=\"$DOCKER_USER\"\n  if [ \"$DOCKER_USER\" != \"$(whoami)\" ]; then\n    echo \"$DOCKER_USER ALL=(ALL) NOPASSWD:ALL\" | sudo tee -a /etc/sudoers.d/nopasswd > /dev/null\n    # Unfortunately we cannot change $HOME as we cannot move any bind mounts\n    # nor can we bind mount $HOME into a new home as that requires a privileged container.\n    sudo usermod --login \"$DOCKER_USER\" coder\n    sudo groupmod -n \"$DOCKER_USER\" coder\n\n    sudo sed -i \"/coder/d\" /etc/sudoers.d/nopasswd\n  fi\nfi\n\n# Allow users to have scripts run on container startup to prepare workspace.\n# https://github.com/coder/code-server/issues/5177\nif [ -d \"${ENTRYPOINTD}\" ]; then\n  find \"${ENTRYPOINTD}\" -type f -executable -print -exec {} \\;\nfi\n\nexec catatonit -- /usr/bin/code-server \"$@\"\n"
  },
  {
    "path": "ci/release-image/entrypoint.sh",
    "content": "#!/bin/sh\nset -eu\n\n# We do this first to ensure sudo works below when renaming the user.\n# Otherwise the current container UID may not exist in the passwd database.\neval \"$(fixuid -q)\"\n\nif [ \"${DOCKER_USER-}\" ]; then\n  USER=\"$DOCKER_USER\"\n  if [ -z \"$(id -u \"$DOCKER_USER\" 2>/dev/null)\" ]; then\n    echo \"$DOCKER_USER ALL=(ALL) NOPASSWD:ALL\" | sudo tee -a /etc/sudoers.d/nopasswd > /dev/null\n    # Unfortunately we cannot change $HOME as we cannot move any bind mounts\n    # nor can we bind mount $HOME into a new home as that requires a privileged container.\n    sudo usermod --login \"$DOCKER_USER\" coder\n    sudo groupmod -n \"$DOCKER_USER\" coder\n\n    sudo sed -i \"/coder/d\" /etc/sudoers.d/nopasswd\n  fi\nfi\n\n# Allow users to have scripts run on container startup to prepare workspace.\n# https://github.com/coder/code-server/issues/5177\nif [ -d \"${ENTRYPOINTD}\" ]; then\n  find \"${ENTRYPOINTD}\" -type f -executable -print -exec {} \\;\nfi\n\nexec dumb-init /usr/bin/code-server \"$@\"\n"
  },
  {
    "path": "ci/steps/brew-bump.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  # Only sourcing this so we get access to $VERSION\n  source ./ci/lib.sh\n  source ./ci/steps/steps-lib.sh\n\n  echo \"Checking environment variables\"\n\n  # We need VERSION to bump the brew formula\n  if ! is_env_var_set \"VERSION\"; then\n    echo \"VERSION is not set\"\n    exit 1\n  fi\n\n  # We need HOMEBREW_GITHUB_API_TOKEN to push up commits\n  if ! is_env_var_set \"HOMEBREW_GITHUB_API_TOKEN\"; then\n    echo \"HOMEBREW_GITHUB_API_TOKEN is not set\"\n    exit 1\n  fi\n\n  # Find the docs for bump-formula-pr here\n  # https://github.com/Homebrew/brew/blob/master/Library/Homebrew/dev-cmd/bump-formula-pr.rb#L18\n  local output\n  if ! output=$(brew bump-formula-pr --version=\"${VERSION}\" code-server --no-browse --no-audit --message=\"PR opened by @${GITHUB_ACTOR}\" 2>&1); then\n    if [[ $output == *\"Duplicate PRs should not be opened\"* ]]; then\n      echo \"$VERSION is already submitted\"\n      exit 0\n    else\n      echo \"$output\"\n      exit 1\n    fi\n  fi\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/steps/docker-buildx-push.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n  # NOTE@jsjoeio - this script assumes VERSION exists as an\n  # environment variable.\n\n  # NOTE@jsjoeio - this script assumes that you've downloaded\n  # the release-packages artifact to ./release-packages before\n  # running this docker buildx step\n  docker buildx bake -f ci/release-image/docker-bake.hcl --push\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/steps/publish-npm.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\n\nmain() {\n  cd \"$(dirname \"$0\")/../..\"\n  source ./ci/lib.sh\n  source ./ci/steps/steps-lib.sh\n\n  ## Authentication tokens\n  # Needed to publish on NPM\n  if ! is_env_var_set \"NPM_TOKEN\"; then\n    echo \"NPM_TOKEN is not set. Cannot publish to npm without credentials.\"\n    exit 1\n  fi\n\n  ## Publishing Information\n  # All the variables below are used to determine how we should publish\n  # the npm package. We also use this information for bumping the version.\n  # This is because npm won't publish your package unless it's a new version.\n  # i.e. for development, we bump the version to <current version>-<pr number>-<commit sha>\n  # example: \"version\": \"4.0.1-4769-ad7b23cfe6ffd72914e34781ef7721b129a23040\"\n  # We use this to grab the PR_NUMBER\n  if ! is_env_var_set \"GITHUB_REF\"; then\n    echo \"GITHUB_REF is not set. Are you running this locally? We rely on values provided by GitHub.\"\n    exit 1\n  fi\n\n  # We use this when setting NPM_VERSION\n  if ! is_env_var_set \"GITHUB_SHA\"; then\n    echo \"GITHUB_SHA is not set. Are you running this locally? We rely on values provided by GitHub.\"\n    exit 1\n  fi\n\n  # We use this to determine the NPM_ENVIRONMENT\n  if ! is_env_var_set \"GITHUB_EVENT_NAME\"; then\n    echo \"GITHUB_EVENT_NAME is not set. Are you running this locally? We rely on values provided by GitHub.\"\n    exit 1\n  fi\n\n  # Check that we're using at least v7 of npm CLI\n  if ! command -v jq &> /dev/null; then\n    echo \"Couldn't find jq\"\n    echo \"We need this in order to modify the package.json for dev builds.\"\n    exit 1\n  fi\n\n  # This allows us to publish to npm in CI workflows\n  if [[ ${CI-} ]]; then\n    echo \"//registry.npmjs.org/:_authToken=${NPM_TOKEN}\" > ~/.npmrc\n  fi\n\n  ## Environment\n  # This string is used to determine how we should tag the npm release.\n  # Environment can be one of three choices:\n  # \"development\" - this means we tag with the PR number, allowing\n  # a developer to install this version with `npm install code-server@<pr-number>`\n  # \"staging\" - this means we tag with `beta`, allowing\n  # a developer to install this version with `npm install code-server@beta`\n  # \"production\" - this means we tag with `latest` (default), allowing\n  # a developer to install this version with `npm install code-server@latest`\n  if ! is_env_var_set \"NPM_ENVIRONMENT\"; then\n    echo \"NPM_ENVIRONMENT is not set.\"\n    echo \"Determining in script based on GITHUB environment variables.\"\n\n    if [[ \"$GITHUB_EVENT_NAME\" == 'push' && \"$GITHUB_REF\" == 'refs/heads/main' ]]; then\n      NPM_ENVIRONMENT=\"staging\"\n    else\n      NPM_ENVIRONMENT=\"development\"\n    fi\n\n  fi\n\n  # NOTE@jsjoeio - this script assumes we have the artifact downloaded on disk\n  # That happens in CI as a step before we run this.\n  # https://github.com/actions/upload-artifact/issues/38\n  tar -xzf release-npm-package/package.tar.gz\n\n  # We use this to set the name of the package in the\n  # package.json\n  PACKAGE_NAME=\"code-server\"\n\n  # NOTES:@jsjoeio\n  # We only need to run npm version for \"development\" and \"staging\".\n  # This is because our release:prep script automatically bumps the version\n  # in the package.json and we commit it as part of the release PR.\n  if [[ \"$NPM_ENVIRONMENT\" == \"production\" ]]; then\n    NPM_VERSION=\"$VERSION\"\n    # This means the npm version will be published as \"stable\"\n    # and installed when a user runs `npm install code-server`\n    NPM_TAG=\"latest\"\n  else\n    COMMIT_SHA=\"$GITHUB_SHA\"\n\n    if [[ \"$NPM_ENVIRONMENT\" == \"staging\" ]]; then\n      NPM_VERSION=\"$VERSION-beta-$COMMIT_SHA\"\n      # This means the npm version will be tagged with \"beta\"\n      # and installed when a user runs `npm install code-server@beta`\n      NPM_TAG=\"beta\"\n      PACKAGE_NAME=\"@coder/code-server-pr\"\n    fi\n\n    if [[ \"$NPM_ENVIRONMENT\" == \"development\" ]]; then\n      # Source: https://github.com/actions/checkout/issues/58#issuecomment-614041550\n      PR_NUMBER=$(echo \"$GITHUB_REF\" | awk 'BEGIN { FS = \"/\" } ; { print $3 }')\n      NPM_VERSION=\"$VERSION-$PR_NUMBER-$COMMIT_SHA\"\n      PACKAGE_NAME=\"@coder/code-server-pr\"\n      # This means the npm version will be tagged with \"<pr number>\"\n      # and installed when a user runs `npm install code-server@<pr number>`\n      NPM_TAG=\"$PR_NUMBER\"\n    fi\n\n    echo \"- tag: $NPM_TAG\"\n    echo \"- version: $NPM_VERSION\"\n    echo \"- package name: $PACKAGE_NAME\"\n    echo \"- npm environment: $NPM_ENVIRONMENT\"\n\n    # We modify the version in the package.json\n    # to be the current version + the PR number + commit SHA\n    # or we use current version + beta + commit SHA\n    # Example: \"version\": \"4.0.1-4769-ad7b23cfe6ffd72914e34781ef7721b129a23040\"\n    # Example: \"version\": \"4.0.1-beta-ad7b23cfe6ffd72914e34781ef7721b129a23040\"\n    pushd release\n    npm version \"$NPM_VERSION\"\n    # Use the development package name\n    # This is so we don't clutter the code-server versions on npm\n    # with development versions.\n    # jq can't edit in place so we must store in memory and echo\n    local contents\n    contents=\"$(jq \".name |= \\\"$PACKAGE_NAME\\\"\" package.json)\"\n    echo \"${contents}\" > package.json\n    popd\n  fi\n\n  # We need to make sure we haven't already published the version.\n  # If we get error, continue with script because we want to publish\n  # If version is valid, we check if we're publishing the same one\n  local hasVersion\n  if hasVersion=$(npm view \"$PACKAGE_NAME@$NPM_VERSION\" version 2> /dev/null) && [[ $hasVersion == \"$NPM_VERSION\" ]]; then\n    echo \"$NPM_VERSION is already published under $PACKAGE_NAME\"\n    return\n  fi\n\n  # Since the dev builds are scoped to @coder\n  # We pass --access public to ensure npm knows it's not private.\n  cd release\n  npm publish --tag \"$NPM_TAG\" --access public\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "ci/steps/steps-lib.sh",
    "content": "#!/usr/bin/env bash\n\n# This is a library which contains functions used inside ci/steps\n#\n# We separated it into it's own file so that we could easily unit test\n# these functions and helpers\n\n# Checks whether and environment variable is set.\n# Source: https://stackoverflow.com/a/62210688/3015595\nis_env_var_set() {\n  local name=\"${1:-}\"\n  if test -n \"${!name:-}\"; then\n    return 0\n  else\n    return 1\n  fi\n}\n\n# Checks whether a directory exists.\ndirectory_exists() {\n  local dir=\"${1:-}\"\n  if [[ -d \"${dir:-}\" ]]; then\n    return 0\n  else\n    return 1\n  fi\n}\n\n# Checks whether a file exists.\nfile_exists() {\n  local file=\"${1:-}\"\n  if test -f \"${file:-}\"; then\n    return 0\n  else\n    return 1\n  fi\n}\n\n# Checks whether a file is executable.\nis_executable() {\n  local file=\"${1:-}\"\n  if [ -f \"${file}\" ] && [ -r \"${file}\" ] && [ -x \"${file}\" ]; then\n    return 0\n  else\n    return 1\n  fi\n}\n"
  },
  {
    "path": "docs/CODE_OF_CONDUCT.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Contributor Covenant Code of Conduct\n\n- [Contributor Covenant Code of Conduct](#contributor-covenant-code-of-conduct)\n  - [Our Pledge](#our-pledge)\n  - [Our Standards](#our-standards)\n  - [Our Responsibilities](#our-responsibilities)\n  - [Scope](#scope)\n  - [Enforcement](#enforcement)\n  - [Attribution](#attribution)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\n# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n- Using welcoming and inclusive language\n- Being respectful of differing viewpoints and experiences\n- Gracefully accepting constructive criticism\n- Focusing on what is best for the community\n- Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n- The use of sexualized language or imagery and unwelcome sexual attention or\n  advances\n- Trolling, insulting/derogatory comments, and personal or political attacks\n- Public or private harassment\n- Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n- Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at opensource@coder.com. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "docs/CONTRIBUTING.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Contributing\n\n- [Requirements](#requirements)\n  - [Linux-specific requirements](#linux-specific-requirements)\n- [Development workflow](#development-workflow)\n  - [Version updates to Code](#version-updates-to-code)\n  - [Patching Code](#patching-code)\n  - [Build](#build)\n    - [Creating a Standalone Release](#creating-a-standalone-release)\n  - [Troubleshooting](#troubleshooting)\n    - [I see \"Forbidden access\" when I load code-server in the browser](#i-see-forbidden-access-when-i-load-code-server-in-the-browser)\n    - [\"Can only have one anonymous define call per script\"](#can-only-have-one-anonymous-define-call-per-script)\n  - [Help](#help)\n- [Test](#test)\n  - [Unit tests](#unit-tests)\n  - [Script tests](#script-tests)\n  - [Integration tests](#integration-tests)\n  - [End-to-end tests](#end-to-end-tests)\n- [Structure](#structure)\n  - [Modifications to Code](#modifications-to-code)\n  - [Currently Known Issues](#currently-known-issues)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\n## Requirements\n\nThe prerequisites for contributing to code-server are almost the same as those\nfor [VS Code](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites).\nHere is what is needed:\n\n- `node` v22.x\n- `git` v2.x or greater\n- [`git-lfs`](https://git-lfs.github.com)\n- [`npm`](https://www.npmjs.com/)\n  - Used to install JS packages and run scripts\n- [`nfpm`](https://nfpm.goreleaser.com/)\n  - Used to build `.deb` and `.rpm` packages\n- [`jq`](https://stedolan.github.io/jq/)\n  - Used to build code-server releases\n- [`gnupg`](https://gnupg.org/index.html)\n  - All commits must be signed and verified; see GitHub's [Managing commit\n    signature\n    verification](https://docs.github.com/en/github/authenticating-to-github/managing-commit-signature-verification)\n    or follow [this tutorial](https://joeprevite.com/verify-commits-on-github)\n- `quilt`\n  - Used to manage patches to Code\n- `rsync` and `unzip`\n  - Used for code-server releases\n- `bats`\n  - Used to run script unit tests\n\n### Linux-specific requirements\n\nIf you're developing code-server on Linux, make sure you have installed or\ninstall the following dependencies:\n\n```shell\nsudo apt-get install build-essential g++ libx11-dev libxkbfile-dev libsecret-1-dev libkrb5-dev python-is-python3\n```\n\nThese are required by Code. See [their Wiki](https://github.com/microsoft/vscode/wiki/How-to-Contribute#prerequisites)\nfor more information.\n\n## Development workflow\n\n1. `git clone https://github.com/coder/code-server.git` - Clone `code-server`\n2. `git submodule update --init` - Clone `vscode` submodule\n3. `quilt push -a` - Apply patches to the `vscode` submodule.\n4. `npm install` - Install dependencies\n5. `npm run watch` - Launch code-server localhost:8080. code-server will be live\n   reloaded when changes are made; the browser needs to be refreshed manually.\n\nWhen pulling down changes that include modifications to the patches you will\nneed to apply them with `quilt`. If you pull down changes that update the\n`vscode` submodule you will need to run `git submodule update --init` and\nre-apply the patches.\n\nWhen you make a change that affects people deploying the marketplace please\nupdate the changelog as part of your PR.\n\nNote that building code-server takes a very, very long time, and loading it in\nthe browser in development mode also takes a very, very long time.\n\nDisplay language (Spanish, etc) support only works in a full build; it will not\nwork in development mode.\n\nGenerally we prefer that PRs be squashed into `main` but you can rebase or merge\nif it is important to keep the individual commits (make sure to clean up the\ncommits first if you are doing this).\n\n### Version updates to Code\n\n1. Remove any patches with `quilt pop -a`.\n2. Update the `lib/vscode` submodule to the desired upstream version branch.\n   1. `cd lib/vscode && git checkout release/1.66 && cd ../..`\n   2. `git add lib && git commit -m \"chore: update to Code <version>\"`\n3. Apply the patches one at a time (`quilt push`). If the application succeeds\n   but the lines changed, update the patch with `quilt refresh`. If there are\n   conflicts, then force apply with `quilt push -f`, manually add back the\n   rejected code, then run `quilt refresh`.\n4. From the code-server **project root**, run `npm install`.\n5. Check the Node.js version that's used by Electron (which is shipped with VS\n   Code. If necessary, update our version of Node.js to match.\n\n### Patching Code\n\n1. You can go through the patch stack with `quilt push` and `quilt pop`.\n2. Create a new patch (`quilt new {name}.diff`) or use an existing patch.\n3. Add the file(s) you are patching (`quilt add [-P patch] {file}`). A file\n   **must** be added before you make changes to it.\n4. Make your changes. Patches do not need to be independent of each other but\n   each patch must result in a working code-server without any broken in-between\n   states otherwise they are difficult to test and modify.\n5. Add your changes to the patch (`quilt refresh`)\n6. Add a comment in the patch about the reason for the patch and how to\n   reproduce the behavior it fixes or adds. Every patch should have an e2e test\n   as well.\n\n### Build\n\nYou can build a full production as follows:\n\n```shell\ngit submodule update --init\nquilt push -a\nnpm install\nnpm run build\nVERSION=0.0.0 npm run build:vscode\nnpm run release\n```\n\nThis does not keep `node_modules`. If you want them to be kept, use\n`KEEP_MODULES=1 npm run release`\n\nRun your build:\n\n```shell\ncd release\nnpm install --omit=dev # Skip if you used KEEP_MODULES=1\n# Runs the built JavaScript with Node.\nnode .\n```\n\nThen, to build the release package:\n\n```shell\nnpm run release:standalone\nnpm run test:integration\nnpm run package\n```\n\n> On Linux, the currently running distro will become the minimum supported\n> version. In our GitHub Actions CI, we use CentOS 8 for maximum compatibility.\n> If you need your builds to support older distros, run the build commands\n> inside a Docker container with all the build requirements installed.\n\n#### Creating a Standalone Release\n\nPart of the build process involves creating standalone releases. At the time of\nwriting, we do this for the following platforms/architectures:\n\n- Linux amd64 (.tar.gz, .deb, and .rpm)\n- Linux arm64 (.tar.gz, .deb, and .rpm)\n- Linux arm7l (.tar.gz)\n- Linux armhf.deb\n- Linux armhf.rpm\n- macOS arm64.tar.gz\n\nCurrently, these are compiled in CI using the `npm run release:standalone`\ncommand in the `release.yaml` workflow. We then upload them to the draft release\nand distribute via GitHub Releases.\n\n### Troubleshooting\n\n#### I see \"Forbidden access\" when I load code-server in the browser\n\nThis means your patches didn't apply correctly. We have a patch to remove the\nauth from vanilla Code because we use our own.\n\nTry popping off the patches with `quilt pop -a` and reapplying with `quilt push\n-a`.\n\n#### \"Can only have one anonymous define call per script\"\n\nCode might be trying to use a dev or prod HTML in the wrong context. You can try\nre-running code-server and setting `VSCODE_DEV=1`.\n\n### Help\n\nIf you get stuck or need help, you can always start a new GitHub Discussion\n[here](https://github.com/coder/code-server/discussions). One of the maintainers\nwill respond and help you out.\n\n## Test\n\nThere are four kinds of tests in code-server:\n\n1. Unit tests\n2. Script tests\n3. Integration tests\n4. End-to-end tests\n\n### Unit tests\n\nOur unit tests are written in TypeScript and run using\n[Jest](https://jestjs.io/), the testing framework].\n\nThese live under [test/unit](../test/unit).\n\nWe use unit tests for functions and things that can be tested in isolation. The\nfile structure is modeled closely after `/src` so it's easy for people to know\nwhere test files should live.\n\n### Script tests\n\nOur script tests are written in bash and run using [bats](https://github.com/bats-core/bats-core).\n\nThese tests live under `test/scripts`.\n\nWe use these to test anything related to our scripts (most of which live under\n`ci`).\n\n### Integration tests\n\nThese are a work in progress. We build code-server and run tests with `npm run\ntest:integration`, which ensures that code-server builds work on their\nrespective platforms.\n\nOur integration tests look at components that rely on one another. For example,\ntesting the CLI requires us to build and package code-server.\n\n### End-to-end tests\n\nThe end-to-end (e2e) tests are written in TypeScript and run using\n[Playwright](https://playwright.dev/).\n\nThese live under [test/e2e](../test/e2e).\n\nBefore the e2e tests run, we run `globalSetup`, which eliminates the need to log\nin before each test by preserving the authentication state.\n\nTake a look at `codeServer.test.ts` to see how you would use it (see\n`test.use`).\n\nWe also have a model where you can create helpers to use within tests. See\n[models/CodeServer.ts](../test/e2e/models/CodeServer.ts) for an example.\n\n## Structure\n\ncode-server essentially serves as an HTTP API for logging in and starting a\nremote Code process.\n\nThe CLI code is in [src/node](../src/node) and the HTTP routes are implemented\nin [src/node/routes](../src/node/routes).\n\nMost of the meaty parts are in the Code portion of the codebase under\n[lib/vscode](../lib/vscode), which we describe next.\n\n### Modifications to Code\n\nOur modifications to Code can be found in the [patches](../patches) directory.\nWe pull in Code as a submodule pointing to an upstream release branch.\n\nIn v1 of code-server, we had Code as a submodule and used a single massive patch\nthat split the codebase into a front-end and a server. The front-end consisted\nof the UI code, while the server ran the extensions and exposed an API to the\nfront-end for file access and all UI needs.\n\nOver time, Microsoft added support to Code to run it on the web. They had made\nthe front-end open source, but not the server. As such, code-server v2 (and\nlater) uses the Code front-end and implements the server. We did this by using a\nGit subtree to fork and modify Code.\n\nMicrosoft eventually made the server open source and we were able to reduce our\nchanges significantly. Some time later we moved back to a submodule and patches\n(managed by `quilt` this time instead of the mega-patch).\n\nAs the web portion of Code continues to mature, we'll be able to shrink and\npossibly eliminate our patches. In the meantime, upgrading the Code version\nrequires us to ensure that our changes are still applied correctly and work as\nintended. In the future, we'd like to run Code unit tests against our builds to\nensure that features work as expected.\n\n> We have [extension docs](../ci/README.md) on the CI and build system.\n\nIf the functionality you're working on does NOT depend on code from Code, please\nmove it out and into code-server.\n\n### Currently Known Issues\n\n- Creating custom Code extensions and debugging them doesn't work\n- Extension profiling and tips are currently disabled\n"
  },
  {
    "path": "docs/FAQ.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# FAQ\n\n- [Questions?](#questions)\n- [How should I expose code-server to the internet?](#how-should-i-expose-code-server-to-the-internet)\n- [Can I use code-server on the iPad?](#can-i-use-code-server-on-the-ipad)\n- [How does the config file work?](#how-does-the-config-file-work)\n- [How do I make my keyboard shortcuts work?](#how-do-i-make-my-keyboard-shortcuts-work)\n- [Why can't code-server use Microsoft's extension marketplace?](#why-cant-code-server-use-microsofts-extension-marketplace)\n- [How can I request an extension that's missing from the marketplace?](#how-can-i-request-an-extension-thats-missing-from-the-marketplace)\n- [How do I install an extension?](#how-do-i-install-an-extension)\n- [How do I install an extension manually?](#how-do-i-install-an-extension-manually)\n- [How do I use my own extensions marketplace?](#how-do-i-use-my-own-extensions-marketplace)\n- [Where are extensions stored?](#where-are-extensions-stored)\n- [Where is VS Code configuration stored?](#where-is-vs-code-configuration-stored)\n- [How can I reuse my VS Code configuration?](#how-can-i-reuse-my-vs-code-configuration)\n- [How does code-server decide what workspace or folder to open?](#how-does-code-server-decide-what-workspace-or-folder-to-open)\n- [How do I access my Documents/Downloads/Desktop folders in code-server on macOS?](#how-do-i-access-my-documentsdownloadsdesktop-folders-in-code-server-on-macos)\n- [How do I direct server-side requests through a proxy?](#how-do-i-direct-server-side-requests-through-a-proxy)\n- [How do I debug issues with code-server?](#how-do-i-debug-issues-with-code-server)\n- [What is the healthz endpoint?](#what-is-the-healthz-endpoint)\n- [What is the heartbeat file?](#what-is-the-heartbeat-file)\n- [How do I change the password?](#how-do-i-change-the-password)\n- [Can I store my password hashed?](#can-i-store-my-password-hashed)\n- [Is multi-tenancy possible?](#is-multi-tenancy-possible)\n- [Can I use Docker in a code-server container?](#can-i-use-docker-in-a-code-server-container)\n- [How do I disable telemetry?](#how-do-i-disable-telemetry)\n- [What's the difference between code-server and Coder?](#whats-the-difference-between-code-server-and-coder)\n- [What's the difference between code-server and Theia?](#whats-the-difference-between-code-server-and-theia)\n- [What's the difference between code-server and OpenVSCode-Server?](#whats-the-difference-between-code-server-and-openvscode-server)\n- [What's the difference between code-server and GitHub Codespaces?](#whats-the-difference-between-code-server-and-github-codespaces)\n- [What's the difference between code-server and VS Code web?](#whats-the-difference-between-code-server-and-vs-code-web)\n- [Does code-server have any security login validation?](#does-code-server-have-any-security-login-validation)\n- [Are there community projects involving code-server?](#are-there-community-projects-involving-code-server)\n- [How do I change the port?](#how-do-i-change-the-port)\n- [How do I hide the coder/coder promotion in Help: Getting Started?](#how-do-i-hide-the-codercoder-promotion-in-help-getting-started)\n- [How do I disable the proxy?](#how-do-i-disable-the-proxy)\n- [How do I disable file download?](#how-do-i-disable-file-download)\n- [Why do web views not work?](#why-do-web-views-not-work)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\n## Questions?\n\nPlease file all questions and support requests at\n<https://github.com/coder/code-server/discussions>.\n\n## How should I expose code-server to the internet?\n\nPlease see [our instructions on exposing code-server safely to the\ninternet](./guide.md).\n\n## Can I use code-server on the iPad?\n\nSee [iPad](./ipad.md) for information on using code-server on the iPad.\n\n## How does the config file work?\n\nWhen `code-server` starts up, it creates a default config file in `~/.config/code-server/config.yaml`:\n\n```yaml\nbind-addr: 127.0.0.1:8080\nauth: password\npassword: mew...22 # Randomly generated for each config.yaml\ncert: false\n```\n\nThe default config defines the following behavior:\n\n- Listen on the loopback IP port 8080\n- Enable password authorization\n- Do not use TLS\n\nEach key in the file maps directly to a `code-server` flag (run `code-server --help` to see a listing of all the flags). Any flags passed to `code-server`\nwill take priority over the config file.\n\nYou can change the config file's location using the `--config` flag or\n`$CODE_SERVER_CONFIG` environment variable.\n\nThe default location respects `$XDG_CONFIG_HOME`.\n\n## How do I make my keyboard shortcuts work?\n\nMany shortcuts will not work by default, since they'll be \"caught\" by the browser.\n\nIf you use Chrome, you can work around this by installing the progressive web\napp (PWA):\n\n1. Start the editor\n2. Click the **plus** icon in the URL toolbar to install the PWA\n\nIf you use Firefox, you can use the appropriate extension to install PWA.\n\n1. Go to the installation [website](https://addons.mozilla.org/en-US/firefox/addon/pwas-for-firefox/) of the add-on\n2. Add the add-on to Firefox\n3. Follow the os-specific instructions on how to install the runtime counterpart\n\nFor other browsers, you'll have to remap keybindings for shortcuts to work.\n\n## Why can't code-server use Microsoft's extension marketplace?\n\nThough code-server takes the open-source core of VS Code and allows you to run\nit in the browser, it is not entirely equivalent to Microsoft's VS Code.\n\nOne major difference is in regards to extensions and the marketplace. The core\nof VS code is open source, while the marketplace and many published Microsoft\nextensions are not. Furthermore, Microsoft prohibits the use of any\nnon-Microsoft VS Code from accessing their marketplace. Per the [Terms of\nService](https://cdn.vsassets.io/v/M146_20190123.39/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf):\n\n> Marketplace Offerings are intended for use only with Visual Studio Products\n> and Services, and you may only install and use Marketplace Offerings with\n> Visual Studio Products and Services.\n\nBecause of this, we can't offer any extensions on Microsoft's marketplace.\nInstead, we use the [Open-VSX extension gallery](https://open-vsx.org), which is also used by various other forks.\nIt isn't perfect, but its getting better by the day with more and more extensions.\n\nWe also offer our own marketplace for open source extensions, but plan to\ndeprecate it at a future date and completely migrate to Open-VSX.\n\nThese are the closed-source extensions that are presently unavailable:\n\n1. [Live Share](https://visualstudio.microsoft.com/services/live-share). We may\n   implement something similar (see\n   [#33](https://github.com/coder/code-server/issues/33))\n1. [Remote Extensions (SSH, Containers,\n   WSL)](https://github.com/microsoft/vscode-remote-release). We may implement\n   these again at some point, see\n   ([#1315](https://github.com/coder/code-server/issues/1315)).\n\nFor more about the closed source portions of VS Code, see [vscodium/vscodium](https://github.com/VSCodium/vscodium#why-does-this-exist).\n\n## How can I request an extension that's missing from the marketplace?\n\nTo add an extension to Open-VSX, please see [open-vsx/publish-extensions](https://github.com/open-vsx/publish-extensions).\nWe no longer plan to add new extensions to our legacy extension gallery.\n\n## How do I install an extension?\n\nYou can install extensions from the marketplace using the extensions sidebar in\ncode-server or from the command line:\n\n```console\ncode-server --install-extension <extension id>\n# example: code-server --install-extension wesbos.theme-cobalt2\n\n# From the Coder extension marketplace\ncode-server --install-extension ms-python.python\n\n# From a downloaded VSIX on the file system\ncode-server --install-extension downloaded-ms-python.python.vsix\n```\n\n## How do I install an extension manually?\n\nIf there's an extension unavailable in the marketplace or an extension that\ndoesn't work, you can download the VSIX from its GitHub releases or build it\nyourself.\n\nOnce you have downloaded the VSIX to the remote machine, you can either:\n\n- Run the **Extensions: Install from VSIX** command in the Command Palette.\n- Run `code-server --install-extension <path to vsix>` in the terminal\n\nYou can also download extensions using the command line. For instance,\ndownloading from OpenVSX can be done like this:\n\n```shell\ncode-server --install-extension <extension id>\n```\n\n## How do I use my own extensions marketplace?\n\nIf you own a marketplace that implements the VS Code Extension Gallery API, you\ncan point code-server to it by setting `$EXTENSIONS_GALLERY`.\nThis corresponds directly with the `extensionsGallery` entry in in VS Code's `product.json`.\n\nFor example:\n\n```bash\nexport EXTENSIONS_GALLERY='{\"serviceUrl\": \"https://my-extensions/api\"}'\n```\n\nThough you can technically use Microsoft's marketplace in this manner, we\nstrongly discourage you from doing so since this is [against their Terms of Use](#why-cant-code-server-use-microsofts-extension-marketplace).\n\nFor further information, see [this\ndiscussion](https://github.com/microsoft/vscode/issues/31168#issue-244533026)\nregarding the use of the Microsoft URLs in forks, as well as [VSCodium's\ndocs](https://github.com/VSCodium/vscodium/blob/master/DOCS.md#extensions--marketplace).\n\n## Where are extensions stored?\n\nExtensions are stored in `~/.local/share/code-server/extensions` by default.\n\nOn Linux and macOS if you set the `XDG_DATA_HOME` environment variable, the\nextensions directory will be `$XDG_DATA_HOME/code-server/extensions`. In\ngeneral, we try to follow the XDG directory spec.\n\n## Where is VS Code configuration stored?\n\nVS Code configuration such as settings and keybindings are stored in\n`~/.local/share/code-server` by default.\n\nOn Linux and macOS if you set the `XDG_DATA_HOME` environment variable, the data\ndirectory will be `$XDG_DATA_HOME/code-server`. In general, we try to follow the\nXDG directory spec.\n\n## How can I reuse my VS Code configuration?\n\nYou can use the [Settings\nSync](https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync)\nextension for this purpose.\n\nAlternatively, you can also pass `--user-data-dir ~/.vscode` or copy `~/.vscode`\ninto `~/.local/share/code-server` to reuse your existing VS Code extensions and\nconfiguration.\n\n## How does code-server decide what workspace or folder to open?\n\ncode-server tries the following in this order:\n\n1. The `workspace` query parameter\n2. The `folder` query parameter\n3. The workspace or directory passed via the command line\n4. The last opened workspace or directory\n\n## How do I access my Documents/Downloads/Desktop folders in code-server on macOS?\n\nNewer versions of macOS require permission through a non-UNIX mechanism for\ncode-server to access the Desktop, Documents, Pictures, Downloads, and other folders.\n\nYou may have to give Node.js full disk access, since it doesn't implement any of the macOS permission request features natively:\n\n1. Find where Node.js is installed on your machine\n\n   ```console\n   $ which node\n   /usr/local/bin/node\n   ```\n\n2. Grant Node.js full disk access. Open **System Preferences** > **Security &\n   Privacy** > **Privacy** > **Full Disk Access**. Then, click the 🔒 to unlock,\n   click **+**, and select the Node.js binary you located in the previous step.\n\nSee [#2794](https://github.com/coder/code-server/issues/2794) for additional context.\n\n## How do I direct server-side requests through a proxy?\n\n> code-server proxies only server-side requests.\n\nTo direct server-side requests through a proxy, code-server supports the\nfollowing environment variables:\n\n- `$HTTP_PROXY`\n- `$HTTPS_PROXY`\n- `$NO_PROXY`\n\n```sh\nexport HTTP_PROXY=https://134.8.5.4\nexport HTTPS_PROXY=https://134.8.5.4\n# Now all of code-server's server side requests will go through\n# https://134.8.5.4 first.\ncode-server\n```\n\n- See\n  [proxy-from-env](https://www.npmjs.com/package/proxy-from-env#environment-variables)\n  for a detailed reference on these environment variables and their syntax (note\n  that code-server only uses the `http` and `https` protocols).\n- See [proxy-agent](https://www.npmjs.com/package/proxy-agent) for information\n  on on the supported proxy protocols.\n\n## How do I debug issues with code-server?\n\nFirst, run code-server with the `debug` logging (or `trace` to be really\nthorough) by setting the `--log` flag or the `LOG_LEVEL` environment variable.\n`-vvv` and `--verbose` are aliases for `--log trace`.\n\nFirst, run code-server with `debug` logging (or `trace` logging for more\nthorough messages) by setting the `--log` flag or the `LOG_LEVEL` environment\nvariable.\n\n```text\ncode-server --log debug\n```\n\n> Note that the `-vvv` and `--verbose` flags are aliases for `--log trace`.\n\nNext, replicate the issue you're having so that you can collect logging\ninformation from the following places:\n\n1. The most recent files from `~/.local/share/code-server/coder-logs`\n2. The browser console\n3. The browser network tab\n\nAdditionally, collecting core dumps (you may need to enable them first) if\ncode-server crashes can be helpful.\n\n## What is the healthz endpoint?\n\nYou can use the `/healthz` endpoint exposed by code-server to check whether\ncode-server is running without triggering a heartbeat. The response includes a\nstatus (e.g., `alive` or `expired`) and a timestamp for the last heartbeat\n(the default is `0`).\n\n```json\n{\n  \"status\": \"alive\",\n  \"lastHeartbeat\": 1599166210566\n}\n```\n\nThis endpoint doesn't require authentication.\n\n## What is the heartbeat file?\n\nAs long as there is an active browser connection, code-server touches\n`~/.local/share/code-server/heartbeat` once a minute.\n\nIf you want to shutdown code-server if there hasn't been an active connection\nafter a predetermined amount of time, you can use the --idle-timeout-seconds flag\nor set an `CODE_SERVER_IDLE_TIMEOUT_SECONDS` environment variable.\n\n## How do I change the password?\n\nEdit the `password` field in the code-server config file at\n`~/.config/code-server/config.yaml`, then restart code-server:\n\n```bash\nsudo systemctl restart code-server@$USER\n```\n\n## Can I store my password hashed?\n\nYes, you can do so by setting the value of `hashed-password` instead of `password`. Generate the hash with:\n\n```shell\necho -n \"thisismypassword\" | npx argon2-cli -e\n$argon2i$v=19$m=4096,t=3,p=1$wst5qhbgk2lu1ih4dmuxvg$ls1alrvdiwtvzhwnzcm1dugg+5dto3dt1d5v9xtlws4\n```\n\nReplace `thisismypassword` with your actual password and **remember to put it\ninside quotes**! For example:\n\n```yaml\nauth: password\nhashed-password: \"$argon2i$v=19$m=4096,t=3,p=1$wST5QhBgk2lu1ih4DMuxvg$LS1alrVdIWtvZHwnzCM1DUGg+5DTO3Dt1d5v9XtLws4\"\n```\n\nThe `hashed-password` field takes precedence over `password`.\n\nIf you're using Docker Compose file, in order to make this work, you need to change all the single $ to $$. For example:\n\n```yaml\n- HASHED_PASSWORD=$$argon2i$$v=19$$m=4096,t=3,p=1$$wST5QhBgk2lu1ih4DMuxvg$$LS1alrVdIWtvZHwnzCM1DUGg+5DTO3Dt1d5v9XtLws4\n```\n\n## Is multi-tenancy possible?\n\nIf you want to run multiple code-servers on shared infrastructure, we recommend\nusing virtual machines (provide one VM per user). This will easily allow users\nto run a Docker daemon. If you want to use Kubernetes, you'll want to\nuse [kubevirt](https://kubevirt.io) or\n[sysbox](https://github.com/nestybox/sysbox) to give each user a VM-like\nexperience instead of just a container.\n\n## Can I use Docker in a code-server container?\n\nIf you'd like to access Docker inside of code-server, mount the Docker socket in\nfrom `/var/run/docker.sock`. Then, install the Docker CLI in the code-server\ncontainer, and you should be able to access the daemon.\n\nYou can even make volume mounts work. Let's say you want to run a container and\nmount into `/home/coder/myproject` from inside the `code-server` container. You\nneed to make sure the Docker daemon's `/home/coder/myproject` is the same as the\none mounted inside the `code-server` container, and the mount will work.\n\nIf you want Docker enabled when deploying on Kubernetes, look at the `values.yaml`\nfile for the 3 fields: `extraVars`, `lifecycle.postStart`, and `extraContainers`.\n\n## How do I disable telemetry?\n\nUse the `--disable-telemetry` flag to disable telemetry.\n\n> We use the data collected only to improve code-server.\n\n## What's the difference between code-server and Coder?\n\ncode-server and Coder are both applications that can be installed on any\nmachine. The main difference is who they serve. Out of the box, code-server is\nsimply VS Code in the browser while Coder is a tool for provisioning remote\ndevelopment environments via Terraform.\n\ncode-server was built for individuals while Coder was built for teams. In Coder, you create Workspaces which can have applications like code-server. If you're looking for a team solution, you should reach for [Coder](https://github.com/coder/coder).\n\n## What's the difference between code-server and Theia?\n\nAt a high level, code-server is a patched fork of VS Code that runs in the\nbrowser whereas Theia takes some parts of VS Code but is an entirely different\neditor.\n\n[Theia](https://github.com/eclipse-theia/theia) is a browser IDE loosely based\non VS Code. It uses the same text editor library\n([Monaco](https://github.com/Microsoft/monaco-editor)) and extension API, but\neverything else is different. Theia also uses [Open VSX](https://open-vsx.org)\nfor extensions.\n\nTheia doesn't allow you to reuse your existing VS Code config.\n\n## What's the difference between code-server and OpenVSCode-Server?\n\ncode-server and OpenVSCode-Server both allow you to access VS Code via a\nbrowser. OpenVSCode-Server is a direct fork of VS Code with changes comitted\ndirectly while code-server pulls VS Code in via a submodule and makes changes\nvia patch files.\n\nHowever, OpenVSCode-Server is scoped at only making VS Code available as-is in\nthe web browser. code-server contains additional changes to make the self-hosted\nexperience better (see the next section for details).\n\n## What's the difference between code-server and GitHub Codespaces?\n\nBoth code-server and GitHub Codespaces allow you to access VS Code via a\nbrowser. GitHub Codespaces, however, is a closed-source, paid service offered by\nGitHub and Microsoft.\n\nOn the other hand, code-server is self-hosted, free, open-source, and can be run\non any machine with few limitations.\n\nSpecific changes include:\n\n- Password authentication\n- The ability to host at sub-paths\n- Self-contained web views that do not call out to Microsoft's servers\n- The ability to use your own marketplace and collect your own telemetry\n- Built-in proxy for accessing ports on the remote machine integrated into\n  VS Code's ports panel\n- Settings are stored on disk like desktop VS Code, instead of in browser\n  storage (note that state is still stored in browser storage).\n- Wrapper process that spawns VS Code on-demand and has a separate CLI\n- Notification when updates are available\n- [Some other things](https://github.com/coder/code-server/tree/main/patches)\n\nSome of these changes appear very unlikely to ever be adopted by Microsoft.\nSome may make their way upstream, further closing the gap, but at the moment it\nlooks like there will always be some subtle differences.\n\n## What's the difference between code-server and VS Code web?\n\nVS Code web (which can be ran using `code serve-web`) has the same differences\nas the Codespaces section above. VS Code web can be a better choice if you need\naccess to the official Microsoft marketplace.\n\n## Does code-server have any security login validation?\n\ncode-server supports setting a single password and limits logins to two per\nminute plus an additional twelve per hour.\n\n## Are there community projects involving code-server?\n\nVisit the [awesome-code-server](https://github.com/coder/awesome-code-server)\nrepository to view community projects and guides with code-server! Feel free to\nadd your own!\n\n## How do I change the port?\n\nThere are two ways to change the port on which code-server runs:\n\n1. with an environment variable e.g. `PORT=3000 code-server`\n2. using the flag `--bind-addr` e.g. `code-server --bind-addr localhost:3000`\n\n## How do I hide the coder/coder promotion in Help: Getting Started?\n\nYou can pass the flag `--disable-getting-started-override` to `code-server` or\nyou can set the environment variable `CS_DISABLE_GETTING_STARTED_OVERRIDE=1` or\n`CS_DISABLE_GETTING_STARTED_OVERRIDE=true`.\n\n## How do I disable the proxy?\n\nYou can pass the flag `--disable-proxy` to `code-server` or\nyou can set the environment variable `CS_DISABLE_PROXY=1` or\n`CS_DISABLE_PROXY=true`.\n\nNote, this option currently only disables the proxy routes to forwarded ports, including\nthe domain and path proxy routes over HTTP and WebSocket; however, it does not\ndisable the automatic port forwarding in the VS Code workbench itself. In other words,\nuser will still see the Ports tab and notifications, but will not be able to actually\nuse access the ports. It is recommended to set `remote.autoForwardPorts` to `false`\nwhen using the option.\n\n## How do I disable file download?\n\nYou can pass the flag `--disable-file-downloads` to `code-server`\n\n## Why do web views not work?\n\nWeb views rely on service workers, and service workers are only available in a\nsecure context, so most likely the answer is that you are using an insecure\ncontext (for example an IP address).\n\nIf this happens, in the browser log you will see something like:\n\n> Error loading webview: Error: Could not register service workers: SecurityError: Failed to register a ServiceWorker for scope with script: An SSL certificate error occurred when fetching the script..\n\nTo fix this, you must either:\n\n- Access over localhost/127.0.0.1 which is always considered secure.\n- Use a domain with a real certificate (for example with Let's Encrypt).\n- Use a trusted self-signed certificate with [mkcert](https://mkcert.dev) (or\n  create and trust a certificate manually).\n- Disable security if your browser allows it. For example, in Chromium see\n  `chrome://flags/#unsafely-treat-insecure-origin-as-secure`\n"
  },
  {
    "path": "docs/MAINTAINING.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Maintaining\n\n- [Releasing](#releasing)\n    - [Release Candidates](#release-candidates)\n    - [AUR](#aur)\n    - [Docker](#docker)\n    - [Homebrew](#homebrew)\n    - [nixpkgs](#nixpkgs)\n    - [npm](#npm)\n- [Testing](#testing)\n- [Documentation](#documentation)\n  - [Troubleshooting](#troubleshooting)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\nWe keep code-server up to date with VS Code releases (there are usually two or\nthree a month) but we are not generally actively developing code-server aside\nfrom fixing regressions.\n\nMost of the work is keeping on top of issues and discussions.\n\n## Releasing\n\n1. Check that the changelog lists all the important changes.\n2. Make sure the changelog entry lists the current version of VS Code.\n3. Update the changelog with the release date.\n4. Go to GitHub Actions > Draft release > Run workflow on the commit you want to\n   release. Make sure CI has finished the build workflow on that commit or this\n   will fail. For the version we match VS Code's minor and patch version. The\n   patch number may become temporarily out of sync if we need to put out a\n   patch, but if we make our own minor change then we will not release it until\n   the next minor VS Code release.\n5. CI will automatically grab the build artifact on that commit (which is why CI\n   has to have completed), inject the provided version into the `package.json`,\n   put together platform-specific packages, and upload those packages to a draft\n   release.\n6. Update the resulting draft release with the changelog contents.\n7. Publish the draft release after validating it.\n8. Bump the Helm chart version once the Docker images have published.\n\n#### Release Candidates\n\nWe prefer to do release candidates so the community can test things before a\nfull-blown release. To do this follow the same steps as above but:\n\n1. Add a `-rc.<number>` suffix to the version.\n2. When you publish the release select \"pre-release\". CI will not automatically\n   publish pre-releases.\n3. Do not update the chart version or merge in the changelog until the final\n   release.\n\n#### AUR\n\nWe publish to AUR as a package [here](https://aur.archlinux.org/packages/code-server/). This process is manual and can be done by following the steps in [this repo](https://github.com/coder/code-server-aur).\n\n#### Docker\n\nWe publish code-server as a Docker image [here](https://hub.docker.com/r/codercom/code-server), tagging it both with the version and latest.\n\nThis is currently automated with the release process.\n\n#### Homebrew\n\nWe publish code-server on Homebrew [here](https://github.com/Homebrew/homebrew-core/blob/master/Formula/code-server.rb).\n\nThis is currently automated with the release process (but may fail occasionally). If it does, run this locally:\n\n```shell\n# Replace VERSION with version\nbrew bump-formula-pr --version=\"${VERSION}\" code-server --no-browse --no-audit\n```\n\n#### nixpkgs\n\nWe publish code-server in nixpkgs but it must be updated manually.\n\n#### npm\n\nWe publish code-server as a npm package [here](https://www.npmjs.com/package/code-server/v/latest).\n\nThis is currently automated with the release process.\n\n## Testing\n\nOur testing structure is laid out under our [Contributing docs](https://coder.com/docs/code-server/latest/CONTRIBUTING#test).\n\nIf you're ever looking to add more tests, here are a few ways to get started:\n\n- run `npm run test:unit` and look at the coverage chart. You'll see all the\n  uncovered lines. This is a good place to start.\n- look at `test/scripts` to see which scripts are tested. We can always use more\n  tests there.\n- look at `test/e2e`. We can always use more end-to-end tests.\n\nOtherwise, talk to a current maintainer and ask which part of the codebase is\nlacking most when it comes to tests.\n\n## Documentation\n\n### Troubleshooting\n\nOur docs are hosted on [Vercel](https://vercel.com/). Vercel only shows logs in\nrealtime, which means you need to have the logs open in one tab and reproduce\nyour error in another tab. Since our logs are private to Coder the organization,\nyou can only follow these steps if you're a Coder employee. Ask a maintainer for\nhelp if you need it.\n\nTaking a real scenario, let's say you wanted to troubleshoot [this docs\nchange](https://github.com/coder/code-server/pull/4042). Here is how you would\ndo it:\n\n1. Go to https://vercel.com/codercom/codercom\n2. Click \"View Function Logs\"\n3. In a separate tab, open the preview link from github-actions-bot\n4. Now look at the function logs and see if there are errors in the logs\n"
  },
  {
    "path": "docs/README.md",
    "content": "# code-server\n\n[![\"GitHub Discussions\"](https://img.shields.io/badge/%20GitHub-%20Discussions-gray.svg?longCache=true&logo=github&colorB=purple)](https://github.com/coder/code-server/discussions) [![\"Join us on Slack\"](https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen)](https://coder.com/community) [![Twitter Follow](https://img.shields.io/twitter/follow/CoderHQ?label=%40CoderHQ&style=social)](https://twitter.com/coderhq) [![Discord](https://img.shields.io/discord/747933592273027093)](https://discord.com/invite/coder) [![codecov](https://codecov.io/gh/coder/code-server/branch/main/graph/badge.svg?token=5iM9farjnC)](https://codecov.io/gh/coder/code-server) [![See latest](https://img.shields.io/static/v1?label=Docs&message=see%20latest&color=blue)](https://coder.com/docs/code-server/latest)\n\nRun [VS Code](https://github.com/Microsoft/vscode) on any machine anywhere and\naccess it in the browser.\n\n![Screenshot](./assets/screenshot-1.png)\n![Screenshot](./assets/screenshot-2.png)\n\n## Highlights\n\n- Code on any device with a consistent development environment\n- Use cloud servers to speed up tests, compilations, downloads, and more\n- Preserve battery life when you're on the go; all intensive tasks run on your\n  server\n\n## Requirements\n\nSee [requirements](https://coder.com/docs/code-server/latest/requirements) for minimum specs, as well as instructions\non how to set up a Google VM on which you can install code-server.\n\n**TL;DR:** Linux machine with WebSockets enabled, 1 GB RAM, and 2 vCPUs\n\n## Getting started\n\nThere are five ways to get started:\n\n1. Using the [install\n   script](https://github.com/coder/code-server/blob/main/install.sh), which\n   automates most of the process. The script uses the system package manager if\n   possible.\n2. Manually [installing\n   code-server](https://coder.com/docs/code-server/latest/install)\n3. Deploy code-server to your team with [coder/coder](https://cdr.co/coder-github)\n4. Using our one-click buttons and guides to [deploy code-server to a cloud\n   provider](https://github.com/coder/deploy-code-server) ⚡\n5. Using the [code-server feature for\n   devcontainers](https://github.com/coder/devcontainer-features/blob/main/src/code-server/README.md),\n   if you already use devcontainers in your project.\n\nIf you use the install script, you can preview what occurs during the install\nprocess:\n\n```bash\ncurl -fsSL https://code-server.dev/install.sh | sh -s -- --dry-run\n```\n\nTo install, run:\n\n```bash\ncurl -fsSL https://code-server.dev/install.sh | sh\n```\n\nWhen done, the install script prints out instructions for running and starting\ncode-server.\n\n> **Note**\n> To manage code-server for a team on your infrastructure, see: [coder/coder](https://cdr.co/coder-github)\n\nWe also have an in-depth [setup and\nconfiguration](https://coder.com/docs/code-server/latest/guide) guide.\n\n## Questions?\n\nSee answers to [frequently asked\nquestions](https://coder.com/docs/code-server/latest/FAQ).\n\n## Want to help?\n\nSee [Contributing](https://coder.com/docs/code-server/latest/CONTRIBUTING) for\ndetails.\n\n## Hiring\n\nInterested in [working at Coder](https://coder.com/careers)? Check out [our open\npositions](https://coder.com/careers#openings)!\n\n## For Teams\n\nWe develop [coder/coder](https://cdr.co/coder-github) to help teams to\nadopt remote development.\n"
  },
  {
    "path": "docs/SECURITY.md",
    "content": "# Security Policy\n\nCoder and the code-server team want to keep the code-server project secure and safe for end-users.\n\n## Tools\n\nWe use the following tools to help us stay on top of vulnerability mitigation.\n\n- [dependabot](https://dependabot.com/)\n  - Submits pull requests to upgrade dependencies. We use dependabot's version\n    upgrades as well as security updates.\n- code-scanning\n  - [CodeQL](https://securitylab.github.com/tools/codeql/)\n    - Semantic code analysis engine that runs on a regular schedule (see\n      `codeql-analysis.yml`)\n  - [trivy](https://github.com/aquasecurity/trivy)\n    - Comprehensive vulnerability scanner that runs on PRs into the default\n      branch and scans both our container image and repository code (see\n      `trivy-scan-repo` and `trivy-scan-image` jobs in `build.yaml`)\n- `npm audit`\n  - Audits NPM dependencies.\n\n## Supported Versions\n\nCoder sponsors the development and maintenance of the code-server project. We will fix security issues within 90 days of receiving a report and publish the fix in a subsequent release. The code-server project does not provide backports or patch releases for security issues at this time.\n\n| Version                                                 | Supported          |\n| ------------------------------------------------------- | ------------------ |\n| [Latest](https://github.com/coder/code-server/releases) | :white_check_mark: |\n\n## Reporting a Vulnerability\n\nTo report a vulnerability, please send an email to security[@]coder.com, and our security team will respond to you.\n"
  },
  {
    "path": "docs/android.md",
    "content": "# Running code-server using UserLAnd\n\n1. Install UserLAnd from [Google Play](https://play.google.com/store/apps/details?id=tech.ula&hl=en_US&gl=US)\n2. Install an Ubuntu VM\n3. Start app\n4. Install Node.js and `curl` using `sudo apt install nodejs npm curl -y`\n5. Install `nvm`:\n\n```shell\ncurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash\n```\n\n6. Exit the terminal using `exit` and then reopen the terminal\n7. Install and use Node.js 22:\n\n```shell\nnvm install 22\nnvm use 22\n```\n\n8. Install code-server globally on device with: `npm install --global code-server`\n9. Run code-server with `code-server`\n10. Access on localhost:8080 in your browser\n\n# Running code-server using Nix-on-Droid\n\n1. Install Nix-on-Droid from [F-Droid](https://f-droid.org/packages/com.termux.nix/)\n2. Start app\n3. Spawn a shell with code-server by running `nix-shell -p code-server`\n4. Run code-server with `code-server`\n5. Access on localhost:8080 in your browser\n"
  },
  {
    "path": "docs/coder.md",
    "content": "# Coder\n\nTo install and run code-server in a Coder workspace, we suggest using the `install.sh`\nscript in your template like so:\n\n```terraform\nresource \"coder_agent\" \"dev\" {\n  arch           = \"amd64\"\n  os             = \"linux\"\n  startup_script = <<EOF\n    #!/bin/sh\n    set -x\n    # install and start code-server\n    curl -fsSL https://code-server.dev/install.sh | sh -s -- --version 4.8.3\n    code-server --auth none --port 13337 &\n    EOF\n}\n\nresource \"coder_app\" \"code-server\" {\n  agent_id     = coder_agent.dev.id\n  slug         = \"code-server\"\n  display_name = \"code-server\"\n  url          = \"http://localhost:13337/\"\n  icon         = \"/icon/code.svg\"\n  subdomain    = false\n  share        = \"owner\"\n\n  healthcheck {\n    url       = \"http://localhost:13337/healthz\"\n    interval  = 3\n    threshold = 10\n  }\n}\n```\n\nOr use our official [`code-server`](https://registry.coder.com/modules/code-server) module from the Coder [module registry](https://registry.coder.com/modules):\n\n```terraform\nmodule \"code-server\" {\n  source     = \"registry.coder.com/modules/code-server/coder\"\n  version    = \"1.0.5\"\n  agent_id   = coder_agent.example.id\n  extensions = [\"dracula-theme.theme-dracula\", \"ms-azuretools.vscode-docker\"]\n}\n```\n\nIf you run into issues, ask for help on the `coder/coder` [Discussions\nhere](https://github.com/coder/coder/discussions).\n"
  },
  {
    "path": "docs/collaboration.md",
    "content": "# Collaboration\n\nWith third-party extensions, you can use code-server to collaborate with other developers in real time.\n\n## Code sharing using Duckly\n\n[Duckly](https://duckly.com/) allows you to share your code in real-time even with people using different IDEs (like JetBrains and VSCode).\n\n- Cross-IDE support,\n- Real-time typing,\n- P2P encrypted,\n- Voice and audio chat,\n- Terminal sharing\n\n### Installing the Duckly Extension\n\nDuckly uses an extension to provide real time sharing features\n\n1. Install the Duckly extension from OpenVSX on `code-server`.\n\n```bash\nSERVICE_URL=https://open-vsx.org/vscode/gallery \\\n  ITEM_URL=https://open-vsx.org/vscode/item \\\n  code-server --install-extension gitduck.code-streaming\n```\n\n2. Refresh you `code-server` window. You should now be able to see the Duckly extension.\n\n### Sharing with Duckly\n\nAs `code-server` is based on VS Code, you can follow the steps described on Duckly's [Pair programming with VS Code](https://duckly.com/tools/vscode) page and skip the installation step.\n\n## Code sharing using CodeTogether\n\n[CodeTogether](https://www.codetogether.com/) is a real-time cross-IDE replacement for Microsoft Live Share providing:\n\n- Cross-IDE support - between VS Code, Eclipse, IntelliJ and IDEs based on them (browser or desktop)\n- Real-time editing - shared or individual cursors for pairing, mobbing, swarming, or whatever\n- P2P encrypted - servers can't decrypt the traffic ([Security Details](https://codetogether.com/download/security/))\n- SaaS or [On-premises](https://codetogether.com/on-premises/) options\n- Shared servers, terminals, and consoles\n- Unit Testing - with support for Red, Green, Refactor TDD\n- Joining via a web browser or your preferred IDE\n- Free unlimited 1 hour sessions with 4 participants\n- Multiple plans including [free or paid options](https://www.codetogether.com/pricing/)\n\n### Installing the CodeTogether extension\n\n1. Install the CodeTogether extension from OpenVSX on `code-server`.\n\n   ```sh\n   SERVICE_URL=https://open-vsx.org/vscode/gallery \\\n     ITEM_URL=https://open-vsx.org/vscode/item \\\n     code-server --install-extension genuitecllc.codetogether\n   ```\n\n2. CodeTogether requires VS Code's proposed API to run. Start code-server with the following flag:\n\n   ```sh\n   code-server --enable-proposed-api genuitecllc.codetogether\n   ```\n\n   Another option would be to add a value in code-server's [config file](https://coder.com/docs/code-server/latest/FAQ#how-does-the-config-file-work).\n\n3. Refresh code-server and navigate to the CodeTogether icon in the sidebar to host or join a coding session.\n"
  },
  {
    "path": "docs/guide.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Setup Guide\n\n- [Expose code-server](#expose-code-server)\n  - [Port forwarding via SSH](#port-forwarding-via-ssh)\n  - [Using Let's Encrypt with Caddy](#using-lets-encrypt-with-caddy)\n  - [Using Let's Encrypt with NGINX](#using-lets-encrypt-with-nginx)\n  - [Using a self-signed certificate](#using-a-self-signed-certificate)\n  - [TLS 1.3 and Safari](#tls-13-and-safari)\n- [External authentication](#external-authentication)\n- [HTTPS and self-signed certificates](#https-and-self-signed-certificates)\n- [Accessing web services](#accessing-web-services)\n  - [Using a subdomain](#using-a-subdomain)\n  - [Using a subpath](#using-a-subpath)\n  - [Using your own proxy](#using-your-own-proxy)\n  - [Stripping `/proxy/<port>` from the request path](#stripping-proxyport-from-the-request-path)\n  - [Proxying to create a React app](#proxying-to-create-a-react-app)\n  - [Proxying to a Vue app](#proxying-to-a-vue-app)\n  - [Proxying to an Angular app](#proxying-to-an-angular-app)\n  - [Proxying to a Svelte app](#proxying-to-a-svelte-app)\n  - [Prefixing `/absproxy/<port>` with a path](#prefixing-absproxyport-with-a-path)\n  - [Preflight requests](#preflight-requests)\n- [Internationalization and customization](#internationalization-and-customization)\n  - [Available keys and placeholders](#available-keys-and-placeholders)\n  - [Legacy flag](#legacy-flag)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\nThis article will walk you through exposing code-server securely once you've\ncompleted the [installation process](install.md).\n\n## Expose code-server\n\n**Never** expose code-server directly to the internet without some form of\nauthentication and encryption, otherwise someone can take over your machine via\nthe terminal.\n\nBy default, code-server uses password authentication. As such, you must copy the\npassword from code-server's config file to log in. To avoid exposing itself\nunnecessarily, code-server listens on `localhost`; this practice is fine for\ntesting, but it doesn't work if you want to access code-server from a different\nmachine.\n\n> **Rate limits:** code-server rate limits password authentication attempts to\n> two per minute plus an additional twelve per hour.\n\nThere are several approaches to operating and exposing code-server securely:\n\n- Port forwarding via SSH\n- Using Let's Encrypt with Caddy\n- Using Let's Encrypt with NGINX\n- Using a self-signed certificate\n\n### Port forwarding via SSH\n\nWe highly recommend using [port forwarding via\nSSH](https://help.ubuntu.com/community/SSH/OpenSSH/PortForwarding) to access\ncode-server. If you have an SSH server on your remote machine, this approach\ndoesn't require any additional setup at all.\n\nThe downside to SSH forwarding, however, is that you can't access code-server\nwhen using machines without SSH clients (such as iPads). If this applies to you,\nwe recommend using another method, such as [Let's Encrypt](#let-encrypt) instead.\n\n> To work properly, your environment should have WebSockets enabled, which\n> code-server uses to communicate between the browser and server.\n\n1. SSH into your instance and edit the code-server config file to disable\n   password authentication:\n\n   ```console\n   # Replaces \"auth: password\" with \"auth: none\" in the code-server config.\n   sed -i.bak 's/auth: password/auth: none/' ~/.config/code-server/config.yaml\n   ```\n\n2. Restart code-server:\n\n   ```console\n   sudo systemctl restart code-server@$USER\n   ```\n\n3. Forward local port `8080` to `127.0.0.1:8080` on the remote instance by running the following command on your local machine:\n\n   ```console\n   # -N disables executing a remote shell\n   ssh -N -L 8080:127.0.0.1:8080 [user]@<instance-ip>\n   ```\n\n4. At this point, you can access code-server by pointing your web browser to `http://127.0.0.1:8080`.\n\n5. If you'd like to make the port forwarding via SSH persistent, we recommend\n   using [mutagen](https://mutagen.io/documentation/introduction/installation)\n   to do so. Once you've installed mutagen, you can port forward as follows:\n\n   ```shell\n   # This is the same as the above SSH command, but it runs in the background\n   # continuously. Be sure to add `mutagen daemon start` to your ~/.bashrc to\n   # start the mutagen daemon when you open a shell.\n   mutagen forward create --name=code-server tcp:127.0.0.1:8080 < instance-ip > :tcp:127.0.0.1:8080\n   ```\n\n6. Optional, but highly recommended: add the following to `~/.ssh/config` so\n   that you can detect bricked SSH connections:\n\n   ```bash\n   Host *\n   ServerAliveInterval 5\n   ExitOnForwardFailure yes\n   ```\n\n> You can [forward your\n> SSH](https://developer.github.com/v3/guides/using-ssh-agent-forwarding/) and\n> [GPG agent](https://wiki.gnupg.org/AgentForwarding) to the instance to\n> securely access GitHub and sign commits without having to copy your keys.\n\n### Using Let's Encrypt with Caddy\n\nUsing [Let's Encrypt](https://letsencrypt.org) is an option if you want to\naccess code-server on an iPad or do not want to use SSH port forwarding.\n\n1. This option requires that the remote machine be exposed to the internet. Make sure that your instance allows HTTP/HTTPS traffic.\n\n2. You'll need a domain name (if you don't have one, you can purchase one from\n   [Google Domains](https://domains.google.com) or the domain service of your\n   choice). Once you have a domain name, add an A record to your domain that contains your\n   instance's IP address.\n\n3. Install [Caddy](https://caddyserver.com/docs/download#debian-ubuntu-raspbian):\n\n   ```console\n   sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https\n   curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg\n   curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list\n   sudo apt update\n   sudo apt install caddy\n   ```\n\n4. Replace `/etc/caddy/Caddyfile` using `sudo` so that the file looks like this:\n\n   ```text\n   mydomain.com {\n     reverse_proxy 127.0.0.1:8080\n   }\n   ```\n\n   If you want to serve code-server from a sub-path, you can do so as follows:\n\n   ```text\n   mydomain.com/code/* {\n     uri strip_prefix /code\n     reverse_proxy 127.0.0.1:8080\n   }\n   ```\n\n   Remember to replace `mydomain.com` with your domain name!\n\n5. Reload Caddy:\n\n   ```console\n   sudo systemctl reload caddy\n   ```\n\nAt this point, you should be able to access code-server via\n`https://mydomain.com`.\n\n### Using Let's Encrypt with NGINX\n\n1. This option requires that the remote machine be exposed to the internet. Make\n   sure that your instance allows HTTP/HTTPS traffic.\n\n2. You'll need a domain name (if you don't have one, you can purchase one from\n   [Google Domains](https://domains.google.com) or the domain service of your\n   choice). Once you have a domain name, add an A record to your domain that contains your\n   instance's IP address.\n\n3. Install NGINX:\n\n   ```bash\n   sudo apt update\n   sudo apt install -y nginx certbot python3-certbot-nginx\n   ```\n\n4. Update `/etc/nginx/sites-available/code-server` using sudo with the following\n   configuration:\n\n   ```text\n   server {\n       listen 80;\n       listen [::]:80;\n       server_name mydomain.com;\n\n       location / {\n         proxy_pass http://localhost:8080/;\n         proxy_set_header Host $http_host;\n         proxy_set_header Upgrade $http_upgrade;\n         proxy_set_header Connection upgrade;\n         proxy_set_header Accept-Encoding gzip;\n       }\n   }\n   ```\n\n   Be sure to replace `mydomain.com` with your domain name!\n\n5. Enable the config:\n   ```console\n   sudo ln -s ../sites-available/code-server /etc/nginx/sites-enabled/code-server\n   sudo certbot --non-interactive --redirect --agree-tos --nginx -d mydomain.com -m me@example.com\n   ```\n   Be sure to replace `me@example.com` with your actual email.\n\nAt this point, you should be able to access code-server via\n`https://mydomain.com`.\n\n### Using a self-signed certificate\n\n> Self signed certificates do not work with iPad; see [./ipad.md](./ipad.md) for\n> more information.\n\nBefore proceeding, we recommend familiarizing yourself with the [risks of\nself-signing a certificate for\nSSL](https://security.stackexchange.com/questions/8110).\n\nWe recommend self-signed certificates as a last resort, since self-signed\ncertificates do not work with iPads and may cause unexpected issues with\ncode-server. You should only proceed with this option if:\n\n- You do not want to buy a domain or you cannot expose the remote machine to\n  the internet\n- You do not want to use port forwarding via SSH\n\nTo use a self-signed certificate:\n\n1. This option requires that the remote machine be exposed to the internet. Make\n   sure that your instance allows HTTP/HTTPS traffic.\n\n1. SSH into your instance and edit your code-server config file to use a\n   randomly generated self-signed certificate:\n\n   ```console\n   # Replaces \"cert: false\" with \"cert: true\" in the code-server config.\n   sed -i.bak 's/cert: false/cert: true/' ~/.config/code-server/config.yaml\n   # Replaces \"bind-addr: 127.0.0.1:8080\" with \"bind-addr: 0.0.0.0:443\" in the code-server config.\n   sed -i.bak 's/bind-addr: 127.0.0.1:8080/bind-addr: 0.0.0.0:443/' ~/.config/code-server/config.yaml\n   # Allows code-server to listen on port 443.\n   sudo setcap cap_net_bind_service=+ep /usr/lib/code-server/lib/node\n   ```\n\n1. Restart code-server:\n\n   ```console\n   sudo systemctl restart code-server@$USER\n   ```\n\nAt this point, you should be able to access code-server via\n`https://<your-instance-ip>`.\n\nIf you'd like to avoid the warnings displayed by code-server when using a\nself-signed certificate, you can use [mkcert](https://mkcert.dev) to create a\nself-signed certificate that's trusted by your operating system, then pass the\ncertificate to code-server via the `cert` and `cert-key` config fields.\n\n### TLS 1.3 and Safari\n\nIf you will be using Safari and your configuration does not allow anything less\nthan TLS 1.3 you will need to add support for TLS 1.2 since Safari does not\nsupport TLS 1.3 for web sockets at the time of writing. If this is the case you\nshould see OSSStatus: 9836 in the browser console.\n\n## External authentication\n\nIf you want to use external authentication mechanism (e.g., Sign in with\nGoogle), you can do this with a reverse proxy such as:\n\n- [Pomerium](https://www.pomerium.com/docs/guides/code-server.html)\n- [oauth2-proxy](https://oauth2-proxy.github.io/oauth2-proxy/)\n- [Cloudflare Access](https://www.cloudflare.com/zero-trust/products/access/)\n\n## HTTPS and self-signed certificates\n\nFor HTTPS, you can use a self-signed certificate by:\n\n- Passing in `--cert`\n- Passing in an existing certificate by providing the path to `--cert` and the\n  path to the key with `--cert-key`\n\nThe self signed certificate will be generated to\n`~/.local/share/code-server/self-signed.crt`.\n\nIf you pass a certificate to code-server, it will respond to HTTPS requests and\nredirect all HTTP requests to HTTPS.\n\n> You can use [Let's Encrypt](https://letsencrypt.org/) to get a TLS certificate\n> for free.\n\nNote: if you set `proxy_set_header Host $host;` in your reverse proxy config, it\nwill change the address displayed in the green section of code-server in the\nbottom left to show the correct address.\n\n## Accessing web services\n\nIf you're working on web services and want to access them locally, code-server\ncan proxy to any port using either a subdomain or a subpath, allowing you to\nsecurely access these services using code-server's built-in authentication.\n\n### Using a subdomain\n\nYou will need a DNS entry that points to your server for each port you want to\naccess. You can either set up a wildcard DNS entry for `*.<domain>` if your\ndomain name registrar supports it, or you can create one for every port you want\nto access (`3000.<domain>`, `8080.<domain>`, etc).\n\nYou should also set up TLS certificates for these subdomains, either using a\nwildcard certificate for `*.<domain>` or individual certificates for each port.\n\nTo set your domain, start code-server with the `--proxy-domain` flag:\n\n```console\ncode-server --proxy-domain <domain>\n```\n\nFor instance, if you have code-server exposed on `domain.tld` and a Python\nserver running on port 8080 of the same machine code-server is running on, you\ncould run code-server with `--proxy-domain domain.tld` and access the Python\nserver via `8080.domain.tld`.\n\nNote that this uses the host header, so ensure your reverse proxy (if you're\nusing one) forwards that information.\n\n### Using a subpath\n\nSimply browse to `/proxy/<port>/`. For instance, if you have code-server\nexposed on `domain.tld` and a Python server running on port 8080 of the same\nmachine code-server is running on, you could access the Python server via\n`domain.tld/proxy/8000`.\n\n### Using your own proxy\n\nYou can make extensions and the ports panel use your own proxy by setting\n`VSCODE_PROXY_URI`. For example if you set\n`VSCODE_PROXY_URI=https://{{port}}.kyle.dev` when an application is detected\nrunning on port 3000 of the same machine code-server is running on the ports\npanel will create a link to https://3000.kyle.dev instead of pointing to the\nbuilt-in subpath-based proxy.\n\nNote: relative paths are also supported i.e.\n`VSCODE_PROXY_URI=./proxy/{{port}}`\n\n### Stripping `/proxy/<port>` from the request path\n\nYou may notice that the code-server proxy strips `/proxy/<port>` from the\nrequest path.\n\nHTTP servers should use relative URLs to avoid the need to be coupled to the\nabsolute path at which they are served. This means you must [use trailing\nslashes on all paths with\nsubpaths](https://blog.cdivilly.com/2019/02/28/uri-trailing-slashes).\n\nThis reasoning is why the default behavior is to strip `/proxy/<port>` from the\nbase path. If your application uses relative URLs and does not assume the\nabsolute path at which it is being served, it will just work no matter what port\nyou decide to serve it off or if you put it in behind code-server or any other\nproxy.\n\nHowever, some prefer the cleaner aesthetic of no trailing slashes. Omitting the\ntrailing slashes couples you to the base path, since you cannot use relative\nredirects correctly anymore. If you're okay with this tradeoff, use `/absproxy`\ninstead and the path will be passed as is (e.g., `/absproxy/3000/my-app-path`).\n\n### Proxying to create a React app\n\nYou must use `/absproxy/<port>` with `create-react-app` (see\n[#2565](https://github.com/coder/code-server/issues/2565) and\n[#2222](https://github.com/coder/code-server/issues/2222) for more information).\nYou will need to inform `create-react-app` of the path at which you are serving\nvia `$PUBLIC_URL` and webpack via `$WDS_SOCKET_PATH`:\n\n```sh\nPUBLIC_URL=/absproxy/3000 \\\n  WDS_SOCKET_PATH=$PUBLIC_URL/sockjs-node \\\n  BROWSER=none yarn start\n```\n\nYou should then be able to visit\n`https://my-code-server-address.io/absproxy/3000` to see your app exposed\nthrough code-server.\n\n> We highly recommend using the subdomain approach instead to avoid this class of issue.\n\n### Proxying to a Vue app\n\nSimilar to the situation with React apps, you have to make a few modifications\nto proxy a Vue app.\n\n1. add `vue.config.js`\n2. update the values to match this (you can use any free port):\n\n```js\nmodule.exports = {\n  devServer: {\n    port: 3454,\n    sockPath: \"sockjs-node\",\n  },\n  publicPath: \"/absproxy/3454\",\n}\n```\n\n3. access app at `<code-server-root>/absproxy/3454` e.g. `http://localhost:8080/absproxy/3454`\n\nRead more about `publicPath` in the [Vue.js docs](https://cli.vuejs.org/config/#publicpath)\n\n### Proxying to an Angular app\n\nIn order to use code-server's built-in proxy with Angular, you need to make the\nfollowing changes in your app:\n\n1. use `<base href=\"./.\">` in `src/index.html`\n2. add `--serve-path /absproxy/4200` to `ng serve` in your `package.json`\n\nFor additional context, see [this GitHub Discussion](https://github.com/coder/code-server/discussions/5439#discussioncomment-3371983).\n\n### Proxying to a Svelte app\n\nIn order to use code-server's built-in proxy with Svelte, you need to make the\nfollowing changes in your app:\n\n1. Add `svelte.config.js` if you don't already have one\n2. Update the values to match this (you can use any free port):\n\n```js\nconst config = {\n  kit: {\n    paths: {\n      base: \"/absproxy/5173\",\n    },\n  },\n}\n```\n\n3. Access app at `<code-server-root>/absproxy/5173/` e.g. `http://localhost:8080/absproxy/5173/\n\nFor additional context, see [this Github Issue](https://github.com/sveltejs/kit/issues/2958)\n\n### Prefixing `/absproxy/<port>` with a path\n\nThis is a case where you need to serve an application via `absproxy` as\nexplained above while serving code-server itself from a path other than the root\nin your domain.\n\nFor example: `http://my-code-server.com/user/123/workspace/my-app`. To achieve\nthis result:\n\n1. Start code-server with the switch `--abs-proxy-base-path=/user/123/workspace`\n2. Follow one of the instructions above for your framework.\n\n### Preflight requests\n\nBy default, if you have auth enabled, code-server will authenticate all proxied\nrequests including preflight requests. This can cause issues because preflight\nrequests do not typically include credentials. To allow all preflight requests\nthrough the proxy without authentication, use `--skip-auth-preflight`.\n\n## Internationalization and customization\n\ncode-server allows you to provide a JSON file to configure certain strings. This\ncan be used for both internationalization and customization.\n\nCreate a JSON file with your custom strings:\n\n```json\n{\n  \"WELCOME\": \"Welcome to {{app}}\",\n  \"LOGIN_TITLE\": \"{{app}} Access Portal\",\n  \"LOGIN_BELOW\": \"Please log in to continue\",\n  \"PASSWORD_PLACEHOLDER\": \"Enter Password\"\n}\n```\n\nThen reference the file:\n\n```shell\ncode-server --i18n /path/to/custom-strings.json\n```\n\nOr this can be done in the config file:\n\n```yaml\ni18n: /path/to/custom-strings.json\n```\n\nYou can combine this with the `--locale` flag to configure language support for\nboth code-server and VS Code in cases where code-server has no support but VS\nCode does. If you are using this for internationalization, please consider\nsending us a pull request to contribute it to `src/node/i18n/locales`.\n\n### Available keys and placeholders\n\nRefer to [../src/node/i18n/locales/en.json](../src/node/i18n/locales/en.json)\nfor a full list of the available keys for translations. Note that the only\nplaceholders supported for each key are the ones used in the default string.\n\nThe `--app-name` flag controls the `{{app}}` placeholder in templates. If you\nwant to change the name, you can either:\n\n1. Set `--app-name` (potentially alongside `--i18n`)\n2. Use `--i18n` and hardcode the name in your strings\n\n### Legacy flag\n\nThe `--welcome-text` flag is now deprecated. Use the `WELCOME` key instead.\n"
  },
  {
    "path": "docs/helm.md",
    "content": "# code-server Helm Chart\n\n[![Version: 1.0.0](https://img.shields.io/badge/Version-1.0.0-informational?style=flat-square)](https://img.shields.io/badge/Version-1.0.0-informational?style=flat-square) [![Type: application](https://img.shields.io/badge/Type-application-informational?style=flat-square)](https://img.shields.io/badge/Type-application-informational?style=flat-square) [![AppVersion: 4.8.0](https://img.shields.io/badge/AppVersion-4.8.0-informational?style=flat-square)](https://img.shields.io/badge/AppVersion-4.8.0-informational?style=flat-square)\n\n[code-server](https://github.com/coder/code-server) code-server is VS Code running\non a remote server, accessible through the browser.\n\nThis chart is community maintained by [@Matthew-Beckett](https://github.com/Matthew-Beckett) and [@alexgorbatchev](https://github.com/alexgorbatchev)\n\n## Quickstart\n\n```console\n$ git clone https://github.com/coder/code-server\n$ cd code-server\n$ helm upgrade --install code-server ci/helm-chart\n```\n\n## Introduction\n\nThis chart bootstraps a code-server deployment on a\n[Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh)\npackage manager.\n\n## Prerequisites\n\n- Kubernetes 1.6+\n\n## Installing the Chart\n\nTo install the chart with the release name `code-server`:\n\n```console\n$ git clone https://github.com/coder/code-server\n$ cd code-server\n$ helm upgrade --install code-server ci/helm-chart\n```\n\nThe command deploys code-server on the Kubernetes cluster in the default\nconfiguration. The [configuration](#configuration) section lists the parameters\nthat can be configured during installation.\n\n> **Tip**: List all releases using `helm list`\n\n## Uninstalling the Chart\n\nTo uninstall/delete the `code-server` deployment:\n\n```console\n$ helm delete code-server\n```\n\nThe command removes all the Kubernetes components associated with the chart and\ndeletes the release.\n\n## Configuration\n\nThe following table lists the configurable parameters of the code-server chart\nand their default values.\n\n## Values\n\n| Key                                         | Type   | Default                  |\n| ------------------------------------------- | ------ | ------------------------ |\n| affinity                                    | object | `{}`                     |\n| extraArgs                                   | list   | `[]`                     |\n| extraConfigmapMounts                        | list   | `[]`                     |\n| extraContainers                             | string | `\"\"`                     |\n| extraInitContainers                         | string | `\"\"`                     |\n| extraSecretMounts                           | list   | `[]`                     |\n| extraVars                                   | list   | `[]`                     |\n| extraVolumeMounts                           | list   | `[]`                     |\n| fullnameOverride                            | string | `\"\"`                     |\n| hostnameOverride                            | string | `\"\"`                     |\n| image.pullPolicy                            | string | `\"Always\"`               |\n| image.repository                            | string | `\"codercom/code-server\"` |\n| image.tag                                   | string | `\"4.8.0\"`                |\n| imagePullSecrets                            | list   | `[]`                     |\n| ingress.enabled                             | bool   | `false`                  |\n| nameOverride                                | string | `\"\"`                     |\n| nodeSelector                                | object | `{}`                     |\n| persistence.accessMode                      | string | `\"ReadWriteOnce\"`        |\n| persistence.annotations                     | object | `{}`                     |\n| persistence.enabled                         | bool   | `true`                   |\n| persistence.size                            | string | `\"1Gi\"`                  |\n| podAnnotations                              | object | `{}`                     |\n| podSecurityContext                          | object | `{}`                     |\n| replicaCount                                | int    | `1`                      |\n| resources                                   | object | `{}`                     |\n| securityContext.enabled                     | bool   | `true`                   |\n| securityContext.fsGroup                     | int    | `1000`                   |\n| securityContext.runAsUser                   | int    | `1000`                   |\n| service.port                                | int    | `8443`                   |\n| service.type                                | string | `\"ClusterIP\"`            |\n| serviceAccount.create                       | bool   | `true`                   |\n| serviceAccount.name                         | string | `nil`                    |\n| tolerations                                 | list   | `[]`                     |\n| volumePermissions.enabled                   | bool   | `true`                   |\n| volumePermissions.securityContext.runAsUser | int    | `0`                      |\n\nSpecify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,\n\n```console\n$ helm upgrade --install code-server \\\n  ci/helm-chart \\\n  --set persistence.enabled=false\n```\n\nThe above command sets the the persistence storage to false.\n\nAlternatively, a YAML file that specifies the values for the above parameters\ncan be provided while installing the chart. For example,\n\n```console\n$ helm upgrade --install code-server ci/helm-chart -f values.yaml\n```\n\n> **Tip**: You can use the default [values.yaml](values.yaml)\n\n# Extra Containers\n\nThere are two parameters which allow to add more containers to pod.\nUse `extraContainers` to add regular containers\nand `extraInitContainers` to add init containers. You can read more\nabout init containers in [k8s documentation](https://kubernetes.io/docs/concepts/workloads/pods/init-containers/).\n\nBoth parameters accept strings and use them as a templates\n\nExample of using `extraInitContainers`:\n\n```yaml\nextraInitContainers: |\n  - name: customization\n    image: {{ .Values.image.repository }}:{{ .Values.image.tag }}\n    imagePullPolicy: IfNotPresent\n    env:\n      - name: SERVICE_URL\n        value: https://open-vsx.org/vscode/gallery\n      - name: ITEM_URL\n        value: https://open-vsx.org/vscode/item\n    command:\n      - sh\n      - -c\n      - |\n        code-server --install-extension ms-python.python\n        code-server --install-extension golang.Go\n    volumeMounts:\n      - name: data\n        mountPath: /home/coder\n```\n\nWith this yaml in file `init.yaml`, you can execute\n\n```console\n$ helm upgrade --install code-server \\\n  ci/helm-chart \\\n  --values init.yaml\n```\n\nto deploy code-server with python and golang extensions preinstalled\nbefore main container have started.\n"
  },
  {
    "path": "docs/install.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Install\n\n- [install.sh](#installsh)\n  - [Detection reference](#detection-reference)\n- [npm](#npm)\n- [Standalone releases](#standalone-releases)\n- [Debian, Ubuntu](#debian-ubuntu)\n- [Fedora, CentOS, RHEL, SUSE](#fedora-centos-rhel-suse)\n- [Arch Linux](#arch-linux)\n- [Artix Linux](#artix-linux)\n- [macOS](#macos)\n- [Docker](#docker)\n- [Helm](#helm)\n- [Windows](#windows)\n- [Raspberry Pi](#raspberry-pi)\n- [Termux](#termux)\n- [Cloud providers](#cloud-providers)\n- [Uninstall](#uninstall)\n  - [install.sh](#installsh-1)\n  - [Homebrew](#homebrew)\n  - [npm](#npm-1)\n  - [Debian, Ubuntu](#debian-ubuntu-1)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\nThis document demonstrates how to install `code-server` on various distros and\noperating systems.\n\n## install.sh\n\nThe easiest way to install code-server is to use our [install\nscript](https://github.com/coder/code-server/blob/main/install.sh) for Linux, macOS and FreeBSD. The install script\n[attempts to use the system package manager](#detection-reference) if possible.\n\nYou can preview what occurs during the install process:\n\n```bash\ncurl -fsSL https://code-server.dev/install.sh | sh -s -- --dry-run\n```\n\nTo install, run:\n\n```bash\ncurl -fsSL https://code-server.dev/install.sh | sh\n```\n\nYou can modify the installation process by including one or more of the\nfollowing flags:\n\n- `--dry-run`: echo the commands for the install process without running them.\n- `--method`: choose the installation method.\n  - `--method=detect`: detect the package manager but fallback to\n    `--method=standalone`.\n  - `--method=standalone`: install a standalone release archive into `~/.local`.\n- `--prefix=/usr/local`: install a standalone release archive system-wide.\n- `--version=X.X.X`: install version `X.X.X` instead of latest version.\n- `--help`: see usage docs.\n- `--edge`: install the latest edge version (i.e. pre-release)\n\nWhen done, the install script prints out instructions for running and starting\ncode-server.\n\n> If you're concerned about the install script's use of `curl | sh` and the\n> security implications, please see [this blog\n> post](https://sandstorm.io/news/2015-09-24-is-curl-bash-insecure-pgp-verified-install)\n> by [sandstorm.io](https://sandstorm.io).\n\nIf you prefer to install code-server manually, despite the [detection\nreferences](#detection-reference) and `--dry-run` feature, then continue on for\ninformation on how to do this. The [`install.sh`](https://github.com/coder/code-server/blob/main/install.sh) script runs the\n_exact_ same commands presented in the rest of this document.\n\n### Detection reference\n\n- For Debian and Ubuntu, code-server will install the latest deb package.\n- For Fedora, CentOS, RHEL and openSUSE, code-server will install the latest RPM\n  package.\n- For Arch Linux, code-server will install the AUR package.\n- For any unrecognized Linux operating system, code-server will install the\n  latest standalone release into `~/.local`.\n  - Ensure that you add `~/.local/bin` to your `$PATH` to run code-server.\n\n- For macOS, code-server will install the Homebrew package (if you don't have\n  Homebrew installed, code-server will install the latest standalone release\n  into `~/.local`).\n  - Ensure that you add `~/.local/bin` to your `$PATH` to run code-server.\n\n- For FreeBSD, code-server will install the [npm package](#npm) with `npm`\n\n- If you're installing code-server onto architecture with no releases,\n  code-server will install the [npm package](#npm) with `npm`\n  - We currently offer releases for amd64 and arm64.\n  - The [npm package](#npm) builds the native modules on post-install.\n\n## npm\n\nWe recommend installing with `npm` when:\n\n1. You aren't using a machine with `amd64` or `arm64`.\n2. You are installing code-server on Windows.\n3. You're on Linux with `glibc` < v2.28 or `glibcxx` < v3.4.21.\n4. You're running Alpine Linux or are using a non-glibc libc. See\n   [#1430](https://github.com/coder/code-server/issues/1430#issuecomment-629883198)\n   for more information.\n\nInstalling code-server with `npm` builds native modules on install.\n\nThis process requires C dependencies; see our guide on [installing with npm](./npm.md) for more information.\n\n## Standalone releases\n\nWe publish self-contained `.tar.gz` archives for every release on\n[GitHub](https://github.com/coder/code-server/releases). The archives bundle the\nnode binary and node modules.\n\nWe create the standalone releases using the [npm package](#npm), and we\nthen create the remaining releases using the standalone version.\n\nThe only requirement to use the standalone release is `glibc` >= 2.28 and\n`glibcxx` >= v3.4.21 on Linux (for macOS, there is no minimum system\nrequirement).\n\nTo use a standalone release:\n\n1. Download the latest release archive for your system from\n   [GitHub](https://github.com/coder/code-server/releases).\n2. Unpack the release.\n3. Run code-server by executing `./bin/code-server`.\n\nYou can add `./bin/code-server` to your `$PATH` so that you can execute\n`code-server` without providing full path each time.\n\nHere is a sample script for installing and using a standalone code-server\nrelease on Linux:\n\n```bash\nmkdir -p ~/.local/lib ~/.local/bin\ncurl -fL https://github.com/coder/code-server/releases/download/v$VERSION/code-server-$VERSION-linux-amd64.tar.gz \\\n  | tar -C ~/.local/lib -xz\nmv ~/.local/lib/code-server-$VERSION-linux-amd64 ~/.local/lib/code-server-$VERSION\nln -s ~/.local/lib/code-server-$VERSION/bin/code-server ~/.local/bin/code-server\nPATH=\"~/.local/bin:$PATH\"\ncode-server\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Debian, Ubuntu\n\n> The standalone arm64 .deb does not support Ubuntu 16.04 or earlier. Please\n> upgrade or [build with npm](#npm).\n\n```bash\ncurl -fOL https://github.com/coder/code-server/releases/download/v$VERSION/code-server_${VERSION}_amd64.deb\nsudo dpkg -i code-server_${VERSION}_amd64.deb\nsudo systemctl enable --now code-server@$USER\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Fedora, CentOS, RHEL, SUSE\n\n> The standalone arm64 .rpm does not support CentOS 7. Please upgrade or [build\n> with npm](#npm).\n\n```bash\ncurl -fOL https://github.com/coder/code-server/releases/download/v$VERSION/code-server-$VERSION-amd64.rpm\nsudo rpm -i code-server-$VERSION-amd64.rpm\nsudo systemctl enable --now code-server@$USER\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Arch Linux\n\n```bash\n# Install code-server from the AUR using yay.\nyay -S code-server\nsudo systemctl enable --now code-server@$USER\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n```bash\n# Install code-server from the AUR with plain makepkg.\ngit clone https://aur.archlinux.org/code-server.git\ncd code-server\nmakepkg -si\nsudo systemctl enable --now code-server@$USER\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Artix Linux\n\n```bash\n# Install code-server from the AUR\ngit clone https://aur.archlinux.org/code-server.git\ncd code-server\nmakepkg -si\n```\n\nSave the file as `code-server` in `/etc/init.d/` and make it executable with `chmod +x code-server`. Put your username in line 3.\n\n```bash\n#!/sbin/openrc-run\nname=$RC_SVCNAME\ndescription=\"$name - VS Code on a remote server\"\nuser=\"\" # your username here\nhomedir=\"/home/$user\"\ncommand=\"$(which code-server)\"\n# Just because you can do this does not mean you should. Use ~/.config/code-server/config.yaml instead\n#command_args=\"--extensions-dir $homedir/.local/share/$name/extensions --user-data-dir $homedir/.local/share/$name --disable-telemetry\"\ncommand_user=\"$user:$user\"\npidfile=\"/run/$name/$name.pid\"\ncommand_background=\"yes\"\nextra_commands=\"report\"\n\ndepend() {\n  use logger dns\n  need net\n}\n\nstart_pre() {\n  checkpath --directory --owner $command_user --mode 0755 /run/$name /var/log/$name\n}\n\nstart() {\n  default_start\n  report\n}\n\nstop() {\n  default_stop\n}\n\nstatus() {\n  default_status\n  report\n}\n\nreport() {\n  # Report to the user\n  einfo \"Reading configuration from ~/.config/code-server/config.yaml\"\n}\n```\n\nStart on boot with default runlevel\n\n```\nrc-update add code-server default\n```\n\nStart the service immediately\n\n```\nrc-service code-server start\n```\n\n## macOS\n\n```bash\nbrew install code-server\nbrew services start code-server\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Docker\n\n```bash\n# This will start a code-server container and expose it at http://127.0.0.1:8080.\n# It will also mount your current directory into the container as `/home/coder/project`\n# and forward your UID/GID so that all file system operations occur as your user outside\n# the container.\n#\n# Your $HOME/.config is mounted at $HOME/.config within the container to ensure you can\n# easily access/modify your code-server config in $HOME/.config/code-server/config.json\n# outside the container.\nmkdir -p ~/.config\ndocker run -it --name code-server -p 127.0.0.1:8080:8080 \\\n  -v \"$HOME/.local:/home/coder/.local\" \\\n  -v \"$HOME/.config:/home/coder/.config\" \\\n  -v \"$PWD:/home/coder/project\" \\\n  -u \"$(id -u):$(id -g)\" \\\n  -e \"DOCKER_USER=$USER\" \\\n  codercom/code-server:latest\n```\n\nOur official image supports `amd64` and `arm64`. For `arm32` support, you can\nuse a [community-maintained code-server\nalternative](https://hub.docker.com/r/linuxserver/code-server).\n\n## Helm\n\nYou can install code-server using the [Helm package manager](https://coder.com/docs/code-server/latest/helm).\n\n## Windows\n\nWe currently [do not publish Windows\nreleases](https://github.com/coder/code-server/issues/1397). We recommend\ninstalling code-server onto Windows with [`npm`](#npm).\n\n## Raspberry Pi\n\nWe recommend installing code-server onto Raspberry Pi with [`npm`](#npm).\n\nIf you see an error related to `node-gyp` during installation, See [#5174](https://github.com/coder/code-server/issues/5174) for more information.\n\n## Termux\n\nPlease see code-server's [Termux docs](./termux.md#installation) for more\ninformation.\n\n## Cloud providers\n\nWe maintain [one-click apps and install scripts for cloud\nproviders](https://github.com/coder/deploy-code-server) such as DigitalOcean,\nRailway, Heroku, and Azure.\n\n## Uninstall\n\ncode-server can be completely uninstalled by removing the application directory, and your user configuration directory.\n\nTo delete settings and data:\n\n```shell\nrm -rf ~/.local/share/code-server ~/.config/code-server\n```\n\n### install.sh\n\nIf you installed with the install script, by default code-server will be in `~/.local/lib/code-server-<version>` and you can remove it with `rm -rf`. e.g.\n\n```shell\nrm -rf ~/.local/lib/code-server-*\n```\n\n### Homebrew\n\nTo remove the code-server homebrew package, run:\n\n```shell\nbrew remove code-server\n\n# Alternatively\nbrew uninstall code-server\n```\n\n### npm\n\nTo remove the code-server global module, run:\n\n```shell\nnpm uninstall --global code-server\n```\n\n### Debian, Ubuntu\n\nTo uninstall, run:\n\n```shell\nsudo apt remove code-server\n```\n"
  },
  {
    "path": "docs/ios.md",
    "content": "# Using code-server on iOS with iSH\n\n1. Install iSH from the [App Store](https://apps.apple.com/us/app/ish-shell/id1436902243)\n2. Install `curl` and `nano` with `apk add curl nano`\n3. Configure iSH to use an earlier version of NodeJS with `nano /etc/apk/repositories` and edit `v3.14` to `v3.12` on both repository links.\n4. Install `nodejs` and `npm` with `apk add nodejs npm`\n5. Install code-server with `curl -fsSL https://code-server.dev/install.sh | sh`\n6. Run code-server with `code-server`\n7. Access on localhost:8080 in your browser\n"
  },
  {
    "path": "docs/ipad.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# iPad\n\n- [Using the code-server progressive web app (PWA)](#using-the-code-server-progressive-web-app-pwa)\n- [Access code-server using Servediter](#access-code-server-using-servediter)\n- [Raspberry Pi USB-C network](#raspberry-pi-usb-c-network)\n- [Recommendations](#recommendations)\n- [Known issues](#known-issues)\n  - [Workaround for issue with `ctrl+c` not stopping a running process in the terminal](#workaround-for-issue-with-ctrlc-not-stopping-a-running-process-in-the-terminal)\n- [Access code-server with a self-signed certificate on an iPad](#access-code-server-with-a-self-signed-certificate-on-an-ipad)\n  - [Certificate requirements](#certificate-requirements)\n  - [Sharing a self-signed certificate with an iPad](#sharing-a-self-signed-certificate-with-an-ipad)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\nOnce you've installed code-server, you can access it from an iPad.\n\n## Using the code-server progressive web app (PWA)\n\nTo use code-server on an iPad, we recommend installing the code-server\nprogressive web app (PWA):\n\n1. Open code-server in Safari.\n2. Click the **Share** icon.\n3. Click **Add to Home Screen**.\n\nYou can now open code-server from the Home screen, and when you do, you'll be\nusing the PWA. Running code-server as a PWA gets you more screen real estate and\naccess to top-level keyboard shortcuts since its running like a native app.\n\nFor example, you can use `cmd+w` to close an active file in the workbench. You\ncan add this to `keybindings.json`:\n\n1. Open code-server\n2. Go to **Command Palette** > **Open Keyboard Shortcuts (JSON)**\n3. Add the following to `keybindings.json`\n\n   ```json\n   {\n     \"key\": \"cmd+w\",\n     \"command\": \"workbench.action.closeActiveEditor\"\n   }\n   ```\n\n4. Test the command by using `cmd+w` to close an active file.\n\n## Access code-server using Servediter\n\nIf you are unable to get the self-signed certificate working, or you do not have a domain\nname to use, you can use [Servediter for code-server](https://apps.apple.com/us/app/servediter-for-code-server/id1504491325).\n\n> Servediter for code-server is **not** officially supported by the code-server team!\n\nTo use Servediter:\n\n1. Download the app from the App Store.\n2. When prompted, provide your server information. If you are running a local\n   server or a [Raspberry Pi connected via USB-C](#raspberry-pi-usb-c-network), you will input your settings\n   into **Self Hosted Server**.\n\n## Raspberry Pi USB-C network\n\nWe've heard of users having great success using code-server on an iPad connected\nto a Raspberry Pi via USB-C (the Raspberry Pi provides both power and direct\nnetwork access). Setting this up requires you to turn on **Network over USB-C**\non the Raspberry Pi, then continuing with code-server as usual on the iPad.\n\nFor more information, see:\n\n- [General introduction to Pi as an iPad\n  accessory](https://www.youtube.com/watch?v=IR6sDcKo3V8)\n- [iPad with Pi FAQ](https://www.youtube.com/watch?v=SPSlyqo5Q2Q)\n- [Technical guide to connecting a Raspberry Pi to an\n  iPad](https://www.geeky-gadgets.com/connect-a-raspberry-pi-4-to-an-ipad-pro-21-01-2020/)\n\nYou may also find the following tips from [Acker\nApple](http://github.com/ackerapple/) helpful:\n\n> Here are my keys to success. I bought a 4\" touch screen with fan included that\n> attaches as a case to the Pi. I use the touch screen for anytime I have\n> connection issues, otherwise I turn off the Pi screen. I gave my Pi a network\n> name so I can easily connect at home on wifi or when on go with 1 usb-c cable\n> that supplys both power and network connectivity. Lastly, not all usb-c cables\n> are equal and not all will work so try different usb-c cables if you are going\n> mad (confirm over wifi first then move to cable).\n\n## Recommendations\n\nOnce you can access code-server on your iPad, you may find the following tips\nand tricks helpful:\n\n- Use multi-task mode to make code changes and see the browser at the same time\n  - This prevents the iOS background from dropping an app's state if you are\n    switching between code-server and browser (with both in full-screen)\n- Be sure you are using the debug/terminal that is built into VS Code so that\n  you don’t need another terminal app running\n  - This also prevents switching between full screen apps and losing your view\n    due to iOS' background app memory management\n\n## Known issues\n\n- Getting self-signed certificates to work [is an involved\n  process](#access-code-server-with-a-self-signed-certificate-on-an-ipad)\n- Keyboard issues:\n  - The keyboard disappear sometimes\n    [#979](https://github.com/coder/code-server/issues/979)\n  - Some expectations regarding shortcuts may not be met:\n    - `cmd + n` opens new browser window instead of new file, and it's difficult\n      to set alternative as a workaround\n    - In general, expect to edit your keyboard shortcuts\n  - There's no escape key by default on the Magic Keyboard, so most users set\n    the globe key to be an escape key\n- Trackpad scrolling does not work on iPadOS < 14.5\n  ([#1455](https://github.com/coder/code-server/issues/1455))\n  - [WebKit fix](https://bugs.webkit.org/show_bug.cgi?id=210071#c13)\n- Keyboard may lose focus in Safari / split view [#4182](https://github.com/coder/code-server/issues/4182)\n- Terminal text does not appear by default [#3824](https://github.com/coder/code-server/issues/3824)\n- Copy & paste in terminal does not work well with keyboard shortcuts [#3491](https://github.com/coder/code-server/issues/3491)\n- `ctrl+c` does not stop a long-running process in the browser\n  - Tracking upstream issue here:\n    [#114009](https://github.com/microsoft/vscode/issues/114009)\n  - See [workaround](#ctrl-c-workaround)\n\nAdditionally, see [issues in the code-server repo that are tagged with the `os-ios`\nlabel](https://github.com/coder/code-server/issues?q=is%3Aopen+is%3Aissue+label%3Aos-ios)\nfor more information.\n\n### Workaround for issue with `ctrl+c` not stopping a running process in the terminal\n\nThis's currently an issue with `ctrl+c` not stopping a running process in the\nintegrated terminal. We have filed an issue upstream and are tracking\n[here](https://github.com/microsoft/vscode/issues/114009).\n\nIn the meantime, you can manually define a shortcut as a workaround:\n\n1. Open the Command Palette\n2. Look for **Preferences: Open Keyboard Shortcuts (JSON)**\n3. Add the following snippet:\n\n   ```json\n   {\n     \"key\": \"ctrl+c\",\n     \"command\": \"workbench.action.terminal.sendSequence\",\n     \"args\": {\n       \"text\": \"\\u0003\"\n     },\n     \"when\": \"terminalFocus\"\n   }\n   ```\n\n_Source: [StackOverflow](https://stackoverflow.com/a/52735954/3015595)_\n\n## Access code-server with a self-signed certificate on an iPad\n\nIf you've installed code-server and are [running it with a self-signed\ncertificate](./guide.md#using-a-self-signed-certificate), you may see multiple\nsecurity warnings from Safari. To fix this, you'll need to install the\nself-signed certificate generated by code-server as a profile on your device (you'll also need to do this to\nenable WebSocket connections).\n\n### Certificate requirements\n\n- We're assuming that you're using the self-signed certificate code-server\n  generates for you (if not, make sure that your certificate [abides by the\n  guidelines issued by Apple](https://support.apple.com/en-us/HT210176)).\n- We've noticed that the certificate has to include `basicConstraints=CA:true`.\n- Your certificate must have a subject alt name that matches the hostname you'll\n  use to access code-server from the iPad. You can pass this name to code-server\n  so that it generates the certificate correctly using `--cert-host`.\n\n### Sharing a self-signed certificate with an iPad\n\nTo share a self-signed certificate with an iPad:\n\n1. Get the location of the certificate code-server generated; code-server prints\n   the certificate's location in its logs:\n\n   ```console\n   [2020-10-30T08:55:45.139Z] info - Using generated certificate and key for HTTPS: ~/.local/share/code-server/mymbp_local.crt\n   ```\n\n2. Send the certificate to the iPad, either by emailing it to yourself or using\n   Apple's Airdrop feature.\n\n3. Open the `*.crt` file so that you're prompted to go into Settings to install.\n\n4. Go to **Settings** > **General** > **Profile**, and select the profile. Tap **Install**.\n\n5. Go to **Settings** > **About** > **Certificate Trust Settings** and [enable\n   full trust for your certificate](https://support.apple.com/en-us/HT204477).\n\nYou should be able to access code-server without all of Safari's warnings now.\n\n**warning**: Your iPad must access code-server via a domain name. It could be local\nDNS like `mymacbookpro.local`, but it must be a domain name. Otherwise, Safari will\nnot allow WebSockets connections.\n"
  },
  {
    "path": "docs/manifest.json",
    "content": "{\n  \"versions\": [\"v4.8.0\"],\n  \"routes\": [\n    {\n      \"title\": \"Home\",\n      \"description\": \"Learn how to install and run code-server.\",\n      \"path\": \"./README.md\",\n      \"icon_path\": \"assets/images/icons/home.svg\"\n    },\n    {\n      \"title\": \"Requirements\",\n      \"description\": \"Learn about what you need to run code-server.\",\n      \"icon_path\": \"assets/images/icons/requirements.svg\",\n      \"path\": \"./requirements.md\"\n    },\n    {\n      \"title\": \"Install\",\n      \"description\": \"How to install code-server.\",\n      \"icon_path\": \"assets/images/icons/wrench.svg\",\n      \"path\": \"./install.md\",\n      \"children\": [\n        {\n          \"title\": \"npm\",\n          \"description\": \"How to install code-server using npm\",\n          \"path\": \"./npm.md\"\n        },\n        {\n          \"title\": \"Helm\",\n          \"description\": \"How to install code-server using the Helm package manager\",\n          \"path\": \"./helm.md\"\n        }\n      ]\n    },\n    {\n      \"title\": \"Usage\",\n      \"description\": \"How to set up and use code-server.\",\n      \"icon_path\": \"assets/images/icons/usage.svg\",\n      \"path\": \"./guide.md\",\n      \"children\": [\n        {\n          \"title\": \"Coder\",\n          \"description\": \"How to run code-server in Coder\",\n          \"path\": \"./coder.md\"\n        },\n        {\n          \"title\": \"iPad\",\n          \"description\": \"How to access your code-server installation using an iPad.\",\n          \"path\": \"./ipad.md\"\n        },\n        {\n          \"title\": \"Termux\",\n          \"description\": \"How to install Termux to run code-server on an Android device.\",\n          \"path\": \"./termux.md\"\n        },\n        {\n          \"title\": \"iOS\",\n          \"description\": \"How to use code-server on iOS with iSH.\",\n          \"path\": \"./ios.md\"\n        },\n        {\n          \"title\": \"Android\",\n          \"description\": \"How to run code-server on an Android device using UserLAnd.\",\n          \"path\": \"./android.md\"\n        }\n      ]\n    },\n    {\n      \"title\": \"Collaboration\",\n      \"description\": \"How to setup real time collaboration using code server.\",\n      \"icon_path\": \"assets/images/icons/collab.svg\",\n      \"path\": \"./collaboration.md\"\n    },\n    {\n      \"title\": \"Upgrade\",\n      \"description\": \"How to upgrade code-server.\",\n      \"icon_path\": \"assets/images/icons/upgrade.svg\",\n      \"path\": \"./upgrade.md\"\n    },\n    {\n      \"title\": \"FAQ\",\n      \"description\": \"Frequently asked questions on installing and running code-server.\",\n      \"icon_path\": \"assets/images/icons/faq.svg\",\n      \"path\": \"./FAQ.md\"\n    },\n    {\n      \"title\": \"Contributing\",\n      \"description\": \"How to contribute to code-server.\",\n      \"icon_path\": \"assets/images/icons/contributing.svg\",\n      \"path\": \"./CONTRIBUTING.md\",\n      \"children\": [\n        {\n          \"title\": \"Code of conduct\",\n          \"description\": \"Coder expects contributors to code-server to behave in a manner that creates an open and welcoming environment.\",\n          \"path\": \"./CODE_OF_CONDUCT.md\"\n        },\n        {\n          \"title\": \"Maintenance\",\n          \"description\": \"Learn about the workflow followed by code-server's maintainers.\",\n          \"path\": \"./MAINTAINING.md\"\n        },\n        {\n          \"title\": \"Triage\",\n          \"description\": \"How the maintainers triage issues with code-server.\",\n          \"path\": \"./triage.md\"\n        },\n        {\n          \"title\": \"Security\",\n          \"description\": \"Learn about the tools used to detect vulnerabilities in code-server, and how you can report vulnerabilities.\",\n          \"path\": \"./SECURITY.md\"\n        }\n      ]\n    }\n  ]\n}\n"
  },
  {
    "path": "docs/npm.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# npm Install Requirements\n\n- [Node.js version](#nodejs-version)\n- [Ubuntu, Debian](#ubuntu-debian)\n- [Fedora, CentOS, RHEL](#fedora-centos-rhel)\n- [Alpine](#alpine)\n- [macOS](#macos)\n- [FreeBSD](#freebsd)\n- [Windows](#windows)\n- [Installing](#installing)\n- [Troubleshooting](#troubleshooting)\n  - [Issues with Node.js after version upgrades](#issues-with-nodejs-after-version-upgrades)\n  - [Debugging install issues with npm](#debugging-install-issues-with-npm)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\nIf you're installing code-server via `npm`, you'll need to install additional\ndependencies required to build the native modules used by VS Code. This article\nincludes installing instructions based on your operating system.\n\n> **WARNING**: Do not use `yarn` to install code-server. Unlike `npm`, it does not respect\n> lockfiles for distributed applications. It will instead use the latest version\n> available at installation time - which might not be the one used for a given\n> code-server release, and [might lead to unexpected behavior](https://github.com/coder/code-server/issues/4927).\n\n## Node.js version\n\nWe use the same major version of Node.js shipped with Code's remote, which is\ncurrently `22.x`. VS Code also [lists Node.js\nrequirements](https://github.com/microsoft/vscode/wiki/How-to-Contribute#prerequisites).\n\nUsing other versions of Node.js [may lead to unexpected\nbehavior](https://github.com/coder/code-server/issues/1633).\n\n## Ubuntu, Debian\n\n```bash\nsudo apt-get install -y \\\n  build-essential \\\n  pkg-config \\\n  python3\nnpm config set python python3\n```\n\nProceed to [installing](#installing)\n\n## Fedora, CentOS, RHEL\n\n```bash\nsudo yum groupinstall -y 'Development Tools'\nsudo yum config-manager --set-enabled PowerTools # unnecessary on CentOS 7\nsudo yum install -y python2\nnpm config set python python2\n```\n\nProceed to [installing](#installing)\n\n## Alpine\n\n```bash\napk add alpine-sdk bash libstdc++ libc6-compat python3 krb5-dev\n```\n\nProceed to [installing](#installing)\n\n## macOS\n\n```bash\nxcode-select --install\n```\n\nProceed to [installing](#installing)\n\n## FreeBSD\n\n```sh\npkg install -y git python npm-node22 pkgconf\npkg install -y libinotify\n```\n\nProceed to [installing](#installing)\n\n## Windows\n\nInstalling code-server requires all of the [prerequisites for VS Code development](https://github.com/Microsoft/vscode/wiki/How-to-Contribute#prerequisites). When installing the C++ compiler tool chain, we recommend using \"Option 2: Visual Studio 2019\" for best results.\n\nNext, install code-server with:\n\n```bash\nnpm install --global code-server\ncode-server\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\nA `postinstall.sh` script will attempt to run. Select your terminal (e.g., Git bash) as the default shell for npm run-scripts. If an additional dialog does not appear, run the install command again.\n\nIf the `code-server` command is not found, you'll need to [add a directory to your PATH](https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/). To find the directory, use the following command:\n\n```shell\nnpm config get prefix\n```\n\nFor help and additional troubleshooting, see [#1397](https://github.com/coder/code-server/issues/1397).\n\n## Installing\n\nAfter adding the dependencies for your OS, install the code-server package globally:\n\n```bash\nnpm install --global code-server\ncode-server\n# Now visit http://127.0.0.1:8080. Your password is in ~/.config/code-server/config.yaml\n```\n\n## Troubleshooting\n\nIf you need further assistance, post on our [GitHub Discussions\npage](https://github.com/coder/code-server/discussions).\n\n### Issues with Node.js after version upgrades\n\nOccasionally, you may run into issues with Node.js.\n\nIf you install code-server using `npm`, and you upgrade your Node.js\nversion, you may need to reinstall code-server to recompile native modules.\nSometimes, you can get around this by navigating into code-server's `lib/vscode`\ndirectory and running `npm rebuild` to recompile the modules.\n\nA step-by-step example of how you might do this is:\n\n1. Install code-server: `brew install code-server`\n2. Navigate into the directory: `cd /usr/local/Cellar/code-server/<version>/libexec/lib/vscode/`\n3. Recompile the native modules: `npm rebuild`\n4. Restart code-server\n\n### Debugging install issues with npm\n\nTo debug installation issues, install with `npm`:\n\n```shell\n# Uninstall\nnpm uninstall --global code-server > /dev/null 2>&1\n\n# Install with logging\nnpm install --loglevel verbose --global code-server\n```\n"
  },
  {
    "path": "docs/requirements.md",
    "content": "# Requirements\n\nYou'll need a machine on which you can run code-server. You can use a physical\nmachine you have, or you can use a VM on GCP/AWS.\n\nAt the minimum, we recommend:\n\n- 1 GB of RAM\n- 2 CPU cores\n\nYou can use any Linux distribution, but [our\ndocs](https://coder.com/docs/code-server/latest/guide) assume that you're using\nDebian hosted by Google Cloud (see the following section for instructions on\nsetting this up).\n\nYour environment must have WebSockets enabled, since code-server uses WebSockets\nfor communication between the browser and the server.\n\n## Set up a VM on Google Cloud\n\nThe following steps walk you through setting up a VM running Debian using Google\nCloud (though you are welcome to use any machine or VM provider).\n\nIf you're [signing up with Google](https://console.cloud.google.com/getting-started) for the first time, you should get a 3-month trial with\n\\$300 of credits.\n\nAfter you sign up and create a new Google Cloud Provider (GCP) project, create a\nnew Compute Engine VM instance:\n\n1. Using the sidebar, navigate to **Compute Engine** > **VM Instances**.\n2. Click **Create Instance**.\n3. Provide a **name** for new instance.\n4. Choose the **region** that's closest to you based on [GCP\n   ping](https://gcping.com/).\n5. Choose a **zone** (any option is fine).\n6. We recommend choosing an **E2 series instance** from the [general-purpose\n   family](https://cloud.google.com/compute/docs/machine-types#general_purpose).\n7. Change the instance type to **custom** and set at least **2 cores** and **2\n   GB of RAM**. You can add more resources if desired, though you can also edit\n   your instance at a later point.\n8. Though optional, we highly recommend switching the persistent disk to an SSD\n   with at least 32 GB. To do so, click **change** under **Boot Disk**. Then,\n   change the type to **SSD Persistent Disk**, and set the size to **32**. (You\n   can also grow your disk at a later date).\n9. Go to **Networking** > **Networking Interfaces** and edit the existing\n   interface to use a static internal IP. Click **Done** to save.\n10. If you don't have a [project-wide SSH\n    key](https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys#project-wide),\n    go to **Security** > **SSH Keys** to add your public key.\n11. Click **Create** to proceed.\n\nNotes:\n\n- To lower costs, you can shut down your server when you're not using it.\n- We recommend using the `gcloud cli` to avoid using the GCP Dashboard if possible.\n- For serving code-server over HTTPS, we recommend using an external domain name along with a service such as Let's Encrypt\n"
  },
  {
    "path": "docs/termux.md",
    "content": "<!-- prettier-ignore-start -->\n<!-- START doctoc generated TOC please keep comment here to allow auto update -->\n<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->\n# Termux\n\n- [Install](#install)\n- [NPM Installation](#npm-installation)\n- [Upgrade](#upgrade)\n- [Known Issues](#known-issues)\n  - [Git won't work in `/sdcard`](#git-wont-work-in-sdcard)\n  - [Many extensions including language packs fail to install](#many-extensions-including-language-packs-fail-to-install)\n- [Extra](#extra)\n  - [Keyboard Shortcuts and Tab Key](#keyboard-shortcuts-and-tab-key)\n  - [Create a new user](#create-a-new-user)\n  - [Install Go](#install-go)\n  - [Install Python](#install-python)\n\n<!-- END doctoc generated TOC please keep comment here to allow auto update -->\n<!-- prettier-ignore-end -->\n\n## Install\n\n1. Get [Termux](https://f-droid.org/en/packages/com.termux/) from **F-Droid**.\n2. Run `pkg install tur-repo`\n3. Run `pkg install code-server`\n4. You can now start code server by simply running `code-server`.\n\n## NPM Installation\n\n1. Get [Termux](https://f-droid.org/en/packages/com.termux/) from **F-Droid**.\n\n2. We will now change using the following command.\n\n```sh\ntermux-change-repo\n```\n\nNow select `Main Repository` then change repo to `Mirrors by Grimler Hosted on grimler.se`.\n\n3. After successfully updating of repository update and upgrade all the packages by the following command\n\n```sh\npkg update\npkg upgrade -y\n```\n\n4. Now let's install requirement dependancy.\n\n```sh\npkg install -y \\\n  build-essential \\\n  binutils \\\n  pkg-config \\\n  python3 \\\n  nodejs-lts\nnpm config set python python3\nnode -v\n```\n\nyou will get Node version `v22`\n\n5. Now install code-server following our guide on [installing with npm](./npm.md)\n\n6. Congratulation code-server is installed on your device using the following command.\n\n```sh\ncode-server --auth none\n```\n\n7. If already installed then use the following command for upgradation.\n\n```\nnpm update --global code-server\n```\n\n## Upgrade\n\n1. Remove all previous installs `rm -rf ~/.local/lib/code-server-*`\n2. Run the install script again `curl -fsSL https://code-server.dev/install.sh | sh`\n\n## Known Issues\n\n### Git won't work in `/sdcard`\n\nIssue : Using git in the `/sdcard` directory will fail during cloning/commit/staging/etc...\\\nFix : None\\\nPotential Workaround :\n\n1. Create a soft-link from the debian-fs to your folder in `/sdcard`\n2. Use git from termux (preferred)\n\n### Many extensions including language packs fail to install\n\nIssue: Android is not seen as a Linux environment but as a separate, unsupported platform, so code-server only allows [Web Extensions](https://code.visualstudio.com/api/extension-guides/web-extensions), refusing to download extensions that run on the server.\\\nFix: None\\\nPotential workarounds :\n\nEither\n\n- Manually download extensions as `.vsix` file and install them via `Extensions: Install from VSIX...` in the Command Palette.\n\n- Use an override to pretend the platform is Linux:\n\nCreate a JS script that patches `process.platform`:\n\n```js\n// android-as-linux.js\nObject.defineProperty(process, \"platform\", {\n  get() {\n    return \"linux\"\n  },\n})\n```\n\nThen use Node's `--require` option to make sure it is loaded before `code-server` starts:\n\n```sh\nNODE_OPTIONS=\"--require /path/to/android-as-linux.js\" code-server\n```\n\n⚠️ Note that Android and Linux are not 100% compatible, so use these workarounds at your own risk. Extensions that have native dependencies other than Node or that directly interact with the OS might cause issues.\n\n## Extra\n\n### Keyboard Shortcuts and Tab Key\n\nIn order to support the tab key and use keyboard shortcuts, add this to your\nsettings.json:\n\n```json\n{\n  \"keyboard.dispatch\": \"keyCode\"\n}\n```\n\n### Create a new user\n\nTo create a new user follow these simple steps -\n\n1. Create a new user by running `useradd <username> -m`.\n2. Change the password by running `passwd <username>`.\n3. Give your new user sudo access by running `visudo`, scroll down to `User privilege specification` and add the following line after root `username ALL=(ALL:ALL) ALL`.\n4. Now edit the `/etc/passwd` file with your command line editor of choice and at the end of the line that specifies your user change `/bin/sh` to `/bin/bash`.\n5. Now switch users by running `su - <username>`\n\n- Remember the `-` betweeen `su` and username is required to execute `/etc/profile`,\\\n  since `/etc/profile` may have some necessary things to be executed you should always add a `-`.\n\n### Install Go\n\n> From https://golang.org/doc/install\n\n1. Go to https://golang.org/dl/ and copy the download link for `linux arm` and run the following:\n\n```bash\nwget download_link\n```\n\n2. Extract the downloaded archive. (This step will erase all previous GO installs, make sure to create a backup if you have previously installed GO)\n\n```bash\nrm -rf /usr/local/go && tar -C /usr/local -xzf archive_name\n```\n\n3. Run `nano /etc/profile` and add the following line `export PATH=$PATH:/usr/local/go/bin`.\n4. Now run `exit` (depending on if you have switched users or not, you may have to run `exit` multiple times to get to normal termux shell) and start Debian again.\n5. Check if your install was successful by running `go version`\n\n### Install Python\n\n> Run these commands as root\n\n1. Run the following commands to install required packages to build python:\n\n```bash\nsudo apt-get update\nsudo apt-get install make build-essential libssl-dev zlib1g-dev \\\n  libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \\\n  libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev\n```\n\n2. Install [pyenv](https://github.com/pyenv/pyenv/) from [pyenv-installer](https://github.com/pyenv/pyenv-installer) by running:\n\n```bash\ncurl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash\n```\n\n3. Run `nano /etc/profile` and add the following:\n\n```bash\nexport PYENV_ROOT=\"/root/.pyenv\"\nexport PATH=\"/root/.pyenv/bin:$PATH\"\neval \"$(pyenv init --path)\"\neval \"$(pyenv virtualenv-init -)\"\n```\n\n4. Exit and start Debian again.\n5. Run `pyenv versions` to list all installable versions.\n6. Run `pyenv install version` to install the desired python version.\n   > The build process may take some time (an hour or 2 depending on your device).\n7. Run `touch /root/.pyenv/version && echo \"your_version_here\" > /root/.pyenv/version`\n8. (You may have to start Debian again) Run `python3 -V` to verify if PATH works or not.\n   > If `python3` doesn't work but pyenv says that the install was successful in step 6 then try running `$PYENV_ROOT/versions/your_version/bin/python3`.\n"
  },
  {
    "path": "docs/triage.md",
    "content": "# Triage\n\nTriaging code-server issues is done with the following issue filter:\n\n```text\nis:issue is:open no:project sort:created-asc -label:blocked -label:upstream -label:waiting-for-info -label:extension-request\n```\n\nThis will show issues that:\n\n1. Are open.\n1. Have no assigned project.\n1. Are not `blocked` or tagged for work by `upstream` (the VS Code core team).\n   If an upstream issue is detrimental to the code-server experience we may fix\n   it in our patch instead of waiting for the VS Code team to fix it. Someone\n   should periodically go through these issues to see if they can be unblocked!\n1. Are not labeled `waiting-for-info`.\n1. Are not extension requests.\n\n## Triage process\n\n1. If an issue is a question/discussion, it should be converted into a GitHub\n   discussion.\n1. Otherwise, give the issue the appropriate labels (feel free to create new\n   ones if necessary). There are no hard and set rules for labels. We don't have\n   many so look through and see how they've been used throughout the repository.\n   They all also have descriptions.\n1. If more information is required, please ask the submitter and tag as\n   `waiting-for-info` and wait.\n1. Finally, the issue should be moved into the\n   [code-server](https://github.com/coder/code-server/projects/1) project where we\n   pick out issues to fix and track their progress.\n\nWe also use [milestones](https://github.com/coder/code-server/milestones) to track\nwhat issues are planned/or were closed for what release.\n"
  },
  {
    "path": "docs/upgrade.md",
    "content": "# Upgrade\n\nTo upgrade code-server, install the new version over the old version. All user\ndata is in `~/.local/share/code-server`, so they are preserved between\ninstallations.\n"
  },
  {
    "path": "eslint.config.mjs",
    "content": "import { fixupConfigRules } from \"@eslint/compat\"\nimport globals from \"globals\"\nimport tsParser from \"@typescript-eslint/parser\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport js from \"@eslint/js\"\nimport { FlatCompat } from \"@eslint/eslintrc\"\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = path.dirname(__filename)\nconst compat = new FlatCompat({\n  baseDirectory: __dirname,\n  recommendedConfig: js.configs.recommended,\n  allConfig: js.configs.all,\n})\n\nexport default [\n  ...fixupConfigRules(\n    compat.extends(\n      \"eslint:recommended\",\n      \"plugin:@typescript-eslint/recommended\",\n      \"plugin:import/recommended\",\n      \"plugin:import/typescript\",\n      \"plugin:prettier/recommended\",\n      \"prettier\",\n    ),\n  ),\n  {\n    languageOptions: {\n      globals: {\n        ...globals.browser,\n        ...globals.jest,\n        ...globals.node,\n      },\n\n      parser: tsParser,\n      ecmaVersion: 2018,\n      sourceType: \"module\",\n    },\n\n    settings: {\n      \"import/resolver\": {\n        typescript: {\n          alwaysTryTypes: true,\n        },\n      },\n    },\n\n    rules: {\n      \"@typescript-eslint/no-unused-vars\": [\n        \"error\",\n        {\n          args: \"none\",\n        },\n      ],\n\n      \"no-dupe-class-members\": \"off\",\n      \"@typescript-eslint/no-use-before-define\": \"off\",\n      \"@typescript-eslint/no-non-null-assertion\": \"off\",\n      \"@typescript-eslint/ban-types\": \"off\",\n      \"@typescript-eslint/no-var-requires\": \"off\",\n      \"@typescript-eslint/explicit-module-boundary-types\": \"off\",\n      \"@typescript-eslint/no-explicit-any\": \"off\",\n      \"@typescript-eslint/no-extra-semi\": \"off\",\n      \"@typescript-eslint/no-require-imports\": \"off\",\n      \"@typescript-eslint/no-unused-vars\": \"off\", // TODO: Fix these.\n      \"@typescript-eslint/no-empty-object-type\": \"off\",\n      eqeqeq: \"error\",\n\n      \"import/order\": [\n        \"error\",\n        {\n          alphabetize: {\n            order: \"asc\",\n          },\n\n          groups: [[\"builtin\", \"external\", \"internal\"], \"parent\", \"sibling\"],\n        },\n      ],\n\n      \"no-async-promise-executor\": \"off\",\n    },\n  },\n]\n"
  },
  {
    "path": "flake.nix",
    "content": "{\n  description = \"code-server\";\n\n  inputs = {\n    nixpkgs.url = \"github:nixos/nixpkgs/nixos-unstable-small\";\n    flake-utils.url = \"github:numtide/flake-utils\";\n  };\n\n  outputs = { self, nixpkgs, flake-utils }:\n    flake-utils.lib.eachDefaultSystem\n      (system:\n        let pkgs = nixpkgs.legacyPackages.${system};\n            nodejs = pkgs.nodejs_22;\n        in {\n          devShells.default = pkgs.mkShell {\n            nativeBuildInputs = with pkgs; [\n              imagemagick\n              nodejs\n              python3\n              pkg-config\n              git\n              rsync\n              jq\n              moreutils\n              quilt\n              bats\n              openssl\n            ];\n            buildInputs = with pkgs; (lib.optionals (!stdenv.isDarwin) [ libsecret libkrb5 ]\n                          ++ (with xorg; [ libX11 libxkbfile ])\n                          ++ lib.optionals stdenv.isDarwin (with pkgs.darwin.apple_sdk.frameworks; [\n                            AppKit Cocoa CoreServices Security xcbuild\n                          ]));\n          };\n        }\n      );\n}\n"
  },
  {
    "path": "install.sh",
    "content": "#!/bin/sh\nset -eu\n\n# code-server's automatic install script.\n# See https://coder.com/docs/code-server/latest/install\n\nusage() {\n  arg0=\"$0\"\n  if [ \"$0\" = sh ]; then\n    arg0=\"curl -fsSL https://code-server.dev/install.sh | sh -s --\"\n  else\n    not_curl_usage=\"The latest script is available at https://code-server.dev/install.sh\n\"\n  fi\n\n  cath << EOF\nInstalls code-server.\nIt tries to use the system package manager if possible.\nAfter successful installation it explains how to start using code-server.\n\nPass in user@host to install code-server on user@host over ssh.\nThe remote host must have internet access.\n${not_curl_usage-}\nUsage:\n\n  $arg0 [--dry-run] [--version X.X.X] [--edge] [--method detect] \\\n        [--prefix ~/.local] [--rsh ssh] [user@host]\n\n  --dry-run\n      Echo the commands for the install process without running them.\n\n  --version X.X.X\n      Install a specific version instead of the latest.\n\n  --edge\n      Install the latest edge version instead of the latest stable version.\n\n  --method [detect | standalone]\n      Choose the installation method. Defaults to detect.\n      - detect detects the system package manager and tries to use it.\n        Full reference on the process is further below.\n      - standalone installs a standalone release archive into ~/.local\n        Add ~/.local/bin to your \\$PATH to use it.\n\n  --prefix <dir>\n      Sets the prefix used by standalone release archives. Defaults to ~/.local\n      The release is unarchived into ~/.local/lib/code-server-X.X.X\n      and the binary symlinked into ~/.local/bin/code-server\n      To install system wide pass --prefix=/usr/local\n\n  --rsh <bin>\n      Specifies the remote shell for remote installation. Defaults to ssh.\n\nThe detection method works as follows:\n  - Debian, Ubuntu, Raspbian: install the deb package from GitHub.\n  - Fedora, CentOS, RHEL, openSUSE: install the rpm package from GitHub.\n  - Arch Linux: install from the AUR (which pulls releases from GitHub).\n  - FreeBSD, Alpine: install from npm.\n  - macOS: install using Homebrew if installed otherwise install from GitHub.\n  - All others: install the release from GitHub.\n\nWe only build releases on GitHub for amd64 and arm64 on Linux and amd64 for\nmacOS. When the detection method tries to pull a release from GitHub it will\nfall back to installing from npm when there is no matching release for the\nsystem's operating system and architecture.\n\nThe standalone method will force installion using GitHub releases. It will not\nfall back to npm so on architectures without pre-built releases this will error.\n\nThe installer will cache all downloaded assets into ~/.cache/code-server\n\nMore installation docs are at https://coder.com/docs/code-server/latest/install\nEOF\n}\n\necho_latest_version() {\n  if [ \"${EDGE-}\" ]; then\n    version=\"$(curl -fsSL https://api.github.com/repos/coder/code-server/releases | awk 'match($0,/.*\"html_url\": \"(.*\\/releases\\/tag\\/.*)\".*/)' | head -n 1 | awk -F '\"' '{print $4}')\"\n  else\n    # https://gist.github.com/lukechilds/a83e1d7127b78fef38c2914c4ececc3c#gistcomment-2758860\n    version=\"$(curl -fsSLI -o /dev/null -w \"%{url_effective}\" https://github.com/coder/code-server/releases/latest)\"\n  fi\n  version=\"${version#https://github.com/coder/code-server/releases/tag/}\"\n  version=\"${version#v}\"\n  echo \"$version\"\n}\n\necho_npm_postinstall() {\n  echoh\n  cath << EOF\nnpm package has been installed.\n\nExtend your path to use code-server:\n  PATH=\"$NPM_BIN_DIR:\\$PATH\"\nThen run with:\n  code-server\nEOF\n}\n\necho_standalone_postinstall() {\n  echoh\n  cath << EOF\nStandalone release has been installed into $STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION\n\nExtend your path to use code-server:\n  PATH=\"$STANDALONE_INSTALL_PREFIX/bin:\\$PATH\"\nThen run with:\n  code-server\nEOF\n}\n\necho_brew_postinstall() {\n  echoh\n  cath << EOF\nBrew release has been installed.\n\nRun with:\n  code-server\nEOF\n}\n\necho_systemd_postinstall() {\n  echoh\n  cath << EOF\n$1 package has been installed.\n\nTo have systemd start code-server now and restart on boot:\n  sudo systemctl enable --now code-server@\\$USER\nOr, if you don't want/need a background service you can run:\n  code-server\nEOF\n}\n\necho_coder_postinstall() {\n  echoh\n  echoh \"Deploy code-server for your team with Coder: https://github.com/coder/coder\"\n}\n\nmain() {\n  if [ \"${TRACE-}\" ]; then\n    set -x\n  fi\n\n  unset \\\n    DRY_RUN \\\n    METHOD \\\n    OPTIONAL \\\n    ALL_FLAGS \\\n    RSH_ARGS \\\n    EDGE \\\n    RSH\n\n  ALL_FLAGS=\"\"\n  while [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n      -*)\n        ALL_FLAGS=\"${ALL_FLAGS} $1\"\n        ;;\n    esac\n\n    case \"$1\" in\n      --dry-run)\n        DRY_RUN=1\n        ;;\n      --method)\n        METHOD=\"$(parse_arg \"$@\")\"\n        shift\n        ;;\n      --method=*)\n        METHOD=\"$(parse_arg \"$@\")\"\n        ;;\n      --prefix)\n        STANDALONE_INSTALL_PREFIX=\"$(parse_arg \"$@\")\"\n        shift\n        ;;\n      --prefix=*)\n        STANDALONE_INSTALL_PREFIX=\"$(parse_arg \"$@\")\"\n        ;;\n      --version)\n        VERSION=\"$(parse_arg \"$@\")\"\n        shift\n        ;;\n      --version=*)\n        VERSION=\"$(parse_arg \"$@\")\"\n        ;;\n      --edge)\n        EDGE=1\n        ;;\n      --rsh)\n        RSH=\"$(parse_arg \"$@\")\"\n        shift\n        ;;\n      --rsh=*)\n        RSH=\"$(parse_arg \"$@\")\"\n        ;;\n      -h | --h | -help | --help)\n        usage\n        exit 0\n        ;;\n      --)\n        shift\n        # We remove the -- added above.\n        ALL_FLAGS=\"${ALL_FLAGS% --}\"\n        RSH_ARGS=\"$*\"\n        break\n        ;;\n      -*)\n        echoerr \"Unknown flag $1\"\n        echoerr \"Run with --help to see usage.\"\n        exit 1\n        ;;\n      *)\n        RSH_ARGS=\"$*\"\n        break\n        ;;\n    esac\n\n    shift\n  done\n\n  if [ \"${RSH_ARGS-}\" ]; then\n    RSH=\"${RSH-ssh}\"\n    echoh \"Installing remotely with $RSH $RSH_ARGS\"\n    curl -fsSL https://code-server.dev/install.sh | prefix \"$RSH_ARGS\" \"$RSH\" \"$RSH_ARGS\" sh -s -- \"$ALL_FLAGS\"\n    return\n  fi\n\n  METHOD=\"${METHOD-detect}\"\n  if [ \"$METHOD\" != detect ] && [ \"$METHOD\" != standalone ]; then\n    echoerr \"Unknown install method \\\"$METHOD\\\"\"\n    echoerr \"Run with --help to see usage.\"\n    exit 1\n  fi\n\n  # These are used by the various install_* functions that make use of GitHub\n  # releases in order to download and unpack the right release.\n  CACHE_DIR=$(echo_cache_dir)\n  STANDALONE_INSTALL_PREFIX=${STANDALONE_INSTALL_PREFIX:-$HOME/.local}\n  VERSION=${VERSION:-$(echo_latest_version)}\n  # These can be overridden for testing but shouldn't normally be used as it can\n  # result in a broken code-server.\n  OS=${OS:-$(os)}\n  ARCH=${ARCH:-$(arch)}\n\n  distro_name\n\n  # Standalone installs by pulling pre-built releases from GitHub.\n  if [ \"$METHOD\" = standalone ]; then\n    if has_standalone; then\n      install_standalone\n      echo_coder_postinstall\n      exit 0\n    else\n      echoerr \"There are no standalone releases for $ARCH\"\n      echoerr \"Please try again without '--method standalone'\"\n      exit 1\n    fi\n  fi\n\n  # DISTRO can be overridden for testing but shouldn't normally be used as it\n  # can result in a broken code-server.\n  DISTRO=${DISTRO:-$(distro)}\n\n  case $DISTRO in\n    # macOS uses brew when available and falls back to standalone. We only have\n    # amd64 for macOS so for anything else use npm.\n    macos)\n      BREW_PATH=\"${BREW_PATH-brew}\"\n      if command_exists \"$BREW_PATH\"; then\n        install_brew\n      else\n        echoh \"Homebrew not installed.\"\n        echoh \"Falling back to standalone installation.\"\n        npm_fallback install_standalone\n      fi\n      ;;\n    # The .deb and .rpm files are pulled from GitHub and we only have amd64 and\n    # arm64 there and need to fall back to npm otherwise.\n    debian) npm_fallback install_deb ;;\n    fedora | opensuse) npm_fallback install_rpm ;;\n    # Arch uses the AUR package which only supports amd64 and arm64 since it\n    # pulls releases from GitHub so we need to fall back to npm.\n    arch) npm_fallback install_aur ;;\n    # We don't have GitHub releases that work on Alpine or FreeBSD so we have no\n    # choice but to use npm here.\n    alpine | freebsd) install_npm ;;\n    # For anything else we'll try to install standalone but fall back to npm if\n    # we don't have releases for the architecture.\n    *)\n      echoh \"Unsupported package manager.\"\n      echoh \"Falling back to standalone installation.\"\n      npm_fallback install_standalone\n      ;;\n  esac\n\n  echo_coder_postinstall\n}\n\nparse_arg() {\n  case \"$1\" in\n    *=*)\n      # Remove everything after first equal sign.\n      opt=\"${1%%=*}\"\n      # Remove everything before first equal sign.\n      optarg=\"${1#*=}\"\n      if [ ! \"$optarg\" ] && [ ! \"${OPTIONAL-}\" ]; then\n        echoerr \"$opt requires an argument\"\n        echoerr \"Run with --help to see usage.\"\n        exit 1\n      fi\n      echo \"$optarg\"\n      return\n      ;;\n  esac\n\n  case \"${2-}\" in\n    \"\" | -*)\n      if [ ! \"${OPTIONAL-}\" ]; then\n        echoerr \"$1 requires an argument\"\n        echoerr \"Run with --help to see usage.\"\n        exit 1\n      fi\n      ;;\n    *)\n      echo \"$2\"\n      return\n      ;;\n  esac\n}\n\nfetch() {\n  URL=\"$1\"\n  FILE=\"$2\"\n\n  if [ -e \"$FILE\" ]; then\n    echoh \"+ Reusing $FILE\"\n    return\n  fi\n\n  sh_c mkdir -p \"$CACHE_DIR\"\n  sh_c curl \\\n    -#fL \\\n    -o \"$FILE.incomplete\" \\\n    -C - \\\n    \"$URL\"\n  sh_c mv \"$FILE.incomplete\" \"$FILE\"\n}\n\ninstall_brew() {\n  echoh \"Installing latest from Homebrew.\"\n  echoh\n\n  sh_c \"$BREW_PATH\" install code-server\n\n  echo_brew_postinstall\n}\n\ninstall_deb() {\n  echoh \"Installing v$VERSION of the $ARCH deb package from GitHub.\"\n  echoh\n\n  fetch \"https://github.com/coder/code-server/releases/download/v$VERSION/code-server_${VERSION}_$ARCH.deb\" \\\n    \"$CACHE_DIR/code-server_${VERSION}_$ARCH.deb\"\n  sudo_sh_c dpkg -i \"$CACHE_DIR/code-server_${VERSION}_$ARCH.deb\"\n\n  echo_systemd_postinstall deb\n}\n\ninstall_rpm() {\n  echoh \"Installing v$VERSION of the $ARCH rpm package from GitHub.\"\n  echoh\n\n  fetch \"https://github.com/coder/code-server/releases/download/v$VERSION/code-server-$VERSION-$ARCH.rpm\" \\\n    \"$CACHE_DIR/code-server-$VERSION-$ARCH.rpm\"\n  sudo_sh_c rpm -U \"$CACHE_DIR/code-server-$VERSION-$ARCH.rpm\"\n\n  echo_systemd_postinstall rpm\n}\n\ninstall_aur() {\n  echoh \"Installing latest from the AUR.\"\n  echoh\n\n  sh_c mkdir -p \"$CACHE_DIR/code-server-aur\"\n  sh_c \"curl -#fsSL https://aur.archlinux.org/cgit/aur.git/snapshot/code-server.tar.gz | tar -xzC $CACHE_DIR/code-server-aur --strip-components 1\"\n  echo \"+ cd $CACHE_DIR/code-server-aur\"\n  if [ ! \"${DRY_RUN-}\" ]; then\n    cd \"$CACHE_DIR/code-server-aur\"\n  fi\n  sh_c makepkg -si --noconfirm\n\n  echo_systemd_postinstall AUR\n}\n\ninstall_standalone() {\n  echoh \"Installing v$VERSION of the $ARCH release from GitHub.\"\n  echoh\n\n  fetch \"https://github.com/coder/code-server/releases/download/v$VERSION/code-server-$VERSION-$OS-$ARCH.tar.gz\" \\\n    \"$CACHE_DIR/code-server-$VERSION-$OS-$ARCH.tar.gz\"\n\n  # -w only works if the directory exists so try creating it first. If this\n  # fails we can ignore the error as the -w check will then swap us to sudo.\n  sh_c mkdir -p \"$STANDALONE_INSTALL_PREFIX\" 2> /dev/null || true\n\n  sh_c=\"sh_c\"\n  if [ ! -w \"$STANDALONE_INSTALL_PREFIX\" ]; then\n    sh_c=\"sudo_sh_c\"\n  fi\n\n  if [ -e \"$STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION\" ]; then\n    echoh\n    echoh \"code-server-$VERSION is already installed at $STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION\"\n    echoh \"Remove it to reinstall.\"\n    exit 0\n  fi\n\n  \"$sh_c\" mkdir -p \"$STANDALONE_INSTALL_PREFIX/lib\" \"$STANDALONE_INSTALL_PREFIX/bin\"\n  \"$sh_c\" tar -C \"$STANDALONE_INSTALL_PREFIX/lib\" -xzf \"$CACHE_DIR/code-server-$VERSION-$OS-$ARCH.tar.gz\"\n  \"$sh_c\" mv -f \"$STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION-$OS-$ARCH\" \"$STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION\"\n  \"$sh_c\" ln -fs \"$STANDALONE_INSTALL_PREFIX/lib/code-server-$VERSION/bin/code-server\" \"$STANDALONE_INSTALL_PREFIX/bin/code-server\"\n\n  echo_standalone_postinstall\n}\n\ninstall_npm() {\n  echoh \"Installing v$VERSION from npm.\"\n  echoh\n\n  NPM_PATH=\"${YARN_PATH-npm}\"\n\n  if command_exists \"$NPM_PATH\"; then\n    sh_c=\"sh_c\"\n    if [ ! \"${DRY_RUN-}\" ] && [ ! -w \"$(NPM_PATH config get prefix)\" ]; then\n      sh_c=\"sudo_sh_c\"\n    fi\n    echoh \"Installing with npm.\"\n    echoh\n    \"$sh_c\" \"$NPM_PATH\" install -g \"code-server@$VERSION\" --unsafe-perm\n    NPM_BIN_DIR=\"\\$($NPM_PATH bin -g)\" echo_npm_postinstall\n    return\n  fi\n  echoerr \"Please install npm to install code-server!\"\n  echoerr \"You will need at least node v20 and a few C dependencies.\"\n  echoerr \"See the docs https://coder.com/docs/code-server/latest/install#npm\"\n\n  exit 1\n}\n\n# Run $1 if we have a standalone otherwise run install_npm.\nnpm_fallback() {\n  if has_standalone; then\n    $1\n  else\n    echoh \"No standalone releases for $ARCH.\"\n    echoh \"Falling back to installation from npm.\"\n    install_npm\n  fi\n}\n\n# Determine if we have standalone releases on GitHub for the system's arch.\nhas_standalone() {\n  case $ARCH in\n    arm64) return 0 ;;\n    # We only have arm64 for macOS.\n    amd64)\n      [ \"$(distro)\" != macos ]\n      return\n      ;;\n    *) return 1 ;;\n  esac\n}\n\nos() {\n  uname=\"$(uname)\"\n  case $uname in\n    Linux) echo linux ;;\n    Darwin) echo macos ;;\n    FreeBSD) echo freebsd ;;\n    *) echo \"$uname\" ;;\n  esac\n}\n\n# Print the detected Linux distro, otherwise print the OS name.\n#\n# Example outputs:\n# - macos -> macos\n# - freebsd -> freebsd\n# - ubuntu, raspbian, debian ... -> debian\n# - amzn, centos, rhel, fedora, ... -> fedora\n# - opensuse-{leap,tumbleweed} -> opensuse\n# - alpine -> alpine\n# - arch, manjaro, endeavouros, ... -> arch\n#\n# Inspired by https://github.com/docker/docker-install/blob/26ff363bcf3b3f5a00498ac43694bf1c7d9ce16c/install.sh#L111-L120.\ndistro() {\n  if [ \"$OS\" = \"macos\" ] || [ \"$OS\" = \"freebsd\" ]; then\n    echo \"$OS\"\n    return\n  fi\n\n  if [ -f /etc/os-release ]; then\n    (\n      . /etc/os-release\n      if [ \"${ID_LIKE-}\" ]; then\n        for id_like in $ID_LIKE; do\n          case \"$id_like\" in debian | fedora | opensuse | arch)\n            echo \"$id_like\"\n            return\n            ;;\n          esac\n        done\n      fi\n\n      echo \"$ID\"\n    )\n    return\n  fi\n}\n\n# Print a human-readable name for the OS/distro.\ndistro_name() {\n  if [ \"$(uname)\" = \"Darwin\" ]; then\n    echo \"macOS v$(sw_vers -productVersion)\"\n    return\n  fi\n\n  if [ -f /etc/os-release ]; then\n    (\n      . /etc/os-release\n      echo \"$PRETTY_NAME\"\n    )\n    return\n  fi\n\n  # Prints something like: Linux 4.19.0-9-amd64\n  uname -sr\n}\n\narch() {\n  uname_m=$(uname -m)\n  case $uname_m in\n    aarch64) echo arm64 ;;\n    x86_64) echo amd64 ;;\n    *) echo \"$uname_m\" ;;\n  esac\n}\n\ncommand_exists() {\n  if [ ! \"$1\" ]; then return 1; fi\n  command -v \"$@\" > /dev/null\n}\n\nsh_c() {\n  echoh \"+ $*\"\n  if [ ! \"${DRY_RUN-}\" ]; then\n    sh -c \"$*\"\n  fi\n}\n\nsudo_sh_c() {\n  if [ \"$(id -u)\" = 0 ]; then\n    sh_c \"$@\"\n  elif command_exists doas; then\n    sh_c \"doas $*\"\n  elif command_exists sudo; then\n    sh_c \"sudo $*\"\n  elif command_exists su; then\n    sh_c \"su root -c '$*'\"\n  else\n    echoh\n    echoerr \"This script needs to run the following command as root.\"\n    echoerr \"  $*\"\n    echoerr \"Please install doas, sudo, or su.\"\n    exit 1\n  fi\n}\n\necho_cache_dir() {\n  if [ \"${XDG_CACHE_HOME-}\" ]; then\n    echo \"$XDG_CACHE_HOME/code-server\"\n  elif [ \"${HOME-}\" ]; then\n    echo \"$HOME/.cache/code-server\"\n  else\n    echo \"/tmp/code-server-cache\"\n  fi\n}\n\nechoh() {\n  echo \"$@\" | humanpath\n}\n\ncath() {\n  humanpath\n}\n\nechoerr() {\n  echoh \"$@\" >&2\n}\n\n# humanpath replaces all occurrences of \" $HOME\" with \" ~\"\n# and all occurrences of '\"$HOME' with the literal '\"$HOME'.\nhumanpath() {\n  sed \"s# $HOME# ~#g; s#\\\"$HOME#\\\"\\$HOME#g\"\n}\n\n# We need to make sure we exit with a non zero exit if the command fails.\n# /bin/sh does not support -o pipefail unfortunately.\nprefix() {\n  PREFIX=\"$1\"\n  shift\n  fifo=\"$(mktemp -d)/fifo\"\n  mkfifo \"$fifo\"\n  sed -e \"s#^#$PREFIX: #\" \"$fifo\" &\n  \"$@\" > \"$fifo\" 2>&1\n}\n\nmain \"$@\"\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"code-server\",\n  \"license\": \"MIT\",\n  \"version\": \"0.0.0\",\n  \"description\": \"Run VS Code on a remote server.\",\n  \"homepage\": \"https://github.com/coder/code-server\",\n  \"bugs\": {\n    \"url\": \"https://github.com/coder/code-server/issues\"\n  },\n  \"repository\": \"https://github.com/coder/code-server\",\n  \"scripts\": {\n    \"clean\": \"./ci/build/clean.sh\",\n    \"build\": \"./ci/build/build-code-server.sh\",\n    \"build:vscode\": \"./ci/build/build-vscode.sh\",\n    \"doctoc\": \"./ci/dev/doctoc.sh\",\n    \"release\": \"./ci/build/build-release.sh\",\n    \"release:standalone\": \"./ci/build/build-standalone-release.sh\",\n    \"release:prep\": \"./ci/build/release-prep.sh\",\n    \"test:e2e\": \"VSCODE_IPC_HOOK_CLI= ./ci/dev/test-e2e.sh\",\n    \"test:e2e:proxy\": \"USE_PROXY=1 ./ci/dev/test-e2e.sh\",\n    \"test:unit\": \"./ci/dev/test-unit.sh --forceExit --detectOpenHandles\",\n    \"test:integration\": \"./ci/dev/test-integration.sh\",\n    \"test:native\": \"./ci/dev/test-native.sh\",\n    \"test:scripts\": \"./ci/dev/test-scripts.sh\",\n    \"package\": \"./ci/build/build-packages.sh\",\n    \"prettier\": \"prettier --write --log-level=warn --cache .\",\n    \"preinstall\": \"node ./ci/dev/preinstall.js\",\n    \"postinstall\": \"./ci/dev/postinstall.sh\",\n    \"publish:npm\": \"./ci/steps/publish-npm.sh\",\n    \"publish:docker\": \"./ci/steps/docker-buildx-push.sh\",\n    \"fmt\": \"npm run prettier && ./ci/dev/doctoc.sh\",\n    \"lint:scripts\": \"./ci/dev/lint-scripts.sh\",\n    \"lint:ts\": \"eslint --max-warnings=0 --fix $(git ls-files '*.ts' '*.js' | grep -v 'lib/vscode')\",\n    \"test\": \"echo 'Run npm run test:unit or npm run test:e2e' && exit 1\",\n    \"watch\": \"VSCODE_DEV=1 VSCODE_IPC_HOOK_CLI= NODE_OPTIONS='--max_old_space_size=32384 --trace-warnings' ts-node ./ci/dev/watch.ts\",\n    \"icons\": \"./ci/dev/gen_icons.sh\"\n  },\n  \"main\": \"out/node/entry.js\",\n  \"devDependencies\": {\n    \"@eslint/compat\": \"^1.2.0\",\n    \"@eslint/eslintrc\": \"^3.1.0\",\n    \"@eslint/js\": \"^9.12.0\",\n    \"@schemastore/package\": \"^0.0.10\",\n    \"@types/compression\": \"^1.7.3\",\n    \"@types/cookie-parser\": \"^1.4.4\",\n    \"@types/eslint__js\": \"^8.42.3\",\n    \"@types/express\": \"^5.0.0\",\n    \"@types/http-proxy\": \"1.17.7\",\n    \"@types/js-yaml\": \"^4.0.6\",\n    \"@types/node\": \"22.x\",\n    \"@types/pem\": \"^1.14.1\",\n    \"@types/proxy-from-env\": \"^1.0.1\",\n    \"@types/safe-compare\": \"^1.1.0\",\n    \"@types/semver\": \"^7.5.2\",\n    \"@types/trusted-types\": \"^2.0.4\",\n    \"@types/ws\": \"^8.5.5\",\n    \"doctoc\": \"^2.2.1\",\n    \"eslint\": \"^9.12.0\",\n    \"eslint-config-prettier\": \"^10.1.8\",\n    \"eslint-import-resolver-typescript\": \"^4.4.4\",\n    \"eslint-plugin-import\": \"^2.28.1\",\n    \"eslint-plugin-prettier\": \"^5.0.0\",\n    \"globals\": \"^16.1.0\",\n    \"prettier\": \"3.6.2\",\n    \"prettier-plugin-sh\": \"^0.18.0\",\n    \"ts-node\": \"^10.9.1\",\n    \"typescript\": \"^5.6.2\",\n    \"typescript-eslint\": \"^8.8.0\"\n  },\n  \"dependencies\": {\n    \"@coder/logger\": \"^3.0.1\",\n    \"argon2\": \"^0.44.0\",\n    \"compression\": \"^1.7.4\",\n    \"cookie-parser\": \"^1.4.6\",\n    \"env-paths\": \"^2.2.1\",\n    \"express\": \"^5.0.1\",\n    \"http-proxy\": \"^1.18.1\",\n    \"httpolyglot\": \"^0.1.2\",\n    \"i18next\": \"^25.8.3\",\n    \"js-yaml\": \"^4.1.0\",\n    \"limiter\": \"^2.1.0\",\n    \"pem\": \"^1.14.8\",\n    \"proxy-agent\": \"^6.3.1\",\n    \"qs\": \"^6.15.0\",\n    \"rotating-file-stream\": \"^3.1.1\",\n    \"safe-compare\": \"^1.1.4\",\n    \"semver\": \"^7.5.4\",\n    \"ws\": \"^8.14.2\",\n    \"xdg-basedir\": \"^4.0.0\"\n  },\n  \"resolutions\": {\n    \"@types/node\": \"22.x\"\n  },\n  \"bin\": {\n    \"code-server\": \"out/node/entry.js\"\n  },\n  \"keywords\": [\n    \"vscode\",\n    \"development\",\n    \"ide\",\n    \"coder\",\n    \"vscode-remote\",\n    \"browser-ide\",\n    \"remote-development\"\n  ],\n  \"engines\": {\n    \"node\": \"22\"\n  },\n  \"jest\": {\n    \"transform\": {\n      \"^.+\\\\.ts$\": \"<rootDir>/test/node_modules/ts-jest\"\n    },\n    \"testEnvironment\": \"node\",\n    \"testPathIgnorePatterns\": [\n      \"/node_modules/\",\n      \"/lib/\",\n      \"/out/\",\n      \"test/e2e\"\n    ],\n    \"collectCoverage\": true,\n    \"collectCoverageFrom\": [\n      \"<rootDir>/src/**/*.ts\"\n    ],\n    \"coverageDirectory\": \"<rootDir>/coverage\",\n    \"coverageReporters\": [\n      \"json\",\n      \"json-summary\",\n      \"text\",\n      \"clover\"\n    ],\n    \"coveragePathIgnorePatterns\": [\n      \"/out\"\n    ],\n    \"coverageThreshold\": {\n      \"global\": {\n        \"lines\": 60\n      }\n    },\n    \"modulePathIgnorePatterns\": [\n      \"<rootDir>/release-packages\",\n      \"<rootDir>/release\",\n      \"<rootDir>/release-standalone\",\n      \"<rootDir>/release-npm-package\",\n      \"<rootDir>/release-gcp\",\n      \"<rootDir>/release-images\",\n      \"<rootDir>/lib\"\n    ],\n    \"moduleNameMapper\": {\n      \"^.+\\\\.(css|less)$\": \"<rootDir>/test/utils/cssStub.ts\"\n    },\n    \"globalSetup\": \"<rootDir>/test/utils/globalUnitSetup.ts\"\n  }\n}\n"
  },
  {
    "path": "patches/base-path.diff",
    "content": "Add base path support\n\nSome users will host code-server behind a path-rewriting reverse proxy, for\nexample domain.tld/my/base/path.  This patch adds support for that since Code\nassumes everything is on / by default.\n\nTo test this serve code-server behind a reverse proxy with a path like /code.\n\nIndex: code-server/lib/vscode/src/vs/base/common/network.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/network.ts\n+++ code-server/lib/vscode/src/vs/base/common/network.ts\n@@ -245,7 +245,9 @@ class RemoteAuthoritiesImpl {\n \t\treturn URI.from({\n \t\t\tscheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,\n \t\t\tauthority: `${host}:${port}`,\n-\t\t\tpath: this._remoteResourcesPath,\n+\t\t\tpath: platform.isWeb\n+\t\t\t\t? (window.location.pathname + \"/\" + this._remoteResourcesPath).replace(/\\/\\/+/g, \"/\")\n+\t\t\t\t: this._remoteResourcesPath,\n \t\t\tquery\n \t\t});\n \t}\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n@@ -11,8 +11,8 @@\n \t\t<meta name=\"mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-title\" content=\"Code\">\n-\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"/_static/src/browser/media/pwa-icon-192.png\" />\n-\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"/_static/src/browser/media/pwa-icon-512.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"{{BASE}}/_static/src/browser/media/pwa-icon-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"{{BASE}}/_static/src/browser/media/pwa-icon-512.png\" />\n \n \t\t<!-- Disable pinch zooming -->\n \t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\">\n@@ -27,9 +27,9 @@\n \t\t<meta id=\"vscode-workbench-builtin-extensions\" data-settings=\"{{WORKBENCH_BUILTIN_EXTENSIONS}}\">\n \n \t\t<!-- Workbench Icon/Manifest/CSS -->\n-\t\t<link rel=\"icon\" href=\"/_static/src/browser/media/favicon-dark-support.svg\" />\n-\t\t<link rel=\"alternate icon\" href=\"/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n-\t\t<link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n+\t\t<link rel=\"icon\" href=\"{{BASE}}/_static/src/browser/media/favicon-dark-support.svg\" />\n+\t\t<link rel=\"alternate icon\" href=\"{{BASE}}/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n+\t\t<link rel=\"manifest\" href=\"{{VS_BASE}}/manifest.json\" crossorigin=\"use-credentials\" />\n \t\t<style id=\"vscode-css-modules\" type=\"text/css\" media=\"screen\"></style>\n \n \t</head>\n@@ -39,7 +39,7 @@\n \n \t<!-- Startup (do not modify order of script tags!) -->\n \t<script>\n-\t\tconst baseUrl = new URL('{{WORKBENCH_WEB_BASE_URL}}', window.location.origin).toString();\n+\t\tconst baseUrl = new URL('{{WORKBENCH_WEB_BASE_URL}}', window.location).toString();\n \t\tglobalThis._VSCODE_FILE_ROOT = baseUrl + '/out/';\n \t</script>\n \t<script>\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench.html\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench.html\n@@ -11,8 +11,8 @@\n \t\t<meta name=\"mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-title\" content=\"Code\">\n-\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"/_static/src/browser/media/pwa-icon-192.png\" />\n-\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"/_static/src/browser/media/pwa-icon-512.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"{{BASE}}/_static/src/browser/media/pwa-icon-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"{{BASE}}/_static/src/browser/media/pwa-icon-512.png\" />\n \n \t\t<!-- Disable pinch zooming -->\n \t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\">\n@@ -24,9 +24,9 @@\n \t\t<meta id=\"vscode-workbench-auth-session\" data-settings=\"{{WORKBENCH_AUTH_SESSION}}\">\n \n \t\t<!-- Workbench Icon/Manifest/CSS -->\n-\t\t<link rel=\"icon\" href=\"/_static/src/browser/media/favicon-dark-support.svg\" />\n-\t\t<link rel=\"alternate icon\" href=\"/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n-\t\t<link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n+\t\t<link rel=\"icon\" href=\"{{BASE}}/_static/src/browser/media/favicon-dark-support.svg\" />\n+\t\t<link rel=\"alternate icon\" href=\"{{BASE}}/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n+\t\t<link rel=\"manifest\" href=\"{{VS_BASE}}/manifest.json\" crossorigin=\"use-credentials\" />\n \t\t<link rel=\"stylesheet\" href=\"{{WORKBENCH_WEB_BASE_URL}}/out/vs/code/browser/workbench/workbench.css\">\n \n \t</head>\n@@ -36,7 +36,7 @@\n \n \t<!-- Startup (do not modify order of script tags!) -->\n \t<script>\n-\t\tconst baseUrl = new URL('{{WORKBENCH_WEB_BASE_URL}}', window.location.origin).toString();\n+\t\tconst baseUrl = new URL('{{WORKBENCH_WEB_BASE_URL}}', window.location).toString();\n \t\tglobalThis._VSCODE_FILE_ROOT = baseUrl + '/out/';\n \t</script>\n \t<script>\nIndex: code-server/lib/vscode/src/vs/platform/remote/browser/browserSocketFactory.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/remote/browser/browserSocketFactory.ts\n+++ code-server/lib/vscode/src/vs/platform/remote/browser/browserSocketFactory.ts\n@@ -282,6 +282,7 @@ export class BrowserSocketFactory implem\n \tconnect({ host, port }: WebSocketRemoteConnection, path: string, query: string, debugLabel: string): Promise<ISocket> {\n \t\treturn new Promise<ISocket>((resolve, reject) => {\n \t\t\tconst webSocketSchema = (/^https:/.test(mainWindow.location.href) ? 'wss' : 'ws');\n+\t\t\tpath = (mainWindow.location.pathname + \"/\" + path).replace(/\\/\\/+/g, \"/\")\n \t\t\tconst socket = this._webSocketFactory.create(`${webSocketSchema}://${(/:/.test(host) && !/\\[/.test(host)) ? `[${host}]` : host}:${port}${path}?${query}&skipWebSocketFrames=false`, debugLabel);\n \t\t\tconst disposables = new DisposableStore();\n \t\t\tdisposables.add(socket.onError(reject));\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -246,7 +246,9 @@ export class WebClientServer {\n \t\t};\n \n \t\t// Prefix routes with basePath for clients\n-\t\tconst basePath = getFirstHeader('x-forwarded-prefix') || this._basePath;\n+\t\tconst rootBase = relativeRoot(getOriginalUrl(req))\n+\t\tconst vscodeBase = relativePath(getOriginalUrl(req))\n+\t\tconst basePath = vscodeBase || getFirstHeader('x-forwarded-prefix') || this._basePath;\n \n \t\tconst queryConnectionToken = parsedUrl.query[connectionTokenQueryName];\n \t\tif (typeof queryConnectionToken === 'string') {\n@@ -285,10 +287,14 @@ export class WebClientServer {\n \t\t};\n \n \t\tconst useTestResolver = (!this._environmentService.isBuilt && this._environmentService.args['use-test-resolver']);\n+\t\t// For now we are getting the remote authority from the client to avoid\n+\t\t// needing specific configuration for reverse proxies to work.  Set this to\n+\t\t// something invalid to make sure we catch code that is using this value\n+\t\t// from the backend when it should not.\n \t\tlet remoteAuthority = (\n \t\t\tuseTestResolver\n \t\t\t\t? 'test+test'\n-\t\t\t\t: (getFirstHeader('x-original-host') || getFirstHeader('x-forwarded-host') || req.headers.host)\n+\t\t\t\t: 'remote'\n \t\t);\n \t\tif (!remoteAuthority) {\n \t\t\treturn serveError(req, res, 400, `Bad request.`);\n@@ -335,6 +341,7 @@ export class WebClientServer {\n \n \t\tconst productConfiguration: Partial<Mutable<IProductConfiguration>> = {\n \t\t\tcodeServerVersion: this._productService.codeServerVersion,\n+\t\t\trootEndpoint: rootBase,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._webExtensionResourceUrlTemplate && this._productService.extensionsGallery ? {\n \t\t\t\t...this._productService.extensionsGallery,\n@@ -388,7 +395,9 @@ export class WebClientServer {\n \t\t\tWORKBENCH_AUTH_SESSION: authSessionInfo ? asJSON(authSessionInfo) : '',\n \t\t\tWORKBENCH_WEB_BASE_URL: staticRoute,\n \t\t\tWORKBENCH_NLS_URL,\n-\t\t\tWORKBENCH_NLS_FALLBACK_URL: `${staticRoute}/out/nls.messages.js`\n+\t\t\tWORKBENCH_NLS_FALLBACK_URL: `${staticRoute}/out/nls.messages.js`,\n+\t\t\tBASE: rootBase,\n+\t\t\tVS_BASE: basePath,\n \t\t};\n \n \t\t// DEV ---------------------------------------------------------------------------------------\n@@ -425,7 +434,7 @@ export class WebClientServer {\n \t\t\t'default-src \\'self\\';',\n \t\t\t'img-src \\'self\\' https: data: blob:;',\n \t\t\t'media-src \\'self\\';',\n-\t\t\t`script-src 'self' 'unsafe-eval' ${WORKBENCH_NLS_BASE_URL ?? ''} blob: 'nonce-1nline-m4p' ${this._getScriptCspHashes(data).join(' ')} '${webWorkerExtensionHostIframeScriptSHA}' 'sha256-/r7rqQ+yrxt57sxLuQ6AMYcy/lUpvAIzHjIJt/OeLWU=' ${useTestResolver ? '' : `http://${remoteAuthority}`};`,  // the sha is the same as in src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html\n+\t\t\t`script-src 'self' 'unsafe-eval' ${WORKBENCH_NLS_BASE_URL ?? ''} blob: 'nonce-1nline-m4p' ${this._getScriptCspHashes(data).join(' ')} '${webWorkerExtensionHostIframeScriptSHA}' 'sha256-/r7rqQ+yrxt57sxLuQ6AMYcy/lUpvAIzHjIJt/OeLWU=' ${useTestResolver ? '' : ``};`,  // the sha is the same as in src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html\n \t\t\t'child-src \\'self\\';',\n \t\t\t`frame-src 'self' https://*.vscode-cdn.net data:;`,\n \t\t\t'worker-src \\'self\\' data: blob:;',\n@@ -498,3 +507,70 @@ export class WebClientServer {\n \t\treturn void res.end(data);\n \t}\n }\n+\n+/**\n+ * Remove extra slashes in a URL.\n+ *\n+ * This is meant to fill the job of `path.join` so you can concatenate paths and\n+ * then normalize out any extra slashes.\n+ *\n+ * If you are using `path.join` you do not need this but note that `path` is for\n+ * file system paths, not URLs.\n+ */\n+export const normalizeUrlPath = (url: string, keepTrailing = false): string => {\n+\treturn url.replace(/\\/\\/+/g, \"/\").replace(/\\/+$/, keepTrailing ? \"/\" : \"\")\n+}\n+\n+/**\n+ * Get the relative path that will get us to the root of the page. For each\n+ * slash we need to go up a directory.  Will not have a trailing slash.\n+ *\n+ * For example:\n+ *\n+ * / => .\n+ * /foo => .\n+ * /foo/ => ./..\n+ * /foo/bar => ./..\n+ * /foo/bar/ => ./../..\n+ *\n+ * All paths must be relative in order to work behind a reverse proxy since we\n+ * we do not know the base path.  Anything that needs to be absolute (for\n+ * example cookies) must get the base path from the frontend.\n+ *\n+ * All relative paths must be prefixed with the relative root to ensure they\n+ * work no matter the depth at which they happen to appear.\n+ *\n+ * For Express `req.originalUrl` should be used as they remove the base from the\n+ * standard `url` property making it impossible to get the true depth.\n+ */\n+export const relativeRoot = (originalUrl: string): string => {\n+\tconst depth = (originalUrl.split(\"?\", 1)[0].match(/\\//g) || []).length\n+\treturn normalizeUrlPath(\"./\" + (depth > 1 ? \"../\".repeat(depth - 1) : \"\"))\n+}\n+\n+/**\n+ * Get the relative path to the current resource.\n+ *\n+ * For example:\n+ *\n+ * / => .\n+ * /foo => ./foo\n+ * /foo/ => .\n+ * /foo/bar => ./bar\n+ * /foo/bar/ => .\n+ */\n+export const relativePath = (originalUrl: string): string => {\n+\tconst parts = originalUrl.split(\"?\", 1)[0].split(\"/\")\n+\treturn normalizeUrlPath(\"./\" + parts[parts.length - 1])\n+}\n+\n+/**\n+ * code-server serves Code using Express.  Express removes the base from the url\n+ * and puts the original in `originalUrl` so we must use this to get the correct\n+ * depth.  Code is not aware it is behind Express so the types do not match.  We\n+ * may want to continue moving code into Code and eventually remove the Express\n+ * wrapper or move the web server back into code-server.\n+ */\n+export const getOriginalUrl = (req: http.IncomingMessage): string => {\n+\treturn (req as any).originalUrl || req.url\n+}\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -66,6 +66,7 @@ export type ExtensionVirtualWorkspaceSup\n \n export interface IProductConfiguration {\n \treadonly codeServerVersion?: string\n+\treadonly rootEndpoint?: string\n \n \treadonly version: string;\n \treadonly date?: string;\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n@@ -339,7 +339,8 @@ class LocalStorageURLCallbackProvider ex\n \t\t\tthis.startListening();\n \t\t}\n \n-\t\treturn URI.parse(mainWindow.location.href).with({ path: this._callbackRoute, query: queryParams.join('&') });\n+\t\tconst path = (mainWindow.location.pathname + \"/\" + this._callbackRoute).replace(/\\/\\/+/g, \"/\");\n+\t\treturn URI.parse(mainWindow.location.href).with({ path: path, query: queryParams.join('&') });\n \t}\n \n \tprivate startListening(): void {\n@@ -584,17 +585,6 @@ class WorkspaceProvider implements IWork\n \t}\n }\n \n-function readCookie(name: string): string | undefined {\n-\tconst cookies = document.cookie.split('; ');\n-\tfor (const cookie of cookies) {\n-\t\tif (cookie.startsWith(name + '=')) {\n-\t\t\treturn cookie.substring(name.length + 1);\n-\t\t}\n-\t}\n-\n-\treturn undefined;\n-}\n-\n (function () {\n \n \t// Find config by checking for DOM\n@@ -604,8 +594,8 @@ function readCookie(name: string): strin\n \tif (!configElement || !configElementAttribute) {\n \t\tthrow new Error('Missing web configuration element');\n \t}\n-\tconst config: IWorkbenchConstructionOptions & { folderUri?: UriComponents; workspaceUri?: UriComponents; callbackRoute: string } = JSON.parse(configElementAttribute);\n-\tconst secretStorageKeyPath = readCookie('vscode-secret-key-path');\n+\tconst config: IWorkbenchConstructionOptions & { folderUri?: UriComponents; workspaceUri?: UriComponents; callbackRoute: string } = { ...JSON.parse(configElementAttribute), remoteAuthority: location.host }\n+\tconst secretStorageKeyPath = (window.location.pathname + \"/mint-key\").replace(/\\/\\/+/g, \"/\");\n \tconst secretStorageCrypto = secretStorageKeyPath && ServerKeyedAESCrypto.supported()\n \t\t? new ServerKeyedAESCrypto(secretStorageKeyPath) : new TransparentCrypto();\n \nIndex: code-server/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n+++ code-server/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n@@ -120,7 +120,7 @@ export abstract class AbstractExtensionR\n \t\t\t\t\t: version,\n \t\t\t\tpath: 'extension'\n \t\t\t}));\n-\t\t\treturn this._isWebExtensionResourceEndPoint(uri) ? uri.with({ scheme: RemoteAuthorities.getPreferredWebSchema() }) : uri;\n+\t\t\treturn this._isWebExtensionResourceEndPoint(uri) ? URI.joinPath(URI.parse(window.location.href), uri.path) : uri;\n \t\t}\n \t\treturn undefined;\n \t}\n"
  },
  {
    "path": "patches/cli-window-open.diff",
    "content": "Make opening files/folders from the terminal only open in the current instance\n\nPreviously they would open in every code-server tab/window.\n\nTo test:\n\n1. Run code-server\n2. Open code-server\n3. Open terminal\n4. Open another code-server window\n5. Run node ./out/node/entry.js with a file or directory argument\n\nThe file or directory should only open from the instance attached to that\nterminal.\n\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n@@ -108,10 +108,14 @@ class RemoteTerminalBackend extends Base\n \t\t\t}\n \t\t\tconst reqId = e.reqId;\n \t\t\tconst commandId = e.commandId;\n+\t\t\tconst terminalId = e.persistentProcessId;\n \t\t\tif (!allowedCommands.includes(commandId)) {\n \t\t\t\tthis._remoteTerminalChannel.sendCommandResult(reqId, true, 'Invalid remote cli command: ' + commandId);\n \t\t\t\treturn;\n \t\t\t}\n+\t\t\tif (typeof terminalId !== \"undefined\" && !this._ptys.has(terminalId)) {\n+\t\t\t\treturn\n+\t\t\t}\n \t\t\tconst commandArgs = e.commandArgs.map(arg => revive(arg));\n \t\t\ttry {\n \t\t\t\tconst result = await this._commandService.executeCommand(e.commandId, ...commandArgs);\n"
  },
  {
    "path": "patches/clipboard.diff",
    "content": "Index: code-server/lib/vscode/src/vs/workbench/api/browser/mainThreadCLICommands.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/api/browser/mainThreadCLICommands.ts\n+++ code-server/lib/vscode/src/vs/workbench/api/browser/mainThreadCLICommands.ts\n@@ -8,6 +8,7 @@ import { isWeb } from '../../../base/com\n import { isString } from '../../../base/common/types.js';\n import { URI, UriComponents } from '../../../base/common/uri.js';\n import { localize } from '../../../nls.js';\n+import { IClipboardService } from '../../../platform/clipboard/common/clipboardService.js';\n import { CommandsRegistry, ICommandService } from '../../../platform/commands/common/commands.js';\n import { IExtensionGalleryService, IExtensionManagementService } from '../../../platform/extensionManagement/common/extensionManagement.js';\n import { ExtensionManagementCLI } from '../../../platform/extensionManagement/common/extensionManagementCLI.js';\n@@ -96,6 +97,11 @@ CommandsRegistry.registerCommand('_remot\n \n });\n \n+CommandsRegistry.registerCommand('_remoteCLI.setClipboard', function (accessor: ServicesAccessor, content: string) {\n+\tconst clipboardService = accessor.get(IClipboardService);\n+\tclipboardService.writeText(content);\n+})\n+\n class RemoteExtensionManagementCLI extends ExtensionManagementCLI {\n \n \tprivate _location: string | undefined;\nIndex: code-server/lib/vscode/src/vs/workbench/api/node/extHostCLIServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/api/node/extHostCLIServer.ts\n+++ code-server/lib/vscode/src/vs/workbench/api/node/extHostCLIServer.ts\n@@ -44,7 +44,12 @@ export interface ExtensionManagementPipe\n \tforce?: boolean;\n }\n \n-export type PipeCommand = OpenCommandPipeArgs | StatusPipeArgs | OpenExternalCommandPipeArgs | ExtensionManagementPipeArgs;\n+export interface ClipboardPipeArgs {\n+\ttype: 'clipboard';\n+\tcontent: string;\n+}\n+\n+export type PipeCommand = OpenCommandPipeArgs | StatusPipeArgs | OpenExternalCommandPipeArgs | ExtensionManagementPipeArgs | ClipboardPipeArgs;\n \n export interface ICommandsExecuter {\n \texecuteCommand<T>(id: string, ...args: unknown[]): Promise<T>;\n@@ -110,6 +115,9 @@ export class CLIServerBase {\n \t\t\t\t\tcase 'extensionManagement':\n \t\t\t\t\t\treturnObj = await this.manageExtensions(data);\n \t\t\t\t\t\tbreak;\n+\t\t\t\t\tcase 'clipboard':\n+\t\t\t\t\t\treturnObj = await this.clipboard(data);\n+\t\t\t\t\t\tbreak;\n \t\t\t\t\tdefault:\n \t\t\t\t\t\tsendResponse(404, `Unknown message type: ${data.type}`);\n \t\t\t\t\t\tbreak;\n@@ -180,6 +188,10 @@ export class CLIServerBase {\n \t\treturn await this._commands.executeCommand<string | undefined>('_remoteCLI.getSystemStatus');\n \t}\n \n+\tprivate async clipboard(data: ClipboardPipeArgs): Promise<undefined> {\n+\t\treturn await this._commands.executeCommand('_remoteCLI.setClipboard', data.content);\n+\t}\n+\n \tdispose(): void {\n \t\tthis._disposed = true;\n \t\tthis._server?.close();\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/terminal/browser/remoteTerminalBackend.ts\n@@ -99,7 +99,7 @@ class RemoteTerminalBackend extends Base\n \t\t\t}\n \t\t}));\n \n-\t\tconst allowedCommands = ['_remoteCLI.openExternal', '_remoteCLI.windowOpen', '_remoteCLI.getSystemStatus', '_remoteCLI.manageExtensions'];\n+\t\tconst allowedCommands = ['_remoteCLI.openExternal', '_remoteCLI.windowOpen', '_remoteCLI.getSystemStatus', '_remoteCLI.manageExtensions', '_remoteCLI.setClipboard'];\n \t\tthis._register(this._remoteTerminalChannel.onExecuteCommand(async e => {\n \t\t\t// Ensure this request for for this window\n \t\t\tconst pty = this._ptys.get(e.persistentProcessId);\nIndex: code-server/lib/vscode/src/vs/platform/environment/common/argv.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/environment/common/argv.ts\n+++ code-server/lib/vscode/src/vs/platform/environment/common/argv.ts\n@@ -139,6 +139,7 @@ export interface NativeParsedArgs {\n \t'disable-chromium-sandbox'?: boolean;\n \tsandbox?: boolean;\n \t'enable-coi'?: boolean;\n+\t'stdin-to-clipboard'?: boolean;\n \t'unresponsive-sample-interval'?: string;\n \t'unresponsive-sample-period'?: string;\n \t'enable-rdp-display-tracking'?: boolean;\nIndex: code-server/lib/vscode/src/vs/platform/environment/node/argv.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/environment/node/argv.ts\n+++ code-server/lib/vscode/src/vs/platform/environment/node/argv.ts\n@@ -106,6 +106,7 @@ export const OPTIONS: OptionDescriptions\n \t'user-data-dir': { type: 'string', cat: 'o', args: 'dir', description: localize('userDataDir', \"Specifies the directory that user data is kept in. Can be used to open multiple distinct instances of Code.\") },\n \t'profile': { type: 'string', 'cat': 'o', args: 'profileName', description: localize('profileName', \"Opens the provided folder or workspace with the given profile and associates the profile with the workspace. If the profile does not exist, a new empty one is created.\") },\n \t'help': { type: 'boolean', cat: 'o', alias: 'h', description: localize('help', \"Print usage.\") },\n+\t'stdin-to-clipboard': { type: 'boolean', cat: 'o', alias: 'c', description: localize('clipboard', \"copies the STDIN to the clipboard\") },\n \n \t'extensions-dir': { type: 'string', deprecates: ['extensionHomePath'], cat: 'e', args: 'dir', description: localize('extensionHomePath', \"Set the root path for extensions.\") },\n \t'extensions-download-dir': { type: 'string' },\nIndex: code-server/lib/vscode/src/vs/server/node/server.cli.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/server.cli.ts\n+++ code-server/lib/vscode/src/vs/server/node/server.cli.ts\n@@ -77,6 +77,7 @@ const isSupportedForPipe = (optionId: ke\n \t\tcase 'verbose':\n \t\tcase 'remote':\n \t\tcase 'locate-shell-integration-path':\n+\t\tcase 'stdin-to-clipboard':\n \t\t\treturn true;\n \t\tdefault:\n \t\t\treturn false;\n@@ -300,6 +301,22 @@ export async function main(desc: Product\n \t\t\t}\n \t\t}\n \t} else {\n+\t\tif (parsedArgs['stdin-to-clipboard']) {\n+\t\t\tif(!hasStdinWithoutTty()) {\n+\t\t\t\tconsole.error(\"stdin has a tty.\");\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tconst stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0\n+\t\t\tconst clipboardContent = stdinBuffer.toString();\n+\t\t\tsendToPipe({\n+\t\t\t\ttype: 'clipboard',\n+\t\t\t\tcontent: clipboardContent\n+\t\t\t}, verbose).catch(e => {\n+\t\t\t\tconsole.error('Error when requesting status:', e);\n+\t\t\t});\n+\t\t\treturn;\n+\t\t}\n+\n \t\tif (parsedArgs.status) {\n \t\t\tawait sendToPipe({\n \t\t\t\ttype: 'status'\n"
  },
  {
    "path": "patches/disable-builtin-ext-update.diff",
    "content": "Prevent builtin extensions from being updated\n\nUpdating builtin extensions from the marketplace prevents us from patching them\n(for example out GitHub authentication patches).\n\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsWorkbenchService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsWorkbenchService.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsWorkbenchService.ts\n@@ -342,6 +342,10 @@ export class Extension implements IExten\n \t\t\tif (this.type === ExtensionType.System && this.productService.quality === 'stable') {\n \t\t\t\treturn false;\n \t\t\t}\n+\t\t\t// Do not update builtin extensions.\n+\t\t\tif (this.type !== ExtensionType.User) {\n+\t\t\t\treturn false;\n+\t\t\t}\n \t\t\tif (!this.local.preRelease && this.gallery.properties.isPreReleaseVersion) {\n \t\t\t\treturn false;\n \t\t\t}\n"
  },
  {
    "path": "patches/display-language.diff",
    "content": "Add display language support\n\nVS Code web appears to implement language support by setting a cookie and\ndownloading language packs from a URL configured in the product.json. This patch\nsupports language pack extensions and uses files on the remote to set the\nlanguage instead, so it works like the desktop version.\n\nIndex: code-server/lib/vscode/src/vs/server/node/serverServices.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverServices.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverServices.ts\n@@ -12,7 +12,7 @@ import * as path from '../../base/common\n import { IURITransformer } from '../../base/common/uriIpc.js';\n import { getMachineId, getSqmMachineId, getDevDeviceId } from '../../base/node/id.js';\n import { Promises } from '../../base/node/pfs.js';\n-import { ClientConnectionEvent, IMessagePassingProtocol, IPCServer, StaticRouter } from '../../base/parts/ipc/common/ipc.js';\n+import { ClientConnectionEvent, IMessagePassingProtocol, IPCServer, ProxyChannel, StaticRouter } from '../../base/parts/ipc/common/ipc.js';\n import { ProtocolConstants } from '../../base/parts/ipc/common/ipc.net.js';\n import { IConfigurationService } from '../../platform/configuration/common/configuration.js';\n import { ConfigurationService } from '../../platform/configuration/common/configurationService.js';\n@@ -277,6 +277,9 @@ export async function setupServerService\n \n \t\tsocketServer.registerChannel('mcpManagement', new McpManagementChannel(mcpManagementService, (ctx: RemoteAgentConnectionContext) => getUriTransformer(ctx.remoteAuthority)));\n \n+\t\tconst languagePackChannel = ProxyChannel.fromService<RemoteAgentConnectionContext>(accessor.get(ILanguagePackService), disposables);\n+\t\tsocketServer.registerChannel('languagePacks', languagePackChannel);\n+\n \t\t// clean up extensions folder\n \t\tremoteExtensionsScanner.whenExtensionsReady().then(() => extensionManagementService.cleanUp());\n \nIndex: code-server/lib/vscode/src/vs/platform/environment/common/environmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/environment/common/environmentService.ts\n+++ code-server/lib/vscode/src/vs/platform/environment/common/environmentService.ts\n@@ -98,7 +98,7 @@ export abstract class AbstractNativeEnvi\n \t\t\treturn URI.file(join(vscodePortable, 'argv.json'));\n \t\t}\n \n-\t\treturn joinPath(this.userHome, this.productService.dataFolderName, 'argv.json');\n+\t\treturn joinPath(this.appSettingsHome, 'argv.json');\n \t}\n \n \t@memoize\nIndex: code-server/lib/vscode/src/vs/server/node/remoteLanguagePacks.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/remoteLanguagePacks.ts\n+++ code-server/lib/vscode/src/vs/server/node/remoteLanguagePacks.ts\n@@ -3,6 +3,8 @@\n  *  Licensed under the MIT License. See License.txt in the project root for license information.\n  *--------------------------------------------------------------------------------------------*/\n \n+import { promises as fs } from 'fs';\n+import * as path from 'path';\n import { FileAccess } from '../../base/common/network.js';\n import { join } from '../../base/common/path.js';\n import type { INLSConfiguration } from '../../nls.js';\n@@ -33,7 +35,94 @@ export async function getNLSConfiguratio\n \tif (!result) {\n \t\tresult = resolveNLSConfiguration({ userLocale: language, osLocale: language, commit: product.commit, userDataPath, nlsMetadataPath });\n \t\tnlsConfigurationCache.set(cacheKey, result);\n+\t\t// If the language pack does not yet exist, it defaults to English, which is\n+\t\t// then cached and you have to restart even if you then install the pack.\n+\t\tresult.then((r) => {\n+\t\t\tif (!language.startsWith('en') && r.resolvedLanguage.startsWith('en')) {\n+\t\t\t\tnlsConfigurationCache.delete(cacheKey);\n+\t\t\t}\n+\t\t})\n \t}\n \n \treturn result;\n }\n+\n+/**\n+ * Copied from from src/main.js.\n+ */\n+export const getLocaleFromConfig = async (argvResource: string): Promise<string> => {\n+\ttry {\n+\t\tconst content = stripComments(await fs.readFile(argvResource, 'utf8'));\n+\t\treturn JSON.parse(content).locale;\n+\t} catch (error) {\n+\t\tif (error.code !== \"ENOENT\") {\n+\t\t\tconsole.warn(error)\n+\t\t}\n+\t\treturn 'en';\n+\t}\n+};\n+\n+/**\n+ * Copied from from src/main.js.\n+ */\n+const stripComments = (content: string): string => {\n+\tconst regexp = /('(?:[^\\\\']*(?:\\\\.)?)*')|('(?:[^\\\\']*(?:\\\\.)?)*')|(\\/\\*(?:\\r?\\n|.)*?\\*\\/)|(\\/{2,}.*?(?:(?:\\r?\\n)|$))/g;\n+\n+\treturn content.replace(regexp, (match, _m1, _m2, m3, m4) => {\n+\t\t// Only one of m1, m2, m3, m4 matches\n+\t\tif (m3) {\n+\t\t\t// A block comment. Replace with nothing\n+\t\t\treturn '';\n+\t\t} else if (m4) {\n+\t\t\t// A line comment. If it ends in \\r?\\n then keep it.\n+\t\t\tconst length_1 = m4.length;\n+\t\t\tif (length_1 > 2 && m4[length_1 - 1] === '\\n') {\n+\t\t\t\treturn m4[length_1 - 2] === '\\r' ? '\\r\\n' : '\\n';\n+\t\t\t}\n+\t\t\telse {\n+\t\t\t\treturn '';\n+\t\t\t}\n+\t\t} else {\n+\t\t\t// We match a string\n+\t\t\treturn match;\n+\t\t}\n+\t});\n+};\n+\n+/**\n+ * Generate translations then return a path to a JavaScript file that sets the\n+ * translations into global variables.  This file is loaded by the browser to\n+ * set global variables that the loader uses when looking for translations.\n+ *\n+ * Normally, VS Code pulls these files from a CDN but we want them to be local.\n+ */\n+export async function getBrowserNLSConfiguration(locale: string, userDataPath: string): Promise<string> {\n+\tif (locale.startsWith('en')) {\n+\t\treturn ''; // Use fallback translations.\n+\t}\n+\n+\tconst nlsConfig = await getNLSConfiguration(locale, userDataPath);\n+\tconst messagesFile = nlsConfig?.languagePack?.messagesFile;\n+\tconst resolvedLanguage = nlsConfig?.resolvedLanguage;\n+\tif (!messagesFile || !resolvedLanguage) {\n+\t\treturn ''; // Use fallback translations.\n+\t}\n+\n+\tconst nlsFile = path.join(path.dirname(messagesFile), \"nls.messages.js\");\n+\ttry {\n+\t\tawait fs.stat(nlsFile);\n+\t\treturn nlsFile; // We already generated the file.\n+\t} catch (error) {\n+\t\t// ENOENT is fine, that just means we need to generate the file.\n+\t\tif (error.code !== 'ENOENT') {\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+\n+\tconst messages = (await fs.readFile(messagesFile)).toString();\n+\tconst content = `globalThis._VSCODE_NLS_MESSAGES=${messages};\n+globalThis._VSCODE_NLS_LANGUAGE=${JSON.stringify(resolvedLanguage)};`\n+\tawait fs.writeFile(nlsFile, content, \"utf-8\");\n+\n+\treturn nlsFile;\n+}\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -25,6 +25,7 @@ import { URI } from '../../base/common/u\n import { streamToBuffer } from '../../base/common/buffer.js';\n import { IProductConfiguration } from '../../base/common/product.js';\n import { isString, Mutable } from '../../base/common/types.js';\n+import { getLocaleFromConfig, getBrowserNLSConfiguration } from './remoteLanguagePacks.js';\n import { CharCode } from '../../base/common/charCode.js';\n import { IExtensionManifest } from '../../platform/extensions/common/extensions.js';\n import { ICSSDevelopmentService } from '../../platform/cssDev/node/cssDevService.js';\n@@ -386,14 +387,22 @@ export class WebClientServer {\n \t\t};\n \n \t\tconst cookies = cookie.parse(req.headers.cookie || '');\n-\t\tconst locale = cookies['vscode.nls.locale'] || req.headers['accept-language']?.split(',')[0]?.toLowerCase() || 'en';\n+\t\tconst locale = this._environmentService.args.locale || await getLocaleFromConfig(this._environmentService.argvResource.fsPath) || cookies['vscode.nls.locale'] || req.headers['accept-language']?.split(',')[0]?.toLowerCase() || 'en';\n \t\tlet WORKBENCH_NLS_BASE_URL: string | undefined;\n \t\tlet WORKBENCH_NLS_URL: string;\n \t\tif (!locale.startsWith('en') && this._productService.nlsCoreBaseUrl) {\n \t\t\tWORKBENCH_NLS_BASE_URL = this._productService.nlsCoreBaseUrl;\n \t\t\tWORKBENCH_NLS_URL = `${WORKBENCH_NLS_BASE_URL}${this._productService.commit}/${this._productService.version}/${locale}/nls.messages.js`;\n \t\t} else {\n-\t\t\tWORKBENCH_NLS_URL = ''; // fallback will apply\n+\t\t\ttry {\n+\t\t\t\tconst nlsFile = await getBrowserNLSConfiguration(locale, this._environmentService.userDataPath);\n+\t\t\t\tWORKBENCH_NLS_URL = nlsFile\n+\t\t\t\t\t? `${vscodeBase}/vscode-remote-resource?path=${encodeURIComponent(nlsFile)}`\n+\t\t\t\t\t: '';\n+\t\t\t} catch (error) {\n+\t\t\t\tconsole.error(\"Failed to generate translations\", error);\n+\t\t\t\tWORKBENCH_NLS_URL = '';\n+\t\t\t}\n \t\t}\n \n \t\tconst values: { [key: string]: string } = {\nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -22,6 +22,7 @@ export const serverOptions: OptionDescri\n \t'disable-file-downloads': { type: 'boolean' },\n \t'disable-file-uploads': { type: 'boolean' },\n \t'disable-getting-started-override': { type: 'boolean' },\n+\t'locale': { type: 'string' },\n \n \t/* ----- server setup ----- */\n \n@@ -113,6 +114,7 @@ export interface ServerParsedArgs {\n \t'disable-file-downloads'?: boolean;\n \t'disable-file-uploads'?: boolean;\n \t'disable-getting-started-override'?: boolean,\n+\t'locale'?: string\n \n \t/* ----- server setup ----- */\n \nIndex: code-server/lib/vscode/src/vs/platform/languagePacks/browser/languagePacks.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/languagePacks/browser/languagePacks.ts\n+++ code-server/lib/vscode/src/vs/platform/languagePacks/browser/languagePacks.ts\n@@ -5,18 +5,24 @@\n \n import { CancellationTokenSource } from '../../../base/common/cancellation.js';\n import { URI } from '../../../base/common/uri.js';\n+import { ProxyChannel } from '../../../base/parts/ipc/common/ipc.js';\n import { IExtensionGalleryService } from '../../extensionManagement/common/extensionManagement.js';\n import { IExtensionResourceLoaderService } from '../../extensionResourceLoader/common/extensionResourceLoader.js';\n-import { ILanguagePackItem, LanguagePackBaseService } from '../common/languagePacks.js';\n+import { ILanguagePackItem, ILanguagePackService, LanguagePackBaseService } from '../common/languagePacks.js';\n import { ILogService } from '../../log/common/log.js';\n+import { IRemoteAgentService } from '../../../workbench/services/remote/common/remoteAgentService.js';\n \n export class WebLanguagePacksService extends LanguagePackBaseService {\n+\tprivate readonly languagePackService: ILanguagePackService;\n+\n \tconstructor(\n+\t\t@IRemoteAgentService remoteAgentService: IRemoteAgentService,\n \t\t@IExtensionResourceLoaderService private readonly extensionResourceLoaderService: IExtensionResourceLoaderService,\n \t\t@IExtensionGalleryService extensionGalleryService: IExtensionGalleryService,\n \t\t@ILogService private readonly logService: ILogService\n \t) {\n \t\tsuper(extensionGalleryService);\n+\t\tthis.languagePackService = ProxyChannel.toService<ILanguagePackService>(remoteAgentService.getConnection()!.getChannel('languagePacks'))\n \t}\n \n \tasync getBuiltInExtensionTranslationsUri(id: string, language: string): Promise<URI | undefined> {\n@@ -72,6 +78,6 @@ export class WebLanguagePacksService ext\n \n \t// Web doesn't have a concept of language packs, so we just return an empty array\n \tgetInstalledLanguages(): Promise<ILanguagePackItem[]> {\n-\t\treturn Promise.resolve([]);\n+\t\treturn this.languagePackService.getInstalledLanguages()\n \t}\n }\nIndex: code-server/lib/vscode/src/vs/workbench/services/localization/electron-browser/localeService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/localization/electron-browser/localeService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/localization/electron-browser/localeService.ts\n@@ -51,7 +51,8 @@ class NativeLocaleService implements ILo\n \t\t@IProductService private readonly productService: IProductService\n \t) { }\n \n-\tprivate async validateLocaleFile(): Promise<boolean> {\n+\t// Make public just so we do not have to patch all the unused code out.\n+\tpublic async validateLocaleFile(): Promise<boolean> {\n \t\ttry {\n \t\t\tconst content = await this.textFileService.read(this.environmentService.argvResource, { encoding: 'utf8' });\n \n@@ -78,9 +79,6 @@ class NativeLocaleService implements ILo\n \t}\n \n \tprivate async writeLocaleValue(locale: string | undefined): Promise<boolean> {\n-\t\tif (!(await this.validateLocaleFile())) {\n-\t\t\treturn false;\n-\t\t}\n \t\tawait this.jsonEditingService.write(this.environmentService.argvResource, [{ path: ['locale'], value: locale }], true);\n \t\treturn true;\n \t}\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/extensions/browser/extensionsActions.ts\n@@ -474,9 +474,6 @@ export class InstallAction extends Exten\n \t\tif (this.extension.isBuiltin) {\n \t\t\treturn;\n \t\t}\n-\t\tif (this.extensionsWorkbenchService.canSetLanguage(this.extension)) {\n-\t\t\treturn;\n-\t\t}\n \t\tif (this.extension.state !== ExtensionState.Uninstalled) {\n \t\t\treturn;\n \t\t}\n@@ -781,7 +778,7 @@ export abstract class InstallInOtherServ\n \t\t}\n \n \t\tif (isLanguagePackExtension(this.extension.local.manifest)) {\n-\t\t\treturn true;\n+\t\t\treturn false;\n \t\t}\n \n \t\t// Prefers to run on UI\n@@ -2072,17 +2069,6 @@ export class SetLanguageAction extends E\n \tupdate(): void {\n \t\tthis.enabled = false;\n \t\tthis.class = SetLanguageAction.DisabledClass;\n-\t\tif (!this.extension) {\n-\t\t\treturn;\n-\t\t}\n-\t\tif (!this.extensionsWorkbenchService.canSetLanguage(this.extension)) {\n-\t\t\treturn;\n-\t\t}\n-\t\tif (this.extension.gallery && language === getLocale(this.extension.gallery)) {\n-\t\t\treturn;\n-\t\t}\n-\t\tthis.enabled = true;\n-\t\tthis.class = SetLanguageAction.EnabledClass;\n \t}\n \n \toverride async run(): Promise<any> {\n@@ -2099,7 +2085,6 @@ export class ClearLanguageAction extends\n \tprivate static readonly DisabledClass = `${this.EnabledClass} disabled`;\n \n \tconstructor(\n-\t\t@IExtensionsWorkbenchService private readonly extensionsWorkbenchService: IExtensionsWorkbenchService,\n \t\t@ILocaleService private readonly localeService: ILocaleService,\n \t) {\n \t\tsuper(ClearLanguageAction.ID, ClearLanguageAction.TITLE.value, ClearLanguageAction.DisabledClass, false);\n@@ -2109,17 +2094,6 @@ export class ClearLanguageAction extends\n \tupdate(): void {\n \t\tthis.enabled = false;\n \t\tthis.class = ClearLanguageAction.DisabledClass;\n-\t\tif (!this.extension) {\n-\t\t\treturn;\n-\t\t}\n-\t\tif (!this.extensionsWorkbenchService.canSetLanguage(this.extension)) {\n-\t\t\treturn;\n-\t\t}\n-\t\tif (this.extension.gallery && language !== getLocale(this.extension.gallery)) {\n-\t\t\treturn;\n-\t\t}\n-\t\tthis.enabled = true;\n-\t\tthis.class = ClearLanguageAction.EnabledClass;\n \t}\n \n \toverride async run(): Promise<any> {\nIndex: code-server/lib/vscode/src/vs/workbench/workbench.web.main.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/workbench.web.main.ts\n+++ code-server/lib/vscode/src/vs/workbench/workbench.web.main.ts\n@@ -55,7 +55,7 @@ import './services/host/browser/browserH\n import '../platform/meteredConnection/browser/meteredConnectionService.js';\n import './services/lifecycle/browser/lifecycleService.js';\n import './services/clipboard/browser/clipboardService.js';\n-import './services/localization/browser/localeService.js';\n+import './services/localization/electron-browser/localeService.js';\n import './services/path/browser/pathService.js';\n import './services/themes/browser/browserHostColorSchemeService.js';\n import './services/encryption/browser/encryptionService.js';\n"
  },
  {
    "path": "patches/external-file-actions.diff",
    "content": "Add option to disable file downloads and uploads via cli\n\nThis patch adds support for a new CLI flag called `--disable-file-downloads`\nwhich allows a user to remove the \"Download...\" option that shows up when you\nright-click files in Code. It also disables the \"Show Local\" button on the dialog \nfor Save, Save-As and Save Workspace. The default value for this is `false`.\n\nThis patch also add support for a new CLI flag called `--disable-file-uploads`\nwhich disables the drag to upload functionality and the \"Upload...\" option when you\nright-click folders in Code. It also disables the \"Show Local\" button on the dialog \nfor opening a file. The default value for this is `false`.\n\nThis patch also adds trace log statements for when a file is read and written to disk.\n\nTo test disabling downloads, start code-server with `--disable-file-downloads`, open editor,\nright-click on a file (not a folder) and you should **not** see the\n\"Download...\" option. When saving a file or workspace, the \"Show Local\" button \nshould **not** appear on the dialog that comes on screen.\n\nTo test disabling uploads, start code-server with `--disable-file-uploads`, open editor,\nright-click on a folder (not a file) and you should **not** see the\n\"Upload...\" option. If you drag a file into the file navigator, the file should **not** upload \nand appear in the file navigator. When opening a file, the \"Show Local\" button \nshould **not** appear on the dialog that comes on screen.\n\nIndex: code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/web.api.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n@@ -303,6 +303,16 @@ export interface IWorkbenchConstructionO\n \t */\n \treadonly userDataPath?: string\n \n+\t/**\n+\t * Whether the \"Download...\" option is enabled for files.\n+\t */\n+\treadonly isEnabledFileDownloads?: boolean\n+\n+\t/**\n+\t * Whether the \"Upload...\" button is enabled.\n+\t */\n+\treadonly isEnabledFileUploads?: boolean\n+\n \t//#endregion\n \n \t//#region Profile options\nIndex: code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n@@ -34,6 +34,16 @@ export interface IBrowserWorkbenchEnviro\n \treadonly options?: IWorkbenchConstructionOptions;\n \n \t/**\n+\t * Enable downloading files via menu actions.\n+\t */\n+\treadonly isEnabledFileDownloads?: boolean;\n+\n+\t/**\n+\t * Enable uploading files via menu actions.\n+\t */\n+\treadonly isEnabledFileUploads?: boolean;\n+\n+\t/**\n \t * Gets whether a resolver extension is expected for the environment.\n \t */\n \treadonly expectsResolverExtension: boolean;\n@@ -111,6 +121,20 @@ export class BrowserWorkbenchEnvironment\n \t\treturn this.options.userDataPath;\n \t}\n \n+\tget isEnabledFileDownloads(): boolean {\n+\t\tif (typeof this.options.isEnabledFileDownloads === \"undefined\") {\n+\t\t\tthrow new Error('isEnabledFileDownloads was not provided to the browser');\n+\t\t}\n+\t\treturn this.options.isEnabledFileDownloads;\n+\t}\n+\n+\tget isEnabledFileUploads(): boolean {\n+\t\tif (typeof this.options.isEnabledFileUploads === \"undefined\") {\n+\t\t\tthrow new Error('isEnabledFileUploads was not provided to the browser');\n+\t\t}\n+\t\treturn this.options.isEnabledFileUploads;\n+\t}\n+\n \t@memoize\n \tget argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); }\n \nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -19,6 +19,8 @@ export const serverOptions: OptionDescri\n \t/* ----- code-server ----- */\n \t'disable-update-check': { type: 'boolean' },\n \t'auth': { type: 'string' },\n+\t'disable-file-downloads': { type: 'boolean' },\n+\t'disable-file-uploads': { type: 'boolean' },\n \n \t/* ----- server setup ----- */\n \n@@ -107,6 +109,8 @@ export interface ServerParsedArgs {\n \t/* ----- code-server ----- */\n \t'disable-update-check'?: boolean;\n \t'auth'?: string;\n+\t'disable-file-downloads'?: boolean;\n+\t'disable-file-uploads'?: boolean;\n \n \t/* ----- server setup ----- */\n \nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -370,6 +370,8 @@ export class WebClientServer {\n \t\t\tserverBasePath: basePath,\n \t\t\twebviewEndpoint: staticRoute + '/out/vs/workbench/contrib/webview/browser/pre',\n \t\t\tuserDataPath: this._environmentService.userDataPath,\n+\t\t\tisEnabledFileDownloads: !this._environmentService.args['disable-file-downloads'],\n+\t\t\tisEnabledFileUploads: !this._environmentService.args['disable-file-uploads'],\n \t\t\t_wrapWebWorkerExtHostInIframe,\n \t\t\tdevelopmentOptions: { enableSmokeTestDriver: this._environmentService.args['enable-smoke-test-driver'] ? true : undefined, logLevel: this._logService.getLevel() },\n \t\t\tsettingsSyncOptions: !this._environmentService.isBuilt && this._environmentService.args['enable-sync'] ? { enabled: true } : undefined,\nIndex: code-server/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n@@ -6,10 +6,10 @@\n import { Disposable } from '../../base/common/lifecycle.js';\n import { IContextKeyService, IContextKey, setConstant as setConstantContextKey } from '../../platform/contextkey/common/contextkey.js';\n import { IsMacContext, IsLinuxContext, IsWindowsContext, IsWebContext, IsMacNativeContext, IsDevelopmentContext, IsIOSContext, ProductQualityContext, IsMobileContext } from '../../platform/contextkey/common/contextkeys.js';\n-import { SplitEditorsVertically, InEditorZenModeContext, AuxiliaryBarVisibleContext, SideBarVisibleContext, PanelAlignmentContext, PanelMaximizedContext, PanelVisibleContext, EmbedderIdentifierContext, EditorTabsVisibleContext, IsMainEditorCenteredLayoutContext, MainEditorAreaVisibleContext, DirtyWorkingCopiesContext, EmptyWorkspaceSupportContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, IsMainWindowFullscreenContext, OpenFolderWorkspaceSupportContext, RemoteNameContext, VirtualWorkspaceContext, WorkbenchStateContext, WorkspaceFolderCountContext, PanelPositionContext, TemporaryWorkspaceContext, TitleBarVisibleContext, TitleBarStyleContext, IsAuxiliaryWindowFocusedContext, ActiveEditorGroupEmptyContext, ActiveEditorGroupIndexContext, ActiveEditorGroupLastContext, ActiveEditorGroupLockedContext, MultipleEditorGroupsContext, EditorsVisibleContext, AuxiliaryBarMaximizedContext, InAutomationContext, IsSessionsWindowContext } from '../common/contextkeys.js';\n+import { SplitEditorsVertically, InEditorZenModeContext, AuxiliaryBarVisibleContext, SideBarVisibleContext, PanelAlignmentContext, PanelMaximizedContext, PanelVisibleContext, EmbedderIdentifierContext, EditorTabsVisibleContext, IsMainEditorCenteredLayoutContext, MainEditorAreaVisibleContext, DirtyWorkingCopiesContext, EmptyWorkspaceSupportContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, IsMainWindowFullscreenContext, OpenFolderWorkspaceSupportContext, RemoteNameContext, VirtualWorkspaceContext, WorkbenchStateContext, WorkspaceFolderCountContext, PanelPositionContext, TemporaryWorkspaceContext, TitleBarVisibleContext, TitleBarStyleContext, IsAuxiliaryWindowFocusedContext, ActiveEditorGroupEmptyContext, ActiveEditorGroupIndexContext, ActiveEditorGroupLastContext, ActiveEditorGroupLockedContext, MultipleEditorGroupsContext, EditorsVisibleContext, AuxiliaryBarMaximizedContext, InAutomationContext, IsSessionsWindowContext, IsEnabledFileDownloads, IsEnabledFileUploads } from '../common/contextkeys.js';\n import { preferredSideBySideGroupDirection, GroupDirection, IEditorGroupsService } from '../services/editor/common/editorGroupsService.js';\n import { IConfigurationService } from '../../platform/configuration/common/configuration.js';\n-import { IWorkbenchEnvironmentService } from '../services/environment/common/environmentService.js';\n+import { IBrowserWorkbenchEnvironmentService } from '../services/environment/browser/environmentService.js';\n import { WorkbenchState, IWorkspaceContextService, isTemporaryWorkspace } from '../../platform/workspace/common/workspace.js';\n import { IWorkbenchLayoutService, Parts, positionToString } from '../services/layout/browser/layoutService.js';\n import { getRemoteName } from '../../platform/remote/common/remoteHosts.js';\n@@ -69,7 +69,7 @@ export class WorkbenchContextKeysHandler\n \t\t@IContextKeyService private readonly contextKeyService: IContextKeyService,\n \t\t@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,\n \t\t@IConfigurationService private readonly configurationService: IConfigurationService,\n-\t\t@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,\n+\t\t@IBrowserWorkbenchEnvironmentService private readonly environmentService: IBrowserWorkbenchEnvironmentService,\n \t\t@IProductService private readonly productService: IProductService,\n \t\t@IEditorGroupsService private readonly editorGroupService: IEditorGroupsService,\n \t\t@IEditorService private readonly editorService: IEditorService,\n@@ -201,6 +201,10 @@ export class WorkbenchContextKeysHandler\n \t\tthis.auxiliaryBarMaximizedContext = AuxiliaryBarMaximizedContext.bindTo(this.contextKeyService);\n \t\tthis.auxiliaryBarMaximizedContext.set(this.layoutService.isAuxiliaryBarMaximized());\n \n+\t\t// code-server\n+\t\tIsEnabledFileDownloads.bindTo(this.contextKeyService).set(this.environmentService.isEnabledFileDownloads ?? true)\n+\t\tIsEnabledFileUploads.bindTo(this.contextKeyService).set(this.environmentService.isEnabledFileUploads ?? true)\n+\n \t\tthis.registerListeners();\n \t}\n \nIndex: code-server/lib/vscode/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/files/browser/fileActions.contribution.ts\n@@ -20,7 +20,7 @@ import { CLOSE_SAVED_EDITORS_COMMAND_ID,\n import { AutoSaveAfterShortDelayContext } from '../../../services/filesConfiguration/common/filesConfigurationService.js';\n import { WorkbenchListDoubleSelection } from '../../../../platform/list/browser/listService.js';\n import { Schemas } from '../../../../base/common/network.js';\n-import { DirtyWorkingCopiesContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, WorkbenchStateContext, WorkspaceFolderCountContext, SidebarFocusContext, ActiveEditorCanRevertContext, ActiveEditorContext, ResourceContextKey, ActiveEditorAvailableEditorIdsContext, MultipleEditorsSelectedInGroupContext, TwoEditorsSelectedInGroupContext, SelectedEditorsInGroupFileOrUntitledResourceContextKey } from '../../../common/contextkeys.js';\n+import { IsEnabledFileDownloads, IsEnabledFileUploads, DirtyWorkingCopiesContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, WorkbenchStateContext, WorkspaceFolderCountContext, SidebarFocusContext, ActiveEditorCanRevertContext, ActiveEditorContext, ResourceContextKey, ActiveEditorAvailableEditorIdsContext, MultipleEditorsSelectedInGroupContext, TwoEditorsSelectedInGroupContext, SelectedEditorsInGroupFileOrUntitledResourceContextKey } from '../../../common/contextkeys.js';\n import { IsWebContext } from '../../../../platform/contextkey/common/contextkeys.js';\n import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js';\n import { ThemeIcon } from '../../../../base/common/themables.js';\n@@ -571,13 +571,16 @@ MenuRegistry.appendMenuItem(MenuId.Explo\n \t\tid: DOWNLOAD_COMMAND_ID,\n \t\ttitle: DOWNLOAD_LABEL\n \t},\n-\twhen: ContextKeyExpr.or(\n-\t\t// native: for any remote resource\n-\t\tContextKeyExpr.and(IsWebContext.toNegated(), ResourceContextKey.Scheme.notEqualsTo(Schemas.file)),\n-\t\t// web: for any files\n-\t\tContextKeyExpr.and(IsWebContext, ExplorerFolderContext.toNegated(), ExplorerRootContext.toNegated()),\n-\t\t// web: for any folders if file system API support is provided\n-\t\tContextKeyExpr.and(IsWebContext, HasWebFileSystemAccess)\n+\twhen: ContextKeyExpr.and(\n+\t\tIsEnabledFileDownloads,\n+\t\tContextKeyExpr.or(\n+\t\t\t// native: for any remote resource\n+\t\t\tContextKeyExpr.and(IsWebContext.toNegated(), ResourceContextKey.Scheme.notEqualsTo(Schemas.file)),\n+\t\t\t// web: for any files\n+\t\t\tContextKeyExpr.and(IsWebContext, ExplorerFolderContext.toNegated(), ExplorerRootContext.toNegated()),\n+\t\t\t// web: for any folders if file system API support is provided\n+\t\t\tContextKeyExpr.and(IsWebContext, HasWebFileSystemAccess)\n+\t\t)\n \t)\n }));\n \n@@ -589,6 +592,7 @@ MenuRegistry.appendMenuItem(MenuId.Explo\n \t\ttitle: UPLOAD_LABEL,\n \t},\n \twhen: ContextKeyExpr.and(\n+\t\tIsEnabledFileUploads,\n \t\t// only in web\n \t\tIsWebContext,\n \t\t// only on folders\nIndex: code-server/lib/vscode/src/vs/workbench/common/contextkeys.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/common/contextkeys.ts\n+++ code-server/lib/vscode/src/vs/workbench/common/contextkeys.ts\n@@ -41,6 +41,9 @@ export const EmbedderIdentifierContext =\n \n export const InAutomationContext = new RawContextKey<boolean>('inAutomation', false, localize('inAutomation', \"Whether VS Code is running under automation/smoke test\"));\n \n+export const IsEnabledFileDownloads = new RawContextKey<boolean>('isEnabledFileDownloads', true, true);\n+export const IsEnabledFileUploads = new RawContextKey<boolean>('isEnabledFileUploads', true, true);\n+\n //#endregion\n \n //#region < --- Window --- >\nIndex: code-server/lib/vscode/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/dialogs/browser/simpleFileDialog.ts\n@@ -18,7 +18,7 @@ import { IModelService } from '../../../\n import { ILanguageService } from '../../../../editor/common/languages/language.js';\n import { getIconClasses } from '../../../../editor/common/services/getIconClasses.js';\n import { Schemas } from '../../../../base/common/network.js';\n-import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js';\n+import { IBrowserWorkbenchEnvironmentService } from '../../environment/browser/environmentService.js';\n import { IRemoteAgentService } from '../../remote/common/remoteAgentService.js';\n import { IContextKeyService, IContextKey, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js';\n import { equalsIgnoreCase, format, startsWithIgnoreCase } from '../../../../base/common/strings.js';\n@@ -144,7 +144,7 @@ export class SimpleFileDialog extends Di\n \t\t@IFileDialogService private readonly fileDialogService: IFileDialogService,\n \t\t@IModelService private readonly modelService: IModelService,\n \t\t@ILanguageService private readonly languageService: ILanguageService,\n-\t\t@IWorkbenchEnvironmentService protected readonly environmentService: IWorkbenchEnvironmentService,\n+\t\t@IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService,\n \t\t@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,\n \t\t@IPathService protected readonly pathService: IPathService,\n \t\t@IKeybindingService private readonly keybindingService: IKeybindingService,\n@@ -322,21 +322,23 @@ export class SimpleFileDialog extends Di\n \t\t\tthis.filePickBox.placeholder = nls.localize('remoteFileDialog.placeholder', \"Folder path\");\n \t\t\tthis.filePickBox.ok = true;\n \t\t\tthis.filePickBox.okLabel = typeof this.options.openLabel === 'string' ? this.options.openLabel : this.options.openLabel?.withoutMnemonic;\n-\t\t\tif ((this.scheme !== Schemas.file) && this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1) && (this.options.availableFileSystems.indexOf(Schemas.file) > -1)) {\n-\t\t\t\tthis.filePickBox.customButton = true;\n-\t\t\t\tthis.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');\n-\t\t\t\tthis.filePickBox.customButtonSecondary = true;\n-\t\t\t\tlet action;\n-\t\t\t\tif (isSave) {\n-\t\t\t\t\taction = SaveLocalFileCommand;\n-\t\t\t\t} else {\n-\t\t\t\t\taction = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderCommand : OpenLocalFileCommand) : OpenLocalFolderCommand;\n-\t\t\t\t}\n-\t\t\t\tconst keybinding = this.keybindingService.lookupKeybinding(action.ID);\n-\t\t\t\tif (keybinding) {\n-\t\t\t\t\tconst label = keybinding.getLabel();\n-\t\t\t\t\tif (label) {\n-\t\t\t\t\t\tthis.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);\n+\t\t\tif ((isSave && this.environmentService.isEnabledFileDownloads) || (!isSave && this.environmentService.isEnabledFileUploads)) {\n+\t\t\t\tif ((this.scheme !== Schemas.file) && this.options && this.options.availableFileSystems && (this.options.availableFileSystems.length > 1) && (this.options.availableFileSystems.indexOf(Schemas.file) > -1)) {\n+\t\t\t\t\tthis.filePickBox.customButton = true;\n+\t\t\t\t\tthis.filePickBox.customLabel = nls.localize('remoteFileDialog.local', 'Show Local');\n+\t\t\t\t\tthis.filePickBox.customButtonSecondary = true;\n+\t\t\t\t\tlet action;\n+\t\t\t\t\tif (isSave) {\n+\t\t\t\t\t\taction = SaveLocalFileCommand;\n+\t\t\t\t\t} else {\n+\t\t\t\t\t\taction = this.allowFileSelection ? (this.allowFolderSelection ? OpenLocalFileFolderCommand : OpenLocalFileCommand) : OpenLocalFolderCommand;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst keybinding = this.keybindingService.lookupKeybinding(action.ID);\n+\t\t\t\t\tif (keybinding) {\n+\t\t\t\t\t\tconst label = keybinding.getLabel();\n+\t\t\t\t\t\tif (label) {\n+\t\t\t\t\t\t\tthis.filePickBox.customHover = format('{0} ({1})', action.LABEL, label);\n+\t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/files/browser/views/explorerViewer.ts\n@@ -65,6 +65,7 @@ import { timeout } from '../../../../../\n import { IFilesConfigurationService } from '../../../../services/filesConfiguration/common/filesConfigurationService.js';\n import { mainWindow } from '../../../../../base/browser/window.js';\n import { IExplorerFileContribution, explorerFileContribRegistry } from '../explorerFileContrib.js';\n+import { IBrowserWorkbenchEnvironmentService } from '../../../../services/environment/browser/environmentService.js';\n import { WorkbenchCompressibleAsyncDataTree } from '../../../../../platform/list/browser/listService.js';\n import { ISearchService, QueryType, getExcludes, ISearchConfiguration, ISearchComplete, IFileQuery } from '../../../../services/search/common/search.js';\n import { CancellationToken } from '../../../../../base/common/cancellation.js';\n@@ -1587,7 +1588,8 @@ export class FileDragAndDrop implements\n \t\t@IConfigurationService private configurationService: IConfigurationService,\n \t\t@IInstantiationService private instantiationService: IInstantiationService,\n \t\t@IWorkspaceEditingService private workspaceEditingService: IWorkspaceEditingService,\n-\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService\n+\t\t@IUriIdentityService private readonly uriIdentityService: IUriIdentityService,\n+\t\t@IBrowserWorkbenchEnvironmentService protected readonly environmentService: IBrowserWorkbenchEnvironmentService\n \t) {\n \t\tconst updateDropEnablement = (e: IConfigurationChangeEvent | undefined) => {\n \t\t\tif (!e || e.affectsConfiguration('explorer.enableDragAndDrop')) {\n@@ -1812,15 +1814,17 @@ export class FileDragAndDrop implements\n \n \t\t\t// External file DND (Import/Upload file)\n \t\t\tif (data instanceof NativeDragAndDropData) {\n-\t\t\t\t// Use local file import when supported\n-\t\t\t\tif (!isWeb || (isTemporaryWorkspace(this.contextService.getWorkspace()) && WebFileSystemAccess.supported(mainWindow))) {\n-\t\t\t\t\tconst fileImport = this.instantiationService.createInstance(ExternalFileImport);\n-\t\t\t\t\tawait fileImport.import(resolvedTarget, originalEvent, mainWindow);\n-\t\t\t\t}\n-\t\t\t\t// Otherwise fallback to browser based file upload\n-\t\t\t\telse {\n-\t\t\t\t\tconst browserUpload = this.instantiationService.createInstance(BrowserFileUpload);\n-\t\t\t\t\tawait browserUpload.upload(target, originalEvent);\n+\t\t\t\tif (this.environmentService.isEnabledFileUploads) {\n+\t\t\t\t\t// Use local file import when supported\n+\t\t\t\t\tif (!isWeb || (isTemporaryWorkspace(this.contextService.getWorkspace()) && WebFileSystemAccess.supported(mainWindow))) {\n+\t\t\t\t\t\tconst fileImport = this.instantiationService.createInstance(ExternalFileImport);\n+\t\t\t\t\t\tawait fileImport.import(resolvedTarget, originalEvent, mainWindow);\n+\t\t\t\t\t}\n+\t\t\t\t\t// Otherwise fallback to browser based file upload\n+\t\t\t\t\telse {\n+\t\t\t\t\t\tconst browserUpload = this.instantiationService.createInstance(BrowserFileUpload);\n+\t\t\t\t\t\tawait browserUpload.upload(target, originalEvent);\n+\t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \nIndex: code-server/lib/vscode/src/vs/platform/files/node/diskFileSystemProviderServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/files/node/diskFileSystemProviderServer.ts\n+++ code-server/lib/vscode/src/vs/platform/files/node/diskFileSystemProviderServer.ts\n@@ -99,6 +99,7 @@ export abstract class AbstractDiskFileSy\n \n \tprivate async readFile(uriTransformer: IURITransformer, _resource: UriComponents, opts?: IFileAtomicReadOptions): Promise<VSBuffer> {\n \t\tconst resource = this.transformIncoming(uriTransformer, _resource, true);\n+\t\tthis.logService.trace(`File action: readFile ${resource.path}`);\n \t\tconst buffer = await this.provider.readFile(resource, opts);\n \n \t\treturn VSBuffer.wrap(buffer);\n@@ -117,6 +118,7 @@ export abstract class AbstractDiskFileSy\n \t\t\t}\n \t\t});\n \n+\t\tthis.logService.trace(`File action: readFileStream ${resource.path}`);\n \t\tconst fileStream = this.provider.readFileStream(resource, opts, cts.token);\n \t\tlistenStream(fileStream, {\n \t\t\tonData: chunk => emitter.fire(VSBuffer.wrap(chunk)),\n@@ -137,7 +139,7 @@ export abstract class AbstractDiskFileSy\n \n \tprivate writeFile(uriTransformer: IURITransformer, _resource: UriComponents, content: VSBuffer, opts: IFileWriteOptions): Promise<void> {\n \t\tconst resource = this.transformIncoming(uriTransformer, _resource);\n-\n+\t\tthis.logService.trace(`File action: writeFile ${resource.path}`);\n \t\treturn this.provider.writeFile(resource, content.buffer, opts);\n \t}\n \n"
  },
  {
    "path": "patches/fix-build.diff",
    "content": "Fix protected field error\n\nThe mangler is reporting this error:\n\nWARN: 'setEditorVisible' from lib/vscode/src/vs/workbench/browser/parts/editor/editorPane.ts:160 became PUBLIC because of: lib/vscode/src/vs/workbench/contrib/chat/browser/chatDebug/chatDebugEditor.ts:304\nERROR: Protected fields have been made PUBLIC. This hurts minification and is therefore not allowed. Review the WARN messages further above\n\nNo idea how VS Code is dealing with this in their own builds.\n\nAdditionally, in CI the build keeps getting terminated, possibly from running\nout of memory (there is no error message, it simply says it was canceled).\n\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/chat/browser/chatDebug/chatDebugEditor.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/chat/browser/chatDebug/chatDebugEditor.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/chat/browser/chatDebug/chatDebugEditor.ts\n@@ -299,7 +299,7 @@ export class ChatDebugEditor extends Edi\n \t\t}\n \t}\n \n-\toverride setEditorVisible(visible: boolean): void {\n+\tprotected override setEditorVisible(visible: boolean): void {\n \t\tsuper.setEditorVisible(visible);\n \t\tif (visible) {\n \t\t\tthis.telemetryService.publicLog2<{}, ChatDebugPanelOpenedClassification>('chatDebugPanelOpened');\nIndex: code-server/lib/vscode/build/lib/mangle/index.ts\n===================================================================\n--- code-server.orig/lib/vscode/build/lib/mangle/index.ts\n+++ code-server/lib/vscode/build/lib/mangle/index.ts\n@@ -430,7 +430,7 @@ export class Mangler {\n \t\tthis.config = config;\n \n \t\tthis.renameWorkerPool = workerpool.pool(path.join(import.meta.dirname, 'renameWorker.ts'), {\n-\t\t\tmaxWorkers: 4,\n+\t\t\tmaxWorkers: 2,\n \t\t\tminWorkers: 'max'\n \t\t});\n \t}\n"
  },
  {
    "path": "patches/getting-started.diff",
    "content": "Modify Help: Getting Started\n\nThis modifies some text on the Getting Started page and adds text about using\ncode-server on a team.\n\nIt is enabled by default but can be overriden using the cli flag\n`--disable-getting-started-override`.\n\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/gettingStarted.ts\n@@ -3,7 +3,7 @@\n  *  Licensed under the MIT License. See License.txt in the project root for license information.\n  *--------------------------------------------------------------------------------------------*/\n \n-import { $, Dimension, addDisposableListener, append, clearNode, reset } from '../../../../base/browser/dom.js';\n+import { $, Dimension, addDisposableListener, append, clearNode, reset, prepend } from '../../../../base/browser/dom.js';\n import { renderFormattedText } from '../../../../base/browser/formattedTextRenderer.js';\n import { status } from '../../../../base/browser/ui/aria/aria.js';\n import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js';\n@@ -54,7 +54,7 @@ import { IRecentFolder, IRecentWorkspace\n import { OpenRecentAction } from '../../../browser/actions/windowActions.js';\n import { OpenFileFolderAction, OpenFolderAction, OpenFolderViaWorkspaceAction } from '../../../browser/actions/workspaceActions.js';\n import { EditorPane } from '../../../browser/parts/editor/editorPane.js';\n-import { WorkbenchStateContext } from '../../../common/contextkeys.js';\n+import { IsEnabledCoderGettingStarted, WorkbenchStateContext } from '../../../common/contextkeys.js';\n import { IEditorOpenContext, IEditorSerializer } from '../../../common/editor.js';\n import { IWebviewElement, IWebviewService } from '../../webview/browser/webview.js';\n import './gettingStartedColors.js';\n@@ -924,6 +924,72 @@ export class GettingStartedPage extends\n \t\t\t$('p.subtitle.description', {}, localize({ key: 'gettingStarted.editingEvolved', comment: ['Shown as subtitle on the Welcome page.'] }, \"Editing evolved\"))\n \t\t);\n \n+\t\tlet gettingStartedCoder: HTMLElement = $('.header', {});\n+\t\tif (this.contextService.contextMatchesRules(IsEnabledCoderGettingStarted)) {\n+\t\t\tgettingStartedCoder = $('.gettingStartedCategory', {},\n+\t\t\t\t$('h2', {\n+\t\t\t\t\tstyle: 'margin-bottom: 12px',\n+\t\t\t\t}, 'Next Up'),\n+\t\t\t\t$('a', {\n+\t\t\t\t\thref: 'https://cdr.co/code-server-to-coder',\n+\t\t\t\t\ttarget: '_blank',\n+\t\t\t\t},\n+\t\t\t\t\t$('button', {\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'padding: 10px 16px\t',\n+\t\t\t\t\t\t\t'border-radius: 4px',\n+\t\t\t\t\t\t\t'background: linear-gradient(94.04deg, #7934DA 0%, #4D52E0 101.2%)',\n+\t\t\t\t\t\t\t'color: white',\n+\t\t\t\t\t\t\t'overflow: hidden',\n+\t\t\t\t\t\t\t'margin-right: 14px',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t},\n+\t\t\t\t\t$('h3', {\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'margin: 0px 0px 6px',\n+\t\t\t\t\t\t\t'font-weight: 500',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t}, 'Deploy code-server for your team'),\n+\t\t\t\t\t$('p', {\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'margin: 0',\n+\t\t\t\t\t\t\t'font-size: 13px',\n+\t\t\t\t\t\t\t'color: #dcdee2',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t}, 'Provision software development environments on your infrastructure with Coder.'),\n+\t\t\t\t\t$('p', {\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'margin-top: 8px',\n+\t\t\t\t\t\t\t'font-size: 13px',\n+\t\t\t\t\t\t\t'color: #dcdee2',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t}, 'Coder is a self-service portal which provisions via Terraform—Linux, macOS, Windows, x86, ARM, and, of course, Kubernetes based infrastructure.'),\n+\t\t\t\t\t$('p', {\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'margin: 0',\n+\t\t\t\t\t\t\t'margin-top: 8px',\n+\t\t\t\t\t\t\t'font-size: 13px',\n+\t\t\t\t\t\t\t'display: flex',\n+\t\t\t\t\t\t\t'align-items: center',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t}, 'Get started ', $('span', {\n+\t\t\t\t\t\tclass: ThemeIcon.asClassName(Codicon.arrowRight),\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'color: white',\n+\t\t\t\t\t\t\t'margin-left: 8px',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t})),\n+\t\t\t\t\t$('img', {\n+\t\t\t\t\t\tsrc: './_static/src/browser/media/templates.png',\n+\t\t\t\t\t\tstyle: [\n+\t\t\t\t\t\t\t'margin-bottom: -65px',\n+\t\t\t\t\t\t].join(';'),\n+\t\t\t\t\t}),\n+\t\t\t\t\t),\n+\t\t\t\t),\n+\t\t\t);\n+\t\t}\n+\n \t\tconst leftColumn = $('.categories-column.categories-column-left', {},);\n \t\tconst rightColumn = $('.categories-column.categories-column-right', {},);\n \n@@ -959,6 +1025,9 @@ export class GettingStartedPage extends\n \t\t\t\trecentList.setLimit(5);\n \t\t\t\treset(leftColumn, startList.getDomElement(), recentList.getDomElement());\n \t\t\t}\n+\t\t\tif (this.contextService.contextMatchesRules(IsEnabledCoderGettingStarted)) {\n+\t\t\t\tprepend(rightColumn, gettingStartedCoder)\n+\t\t\t}\n \t\t};\n \n \t\tgettingStartedList.onDidChange(layoutLists);\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/media/gettingStarted.css\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/media/gettingStarted.css\n+++ code-server/lib/vscode/src/vs/workbench/contrib/welcomeGettingStarted/browser/media/gettingStarted.css\n@@ -60,6 +60,15 @@\n \tdisplay: block;\n }\n \n+.monaco-workbench .part.editor > .content .gettingStartedContainer .coder {\n+\tmargin-bottom: 0.2em;\n+}\n+\n+.monaco-workbench .part.editor > .content .gettingStartedContainer .coder-coder {\n+\tfont-size: 1em;\n+\tmargin-top: 0.2em;\n+}\n+\n .monaco-workbench.hc-black .part.editor > .content .gettingStartedContainer .subtitle,\n .monaco-workbench.hc-light .part.editor > .content .gettingStartedContainer .subtitle {\n \tfont-weight: 200;\nIndex: code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/web.api.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n@@ -313,6 +313,11 @@ export interface IWorkbenchConstructionO\n \t */\n \treadonly isEnabledFileUploads?: boolean\n \n+\t/**\n+\t * Whether to use Coder's custom Getting Started text.\n+\t */\n+\treadonly isEnabledCoderGettingStarted?: boolean\n+\n \t//#endregion\n \n \t//#region Profile options\nIndex: code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n@@ -44,6 +44,11 @@ export interface IBrowserWorkbenchEnviro\n \treadonly isEnabledFileUploads?: boolean;\n \n \t/**\n+\t * Enable Coder's custom getting started text.\n+\t */\n+\treadonly isEnabledCoderGettingStarted?: boolean;\n+\n+\t/**\n \t * Gets whether a resolver extension is expected for the environment.\n \t */\n \treadonly expectsResolverExtension: boolean;\n@@ -135,6 +140,13 @@ export class BrowserWorkbenchEnvironment\n \t\treturn this.options.isEnabledFileUploads;\n \t}\n \n+\tget isEnabledCoderGettingStarted(): boolean {\n+\t\tif (typeof this.options.isEnabledCoderGettingStarted === \"undefined\") {\n+\t\t\tthrow new Error('isEnabledCoderGettingStarted was not provided to the browser');\n+\t\t}\n+\t\treturn this.options.isEnabledCoderGettingStarted;\n+\t}\n+\n \t@memoize\n \tget argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); }\n \nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -21,6 +21,7 @@ export const serverOptions: OptionDescri\n \t'auth': { type: 'string' },\n \t'disable-file-downloads': { type: 'boolean' },\n \t'disable-file-uploads': { type: 'boolean' },\n+\t'disable-getting-started-override': { type: 'boolean' },\n \n \t/* ----- server setup ----- */\n \n@@ -111,6 +112,7 @@ export interface ServerParsedArgs {\n \t'auth'?: string;\n \t'disable-file-downloads'?: boolean;\n \t'disable-file-uploads'?: boolean;\n+\t'disable-getting-started-override'?: boolean,\n \n \t/* ----- server setup ----- */\n \nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -374,6 +374,7 @@ export class WebClientServer {\n \t\t\tuserDataPath: this._environmentService.userDataPath,\n \t\t\tisEnabledFileDownloads: !this._environmentService.args['disable-file-downloads'],\n \t\t\tisEnabledFileUploads: !this._environmentService.args['disable-file-uploads'],\n+\t\t\tisEnabledCoderGettingStarted: !this._environmentService.args['disable-getting-started-override'],\n \t\t\t_wrapWebWorkerExtHostInIframe,\n \t\t\tdevelopmentOptions: { enableSmokeTestDriver: this._environmentService.args['enable-smoke-test-driver'] ? true : undefined, logLevel: this._logService.getLevel() },\n \t\t\tsettingsSyncOptions: !this._environmentService.isBuilt && this._environmentService.args['enable-sync'] ? { enabled: true } : undefined,\nIndex: code-server/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/contextkeys.ts\n@@ -6,7 +6,7 @@\n import { Disposable } from '../../base/common/lifecycle.js';\n import { IContextKeyService, IContextKey, setConstant as setConstantContextKey } from '../../platform/contextkey/common/contextkey.js';\n import { IsMacContext, IsLinuxContext, IsWindowsContext, IsWebContext, IsMacNativeContext, IsDevelopmentContext, IsIOSContext, ProductQualityContext, IsMobileContext } from '../../platform/contextkey/common/contextkeys.js';\n-import { SplitEditorsVertically, InEditorZenModeContext, AuxiliaryBarVisibleContext, SideBarVisibleContext, PanelAlignmentContext, PanelMaximizedContext, PanelVisibleContext, EmbedderIdentifierContext, EditorTabsVisibleContext, IsMainEditorCenteredLayoutContext, MainEditorAreaVisibleContext, DirtyWorkingCopiesContext, EmptyWorkspaceSupportContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, IsMainWindowFullscreenContext, OpenFolderWorkspaceSupportContext, RemoteNameContext, VirtualWorkspaceContext, WorkbenchStateContext, WorkspaceFolderCountContext, PanelPositionContext, TemporaryWorkspaceContext, TitleBarVisibleContext, TitleBarStyleContext, IsAuxiliaryWindowFocusedContext, ActiveEditorGroupEmptyContext, ActiveEditorGroupIndexContext, ActiveEditorGroupLastContext, ActiveEditorGroupLockedContext, MultipleEditorGroupsContext, EditorsVisibleContext, AuxiliaryBarMaximizedContext, InAutomationContext, IsSessionsWindowContext, IsEnabledFileDownloads, IsEnabledFileUploads } from '../common/contextkeys.js';\n+import { SplitEditorsVertically, InEditorZenModeContext, AuxiliaryBarVisibleContext, SideBarVisibleContext, PanelAlignmentContext, PanelMaximizedContext, PanelVisibleContext, EmbedderIdentifierContext, EditorTabsVisibleContext, IsMainEditorCenteredLayoutContext, MainEditorAreaVisibleContext, DirtyWorkingCopiesContext, EmptyWorkspaceSupportContext, EnterMultiRootWorkspaceSupportContext, HasWebFileSystemAccess, IsMainWindowFullscreenContext, OpenFolderWorkspaceSupportContext, RemoteNameContext, VirtualWorkspaceContext, WorkbenchStateContext, WorkspaceFolderCountContext, PanelPositionContext, TemporaryWorkspaceContext, TitleBarVisibleContext, TitleBarStyleContext, IsAuxiliaryWindowFocusedContext, ActiveEditorGroupEmptyContext, ActiveEditorGroupIndexContext, ActiveEditorGroupLastContext, ActiveEditorGroupLockedContext, MultipleEditorGroupsContext, EditorsVisibleContext, AuxiliaryBarMaximizedContext, InAutomationContext, IsSessionsWindowContext, IsEnabledFileDownloads, IsEnabledFileUploads, IsEnabledCoderGettingStarted, } from '../common/contextkeys.js';\n import { preferredSideBySideGroupDirection, GroupDirection, IEditorGroupsService } from '../services/editor/common/editorGroupsService.js';\n import { IConfigurationService } from '../../platform/configuration/common/configuration.js';\n import { IBrowserWorkbenchEnvironmentService } from '../services/environment/browser/environmentService.js';\n@@ -204,6 +204,7 @@ export class WorkbenchContextKeysHandler\n \t\t// code-server\n \t\tIsEnabledFileDownloads.bindTo(this.contextKeyService).set(this.environmentService.isEnabledFileDownloads ?? true)\n \t\tIsEnabledFileUploads.bindTo(this.contextKeyService).set(this.environmentService.isEnabledFileUploads ?? true)\n+\t\tIsEnabledCoderGettingStarted.bindTo(this.contextKeyService).set(this.environmentService.isEnabledCoderGettingStarted ?? true)\n \n \t\tthis.registerListeners();\n \t}\nIndex: code-server/lib/vscode/src/vs/workbench/common/contextkeys.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/common/contextkeys.ts\n+++ code-server/lib/vscode/src/vs/workbench/common/contextkeys.ts\n@@ -43,6 +43,7 @@ export const InAutomationContext = new R\n \n export const IsEnabledFileDownloads = new RawContextKey<boolean>('isEnabledFileDownloads', true, true);\n export const IsEnabledFileUploads = new RawContextKey<boolean>('isEnabledFileUploads', true, true);\n+export const IsEnabledCoderGettingStarted = new RawContextKey<boolean>('isEnabledCoderGettingStarted', true, true);\n \n //#endregion\n \n"
  },
  {
    "path": "patches/insecure-notification.diff",
    "content": "Add a notification when accessing code-server in an insecure context\n\nThis is done because otherwise when things like the clipboard do not work users\nmay think code-server is broken.  Ideally there would be a notification at the\npoint where these things are used instead of this though.\n\nTo test access over something like an HTTP domain or an IP address (not\nlocalhost). For example:\n\n1. run code-server\n2. use ngrok to expose code-server\n3. access via HTTP\n4. look for notification in bottom right\n\nIndex: code-server/lib/vscode/src/vs/workbench/browser/client.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/client.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/client.ts\n@@ -1,7 +1,10 @@\n import { Disposable } from \"../../base/common/lifecycle.js\";\n+import { localize } from '../../nls.js';\n+import { INotificationService, Severity } from '../../platform/notification/common/notification.js';\n \n export class CodeServerClient extends Disposable {\n \tconstructor (\n+\t\t@INotificationService private notificationService: INotificationService,\n \t) {\n \t\tsuper();\n \t}\n@@ -42,5 +45,31 @@ export class CodeServerClient extends Di\n \t\t\t\t}\n \t\t\t});\n \t\t}\n+\n+\t\tif (!window.isSecureContext) {\n+\t\t\tthis.notificationService.notify({\n+\t\t\t\tseverity: Severity.Warning,\n+\t\t\t\tmessage: localize(\n+\t\t\t\t\t'insecureContext',\n+\t\t\t\t\t\"{0} is being accessed in an insecure context. Web views, the clipboard, and other functionality may not work as expected.\",\n+\t\t\t\t\t'code-server',\n+\t\t\t\t),\n+\t\t\t\tactions: {\n+\t\t\t\t\tprimary: [\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tid: 'understand',\n+\t\t\t\t\t\t\tlabel: localize('confirmInsecure', \"I understand\"),\n+\t\t\t\t\t\t\ttooltip: '',\n+\t\t\t\t\t\t\tclass: undefined,\n+\t\t\t\t\t\t\tenabled: true,\n+\t\t\t\t\t\t\tchecked: true,\n+\t\t\t\t\t\t\trun: () => {\n+\t\t\t\t\t\t\t\treturn Promise.resolve();\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t},\n+\t\t\t\t\t],\n+\t\t\t\t},\n+\t\t\t});\n+\t\t}\n \t}\n }\n"
  },
  {
    "path": "patches/integration.diff",
    "content": "Prepare Code for integration with code-server\n\n1. We already have the arguments so allow passing them in.  There is also a\n   slight change in a few directories to preserve the directory structure we\n   have been using and to not override passed-in arguments.\n2. Modify the entry point to allow importing the code, instead of just running\n   the server immediately.\n3. Modify the terminal environment to filter out code-server environment variables.\n4. Add the code-server version to the help dialog.\n5. Add ready events for use in an iframe.\n6. Add our icons and remove the existing ones.\n7. Use our own manifest.\n\nIndex: code-server/lib/vscode/src/vs/server/node/server.main.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/server.main.ts\n+++ code-server/lib/vscode/src/vs/server/node/server.main.ts\n@@ -12,7 +12,7 @@ import { createServer as doCreateServer,\n import { parseArgs, ErrorReporter } from '../../platform/environment/node/argv.js';\n import { join, dirname } from '../../base/common/path.js';\n import { performance } from 'perf_hooks';\n-import { serverOptions } from './serverEnvironmentService.js';\n+import { serverOptions, ServerParsedArgs } from './serverEnvironmentService.js';\n import product from '../../platform/product/common/product.js';\n import * as perf from '../../base/common/performance.js';\n \n@@ -34,38 +34,47 @@ const errorReporter: ErrorReporter = {\n \t}\n };\n \n-const args = parseArgs(process.argv.slice(2), serverOptions, errorReporter);\n+function parse(): ServerParsedArgs {\n+\treturn parseArgs(process.argv.slice(2), serverOptions, errorReporter);\n+}\n \n-const REMOTE_DATA_FOLDER = args['server-data-dir'] || process.env['VSCODE_AGENT_FOLDER'] || join(os.homedir(), product.serverDataFolderName || '.vscode-remote');\n-const USER_DATA_PATH = join(REMOTE_DATA_FOLDER, 'data');\n-const APP_SETTINGS_HOME = join(USER_DATA_PATH, 'User');\n-const GLOBAL_STORAGE_HOME = join(APP_SETTINGS_HOME, 'globalStorage');\n-const LOCAL_HISTORY_HOME = join(APP_SETTINGS_HOME, 'History');\n-const MACHINE_SETTINGS_HOME = join(USER_DATA_PATH, 'Machine');\n-args['user-data-dir'] = USER_DATA_PATH;\n-const APP_ROOT = dirname(FileAccess.asFileUri('').fsPath);\n-const BUILTIN_EXTENSIONS_FOLDER_PATH = join(APP_ROOT, 'extensions');\n-args['builtin-extensions-dir'] = BUILTIN_EXTENSIONS_FOLDER_PATH;\n-args['extensions-dir'] = args['extensions-dir'] || join(REMOTE_DATA_FOLDER, 'extensions');\n-\n-[REMOTE_DATA_FOLDER, args['extensions-dir'], USER_DATA_PATH, APP_SETTINGS_HOME, MACHINE_SETTINGS_HOME, GLOBAL_STORAGE_HOME, LOCAL_HISTORY_HOME].forEach(f => {\n-\ttry {\n-\t\tif (!fs.existsSync(f)) {\n-\t\t\tfs.mkdirSync(f, { mode: 0o700, recursive: true });\n-\t\t}\n-\t} catch (err) { console.error(err); }\n-});\n+function createDirs(args: ServerParsedArgs): string {\n+\tconst REMOTE_DATA_FOLDER = args['server-data-dir'] || args['user-data-dir'] || process.env['VSCODE_AGENT_FOLDER'] || join(os.homedir(), product.serverDataFolderName || '.vscode-remote');\n+\tconst USER_DATA_PATH = args['user-data-dir'] || join(REMOTE_DATA_FOLDER, 'data');\n+\tconst APP_SETTINGS_HOME = join(USER_DATA_PATH, 'User');\n+\tconst GLOBAL_STORAGE_HOME = join(APP_SETTINGS_HOME, 'globalStorage');\n+\tconst LOCAL_HISTORY_HOME = join(APP_SETTINGS_HOME, 'History');\n+\tconst MACHINE_SETTINGS_HOME = join(USER_DATA_PATH, 'Machine');\n+\targs['user-data-dir'] = USER_DATA_PATH;\n+\tconst APP_ROOT = dirname(FileAccess.asFileUri('').fsPath);\n+\tconst BUILTIN_EXTENSIONS_FOLDER_PATH = args['builtin-extensions-dir'] || join(APP_ROOT, 'extensions');\n+\targs['builtin-extensions-dir'] = BUILTIN_EXTENSIONS_FOLDER_PATH;\n+\targs['extensions-dir'] = args['extensions-dir'] || join(REMOTE_DATA_FOLDER, 'extensions');\n+\n+\t[REMOTE_DATA_FOLDER, args['extensions-dir'], USER_DATA_PATH, APP_SETTINGS_HOME, MACHINE_SETTINGS_HOME, GLOBAL_STORAGE_HOME, LOCAL_HISTORY_HOME].forEach(f => {\n+\t\ttry {\n+\t\t\tif (!fs.existsSync(f)) {\n+\t\t\t\tfs.mkdirSync(f, { mode: 0o700, recursive: true });\n+\t\t\t}\n+\t\t} catch (err) { console.error(err); }\n+\t});\n+\treturn REMOTE_DATA_FOLDER;\n+}\n \n /**\n  * invoked by server-main.js\n  */\n-export function spawnCli() {\n-\trunCli(args, REMOTE_DATA_FOLDER, serverOptions);\n+function spawnCli(args = parse()): Promise<void> {\n+\treturn runCli(args, createDirs(args), serverOptions);\n }\n \n /**\n  * invoked by server-main.js\n  */\n-export function createServer(address: string | net.AddressInfo | null): Promise<IServerAPI> {\n-\treturn doCreateServer(address, args, REMOTE_DATA_FOLDER);\n+function createServer(address: string | net.AddressInfo | null, args = parse()): Promise<IServerAPI> {\n+\treturn doCreateServer(address, args, createDirs(args));\n }\n+\n+// The aliases prevent the names getting mangled during minification which would\n+// make it difficult to import.\n+export { spawnCli as spawnCli, createServer as createServer };\nIndex: code-server/lib/vscode/src/vs/base/common/processes.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/processes.ts\n+++ code-server/lib/vscode/src/vs/base/common/processes.ts\n@@ -111,6 +111,8 @@ export function sanitizeProcessEnvironme\n \t\t/^VSCODE_(?!(PORTABLE|SHELL_LOGIN|ENV_REPLACE|ENV_APPEND|ENV_PREPEND)).+$/,\n \t\t/^SNAP(|_.*)$/,\n \t\t/^GDK_PIXBUF_.+$/,\n+\t\t/^CODE_SERVER_.+$/,\n+\t\t/^CS_.+$/,\n \t];\n \tconst envKeys = Object.keys(env);\n \tenvKeys\nIndex: code-server/lib/vscode/src/vs/workbench/browser/client.ts\n===================================================================\n--- /dev/null\n+++ code-server/lib/vscode/src/vs/workbench/browser/client.ts\n@@ -0,0 +1,46 @@\n+import { Disposable } from \"../../base/common/lifecycle.js\";\n+\n+export class CodeServerClient extends Disposable {\n+\tconstructor (\n+\t) {\n+\t\tsuper();\n+\t}\n+\n+\tasync startup(): Promise<void> {\n+\t\t// Emit ready events\n+\t\tconst event = new CustomEvent('ide-ready');\n+\t\twindow.dispatchEvent(event);\n+\n+\t\tif (parent) {\n+\t\t\t// Tell the parent loading has completed.\n+\t\t\tparent.postMessage({ event: 'loaded' }, '*');\n+\n+\t\t\t// Proxy or stop proxing events as requested by the parent.\n+\t\t\tconst listeners = new Map<string, (event: Event) => void>();\n+\n+\t\t\twindow.addEventListener('message', parentEvent => {\n+\t\t\t\tconst eventName = parentEvent.data.bind || parentEvent.data.unbind;\n+\t\t\t\tif (eventName) {\n+\t\t\t\t\tconst oldListener = listeners.get(eventName);\n+\t\t\t\t\tif (oldListener) {\n+\t\t\t\t\t\tdocument.removeEventListener(eventName, oldListener);\n+\t\t\t\t\t}\n+\t\t\t\t}\n+\n+\t\t\t\tif (parentEvent.data.bind && parentEvent.data.prop) {\n+\t\t\t\t\tconst listener = (event: Event) => {\n+\t\t\t\t\t\tparent?.postMessage(\n+\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\tevent: parentEvent.data.event,\n+\t\t\t\t\t\t\t\t[parentEvent.data.prop]: event[parentEvent.data.prop as keyof Event],\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\twindow.location.origin,\n+\t\t\t\t\t\t);\n+\t\t\t\t\t};\n+\t\t\t\t\tlisteners.set(parentEvent.data.bind, listener);\n+\t\t\t\t\tdocument.addEventListener(parentEvent.data.bind, listener);\n+\t\t\t\t}\n+\t\t\t});\n+\t\t}\n+\t}\n+}\nIndex: code-server/lib/vscode/src/vs/workbench/browser/web.main.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/web.main.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/web.main.ts\n@@ -65,6 +65,7 @@ import { IOpenerService } from '../../pl\n import { mixin, safeStringify } from '../../base/common/objects.js';\n import { IndexedDB } from '../../base/browser/indexedDB.js';\n import { WebFileSystemAccess } from '../../platform/files/browser/webFileSystemAccess.js';\n+import { CodeServerClient } from '../../workbench/browser/client.js';\n import { IProgressService } from '../../platform/progress/common/progress.js';\n import { DelayedLogChannel } from '../services/output/common/delayedLogChannel.js';\n import { dirname, joinPath } from '../../base/common/resources.js';\n@@ -140,6 +141,9 @@ export class BrowserMain extends Disposa\n \t\t// Startup\n \t\tconst instantiationService = workbench.startup();\n \n+\t\tconst codeServerClient = this._register(instantiationService.createInstance(CodeServerClient));\n+\t\tawait codeServerClient.startup();\n+\n \t\t// Window\n \t\tthis._register(instantiationService.createInstance(BrowserWindow));\n \nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -65,6 +65,8 @@ export type ExtensionVirtualWorkspaceSup\n };\n \n export interface IProductConfiguration {\n+\treadonly codeServerVersion?: string\n+\n \treadonly version: string;\n \treadonly date?: string;\n \treadonly quality?: string;\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench-dev.html\n@@ -11,7 +11,8 @@\n \t\t<meta name=\"mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-title\" content=\"Code\">\n-\t\t<link rel=\"apple-touch-icon\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/code-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"/_static/src/browser/media/pwa-icon-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"/_static/src/browser/media/pwa-icon-512.png\" />\n \n \t\t<!-- Disable pinch zooming -->\n \t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\">\n@@ -26,8 +27,9 @@\n \t\t<meta id=\"vscode-workbench-builtin-extensions\" data-settings=\"{{WORKBENCH_BUILTIN_EXTENSIONS}}\">\n \n \t\t<!-- Workbench Icon/Manifest/CSS -->\n-\t\t<link rel=\"icon\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/favicon.ico\" type=\"image/x-icon\" />\n-\t\t<link rel=\"manifest\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/manifest.json\" crossorigin=\"use-credentials\" />\n+\t\t<link rel=\"icon\" href=\"/_static/src/browser/media/favicon-dark-support.svg\" />\n+\t\t<link rel=\"alternate icon\" href=\"/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n+\t\t<link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n \t\t<style id=\"vscode-css-modules\" type=\"text/css\" media=\"screen\"></style>\n \n \t</head>\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench.html\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench.html\n@@ -11,7 +11,8 @@\n \t\t<meta name=\"mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n \t\t<meta name=\"apple-mobile-web-app-title\" content=\"Code\">\n-\t\t<link rel=\"apple-touch-icon\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/code-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"/_static/src/browser/media/pwa-icon-192.png\" />\n+\t\t<link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"/_static/src/browser/media/pwa-icon-512.png\" />\n \n \t\t<!-- Disable pinch zooming -->\n \t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\">\n@@ -23,8 +24,9 @@\n \t\t<meta id=\"vscode-workbench-auth-session\" data-settings=\"{{WORKBENCH_AUTH_SESSION}}\">\n \n \t\t<!-- Workbench Icon/Manifest/CSS -->\n-\t\t<link rel=\"icon\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/favicon.ico\" type=\"image/x-icon\" />\n-\t\t<link rel=\"manifest\" href=\"{{WORKBENCH_WEB_BASE_URL}}/resources/server/manifest.json\" crossorigin=\"use-credentials\" />\n+\t\t<link rel=\"icon\" href=\"/_static/src/browser/media/favicon-dark-support.svg\" />\n+\t\t<link rel=\"alternate icon\" href=\"/_static/src/browser/media/favicon.ico\" type=\"image/x-icon\" />\n+\t\t<link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n \t\t<link rel=\"stylesheet\" href=\"{{WORKBENCH_WEB_BASE_URL}}/out/vs/code/browser/workbench/workbench.css\">\n \n \t</head>\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -334,6 +334,7 @@ export class WebClientServer {\n \t\t} : undefined;\n \n \t\tconst productConfiguration: Partial<Mutable<IProductConfiguration>> = {\n+\t\t\tcodeServerVersion: this._productService.codeServerVersion,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._webExtensionResourceUrlTemplate && this._productService.extensionsGallery ? {\n \t\t\t\t...this._productService.extensionsGallery,\nIndex: code-server/lib/vscode/src/server-main.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/server-main.ts\n+++ code-server/lib/vscode/src/server-main.ts\n@@ -22,6 +22,9 @@ import { IServerAPI } from './vs/server/\n perf.mark('code/server/start');\n (globalThis as { vscodeServerStartTime?: number }).vscodeServerStartTime = performance.now();\n \n+// This is not indented to make the diff less noisy.  We need to move this out\n+// of the top-level so it will not run immediately and we can control the start.\n+async function start() {\n // Do a quick parse to determine if a server or the cli needs to be started\n const parsedArgs = minimist(process.argv.slice(2), {\n \tboolean: ['start-server', 'list-extensions', 'print-ip-address', 'help', 'version', 'accept-server-license-terms', 'update-extensions'],\n@@ -150,6 +153,7 @@ if (shouldSpawnCli) {\n \t\t}\n \t});\n }\n+}\n \n function sanitizeStringArg(val: unknown): string | undefined {\n \tif (Array.isArray(val)) { // if an argument is passed multiple times, minimist creates an array\n@@ -283,3 +287,22 @@ function prompt(question: string): Promi\n \t\t});\n \t});\n }\n+\n+async function loadCodeWithNls() {\n+\tconst nlsConfiguration = await resolveNLSConfiguration({\n+\t\tuserLocale: 'en',\n+\t\tosLocale: 'en',\n+\t\tcommit: product.commit,\n+\t\tuserDataPath: '',\n+\t\tnlsMetadataPath: import.meta.dirname,\n+\t});\n+\treturn loadCode(nlsConfiguration);\n+}\n+\n+// This alias prevents the name getting mangled during minification which would\n+// make it difficult to import.\n+export { loadCodeWithNls as loadCodeWithNls };\n+\n+if (!process.env.CODE_SERVER_PARENT_PID) {\n+\tstart();\n+}\nIndex: code-server/lib/vscode/src/vs/workbench/browser/parts/dialogs/dialog.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/parts/dialogs/dialog.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/parts/dialogs/dialog.ts\n@@ -47,8 +47,11 @@ export function createWorkbenchDialogOpt\n \n export function createBrowserAboutDialogDetails(productService: IProductService): { title: string; details: string; detailsToCopy: string } {\n \tconst detailString = (useAgo: boolean): string => {\n-\t\treturn localize('aboutDetail',\n-\t\t\t\"Version: {0}\\nCommit: {1}\\nDate: {2}\\nBrowser: {3}\",\n+\t\treturn localize('aboutCodeServerDetail',\n+\t\t\t\"code-server: {0}\",\n+\t\t\tproductService.codeServerVersion ? `v${productService.codeServerVersion}` : 'Unknown'\n+\t\t) + '\\n' + localize('aboutDetail',\n+\t\t\t\"Code: {0}\\nCommit: {1}\\nDate: {2}\\nBrowser: {3}\",\n \t\t\tproductService.version || 'Unknown',\n \t\t\tproductService.commit || 'Unknown',\n \t\t\tproductService.date ? `${productService.date}${useAgo ? ' (' + fromNow(new Date(productService.date), true) + ')' : ''}` : 'Unknown',\n"
  },
  {
    "path": "patches/keepalive.diff",
    "content": "This can be removed after upgrading to Node >= 19 as keepAlive is defaulted to\ntrue after 19.\n\nIndex: code-server/lib/vscode/src/vs/platform/request/node/proxy.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/request/node/proxy.ts\n+++ code-server/lib/vscode/src/vs/platform/request/node/proxy.ts\n@@ -42,6 +42,7 @@ export async function getProxyAgent(rawR\n \t\tport: (proxyEndpoint.port ? +proxyEndpoint.port : 0) || (proxyEndpoint.protocol === 'https' ? 443 : 80),\n \t\tauth: proxyEndpoint.auth,\n \t\trejectUnauthorized: isBoolean(options.strictSSL) ? options.strictSSL : true,\n+\t\tkeepAlive: true,\n \t};\n \n \tif (requestURL.protocol === 'http:') {\n"
  },
  {
    "path": "patches/local-storage.diff",
    "content": "Make storage local to the remote server\n\nThis makes user settings will be stored in the file system instead of in browser\nstorage. Using browser storage makes sharing or seeding settings between\nbrowsers difficult and remote settings is not a sufficient replacement because\nsome settings are only allowed to be set on the user level.\n\nUnfortunately this does not affect state which uses a separate method with\nIndexedDB and does not appear nearly as easy to redirect to disk.\n\nTo test change settings from the UI and on disk while making sure they appear on\nthe other side.\n\nThis patch also resolves a bug where a global value for workspace initialization\nis used in a non async-safe way.\n\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -365,6 +365,7 @@ export class WebClientServer {\n \t\t\tremoteAuthority,\n \t\t\tserverBasePath: basePath,\n \t\t\twebviewEndpoint: staticRoute + '/out/vs/workbench/contrib/webview/browser/pre',\n+\t\t\tuserDataPath: this._environmentService.userDataPath,\n \t\t\t_wrapWebWorkerExtHostInIframe,\n \t\t\tdevelopmentOptions: { enableSmokeTestDriver: this._environmentService.args['enable-smoke-test-driver'] ? true : undefined, logLevel: this._logService.getLevel() },\n \t\t\tsettingsSyncOptions: !this._environmentService.isBuilt && this._environmentService.args['enable-sync'] ? { enabled: true } : undefined,\nIndex: code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/web.api.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/web.api.ts\n@@ -298,6 +298,11 @@ export interface IWorkbenchConstructionO\n \t */\n \treadonly configurationDefaults?: Record<string, unknown>;\n \n+\t/**\n+\t * Path to the user data directory.\n+\t */\n+\treadonly userDataPath?: string\n+\n \t//#endregion\n \n \t//#region Profile options\nIndex: code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n@@ -102,7 +102,14 @@ export class BrowserWorkbenchEnvironment\n \tget logFile(): URI { return joinPath(this.windowLogsPath, 'window.log'); }\n \n \t@memoize\n-\tget userRoamingDataHome(): URI { return URI.file('/User').with({ scheme: Schemas.vscodeUserData }); }\n+\tget userRoamingDataHome(): URI { return joinPath(URI.file(this.userDataPath).with({ scheme: Schemas.vscodeRemote }), 'User'); }\n+\n+\tget userDataPath(): string {\n+\t\tif (!this.options.userDataPath) {\n+\t\t\tthrow new Error('userDataPath was not provided to the browser');\n+\t\t}\n+\t\treturn this.options.userDataPath;\n+\t}\n \n \t@memoize\n \tget argvResource(): URI { return joinPath(this.userRoamingDataHome, 'argv.json'); }\nIndex: code-server/lib/vscode/src/vs/workbench/services/configuration/browser/configurationService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/configuration/browser/configurationService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/configuration/browser/configurationService.ts\n@@ -148,8 +148,10 @@ export class WorkspaceService extends Di\n \t\tthis.workspaceConfiguration = this._register(new WorkspaceConfiguration(configurationCache, fileService, uriIdentityService, logService));\n \t\tthis._register(this.workspaceConfiguration.onDidUpdateConfiguration(fromCache => {\n \t\t\tthis.onWorkspaceConfigurationChanged(fromCache).then(() => {\n-\t\t\t\tthis.workspace.initialized = this.workspaceConfiguration.initialized;\n-\t\t\t\tthis.checkAndMarkWorkspaceComplete(fromCache);\n+\t\t\t\tif (this.workspace) { // The workspace may not have been created yet.\n+\t\t\t\t\tthis.workspace.initialized = this.workspaceConfiguration.initialized;\n+\t\t\t\t\tthis.checkAndMarkWorkspaceComplete(fromCache);\n+\t\t\t\t}\n \t\t\t});\n \t\t}));\n \n@@ -561,6 +563,12 @@ export class WorkspaceService extends Di\n \t\t\tpreviousFolders = this.workspace.folders;\n \t\t\tthis.workspace.update(workspace);\n \t\t} else {\n+\t\t\t// It is possible for the configuration to become initialized in between\n+\t\t\t// when the workspace was created and this function was called, so check\n+\t\t\t// the configuration again now.\n+\t\t\tif (!workspace.initialized && this.workspaceConfiguration.initialized) {\n+\t\t\t\tworkspace.initialized = true;\n+\t\t\t}\n \t\t\tthis.workspace = workspace;\n \t\t}\n \n"
  },
  {
    "path": "patches/logout.diff",
    "content": "Add a logout command and menu item\n\nThis will only show if you have authentication enabled.\n\nThis has e2e tests but are currently disabled and need to be fixed.\n\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -68,6 +68,7 @@ export interface IProductConfiguration {\n \treadonly codeServerVersion?: string\n \treadonly rootEndpoint?: string\n \treadonly updateEndpoint?: string\n+\treadonly logoutEndpoint?: string\n \n \treadonly version: string;\n \treadonly date?: string;\nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -18,6 +18,7 @@ import { ProtocolConstants } from '../..\n export const serverOptions: OptionDescriptions<Required<ServerParsedArgs>> = {\n \t/* ----- code-server ----- */\n \t'disable-update-check': { type: 'boolean' },\n+\t'auth': { type: 'string' },\n \n \t/* ----- server setup ----- */\n \n@@ -105,6 +106,7 @@ export const serverOptions: OptionDescri\n export interface ServerParsedArgs {\n \t/* ----- code-server ----- */\n \t'disable-update-check'?: boolean;\n+\t'auth'?: string;\n \n \t/* ----- server setup ----- */\n \nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -342,6 +342,7 @@ export class WebClientServer {\n \t\t\tcodeServerVersion: this._productService.codeServerVersion,\n \t\t\trootEndpoint: rootBase,\n \t\t\tupdateEndpoint: !this._environmentService.args['disable-update-check'] ? rootBase + '/update/check' : undefined,\n+\t\t\tlogoutEndpoint: this._environmentService.args['auth'] && this._environmentService.args['auth'] !== \"none\" ? rootBase + '/logout' : undefined,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\nIndex: code-server/lib/vscode/src/vs/workbench/browser/client.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/client.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/client.ts\n@@ -1,11 +1,15 @@\n import { Disposable } from \"../../base/common/lifecycle.js\";\n import { localize } from '../../nls.js';\n+import { MenuId, MenuRegistry } from '../../platform/actions/common/actions.js';\n+import { CommandsRegistry } from '../../platform/commands/common/commands.js';\n import { ILogService } from '../../platform/log/common/log.js';\n import { INotificationService, Severity } from '../../platform/notification/common/notification.js';\n import { IProductService } from '../../platform/product/common/productService.js';\n import { IStorageService, StorageScope, StorageTarget } from '../../platform/storage/common/storage.js';\n \n export class CodeServerClient extends Disposable {\n+\tstatic LOGOUT_COMMAND_ID = 'code-server.logout';\n+\n \tconstructor (\n \t\t@ILogService private logService: ILogService,\n \t\t@INotificationService private notificationService: INotificationService,\n@@ -81,6 +85,10 @@ export class CodeServerClient extends Di\n \t\tif (this.productService.updateEndpoint) {\n \t\t\tthis.checkUpdates(this.productService.updateEndpoint)\n \t\t}\n+\n+\t\tif (this.productService.logoutEndpoint) {\n+\t\t\tthis.addLogoutCommand(this.productService.logoutEndpoint);\n+\t\t}\n \t}\n \n \tprivate checkUpdates(updateEndpoint: string) {\n@@ -132,4 +140,25 @@ export class CodeServerClient extends Di\n \n \t\tupdateLoop();\n \t}\n+\n+\tprivate addLogoutCommand(logoutEndpoint: string) {\n+\t\tCommandsRegistry.registerCommand(CodeServerClient.LOGOUT_COMMAND_ID, () => {\n+\t\t\tconst logoutUrl = new URL(logoutEndpoint, window.location.href);\n+\t\t\t// Cookies must be set with absolute paths and must use the same path to\n+\t\t\t// be unset (we set it on the root) so send the relative root and the\n+\t\t\t// current href so the backend can derive the absolute path to the root.\n+\t\t\tlogoutUrl.searchParams.set('base', this.productService.rootEndpoint || \".\");\n+\t\t\tlogoutUrl.searchParams.set('href', window.location.href);\n+\t\t\twindow.location.assign(logoutUrl);\n+\t\t});\n+\n+\t\tfor (const menuId of [MenuId.CommandPalette, MenuId.MenubarHomeMenu]) {\n+\t\t\tMenuRegistry.appendMenuItem(menuId, {\n+\t\t\t\tcommand: {\n+\t\t\t\t\tid: CodeServerClient.LOGOUT_COMMAND_ID,\n+\t\t\t\t\ttitle: localize('logout', \"Sign out of {0}\", 'code-server'),\n+\t\t\t\t},\n+\t\t\t});\n+\t\t}\n+\t}\n }\n"
  },
  {
    "path": "patches/marketplace.diff",
    "content": "Add Open VSX default and an env var for marketplace, fix old marketplace\n\nOur old marketplace only supports `serviceUrl` but this causes the marketplace\nto be disabled entirely so this moves the template var check to fix that.\n\nThis also removes serverRootPath from the web extension route because that will\ninclude the commit.  When you update code-server (including this update) the web\nextension will continue using the old path since it is stored in the browser but\nthe path will 404 because the commit no longer matches.  This change is only to\nsupport current installations though because this patch also removes the\nin-between and has web extensions install directly from the marketplace.\n\nThis can be tested by setting EXTENSIONS_GALLERY set to:\n\n    '{\"serviceUrl\": \"https://my-extensions/api\"}'\n\n\nIndex: code-server/lib/vscode/src/vs/platform/product/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/product/common/product.ts\n+++ code-server/lib/vscode/src/vs/platform/product/common/product.ts\n@@ -49,6 +49,17 @@ else if (globalThis._VSCODE_PRODUCT_JSON\n \t\t\tversion: pkg.version\n \t\t});\n \t}\n+\n+\tObject.assign(product, {\n+\t\textensionsGallery: env.EXTENSIONS_GALLERY ? JSON.parse(env.EXTENSIONS_GALLERY) : (product.extensionsGallery || {\n+\t\t\tserviceUrl: \"https://open-vsx.org/vscode/gallery\",\n+\t\t\titemUrl: \"https://open-vsx.org/vscode/item\",\n+\t\t\textensionUrlTemplate: \"https://open-vsx.org/vscode/gallery/{publisher}/{name}/latest\",\n+\t\t\tresourceUrlTemplate: \"https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}\",\n+\t\t\tcontrolUrl: \"\",\n+\t\t\trecommendationsUrl: \"\",\n+\t\t})\n+\t});\n }\n \n // Web environment or unknown\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -327,7 +327,6 @@ export class WebClientServer {\n \n \t\tconst staticRoute = posix.join(basePath, this._productPath, STATIC_PATH);\n \t\tconst callbackRoute = posix.join(basePath, this._productPath, CALLBACK_PATH);\n-\t\tconst webExtensionRoute = posix.join(basePath, this._productPath, WEB_EXTENSION_PATH);\n \n \t\tconst resolveWorkspaceURI = (defaultLocation?: string) => defaultLocation && URI.file(resolve(defaultLocation)).with({ scheme: Schemas.vscodeRemote, authority: remoteAuthority });\n \n@@ -343,14 +342,7 @@ export class WebClientServer {\n \t\t\tcodeServerVersion: this._productService.codeServerVersion,\n \t\t\trootEndpoint: rootBase,\n \t\t\tembedderIdentifier: 'server-distro',\n-\t\t\textensionsGallery: this._webExtensionResourceUrlTemplate && this._productService.extensionsGallery ? {\n-\t\t\t\t...this._productService.extensionsGallery,\n-\t\t\t\tresourceUrlTemplate: this._webExtensionResourceUrlTemplate.with({\n-\t\t\t\t\tscheme: 'http',\n-\t\t\t\t\tauthority: remoteAuthority,\n-\t\t\t\t\tpath: `${webExtensionRoute}/${this._webExtensionResourceUrlTemplate.authority}${this._webExtensionResourceUrlTemplate.path}`\n-\t\t\t\t}).toString(true)\n-\t\t\t} : undefined\n+\t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\n \n \t\tconst proposedApi = this._environmentService.args['enable-proposed-api'];\nIndex: code-server/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n+++ code-server/lib/vscode/src/vs/platform/extensionResourceLoader/common/extensionResourceLoader.ts\n@@ -15,7 +15,6 @@ import { getServiceMachineId } from '../\n import { IStorageService } from '../../storage/common/storage.js';\n import { TelemetryLevel } from '../../telemetry/common/telemetry.js';\n import { getTelemetryLevel, supportsTelemetry } from '../../telemetry/common/telemetryUtils.js';\n-import { RemoteAuthorities } from '../../../base/common/network.js';\n import { TargetPlatform } from '../../extensions/common/extensions.js';\n import { ExtensionGalleryResourceType, getExtensionGalleryManifestResourceUri, IExtensionGalleryManifest, IExtensionGalleryManifestService } from '../../extensionManagement/common/extensionGalleryManifest.js';\n import { ILogService } from '../../log/common/log.js';\n@@ -163,9 +162,9 @@ export abstract class AbstractExtensionR\n \t}\n \n \tprotected _isWebExtensionResourceEndPoint(uri: URI): boolean {\n-\t\tconst uriPath = uri.path, serverRootPath = RemoteAuthorities.getServerRootPath();\n-\t\t// test if the path starts with the server root path followed by the web extension resource end point segment\n-\t\treturn uriPath.startsWith(serverRootPath) && uriPath.startsWith(WEB_EXTENSION_RESOURCE_END_POINT_SEGMENT, serverRootPath.length);\n+\t\tconst uriPath = uri.path;\n+\t\t// test if the path starts with the web extension resource end point segment\n+\t\treturn uriPath.startsWith(WEB_EXTENSION_RESOURCE_END_POINT_SEGMENT);\n \t}\n \n }\nIndex: code-server/lib/vscode/src/vs/platform/externalServices/common/marketplace.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/externalServices/common/marketplace.ts\n+++ code-server/lib/vscode/src/vs/platform/externalServices/common/marketplace.ts\n@@ -26,6 +26,10 @@ export async function resolveMarketplace\n \t\t'User-Agent': `VSCode ${version} (${productService.nameShort})`\n \t};\n \n+\tif (productService.extensionsGallery?.authorizationHeaderToken) {\n+\t\theaders['Authorization'] = `Bearer ${productService.extensionsGallery.authorizationHeaderToken}`;\n+\t}\n+\n \tif (supportsTelemetry(productService, environmentService) && getTelemetryLevel(configurationService) === TelemetryLevel.USAGE) {\n \t\tconst serviceMachineId = await getServiceMachineId(environmentService, fileService, storageService);\n \t\theaders['X-Market-User-Id'] = serviceMachineId;\n"
  },
  {
    "path": "patches/proposed-api.diff",
    "content": "Unconditionally enable the proposed API\n\nTo test run an extension that uses the proposed API (i.e.\nhttps://github.com/microsoft/vscode-extension-samples/tree/ddae6c0c9ff203b4ed6f6b43bfacdd0834215f83/proposed-api-sample)\n\nWe also override isProposedApiEnabled in case an extension does not declare the\nAPIs it needs correctly (the Jupyter extension had this issue).\n\nIndex: code-server/lib/vscode/src/vs/workbench/services/extensions/common/extensions.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/extensions/common/extensions.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/extensions/common/extensions.ts\n@@ -321,10 +321,7 @@ function extensionDescriptionArrayToMap(\n }\n \n export function isProposedApiEnabled(extension: IExtensionDescription, proposal: ApiProposalName): boolean {\n-\tif (!extension.enabledApiProposals) {\n-\t\treturn false;\n-\t}\n-\treturn extension.enabledApiProposals.includes(proposal);\n+\treturn true\n }\n \n export function checkProposedApiEnabled(extension: IExtensionDescription, proposal: ApiProposalName): void {\nIndex: code-server/lib/vscode/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/extensions/common/extensionsProposedApi.ts\n@@ -31,7 +31,7 @@ export class ExtensionsProposedApi {\n \n \t\tthis._envEnabledExtensions = new Set((_environmentService.extensionEnabledProposedApi ?? []).map(id => ExtensionIdentifier.toKey(id)));\n \n-\t\tthis._envEnablesProposedApiForAll =\n+\t\tthis._envEnablesProposedApiForAll = true ||\n \t\t\t!_environmentService.isBuilt || // always allow proposed API when running out of sources\n \t\t\t(_environmentService.isExtensionDevelopment && productService.quality !== 'stable') || // do not allow proposed API against stable builds when developing an extension\n \t\t\t(this._envEnabledExtensions.size === 0 && Array.isArray(_environmentService.extensionEnabledProposedApi)); // always allow proposed API if --enable-proposed-api is provided without extension ID\n"
  },
  {
    "path": "patches/proxy-uri.diff",
    "content": "Add VSCODE_PROXY_URI environment variable\n\nThis can be used by extensions to open a port and access it through the proxy.\n\nIt is available in the terminal as well.\n\nThis can be tested using printenv in the terminal and by using the\ncodeServerTest.proxyUri command through the test extension (copy it into your\nextensions, use --extensions-dir, or symlink it).\n\nThis has e2e tests.\n\nFor the `asExternalUri` changes, you'll need to test manually by:\n1. running code-server with the test extension\n2. Command Palette > code-server: asExternalUri test\n3. input a url like http://localhost:3000\n4. it should show a notification and show output as <code-server>/proxy/3000\n\nDo the same thing but set `VSCODE_PROXY_URI: \"https://{{port}}-main-workspace-name-user-name.coder.com\"`\nand the output should replace `{{port}}` with port used in input url.\n\nThis also enables the forwared ports view panel by default.\n\nLastly, it adds a tunnelProvider so that ports are forwarded using code-server's\nbuilt-in proxy. You can test this by starting a server i.e. `python3 -m\nhttp.server` and it should show a notification and show up in the ports panel\nusing the /proxy/port.\n\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -69,6 +69,7 @@ export interface IProductConfiguration {\n \treadonly rootEndpoint?: string\n \treadonly updateEndpoint?: string\n \treadonly logoutEndpoint?: string\n+\treadonly proxyEndpointTemplate?: string\n \n \treadonly version: string;\n \treadonly date?: string;\nIndex: code-server/lib/vscode/src/vs/platform/remote/browser/remoteAuthorityResolverService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/remote/browser/remoteAuthorityResolverService.ts\n+++ code-server/lib/vscode/src/vs/platform/remote/browser/remoteAuthorityResolverService.ts\n@@ -35,7 +35,7 @@ export class RemoteAuthorityResolverServ\n \t\tconnectionToken: Promise<string> | string | undefined,\n \t\tresourceUriProvider: ((uri: URI) => URI) | undefined,\n \t\tserverBasePath: string | undefined,\n-\t\t@IProductService productService: IProductService,\n+\t\t@IProductService private readonly productService: IProductService,\n \t\t@ILogService private readonly _logService: ILogService,\n \t) {\n \t\tsuper();\n@@ -86,9 +86,14 @@ export class RemoteAuthorityResolverServ\n \t\tconst connectionToken = await Promise.resolve(this._connectionTokens.get(authority) || this._connectionToken);\n \t\tperformance.mark(`code/didResolveConnectionToken/${authorityPrefix}`);\n \t\tthis._logService.info(`Resolved connection token (${authorityPrefix}) after ${sw.elapsed()} ms`);\n+\t\tlet options: ResolvedOptions | undefined;\n+\t\tif (this.productService.proxyEndpointTemplate) {\n+\t\t\tconst proxyUrl = new URL(this.productService.proxyEndpointTemplate, mainWindow.location.href);\n+\t\t\toptions = { extensionHostEnv: { VSCODE_PROXY_URI: decodeURIComponent(proxyUrl.toString()) }}\n+\t\t}\n \t\tconst defaultPort = (/^https:/.test(mainWindow.location.href) ? 443 : 80);\n \t\tconst { host, port } = parseAuthorityWithOptionalPort(authority, defaultPort);\n-\t\tconst result: ResolverResult = { authority: { authority, connectTo: new WebSocketRemoteConnection(host, port), connectionToken } };\n+\t\tconst result: ResolverResult = { authority: { authority, connectTo: new WebSocketRemoteConnection(host, port), connectionToken }, options };\n \t\tRemoteAuthorities.set(authority, host, port);\n \t\tthis._cache.set(authority, result);\n \t\tthis._onDidChangeConnectionData.fire();\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -343,6 +343,7 @@ export class WebClientServer {\n \t\t\trootEndpoint: rootBase,\n \t\t\tupdateEndpoint: !this._environmentService.args['disable-update-check'] ? rootBase + '/update/check' : undefined,\n \t\t\tlogoutEndpoint: this._environmentService.args['auth'] && this._environmentService.args['auth'] !== \"none\" ? rootBase + '/logout' : undefined,\n+\t\t\tproxyEndpointTemplate: process.env.VSCODE_PROXY_URI ?? rootBase + '/proxy/{{port}}/',\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/terminal/common/terminalEnvironment.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/terminal/common/terminalEnvironment.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/terminal/common/terminalEnvironment.ts\n@@ -292,7 +292,7 @@ export async function createTerminalEnvi\n \n \t\t// Sanitize the environment, removing any undesirable VS Code and Electron environment\n \t\t// variables\n-\t\tsanitizeProcessEnvironment(env, 'VSCODE_IPC_HOOK_CLI');\n+\t\tsanitizeProcessEnvironment(env, 'VSCODE_IPC_HOOK_CLI', 'VSCODE_PROXY_URI');\n \n \t\t// Merge config (settings) and ShellLaunchConfig environments\n \t\tmergeEnvironments(env, allowedEnvFromConfig);\nIndex: code-server/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n+++ code-server/lib/vscode/src/vs/code/browser/workbench/workbench.ts\n@@ -20,6 +20,7 @@ import { ISecretStorageProvider } from '\n import { isFolderToOpen, isWorkspaceToOpen } from '../../../platform/window/common/window.js';\n import type { IWorkbenchConstructionOptions, IWorkspace, IWorkspaceProvider } from '../../../workbench/browser/web.api.js';\n import { AuthenticationSessionInfo } from '../../../workbench/services/authentication/browser/authenticationService.js';\n+import { extractLocalHostUriMetaDataForPortMapping, TunnelOptions, TunnelCreationOptions } from '../../../platform/tunnel/common/tunnel.js';\n import type { IURLCallbackProvider } from '../../../workbench/services/url/browser/urlService.js';\n import { create } from '../../../workbench/workbench.web.main.internal.js';\n \n@@ -606,6 +607,39 @@ class WorkspaceProvider implements IWork\n \t\tsettingsSyncOptions: config.settingsSyncOptions ? { enabled: config.settingsSyncOptions.enabled, } : undefined,\n \t\tworkspaceProvider: WorkspaceProvider.create(config),\n \t\turlCallbackProvider: new LocalStorageURLCallbackProvider(config.callbackRoute),\n+\t\tresolveExternalUri: (uri: URI): Promise<URI> => {\n+\t\t\tlet resolvedUri = uri\n+\t\t\tconst localhostMatch = extractLocalHostUriMetaDataForPortMapping(resolvedUri)\n+\t\t\tif (localhostMatch && resolvedUri.authority !== location.host) {\n+\t\t\t\tif (config.productConfiguration && config.productConfiguration.proxyEndpointTemplate) {\n+\t\t\t\t\tconst renderedTemplate = config.productConfiguration.proxyEndpointTemplate\n+\t\t\t\t\t\t.replace('{{port}}', localhostMatch.port.toString())\n+\t\t\t\t\t\t.replace('{{host}}', window.location.host)\n+\t\t\t\t\tresolvedUri = URI.parse(new URL(renderedTemplate, window.location.href).toString())\n+\t\t\t\t} else {\n+\t\t\t\t\tthrow new Error(`Failed to resolve external URI: ${uri.toString()}. Could not determine base url because productConfiguration missing.`)\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\t// If not localhost, return unmodified.\n+\t\t\treturn Promise.resolve(resolvedUri)\n+\t\t},\n+\t\ttunnelProvider: {\n+\t\t\ttunnelFactory: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => {\n+\t\t\t\tconst onDidDispose: Emitter<void> = new Emitter();\n+\t\t\t\tlet isDisposed = false;\n+\t\t\t\treturn Promise.resolve({\n+\t\t\t\t\tremoteAddress: tunnelOptions.remoteAddress,\n+\t\t\t\t\tlocalAddress: `localhost:${tunnelOptions.remoteAddress.port}`,\n+\t\t\t\t\tonDidDispose: onDidDispose.event,\n+\t\t\t\t\tdispose: () => {\n+\t\t\t\t\t\tif (!isDisposed) {\n+\t\t\t\t\t\t\tisDisposed = true;\n+\t\t\t\t\t\t\tonDidDispose.fire();\n+\t\t\t\t\t\t}\n+\t\t\t\t\t}\n+\t\t\t\t})\n+\t\t\t}\n+\t\t},\n \t\tsecretStorageProvider: config.remoteAuthority && !secretStorageKeyPath\n \t\t\t? undefined /* with a remote without embedder-preferred storage, store on the remote */\n \t\t\t: new LocalStorageSecretStorageProvider(secretStorageCrypto),\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/remote/browser/remoteExplorer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/remote/browser/remoteExplorer.ts\n+++ code-server/lib/vscode/src/vs/workbench/contrib/remote/browser/remoteExplorer.ts\n@@ -83,8 +83,8 @@ export class ForwardedPortsView extends\n \tprivate async enableForwardedPortsFeatures() {\n \t\tthis.contextKeyListener.clear();\n \n-\t\tconst featuresEnabled: boolean = !!forwardedPortsFeaturesEnabled.getValue(this.contextKeyService);\n-\t\tconst viewEnabled: boolean = !!forwardedPortsViewEnabled.getValue(this.contextKeyService);\n+\t\tconst featuresEnabled: boolean = true;\n+\t\tconst viewEnabled: boolean = true;\n \n \t\tif (featuresEnabled || viewEnabled) {\n \t\t\t// Also enable the view if it isn't already.\n"
  },
  {
    "path": "patches/series",
    "content": "integration.diff\nbase-path.diff\nproposed-api.diff\nmarketplace.diff\nwebview.diff\ndisable-builtin-ext-update.diff\ninsecure-notification.diff\nupdate-check.diff\nlogout.diff\nstore-socket.diff\nproxy-uri.diff\nunique-db.diff\nlocal-storage.diff\nservice-worker.diff\nsourcemaps.diff\nexternal-file-actions.diff\ntelemetry.diff\ncli-window-open.diff\ngetting-started.diff\nkeepalive.diff\nclipboard.diff\ndisplay-language.diff\ntrusted-domains.diff\nsignature-verification.diff\nfix-build.diff\n"
  },
  {
    "path": "patches/service-worker.diff",
    "content": "Add a service worker\n\nTo test try installing code-server as a PWA.\n\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -70,6 +70,10 @@ export interface IProductConfiguration {\n \treadonly updateEndpoint?: string\n \treadonly logoutEndpoint?: string\n \treadonly proxyEndpointTemplate?: string\n+\treadonly serviceWorker?: {\n+\t\treadonly path: string;\n+\t\treadonly scope: string;\n+\t}\n \n \treadonly version: string;\n \treadonly date?: string;\nIndex: code-server/lib/vscode/src/vs/workbench/browser/client.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/client.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/client.ts\n@@ -89,6 +89,10 @@ export class CodeServerClient extends Di\n \t\tif (this.productService.logoutEndpoint) {\n \t\t\tthis.addLogoutCommand(this.productService.logoutEndpoint);\n \t\t}\n+\n+\t\tif (this.productService.serviceWorker) {\n+\t\t\tawait this.registerServiceWorker(this.productService.serviceWorker);\n+\t\t}\n \t}\n \n \tprivate checkUpdates(updateEndpoint: string) {\n@@ -161,4 +165,17 @@ export class CodeServerClient extends Di\n \t\t\t});\n \t\t}\n \t}\n+\n+\tprivate async registerServiceWorker(serviceWorker: { path: string; scope: string }) {\n+\t\tif (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {\n+\t\t\ttry {\n+\t\t\t\tawait navigator.serviceWorker.register(serviceWorker.path, {\n+\t\t\t\t\tscope: serviceWorker.scope,\n+\t\t\t\t});\n+\t\t\t\tthis.logService.info('[Service Worker] registered');\n+\t\t\t} catch (error: any) {\n+\t\t\t\tthis.logService.error('[Service Worker] registration', error as Error);\n+\t\t\t}\n+\t\t}\n+\t}\n }\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -344,6 +344,10 @@ export class WebClientServer {\n \t\t\tupdateEndpoint: !this._environmentService.args['disable-update-check'] ? rootBase + '/update/check' : undefined,\n \t\t\tlogoutEndpoint: this._environmentService.args['auth'] && this._environmentService.args['auth'] !== \"none\" ? rootBase + '/logout' : undefined,\n \t\t\tproxyEndpointTemplate: process.env.VSCODE_PROXY_URI ?? rootBase + '/proxy/{{port}}/',\n+\t\t\tserviceWorker: {\n+\t\t\t\tscope: vscodeBase + '/',\n+\t\t\t\tpath: rootBase + '/_static/out/browser/serviceWorker.js',\n+\t\t\t},\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\n"
  },
  {
    "path": "patches/signature-verification.diff",
    "content": "Disable signature verification.\n\nExtension signature verification is now mandatory for all platforms and needs to be disabled.\n\nIndex: code-server/lib/vscode/src/vs/platform/extensionManagement/node/extensionManagementService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/extensionManagement/node/extensionManagementService.ts\n+++ code-server/lib/vscode/src/vs/platform/extensionManagement/node/extensionManagementService.ts\n@@ -34,6 +34,7 @@ import {\n \tExtensionSignatureVerificationCode,\n \tcomputeSize,\n \tIAllowedExtensionsService,\n+\t// @ts-expect-error no-unused-variable\n \tVerifyExtensionSignatureConfigKey,\n \tshouldRequireRepositorySignatureFor,\n } from '../common/extensionManagement.js';\n@@ -87,6 +88,7 @@ export class ExtensionManagementService\n \t\t@IDownloadService private downloadService: IDownloadService,\n \t\t@IInstantiationService private readonly instantiationService: IInstantiationService,\n \t\t@IFileService private readonly fileService: IFileService,\n+\t\t// @ts-expect-error no-unused-variable\n \t\t@IConfigurationService private readonly configurationService: IConfigurationService,\n \t\t@IExtensionGalleryManifestService protected readonly extensionGalleryManifestService: IExtensionGalleryManifestService,\n \t\t@IProductService productService: IProductService,\n@@ -339,8 +341,7 @@ export class ExtensionManagementService\n \n \tprivate async downloadExtension(extension: IGalleryExtension, operation: InstallOperation, verifySignature: boolean, clientTargetPlatform?: TargetPlatform): Promise<{ readonly location: URI; readonly verificationStatus: ExtensionSignatureVerificationCode | undefined }> {\n \t\tif (verifySignature) {\n-\t\t\tconst value = this.configurationService.getValue(VerifyExtensionSignatureConfigKey);\n-\t\t\tverifySignature = isBoolean(value) ? value : true;\n+\t\t\tverifySignature = false;\n \t\t}\n \t\tconst { location, verificationStatus } = await this.extensionsDownloader.download(extension, operation, verifySignature, clientTargetPlatform);\n \t\tconst shouldRequireSignature = shouldRequireRepositorySignatureFor(extension.private, await this.extensionGalleryManifestService.getExtensionGalleryManifest());\n"
  },
  {
    "path": "patches/sourcemaps.diff",
    "content": "Make sourcemaps self-hosted\n\nNormally source maps get removed as part of the build process so prevent that\nfrom happening.  Also avoid using the windows.net host since obviously we can\nnot host our source maps there and want them to be self-hosted even if we could.\n\nTo test try debugging/browsing the source of a build in a browser.\n\nIndex: code-server/lib/vscode/build/gulpfile.reh.ts\n===================================================================\n--- code-server.orig/lib/vscode/build/gulpfile.reh.ts\n+++ code-server/lib/vscode/build/gulpfile.reh.ts\n@@ -262,8 +262,7 @@ function packageTask(type: string, platf\n \treturn () => {\n \t\tconst src = gulp.src(sourceFolderName + '/**', { base: '.' })\n \t\t\t.pipe(rename(function (path) { path.dirname = path.dirname!.replace(new RegExp('^' + sourceFolderName), 'out'); }))\n-\t\t\t.pipe(util.setExecutableBit(['**/*.sh']))\n-\t\t\t.pipe(filter(['**', '!**/*.{js,css}.map']));\n+\t\t\t.pipe(util.setExecutableBit(['**/*.sh']));\n \n \t\tconst workspaceExtensionPoints = ['debuggers', 'jsonValidation'];\n \t\tconst isUIExtension = (manifest: { extensionKind?: string; main?: string; contributes?: Record<string, unknown> }) => {\n@@ -303,9 +302,9 @@ function packageTask(type: string, platf\n \t\t\t.map(name => `.build/extensions/${name}/**`);\n \n \t\tconst extensions = gulp.src(extensionPaths, { base: '.build', dot: true });\n-\t\tconst extensionsCommonDependencies = gulp.src('.build/extensions/node_modules/**', { base: '.build', dot: true });\n-\t\tconst sources = es.merge(src, extensions, extensionsCommonDependencies)\n+\t\tconst extensionsCommonDependencies = gulp.src('.build/extensions/node_modules/**', { base: '.build', dot: true })\n \t\t\t.pipe(filter(['**', '!**/*.{js,css}.map'], { dot: true }));\n+\t\tconst sources = es.merge(src, extensions, extensionsCommonDependencies);\n \n \t\tlet version = packageJson.version;\n \t\tconst quality = (product as typeof product & { quality?: string }).quality;\n@@ -492,7 +491,7 @@ function tweakProductForServerWeb(produc\n \tconst minifyTask = task.define(`minify-vscode-${type}`, task.series(\n \t\tbundleTask,\n \t\tutil.rimraf(`out-vscode-${type}-min`),\n-\t\toptimize.minifyTask(`out-vscode-${type}`, `https://main.vscode-cdn.net/sourcemaps/${commit}/core`)\n+\t\toptimize.minifyTask(`out-vscode-${type}`, ``)\n \t));\n \tgulp.task(minifyTask);\n \n"
  },
  {
    "path": "patches/store-socket.diff",
    "content": "Store the IPC socket with workspace metadata.\n\nThis lets us use it to open files inside code-server from outside of\ncode-server.\n\nTo test this:\n1. run code-server\n2. open file outside of code-server i.e. `code-server <path-to-file`\n\nIt should open in your existing code-server instance.\n\nWhen the extension host is terminated, the socket is unregistered.\n\nIndex: code-server/lib/vscode/src/vs/workbench/api/node/extHostExtensionService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/api/node/extHostExtensionService.ts\n+++ code-server/lib/vscode/src/vs/workbench/api/node/extHostExtensionService.ts\n@@ -3,6 +3,7 @@\n  *  Licensed under the MIT License. See License.txt in the project root for license information.\n  *--------------------------------------------------------------------------------------------*/\n \n+import * as _http from 'http';\n import * as performance from '../../../base/common/performance.js';\n import type * as vscode from 'vscode';\n import { createApiFactoryAndRegisterActors } from '../common/extHost.api.impl.js';\n@@ -18,6 +19,7 @@ import { ExtensionRuntime } from '../com\n import { CLIServer } from './extHostCLIServer.js';\n import { realpathSync } from '../../../base/node/pfs.js';\n import { ExtHostConsoleForwarder } from './extHostConsoleForwarder.js';\n+import { IExtHostWorkspace } from '../common/extHostWorkspace.js';\n import { ExtHostDiskFileSystemProvider } from './extHostDiskFileSystemProvider.js';\n import nodeModule from 'node:module';\n import { assertType } from '../../../base/common/types.js';\n@@ -226,6 +228,52 @@ export class ExtHostExtensionService ext\n \n \t\tperformance.mark('code/extHost/didInitAPI');\n \n+\t\t(async () => {\n+\t\t\tconst socketPath = process.env['VSCODE_IPC_HOOK_CLI'];\n+\t\t\tconst codeServerSocketPath = process.env['CODE_SERVER_SESSION_SOCKET']\n+\t\t\tif (!socketPath || !codeServerSocketPath) {\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tconst workspace = this._instaService.invokeFunction((accessor) => {\n+\t\t\t\tconst workspaceService = accessor.get(IExtHostWorkspace);\n+\t\t\t\treturn workspaceService.workspace;\n+\t\t\t});\n+\t\t\tconst entry = {\n+\t\t\t\tworkspace,\n+\t\t\t\tsocketPath\n+\t\t\t};\n+\t\t\tconst message = JSON.stringify({entry});\n+\t\t\tawait new Promise<void>((resolve, reject) => {\n+\t\t\t\tconst opts: _http.RequestOptions = {\n+\t\t\t\t\tpath: '/add-session',\n+\t\t\t\t\tsocketPath: codeServerSocketPath,\n+\t\t\t\t\tmethod: 'POST',\n+\t\t\t\t\theaders: {\n+\t\t\t\t\t\t'content-type': 'application/json',\n+\t\t\t\t\t}\n+\t\t\t\t};\n+\t\t\t\tconst req = _http.request(opts, (res) => {\n+\t\t\t\t\tres.on('error', reject);\n+\t\t\t\t\tres.on('end', () => {\n+\t\t\t\t\t\ttry {\n+\t\t\t\t\t\t\tif (res.statusCode === 200) {\n+\t\t\t\t\t\t\t\tresolve();\n+\t\t\t\t\t\t\t} else {\n+\t\t\t\t\t\t\t\treject(new Error('Unexpected status code: ' + res.statusCode));\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t} catch (e: unknown) {\n+\t\t\t\t\t\t\treject(e);\n+\t\t\t\t\t\t}\n+\t\t\t\t\t});\n+\t\t\t\t});\n+\t\t\t\treq.on('error', reject);\n+\t\t\t\treq.write(message);\n+\t\t\t\treq.end();\n+\t\t\t});\n+\t\t})().catch(error => {\n+\t\t\tthis._logService.error(error);\n+\t\t});\n+\n \t\t// Do this when extension service exists, but extensions are not being activated yet.\n \t\tconst configProvider = await this._extHostConfiguration.getConfigProvider();\n \t\tawait connectProxyResolver(this._extHostWorkspace, configProvider, this, this._logService, this._mainThreadTelemetryProxy, this._initData, this._store);\nIndex: code-server/lib/vscode/src/vs/workbench/api/node/extensionHostProcess.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/api/node/extensionHostProcess.ts\n+++ code-server/lib/vscode/src/vs/workbench/api/node/extensionHostProcess.ts\n@@ -3,6 +3,7 @@\n  *  Licensed under the MIT License. See License.txt in the project root for license information.\n  *--------------------------------------------------------------------------------------------*/\n \n+import * as _http from 'http';\n import minimist from 'minimist';\n import * as nativeWatchdog from '@vscode/native-watchdog';\n import * as net from 'net';\n@@ -469,7 +470,28 @@ async function startExtensionHostProcess\n \t);\n \n \t// rewrite onTerminate-function to be a proper shutdown\n-\tonTerminate = (reason: string) => extensionHostMain.terminate(reason);\n+\tonTerminate = (reason: string) => {\n+\t\textensionHostMain.terminate(reason);\n+\n+\t\tconst socketPath = process.env['VSCODE_IPC_HOOK_CLI'];\n+\t\tconst codeServerSocketPath = process.env['CODE_SERVER_SESSION_SOCKET']\n+\t\tif (!socketPath || !codeServerSocketPath) {\n+\t\t\treturn;\n+\t\t}\n+\t\tconst message = JSON.stringify({socketPath});\n+\t\tconst opts: _http.RequestOptions = {\n+\t\t\tpath: '/delete-session',\n+\t\t\tsocketPath: codeServerSocketPath,\n+\t\t\tmethod: 'POST',\n+\t\t\theaders: {\n+\t\t\t\t'content-type': 'application/json',\n+\t\t\t\t'accept': 'application/json'\n+\t\t\t}\n+\t\t};\n+\t\tconst req = _http.request(opts);\n+\t\treq.write(message);\n+\t\treq.end();\n+\t};\n }\n \n startExtensionHostProcess().catch((err) => console.log(err));\n"
  },
  {
    "path": "patches/telemetry.diff",
    "content": "Add support for telemetry endpoint\n\nTo test:\n1. Create a mock API using [RequestBin](https://requestbin.io/) or [Beeceptor](https://beeceptor.com/)\n2. Run code-server with `CS_TELEMETRY_URL` set: \n  i.e. `CS_TELEMETRY_URL=\"https://requestbin.io/1ebub9z1\" ./code-server-<version>-macos-amd64/bin/code-server`\n  NOTE: it has to be a production build.\n3. Load code-server in browser an do things (i.e. open a file)\n4. Refresh RequestBin and you should see logs\n\nIndex: code-server/lib/vscode/src/vs/server/node/serverServices.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverServices.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverServices.ts\n@@ -4,6 +4,7 @@\n  *--------------------------------------------------------------------------------------------*/\n \n import { hostname, release } from 'os';\n+import { promises as fs } from 'fs';\n import { Emitter, Event } from '../../base/common/event.js';\n import { DisposableStore, toDisposable } from '../../base/common/lifecycle.js';\n import { Schemas } from '../../base/common/network.js';\n@@ -65,6 +66,7 @@ import { IExtensionsScannerService } fro\n import { ExtensionsScannerService } from './extensionsScannerService.js';\n import { IExtensionsProfileScannerService } from '../../platform/extensionManagement/common/extensionsProfileScannerService.js';\n import { IUserDataProfilesService } from '../../platform/userDataProfile/common/userDataProfile.js';\n+import { TelemetryClient } from './telemetryClient.js';\n import { NullPolicyService } from '../../platform/policy/common/policy.js';\n import { OneDataSystemAppender } from '../../platform/telemetry/node/1dsAppender.js';\n import { LoggerService } from '../../platform/log/node/loggerService.js';\n@@ -169,11 +171,23 @@ export async function setupServerService\n \tconst requestService = new RequestService('remote', configurationService, environmentService, logService);\n \tservices.set(IRequestService, requestService);\n \n+\tlet isContainer = undefined;\n+\ttry {\n+\t\tawait fs.stat('/run/.containerenv');\n+\t\tisContainer = true;\n+\t} catch (error) { /* Does not exist, probably. */ }\n+\tif (!isContainer) {\n+\t\ttry {\n+\t\t\tconst content = await fs.readFile('/proc/self/cgroup', 'utf8')\n+\t\t\tisContainer = content.includes('docker');\n+\t\t} catch (error) { /* Permission denied, probably. */ }\n+\t}\n+\n \tlet oneDsAppender: ITelemetryAppender = NullAppender;\n \tconst isInternal = isInternalTelemetry(productService, configurationService);\n \tif (supportsTelemetry(productService, environmentService)) {\n-\t\tif (!isLoggingOnly(productService, environmentService) && productService.aiConfig?.ariaKey) {\n-\t\t\toneDsAppender = new OneDataSystemAppender(requestService, isInternal, eventPrefix, null, productService.aiConfig.ariaKey);\n+\t\tif (!isLoggingOnly(productService, environmentService) && productService.telemetryEndpoint) {\n+\t\t\toneDsAppender = new OneDataSystemAppender(requestService, isInternal, eventPrefix, null, () => new TelemetryClient(productService.telemetryEndpoint!, machineId, isContainer));\n \t\t\tdisposables.add(toDisposable(() => oneDsAppender?.flush())); // Ensure the AI appender is disposed so that it flushes remaining data\n \t\t}\n \nIndex: code-server/lib/vscode/src/vs/server/node/telemetryClient.ts\n===================================================================\n--- /dev/null\n+++ code-server/lib/vscode/src/vs/server/node/telemetryClient.ts\n@@ -0,0 +1,71 @@\n+import { AppInsightsCore, IExtendedTelemetryItem, ITelemetryItem } from '@microsoft/1ds-core-js';\n+import * as https from 'https';\n+import * as http from 'http';\n+import * as os from 'os';\n+\n+interface SystemInfo {\n+\tmeasurements: Record<string, number | undefined>;\n+\tproperties: Record<string, string | boolean | null | undefined>;\n+}\n+\n+export class TelemetryClient extends AppInsightsCore {\n+\tprivate readonly systemInfo: SystemInfo = {\n+\t\tmeasurements: {},\n+\t\tproperties: {},\n+\t};\n+\n+\tpublic constructor(\n+\t\tprivate readonly endpoint: string,\n+\t\tmachineId: string,\n+\t\tisContainer: boolean | undefined) {\n+\t\tsuper();\n+\n+\t\t// os.cpus() can take a very long time sometimes (personally I see 1-2\n+\t\t// seconds in a Coder workspace).  This adds up significantly, especially\n+\t\t// when many telemetry requests are sent during startup, which can cause\n+\t\t// connection timeouts.  Try to cache as much as we can.\n+\t\ttry {\n+\t\t\tconst cpus = os.cpus();\n+\t\t\tthis.systemInfo.measurements.cores = cpus.length;\n+\t\t\tthis.systemInfo.properties['common.cpuModel'] = cpus[0].model;\n+\t\t} catch (error) {}\n+\n+\t\ttry {\n+\t\t\tthis.systemInfo.properties['common.shell'] = os.userInfo().shell;\n+\t\t\tthis.systemInfo.properties['common.release'] = os.release();\n+\t\t\tthis.systemInfo.properties['common.arch'] = os.arch();\n+\t\t} catch (error) {}\n+\n+\t\tthis.systemInfo.properties['common.remoteMachineId'] = machineId;\n+\t\tthis.systemInfo.properties['common.isContainer'] = isContainer;\n+\t}\n+\n+\tpublic override track(item: IExtendedTelemetryItem | ITelemetryItem): void {\n+\t\tconst options = item.baseData || {}\n+\t\toptions.measurements = {\n+\t\t\t...(options.measurements || {}),\n+\t\t\t...this.systemInfo.measurements,\n+\t\t}\n+\t\toptions.properties = {\n+\t\t\t...(options.properties || {}),\n+\t\t\t...this.systemInfo.properties,\n+\t\t}\n+\n+\t\ttry {\n+\t\t\toptions.measurements.memoryFree = os.freemem();\n+\t\t\toptions.measurements.memoryTotal = os.totalmem();\n+\t\t} catch (error) {}\n+\n+\t\ttry {\n+\t\t\tconst request = (/^http:/.test(this.endpoint) ? http : https).request(this.endpoint, {\n+\t\t\t\tmethod: 'POST',\n+\t\t\t\theaders: {\n+\t\t\t\t\t'Content-Type': 'application/json',\n+\t\t\t\t},\n+\t\t\t});\n+\t\t\trequest.on('error', () => { /* We don't care. */ });\n+\t\t\trequest.write(JSON.stringify(options));\n+\t\t\trequest.end();\n+\t\t} catch (error) {}\n+\t}\n+}\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -348,6 +348,8 @@ export class WebClientServer {\n \t\t\t\tscope: vscodeBase + '/',\n \t\t\t\tpath: rootBase + '/_static/out/browser/serviceWorker.js',\n \t\t\t},\n+\t\t\tenableTelemetry: this._productService.enableTelemetry,\n+\t\t\ttelemetryEndpoint: this._productService.telemetryEndpoint,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -74,6 +74,7 @@ export interface IProductConfiguration {\n \t\treadonly path: string;\n \t\treadonly scope: string;\n \t}\n+\treadonly telemetryEndpoint?: string\n \n \treadonly version: string;\n \treadonly date?: string;\nIndex: code-server/lib/vscode/src/vs/platform/product/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/platform/product/common/product.ts\n+++ code-server/lib/vscode/src/vs/platform/product/common/product.ts\n@@ -58,7 +58,8 @@ else if (globalThis._VSCODE_PRODUCT_JSON\n \t\t\tresourceUrlTemplate: \"https://open-vsx.org/vscode/asset/{publisher}/{name}/{version}/Microsoft.VisualStudio.Code.WebResources/{path}\",\n \t\t\tcontrolUrl: \"\",\n \t\t\trecommendationsUrl: \"\",\n-\t\t})\n+\t\t}),\n+\t\ttelemetryEndpoint: env.CS_TELEMETRY_URL || product.telemetryEndpoint || \"https://v1.telemetry.coder.com/track\",\n \t});\n }\n \n"
  },
  {
    "path": "patches/trusted-domains.diff",
    "content": "Allow configuring trusted domains via product.json or flag.\n\nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -23,6 +23,7 @@ export const serverOptions: OptionDescri\n \t'disable-file-uploads': { type: 'boolean' },\n \t'disable-getting-started-override': { type: 'boolean' },\n \t'locale': { type: 'string' },\n+\t'link-protection-trusted-domains': { type: 'string[]' },\n \n \t/* ----- server setup ----- */\n \n@@ -115,6 +116,7 @@ export interface ServerParsedArgs {\n \t'disable-file-uploads'?: boolean;\n \t'disable-getting-started-override'?: boolean,\n \t'locale'?: string\n+\t'link-protection-trusted-domains'?: string[],\n \n \t/* ----- server setup ----- */\n \nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -339,6 +339,14 @@ export class WebClientServer {\n \t\t\tscopes: [['user:email'], ['repo']]\n \t\t} : undefined;\n \n+\t\tconst linkProtectionTrustedDomains: string[] = [];\n+\t\tif (this._environmentService.args['link-protection-trusted-domains']) {\n+\t\t\tlinkProtectionTrustedDomains.push(...this._environmentService.args['link-protection-trusted-domains']);\n+\t\t}\n+\t\tif (this._productService.linkProtectionTrustedDomains) {\n+\t\t\tlinkProtectionTrustedDomains.push(...this._productService.linkProtectionTrustedDomains);\n+\t\t}\n+\n \t\tconst productConfiguration: Partial<Mutable<IProductConfiguration>> = {\n \t\t\tcodeServerVersion: this._productService.codeServerVersion,\n \t\t\trootEndpoint: rootBase,\n@@ -353,6 +361,7 @@ export class WebClientServer {\n \t\t\ttelemetryEndpoint: this._productService.telemetryEndpoint,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n+\t\t\tlinkProtectionTrustedDomains,\n \t\t};\n \n \t\tconst proposedApi = this._environmentService.args['enable-proposed-api'];\n"
  },
  {
    "path": "patches/unique-db.diff",
    "content": "Prevent state collisions\n\nPreviously if you opened different workspaces that had the same filesystem path\n(for example if you have /home/coder on two different machines that are both\naccessed through the same host) they would conflict with each other.  This\nensures that different browser paths will be unique (for example /workspace1 and\n/workspace2).\n\nThe easiest way to test is to open files in the same workspace using both / and\n/vscode and make sure they are not interacting with each other.\n\nIndex: code-server/lib/vscode/src/vs/workbench/services/storage/browser/storageService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/storage/browser/storageService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/storage/browser/storageService.ts\n@@ -18,6 +18,7 @@ import { AbstractStorageService, isProfi\n import { isUserDataProfile, IUserDataProfile } from '../../../../platform/userDataProfile/common/userDataProfile.js';\n import { IAnyWorkspaceIdentifier } from '../../../../platform/workspace/common/workspace.js';\n import { IUserDataProfileService } from '../../userDataProfile/common/userDataProfile.js';\n+import { hash } from '../../../../base/common/hash.js';\n \n export class BrowserStorageService extends AbstractStorageService {\n \n@@ -300,7 +301,11 @@ export class IndexedDBStorageDatabase ex\n \t}\n \n \tstatic async createWorkspaceStorage(workspaceId: string, logService: ILogService): Promise<IIndexedDBStorageDatabase> {\n-\t\treturn IndexedDBStorageDatabase.create({ id: workspaceId }, logService);\n+\t\t// Add a unique ID based on the current path for per-workspace databases.\n+\t\t// This prevents workspaces on different machines that share the same domain\n+\t\t// and file path from colliding (since it does not appear IndexedDB can be\n+\t\t// scoped to a path) as long as they are hosted on different paths.\n+\t\treturn IndexedDBStorageDatabase.create({ id: workspaceId + '-' + hash(location.pathname.toString().replace(/\\/$/, \"\")).toString(16) }, logService);\n \t}\n \n \tstatic async create(options: IndexedDBStorageDatabaseOptions, logService: ILogService): Promise<IIndexedDBStorageDatabase> {\n"
  },
  {
    "path": "patches/update-check.diff",
    "content": "Add a notification that lets you know when an update is out\n\nThe easiest way to test this is probably to change the version in your\npackage.json and delete the last notification storage item.\n\n1. change version in root `package.json`\n2. Open DevTools > Application > Storage (top-level)\n3. Click \"Clear site data\"\n4. See update notification\n\nIndex: code-server/lib/vscode/src/vs/workbench/browser/client.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/browser/client.ts\n+++ code-server/lib/vscode/src/vs/workbench/browser/client.ts\n@@ -1,10 +1,16 @@\n import { Disposable } from \"../../base/common/lifecycle.js\";\n import { localize } from '../../nls.js';\n+import { ILogService } from '../../platform/log/common/log.js';\n import { INotificationService, Severity } from '../../platform/notification/common/notification.js';\n+import { IProductService } from '../../platform/product/common/productService.js';\n+import { IStorageService, StorageScope, StorageTarget } from '../../platform/storage/common/storage.js';\n \n export class CodeServerClient extends Disposable {\n \tconstructor (\n+\t\t@ILogService private logService: ILogService,\n \t\t@INotificationService private notificationService: INotificationService,\n+\t\t@IProductService private productService: IProductService,\n+\t\t@IStorageService private storageService: IStorageService,\n \t) {\n \t\tsuper();\n \t}\n@@ -71,5 +77,59 @@ export class CodeServerClient extends Di\n \t\t\t\t},\n \t\t\t});\n \t\t}\n+\n+\t\tif (this.productService.updateEndpoint) {\n+\t\t\tthis.checkUpdates(this.productService.updateEndpoint)\n+\t\t}\n+\t}\n+\n+\tprivate checkUpdates(updateEndpoint: string) {\n+\t\tconst getUpdate = async (updateCheckEndpoint: string): Promise<void> => {\n+\t\t\tthis.logService.debug('Checking for update...');\n+\n+\t\t\tconst response = await fetch(updateCheckEndpoint, {\n+\t\t\t\theaders: { Accept: 'application/json' },\n+\t\t\t});\n+\t\t\tif (!response.ok) {\n+\t\t\t\tthrow new Error(response.statusText);\n+\t\t\t}\n+\t\t\tconst json = await response.json();\n+\t\t\tif (json.error) {\n+\t\t\t\tthrow new Error(json.error);\n+\t\t\t}\n+\t\t\tif (json.isLatest) {\n+\t\t\t\treturn;\n+\t\t\t}\n+\n+\t\t\tconst lastNoti = this.storageService.getNumber('csLastUpdateNotification', StorageScope.APPLICATION);\n+\t\t\tif (lastNoti) {\n+\t\t\t\t// Only remind them again after 1 week.\n+\t\t\t\tconst timeout = 1000 * 60 * 60 * 24 * 7;\n+\t\t\t\tconst threshold = lastNoti + timeout;\n+\t\t\t\tif (Date.now() < threshold) {\n+\t\t\t\t\treturn;\n+\t\t\t\t}\n+\t\t\t}\n+\n+\t\t\tthis.storageService.store('csLastUpdateNotification', Date.now(), StorageScope.APPLICATION, StorageTarget.MACHINE);\n+\n+\t\t\tthis.notificationService.notify({\n+\t\t\t\tseverity: Severity.Info,\n+\t\t\t\tmessage: `[code-server v${json.latest}](https://github.com/cdr/code-server/releases/tag/v${json.latest}) has been released!`,\n+\t\t\t});\n+\t\t};\n+\n+\t\tconst updateLoop = (): void => {\n+\t\t\tgetUpdate(updateEndpoint)\n+\t\t\t\t.catch(error => {\n+\t\t\t\t\tthis.logService.debug(`failed to check for update: ${error}`);\n+\t\t\t\t})\n+\t\t\t\t.finally(() => {\n+\t\t\t\t\t// Check again every 6 hours.\n+\t\t\t\t\tsetTimeout(updateLoop, 1000 * 60 * 60 * 6);\n+\t\t\t\t});\n+\t\t};\n+\n+\t\tupdateLoop();\n \t}\n }\nIndex: code-server/lib/vscode/src/vs/base/common/product.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/base/common/product.ts\n+++ code-server/lib/vscode/src/vs/base/common/product.ts\n@@ -67,6 +67,7 @@ export type ExtensionVirtualWorkspaceSup\n export interface IProductConfiguration {\n \treadonly codeServerVersion?: string\n \treadonly rootEndpoint?: string\n+\treadonly updateEndpoint?: string\n \n \treadonly version: string;\n \treadonly date?: string;\n@@ -114,6 +115,7 @@ export interface IProductConfiguration {\n \t\treadonly resourceUrlTemplate: string;\n \t\treadonly nlsBaseUrl: string;\n \t\treadonly accessSKUs?: string[];\n+\t\treadonly authorizationHeaderToken?: string;\n \t};\n \n \treadonly mcpGallery?: {\nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -341,6 +341,7 @@ export class WebClientServer {\n \t\tconst productConfiguration: Partial<Mutable<IProductConfiguration>> = {\n \t\t\tcodeServerVersion: this._productService.codeServerVersion,\n \t\t\trootEndpoint: rootBase,\n+\t\t\tupdateEndpoint: !this._environmentService.args['disable-update-check'] ? rootBase + '/update/check' : undefined,\n \t\t\tembedderIdentifier: 'server-distro',\n \t\t\textensionsGallery: this._productService.extensionsGallery,\n \t\t};\nIndex: code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n+++ code-server/lib/vscode/src/vs/server/node/serverEnvironmentService.ts\n@@ -16,6 +16,8 @@ import { join } from '../../base/common/\n import { ProtocolConstants } from '../../base/parts/ipc/common/ipc.net.js';\n \n export const serverOptions: OptionDescriptions<Required<ServerParsedArgs>> = {\n+\t/* ----- code-server ----- */\n+\t'disable-update-check': { type: 'boolean' },\n \n \t/* ----- server setup ----- */\n \n@@ -101,6 +103,8 @@ export const serverOptions: OptionDescri\n };\n \n export interface ServerParsedArgs {\n+\t/* ----- code-server ----- */\n+\t'disable-update-check'?: boolean;\n \n \t/* ----- server setup ----- */\n \n"
  },
  {
    "path": "patches/webview.diff",
    "content": "Serve webviews from the same origin\n\nNormally webviews are served from vscode-webview.net but we would rather them be\nself-hosted.\n\nWhen doing this CSP will block resources (for example when viewing images) so\nadd 'self' to the CSP to fix that.\n\nAdditionally the service worker defaults to handling *all* requests made to the\ncurrent host but when self-hosting the webview this will end up including the\nwebview HTML itself which means these requests will fail since the communication\nchannel between the webview and the main thread has not been set up yet as the\nwebview itself is not ready yet (it has no HTML and therefore no script either).\nSince this code exists only for the authentication case we can just skip it when\nit is served from the current host as authentication is not a problem if the\nrequest is not cross-origin.\n\nThere is also an origin check we bypass (this seems to be related to how the\nwebview host is separate by default but we serve on the same host).\n\nTo test, open a few types of webviews (images, markdown, extension details, etc).\n\nMake sure to update the hash. To do so:\n1. run code-server \n2. open any webview (i.e. preview Markdown)\n3. see error in console and copy hash\n\nThat will test the hash change in pre/index.html\n\nDouble-check the console to make sure there are no console errors for the webWorkerExtensionHostIframe\nwhich also requires a hash change.\n\nparentOriginHash changes\n\nThis fixes webviews from not working properly due to a change upstream.\nUpstream added a check to ensure parent authority is encoded into the webview\norigin. Since our webview origin is the parent authority, we can bypass this\ncheck.\n\nIndex: code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n+++ code-server/lib/vscode/src/vs/workbench/services/environment/browser/environmentService.ts\n@@ -220,7 +220,7 @@ export class BrowserWorkbenchEnvironment\n \n \t@memoize\n \tget webviewExternalEndpoint(): string {\n-\t\tconst endpoint = this.options.webviewEndpoint\n+\t\tconst endpoint = (this.options.webviewEndpoint && new URL(this.options.webviewEndpoint, window.location.toString()).toString())\n \t\t\t|| this.productService.webviewContentExternalBaseUrlTemplate\n \t\t\t|| 'https://{{uuid}}.vscode-cdn.net/{{quality}}/{{commit}}/out/vs/workbench/contrib/webview/browser/pre/';\n \nIndex: code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/server/node/webClientServer.ts\n+++ code-server/lib/vscode/src/vs/server/node/webClientServer.ts\n@@ -361,6 +361,7 @@ export class WebClientServer {\n \t\tconst workbenchWebConfiguration = {\n \t\t\tremoteAuthority,\n \t\t\tserverBasePath: basePath,\n+\t\t\twebviewEndpoint: staticRoute + '/out/vs/workbench/contrib/webview/browser/pre',\n \t\t\t_wrapWebWorkerExtHostInIframe,\n \t\t\tdevelopmentOptions: { enableSmokeTestDriver: this._environmentService.args['enable-smoke-test-driver'] ? true : undefined, logLevel: this._logService.getLevel() },\n \t\t\tsettingsSyncOptions: !this._environmentService.isBuilt && this._environmentService.args['enable-sync'] ? { enabled: true } : undefined,\nIndex: code-server/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/index.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/index.html\n+++ code-server/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/index.html\n@@ -5,7 +5,7 @@\n \t<meta charset=\"UTF-8\">\n \n \t<meta http-equiv=\"Content-Security-Policy\"\n-\t\tcontent=\"default-src 'none'; script-src 'sha256-TaWGDzV7c9rUH2q/5ygOyYUHSyHIqBMYfucPh3lnKvU=' 'self'; frame-src 'self'; style-src 'unsafe-inline';\">\n+\t\tcontent=\"default-src 'none'; script-src 'sha256-nQZh+9dHKZP2cHbhYlCbWDtqxxJtGjRGBx57zNP2DZM=' 'self'; frame-src 'self'; style-src 'unsafe-inline';\">\n \n \t<!-- Disable pinch zooming -->\n \t<meta name=\"viewport\"\n@@ -256,7 +256,7 @@\n \t\t\t}\n \n \t\t\tconst swPath = encodeURI(`service-worker.js?v=${expectedWorkerVersion}&vscode-resource-base-authority=${searchParams.get('vscode-resource-base-authority')}&remoteAuthority=${searchParams.get('remoteAuthority') ?? ''}`);\n-\t\t\tnavigator.serviceWorker.register(swPath, { type: 'module' })\n+\t\t\tnavigator.serviceWorker.register(swPath)\n \t\t\t\t.then(async registration => {\n \t\t\t\t\t/**\n \t\t\t\t\t * @param {MessageEvent} event\n@@ -370,6 +370,12 @@\n \n \t\t\t\tconst hostname = location.hostname;\n \n+\t\t\t\t// It is safe to run if we are on the same host.\n+\t\t\t\tconst parent = new URL(parentOrigin)\n+\t\t\t\tif (parent.hostname === hostname) {\n+\t\t\t\t\treturn start(parentOrigin)\n+\t\t\t\t}\n+\n \t\t\t\tif (!crypto.subtle) {\n \t\t\t\t\t// cannot validate, not running in a secure context\n \t\t\t\t\tthrow new Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);\nIndex: code-server/lib/vscode/src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html\n===================================================================\n--- code-server.orig/lib/vscode/src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html\n+++ code-server/lib/vscode/src/vs/workbench/services/extensions/worker/webWorkerExtensionHostIframe.html\n@@ -4,7 +4,7 @@\n \t\t<meta http-equiv=\"Content-Security-Policy\" content=\"\n \t\t\tdefault-src 'none';\n \t\t\tchild-src 'self' data: blob:;\n-\t\t\tscript-src 'self' 'unsafe-eval' 'sha256-cl8ijlOzEe+0GRCQNJQu2k6nUQ0fAYNYIuuKEm72JDs=' https: http://localhost:* blob:;\n+\t\t\tscript-src 'self' 'unsafe-eval' 'sha256-yhZXuB8LS6t73dvNg6rtLX8y4PHLnqRm5+6DdOGkOcw=' https: http://localhost:* blob:;\n \t\t\tconnect-src 'self' https: wss: http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:*;\"/>\n \t</head>\n \t<body>\n@@ -25,6 +25,13 @@\n \t\t\t// validation not requested\n \t\t\treturn start();\n \t\t}\n+\n+\t\t// It is safe to run if we are on the same host.\n+\t\tconst parent = new URL(parentOrigin)\n+\t\tif (parent.hostname === hostname) {\n+\t\t\treturn start()\n+\t\t}\n+\n \t\tif (!crypto.subtle) {\n \t\t\t// cannot validate, not running in a secure context\n \t\t\treturn sendError(new Error(`Cannot validate in current context!`));\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"rangeStrategy\": \"replace\",\n  \"extends\": [\"config:base\"],\n  \"packageRules\": [\n    {\n      \"matchUpdateTypes\": [\"minor\", \"patch\", \"digest\"],\n      \"automerge\": true,\n      \"groupName\": \"Minor dependency updates\"\n    },\n    {\n      \"matchDepTypes\": [\"peerDependencies\"],\n      \"matchUpdateTypes\": [\"minor\", \"patch\", \"digest\"],\n      \"automerge\": true,\n      \"groupName\": \"Peer dependency updates\"\n    }\n  ],\n  \"vulnerabilityAlerts\": {\n    \"enabled\": \"true\"\n  },\n  \"ignoreDeps\": [\"express\", \"ansi-regex\", \"env-paths\", \"limiter\", \"node\", \"prettier\"]\n}\n"
  },
  {
    "path": "src/browser/pages/error.css",
    "content": ".error-display {\n  box-sizing: border-box;\n  padding: 20px;\n  text-align: center;\n}\n\n.error-display > .header {\n  font-size: 6rem;\n  margin: 0;\n}\n\n.error-display > .body {\n  color: #444;\n  color: light-dark(#444, #ccc);\n  font-size: 1.2rem;\n}\n\n.error-display > .links {\n  margin-top: 16px;\n}\n\n.error-display > .links > .link {\n  color: rgb(87, 114, 245);\n  text-decoration: none;\n}\n\n.error-display > .links > .link:hover {\n  text-decoration: underline;\n}\n\n.error-display .success {\n  color: green;\n}\n"
  },
  {
    "path": "src/browser/pages/error.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\"\n    />\n    <meta\n      http-equiv=\"Content-Security-Policy\"\n      content=\"style-src 'self'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;\"\n    />\n    <meta name=\"color-scheme\" content=\"light dark\" />\n    <title>{{ERROR_TITLE}} - {{APP_NAME}}</title>\n    <link rel=\"icon\" href=\"{{CS_STATIC_BASE}}/src/browser/media/favicon-dark-support.svg\" />\n    <link rel=\"alternate icon\" href=\"{{CS_STATIC_BASE}}/src/browser/media/favicon.ico\" />\n    <link rel=\"manifest\" href=\"/manifest.json\" crossorigin=\"use-credentials\" />\n    <link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-192.png\" />\n    <link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-512.png\" />\n    <link href=\"{{CS_STATIC_BASE}}/src/browser/pages/global.css\" rel=\"stylesheet\" />\n    <link href=\"{{CS_STATIC_BASE}}/src/browser/pages/error.css\" rel=\"stylesheet\" />\n    <meta id=\"coder-options\" data-settings=\"{{OPTIONS}}\" />\n  </head>\n  <body>\n    <div class=\"center-container\">\n      <div class=\"error-display\">\n        <h2 class=\"header\">{{ERROR_HEADER}}</h2>\n        <div class=\"body\">{{ERROR_BODY}}</div>\n        <div class=\"links\">\n          <a class=\"link\" href=\"{{BASE}}{{TO}}\">go home</a>\n        </div>\n      </div>\n    </div>\n  </body>\n</html>\n"
  },
  {
    "path": "src/browser/pages/global.css",
    "content": ":root {\n  color-scheme: light dark;\n}\n\nhtml,\nbody,\n#root {\n  height: 100%;\n  width: 100%;\n}\n\nbody {\n  background: rgb(244, 247, 252);\n  background: light-dark(rgb(244, 247, 252), #111827);\n  color: #111;\n  color: light-dark(#111, #ddd);\n  margin: 0;\n  font-family:\n    -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif, \"Apple Color Emoji\",\n    \"Segoe UI Emoji\", \"Segoe UI Symbol\";\n  overflow: hidden;\n}\n\ninput,\nbutton {\n  font-family: inherit;\n  font-size: 1rem;\n  line-height: 1rem;\n}\n\n.-button {\n  background-color: rgb(87, 114, 245);\n  background-color: light-dark(rgb(87, 114, 245), rgb(26, 86, 219));\n  border-radius: 5px;\n  border: none;\n  box-sizing: border-box;\n  color: white;\n  color: light-dark(white, white);\n  cursor: pointer;\n  padding: 18px 20px;\n  font-weight: 500;\n  text-decoration: none;\n}\n\n.center-container {\n  align-items: center;\n  box-sizing: border-box;\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n  min-height: 100%;\n  padding: 20px;\n  width: 100%;\n}\n\n.card-box {\n  background-color: rgb(250, 253, 258);\n  background-color: light-dark(rgb(250, 253, 258), #1f2937);\n  border-radius: 5px;\n  box-shadow:\n    light-dark(rgba(60, 66, 87, 0.117647), rgba(10, 10, 10, 0.617647)) 0px 7px 14px 0px,\n    rgba(0, 0, 0, 0.117647) 0px 3px 6px 0px;\n  max-width: 650px;\n  width: 100%;\n}\n\n.card-box > .header {\n  border-bottom: 1px solid #ddd;\n  border-bottom: 1px solid light-dark(#ddd, #111827);\n  color: #444;\n  color: light-dark(#444, #fff);\n  padding: 30px;\n}\n\n.card-box > .header > .main {\n  margin: 0;\n  font-size: 1.5rem;\n}\n\n.card-box > .header > .sub {\n  color: #555;\n  color: light-dark(#555, #9ca3af);\n  margin-top: 10px;\n}\n\n.card-box > .content {\n  padding: 40px;\n}\n\n.card-box > .content > .none {\n  margin: 2px 0;\n}\n\n.card-box + .card-box {\n  margin-top: 26px;\n}\n\ncanvas {\n  top: 0;\n  left: 0;\n}\n"
  },
  {
    "path": "src/browser/pages/login.css",
    "content": "body {\n  min-height: 568px;\n  min-width: 320px;\n  overflow: auto;\n}\n\n.login-form {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  justify-content: center;\n}\n\n.login-form > .field {\n  display: flex;\n  flex-direction: row;\n  width: 100%;\n}\n\n@media (max-width: 600px) {\n  .login-form > .field {\n    flex-direction: column;\n  }\n}\n\n.login-form > .error {\n  color: red;\n  margin-top: 16px;\n}\n\n.login-form > .field > .password {\n  background-color: rgb(244, 247, 252);\n  background-color: light-dark(rgb(244, 247, 252), #374151);\n  border-radius: 5px;\n  border: 1px solid #ddd;\n  border: 1px solid light-dark(#ddd, #4b5563);\n  box-sizing: border-box;\n  flex: 1;\n  padding: 16px;\n}\n\n.login-form > .field > .password::placeholder {\n  color: rgb(148 163 184);\n}\n\n.login-form > .field > .password:focus {\n  outline: 2px solid rgb(63, 131, 248);\n}\n\n.login-form > .user {\n  display: none;\n}\n\n.login-form > .field > .submit {\n  margin-left: 20px;\n}\n\n@media (max-width: 600px) {\n  .login-form > .field > .submit {\n    margin-left: 0px;\n    margin-top: 16px;\n  }\n}\n\ninput {\n  -webkit-appearance: none;\n}\n"
  },
  {
    "path": "src/browser/pages/login.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\"\n    />\n    <meta\n      http-equiv=\"Content-Security-Policy\"\n      content=\"style-src 'self'; script-src 'self' 'unsafe-inline'; manifest-src 'self'; img-src 'self' data:; font-src 'self' data:;\"\n    />\n    <meta name=\"color-scheme\" content=\"light dark\" />\n    <title>{{I18N_LOGIN_TITLE}}</title>\n    <link rel=\"icon\" href=\"{{CS_STATIC_BASE}}/src/browser/media/favicon-dark-support.svg\" />\n    <link rel=\"alternate icon\" href=\"{{CS_STATIC_BASE}}/src/browser/media/favicon.ico\" />\n    <link rel=\"manifest\" href=\"{{BASE}}/manifest.json\" crossorigin=\"use-credentials\" />\n    <link rel=\"apple-touch-icon\" sizes=\"192x192\" href=\"{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-192.png\" />\n    <link rel=\"apple-touch-icon\" sizes=\"512x512\" href=\"{{CS_STATIC_BASE}}/src/browser/media/pwa-icon-512.png\" />\n    <link href=\"{{CS_STATIC_BASE}}/src/browser/pages/global.css\" rel=\"stylesheet\" />\n    <link href=\"{{CS_STATIC_BASE}}/src/browser/pages/login.css\" rel=\"stylesheet\" />\n    <meta id=\"coder-options\" data-settings=\"{{OPTIONS}}\" />\n  </head>\n  <body>\n    <div class=\"center-container\">\n      <div class=\"card-box\">\n        <div class=\"header\">\n          <h1 class=\"main\">{{WELCOME_TEXT}}</h1>\n          <div class=\"sub\">{{I18N_LOGIN_BELOW}} {{PASSWORD_MSG}}</div>\n        </div>\n        <div class=\"content\">\n          <form class=\"login-form\" method=\"post\">\n            <input class=\"user\" type=\"text\" autocomplete=\"username\" />\n            <input id=\"base\" type=\"hidden\" name=\"base\" value=\"{{BASE}}\" />\n            <input id=\"href\" type=\"hidden\" name=\"href\" value=\"\" />\n            <div class=\"field\">\n              <input\n                required\n                autofocus\n                class=\"password\"\n                type=\"password\"\n                placeholder=\"{{I18N_PASSWORD_PLACEHOLDER}}\"\n                name=\"password\"\n                autocomplete=\"current-password\"\n              />\n              <input class=\"submit -button\" value=\"{{I18N_SUBMIT}}\" type=\"submit\" />\n            </div>\n            {{ERROR}}\n          </form>\n        </div>\n      </div>\n    </div>\n    <script>\n      // Inform the backend about the path since the proxy might have rewritten\n      // it out of the headers and cookies must be set with absolute paths.\n      const el = document.getElementById(\"href\")\n      if (el) {\n        el.value = location.href\n      }\n    </script>\n  </body>\n</html>\n"
  },
  {
    "path": "src/browser/robots.txt",
    "content": "User-agent: *\nDisallow: /\n"
  },
  {
    "path": "src/browser/security.txt",
    "content": "Contact: mailto:security@coder.com\nAcknowledgments: https://coder.com/security/thanks\nPreferred-Languages: en-US\nCanonical: https://coder.com/.well-known/security.txt\nPolicy: https://coder.com/security/policy\nHiring: https://coder.com/careers"
  },
  {
    "path": "src/browser/serviceWorker.ts",
    "content": "self.addEventListener(\"install\", () => {\n  console.debug(\"[Service Worker] installed\")\n})\n\nself.addEventListener(\"activate\", (event: any) => {\n  event.waitUntil((self as any).clients.claim())\n  console.debug(\"[Service Worker] activated\")\n})\n\nself.addEventListener(\"fetch\", () => {\n  // Without this event handler we won't be recognized as a PWA.\n})\n"
  },
  {
    "path": "src/common/emitter.ts",
    "content": "import { logger } from \"@coder/logger\"\n\n/**\n * Event emitter callback. Called with the emitted value and a promise that\n * resolves when all emitters have finished.\n */\nexport type Callback<T, R = void | Promise<void>> = (t: T, p: Promise<void>) => R\n\nexport interface Disposable {\n  dispose(): void | Promise<void>\n}\n\nexport interface Event<T> {\n  (listener: Callback<T>): Disposable\n}\n\n/**\n * Emitter typecasts for a single event type.\n */\nexport class Emitter<T> {\n  private listeners: Array<Callback<T>> = []\n\n  public get event(): Event<T> {\n    return (cb: Callback<T>): Disposable => {\n      this.listeners.push(cb)\n\n      return {\n        dispose: (): void => {\n          const i = this.listeners.indexOf(cb)\n          if (i !== -1) {\n            this.listeners.splice(i, 1)\n          }\n        },\n      }\n    }\n  }\n\n  /**\n   * Emit an event with a value.\n   */\n  public async emit(value: T): Promise<void> {\n    let resolve: () => void\n    const promise = new Promise<void>((r) => (resolve = r))\n\n    await Promise.all(\n      this.listeners.map(async (cb) => {\n        try {\n          await cb(value, promise)\n        } catch (error: any) {\n          logger.error(error.message)\n        }\n      }),\n    )\n\n    resolve!()\n  }\n\n  public dispose(): void {\n    this.listeners = []\n  }\n}\n"
  },
  {
    "path": "src/common/http.ts",
    "content": "export enum HttpCode {\n  Ok = 200,\n  Redirect = 302,\n  NotFound = 404,\n  BadRequest = 400,\n  Unauthorized = 401,\n  Forbidden = 403,\n  LargePayload = 413,\n  ServerError = 500,\n}\n\n/**\n * Represents an error with a message and an HTTP status code. This code will be\n * used in the HTTP response.\n */\nexport class HttpError extends Error {\n  public constructor(\n    message: string,\n    public readonly statusCode: HttpCode,\n    public readonly details?: object,\n  ) {\n    super(message)\n    this.name = this.constructor.name\n  }\n}\n\nexport function getCookieSessionName(suffix?: string): string {\n  return suffix ? `code-server-session-${suffix.replace(/[^a-zA-Z0-9-]/g, \"-\")}` : \"code-server-session\"\n}\n"
  },
  {
    "path": "src/common/util.ts",
    "content": "/**\n * Appends an 's' to the provided string if count is greater than one;\n * otherwise the string is returned\n */\nexport const plural = (count: number, str: string): string => (count === 1 ? str : `${str}s`)\n\nexport const generateUuid = (length = 24): string => {\n  const possible = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n  return Array(length)\n    .fill(1)\n    .map(() => possible[Math.floor(Math.random() * possible.length)])\n    .join(\"\")\n}\n\n/**\n * Remove extra slashes in a URL.\n *\n * This is meant to fill the job of `path.join` so you can concatenate paths and\n * then normalize out any extra slashes.\n *\n * If you are using `path.join` you do not need this but note that `path` is for\n * file system paths, not URLs.\n */\nexport const normalize = (url: string, keepTrailing = false): string => {\n  return url.replace(/\\/\\/+/g, \"/\").replace(/\\/+$/, keepTrailing ? \"/\" : \"\")\n}\n\n// TODO: Might make sense to add Error handling to the logger itself.\nexport function logError(logger: { error: (msg: string) => void }, prefix: string, err: unknown): void {\n  if (err instanceof Error) {\n    logger.error(`${prefix}: ${err.message} ${err.stack}`)\n  } else {\n    logger.error(`${prefix}: ${err}`)\n  }\n}\n"
  },
  {
    "path": "src/node/app.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport compression from \"compression\"\nimport express, { Express } from \"express\"\nimport { promises as fs } from \"fs\"\nimport http from \"http\"\nimport * as httpolyglot from \"httpolyglot\"\nimport { Disposable } from \"../common/emitter\"\nimport * as util from \"../common/util\"\nimport { DefaultedArgs } from \"./cli\"\nimport { disposer } from \"./http\"\nimport { isNodeJSErrnoException } from \"./util\"\nimport { EditorSessionManager, makeEditorSessionManagerServer } from \"./vscodeSocket\"\nimport { handleUpgrade } from \"./wsRouter\"\n\ntype SocketOptions = { socket: string; \"socket-mode\"?: string }\ntype ListenOptions = DefaultedArgs | SocketOptions\n\nexport interface App extends Disposable {\n  /** Handles regular HTTP requests. */\n  router: Express\n  /** Handles websocket requests. */\n  wsRouter: Express\n  /** The underlying HTTP server. */\n  server: http.Server\n  /** Handles requests to the editor session management API. */\n  editorSessionManagerServer: http.Server\n}\n\nconst isSocketOpts = (opts: ListenOptions): opts is SocketOptions => {\n  return !!(opts as SocketOptions).socket || !(opts as DefaultedArgs).host\n}\n\nexport const listen = async (server: http.Server, opts: ListenOptions) => {\n  if (isSocketOpts(opts)) {\n    try {\n      await fs.unlink(opts.socket)\n    } catch (error: any) {\n      handleArgsSocketCatchError(error)\n    }\n  }\n  await new Promise<void>(async (resolve, reject) => {\n    server.on(\"error\", reject)\n    const onListen = () => {\n      // Promise resolved earlier so this is an unrelated error.\n      server.off(\"error\", reject)\n      server.on(\"error\", (err) => util.logError(logger, \"http server error\", err))\n      resolve()\n    }\n    if (isSocketOpts(opts)) {\n      server.listen(opts.socket, onListen)\n    } else {\n      // [] is the correct format when using :: but Node errors with them.\n      server.listen(opts.port, opts.host.replace(/^\\[|\\]$/g, \"\"), onListen)\n    }\n  })\n\n  // NOTE@jsjoeio: we need to chmod after the server is finished\n  // listening. Otherwise, the socket may not have been created yet.\n  if (isSocketOpts(opts)) {\n    if (opts[\"socket-mode\"]) {\n      await fs.chmod(opts.socket, opts[\"socket-mode\"])\n    }\n  }\n}\n\n/**\n * Create an Express app and an HTTP/S server to serve it.\n */\nexport const createApp = async (args: DefaultedArgs): Promise<App> => {\n  const router = express()\n  router.use(compression())\n\n  const server = args.cert\n    ? httpolyglot.createServer(\n        {\n          cert: args.cert && (await fs.readFile(args.cert.value)),\n          key: args[\"cert-key\"] && (await fs.readFile(args[\"cert-key\"])),\n        },\n        router,\n      )\n    : http.createServer(router)\n\n  const disposeServer = disposer(server)\n\n  await listen(server, args)\n\n  const wsRouter = express()\n  handleUpgrade(wsRouter, server)\n\n  const editorSessionManager = new EditorSessionManager()\n  const editorSessionManagerServer = await makeEditorSessionManagerServer(args[\"session-socket\"], editorSessionManager)\n  const disposeEditorSessionManagerServer = disposer(editorSessionManagerServer)\n\n  const dispose = async () => {\n    await Promise.all([disposeServer(), disposeEditorSessionManagerServer()])\n  }\n\n  return { router, wsRouter, server, dispose, editorSessionManagerServer }\n}\n\n/**\n * Get the address of a server as a string (protocol *is* included) while\n * ensuring there is one (will throw if there isn't).\n *\n * The address might be a URL or it might be a pipe or socket path.\n */\nexport const ensureAddress = (server: http.Server, protocol: string): URL | string => {\n  const addr = server.address()\n\n  if (!addr) {\n    throw new Error(\"Server has no address\")\n  }\n\n  if (typeof addr !== \"string\") {\n    const host = addr.family === \"IPv6\" ? `[${addr.address}]` : addr.address\n    return new URL(`${protocol}://${host}:${addr.port}`)\n  }\n\n  // If this is a string then it is a pipe or Unix socket.\n  return addr\n}\n\n/**\n * Handles the error that occurs in the catch block\n * after we try fs.unlink(args.socket).\n *\n * We extracted into a function so that we could\n * test this logic more easily.\n */\nexport const handleArgsSocketCatchError = (error: any) => {\n  if (!isNodeJSErrnoException(error) || error.code !== \"ENOENT\") {\n    throw Error(error.message ? error.message : error)\n  }\n}\n"
  },
  {
    "path": "src/node/cli.ts",
    "content": "import { field, Level, logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport { load } from \"js-yaml\"\nimport * as path from \"path\"\nimport { generateCertificate, generatePassword, paths, splitOnFirstEquals } from \"./util\"\nimport { EditorSessionManagerClient } from \"./vscodeSocket\"\n\nexport enum Feature {\n  // No current experimental features!\n  Placeholder = \"placeholder\",\n}\n\nexport enum AuthType {\n  Password = \"password\",\n  None = \"none\",\n}\n\nexport class Optional<T> {\n  public constructor(public readonly value?: T) {}\n}\n\nexport enum LogLevel {\n  Trace = \"trace\",\n  Debug = \"debug\",\n  Info = \"info\",\n  Warn = \"warn\",\n  Error = \"error\",\n}\n\nexport class OptionalString extends Optional<string> {}\n\n/**\n * (VS) Code flags provided by the user.\n */\nexport interface UserProvidedCodeArgs {\n  \"disable-telemetry\"?: boolean\n  force?: boolean\n  \"user-data-dir\"?: string\n  \"enable-proposed-api\"?: string[]\n  \"extensions-dir\"?: string\n  \"builtin-extensions-dir\"?: string\n  \"install-extension\"?: string[]\n  \"uninstall-extension\"?: string[]\n  \"list-extensions\"?: boolean\n  \"locate-extension\"?: string[]\n  \"show-versions\"?: boolean\n  category?: string\n  \"github-auth\"?: string\n  \"disable-update-check\"?: boolean\n  \"disable-file-downloads\"?: boolean\n  \"disable-file-uploads\"?: boolean\n  \"disable-workspace-trust\"?: boolean\n  \"disable-getting-started-override\"?: boolean\n  \"disable-proxy\"?: boolean\n  \"session-socket\"?: string\n  \"cookie-suffix\"?: string\n  \"link-protection-trusted-domains\"?: string[]\n  // locale is used by both VS Code and code-server.\n  locale?: string\n}\n\n/**\n * Arguments that the user explicitly provided on the command line.  All\n * arguments must be optional.\n *\n * For arguments with defaults see DefaultedArgs.\n */\nexport interface UserProvidedArgs extends UserProvidedCodeArgs {\n  config?: string\n  auth?: AuthType\n  password?: string\n  \"hashed-password\"?: string\n  cert?: OptionalString\n  \"cert-host\"?: string\n  \"cert-key\"?: string\n  enable?: string[]\n  help?: boolean\n  host?: string\n  port?: number\n  json?: boolean\n  log?: LogLevel\n  open?: boolean\n  \"bind-addr\"?: string\n  socket?: string\n  \"socket-mode\"?: string\n  \"trusted-origins\"?: string[]\n  version?: boolean\n  \"proxy-domain\"?: string[]\n  \"skip-auth-preflight\"?: boolean\n  \"reuse-window\"?: boolean\n  \"new-window\"?: boolean\n  \"ignore-last-opened\"?: boolean\n  verbose?: boolean\n  \"app-name\"?: string\n  \"welcome-text\"?: string\n  \"abs-proxy-base-path\"?: string\n  i18n?: string\n  \"idle-timeout-seconds\"?: number\n  /* Positional arguments. */\n  _?: string[]\n}\n\ninterface Option<T> {\n  type: T\n  /**\n   * Short flag for the option.\n   */\n  short?: string\n  /**\n   * Whether the option is a path and should be resolved.\n   */\n  path?: boolean\n  /**\n   * Description of the option. Leave blank to hide the option.\n   */\n  description?: string\n\n  /**\n   * If marked as deprecated, the option is marked as deprecated in help.\n   */\n  deprecated?: boolean\n}\n\ntype OptionType<T> = T extends boolean\n  ? \"boolean\"\n  : T extends OptionalString\n    ? typeof OptionalString\n    : T extends LogLevel\n      ? typeof LogLevel\n      : T extends AuthType\n        ? typeof AuthType\n        : T extends number\n          ? \"number\"\n          : T extends string\n            ? \"string\"\n            : T extends string[]\n              ? \"string[]\"\n              : \"unknown\"\n\nexport type Options<T> = {\n  [P in keyof T]: Option<OptionType<T[P]>>\n}\n\nexport const options: Options<Required<UserProvidedArgs>> = {\n  auth: { type: AuthType, description: \"The type of authentication to use.\" },\n  password: {\n    type: \"string\",\n    description: \"The password for password authentication (can only be passed in via $PASSWORD or the config file).\",\n  },\n  \"hashed-password\": {\n    type: \"string\",\n    description:\n      \"The password hashed with argon2 for password authentication (can only be passed in via $HASHED_PASSWORD or the config file). \\n\" +\n      \"Takes precedence over 'password'.\",\n  },\n  cert: {\n    type: OptionalString,\n    path: true,\n    description: \"Path to certificate. A self signed certificate is generated if none is provided.\",\n  },\n  \"cert-host\": {\n    type: \"string\",\n    description: \"Hostname to use when generating a self signed certificate.\",\n  },\n  \"cert-key\": { type: \"string\", path: true, description: \"Path to certificate key when using non-generated cert.\" },\n  \"disable-telemetry\": { type: \"boolean\", description: \"Disable telemetry.\" },\n  \"disable-update-check\": {\n    type: \"boolean\",\n    description:\n      \"Disable update check. Without this flag, code-server checks every 6 hours against the latest github release and \\n\" +\n      \"then notifies you once every week that a new release is available.\",\n  },\n  \"session-socket\": {\n    type: \"string\",\n  },\n  \"cookie-suffix\": {\n    type: \"string\",\n    description:\n      \"Adds a suffix to the cookie. This can prevent a collision of cookies for subdomains, making them explixit. \\n\" +\n      \"Without this flag, no suffix is used. This can also be set with CODE_SERVER_COOKIE_SUFFIX set to any string.\",\n  },\n  \"disable-file-downloads\": {\n    type: \"boolean\",\n    description:\n      \"Disable file downloads from Code. This can also be set with CS_DISABLE_FILE_DOWNLOADS set to 'true' or '1'.\",\n  },\n  \"disable-file-uploads\": {\n    type: \"boolean\",\n    description: \"Disable file uploads.\",\n  },\n  \"disable-workspace-trust\": {\n    type: \"boolean\",\n    description: \"Disable Workspace Trust feature. This switch only affects the current session.\",\n  },\n  \"disable-getting-started-override\": {\n    type: \"boolean\",\n    description: \"Disable the coder/coder override in the Help: Getting Started page.\",\n  },\n  \"disable-proxy\": {\n    type: \"boolean\",\n    description: \"Disable domain and path proxy routes.\",\n  },\n  // --enable can be used to enable experimental features. These features\n  // provide no guarantees.\n  enable: { type: \"string[]\" },\n  help: { type: \"boolean\", short: \"h\", description: \"Show this output.\" },\n  json: { type: \"boolean\" },\n  \"link-protection-trusted-domains\": {\n    type: \"string[]\",\n    description: \"Links matching a trusted domain can be opened without link protection.\",\n  },\n  locale: {\n    // The preferred way to set the locale is via the UI.\n    type: \"string\",\n    description: `\n      Set vscode display language and language to show on the login page, more info see\n      https://en.wikipedia.org/wiki/IETF_language_tag\n    `,\n  },\n  open: { type: \"boolean\", description: \"Open in browser on startup. Does not work remotely.\" },\n\n  \"bind-addr\": {\n    type: \"string\",\n    description: \"Address to bind to in host:port. You can also use $PORT to override the port.\",\n  },\n\n  config: {\n    type: \"string\",\n    description: \"Path to yaml config file. Every flag maps directly to a key in the config file.\",\n  },\n\n  // These two have been deprecated by bindAddr.\n  host: { type: \"string\", description: \"\" },\n  port: { type: \"number\", description: \"\" },\n\n  socket: { type: \"string\", path: true, description: \"Path to a socket (bind-addr will be ignored).\" },\n  \"socket-mode\": { type: \"string\", description: \"File mode of the socket.\" },\n  \"trusted-origins\": {\n    type: \"string[]\",\n    description:\n      \"Disables authenticate origin check for trusted origin. Useful if not able to access reverse proxy configuration.\",\n  },\n  version: { type: \"boolean\", short: \"v\", description: \"Display version information.\" },\n  _: { type: \"string[]\" },\n\n  \"user-data-dir\": { type: \"string\", path: true, description: \"Path to the user data directory.\" },\n  \"extensions-dir\": { type: \"string\", path: true, description: \"Path to the extensions directory.\" },\n  \"builtin-extensions-dir\": { type: \"string\", path: true },\n  \"list-extensions\": { type: \"boolean\", description: \"List installed VS Code extensions.\" },\n  force: { type: \"boolean\", description: \"Avoid prompts when installing VS Code extensions.\" },\n  \"locate-extension\": { type: \"string[]\" },\n  category: { type: \"string\" },\n  \"install-extension\": {\n    type: \"string[]\",\n    description:\n      \"Install or update a VS Code extension by id or vsix. The identifier of an extension is `${publisher}.${name}`.\\n\" +\n      \"To install a specific version provide `@${version}`. For example: 'vscode.csharp@1.2.3'.\",\n  },\n  \"enable-proposed-api\": {\n    type: \"string[]\",\n    description:\n      \"Enable proposed API features for extensions. Can receive one or more extension IDs to enable individually.\",\n  },\n  \"uninstall-extension\": { type: \"string[]\", description: \"Uninstall a VS Code extension by id.\" },\n  \"show-versions\": { type: \"boolean\", description: \"Show VS Code extension versions.\" },\n  \"github-auth\": {\n    type: \"string\",\n    description: \"GitHub authentication token (can only be passed in via $GITHUB_TOKEN or the config file).\",\n  },\n  \"proxy-domain\": { type: \"string[]\", description: \"Domain used for proxying ports.\" },\n  \"skip-auth-preflight\": {\n    type: \"boolean\",\n    description: \"Allows preflight requests through proxy without authentication.\",\n  },\n  \"ignore-last-opened\": {\n    type: \"boolean\",\n    short: \"e\",\n    description: \"Ignore the last opened directory or workspace in favor of an empty window.\",\n  },\n  \"new-window\": {\n    type: \"boolean\",\n    short: \"n\",\n    description: \"Force to open a new window.\",\n  },\n  \"reuse-window\": {\n    type: \"boolean\",\n    short: \"r\",\n    description: \"Force to open a file or folder in an already opened window.\",\n  },\n\n  log: { type: LogLevel },\n  verbose: { type: \"boolean\", short: \"vvv\", description: \"Enable verbose logging.\" },\n  \"app-name\": {\n    type: \"string\",\n    short: \"an\",\n    description:\n      \"Will replace the {{app}} placeholder in any strings, which by default includes the title bar and welcome message\",\n  },\n  \"welcome-text\": {\n    type: \"string\",\n    short: \"w\",\n    description: \"Text to show on login page\",\n    deprecated: true,\n  },\n  \"abs-proxy-base-path\": {\n    type: \"string\",\n    description: \"The base path to prefix to all absproxy requests\",\n  },\n  i18n: {\n    type: \"string\",\n    path: true,\n    description: \"Path to JSON file with custom translations. Merges with default strings and supports all i18n keys.\",\n  },\n  \"idle-timeout-seconds\": {\n    type: \"number\",\n    description: \"Timeout in seconds to wait before shutting down when idle.\",\n  },\n}\n\nexport const optionDescriptions = (opts: Partial<Options<Required<UserProvidedArgs>>> = options): string[] => {\n  const entries = Object.entries(opts).filter(([, v]) => !!v.description)\n  const widths = entries.reduce(\n    (prev, [k, v]) => ({\n      long: k.length > prev.long ? k.length : prev.long,\n      short: v.short && v.short.length > prev.short ? v.short.length : prev.short,\n    }),\n    { short: 0, long: 0 },\n  )\n  return entries.map(([k, v]) => {\n    const help = `${\" \".repeat(widths.short - (v.short ? v.short.length : 0))}${v.short ? `-${v.short}` : \" \"} --${k} `\n    return (\n      help +\n      v.description\n        ?.trim()\n        .split(/\\n/)\n        .map((line, i) => {\n          line = line.trim()\n          if (i === 0) {\n            return \" \".repeat(widths.long - k.length) + (v.deprecated ? \"(deprecated) \" : \"\") + line\n          }\n          return \" \".repeat(widths.long + widths.short + 6) + line\n        })\n        .join(\"\\n\") +\n      (typeof v.type === \"object\" ? ` [${Object.values(v.type).join(\", \")}]` : \"\")\n    )\n  })\n}\n\n/**\n * Parse arguments into UserProvidedArgs.  This should not go beyond checking\n * that arguments are valid types and have values when required.\n */\nexport const parse = (\n  argv: string[],\n  opts?: {\n    configFile?: string\n  },\n): UserProvidedArgs => {\n  const error = (msg: string): Error => {\n    if (opts?.configFile) {\n      msg = `error reading ${opts.configFile}: ${msg}`\n    }\n\n    return new Error(msg)\n  }\n\n  const args: UserProvidedArgs = {}\n  let ended = false\n\n  for (let i = 0; i < argv.length; ++i) {\n    const arg = argv[i]\n\n    // -- signals the end of option parsing.\n    if (!ended && arg === \"--\") {\n      ended = true\n      continue\n    }\n\n    // Options start with a dash and require a value if non-boolean.\n    if (!ended && arg.startsWith(\"-\")) {\n      let key: keyof UserProvidedArgs | undefined\n      let value: string | undefined\n      if (arg.startsWith(\"--\")) {\n        const split = splitOnFirstEquals(arg.replace(/^--/, \"\"))\n        key = split[0] as keyof UserProvidedArgs\n        value = split[1]\n      } else {\n        const short = arg.replace(/^-/, \"\")\n        const pair = Object.entries(options).find(([, v]) => v.short === short)\n        if (pair) {\n          key = pair[0] as keyof UserProvidedArgs\n        }\n      }\n\n      if (!key || !options[key]) {\n        throw error(`Unknown option ${arg}`)\n      }\n\n      if (key === \"password\" && !opts?.configFile) {\n        throw new Error(\"--password can only be set in the config file or passed in via $PASSWORD\")\n      }\n\n      if (key === \"hashed-password\" && !opts?.configFile) {\n        throw new Error(\"--hashed-password can only be set in the config file or passed in via $HASHED_PASSWORD\")\n      }\n\n      if (key === \"github-auth\" && !opts?.configFile) {\n        throw new Error(\"--github-auth can only be set in the config file or passed in via $GITHUB_TOKEN\")\n      }\n\n      if (key === \"idle-timeout-seconds\" && Number(value) <= 60) {\n        throw new Error(\"--idle-timeout-seconds must be greater than 60 seconds.\")\n      }\n\n      const option = options[key]\n      if (option.type === \"boolean\") {\n        ;(args[key] as boolean) = true\n        continue\n      }\n\n      // Might already have a value if it was the --long=value format.\n      if (typeof value === \"undefined\") {\n        // A value is only valid if it doesn't look like an option.\n        value = argv[i + 1] && !argv[i + 1].startsWith(\"-\") ? argv[++i] : undefined\n      }\n\n      if (!value && option.type === OptionalString) {\n        ;(args[key] as OptionalString) = new OptionalString(value)\n        continue\n      } else if (!value) {\n        throw error(`--${key} requires a value`)\n      }\n\n      if (option.type === OptionalString && value === \"false\") {\n        continue\n      }\n\n      if (option.path) {\n        value = path.resolve(value)\n      }\n\n      switch (option.type) {\n        case \"string\":\n          ;(args[key] as string) = value\n          break\n        case \"string[]\":\n          if (!args[key]) {\n            ;(args[key] as string[]) = []\n          }\n          ;(args[key] as string[]).push(value)\n          break\n        case \"number\":\n          ;(args[key] as number) = parseInt(value, 10)\n          if (isNaN(args[key] as number)) {\n            throw error(`--${key} must be a number`)\n          }\n          break\n        case OptionalString:\n          ;(args[key] as OptionalString) = new OptionalString(value)\n          break\n        default: {\n          if (!Object.values(option.type).includes(value)) {\n            throw error(`--${key} valid values: [${Object.values(option.type).join(\", \")}]`)\n          }\n          ;(args[key] as string) = value\n          break\n        }\n      }\n\n      continue\n    }\n\n    // Everything else goes into _.\n    if (typeof args._ === \"undefined\") {\n      args._ = []\n    }\n\n    args._.push(arg)\n  }\n\n  // If a cert was provided a key must also be provided.\n  if (args.cert && args.cert.value && !args[\"cert-key\"]) {\n    throw new Error(\"--cert-key is missing\")\n  }\n\n  logger.debug(() => [`parsed ${opts?.configFile ? \"config\" : \"command line\"}`, field(\"args\", redactArgs(args))])\n\n  return args\n}\n\n/**\n * Redact sensitive information from arguments for logging.\n */\nexport const redactArgs = (args: UserProvidedArgs): UserProvidedArgs => {\n  return {\n    ...args,\n    password: args.password ? \"<redacted>\" : undefined,\n    \"hashed-password\": args[\"hashed-password\"] ? \"<redacted>\" : undefined,\n    \"github-auth\": args[\"github-auth\"] ? \"<redacted>\" : undefined,\n  }\n}\n\n/**\n * User-provided arguments with defaults.  The distinction between user-provided\n * args and defaulted args exists so we can tell the difference between end\n * values and what the user actually provided on the command line.\n */\nexport interface DefaultedArgs extends ConfigArgs {\n  auth: AuthType\n  cert?: {\n    value: string\n  }\n  host: string\n  port: number\n  \"proxy-domain\": string[]\n  verbose: boolean\n  usingEnvPassword: boolean\n  usingEnvHashedPassword: boolean\n  \"extensions-dir\": string\n  \"user-data-dir\": string\n  \"session-socket\": string\n  \"app-name\": string\n  /* Positional arguments. */\n  _: string[]\n}\n\n/**\n * Take CLI and config arguments (optional) and return a single set of arguments\n * with the defaults set. Arguments from the CLI are prioritized over config\n * arguments.\n */\nexport async function setDefaults(cliArgs: UserProvidedArgs, configArgs?: ConfigArgs): Promise<DefaultedArgs> {\n  const args = Object.assign({}, configArgs || {}, cliArgs)\n\n  if (!args[\"user-data-dir\"]) {\n    args[\"user-data-dir\"] = paths.data\n  }\n\n  if (!args[\"extensions-dir\"]) {\n    args[\"extensions-dir\"] = path.join(args[\"user-data-dir\"], \"extensions\")\n  }\n\n  if (!args[\"session-socket\"]) {\n    args[\"session-socket\"] = path.join(args[\"user-data-dir\"], \"code-server-ipc.sock\")\n  }\n  process.env.CODE_SERVER_SESSION_SOCKET = args[\"session-socket\"]\n\n  // --verbose takes priority over --log and --log takes priority over the\n  // environment variable.\n  if (args.verbose) {\n    args.log = LogLevel.Trace\n  } else if (\n    !args.log &&\n    process.env.LOG_LEVEL &&\n    Object.values(LogLevel).includes(process.env.LOG_LEVEL as LogLevel)\n  ) {\n    args.log = process.env.LOG_LEVEL as LogLevel\n  }\n\n  // Sync --log, --verbose, the environment variable, and logger level.\n  if (args.log) {\n    process.env.LOG_LEVEL = args.log\n  }\n  switch (args.log) {\n    case LogLevel.Trace:\n      logger.level = Level.Trace\n      args.verbose = true\n      break\n    case LogLevel.Debug:\n      logger.level = Level.Debug\n      args.verbose = false\n      break\n    case LogLevel.Info:\n      logger.level = Level.Info\n      args.verbose = false\n      break\n    case LogLevel.Warn:\n      logger.level = Level.Warn\n      args.verbose = false\n      break\n    case LogLevel.Error:\n      logger.level = Level.Error\n      args.verbose = false\n      break\n  }\n\n  // Default to using a password.\n  if (!args.auth) {\n    args.auth = AuthType.Password\n  }\n\n  const addr = bindAddrFromAllSources(configArgs || {}, cliArgs)\n  args.host = addr.host\n  args.port = addr.port\n\n  if (args.cert && !args.cert.value) {\n    const { cert, certKey } = await generateCertificate(args[\"cert-host\"] || \"localhost\")\n    args.cert = {\n      value: cert,\n    }\n    args[\"cert-key\"] = certKey\n  }\n\n  let usingEnvPassword = !!process.env.PASSWORD\n  if (process.env.PASSWORD) {\n    args.password = process.env.PASSWORD\n  }\n\n  if (process.env.CS_DISABLE_FILE_DOWNLOADS?.match(/^(1|true)$/)) {\n    args[\"disable-file-downloads\"] = true\n  }\n\n  if (process.env.CS_DISABLE_GETTING_STARTED_OVERRIDE?.match(/^(1|true)$/)) {\n    args[\"disable-getting-started-override\"] = true\n  }\n\n  if (process.env.CS_DISABLE_PROXY?.match(/^(1|true)$/)) {\n    args[\"disable-proxy\"] = true\n  }\n\n  const usingEnvHashedPassword = !!process.env.HASHED_PASSWORD\n  if (process.env.HASHED_PASSWORD) {\n    args[\"hashed-password\"] = process.env.HASHED_PASSWORD\n    usingEnvPassword = false\n  }\n\n  if (process.env.CODE_SERVER_COOKIE_SUFFIX) {\n    args[\"cookie-suffix\"] = process.env.CODE_SERVER_COOKIE_SUFFIX\n  }\n\n  if (process.env.GITHUB_TOKEN) {\n    args[\"github-auth\"] = process.env.GITHUB_TOKEN\n  }\n\n  if (process.env.CODE_SERVER_IDLE_TIMEOUT_SECONDS) {\n    if (isNaN(Number(process.env.CODE_SERVER_IDLE_TIMEOUT_SECONDS))) {\n      logger.info(\"CODE_SERVER_IDLE_TIMEOUT_SECONDS must be a number\")\n    }\n    if (Number(process.env.CODE_SERVER_IDLE_TIMEOUT_SECONDS) <= 60) {\n      throw new Error(\"--idle-timeout-seconds must be greater than 60 seconds.\")\n    }\n    args[\"idle-timeout-seconds\"] = Number(process.env.CODE_SERVER_IDLE_TIMEOUT_SECONDS)\n  }\n\n  // Ensure they're not readable by child processes.\n  delete process.env.PASSWORD\n  delete process.env.HASHED_PASSWORD\n  delete process.env.GITHUB_TOKEN\n\n  // Filter duplicate proxy domains and remove any leading `*.`.\n  const proxyDomains = new Set((args[\"proxy-domain\"] || []).map((d) => d.replace(/^\\*\\./, \"\")))\n  const finalProxies = []\n\n  for (const proxyDomain of proxyDomains) {\n    if (!proxyDomain.includes(\"{{port}}\")) {\n      finalProxies.push(\"{{port}}.\" + proxyDomain)\n    } else {\n      finalProxies.push(proxyDomain)\n    }\n  }\n\n  // all proxies are of format anyprefix-{{port}}-anysuffix.{{host}}, where {{host}} is optional\n  // e.g. code-8080.domain.tld would match for code-{{port}}.domain.tld and code-{{port}}.{{host}}\n  if (finalProxies.length > 0 && !process.env.VSCODE_PROXY_URI) {\n    process.env.VSCODE_PROXY_URI = `//${finalProxies[0]}`\n  }\n  args[\"proxy-domain\"] = finalProxies\n\n  if (!args[\"app-name\"]) {\n    args[\"app-name\"] = \"code-server\"\n  }\n\n  args._ = getResolvedPathsFromArgs(args)\n\n  return {\n    ...args,\n    usingEnvPassword,\n    usingEnvHashedPassword,\n  } as DefaultedArgs // TODO: Technically no guarantee this is fulfilled.\n}\n\nexport function getResolvedPathsFromArgs(args: UserProvidedArgs): string[] {\n  return (args._ ?? []).map((p) => path.resolve(p))\n}\n\n/**\n * Helper function to return the default config file.\n *\n * @param {string} password - Password passed in (usually from generatePassword())\n * @returns The default config file:\n *\n * - bind-addr: 127.0.0.1:8080\n * - auth: password\n * - password: <password>\n * - cert: false\n */\nexport function defaultConfigFile(password: string): string {\n  return `bind-addr: 127.0.0.1:8080\nauth: password\npassword: ${password}\ncert: false\n`\n}\n\ninterface ConfigArgs extends UserProvidedArgs {\n  config: string\n}\n\n/**\n * Reads the code-server yaml config file and returns it as Args.\n *\n * @param configPath Read the config from configPath instead of $CODE_SERVER_CONFIG or the default.\n */\nexport async function readConfigFile(configPath?: string): Promise<ConfigArgs> {\n  if (!configPath) {\n    configPath = process.env.CODE_SERVER_CONFIG\n    if (!configPath) {\n      configPath = path.join(paths.config, \"config.yaml\")\n    }\n  }\n\n  await fs.mkdir(path.dirname(configPath), { recursive: true })\n\n  try {\n    const generatedPassword = await generatePassword()\n    await fs.writeFile(configPath, defaultConfigFile(generatedPassword), {\n      flag: \"wx\", // wx means to fail if the path exists.\n    })\n    logger.info(`Wrote default config file to ${configPath}`)\n  } catch (error: any) {\n    // EEXIST is fine; we don't want to overwrite existing configurations.\n    if (error.code !== \"EEXIST\") {\n      throw error\n    }\n  }\n\n  const configFile = await fs.readFile(configPath, \"utf8\")\n  return parseConfigFile(configFile, configPath)\n}\n\n/**\n * parseConfigFile parses configFile into ConfigArgs.\n * configPath is used as the filename in error messages\n */\nexport function parseConfigFile(configFile: string, configPath: string): ConfigArgs {\n  if (!configFile) {\n    return { config: configPath }\n  }\n\n  const config = load(configFile, {\n    filename: configPath,\n  })\n  if (!config || typeof config === \"string\") {\n    throw new Error(`invalid config: ${config}`)\n  }\n\n  // We convert the config file into a set of flags.\n  // This is a temporary measure until we add a proper CLI library.\n  const configFileArgv = Object.entries(config)\n    .map(([optName, opt]) => {\n      if (opt === true) {\n        return `--${optName}`\n      } else if (Array.isArray(opt)) {\n        return opt.map((o) => `--${optName}=${o}`)\n      }\n      return `--${optName}=${opt}`\n    })\n    .flat()\n  const args = parse(configFileArgv, {\n    configFile: configPath,\n  })\n  return {\n    ...args,\n    config: configPath,\n  }\n}\n\nfunction parseBindAddr(bindAddr: string): Addr {\n  const u = new URL(`http://${bindAddr}`)\n  return {\n    host: u.hostname,\n    // With the http scheme 80 will be dropped so assume it's 80 if missing.\n    // This means --bind-addr <addr> without a port will default to 80 as well\n    // and not the code-server default.\n    port: u.port ? parseInt(u.port, 10) : 80,\n  }\n}\n\ninterface Addr {\n  host: string\n  port: number\n}\n\n/**\n * This function creates the bind address\n * using the CLI args.\n */\nexport function bindAddrFromArgs(addr: Addr, args: UserProvidedArgs): Addr {\n  addr = { ...addr }\n  if (args[\"bind-addr\"]) {\n    addr = parseBindAddr(args[\"bind-addr\"])\n  }\n  if (process.env.CODE_SERVER_HOST) {\n    addr.host = process.env.CODE_SERVER_HOST\n  }\n  if (args.host) {\n    addr.host = args.host\n  }\n\n  if (process.env.PORT) {\n    addr.port = parseInt(process.env.PORT, 10)\n  }\n  if (args.port !== undefined) {\n    addr.port = args.port\n  }\n  return addr\n}\n\nfunction bindAddrFromAllSources(...argsConfig: UserProvidedArgs[]): Addr {\n  let addr: Addr = {\n    host: \"localhost\",\n    port: 8080,\n  }\n\n  for (const args of argsConfig) {\n    addr = bindAddrFromArgs(addr, args)\n  }\n\n  return addr\n}\n\n/**\n * Determine if it looks like the user is trying to open a file or folder in an\n * existing instance. The arguments here should be the arguments the user\n * explicitly passed on the command line, *NOT DEFAULTS* or the configuration.\n */\nexport const shouldOpenInExistingInstance = async (\n  args: UserProvidedArgs,\n  sessionSocket: string,\n): Promise<string | undefined> => {\n  // Always use the existing instance if we're running from VS Code's terminal.\n  if (process.env.VSCODE_IPC_HOOK_CLI) {\n    logger.debug(\"Found VSCODE_IPC_HOOK_CLI\")\n    return process.env.VSCODE_IPC_HOOK_CLI\n  }\n\n  const paths = getResolvedPathsFromArgs(args)\n  const client = new EditorSessionManagerClient(sessionSocket)\n\n  // If these flags are set then assume the user is trying to open in an\n  // existing instance since these flags have no effect otherwise.  That means\n  // if there is no existing instance we should error rather than falling back\n  // to spawning code-server normally.\n  const openInFlagCount = [\"reuse-window\", \"new-window\"].reduce((prev, cur) => {\n    return args[cur as keyof UserProvidedArgs] ? prev + 1 : prev\n  }, 0)\n  if (openInFlagCount > 0) {\n    logger.debug(\"Found --reuse-window or --new-window\")\n    const socketPath = await client.getConnectedSocketPath(paths[0])\n    if (!socketPath) {\n      throw new Error(`No opened code-server instances found to handle ${paths[0]}`)\n    }\n    return socketPath\n  }\n\n  // It's possible the user is trying to spawn another instance of code-server.\n  // 1. Check if any unrelated flags are set (this should only run when\n  //    code-server is invoked exactly like this: `code-server my-file`).\n  // 2. That a file or directory was passed.\n  // 3. That the socket is active.\n  // 4. That an instance exists to handle the path (implied by #3).\n  if (Object.keys(args).length === 1 && typeof args._ !== \"undefined\" && args._.length > 0) {\n    if (!(await client.canConnect())) {\n      return undefined\n    }\n    const socketPath = await client.getConnectedSocketPath(paths[0])\n    if (socketPath) {\n      logger.debug(\"Found existing code-server socket\")\n      return socketPath\n    }\n  }\n\n  return undefined\n}\n\n/**\n * Arguments for running Code's server.\n *\n * A subset of ../../lib/vscode/src/vs/server/node/serverEnvironmentService.ts:90\n */\nexport interface CodeArgs extends UserProvidedCodeArgs {\n  \"accept-server-license-terms\"?: boolean\n  \"connection-token\"?: string\n  help: boolean\n  port?: string\n  version: boolean\n  \"without-connection-token\"?: boolean\n  \"without-browser-env-var\"?: boolean\n  compatibility?: string\n  log?: string[]\n}\n\n/**\n * Convert our arguments to equivalent VS Code server arguments.\n * Does not add any extra arguments.\n */\nexport const toCodeArgs = async (args: DefaultedArgs): Promise<CodeArgs> => {\n  return {\n    ...args,\n    /** Type casting. */\n    help: !!args.help,\n    version: !!args.version,\n    port: args.port?.toString(),\n    log: args.log ? [args.log] : undefined,\n  }\n}\n"
  },
  {
    "path": "src/node/constants.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport type { JSONSchemaForNPMPackageJsonFiles } from \"@schemastore/package\"\nimport * as os from \"os\"\nimport * as path from \"path\"\n\nexport function getPackageJson(relativePath: string): JSONSchemaForNPMPackageJsonFiles {\n  let pkg = {}\n  try {\n    pkg = require(relativePath)\n  } catch (error: any) {\n    logger.warn(error.message)\n  }\n\n  return pkg\n}\n\nexport const rootPath = path.resolve(__dirname, \"../..\")\nexport const vsRootPath = path.join(rootPath, \"lib/vscode\")\nconst PACKAGE_JSON = \"package.json\"\nconst pkg = getPackageJson(`${rootPath}/${PACKAGE_JSON}`)\nconst codePkg = getPackageJson(`${vsRootPath}/${PACKAGE_JSON}`) || { version: \"0.0.0\" }\nexport const version = pkg.version || \"development\"\nexport const commit = pkg.commit || \"development\"\nexport const codeVersion = codePkg.version || \"development\"\nexport const tmpdir = path.join(os.tmpdir(), \"code-server\")\nexport const isDevMode = commit === \"development\"\nexport const httpProxyUri =\n  process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy\n\n/**\n * getVersionString returns a human-readable version string suitable\n * for outputting to the console.\n */\nexport function getVersionString(): string {\n  return [version, commit, \"with Code\", codeVersion].join(\" \")\n}\n\n/**\n * getVersionJsonString returns a machine-readable version string\n * suitable for outputting to the console.\n */\nexport function getVersionJsonString(): string {\n  return JSON.stringify({\n    codeServer: version,\n    commit,\n    vscode: codeVersion,\n  })\n}\n"
  },
  {
    "path": "src/node/entry.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { optionDescriptions, parse, readConfigFile, setDefaults, shouldOpenInExistingInstance } from \"./cli\"\nimport { getVersionString, getVersionJsonString } from \"./constants\"\nimport { openInExistingInstance, runCodeServer, runCodeCli, shouldSpawnCliProcess } from \"./main\"\nimport { isChild, wrapper } from \"./wrapper\"\n\nasync function entry(): Promise<void> {\n  // There's no need to check flags like --help or to spawn in an existing\n  // instance for the child process because these would have already happened in\n  // the parent and the child wouldn't have been spawned. We also get the\n  // arguments from the parent so we don't have to parse twice and to account\n  // for environment manipulation (like how PASSWORD gets removed to avoid\n  // leaking to child processes).\n  if (isChild(wrapper)) {\n    const args = await wrapper.handshake()\n    wrapper.preventExit()\n    const server = await runCodeServer(args)\n    wrapper.onDispose(() => server.dispose())\n    return\n  }\n\n  const cliArgs = parse(process.argv.slice(2))\n  const configArgs = await readConfigFile(cliArgs.config)\n  const args = await setDefaults(cliArgs, configArgs)\n\n  if (args.help) {\n    console.log(\"code-server\", getVersionString())\n    console.log(\"\")\n    console.log(`Usage: code-server [options] [path]`)\n    console.log(`    - Opening a directory: code-server ./path/to/your/project`)\n    console.log(`    - Opening a saved workspace: code-server ./path/to/your/project.code-workspace`)\n    console.log(\"\")\n    console.log(\"Options\")\n    optionDescriptions().forEach((description) => {\n      console.log(\"\", description)\n    })\n    return\n  }\n\n  if (args.version) {\n    if (args.json) {\n      console.log(getVersionJsonString())\n    } else {\n      console.log(getVersionString())\n    }\n    return\n  }\n\n  if (shouldSpawnCliProcess(args)) {\n    logger.debug(\"Found VS Code arguments; spawning VS Code CLI\")\n    return runCodeCli(args)\n  }\n\n  const socketPath = await shouldOpenInExistingInstance(cliArgs, args[\"session-socket\"])\n  if (socketPath) {\n    logger.debug(\"Trying to open in existing instance\")\n    return openInExistingInstance(args, socketPath)\n  }\n\n  return wrapper.start(args)\n}\n\nentry().catch((error) => {\n  logger.error(error.message)\n  wrapper.exit(error)\n})\n"
  },
  {
    "path": "src/node/heart.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport { Emitter } from \"../common/emitter\"\n\n/**\n * Provides a heartbeat using a local file to indicate activity.\n */\nexport class Heart {\n  private heartbeatTimer?: NodeJS.Timeout\n  private heartbeatInterval = 60000\n  public lastHeartbeat = 0\n  private readonly _onChange = new Emitter<\"alive\" | \"expired\" | \"unknown\">()\n  readonly onChange = this._onChange.event\n  private state: \"alive\" | \"expired\" | \"unknown\" = \"expired\"\n\n  public constructor(\n    private readonly heartbeatPath: string,\n    private readonly isActive: () => Promise<boolean>,\n  ) {\n    this.beat = this.beat.bind(this)\n    this.alive = this.alive.bind(this)\n  }\n\n  private setState(state: typeof this.state) {\n    if (this.state !== state) {\n      this.state = state\n      this._onChange.emit(this.state)\n    }\n  }\n\n  public alive(): boolean {\n    const now = Date.now()\n    return now - this.lastHeartbeat < this.heartbeatInterval\n  }\n  /**\n   * Write to the heartbeat file if we haven't already done so within the\n   * timeout and start or reset a timer that keeps running as long as there is\n   * activity. Failures are logged as warnings.\n   */\n  public async beat(): Promise<void> {\n    if (this.alive()) {\n      this.setState(\"alive\")\n      return\n    }\n\n    logger.debug(\"heartbeat\")\n    this.lastHeartbeat = Date.now()\n    if (typeof this.heartbeatTimer !== \"undefined\") {\n      clearTimeout(this.heartbeatTimer)\n    }\n\n    this.heartbeatTimer = setTimeout(async () => {\n      try {\n        if (await this.isActive()) {\n          this.beat()\n        } else {\n          this.setState(\"expired\")\n        }\n      } catch (error: unknown) {\n        logger.warn((error as Error).message)\n        this.setState(\"unknown\")\n      }\n    }, this.heartbeatInterval)\n\n    this.setState(\"alive\")\n\n    try {\n      return await fs.writeFile(this.heartbeatPath, \"\")\n    } catch (error: any) {\n      logger.warn(error.message)\n    }\n  }\n\n  /**\n   * Call to clear any heartbeatTimer for shutdown.\n   */\n  public dispose(): void {\n    if (typeof this.heartbeatTimer !== \"undefined\") {\n      clearTimeout(this.heartbeatTimer)\n    }\n  }\n}\n"
  },
  {
    "path": "src/node/http.ts",
    "content": "import { field, logger } from \"@coder/logger\"\nimport * as express from \"express\"\nimport * as http from \"http\"\nimport * as net from \"net\"\nimport qs from \"qs\"\nimport { Disposable } from \"../common/emitter\"\nimport { HttpCode, HttpError } from \"../common/http\"\nimport { normalize } from \"../common/util\"\nimport { AuthType, DefaultedArgs } from \"./cli\"\nimport { version as codeServerVersion } from \"./constants\"\nimport { Heart } from \"./heart\"\nimport { CoderSettings, SettingsProvider } from \"./settings\"\nimport { UpdateProvider } from \"./update\"\nimport {\n  getPasswordMethod,\n  IsCookieValidArgs,\n  isCookieValid,\n  sanitizeString,\n  escapeHtml,\n  escapeJSON,\n  splitOnFirstEquals,\n} from \"./util\"\n\n/**\n * Base options included on every page.\n */\nexport interface ClientConfiguration {\n  codeServerVersion: string\n  /** Relative path from this page to the root.  No trailing slash. */\n  base: string\n  /** Relative path from this page to the static root.  No trailing slash. */\n  csStaticBase: string\n}\n\ndeclare global {\n  // eslint-disable-next-line @typescript-eslint/no-namespace\n  namespace Express {\n    export interface Request {\n      args: DefaultedArgs\n      heart: Heart\n      settings: SettingsProvider<CoderSettings>\n      updater: UpdateProvider\n      cookieSessionName: string\n    }\n  }\n}\n\nexport const createClientConfiguration = (req: express.Request): ClientConfiguration => {\n  const base = relativeRoot(req.originalUrl)\n\n  return {\n    base,\n    csStaticBase: base + \"/_static\",\n    codeServerVersion,\n  }\n}\n\n/**\n * Replace common variable strings in HTML templates.\n */\nexport const replaceTemplates = <T extends object>(\n  req: express.Request,\n  content: string,\n  extraOpts?: Omit<T, \"base\" | \"csStaticBase\" | \"logLevel\">,\n): string => {\n  const serverOptions: ClientConfiguration = {\n    ...createClientConfiguration(req),\n    ...extraOpts,\n  }\n\n  return content\n    .replace(/{{TO}}/g, (typeof req.query.to === \"string\" && escapeHtml(req.query.to)) || \"/\")\n    .replace(/{{BASE}}/g, serverOptions.base)\n    .replace(/{{CS_STATIC_BASE}}/g, serverOptions.csStaticBase)\n    .replace(\"{{OPTIONS}}\", () => escapeJSON(serverOptions))\n}\n\n/**\n * Throw an error if proxy is not enabled. Call `next` if provided.\n */\nexport const ensureProxyEnabled = (req: express.Request, _?: express.Response, next?: express.NextFunction): void => {\n  if (!proxyEnabled(req)) {\n    throw new HttpError(\"Forbidden\", HttpCode.Forbidden)\n  }\n  if (next) {\n    next()\n  }\n}\n\n/**\n * Return true if proxy is enabled.\n */\nexport const proxyEnabled = (req: express.Request): boolean => {\n  return !req.args[\"disable-proxy\"]\n}\n\n/**\n * Throw an error if not authorized. Call `next` if provided.\n */\nexport const ensureAuthenticated = async (\n  req: express.Request,\n  _?: express.Response,\n  next?: express.NextFunction,\n): Promise<void> => {\n  const isAuthenticated = await authenticated(req)\n  if (!isAuthenticated) {\n    throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n  }\n  if (next) {\n    next()\n  }\n}\n\n/**\n * Return true if authenticated via cookies.\n */\nexport const authenticated = async (req: express.Request): Promise<boolean> => {\n  switch (req.args.auth) {\n    case AuthType.None: {\n      return true\n    }\n    case AuthType.Password: {\n      // The password is stored in the cookie after being hashed.\n      const hashedPasswordFromArgs = req.args[\"hashed-password\"]\n      const passwordMethod = getPasswordMethod(hashedPasswordFromArgs)\n      const isCookieValidArgs: IsCookieValidArgs = {\n        passwordMethod,\n        cookieKey: sanitizeString(req.cookies[req.cookieSessionName]),\n        passwordFromArgs: req.args.password || \"\",\n        hashedPasswordFromArgs: req.args[\"hashed-password\"],\n      }\n\n      return await isCookieValid(isCookieValidArgs)\n    }\n    default: {\n      throw new Error(`Unsupported auth type ${req.args.auth}`)\n    }\n  }\n}\n\n/**\n * Get the relative path that will get us to the root of the page. For each\n * slash we need to go up a directory.  Will not have a trailing slash.\n *\n * For example:\n *\n * / => .\n * /foo => .\n * /foo/ => ./..\n * /foo/bar => ./..\n * /foo/bar/ => ./../..\n *\n * All paths must be relative in order to work behind a reverse proxy since we\n * we do not know the base path.  Anything that needs to be absolute (for\n * example cookies) must get the base path from the frontend.\n *\n * All relative paths must be prefixed with the relative root to ensure they\n * work no matter the depth at which they happen to appear.\n *\n * For Express `req.originalUrl` should be used as they remove the base from the\n * standard `url` property making it impossible to get the true depth.\n */\nexport const relativeRoot = (originalUrl: string): string => {\n  const depth = (originalUrl.split(\"?\", 1)[0].match(/\\//g) || []).length\n  return normalize(\"./\" + (depth > 1 ? \"../\".repeat(depth - 1) : \"\"))\n}\n\n/**\n * A helper function to construct a redirect path based on\n * an Express Request, query and a path to redirect to.\n *\n * Redirect path is relative to `/${to}`.\n */\nexport const constructRedirectPath = (req: express.Request, query: qs.ParsedQs, to: string): string => {\n  const relativePath = normalize(`${relativeRoot(req.originalUrl)}/${to}`, true)\n  // %2f or %2F are both equalivent to an encoded slash /\n  const queryString = qs.stringify(query).replace(/%2[fF]/g, \"/\")\n  const redirectPath = `${relativePath}${queryString ? `?${queryString}` : \"\"}`\n\n  return redirectPath\n}\n\n/**\n * Redirect relatively to `/${to}`. Query variables on the current URI will be\n * preserved.  `to` should be a simple path without any query parameters\n * `override` will merge with the existing query (use `undefined` to unset).\n */\nexport const redirect = (req: express.Request, res: express.Response, to: string, override: qs.ParsedQs = {}): void => {\n  const query = Object.assign({}, req.query, override)\n  Object.keys(override).forEach((key) => {\n    if (typeof override[key] === \"undefined\") {\n      delete query[key]\n    }\n  })\n\n  const redirectPath = constructRedirectPath(req, query, to)\n  logger.debug(`redirecting from ${req.originalUrl} to ${redirectPath}`)\n  res.redirect(redirectPath)\n}\n\n/**\n * Get the value that should be used for setting a cookie domain. This will\n * allow the user to authenticate once no matter what sub-domain they use to log\n * in. This will use the highest level proxy domain (e.g. `coder.com` over\n * `test.coder.com` if both are specified).\n */\nexport const getCookieDomain = (host: string, proxyDomains: string[]): string | undefined => {\n  const idx = host.lastIndexOf(\":\")\n  host = idx !== -1 ? host.substring(0, idx) : host\n  // If any of these are true we will still set cookies but without an explicit\n  // `Domain` attribute on the cookie.\n  if (\n    // The host can be be blank or missing so there's nothing we can set.\n    !host ||\n    // IP addresses can't have subdomains so there's no value in setting the\n    // domain for them. Assume that anything with a : is ipv6 (valid domain name\n    // characters are alphanumeric or dashes)...\n    host.includes(\":\") ||\n    // ...and that anything entirely numbers and dots is ipv4 (currently tlds\n    // cannot be entirely numbers).\n    !/[^0-9.]/.test(host) ||\n    // localhost subdomains don't seem to work at all (browser bug?). A cookie\n    // set at dev.localhost cannot be read by 8080.dev.localhost.\n    host.endsWith(\".localhost\") ||\n    // Domains without at least one dot (technically two since domain.tld will\n    // become .domain.tld) are considered invalid according to the spec so don't\n    // set the domain for them. In my testing though localhost is the only\n    // problem (the browser just doesn't store the cookie at all). localhost has\n    // an additional problem which is that a reverse proxy might give\n    // code-server localhost even though the domain is really domain.tld (by\n    // default NGINX does this).\n    !host.includes(\".\")\n  ) {\n    logger.debug(\"no valid cookie domain\", field(\"host\", host))\n    return undefined\n  }\n\n  proxyDomains.forEach((domain) => {\n    if (host.endsWith(domain) && domain.length < host.length) {\n      host = domain\n    }\n  })\n\n  logger.debug(\"got cookie domain\", field(\"host\", host))\n  return host || undefined\n}\n\n/**\n * Return a function capable of fully disposing an HTTP server.\n */\nexport function disposer(server: http.Server): Disposable[\"dispose\"] {\n  const sockets = new Set<net.Socket>()\n  let cleanupTimeout: undefined | NodeJS.Timeout\n\n  server.on(\"connection\", (socket) => {\n    sockets.add(socket)\n\n    socket.on(\"close\", () => {\n      sockets.delete(socket)\n\n      if (cleanupTimeout && sockets.size === 0) {\n        clearTimeout(cleanupTimeout)\n        cleanupTimeout = undefined\n      }\n    })\n  })\n\n  return () => {\n    return new Promise<void>((resolve, reject) => {\n      // The whole reason we need this disposer is because close will not\n      // actually close anything; it only prevents future connections then waits\n      // until everything is closed.\n      server.close((err) => {\n        if (err) {\n          return reject(err)\n        }\n\n        resolve()\n      })\n\n      // If there are sockets remaining we might need to force close them or\n      // this promise might never resolve.\n      if (sockets.size > 0) {\n        // Give sockets a chance to close up shop.\n        cleanupTimeout = setTimeout(() => {\n          cleanupTimeout = undefined\n\n          for (const socket of sockets.values()) {\n            console.warn(\"a socket was left hanging\")\n            socket.destroy()\n          }\n        }, 1000)\n      }\n    })\n  }\n}\n\n/**\n * Get the options for setting a cookie.  The options must be identical for\n * setting and unsetting cookies otherwise they are considered separate.\n */\nexport const getCookieOptions = (req: express.Request): express.CookieOptions => {\n  // Normally we set paths relatively.  However browsers do not appear to allow\n  // cookies to be set relatively which means we need an absolute path.  We\n  // cannot be guaranteed we know the path since a reverse proxy might have\n  // rewritten it.  That means we need to get the path from the frontend.\n\n  // The reason we need to set the path (as opposed to defaulting to /) is to\n  // avoid code-server instances on different sub-paths clobbering each other or\n  // from accessing each other's tokens (and to prevent other services from\n  // accessing code-server's tokens).\n\n  // When logging in or out the request must include the href (the full current\n  // URL of that page) and the relative path to the root as given to it by the\n  // backend.  Using these two we can determine the true absolute root.\n  const url = new URL(\n    req.query.base || req.body?.base || \"/\",\n    req.query.href || req.body?.href || \"http://\" + (req.headers.host || \"localhost\"),\n  )\n  return {\n    domain: getCookieDomain(url.host, req.args[\"proxy-domain\"]),\n    path: normalize(url.pathname) || \"/\",\n    sameSite: \"lax\",\n  }\n}\n\n/**\n * Return the full path to the current page, preserving any trailing slash.\n */\nexport const self = (req: express.Request): string => {\n  return normalize(`${req.baseUrl}${req.originalUrl.endsWith(\"/\") ? \"/\" : \"\"}`, true)\n}\n\nfunction getFirstHeader(req: http.IncomingMessage, headerName: string): string | undefined {\n  const val = req.headers[headerName]\n  return Array.isArray(val) ? val[0] : val\n}\n\n/**\n * Throw a forbidden error if origin checks fail. Call `next` if provided.\n */\nexport function ensureOrigin(req: express.Request, _?: express.Response, next?: express.NextFunction): void {\n  try {\n    authenticateOrigin(req)\n    if (next) {\n      next()\n    }\n  } catch (error) {\n    logger.debug(`${error instanceof Error ? error.message : error}; blocking request to ${req.originalUrl}`)\n    throw new HttpError(\"Forbidden\", HttpCode.Forbidden)\n  }\n}\n\n/**\n * Authenticate the request origin against the host.  Throw if invalid.\n */\nexport function authenticateOrigin(req: express.Request): void {\n  // A missing origin probably means the source is non-browser.  Not sure we\n  // have a use case for this but let it through.\n  const originRaw = getFirstHeader(req, \"origin\")\n  if (!originRaw) {\n    return\n  }\n\n  let origin: string\n  try {\n    origin = new URL(originRaw).host.trim().toLowerCase()\n  } catch (error) {\n    throw new Error(`unable to parse malformed origin \"${originRaw}\"`)\n  }\n\n  const trustedOrigins = req.args[\"trusted-origins\"] || []\n  if (trustedOrigins.includes(origin) || trustedOrigins.includes(\"*\")) {\n    return\n  }\n\n  const host = getHost(req)\n  if (typeof host === \"undefined\") {\n    // A missing host likely means the reverse proxy has not been configured to\n    // forward the host which means we cannot perform the check.  Emit an error\n    // so an admin can fix the issue.\n    logger.error(\"No host headers found\")\n    logger.error(\"Are you behind a reverse proxy that does not forward the host?\")\n    throw new Error(\"no host headers found\")\n  }\n\n  if (host !== origin) {\n    throw new Error(`host \"${host}\" does not match origin \"${origin}\"`)\n  }\n}\n\n/**\n * Get the host from headers.  It will be trimmed and lowercased.\n */\nexport function getHost(req: express.Request): string | undefined {\n  // Honor Forwarded if present.\n  const forwardedRaw = getFirstHeader(req, \"forwarded\")\n  if (forwardedRaw) {\n    const parts = forwardedRaw.split(/[;,]/)\n    for (let i = 0; i < parts.length; ++i) {\n      const [key, value] = splitOnFirstEquals(parts[i])\n      if (key.trim().toLowerCase() === \"host\" && value) {\n        return value.trim().toLowerCase()\n      }\n    }\n  }\n\n  // Honor X-Forwarded-Host if present.  Some reverse proxies will set multiple\n  // comma-separated hosts.\n  const xHost = getFirstHeader(req, \"x-forwarded-host\")\n  if (xHost) {\n    const firstXHost = xHost.split(\",\")[0]\n    if (firstXHost) {\n      return firstXHost.trim().toLowerCase()\n    }\n  }\n\n  const host = getFirstHeader(req, \"host\")\n  return host ? host.trim().toLowerCase() : undefined\n}\n"
  },
  {
    "path": "src/node/i18n/index.ts",
    "content": "import { promises as fs } from \"fs\"\nimport i18next, { init } from \"i18next\"\nimport * as en from \"./locales/en.json\"\nimport * as ja from \"./locales/ja.json\"\nimport * as th from \"./locales/th.json\"\nimport * as ur from \"./locales/ur.json\"\nimport * as zhCn from \"./locales/zh-cn.json\"\n\nconst defaultResources = {\n  en: {\n    translation: en,\n  },\n  \"zh-cn\": {\n    translation: zhCn,\n  },\n  th: {\n    translation: th,\n  },\n  ja: {\n    translation: ja,\n  },\n  ur: {\n    translation: ur,\n  },\n}\n\nexport async function loadCustomStrings(filePath: string): Promise<void> {\n  try {\n    // Read custom strings from file path only\n    const fileContent = await fs.readFile(filePath, \"utf8\")\n    const customStringsData = JSON.parse(fileContent)\n\n    // User-provided strings override all languages.\n    Object.keys(defaultResources).forEach((locale) => {\n      i18next.addResourceBundle(locale, \"translation\", customStringsData)\n    })\n  } catch (error) {\n    if (error && typeof error === \"object\" && \"code\" in error && error.code === \"ENOENT\") {\n      throw new Error(`Custom strings file not found: ${filePath}\\nPlease ensure the file exists and is readable.`)\n    } else if (error instanceof SyntaxError) {\n      throw new Error(`Invalid JSON in custom strings file: ${filePath}\\n${error.message}`)\n    } else {\n      throw new Error(\n        `Failed to load custom strings from ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n      )\n    }\n  }\n}\n\ninit({\n  lng: \"en\",\n  fallbackLng: \"en\", // language to use if translations in user language are not available.\n  returnNull: false,\n  lowerCaseLng: true,\n  debug: process.env.NODE_ENV === \"development\",\n  resources: defaultResources,\n  showSupportNotice: false,\n})\n\nexport default i18next\n"
  },
  {
    "path": "src/node/i18n/locales/en.json",
    "content": "{\n  \"LOGIN_TITLE\": \"{{app}} login\",\n  \"LOGIN_BELOW\": \"Please log in below.\",\n  \"WELCOME\": \"Welcome to {{app}}\",\n  \"LOGIN_PASSWORD\": \"Check the config file for the password.\",\n  \"LOGIN_USING_ENV_PASSWORD\": \"Password was set from $PASSWORD.\",\n  \"LOGIN_USING_HASHED_PASSWORD\": \"Password was set from $HASHED_PASSWORD.\",\n  \"SUBMIT\": \"SUBMIT\",\n  \"PASSWORD_PLACEHOLDER\": \"PASSWORD\",\n  \"LOGIN_RATE_LIMIT\": \"Login rate limited!\",\n  \"MISS_PASSWORD\": \"Missing password\",\n  \"INCORRECT_PASSWORD\": \"Incorrect password\"\n}\n"
  },
  {
    "path": "src/node/i18n/locales/ja.json",
    "content": "{\n  \"LOGIN_TITLE\": \"{{app}} ログイン\",\n  \"LOGIN_BELOW\": \"以下によりログインしてください。\",\n  \"WELCOME\": \"ようこそ {{app}} へ！\",\n  \"LOGIN_PASSWORD\": \"パスワードは設定ファイルを確認してください。\",\n  \"LOGIN_USING_ENV_PASSWORD\": \"パスワードは環境変数 $PASSWORD で設定されています。\",\n  \"LOGIN_USING_HASHED_PASSWORD\": \"パスワードは環境変数 $HASHED_PASSWORD で設定されています。\",\n  \"SUBMIT\": \"実行\",\n  \"PASSWORD_PLACEHOLDER\": \"パスワード\",\n  \"LOGIN_RATE_LIMIT\": \"ログイン制限を超えました！\",\n  \"MISS_PASSWORD\": \"パスワードを入力してください。\",\n  \"INCORRECT_PASSWORD\": \"パスワードが間違っています。\"\n}\n"
  },
  {
    "path": "src/node/i18n/locales/th.json",
    "content": "{\n  \"LOGIN_TITLE\": \"เข้าสู่ระบบ {{app}}\",\n  \"LOGIN_BELOW\": \"กรุณาเข้าสู่ระบบด้านล่าง\",\n  \"WELCOME\": \"ยินดีต้อนรับสู่ {{app}}\",\n  \"LOGIN_PASSWORD\": \"ตรวจสอบไฟล์กำหนดค่าเพื่อดูรหัสผ่าน\",\n  \"LOGIN_USING_ENV_PASSWORD\": \"รหัสผ่านถูกกำหนดเป็น $PASSWORD\",\n  \"LOGIN_USING_HASHED_PASSWORD\": \"รรหัสผ่านถูกกำหนดเป็น $HASHED_PASSWORD\",\n  \"SUBMIT\": \"ส่ง\",\n  \"PASSWORD_PLACEHOLDER\": \"รหัสผ่าน\",\n  \"LOGIN_RATE_LIMIT\": \"ถึงขีดจำกัดอัตราการเข้าสู่ระบบ!\",\n  \"MISS_PASSWORD\": \"รหัสผ่านหายไป\",\n  \"INCORRECT_PASSWORD\": \"รหัสผ่านไม่ถูกต้อง\"\n}\n"
  },
  {
    "path": "src/node/i18n/locales/ur.json",
    "content": "{\n  \"LOGIN_TITLE\": \"{{app}} لاگ ان کریں\",\n  \"LOGIN_BELOW\": \"براہ کرم نیچے لاگ ان کریں۔\",\n  \"WELCOME\": \"میں خوش آمدید {{app}}\",\n  \"LOGIN_PASSWORD\": \"پاس ورڈ کے لیے کنفگ فائل چیک کریں۔\",\n  \"LOGIN_USING_ENV_PASSWORD\": \"پاس ورڈ $PASSWORD سے سیٹ کیا گیا تھا۔\",\n  \"LOGIN_USING_HASHED_PASSWORD\": \"پاس ورڈ $HASHED_PASSWORD سے سیٹ کیا گیا تھا۔\",\n  \"SUBMIT\": \"جمع کرائیں\",\n  \"PASSWORD_PLACEHOLDER\": \"پاس ورڈ\",\n  \"LOGIN_RATE_LIMIT\": \"لاگ ان کی شرح محدود!\",\n  \"MISS_PASSWORD\": \"پاس ورڈ غائب ہے۔\",\n  \"INCORRECT_PASSWORD\": \"غلط پاس ورڈ\"\n}\n"
  },
  {
    "path": "src/node/i18n/locales/zh-cn.json",
    "content": "{\n  \"LOGIN_TITLE\": \"{{app}} 登录\",\n  \"LOGIN_BELOW\": \"请在下面登录。\",\n  \"WELCOME\": \"欢迎来到 {{app}}\",\n  \"LOGIN_PASSWORD\": \"查看配置文件中的密码。\",\n  \"LOGIN_USING_ENV_PASSWORD\": \"密码在 $PASSWORD 中设置。\",\n  \"LOGIN_USING_HASHED_PASSWORD\": \"密码在 $HASHED_PASSWORD 中设置。\",\n  \"SUBMIT\": \"提交\",\n  \"PASSWORD_PLACEHOLDER\": \"密码\",\n  \"LOGIN_RATE_LIMIT\": \"登录速率限制!\",\n  \"MISS_PASSWORD\": \"缺少密码\",\n  \"INCORRECT_PASSWORD\": \"密码不正确\"\n}\n"
  },
  {
    "path": "src/node/main.ts",
    "content": "import { field, logger } from \"@coder/logger\"\nimport http from \"http\"\nimport * as os from \"os\"\nimport * as path from \"path\"\nimport { Disposable } from \"../common/emitter\"\nimport { plural } from \"../common/util\"\nimport { createApp, ensureAddress } from \"./app\"\nimport { AuthType, DefaultedArgs, Feature, toCodeArgs, UserProvidedArgs } from \"./cli\"\nimport { commit, version, vsRootPath } from \"./constants\"\nimport { loadCustomStrings } from \"./i18n\"\nimport { register } from \"./routes\"\nimport { VSCodeModule } from \"./routes/vscode\"\nimport { isDirectory, open } from \"./util\"\nimport { wrapper } from \"./wrapper\"\n\n/**\n * Return true if the user passed an extension-related VS Code flag.\n */\nexport const shouldSpawnCliProcess = (args: UserProvidedArgs): boolean => {\n  return (\n    !!args[\"list-extensions\"] ||\n    !!args[\"install-extension\"] ||\n    !!args[\"uninstall-extension\"] ||\n    !!args[\"locate-extension\"]\n  )\n}\n\n/**\n * This is copy of OpenCommandPipeArgs from\n * ../../lib/vscode/src/vs/workbench/api/node/extHostCLIServer.ts:15\n *\n * Arguments supported by Code's socket.  It can be used to perform actions from\n * the CLI in a running instance of Code (for example to open a file).\n *\n * TODO: Can we import this (and other types) directly?\n */\nexport interface OpenCommandPipeArgs {\n  type: \"open\"\n  fileURIs?: string[]\n  folderURIs: string[]\n  forceNewWindow?: boolean\n  diffMode?: boolean\n  addMode?: boolean\n  gotoLineMode?: boolean\n  forceReuseWindow?: boolean\n  waitMarkerFilePath?: string\n}\n\n/**\n * Run Code's CLI for things like managing extensions.\n */\nexport const runCodeCli = async (args: DefaultedArgs): Promise<void> => {\n  logger.debug(\"Running Code CLI\")\n  try {\n    // See vscode.loadVSCode for more on this jank.\n    process.env.CODE_SERVER_PARENT_PID = process.pid.toString()\n    let modPath = path.join(vsRootPath, \"out/server-main.js\")\n    if (os.platform() === \"win32\") {\n      // On Windows, absolute paths of ESM modules must be a valid file URI.\n      modPath = \"file:///\" + modPath.replace(/\\\\/g, \"/\")\n    }\n    const mod = (await eval(`import(\"${modPath}\")`)) as VSCodeModule\n    const serverModule = await mod.loadCodeWithNls()\n    await serverModule.spawnCli(await toCodeArgs(args))\n    // Rather than have the caller handle errors and exit, spawnCli will exit\n    // itself.  Additionally, it does this on a timeout set to 0.  So, try\n    // waiting for VS Code to exit before giving up and doing it ourselves.\n    await new Promise((r) => setTimeout(r, 1000))\n    logger.warn(\"Code never exited\")\n    process.exit(0)\n  } catch (error: any) {\n    // spawnCli catches all errors, but just in case that changes.\n    logger.error(\"Got error from Code\", error)\n    process.exit(1)\n  }\n}\n\nexport const openInExistingInstance = async (args: DefaultedArgs, socketPath: string): Promise<void> => {\n  const pipeArgs: OpenCommandPipeArgs & { fileURIs: string[] } = {\n    type: \"open\",\n    folderURIs: [],\n    fileURIs: [],\n    forceReuseWindow: args[\"reuse-window\"],\n    forceNewWindow: args[\"new-window\"],\n    gotoLineMode: true,\n  }\n  for (let i = 0; i < args._.length; i++) {\n    const fp = args._[i]\n    if (await isDirectory(fp)) {\n      pipeArgs.folderURIs.push(fp)\n    } else {\n      pipeArgs.fileURIs.push(fp)\n    }\n  }\n  if (pipeArgs.forceNewWindow && pipeArgs.fileURIs.length > 0) {\n    logger.error(\"--new-window can only be used with folder paths\")\n    process.exit(1)\n  }\n  if (pipeArgs.folderURIs.length === 0 && pipeArgs.fileURIs.length === 0) {\n    logger.error(\"Please specify at least one file or folder\")\n    process.exit(1)\n  }\n  const vscode = http.request(\n    {\n      path: \"/\",\n      method: \"POST\",\n      socketPath,\n    },\n    (response) => {\n      response.on(\"data\", (message) => {\n        logger.debug(\"got message from Code\", field(\"message\", message.toString()))\n      })\n    },\n  )\n  vscode.on(\"error\", (error: unknown) => {\n    logger.error(\"got error from Code\", field(\"error\", error))\n  })\n  vscode.write(JSON.stringify(pipeArgs))\n  vscode.end()\n}\n\nexport const runCodeServer = async (\n  args: DefaultedArgs,\n): Promise<{ dispose: Disposable[\"dispose\"]; server: http.Server }> => {\n  logger.info(`code-server ${version} ${commit}`)\n\n  // Load custom strings if provided\n  if (args.i18n) {\n    await loadCustomStrings(args.i18n)\n    logger.info(\"Loaded custom strings\")\n  }\n\n  logger.info(`Using user-data-dir ${args[\"user-data-dir\"]}`)\n  logger.debug(`Using extensions-dir ${args[\"extensions-dir\"]}`)\n\n  if (args.auth === AuthType.Password && !args.password && !args[\"hashed-password\"]) {\n    throw new Error(\n      \"Please pass in a password via the config file or environment variable ($PASSWORD or $HASHED_PASSWORD)\",\n    )\n  }\n\n  const app = await createApp(args)\n  const protocol = args.cert ? \"https\" : \"http\"\n  const serverAddress = ensureAddress(app.server, protocol)\n  const { disposeRoutes, heart } = await register(app, args)\n\n  logger.info(`Using config file ${args.config}`)\n  logger.info(`${protocol.toUpperCase()} server listening on ${serverAddress.toString()}`)\n  if (args.auth === AuthType.Password) {\n    logger.info(\"  - Authentication is enabled\")\n    if (args.usingEnvPassword) {\n      logger.info(\"    - Using password from $PASSWORD\")\n    } else if (args.usingEnvHashedPassword) {\n      logger.info(\"    - Using password from $HASHED_PASSWORD\")\n    } else if (args[\"hashed-password\"]) {\n      logger.info(`    - Using hashed-password from ${args.config}`)\n    } else {\n      logger.info(`    - Using password from ${args.config}`)\n    }\n  } else {\n    logger.info(\"  - Authentication is disabled\")\n  }\n\n  if (args.cert) {\n    logger.info(`  - Using certificate for HTTPS: ${args.cert.value}`)\n  } else {\n    logger.info(\"  - Not serving HTTPS\")\n  }\n\n  if (args[\"idle-timeout-seconds\"]) {\n    logger.info(`  - Idle timeout set to ${args[\"idle-timeout-seconds\"]} seconds`)\n\n    let idleShutdownTimer: NodeJS.Timeout | undefined\n    const startIdleShutdownTimer = () => {\n      idleShutdownTimer = setTimeout(() => {\n        logger.warn(`Idle timeout of ${args[\"idle-timeout-seconds\"]} seconds exceeded`)\n        wrapper.exit(0)\n      }, args[\"idle-timeout-seconds\"]! * 1000)\n    }\n\n    startIdleShutdownTimer()\n\n    heart.onChange((state) => {\n      clearTimeout(idleShutdownTimer)\n      if (state === \"expired\") {\n        startIdleShutdownTimer()\n      }\n    })\n  }\n\n  if (args[\"disable-proxy\"]) {\n    logger.info(\"  - Proxy disabled\")\n  } else if (args[\"proxy-domain\"].length > 0) {\n    logger.info(`  - ${plural(args[\"proxy-domain\"].length, \"Proxying the following domain\")}:`)\n    args[\"proxy-domain\"].forEach((domain) => logger.info(`    - ${domain}`))\n  }\n  if (args[\"skip-auth-preflight\"]) {\n    logger.info(\"  - Skipping authentication for preflight requests\")\n  }\n  if (process.env.VSCODE_PROXY_URI) {\n    logger.info(`Using proxy URI in PORTS tab: ${process.env.VSCODE_PROXY_URI}`)\n  }\n\n  const sessionServerAddress = app.editorSessionManagerServer.address()\n  if (sessionServerAddress) {\n    logger.info(`Session server listening on ${sessionServerAddress.toString()}`)\n  }\n\n  if (process.env.EXTENSIONS_GALLERY) {\n    logger.info(\"Using custom extensions gallery\")\n    logger.debug(`  - ${process.env.EXTENSIONS_GALLERY}`)\n  }\n\n  if (args.enable && args.enable.length > 0) {\n    logger.info(\"Enabling the following experimental features:\")\n    args.enable.forEach((feature) => {\n      if (Object.values(Feature).includes(feature as Feature)) {\n        logger.info(`  - \"${feature}\"`)\n      } else {\n        logger.error(`  X \"${feature}\" (unknown feature)`)\n      }\n    })\n    // TODO: Could be nice to add wrapping to the logger?\n    logger.info(\n      \"  The code-server project does not provide stability guarantees or commit to fixing bugs relating to these experimental features. When filing bug reports, please ensure that you can reproduce the bug with all experimental features turned off.\",\n    )\n  }\n\n  if (args.open) {\n    try {\n      await open(serverAddress)\n      logger.info(`Opened ${serverAddress}`)\n    } catch (error) {\n      logger.error(\"Failed to open\", field(\"address\", serverAddress.toString()), field(\"error\", error))\n    }\n  }\n\n  return {\n    server: app.server,\n    dispose: async () => {\n      disposeRoutes()\n      await app.dispose()\n    },\n  }\n}\n"
  },
  {
    "path": "src/node/proxy.ts",
    "content": "import proxyServer from \"http-proxy\"\nimport { HttpCode } from \"../common/http\"\n\nexport const proxy = proxyServer.createProxyServer({})\n\n// The error handler catches when the proxy fails to connect (for example when\n// there is nothing running on the target port).\nproxy.on(\"error\", (error, _, res) => {\n  // This could be for either a web socket or a regular request.  Despite what\n  // the types say, writeHead() will not exist on web socket requests (nor will\n  // status() from Express).  But writing out the code manually does not work\n  // for regular requests thus the branching behavior.\n  if (typeof res.writeHead !== \"undefined\") {\n    res.writeHead(HttpCode.ServerError)\n    res.end(error.message)\n  } else {\n    res.end(`HTTP/1.1 ${HttpCode.ServerError} ${error.message}\\r\\n\\r\\n`)\n  }\n})\n\n// Intercept the response to rewrite absolute redirects against the base path.\n// Is disabled when the request has no base path which means /absproxy is in use.\nproxy.on(\"proxyRes\", (res, req) => {\n  if (res.headers.location && res.headers.location.startsWith(\"/\") && (req as any).base) {\n    res.headers.location = (req as any).base + res.headers.location\n  }\n})\n"
  },
  {
    "path": "src/node/routes/domainProxy.ts",
    "content": "import { Request, Router } from \"express\"\nimport { HttpCode, HttpError } from \"../../common/http\"\nimport { getHost, ensureProxyEnabled, authenticated, ensureAuthenticated, ensureOrigin, redirect, self } from \"../http\"\nimport { proxy } from \"../proxy\"\nimport { Router as WsRouter } from \"../wsRouter\"\n\nexport const router = Router()\n\nconst proxyDomainToRegex = (matchString: string): RegExp => {\n  const escapedMatchString = matchString.replace(/[.*+?^$()|[\\]\\\\]/g, \"\\\\$&\")\n\n  // Replace {{port}} with a regex group to capture the port\n  // Replace {{host}} with .+ to allow any host match (so rely on DNS record here)\n  let regexString = escapedMatchString.replace(\"{{port}}\", \"(\\\\d+)\")\n  regexString = regexString.replace(\"{{host}}\", \".+\")\n\n  regexString = regexString.replace(/[{}]/g, \"\\\\$&\") //replace any '{}' that might be left\n\n  return new RegExp(\"^\" + regexString + \"$\")\n}\n\nlet proxyRegexes: RegExp[] = []\nconst proxyDomainsToRegex = (proxyDomains: string[]): RegExp[] => {\n  if (proxyDomains.length !== proxyRegexes.length) {\n    proxyRegexes = proxyDomains.map(proxyDomainToRegex)\n  }\n  return proxyRegexes\n}\n\n/**\n * Return the port if the request should be proxied.\n *\n * The proxy-domain should be of format anyprefix-{{port}}-anysuffix.{{host}}, where {{host}} is optional\n * e.g. code-8080.domain.tld would match for code-{{port}}.domain.tld and code-{{port}}.{{host}}.\n *\n */\nconst maybeProxy = (req: Request): string | undefined => {\n  const reqDomain = getHost(req)\n  if (reqDomain === undefined) {\n    return undefined\n  }\n\n  const regexs = proxyDomainsToRegex(req.args[\"proxy-domain\"])\n\n  for (const regex of regexs) {\n    const match = reqDomain.match(regex)\n\n    if (match) {\n      return match[1] // match[1] contains the port\n    }\n  }\n\n  return undefined\n}\n\nrouter.all(/.*/, async (req, res, next) => {\n  const port = maybeProxy(req)\n  if (!port) {\n    return next()\n  }\n\n  ensureProxyEnabled(req)\n\n  if (req.method === \"OPTIONS\" && req.args[\"skip-auth-preflight\"]) {\n    // Allow preflight requests with `skip-auth-preflight` flag\n    return next()\n  }\n\n  // Must be authenticated to use the proxy.\n  const isAuthenticated = await authenticated(req)\n  if (!isAuthenticated) {\n    // Let the assets through since they're used on the login page.\n    if (req.path.startsWith(\"/_static/\") && req.method === \"GET\") {\n      return next()\n    }\n\n    // Assume anything that explicitly accepts text/html is a user browsing a\n    // page (as opposed to an xhr request). Don't use `req.accepts()` since\n    // *every* request that I've seen (in Firefox and Chromium at least)\n    // includes `*/*` making it always truthy. Even for css/javascript.\n    if (req.headers.accept && req.headers.accept.includes(\"text/html\")) {\n      // Let the login through.\n      if (/\\/login\\/?/.test(req.path)) {\n        return next()\n      }\n      // Redirect all other pages to the login.\n      const to = self(req)\n      return redirect(req, res, \"login\", {\n        to: to !== \"/\" ? to : undefined,\n      })\n    }\n\n    // Everything else gets an unauthorized message.\n    throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n  }\n\n  proxy.web(req, res, {\n    ignorePath: true,\n    target: `http://0.0.0.0:${port}${req.originalUrl}`,\n  })\n})\n\nexport const wsRouter = WsRouter()\n\nwsRouter.ws(/.*/, async (req, _, next) => {\n  const port = maybeProxy(req)\n  if (!port) {\n    return next()\n  }\n\n  ensureProxyEnabled(req)\n  ensureOrigin(req)\n  await ensureAuthenticated(req)\n  proxy.ws(req, req.ws, req.head, {\n    ignorePath: true,\n    target: `http://0.0.0.0:${port}${req.originalUrl}`,\n  })\n})\n"
  },
  {
    "path": "src/node/routes/errors.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport express from \"express\"\nimport { promises as fs } from \"fs\"\nimport path from \"path\"\nimport { HttpCode } from \"../../common/http\"\nimport { rootPath } from \"../constants\"\nimport { replaceTemplates } from \"../http\"\nimport { escapeHtml, getMediaMime } from \"../util\"\nimport type { WebsocketRequest } from \"../wsRouter\"\n\ninterface ErrorWithStatusCode {\n  statusCode: number\n}\n\ninterface ErrorWithCode {\n  code: string\n}\n\n/** Error is network related. */\nexport const errorHasStatusCode = (error: any): error is ErrorWithStatusCode => {\n  return error && \"statusCode\" in error\n}\n\n/** Error originates from file system. */\nexport const errorHasCode = (error: any): error is ErrorWithCode => {\n  return error && \"code\" in error\n}\n\nconst notFoundCodes = [404, \"ENOENT\", \"EISDIR\"]\n\n/**\n * Final HTTP error handler.\n *\n * Note: This handler intentionally does not call `next()` even though it\n * accepts it as an argument; it is expected to be mounted last.\n */\nexport const errorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {\n  let statusCode = 500\n\n  if (errorHasStatusCode(err)) {\n    statusCode = err.statusCode\n  } else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {\n    statusCode = HttpCode.NotFound\n  }\n\n  res.status(statusCode)\n\n  // Assume anything that explicitly accepts text/html is a user browsing a\n  // page (as opposed to an xhr request). Don't use `req.accepts()` since\n  // *every* request that I've seen (in Firefox and Chromium at least)\n  // includes `*/*` making it always truthy. Even for css/javascript.\n  if (req.headers.accept && req.headers.accept.includes(\"text/html\")) {\n    const resourcePath = path.resolve(rootPath, \"src/browser/pages/error.html\")\n    res.set(\"Content-Type\", getMediaMime(resourcePath))\n    const content = await fs.readFile(resourcePath, \"utf8\")\n    res.send(\n      replaceTemplates(req, content)\n        .replace(/{{ERROR_TITLE}}/g, statusCode.toString())\n        .replace(/{{ERROR_HEADER}}/g, statusCode.toString())\n        .replace(/{{ERROR_BODY}}/g, escapeHtml(err.message))\n        .replace(/{{APP_NAME}}/g, req.args[\"app-name\"]),\n    )\n  } else {\n    res.json({\n      error: err.message,\n      ...(err.details || {}),\n    })\n  }\n}\n\n/**\n * Final WebSocket error handler.\n *\n * Note: This handler intentionally does not call `next()` even though it\n * accepts it as an argument; it is expected to be mounted last.\n */\nexport const wsErrorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {\n  let statusCode = 500\n  if (errorHasStatusCode(err)) {\n    statusCode = err.statusCode\n  } else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {\n    statusCode = HttpCode.NotFound\n  }\n  if (statusCode >= 500) {\n    logger.error(`${err.message} ${err.stack}`)\n  } else {\n    logger.debug(`${err.message} ${err.stack}`)\n  }\n  ;(req as WebsocketRequest).ws.end(`HTTP/1.1 ${statusCode} ${err.message}\\r\\n\\r\\n`)\n}\n"
  },
  {
    "path": "src/node/routes/health.ts",
    "content": "import { Router } from \"express\"\nimport { wss, Router as WsRouter } from \"../wsRouter\"\n\nexport const router = Router()\n\nrouter.get(\"/\", (req, res) => {\n  res.json({\n    status: req.heart.alive() ? \"alive\" : \"expired\",\n    lastHeartbeat: req.heart.lastHeartbeat,\n  })\n})\n\nexport const wsRouter = WsRouter()\n\nwsRouter.ws(\"/\", async (req) => {\n  wss.handleUpgrade(req, req.ws, req.head, (ws) => {\n    ws.addEventListener(\"message\", () => {\n      ws.send(\n        JSON.stringify({\n          event: \"health\",\n          status: req.heart.alive() ? \"alive\" : \"expired\",\n          lastHeartbeat: req.heart.lastHeartbeat,\n        }),\n      )\n    })\n    req.ws.resume()\n  })\n})\n"
  },
  {
    "path": "src/node/routes/index.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport cookieParser from \"cookie-parser\"\nimport * as express from \"express\"\nimport { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport * as tls from \"tls\"\nimport { Disposable } from \"../../common/emitter\"\nimport { getCookieSessionName, HttpCode, HttpError } from \"../../common/http\"\nimport { plural } from \"../../common/util\"\nimport { App } from \"../app\"\nimport { AuthType, DefaultedArgs } from \"../cli\"\nimport { commit, rootPath } from \"../constants\"\nimport { Heart } from \"../heart\"\nimport { redirect } from \"../http\"\nimport { CoderSettings, SettingsProvider } from \"../settings\"\nimport { UpdateProvider } from \"../update\"\nimport { getMediaMime, paths } from \"../util\"\nimport type { WebsocketRequest } from \"../wsRouter\"\nimport * as domainProxy from \"./domainProxy\"\nimport { errorHandler, wsErrorHandler } from \"./errors\"\nimport * as health from \"./health\"\nimport * as login from \"./login\"\nimport * as logout from \"./logout\"\nimport * as pathProxy from \"./pathProxy\"\nimport * as update from \"./update\"\nimport * as vscode from \"./vscode\"\n\n/**\n * Register all routes and middleware.\n */\nexport const register = async (\n  app: App,\n  args: DefaultedArgs,\n): Promise<{ disposeRoutes: Disposable[\"dispose\"]; heart: Heart }> => {\n  const heart = new Heart(path.join(paths.data, \"heartbeat\"), async () => {\n    return new Promise((resolve, reject) => {\n      // getConnections appears to not call the callback when there are no more\n      // connections.  Feels like it must be a bug?  For now add a timer to make\n      // sure we eventually resolve.\n      const timer = setTimeout(() => {\n        logger.debug(\"Node failed to respond with connections; assuming zero\")\n        resolve(false)\n      }, 5000)\n      app.server.getConnections((error, count) => {\n        clearTimeout(timer)\n        if (error) {\n          return reject(error)\n        }\n        logger.debug(plural(count, `${count} active connection`))\n        resolve(count > 0)\n      })\n    })\n  })\n\n  app.router.disable(\"x-powered-by\")\n  app.wsRouter.disable(\"x-powered-by\")\n\n  app.router.use(cookieParser())\n  app.wsRouter.use(cookieParser())\n\n  const settings = new SettingsProvider<CoderSettings>(path.join(args[\"user-data-dir\"], \"coder.json\"))\n  const updater = new UpdateProvider(\"https://api.github.com/repos/coder/code-server/releases/latest\", settings)\n\n  const cookieSessionName = getCookieSessionName(args[\"cookie-suffix\"])\n\n  const common: express.RequestHandler = (req, _, next) => {\n    // /healthz|/healthz/ needs to be excluded otherwise health checks will make\n    // it look like code-server is always in use.\n    if (!/^\\/healthz\\/?$/.test(req.url)) {\n      // NOTE@jsjoeio - intentionally not awaiting the .beat() call here because\n      // we don't want to slow down the request.\n      heart.beat()\n    }\n\n    // Add common variables routes can use.\n    req.args = args\n    req.heart = heart\n    req.settings = settings\n    req.updater = updater\n    req.cookieSessionName = cookieSessionName\n\n    next()\n  }\n\n  app.router.use(common)\n  app.wsRouter.use(common)\n\n  app.router.use(/.*/, async (req, res, next) => {\n    // If we're handling TLS ensure all requests are redirected to HTTPS.\n    // TODO: This does *NOT* work if you have a base path since to specify the\n    // protocol we need to specify the whole path.\n    if (args.cert && !(req.connection as tls.TLSSocket).encrypted) {\n      return res.redirect(`https://${req.headers.host}${req.originalUrl}`)\n    }\n    next()\n  })\n\n  app.router.get([\"/security.txt\", \"/.well-known/security.txt\"], async (_, res) => {\n    const resourcePath = path.resolve(rootPath, \"src/browser/security.txt\")\n    res.set(\"Content-Type\", getMediaMime(resourcePath))\n    res.send(await fs.readFile(resourcePath))\n  })\n\n  app.router.get(\"/robots.txt\", async (_, res) => {\n    const resourcePath = path.resolve(rootPath, \"src/browser/robots.txt\")\n    res.set(\"Content-Type\", getMediaMime(resourcePath))\n    res.send(await fs.readFile(resourcePath))\n  })\n\n  app.router.use(\"/\", domainProxy.router)\n  app.wsRouter.use(\"/\", domainProxy.wsRouter.router)\n\n  app.router.all(\"/proxy/:port{/*path}\", async (req, res) => {\n    await pathProxy.proxy(req, res)\n  })\n  app.wsRouter.get(\"/proxy/:port{/*path}\", async (req) => {\n    await pathProxy.wsProxy(req as unknown as WebsocketRequest)\n  })\n  // These two routes pass through the path directly.\n  // So the proxied app must be aware it is running\n  // under /absproxy/<someport>/\n  app.router.all(\"/absproxy/:port{/*path}\", async (req, res) => {\n    await pathProxy.proxy(req, res, {\n      passthroughPath: true,\n      proxyBasePath: args[\"abs-proxy-base-path\"],\n    })\n  })\n  app.wsRouter.get(\"/absproxy/:port{/*path}\", async (req) => {\n    await pathProxy.wsProxy(req as unknown as WebsocketRequest, {\n      passthroughPath: true,\n      proxyBasePath: args[\"abs-proxy-base-path\"],\n    })\n  })\n\n  app.router.use(express.json())\n  app.router.use(express.urlencoded({ extended: true }))\n\n  app.router.use(\n    \"/_static\",\n    express.static(rootPath, {\n      cacheControl: commit !== \"development\",\n      fallthrough: false,\n      setHeaders: (res, path, stat) => {\n        // The service worker is served from a sub-path on the static route so\n        // this is required to allow it to register a higher scope (by default\n        // the browser only allows it to register from its own path or lower).\n        if (path.endsWith(\"/serviceWorker.js\")) {\n          res.setHeader(\"Service-Worker-Allowed\", \"/\")\n        }\n      },\n    }),\n  )\n\n  app.router.use(\"/healthz\", health.router)\n  app.wsRouter.use(\"/healthz\", health.wsRouter.router)\n\n  if (args.auth === AuthType.Password) {\n    app.router.use(\"/login\", login.router)\n    app.router.use(\"/logout\", logout.router)\n  } else {\n    app.router.all(\"/login\", (req, res) => redirect(req, res, \"/\", {}))\n    app.router.all(\"/logout\", (req, res) => redirect(req, res, \"/\", {}))\n  }\n\n  app.router.use(\"/update\", update.router)\n\n  // For historic reasons we also load at /vscode because the root was replaced\n  // by a plugin in v1 of Coder.  The plugin system (which was for internal use\n  // only) has been removed, but leave the additional route for now.\n  for (const routePrefix of [\"/vscode\", \"/\"]) {\n    app.router.use(routePrefix, vscode.router)\n    app.wsRouter.use(routePrefix, vscode.wsRouter.router)\n  }\n\n  app.router.use(() => {\n    throw new HttpError(\"Not Found\", HttpCode.NotFound)\n  })\n\n  app.router.use(errorHandler)\n  app.wsRouter.use(wsErrorHandler)\n\n  return {\n    disposeRoutes: () => {\n      heart.dispose()\n      vscode.dispose()\n    },\n    heart,\n  }\n}\n"
  },
  {
    "path": "src/node/routes/login.ts",
    "content": "import { Router, Request } from \"express\"\nimport { promises as fs } from \"fs\"\nimport { RateLimiter as Limiter } from \"limiter\"\nimport * as path from \"path\"\nimport { rootPath } from \"../constants\"\nimport { authenticated, getCookieOptions, redirect, replaceTemplates } from \"../http\"\nimport i18n from \"../i18n\"\nimport { getPasswordMethod, handlePasswordValidation, sanitizeString, escapeHtml } from \"../util\"\n\n// RateLimiter wraps around the limiter library for logins.\n// It allows 2 logins every minute plus 12 logins every hour.\nexport class RateLimiter {\n  private readonly minuteLimiter = new Limiter({ tokensPerInterval: 2, interval: \"minute\" })\n  private readonly hourLimiter = new Limiter({ tokensPerInterval: 12, interval: \"hour\" })\n\n  public canTry(): boolean {\n    // Note: we must check using >= 1 because technically when there are no tokens left\n    // you get back a number like 0.00013333333333333334\n    // which would cause fail if the logic were > 0\n    return this.minuteLimiter.getTokensRemaining() >= 1 || this.hourLimiter.getTokensRemaining() >= 1\n  }\n\n  public removeToken(): boolean {\n    return this.minuteLimiter.tryRemoveTokens(1) || this.hourLimiter.tryRemoveTokens(1)\n  }\n}\n\nconst getRoot = async (req: Request, error?: Error): Promise<string> => {\n  const content = await fs.readFile(path.join(rootPath, \"src/browser/pages/login.html\"), \"utf8\")\n  const locale = req.args[\"locale\"] || \"en\"\n  i18n.changeLanguage(locale)\n  const welcomeText = req.args[\"welcome-text\"] || (i18n.t(\"WELCOME\", { app: req.args[\"app-name\"] }) as string)\n\n  // Determine password message using i18n\n  let passwordMsg = i18n.t(\"LOGIN_PASSWORD\")\n  if (req.args.usingEnvPassword) {\n    passwordMsg = i18n.t(\"LOGIN_USING_ENV_PASSWORD\")\n  } else if (req.args.usingEnvHashedPassword) {\n    passwordMsg = i18n.t(\"LOGIN_USING_HASHED_PASSWORD\")\n  }\n\n  return replaceTemplates(\n    req,\n    content\n      .replace(/{{I18N_LOGIN_TITLE}}/g, i18n.t(\"LOGIN_TITLE\", { app: req.args[\"app-name\"] }))\n      .replace(/{{WELCOME_TEXT}}/g, welcomeText)\n      .replace(/{{PASSWORD_MSG}}/g, passwordMsg)\n      .replace(/{{I18N_LOGIN_BELOW}}/g, i18n.t(\"LOGIN_BELOW\"))\n      .replace(/{{I18N_PASSWORD_PLACEHOLDER}}/g, i18n.t(\"PASSWORD_PLACEHOLDER\"))\n      .replace(/{{I18N_SUBMIT}}/g, i18n.t(\"SUBMIT\"))\n      .replace(/{{ERROR}}/, error ? `<div class=\"error\">${escapeHtml(error.message)}</div>` : \"\"),\n  )\n}\n\nconst limiter = new RateLimiter()\n\nexport const router = Router()\n\nrouter.use(async (req, res, next) => {\n  const to = (typeof req.query.to === \"string\" && req.query.to) || \"/\"\n  if (await authenticated(req)) {\n    return redirect(req, res, to, { to: undefined })\n  }\n  next()\n})\n\nrouter.get(\"/\", async (req, res) => {\n  res.send(await getRoot(req))\n})\n\nrouter.post<{}, string, { password?: string; base?: string } | undefined, { to?: string }>(\"/\", async (req, res) => {\n  const password = sanitizeString(req.body?.password)\n  const hashedPasswordFromArgs = req.args[\"hashed-password\"]\n\n  try {\n    // Check to see if they exceeded their login attempts\n    if (!limiter.canTry()) {\n      throw new Error(i18n.t(\"LOGIN_RATE_LIMIT\") as string)\n    }\n\n    if (!password) {\n      throw new Error(i18n.t(\"MISS_PASSWORD\") as string)\n    }\n\n    const passwordMethod = getPasswordMethod(hashedPasswordFromArgs)\n    const { isPasswordValid, hashedPassword } = await handlePasswordValidation({\n      passwordMethod,\n      hashedPasswordFromArgs,\n      passwordFromRequestBody: password,\n      passwordFromArgs: req.args.password,\n    })\n\n    if (isPasswordValid) {\n      // The hash does not add any actual security but we do it for\n      // obfuscation purposes (and as a side effect it handles escaping).\n      res.cookie(req.cookieSessionName, hashedPassword, getCookieOptions(req))\n\n      const to = (typeof req.query.to === \"string\" && req.query.to) || \"/\"\n      return redirect(req, res, to, { to: undefined })\n    }\n\n    // Note: successful logins should not count against the RateLimiter\n    // which is why this logic must come after the successful login logic\n    limiter.removeToken()\n\n    console.error(\n      \"Failed login attempt\",\n      JSON.stringify({\n        xForwardedFor: req.headers[\"x-forwarded-for\"],\n        remoteAddress: req.connection.remoteAddress,\n        userAgent: req.headers[\"user-agent\"],\n        timestamp: Math.floor(new Date().getTime() / 1000),\n      }),\n    )\n\n    throw new Error(i18n.t(\"INCORRECT_PASSWORD\") as string)\n  } catch (error: any) {\n    const renderedHtml = await getRoot(req, error)\n    res.send(renderedHtml)\n  }\n})\n"
  },
  {
    "path": "src/node/routes/logout.ts",
    "content": "import { Router } from \"express\"\nimport { getCookieOptions, redirect } from \"../http\"\nimport { sanitizeString } from \"../util\"\n\nexport const router = Router()\n\nrouter.get<{}, undefined, undefined, { base?: string; to?: string }>(\"/\", async (req, res) => {\n  // Must use the *identical* properties used to set the cookie.\n  res.clearCookie(req.cookieSessionName, getCookieOptions(req))\n\n  const to = sanitizeString(req.query.to) || \"/\"\n  return redirect(req, res, to, { to: undefined, base: undefined, href: undefined })\n})\n"
  },
  {
    "path": "src/node/routes/pathProxy.ts",
    "content": "import { Request, Response } from \"express\"\nimport * as path from \"path\"\nimport { HttpCode, HttpError } from \"../../common/http\"\nimport { ensureProxyEnabled, authenticated, ensureAuthenticated, ensureOrigin, redirect, self } from \"../http\"\nimport { proxy as _proxy } from \"../proxy\"\nimport type { WebsocketRequest } from \"../wsRouter\"\n\nconst getProxyTarget = (\n  req: Request,\n  opts?: {\n    proxyBasePath?: string\n  },\n): string => {\n  // If there is a base path, strip it out.\n  const base = (req as any).base || \"\"\n  // Cast since we only have one port param.\n  const port = parseInt(req.params.port as string, 10)\n  if (isNaN(port)) {\n    throw new HttpError(\"Invalid port\", HttpCode.BadRequest)\n  }\n  return `http://0.0.0.0:${port}${opts?.proxyBasePath || \"\"}/${req.originalUrl.slice(base.length)}`\n}\n\nexport async function proxy(\n  req: Request,\n  res: Response,\n  opts?: {\n    passthroughPath?: boolean\n    proxyBasePath?: string\n  },\n): Promise<void> {\n  ensureProxyEnabled(req)\n\n  if (req.method === \"OPTIONS\" && req.args[\"skip-auth-preflight\"]) {\n    // Allow preflight requests with `skip-auth-preflight` flag\n  } else if (!(await authenticated(req))) {\n    // If visiting the root (/:port only) redirect to the login page.\n    if (!req.params.path || req.params.path === \"/\") {\n      const to = self(req)\n      return redirect(req, res, \"login\", {\n        to: to !== \"/\" ? to : undefined,\n      })\n    }\n    throw new HttpError(\"Unauthorized\", HttpCode.Unauthorized)\n  }\n\n  // The base is used for rewriting (redirects, target).\n  if (!opts?.passthroughPath) {\n    ;(req as any).base = req.path.split(path.sep).slice(0, 3).join(path.sep)\n  }\n\n  _proxy.web(req, res, {\n    ignorePath: true,\n    target: getProxyTarget(req, opts),\n  })\n}\n\nexport async function wsProxy(\n  req: WebsocketRequest,\n  opts?: {\n    passthroughPath?: boolean\n    proxyBasePath?: string\n  },\n): Promise<void> {\n  ensureProxyEnabled(req)\n  ensureOrigin(req)\n  await ensureAuthenticated(req)\n\n  // The base is used for rewriting (redirects, target).\n  if (!opts?.passthroughPath) {\n    ;(req as any).base = req.path.split(path.sep).slice(0, 3).join(path.sep)\n  }\n\n  _proxy.ws(req, req.ws, req.head, {\n    ignorePath: true,\n    target: getProxyTarget(req, opts),\n  })\n}\n"
  },
  {
    "path": "src/node/routes/update.ts",
    "content": "import { Router } from \"express\"\nimport { version } from \"../constants\"\nimport { ensureAuthenticated } from \"../http\"\n\nexport const router = Router()\n\nrouter.get(\"/check\", ensureAuthenticated, async (req, res) => {\n  const update = await req.updater.getUpdate(req.query.force === \"true\")\n  res.json({\n    checked: update.checked,\n    latest: update.version,\n    current: version,\n    isLatest: req.updater.isLatestVersion(update),\n  })\n})\n"
  },
  {
    "path": "src/node/routes/vscode.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport * as crypto from \"crypto\"\nimport * as express from \"express\"\nimport { promises as fs } from \"fs\"\nimport * as http from \"http\"\nimport * as net from \"net\"\nimport * as os from \"os\"\nimport * as path from \"path\"\nimport { logError } from \"../../common/util\"\nimport { CodeArgs, toCodeArgs } from \"../cli\"\nimport { isDevMode, vsRootPath } from \"../constants\"\nimport { authenticated, ensureAuthenticated, ensureOrigin, redirect, replaceTemplates, self } from \"../http\"\nimport { SocketProxyProvider } from \"../socket\"\nimport { isFile } from \"../util\"\nimport { type WebsocketRequest, Router as WsRouter } from \"../wsRouter\"\n\nexport const router = express.Router()\n\nexport const wsRouter = WsRouter()\n\n/**\n * The API of VS Code's web client server.  code-server delegates requests to VS\n * Code here.\n *\n * @see ../../../lib/vscode/src/vs/server/node/server.main.ts:72\n */\nexport interface IVSCodeServerAPI {\n  handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>\n  handleUpgrade(req: http.IncomingMessage, socket: net.Socket): void\n  handleServerError(err: Error): void\n  dispose(): void\n}\n\n/**\n * VS Code's CLI entrypoint (../../../lib/vscode/src/server-main.js).\n *\n * Normally VS Code will run `node server-main.js` which starts either the web\n * server or the CLI (for installing extensions, etc) but we patch it so we can\n * `require` it and call its functions directly in order to integrate with our\n * web server.\n */\nexport type VSCodeModule = {\n  // See ../../../lib/vscode/src/server-main.js:339.\n  loadCodeWithNls(): Promise<{\n    // See ../../../lib/vscode/src/vs/server/node/server.main.ts:72.\n    createServer(address: string | net.AddressInfo | null, args: CodeArgs): Promise<IVSCodeServerAPI>\n    // See ../../../lib/vscode/src/vs/server/node/server.main.ts:65.\n    spawnCli(args: CodeArgs): Promise<void>\n  }>\n}\n\n/**\n * Load then create the VS Code server.\n */\nasync function loadVSCode(req: express.Request): Promise<IVSCodeServerAPI> {\n  // Since server-main.js is an ES module, we have to use `import`.  However,\n  // tsc will transpile this to `require` unless we change our module type,\n  // which will also require that we switch to ESM, since a hybrid approach\n  // breaks importing `rotating-file-stream` for some reason.  To work around\n  // this, use `eval` for now, but we should consider switching to ESM.\n  let modPath = path.join(vsRootPath, \"out/server-main.js\")\n  if (os.platform() === \"win32\") {\n    // On Windows, absolute paths of ESM modules must be a valid file URI.\n    modPath = \"file:///\" + modPath.replace(/\\\\/g, \"/\")\n  }\n  const mod = (await eval(`import(\"${modPath}\")`)) as VSCodeModule\n  const serverModule = await mod.loadCodeWithNls()\n  return serverModule.createServer(null, {\n    ...(await toCodeArgs(req.args)),\n    \"accept-server-license-terms\": true,\n    // This seems to be used to make the connection token flags optional (when\n    // set to 1.63) but we have always included them.\n    compatibility: \"1.64\",\n    \"without-connection-token\": true,\n  })\n}\n\n// To prevent loading the module more than once at a time.  We also have the\n// resolved value so you do not need to `await` everywhere.\nlet vscodeServerPromise: Promise<IVSCodeServerAPI> | undefined\n\n// The resolved value from the dynamically loaded VS Code server.  Do not use\n// without first calling and awaiting `ensureCodeServerLoaded`.\nlet vscodeServer: IVSCodeServerAPI | undefined\n\n/**\n * Ensure the VS Code server is loaded.\n */\nexport const ensureVSCodeLoaded = async (\n  req: express.Request,\n  _: express.Response,\n  next: express.NextFunction,\n): Promise<void> => {\n  if (vscodeServer) {\n    return next()\n  }\n  if (!vscodeServerPromise) {\n    vscodeServerPromise = loadVSCode(req)\n  }\n  try {\n    vscodeServer = await vscodeServerPromise\n  } catch (error) {\n    vscodeServerPromise = undefined // Unset so we can try again.\n    logError(logger, \"CodeServerRouteWrapper\", error)\n    if (isDevMode) {\n      return next(\n        new Error(\n          (error instanceof Error ? error.message : error) +\n            \" (Have you applied the patches? If so, VS Code may still be compiling)\",\n        ),\n      )\n    }\n    return next(error)\n  }\n  return next()\n}\n\nrouter.get(\"/\", ensureVSCodeLoaded, async (req, res, next) => {\n  const isAuthenticated = await authenticated(req)\n  const NO_FOLDER_OR_WORKSPACE_QUERY = !req.query.folder && !req.query.workspace\n  // Ew means the workspace was closed so clear the last folder/workspace.\n  const FOLDER_OR_WORKSPACE_WAS_CLOSED = req.query.ew\n\n  if (!isAuthenticated) {\n    const to = self(req)\n    return redirect(req, res, \"login\", {\n      to: to !== \"/\" ? to : undefined,\n    })\n  }\n\n  if (NO_FOLDER_OR_WORKSPACE_QUERY && !FOLDER_OR_WORKSPACE_WAS_CLOSED) {\n    const settings = await req.settings.read()\n    const lastOpened = settings.query || {}\n    // This flag disables the last opened behavior\n    const IGNORE_LAST_OPENED = req.args[\"ignore-last-opened\"]\n    const HAS_LAST_OPENED_FOLDER_OR_WORKSPACE = lastOpened.folder || lastOpened.workspace\n    const HAS_FOLDER_OR_WORKSPACE_FROM_CLI = req.args._.length > 0\n    const to = self(req)\n\n    let folder = undefined\n    let workspace = undefined\n\n    // Redirect to the last folder/workspace if nothing else is opened.\n    if (HAS_LAST_OPENED_FOLDER_OR_WORKSPACE && !IGNORE_LAST_OPENED) {\n      folder = lastOpened.folder\n      workspace = lastOpened.workspace\n    } else if (HAS_FOLDER_OR_WORKSPACE_FROM_CLI) {\n      const lastEntry = path.resolve(req.args._[req.args._.length - 1])\n      const entryIsFile = await isFile(lastEntry)\n      const IS_WORKSPACE_FILE = entryIsFile && path.extname(lastEntry) === \".code-workspace\"\n\n      if (IS_WORKSPACE_FILE) {\n        workspace = lastEntry\n      } else if (!entryIsFile) {\n        folder = lastEntry\n      }\n    }\n\n    if (folder || workspace) {\n      return redirect(req, res, to, {\n        folder,\n        workspace,\n      })\n    }\n  }\n\n  // Store the query parameters so we can use them on the next load.  This\n  // also allows users to create functionality around query parameters.\n  await req.settings.write({ query: req.query })\n\n  next()\n})\n\nrouter.get(\"/manifest.json\", async (req, res) => {\n  res.writeHead(200, { \"Content-Type\": \"application/manifest+json\" })\n\n  res.end(\n    replaceTemplates(\n      req,\n      JSON.stringify(\n        {\n          name: req.args[\"app-name\"],\n          short_name: req.args[\"app-name\"],\n          start_url: \".\",\n          display: \"fullscreen\",\n          display_override: [\"window-controls-overlay\"],\n          description: \"Run Code on a remote server.\",\n          icons: [192, 512]\n            .map((size) => [\n              {\n                src: `{{BASE}}/_static/src/browser/media/pwa-icon-${size}.png`,\n                type: \"image/png\",\n                sizes: `${size}x${size}`,\n                purpose: \"any\",\n              },\n              {\n                src: `{{BASE}}/_static/src/browser/media/pwa-icon-maskable-${size}.png`,\n                type: \"image/png\",\n                sizes: `${size}x${size}`,\n                purpose: \"maskable\",\n              },\n            ])\n            .flat(),\n        },\n        null,\n        2,\n      ),\n    ),\n  )\n})\n\nlet mintKeyPromise: Promise<Buffer> | undefined\nrouter.post(\"/mint-key\", async (req, res) => {\n  if (!mintKeyPromise) {\n    mintKeyPromise = new Promise(async (resolve) => {\n      const keyPath = path.join(req.args[\"user-data-dir\"], \"serve-web-key-half\")\n      logger.debug(`Reading server web key half from ${keyPath}`)\n      try {\n        resolve(await fs.readFile(keyPath))\n        return\n      } catch (error: any) {\n        if (error.code !== \"ENOENT\") {\n          logError(logger, `read ${keyPath}`, error)\n        }\n      }\n      // VS Code wants 256 bits.\n      const key = crypto.randomBytes(32)\n      try {\n        await fs.writeFile(keyPath, key)\n      } catch (error: any) {\n        logError(logger, `write ${keyPath}`, error)\n      }\n      resolve(key)\n    })\n  }\n  const key = await mintKeyPromise\n  res.end(key)\n})\n\nrouter.all(/.*/, ensureAuthenticated, ensureVSCodeLoaded, async (req, res) => {\n  vscodeServer!.handleRequest(req, res)\n})\n\nconst socketProxyProvider = new SocketProxyProvider()\nwsRouter.ws(/.*/, ensureOrigin, ensureAuthenticated, ensureVSCodeLoaded, async (req: WebsocketRequest) => {\n  const wrappedSocket = await socketProxyProvider.createProxy(req.ws)\n  // This should actually accept a duplex stream but it seems Code has not\n  // been updated to match the Node 16 types so cast for now.  There does not\n  // appear to be any code specific to sockets so this should be fine.\n  vscodeServer!.handleUpgrade(req, wrappedSocket as net.Socket)\n\n  req.ws.resume()\n})\n\nexport function dispose() {\n  vscodeServer?.dispose()\n  socketProxyProvider.stop()\n}\n"
  },
  {
    "path": "src/node/settings.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport type { ParsedQs } from \"qs\"\nimport { promises as fs } from \"fs\"\n\nexport type Settings = { [key: string]: Settings | string | boolean | number }\n\n/**\n * Provides read and write access to settings.\n */\nexport class SettingsProvider<T> {\n  public constructor(private readonly settingsPath: string) {}\n\n  /**\n   * Read settings from the file. On a failure return last known settings and\n   * log a warning.\n   */\n  public async read(): Promise<T> {\n    try {\n      const raw = (await fs.readFile(this.settingsPath, \"utf8\")).trim()\n      return raw ? JSON.parse(raw) : ({} as T)\n    } catch (error: any) {\n      if (error.code !== \"ENOENT\") {\n        logger.warn(error.message)\n      }\n    }\n    return {} as T\n  }\n\n  /**\n   * Write settings combined with current settings. On failure log a warning.\n   * Settings will be merged shallowly.\n   */\n  public async write(settings: Partial<T>): Promise<void> {\n    try {\n      const oldSettings = await this.read()\n      const nextSettings = { ...oldSettings, ...settings }\n      await fs.writeFile(this.settingsPath, JSON.stringify(nextSettings, null, 2))\n    } catch (error: any) {\n      logger.warn(error.message)\n    }\n  }\n}\n\nexport interface UpdateSettings {\n  update: {\n    checked: number\n    version: string\n  }\n}\n\n/**\n * Global code-server settings.\n */\nexport interface CoderSettings extends UpdateSettings {\n  query?: ParsedQs\n}\n"
  },
  {
    "path": "src/node/socket.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as net from \"net\"\nimport * as path from \"path\"\nimport * as stream from \"stream\"\nimport * as tls from \"tls\"\nimport { Emitter } from \"../common/emitter\"\nimport { generateUuid } from \"../common/util\"\nimport { canConnect, paths } from \"./util\"\n\n/**\n * Provides a way to proxy a TLS socket. Can be used when you need to pass a\n * socket to a child process since you can't pass the TLS socket.\n */\nexport class SocketProxyProvider {\n  private readonly onProxyConnect = new Emitter<net.Socket>()\n  private proxyPipe = path.join(paths.runtime, \"tls-proxy\")\n  private _proxyServer?: Promise<net.Server>\n  private readonly proxyTimeout = 5000\n\n  /**\n   * Stop the proxy server.\n   */\n  public stop(): void {\n    if (this._proxyServer) {\n      this._proxyServer.then((server) => server.close())\n      this._proxyServer = undefined\n    }\n  }\n\n  /**\n   * Create a socket proxy for TLS sockets. If it is not a TLS socket the\n   * original socket or stream is returned. This will spawn a proxy server on\n   * demand.\n   */\n  public async createProxy(socket: tls.TLSSocket | net.Socket): Promise<net.Socket>\n  public async createProxy(socket: stream.Duplex): Promise<stream.Duplex>\n  public async createProxy(socket: tls.TLSSocket | net.Socket | stream.Duplex): Promise<net.Socket | stream.Duplex> {\n    if (!(socket instanceof tls.TLSSocket)) {\n      return socket\n    }\n\n    await this.startProxyServer()\n\n    return new Promise((resolve, reject) => {\n      const id = generateUuid()\n      const proxy = net.connect(this.proxyPipe)\n      proxy.once(\"connect\", () => proxy.write(id))\n\n      const timeout = setTimeout(() => {\n        listener.dispose()\n        socket.destroy()\n        proxy.destroy()\n        reject(new Error(\"TLS socket proxy timed out\"))\n      }, this.proxyTimeout)\n\n      const listener = this.onProxyConnect.event((connection) => {\n        connection.once(\"data\", (data) => {\n          if (!socket.destroyed && !proxy.destroyed && data.toString() === id) {\n            clearTimeout(timeout)\n            listener.dispose()\n            ;[\n              [proxy, socket],\n              [socket, proxy],\n            ].forEach(([a, b]) => {\n              a.pipe(b)\n              a.on(\"error\", () => b.destroy())\n              a.on(\"close\", () => b.destroy())\n              a.on(\"end\", () => b.end())\n            })\n            resolve(connection)\n          }\n        })\n      })\n    })\n  }\n\n  private async startProxyServer(): Promise<net.Server> {\n    if (!this._proxyServer) {\n      this._proxyServer = this.findFreeSocketPath(this.proxyPipe)\n        .then((pipe) => {\n          this.proxyPipe = pipe\n          return Promise.all([\n            fs.mkdir(path.dirname(this.proxyPipe), { recursive: true }),\n            fs.rm(this.proxyPipe, { force: true, recursive: true }),\n          ])\n        })\n        .then(() => {\n          return new Promise((resolve) => {\n            const proxyServer = net.createServer((p) => this.onProxyConnect.emit(p))\n            proxyServer.once(\"listening\", () => resolve(proxyServer))\n            proxyServer.listen(this.proxyPipe)\n          })\n        })\n    }\n    return this._proxyServer\n  }\n\n  public async findFreeSocketPath(basePath: string, maxTries = 100): Promise<string> {\n    let i = 0\n    let path = basePath\n    while ((await canConnect(path)) && i < maxTries) {\n      path = `${basePath}-${++i}`\n    }\n    return path\n  }\n}\n"
  },
  {
    "path": "src/node/update.ts",
    "content": "import { field, logger } from \"@coder/logger\"\nimport * as http from \"http\"\nimport * as https from \"https\"\nimport { ProxyAgent } from \"proxy-agent\"\nimport * as semver from \"semver\"\nimport * as url from \"url\"\nimport { httpProxyUri, version } from \"./constants\"\nimport { SettingsProvider, UpdateSettings } from \"./settings\"\n\nexport interface Update {\n  checked: number\n  version: string\n}\n\nexport interface LatestResponse {\n  name: string\n}\n\n/**\n * Provide update information.\n */\nexport class UpdateProvider {\n  private update?: Promise<Update>\n  private updateInterval = 1000 * 60 * 60 * 24 // Milliseconds between update checks.\n\n  public constructor(\n    /**\n     * The URL for getting the latest version of code-server. Should return JSON\n     * that fulfills `LatestResponse`.\n     */\n    private readonly latestUrl: string,\n    /**\n     * Update information will be stored here.\n     */\n    private readonly settings: SettingsProvider<UpdateSettings>,\n  ) {}\n\n  /**\n   * Query for and return the latest update.\n   */\n  public async getUpdate(force?: boolean): Promise<Update> {\n    // Don't run multiple requests at a time.\n    if (!this.update) {\n      this.update = this._getUpdate(force)\n      this.update.then(() => (this.update = undefined))\n    }\n\n    return this.update\n  }\n\n  private async _getUpdate(force?: boolean): Promise<Update> {\n    const now = Date.now()\n    try {\n      let { update } = !force ? await this.settings.read() : { update: undefined }\n      if (!update || update.checked + this.updateInterval < now) {\n        const buffer = await this.request(this.latestUrl)\n        const data = JSON.parse(buffer.toString()) as LatestResponse\n        update = { checked: now, version: data.name.replace(/^v/, \"\") }\n        await this.settings.write({ update })\n      }\n      logger.debug(\"got latest version\", field(\"latest\", update.version))\n      return update\n    } catch (error: any) {\n      logger.error(\"Failed to get latest version\", field(\"error\", error.message))\n      return {\n        checked: now,\n        version: \"unknown\",\n      }\n    }\n  }\n\n  /**\n   * Return true if the currently installed version is the latest.\n   */\n  public isLatestVersion(latest: Update): boolean {\n    logger.debug(\"comparing versions\", field(\"current\", version), field(\"latest\", latest.version))\n    try {\n      return semver.lte(latest.version, version)\n    } catch (error) {\n      return true\n    }\n  }\n\n  private async request(uri: string): Promise<Buffer> {\n    const response = await this.requestResponse(uri)\n    return new Promise((resolve, reject) => {\n      const chunks: Buffer[] = []\n      let bufferLength = 0\n      response.on(\"data\", (chunk) => {\n        bufferLength += chunk.length\n        chunks.push(chunk)\n      })\n      response.on(\"error\", reject)\n      response.on(\"end\", () => {\n        resolve(Buffer.concat(chunks, bufferLength))\n      })\n    })\n  }\n\n  private async requestResponse(uri: string): Promise<http.IncomingMessage> {\n    let redirects = 0\n    const maxRedirects = 10\n    return new Promise((resolve, reject) => {\n      const request = (uri: string): void => {\n        logger.debug(\"Making request\", field(\"uri\", uri))\n        const isHttps = uri.startsWith(\"https\")\n        const agent = new ProxyAgent({\n          keepAlive: true,\n          getProxyForUrl: () => httpProxyUri || \"\",\n        })\n        const httpx = isHttps ? https : http\n        const client = httpx.get(uri, { headers: { \"User-Agent\": \"code-server\" }, agent }, (response) => {\n          if (!response.statusCode || response.statusCode < 200 || response.statusCode >= 400) {\n            response.destroy()\n            return reject(new Error(`${uri}: ${response.statusCode || \"500\"}`))\n          }\n\n          if (response.statusCode >= 300) {\n            response.destroy()\n            ++redirects\n            if (redirects > maxRedirects) {\n              return reject(new Error(\"reached max redirects\"))\n            }\n            if (!response.headers.location) {\n              return reject(new Error(\"received redirect with no location header\"))\n            }\n            return request(url.resolve(uri, response.headers.location))\n          }\n\n          resolve(response)\n        })\n        client.on(\"error\", reject)\n      }\n      request(uri)\n    })\n  }\n}\n"
  },
  {
    "path": "src/node/util.ts",
    "content": "import * as argon2 from \"argon2\"\nimport * as cp from \"child_process\"\nimport * as crypto from \"crypto\"\nimport envPaths from \"env-paths\"\nimport { promises as fs } from \"fs\"\nimport * as net from \"net\"\nimport * as os from \"os\"\nimport * as path from \"path\"\nimport safeCompare from \"safe-compare\"\nimport * as util from \"util\"\nimport xdgBasedir from \"xdg-basedir\"\n\nexport interface Paths {\n  data: string\n  config: string\n  runtime: string\n}\n\n// From https://github.com/chalk/ansi-regex\nconst pattern = [\n  \"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\n  \"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))\",\n].join(\"|\")\nconst re = new RegExp(pattern, \"g\")\n\nexport type OnLineCallback = (strippedLine: string, originalLine: string) => void\n/**\n * Split stdout on newlines and strip ANSI codes.\n */\nexport const onLine = (proc: cp.ChildProcess, callback: OnLineCallback): void => {\n  let buffer = \"\"\n  if (!proc.stdout) {\n    throw new Error(\"no stdout\")\n  }\n  proc.stdout.setEncoding(\"utf8\")\n  proc.stdout.on(\"data\", (d) => {\n    const data = buffer + d\n    const split = data.split(\"\\n\")\n    const last = split.length - 1\n\n    for (let i = 0; i < last; ++i) {\n      callback(split[i].replace(re, \"\"), split[i])\n    }\n\n    // The last item will either be an empty string (the data ended with a\n    // newline) or a partial line (did not end with a newline) and we must\n    // wait to parse it until we get a full line.\n    buffer = split[last]\n  })\n}\n\nexport const paths = getEnvPaths()\n\n/**\n * Gets the config and data paths for the current platform/configuration.\n * On MacOS this function gets the standard XDG directories instead of using the native macOS\n * ones. Most CLIs do this as in practice only GUI apps use the standard macOS directories.\n */\nexport function getEnvPaths(platform = process.platform): Paths {\n  const paths = envPaths(\"code-server\", { suffix: \"\" })\n  const append = (p: string): string => path.join(p, \"code-server\")\n  switch (platform) {\n    case \"darwin\":\n      return {\n        // envPaths uses native directories so force Darwin to use the XDG spec\n        // to align with other CLI tools.\n        data: xdgBasedir.data ? append(xdgBasedir.data) : paths.data,\n        config: xdgBasedir.config ? append(xdgBasedir.config) : paths.config,\n        // Fall back to temp if there is no runtime dir.\n        runtime: xdgBasedir.runtime ? append(xdgBasedir.runtime) : paths.temp,\n      }\n    case \"win32\":\n      return {\n        data: paths.data,\n        config: paths.config,\n        // Windows doesn't have a runtime dir.\n        runtime: paths.temp,\n      }\n    default:\n      return {\n        data: paths.data,\n        config: paths.config,\n        // Fall back to temp if there is no runtime dir.\n        runtime: xdgBasedir.runtime ? append(xdgBasedir.runtime) : paths.temp,\n      }\n  }\n}\n\nexport const generateCertificate = async (hostname: string): Promise<{ cert: string; certKey: string }> => {\n  const certPath = path.join(paths.data, `${hostname.replace(/\\./g, \"_\")}.crt`)\n  const certKeyPath = path.join(paths.data, `${hostname.replace(/\\./g, \"_\")}.key`)\n\n  // Try generating the certificates if we can't access them (which probably\n  // means they don't exist).\n  try {\n    await Promise.all([fs.access(certPath), fs.access(certKeyPath)])\n  } catch (error) {\n    // Require on demand so openssl isn't required if you aren't going to\n    // generate certificates.\n    const pem = require(\"pem\") as typeof import(\"pem\")\n    const certs = await new Promise<import(\"pem\").CertificateCreationResult>((resolve, reject): void => {\n      pem.createCertificate(\n        {\n          selfSigned: true,\n          commonName: hostname,\n          config: `\n[req]\nreq_extensions = v3_req\n\n[ v3_req ]\nbasicConstraints = CA:true\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n\n[alt_names]\nDNS.1 = ${hostname}\n`,\n        },\n        (error, result) => {\n          return error ? reject(error) : resolve(result)\n        },\n      )\n    })\n    await fs.mkdir(paths.data, { recursive: true })\n    await Promise.all([fs.writeFile(certPath, certs.certificate), fs.writeFile(certKeyPath, certs.serviceKey)])\n  }\n\n  return {\n    cert: certPath,\n    certKey: certKeyPath,\n  }\n}\n\nexport const generatePassword = async (length = 24): Promise<string> => {\n  const buffer = Buffer.alloc(Math.ceil(length / 2))\n  await util.promisify(crypto.randomFill)(buffer)\n  return buffer.toString(\"hex\").substring(0, length)\n}\n\n/**\n * Used to hash the password.\n */\nexport const hash = async (password: string): Promise<string> => {\n  return await argon2.hash(password)\n}\n\n/**\n * Used to verify if the password matches the hash\n */\nexport const isHashMatch = async (password: string, hash: string) => {\n  if (password === \"\" || hash === \"\" || !hash.startsWith(\"$\")) {\n    return false\n  }\n  return await argon2.verify(hash, password)\n}\n\n/**\n * Used to hash the password using the sha256\n * algorithm. We only use this to for checking\n * the hashed-password set in the config.\n *\n * Kept for legacy reasons.\n */\nexport const hashLegacy = (str: string): string => {\n  return crypto.createHash(\"sha256\").update(str).digest(\"hex\")\n}\n\n/**\n * Used to check if the password matches the hash using\n * the hashLegacy function\n */\nexport const isHashLegacyMatch = (password: string, hashPassword: string) => {\n  const hashedWithLegacy = hashLegacy(password)\n  return safeCompare(hashedWithLegacy, hashPassword)\n}\n\nexport type PasswordMethod = \"SHA256\" | \"ARGON2\" | \"PLAIN_TEXT\"\n\n/**\n * Used to determine the password method.\n *\n * There are three options for the return value:\n * 1. \"SHA256\" -> the legacy hashing algorithm\n * 2. \"ARGON2\" -> the newest hashing algorithm\n * 3. \"PLAIN_TEXT\" -> regular ol' password with no hashing\n *\n * @returns {PasswordMethod} \"SHA256\" | \"ARGON2\" | \"PLAIN_TEXT\"\n */\nexport function getPasswordMethod(hashedPassword: string | undefined): PasswordMethod {\n  if (!hashedPassword) {\n    return \"PLAIN_TEXT\"\n  }\n\n  // This is the new hashing algorithm\n  if (hashedPassword.includes(\"$argon\")) {\n    return \"ARGON2\"\n  }\n\n  // This is the legacy hashing algorithm\n  return \"SHA256\"\n}\n\ntype PasswordValidation = {\n  isPasswordValid: boolean\n  hashedPassword: string\n}\n\ntype HandlePasswordValidationArgs = {\n  /** The PasswordMethod */\n  passwordMethod: PasswordMethod\n  /** The password provided by the user */\n  passwordFromRequestBody: string\n  /** The password set in PASSWORD or config */\n  passwordFromArgs: string | undefined\n  /** The hashed-password set in HASHED_PASSWORD or config */\n  hashedPasswordFromArgs: string | undefined\n}\n\n/**\n * Checks if a password is valid and also returns the hash\n * using the PasswordMethod\n */\nexport async function handlePasswordValidation({\n  passwordMethod,\n  passwordFromArgs,\n  passwordFromRequestBody,\n  hashedPasswordFromArgs,\n}: HandlePasswordValidationArgs): Promise<PasswordValidation> {\n  const passwordValidation = <PasswordValidation>{\n    isPasswordValid: false,\n    hashedPassword: \"\",\n  }\n\n  switch (passwordMethod) {\n    case \"PLAIN_TEXT\": {\n      const isValid = passwordFromArgs ? safeCompare(passwordFromRequestBody, passwordFromArgs) : false\n      passwordValidation.isPasswordValid = isValid\n\n      const hashedPassword = await hash(passwordFromRequestBody)\n      passwordValidation.hashedPassword = hashedPassword\n      break\n    }\n    case \"SHA256\": {\n      const isValid = isHashLegacyMatch(passwordFromRequestBody, hashedPasswordFromArgs || \"\")\n      passwordValidation.isPasswordValid = isValid\n\n      passwordValidation.hashedPassword = hashedPasswordFromArgs || (await hashLegacy(passwordFromRequestBody))\n      break\n    }\n    case \"ARGON2\": {\n      const isValid = await isHashMatch(passwordFromRequestBody, hashedPasswordFromArgs || \"\")\n      passwordValidation.isPasswordValid = isValid\n\n      passwordValidation.hashedPassword = hashedPasswordFromArgs || \"\"\n      break\n    }\n    default:\n      break\n  }\n\n  return passwordValidation\n}\n\nexport type IsCookieValidArgs = {\n  passwordMethod: PasswordMethod\n  cookieKey: string\n  hashedPasswordFromArgs: string | undefined\n  passwordFromArgs: string | undefined\n}\n\n/** Checks if a req.cookies.key is valid using the PasswordMethod */\nexport async function isCookieValid({\n  passwordFromArgs = \"\",\n  cookieKey,\n  hashedPasswordFromArgs = \"\",\n  passwordMethod,\n}: IsCookieValidArgs): Promise<boolean> {\n  let isValid = false\n  switch (passwordMethod) {\n    case \"PLAIN_TEXT\":\n      isValid = await isHashMatch(passwordFromArgs, cookieKey)\n      break\n    case \"ARGON2\":\n    case \"SHA256\":\n      isValid = safeCompare(cookieKey, hashedPasswordFromArgs)\n      break\n    default:\n      break\n  }\n  return isValid\n}\n\n/** Ensures that the input is sanitized by checking\n * - it's a string\n * - greater than 0 characters\n * - trims whitespace\n */\nexport function sanitizeString(str: unknown): string {\n  // Very basic sanitization of string\n  // Credit: https://stackoverflow.com/a/46719000/3015595\n  return typeof str === \"string\" ? str.trim() : \"\"\n}\n\nconst mimeTypes: { [key: string]: string } = {\n  \".aac\": \"audio/x-aac\",\n  \".avi\": \"video/x-msvideo\",\n  \".bmp\": \"image/bmp\",\n  \".css\": \"text/css\",\n  \".flv\": \"video/x-flv\",\n  \".gif\": \"image/gif\",\n  \".html\": \"text/html\",\n  \".ico\": \"image/x-icon\",\n  \".jpe\": \"image/jpg\",\n  \".jpeg\": \"image/jpg\",\n  \".jpg\": \"image/jpg\",\n  \".js\": \"application/javascript\",\n  \".json\": \"application/json\",\n  \".m1v\": \"video/mpeg\",\n  \".m2a\": \"audio/mpeg\",\n  \".m2v\": \"video/mpeg\",\n  \".m3a\": \"audio/mpeg\",\n  \".mid\": \"audio/midi\",\n  \".midi\": \"audio/midi\",\n  \".mk3d\": \"video/x-matroska\",\n  \".mks\": \"video/x-matroska\",\n  \".mkv\": \"video/x-matroska\",\n  \".mov\": \"video/quicktime\",\n  \".movie\": \"video/x-sgi-movie\",\n  \".mp2\": \"audio/mpeg\",\n  \".mp2a\": \"audio/mpeg\",\n  \".mp3\": \"audio/mpeg\",\n  \".mp4\": \"video/mp4\",\n  \".mp4a\": \"audio/mp4\",\n  \".mp4v\": \"video/mp4\",\n  \".mpe\": \"video/mpeg\",\n  \".mpeg\": \"video/mpeg\",\n  \".mpg\": \"video/mpeg\",\n  \".mpg4\": \"video/mp4\",\n  \".mpga\": \"audio/mpeg\",\n  \".oga\": \"audio/ogg\",\n  \".ogg\": \"audio/ogg\",\n  \".ogv\": \"video/ogg\",\n  \".png\": \"image/png\",\n  \".psd\": \"image/vnd.adobe.photoshop\",\n  \".qt\": \"video/quicktime\",\n  \".spx\": \"audio/ogg\",\n  \".svg\": \"image/svg+xml\",\n  \".tga\": \"image/x-tga\",\n  \".tif\": \"image/tiff\",\n  \".tiff\": \"image/tiff\",\n  \".txt\": \"text/plain\",\n  \".wav\": \"audio/x-wav\",\n  \".wasm\": \"application/wasm\",\n  \".webm\": \"video/webm\",\n  \".webp\": \"image/webp\",\n  \".wma\": \"audio/x-ms-wma\",\n  \".wmv\": \"video/x-ms-wmv\",\n  \".woff\": \"application/font-woff\",\n}\n\nexport const getMediaMime = (filePath?: string): string => {\n  return (filePath && mimeTypes[path.extname(filePath)]) || \"text/plain\"\n}\n\n/**\n * A helper function that checks if the platform is Windows Subsystem for Linux\n * (WSL)\n *\n * @see https://github.com/sindresorhus/is-wsl/blob/main/index.js\n * @returns {Boolean} boolean if it is WSL\n */\nexport const isWsl = async (\n  platform: NodeJS.Platform,\n  osRelease: string,\n  procVersionFilePath: string,\n): Promise<boolean> => {\n  if (platform !== \"linux\") {\n    return false\n  }\n\n  if (osRelease.toLowerCase().includes(\"microsoft\")) {\n    return true\n  }\n\n  try {\n    return (await fs.readFile(procVersionFilePath, \"utf8\")).toLowerCase().includes(\"microsoft\")\n  } catch (_) {\n    return false\n  }\n}\n\ninterface OpenOptions {\n  args: string[]\n  command: string\n  urlSearch: string\n}\n\n/**\n * A helper function to construct options for `open` function.\n *\n * Extract to make it easier to test.\n *\n * @param platform - platform on machine\n * @param urlSearch - url.search\n * @returns  an object with args, command, options and urlSearch\n */\nexport function constructOpenOptions(platform: NodeJS.Platform | \"wsl\", urlSearch: string): OpenOptions {\n  const args: string[] = []\n  let command = platform === \"darwin\" ? \"open\" : \"xdg-open\"\n  if (platform === \"win32\" || platform === \"wsl\") {\n    command = platform === \"wsl\" ? \"cmd.exe\" : \"cmd\"\n    args.push(\"/c\", \"start\", '\"\"', \"/b\")\n    urlSearch = urlSearch.replace(/&/g, \"^&\")\n  }\n\n  return {\n    args,\n    command,\n    urlSearch,\n  }\n}\n\n/**\n * Try opening an address using whatever the system has set for opening URLs.\n */\nexport const open = async (address: URL | string): Promise<void> => {\n  if (typeof address === \"string\") {\n    throw new Error(\"Cannot open socket paths\")\n  }\n  // Web sockets do not seem to work if browsing with 0.0.0.0.\n  const url = new URL(address)\n  if (url.hostname === \"0.0.0.0\") {\n    url.hostname = \"localhost\"\n  }\n  const platform = (await isWsl(process.platform, os.release(), \"/proc/version\")) ? \"wsl\" : process.platform\n  const { command, args, urlSearch } = constructOpenOptions(platform, url.search)\n  url.search = urlSearch\n  const proc = cp.spawn(command, [...args, url.toString()], {})\n  await new Promise<void>((resolve, reject) => {\n    proc.on(\"error\", reject)\n    proc.on(\"close\", (code) => {\n      return code !== 0 ? reject(new Error(`Failed to open with code ${code}`)) : resolve()\n    })\n  })\n}\n\n/**\n * Return a promise that resolves with whether the socket path is active.\n */\nexport function canConnect(path: string): Promise<boolean> {\n  return new Promise((resolve) => {\n    const socket = net.connect(path)\n    socket.once(\"error\", () => resolve(false))\n    socket.once(\"connect\", () => {\n      socket.destroy()\n      resolve(true)\n    })\n  })\n}\n\nexport const isFile = async (path: string): Promise<boolean> => {\n  try {\n    const stat = await fs.stat(path)\n    return stat.isFile()\n  } catch (error) {\n    return false\n  }\n}\n\nexport const isDirectory = async (path: string): Promise<boolean> => {\n  try {\n    const stat = await fs.stat(path)\n    return stat.isDirectory()\n  } catch (error) {\n    return false\n  }\n}\n\n/**\n * Escapes any HTML string special characters, like &, <, >, \", and '.\n *\n * Source: https://stackoverflow.com/a/6234804/3015595\n **/\nexport function escapeHtml(unsafe: string): string {\n  return unsafe\n    .replace(/&/g, \"&amp;\")\n    .replace(/</g, \"&lt;\")\n    .replace(/>/g, \"&gt;\")\n    .replace(/\"/g, \"&quot;\")\n    .replace(/'/g, \"&apos;\")\n}\n\n/**\n * A helper function which returns a boolean indicating whether\n * the given error is a NodeJS.ErrnoException by checking if\n * it has a .code property.\n */\nexport function isNodeJSErrnoException(error: unknown): error is NodeJS.ErrnoException {\n  return error !== undefined && (error as NodeJS.ErrnoException).code !== undefined\n}\n\n// TODO: Replace with proper templating system.\nexport const escapeJSON = (value: cp.Serializable) => JSON.stringify(value).replace(/\"/g, \"&quot;\")\n\n/**\n * Split a string on the first equals.  The result will always be an array with\n * two items regardless of how many equals there are.  The second item will be\n * undefined if empty or missing.\n */\nexport function splitOnFirstEquals(str: string): [string, string | undefined] {\n  const split = str.split(/=(.+)?/, 2)\n  return [split[0], split[1]]\n}\n"
  },
  {
    "path": "src/node/vscodeSocket.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport express from \"express\"\nimport * as http from \"http\"\nimport * as path from \"path\"\nimport { HttpCode, HttpError } from \"../common/http\"\nimport { listen } from \"./app\"\nimport { errorHandler } from \"./routes/errors\"\nimport { canConnect } from \"./util\"\n\nexport interface EditorSessionEntry {\n  workspace: {\n    id: string\n    folders: {\n      uri: {\n        path: string\n      }\n    }[]\n  }\n\n  socketPath: string\n}\n\ninterface DeleteSessionRequest {\n  socketPath?: string\n}\n\ninterface AddSessionRequest {\n  entry?: EditorSessionEntry\n}\n\ninterface GetSessionResponse {\n  socketPath?: string\n}\n\nexport async function makeEditorSessionManagerServer(\n  codeServerSocketPath: string,\n  editorSessionManager: EditorSessionManager,\n): Promise<http.Server> {\n  const router = express()\n\n  router.use(express.json())\n\n  router.get<{}, GetSessionResponse | string | unknown, undefined, { filePath?: string }>(\n    \"/session\",\n    async (req, res) => {\n      const filePath = req.query.filePath\n      if (!filePath) {\n        throw new HttpError(\"filePath is required\", HttpCode.BadRequest)\n      }\n      const socketPath = await editorSessionManager.getConnectedSocketPath(filePath)\n      const response: GetSessionResponse = { socketPath }\n      res.json(response)\n    },\n  )\n\n  router.post<{}, string, AddSessionRequest | undefined>(\"/add-session\", async (req, res) => {\n    const entry = req.body?.entry\n    if (!entry) {\n      throw new HttpError(\"entry is required\", HttpCode.BadRequest)\n    }\n    editorSessionManager.addSession(entry)\n    res.status(200).send(\"session added\")\n  })\n\n  router.post<{}, string, DeleteSessionRequest | undefined>(\"/delete-session\", async (req, res) => {\n    const socketPath = req.body?.socketPath\n    if (!socketPath) {\n      throw new HttpError(\"socketPath is required\", HttpCode.BadRequest)\n    }\n    editorSessionManager.deleteSession(socketPath)\n    res.status(200).send(\"session deleted\")\n  })\n\n  router.use(errorHandler)\n\n  const server = http.createServer(router)\n  try {\n    await listen(server, { socket: codeServerSocketPath })\n  } catch (e) {\n    logger.warn(`Could not create socket at ${codeServerSocketPath}`)\n  }\n  return server\n}\n\nexport class EditorSessionManager {\n  // Map from socket path to EditorSessionEntry.\n  private entries = new Map<string, EditorSessionEntry>()\n\n  addSession(entry: EditorSessionEntry): void {\n    logger.debug(`Adding session to session registry: ${entry.socketPath}`)\n    this.entries.set(entry.socketPath, entry)\n  }\n\n  getCandidatesForFile(filePath: string): EditorSessionEntry[] {\n    const matchCheckResults = new Map<string, boolean>()\n\n    const checkMatch = (entry: EditorSessionEntry): boolean => {\n      if (matchCheckResults.has(entry.socketPath)) {\n        return matchCheckResults.get(entry.socketPath)!\n      }\n      const result = entry.workspace.folders.some((folder) => filePath.startsWith(folder.uri.path + path.sep))\n      matchCheckResults.set(entry.socketPath, result)\n      return result\n    }\n\n    return Array.from(this.entries.values())\n      .reverse() // Most recently registered first.\n      .sort((a, b) => {\n        // Matches first.\n        const aMatch = checkMatch(a)\n        const bMatch = checkMatch(b)\n        if (aMatch === bMatch) {\n          return 0\n        }\n        if (aMatch) {\n          return -1\n        }\n        return 1\n      })\n  }\n\n  deleteSession(socketPath: string): void {\n    logger.debug(`Deleting session from session registry: ${socketPath}`)\n    this.entries.delete(socketPath)\n  }\n\n  /**\n   * Returns the best socket path that we can connect to.\n   * We also delete any sockets that we can't connect to.\n   */\n  async getConnectedSocketPath(filePath: string): Promise<string | undefined> {\n    const candidates = this.getCandidatesForFile(filePath)\n    let match: EditorSessionEntry | undefined = undefined\n\n    for (const candidate of candidates) {\n      if (await canConnect(candidate.socketPath)) {\n        match = candidate\n        break\n      }\n      this.deleteSession(candidate.socketPath)\n    }\n\n    return match?.socketPath\n  }\n}\n\nexport class EditorSessionManagerClient {\n  constructor(private codeServerSocketPath: string) {}\n\n  async canConnect() {\n    return canConnect(this.codeServerSocketPath)\n  }\n\n  async getConnectedSocketPath(filePath: string): Promise<string | undefined> {\n    const response = await new Promise<GetSessionResponse>((resolve, reject) => {\n      const opts = {\n        path: \"/session?filePath=\" + encodeURIComponent(filePath),\n        socketPath: this.codeServerSocketPath,\n        method: \"GET\",\n      }\n      const req = http.request(opts, (res) => {\n        let rawData = \"\"\n        res.setEncoding(\"utf8\")\n        res.on(\"data\", (chunk) => {\n          rawData += chunk\n        })\n        res.on(\"end\", () => {\n          try {\n            const obj = JSON.parse(rawData)\n            if (res.statusCode === 200) {\n              resolve(obj)\n            } else {\n              reject(new Error(\"Unexpected status code: \" + res.statusCode))\n            }\n          } catch (e: unknown) {\n            reject(e)\n          }\n        })\n      })\n      req.on(\"error\", reject)\n      req.end()\n    })\n    return response.socketPath\n  }\n\n  // Currently only used for tests.\n  async addSession(request: AddSessionRequest): Promise<void> {\n    await new Promise<void>((resolve, reject) => {\n      const opts = {\n        path: \"/add-session\",\n        socketPath: this.codeServerSocketPath,\n        method: \"POST\",\n        headers: {\n          \"content-type\": \"application/json\",\n          accept: \"application/json\",\n        },\n      }\n      const req = http.request(opts, () => {\n        resolve()\n      })\n      req.on(\"error\", reject)\n      req.write(JSON.stringify(request))\n      req.end()\n    })\n  }\n}\n"
  },
  {
    "path": "src/node/wrapper.ts",
    "content": "import { field, Logger, logger } from \"@coder/logger\"\nimport * as cp from \"child_process\"\nimport * as path from \"path\"\nimport * as rfs from \"rotating-file-stream\"\nimport { Emitter } from \"../common/emitter\"\nimport { DefaultedArgs, redactArgs } from \"./cli\"\nimport { paths } from \"./util\"\n\nconst timeoutInterval = 10000 // 10s, matches VS Code's timeouts.\n\n/**\n * Listen to a single message from a process. Reject if the process errors,\n * exits, or times out.\n *\n * `fn` is a function that determines whether the message is the one we're\n * waiting for.\n */\nexport function onMessage<M, T extends M>(\n  proc: cp.ChildProcess | NodeJS.Process,\n  fn: (message: M) => message is T,\n  customLogger?: Logger,\n): Promise<T> {\n  return new Promise((resolve, reject) => {\n    const cleanup = () => {\n      proc.off(\"error\", onError)\n      proc.off(\"exit\", onExit)\n      proc.off(\"message\", onMessage)\n      clearTimeout(timeout)\n    }\n\n    const timeout = setTimeout(() => {\n      cleanup()\n      reject(new Error(\"timed out\"))\n    }, timeoutInterval)\n\n    const onError = (error: Error) => {\n      cleanup()\n      reject(error)\n    }\n\n    const onExit = (code: number) => {\n      cleanup()\n      reject(new Error(`exited unexpectedly with code ${code}`))\n    }\n\n    const onMessage = (message: M) => {\n      if (fn(message)) {\n        cleanup()\n        resolve(message)\n      } else {\n        ;(customLogger || logger).debug(\"got unhandled message\", field(\"message\", message))\n      }\n    }\n\n    proc.on(\"message\", onMessage)\n    // NodeJS.Process doesn't have `error` but binding anyway shouldn't break\n    // anything. It does have `exit` but the types aren't working.\n    ;(proc as cp.ChildProcess).on(\"error\", onError)\n    ;(proc as cp.ChildProcess).on(\"exit\", onExit)\n  })\n}\n\ninterface ParentHandshakeMessage {\n  type: \"handshake\"\n  args: DefaultedArgs\n}\n\ninterface ChildHandshakeMessage {\n  type: \"handshake\"\n}\n\ninterface RelaunchMessage {\n  type: \"relaunch\"\n  version: string\n}\n\ntype ChildMessage = RelaunchMessage | ChildHandshakeMessage\ntype ParentMessage = ParentHandshakeMessage\n\nclass ProcessError extends Error {\n  public constructor(\n    message: string,\n    public readonly code: number | undefined,\n  ) {\n    super(message)\n    this.name = this.constructor.name\n    Error.captureStackTrace(this, this.constructor)\n  }\n}\n\n/**\n * Wrapper around a process that tries to gracefully exit when a process exits\n * and provides a way to prevent `process.exit`.\n */\nabstract class Process {\n  /**\n   * Emit this to trigger a graceful exit.\n   */\n  protected readonly _onDispose = new Emitter<NodeJS.Signals | undefined>()\n\n  /**\n   * Emitted when the process is about to be disposed.\n   */\n  public readonly onDispose = this._onDispose.event\n\n  /**\n   * Uniquely named logger for the process.\n   */\n  public abstract logger: Logger\n\n  public constructor() {\n    process.on(\"SIGINT\", () => this._onDispose.emit(\"SIGINT\"))\n    process.on(\"SIGTERM\", () => this._onDispose.emit(\"SIGTERM\"))\n    process.on(\"exit\", () => this._onDispose.emit(undefined))\n\n    this.onDispose((signal, wait) => {\n      // Remove listeners to avoid possibly triggering disposal again.\n      process.removeAllListeners()\n\n      // Try waiting for other handlers to run first then exit.\n      this.logger.debug(\"disposing\", field(\"code\", signal))\n      wait.then(() => this.exit(0))\n      setTimeout(() => this.exit(0), 5000)\n    })\n  }\n\n  /**\n   * Ensure control over when the process exits.\n   */\n  public preventExit(): void {\n    ;(process.exit as any) = (code?: number) => {\n      this.logger.warn(`process.exit() was prevented: ${code || \"unknown code\"}.`)\n    }\n  }\n\n  private readonly processExit: (code?: number) => never = process.exit\n\n  /**\n   * Will always exit even if normal exit is being prevented.\n   */\n  public exit(error?: number | ProcessError): never {\n    if (error && typeof error !== \"number\") {\n      this.processExit(typeof error.code === \"number\" ? error.code : 1)\n    } else {\n      this.processExit(error)\n    }\n  }\n}\n\n/**\n * Child process that will clean up after itself if the parent goes away and can\n * perform a handshake with the parent and ask it to relaunch.\n */\nexport class ChildProcess extends Process {\n  public logger = logger.named(`child:${process.pid}`)\n\n  public constructor(private readonly parentPid: number) {\n    super()\n\n    // Kill the inner process if the parent dies. This is for the case where the\n    // parent process is forcefully terminated and cannot clean up.\n    setInterval(() => {\n      try {\n        // process.kill throws an exception if the process doesn't exist.\n        process.kill(this.parentPid, 0)\n      } catch (_) {\n        // Consider this an error since it should have been able to clean up\n        // the child process unless it was forcefully killed.\n        this.logger.error(`parent process ${parentPid} died`)\n        this._onDispose.emit(undefined)\n      }\n    }, 5000)\n  }\n\n  /**\n   * Initiate the handshake and wait for a response from the parent.\n   */\n  public async handshake(): Promise<DefaultedArgs> {\n    this.logger.debug(\"initiating handshake\")\n    this.send({ type: \"handshake\" })\n    const message = await onMessage<ParentMessage, ParentHandshakeMessage>(\n      process,\n      (message): message is ParentHandshakeMessage => {\n        return message.type === \"handshake\"\n      },\n      this.logger,\n    )\n    this.logger.debug(\n      \"got message\",\n      field(\"message\", {\n        type: message.type,\n        args: redactArgs(message.args),\n      }),\n    )\n    return message.args\n  }\n\n  /**\n   * Notify the parent process that it should relaunch the child.\n   */\n  public relaunch(version: string): void {\n    this.send({ type: \"relaunch\", version })\n  }\n\n  /**\n   * Send a message to the parent.\n   */\n  private send(message: ChildMessage): void {\n    if (!process.send) {\n      throw new Error(\"not spawned with IPC\")\n    }\n    process.send(message)\n  }\n}\n\n/**\n * Parent process wrapper that spawns the child process and performs a handshake\n * with it. Will relaunch the child if it receives a SIGUSR1 or SIGUSR2 or is\n * asked to by the child. If the child otherwise exits the parent will also\n * exit.\n */\nexport class ParentProcess extends Process {\n  public logger = logger.named(`parent:${process.pid}`)\n\n  private child?: cp.ChildProcess\n  private started?: Promise<void>\n  private readonly logStdoutStream: rfs.RotatingFileStream\n  private readonly logStderrStream: rfs.RotatingFileStream\n\n  protected readonly _onChildMessage = new Emitter<ChildMessage>()\n  protected readonly onChildMessage = this._onChildMessage.event\n\n  private args?: DefaultedArgs\n\n  public constructor(private currentVersion: string) {\n    super()\n\n    process.on(\"SIGUSR1\", async () => {\n      this.logger.info(\"Received SIGUSR1; hotswapping\")\n      this.relaunch()\n    })\n\n    process.on(\"SIGUSR2\", async () => {\n      this.logger.info(\"Received SIGUSR2; hotswapping\")\n      this.relaunch()\n    })\n\n    const opts = {\n      size: \"10M\",\n      maxFiles: 10,\n      path: path.join(paths.data, \"coder-logs\"),\n    }\n    this.logStdoutStream = rfs.createStream(\"code-server-stdout.log\", opts)\n    this.logStderrStream = rfs.createStream(\"code-server-stderr.log\", opts)\n\n    this.onDispose(() => this.disposeChild())\n\n    this.onChildMessage((message) => {\n      switch (message.type) {\n        case \"relaunch\":\n          this.logger.info(`Relaunching: ${this.currentVersion} -> ${message.version}`)\n          this.currentVersion = message.version\n          this.relaunch()\n          break\n        default:\n          this.logger.error(`Unrecognized message ${message}`)\n          break\n      }\n    })\n  }\n\n  private async disposeChild(): Promise<void> {\n    this.started = undefined\n    if (this.child) {\n      const child = this.child\n      child.removeAllListeners()\n      child.kill()\n      // Wait for the child to exit otherwise its output will be lost which can\n      // be especially problematic if you're trying to debug why cleanup failed.\n      await new Promise((r) => child!.on(\"exit\", r))\n    }\n  }\n\n  private async relaunch(): Promise<void> {\n    this.disposeChild()\n    try {\n      this.started = this._start()\n      await this.started\n    } catch (error: any) {\n      this.logger.error(error.message)\n      this.exit(typeof error.code === \"number\" ? error.code : 1)\n    }\n  }\n\n  public start(args: DefaultedArgs): Promise<void> {\n    // Our logger was created before we parsed CLI arguments so update the level\n    // in case it has changed.\n    this.logger.level = logger.level\n\n    // Store for relaunches.\n    this.args = args\n    if (!this.started) {\n      this.started = this._start()\n    }\n    return this.started\n  }\n\n  private async _start(): Promise<void> {\n    const child = this.spawn()\n    this.child = child\n\n    // Log child output to stdout/stderr and to the log directory.\n    if (child.stdout) {\n      child.stdout.on(\"data\", (data) => {\n        this.logStdoutStream.write(data)\n        process.stdout.write(data)\n      })\n    }\n    if (child.stderr) {\n      child.stderr.on(\"data\", (data) => {\n        this.logStderrStream.write(data)\n        process.stderr.write(data)\n      })\n    }\n\n    this.logger.debug(`spawned child process ${child.pid}`)\n\n    await this.handshake(child)\n\n    child.once(\"exit\", (code) => {\n      this.logger.debug(`inner process ${child.pid} exited unexpectedly`)\n      this.exit(code || 0)\n    })\n  }\n\n  private spawn(): cp.ChildProcess {\n    return cp.fork(path.join(__dirname, \"entry\"), {\n      env: {\n        ...process.env,\n        CODE_SERVER_PARENT_PID: process.pid.toString(),\n        NODE_EXEC_PATH: process.execPath,\n      },\n      stdio: [\"pipe\", \"pipe\", \"pipe\", \"ipc\"],\n    })\n  }\n\n  /**\n   * Wait for a handshake from the child then reply.\n   */\n  private async handshake(child: cp.ChildProcess): Promise<void> {\n    if (!this.args) {\n      throw new Error(\"started without args\")\n    }\n    const message = await onMessage<ChildMessage, ChildHandshakeMessage>(\n      child,\n      (message): message is ChildHandshakeMessage => {\n        return message.type === \"handshake\"\n      },\n      this.logger,\n    )\n    this.logger.debug(\"got message\", field(\"message\", message))\n    this.send(child, { type: \"handshake\", args: this.args })\n  }\n\n  /**\n   * Send a message to the child.\n   */\n  private send(child: cp.ChildProcess, message: ParentMessage): void {\n    child.send(message)\n  }\n}\n\n/**\n * Process wrapper.\n */\nexport const wrapper =\n  typeof process.env.CODE_SERVER_PARENT_PID !== \"undefined\"\n    ? new ChildProcess(parseInt(process.env.CODE_SERVER_PARENT_PID))\n    : new ParentProcess(require(\"../../package.json\").version)\n\nexport function isChild(proc: ChildProcess | ParentProcess): proc is ChildProcess {\n  return proc instanceof ChildProcess\n}\n\n// It's possible that the pipe has closed (for example if you run code-server\n// --version | head -1). Assume that means we're done.\nif (!process.stdout.isTTY) {\n  process.stdout.on(\"error\", () => wrapper.exit())\n}\n\n// Don't let uncaught exceptions crash the process.\nprocess.on(\"uncaughtException\", (error) => {\n  wrapper.logger.error(`Uncaught exception: ${error.message}`)\n  if (typeof error.stack !== \"undefined\") {\n    wrapper.logger.error(error.stack)\n  }\n})\n"
  },
  {
    "path": "src/node/wsRouter.ts",
    "content": "import * as express from \"express\"\nimport * as expressCore from \"express-serve-static-core\"\nimport * as http from \"http\"\nimport * as stream from \"stream\"\nimport Websocket from \"ws\"\n\nexport interface WebsocketRequest extends express.Request {\n  ws: stream.Duplex\n  head: Buffer\n}\n\ninterface InternalWebsocketRequest extends WebsocketRequest {\n  _ws_handled: boolean\n}\n\nexport const handleUpgrade = (app: express.Express, server: http.Server): void => {\n  server.on(\"upgrade\", (req, socket, head) => {\n    socket.pause()\n\n    const wreq = req as InternalWebsocketRequest\n    wreq.ws = socket\n    wreq.head = head\n    wreq._ws_handled = false\n\n    // Send the request off to be handled by Express.\n    ;(app as any).handle(wreq, new http.ServerResponse(wreq), () => {\n      if (!wreq._ws_handled) {\n        socket.end(\"HTTP/1.1 404 Not Found\\r\\n\\r\\n\")\n      }\n    })\n  })\n}\n\nexport type WebSocketHandler = (\n  req: WebsocketRequest,\n  res: express.Response,\n  next: express.NextFunction,\n) => void | Promise<void>\n\nexport class WebsocketRouter {\n  public readonly router = express.Router()\n\n  /**\n   * Handle a websocket at this route. Note that websockets are immediately\n   * paused when they come in.\n   *\n   * If the origin header exists it must match the host or the connection will\n   * be prevented.\n   */\n  public ws(route: expressCore.PathParams, ...handlers: WebSocketHandler[]): void {\n    this.router.get(\n      route,\n      ...handlers.map((handler) => {\n        const wrapped: express.Handler = (req, res, next) => {\n          ;(req as InternalWebsocketRequest)._ws_handled = true\n          return handler(req as WebsocketRequest, res, next)\n        }\n        return wrapped\n      }),\n    )\n  }\n}\n\nexport function Router(): WebsocketRouter {\n  return new WebsocketRouter()\n}\n\nexport const wss = new Websocket.Server({ noServer: true })\n"
  },
  {
    "path": "test/e2e/baseFixture.ts",
    "content": "import { test as base } from \"@playwright/test\"\nimport { CodeServer, CodeServerPage } from \"./models/CodeServer\"\n\n/**\n * Wraps `test.describe` to create and manage an instance of code-server. If you\n * don't use this you will need to create your own code-server instance and pass\n * it to `test.use`.\n *\n * If `includeCredentials` is `true` page requests will be authenticated.\n */\nexport const describe = (\n  name: string,\n  codeServerArgs: string[],\n  codeServerEnv: NodeJS.ProcessEnv,\n  fn: (codeServer: CodeServer) => void,\n) => {\n  test.describe(name, () => {\n    // This will spawn on demand so nothing is necessary on before.\n    const codeServer = new CodeServer(name, codeServerArgs, codeServerEnv, undefined)\n\n    // Kill code-server after the suite has ended. This may happen even without\n    // doing it explicitly but it seems prudent to be sure.\n    test.afterAll(async () => {\n      await codeServer.close()\n    })\n\n    test.use({\n      // Makes `codeServer` and `authenticated` available to the extend call\n      // below.\n      codeServer,\n      // NOTE@jsjoeio some tests use --cert which uses a self-signed certificate\n      // without this option, those tests will fail.\n      ignoreHTTPSErrors: true,\n    })\n\n    fn(codeServer)\n  })\n}\n\ninterface TestFixtures {\n  codeServer: CodeServer\n  codeServerPage: CodeServerPage\n}\n\n/**\n * Create a test that spawns code-server if necessary and ensures the page is\n * ready.\n */\nexport const test = base.extend<TestFixtures>({\n  codeServer: undefined, // No default; should be provided through `test.use`.\n  codeServerPage: async ({ codeServer, page }, use) => {\n    // It's possible code-server might prevent navigation because of unsaved\n    // changes (seems to happen based on timing even if no changes have been\n    // made too). In these cases just accept.\n    page.on(\"dialog\", (d) => d.accept())\n\n    const codeServerPage = new CodeServerPage(codeServer, page)\n    await codeServerPage.navigate()\n    await use(codeServerPage)\n  },\n})\n\n/** Shorthand for test.expect. */\nexport const expect = test.expect\n"
  },
  {
    "path": "test/e2e/codeServer.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { getMaybeProxiedCodeServer } from \"../utils/helpers\"\nimport { describe, test, expect } from \"./baseFixture\"\nimport { CodeServer } from \"./models/CodeServer\"\n\ndescribe(\"code-server\", [\"--disable-workspace-trust\"], {}, () => {\n  // TODO@asher: Generalize this?  Could be nice if we were to ever need\n  // multiple migration tests in other suites.\n  const instances = new Map<string, CodeServer>()\n  test.afterAll(async () => {\n    const procs = Array.from(instances.values())\n    instances.clear()\n    await Promise.all(procs.map((cs) => cs.close()))\n  })\n\n  test(\"should navigate to home page\", async ({ codeServerPage }) => {\n    // We navigate codeServer before each test\n    // and we start the test with a storage state\n    // which means we should be logged in\n    // so it should be on the address\n    const url = codeServerPage.page.url()\n    // We use match because there may be a / at the end\n    // so we don't want it to fail if we expect http://localhost:8080 to match http://localhost:8080/\n    const address = await getMaybeProxiedCodeServer(codeServerPage)\n    expect(url).toMatch(address)\n  })\n\n  test(\"should always see the code-server editor\", async ({ codeServerPage }) => {\n    expect(await codeServerPage.isEditorVisible()).toBe(true)\n  })\n\n  test(\"should show the Integrated Terminal\", async ({ codeServerPage }) => {\n    await codeServerPage.focusTerminal()\n    expect(await codeServerPage.page.isVisible(\"#terminal\")).toBe(true)\n  })\n\n  test(\"should open a file\", async ({ codeServerPage }) => {\n    const dir = await codeServerPage.workspaceDir\n    const file = path.join(dir, \"foo\")\n    await fs.writeFile(file, \"bar\")\n    await codeServerPage.openFile(file)\n  })\n})\n"
  },
  {
    "path": "test/e2e/downloads.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { clean } from \"../utils/helpers\"\nimport { describe, test, expect } from \"./baseFixture\"\n\ndescribe(\"Downloads (enabled)\", [\"--disable-workspace-trust\"], {}, async () => {\n  const testName = \"downloads-enabled\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should see the 'Download...' option\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const tmpFilePath = path.join(workspaceDir, \"unique-file.txt\")\n    await fs.writeFile(tmpFilePath, \"hello world\")\n\n    // Action\n    await codeServerPage.openContextMenu(\"text=unique-file.txt\")\n\n    expect(await codeServerPage.page.isVisible(\"text=Download...\")).toBe(true)\n  })\n\n  test(\"should see the 'Show Local' button on Save As\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const fileName = \"unique-file-save-as.txt\"\n    const tmpFilePath = path.join(workspaceDir, fileName)\n    await fs.writeFile(tmpFilePath, \"Hello World\")\n\n    // Action\n    await codeServerPage.page.waitForSelector(`text=${fileName}`)\n\n    await codeServerPage.openFile(fileName)\n    await codeServerPage.page.click(\".tab\")\n    await codeServerPage.navigateMenus([\"File\", \"Auto Save\"])\n    await codeServerPage.page.keyboard.type(\"Making some edits.\")\n    await codeServerPage.navigateMenus([\"File\", \"Save As...\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(true)\n  })\n\n  test(\"should see the 'Show Local' button on Save File\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"New Text File\"])\n    await codeServerPage.waitForTab(\"Untitled-1\")\n    await codeServerPage.navigateMenus([\"File\", \"Save\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(true)\n  })\n\n  test(\"should see the 'Show Local' button on Save Workspace As\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"Save Workspace As...\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(true)\n  })\n})\n\ndescribe(\"Downloads (disabled)\", [\"--disable-workspace-trust\", \"--disable-file-downloads\"], {}, async () => {\n  const testName = \"downloads-disabled\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should not see the 'Download...' option\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const tmpFilePath = path.join(workspaceDir, \"unique-file.txt\")\n    await fs.writeFile(tmpFilePath, \"Hello World\")\n\n    // Action\n    await codeServerPage.openContextMenu(\"text=unique-file.txt\")\n\n    expect(await codeServerPage.page.isVisible(\"text=Download...\")).toBe(false)\n  })\n\n  test(\"should not see the 'Show Local' button on Save as\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const fileName = \"unique-file-save-as.txt\"\n    const tmpFilePath = path.join(workspaceDir, fileName)\n    await fs.writeFile(tmpFilePath, \"Hello World\")\n\n    // Action\n    await codeServerPage.page.waitForSelector(`text=${fileName}`)\n    await codeServerPage.openFile(fileName)\n    await codeServerPage.page.click(\".tab\")\n    await codeServerPage.navigateMenus([\"File\", \"Save As...\"])\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(false)\n  })\n\n  test(\"should not see the 'Show Local' button on Save File\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"New Text File\"])\n    await codeServerPage.waitForTab(\"Untitled-1\")\n    await codeServerPage.navigateMenus([\"File\", \"Save\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(false)\n  })\n\n  test(\"should not see the 'Show Local' button on Save Workspace As\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"Save Workspace As...\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(false)\n  })\n})\n"
  },
  {
    "path": "test/e2e/extensions/test-extension/.gitignore",
    "content": "/extension.js\n"
  },
  {
    "path": "test/e2e/extensions/test-extension/extension.ts",
    "content": "import * as vscode from \"vscode\"\n\nexport function activate(context: vscode.ExtensionContext) {\n  vscode.window.showInformationMessage(\"test extension loaded\")\n  // Test extension\n  context.subscriptions.push(\n    vscode.commands.registerCommand(\"codeServerTest.proxyUri\", () => {\n      if (process.env.VSCODE_PROXY_URI) {\n        vscode.window.showInformationMessage(`proxyUri: ${process.env.VSCODE_PROXY_URI}`)\n      } else {\n        vscode.window.showErrorMessage(\"No proxy URI was set\")\n      }\n    }),\n  )\n\n  // asExternalUri extension\n  context.subscriptions.push(\n    vscode.commands.registerCommand(\"codeServerTest.asExternalUri\", async () => {\n      const input = await vscode.window.showInputBox({\n        prompt: \"URL to pass through to asExternalUri\",\n      })\n\n      if (input) {\n        const output = await vscode.env.asExternalUri(vscode.Uri.parse(input))\n        vscode.window.showInformationMessage(`input: ${input} output: ${output}`)\n      } else {\n        vscode.window.showErrorMessage(`Failed to run test case. No input provided.`)\n      }\n    }),\n  )\n}\n"
  },
  {
    "path": "test/e2e/extensions/test-extension/package.json",
    "content": "{\n  \"name\": \"code-server-extension\",\n  \"description\": \"code-server test extension\",\n  \"version\": \"0.0.1\",\n  \"publisher\": \"coder\",\n  \"license\": \"MIT\",\n  \"activationEvents\": [\n    \"onStartupFinished\"\n  ],\n  \"engines\": {\n    \"vscode\": \"^1.56.0\"\n  },\n  \"main\": \"./extension.js\",\n  \"contributes\": {\n    \"commands\": [\n      {\n        \"command\": \"codeServerTest.proxyUri\",\n        \"title\": \"Get proxy URI\",\n        \"category\": \"code-server\"\n      },\n      {\n        \"command\": \"codeServerTest.asExternalUri\",\n        \"title\": \"asExternalUri test\",\n        \"category\": \"code-server\"\n      }\n    ]\n  },\n  \"devDependencies\": {\n    \"@types/vscode\": \"^1.56.0\",\n    \"typescript\": \"^5.6.2\"\n  },\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}\n"
  },
  {
    "path": "test/e2e/extensions/test-extension/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2020\",\n    \"module\": \"commonjs\",\n    \"outDir\": \".\",\n    \"strict\": true,\n    \"baseUrl\": \"./\",\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"./extension.ts\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "test/e2e/extensions.test.ts",
    "content": "import { test as base } from \"@playwright/test\"\nimport * as path from \"path\"\nimport { getMaybeProxiedCodeServer } from \"../utils/helpers\"\nimport { describe, test, expect } from \"./baseFixture\"\n\nfunction runTestExtensionTests() {\n  // This will only work if the test extension is loaded into code-server.\n  test(\"should have access to VSCODE_PROXY_URI\", async ({ codeServerPage }) => {\n    const address = await getMaybeProxiedCodeServer(codeServerPage)\n\n    await codeServerPage.waitForTestExtensionLoaded()\n    await codeServerPage.executeCommandViaMenus(\"code-server: Get proxy URI\")\n\n    // Remove end slash in address.\n    const normalizedAddress = address.replace(/\\/+$/, \"\")\n    await codeServerPage.page.getByText(`Info: proxyUri: ${normalizedAddress}/proxy/{{port}}/`)\n  })\n}\n\nconst flags = [\"--disable-workspace-trust\", \"--extensions-dir\", path.join(__dirname, \"./extensions\")]\n\ndescribe(\"Extensions\", flags, {}, () => {\n  runTestExtensionTests()\n})\n\nif (process.env.USE_PROXY !== \"1\") {\n  describe(\"Extensions with --cert\", [...flags, \"--cert\"], {}, () => {\n    runTestExtensionTests()\n  })\n} else {\n  base.describe(\"Extensions with --cert\", () => {\n    base.skip(\"skipped because USE_PROXY is set\", () => {\n      // Playwright will not show this without a function.\n    })\n  })\n}\n"
  },
  {
    "path": "test/e2e/github.test.ts",
    "content": "import { test as base } from \"@playwright/test\"\nimport { describe, expect, test } from \"./baseFixture\"\n\nif (process.env.GITHUB_TOKEN) {\n  describe(\"GitHub token\", [\"--disable-workspace-trust\"], {}, () => {\n    test(\"should be logged in to pull requests extension\", async ({ codeServerPage }) => {\n      await codeServerPage.exec(\"git init\")\n      await codeServerPage.exec(\"git remote add origin https://github.com/coder/code-server\")\n      await codeServerPage.installExtension(\"GitHub.vscode-pull-request-github\")\n      await codeServerPage.executeCommandViaMenus(\"View: Show Github\")\n      await codeServerPage.page.click(\"text=Sign in\")\n      await codeServerPage.page.click(\"text=Allow\")\n      // It should ask to select an account, one of which will be the one we\n      // pre-injected.\n      expect(await codeServerPage.page.isVisible(\"text=Select an account\")).toBe(false)\n    })\n  })\n\n  describe(\"No GitHub token\", [\"--disable-workspace-trust\"], { GITHUB_TOKEN: \"\" }, () => {\n    test(\"should not be logged in to pull requests extension\", async ({ codeServerPage }) => {\n      await codeServerPage.exec(\"git init\")\n      await codeServerPage.exec(\"git remote add origin https://github.com/coder/code-server\")\n      await codeServerPage.installExtension(\"GitHub.vscode-pull-request-github\")\n      await codeServerPage.executeCommandViaMenus(\"View: Show Github\")\n      await codeServerPage.page.click(\"text=Sign in\")\n      await codeServerPage.page.click(\"text=Allow\")\n      // Since there is no account it will ask directly for the token (because\n      // we are on localhost; otherwise it would initiate the oauth flow).\n      expect(await codeServerPage.page.isVisible(\"text=GitHub Personal Access Token\")).toBe(false)\n    })\n  })\n} else {\n  base.describe(\"GitHub token\", () => {\n    base.skip(\"skipped because GITHUB_TOKEN is not set\", () => {\n      // Playwright will not show this without a function.\n    })\n  })\n}\n"
  },
  {
    "path": "test/e2e/login.test.ts",
    "content": "import { PASSWORD } from \"../utils/constants\"\nimport { describe, test, expect } from \"./baseFixture\"\n\ndescribe(\"login\", [\"--disable-workspace-trust\", \"--auth\", \"password\"], {}, () => {\n  test(\"should see the login page\", async ({ codeServerPage }) => {\n    // It should send us to the login page\n    expect(await codeServerPage.page.title()).toBe(\"code-server login\")\n  })\n\n  test(\"should be able to login\", async ({ codeServerPage }) => {\n    // Type in password\n    await codeServerPage.page.fill(\".password\", PASSWORD)\n    // Click the submit button and login\n    await codeServerPage.page.click(\".submit\")\n    await codeServerPage.page.waitForLoadState(\"networkidle\")\n    // We do this because occassionally code-server doesn't load on Firefox\n    // but loads if you reload once or twice\n    await codeServerPage.reloadUntilEditorIsReady()\n    // Make sure the editor actually loaded\n    expect(await codeServerPage.isEditorVisible()).toBe(true)\n  })\n\n  test(\"should see an error message for missing password\", async ({ codeServerPage }) => {\n    // Skip entering password\n    // Click the submit button and login\n    await codeServerPage.page.click(\".submit\")\n    await codeServerPage.page.waitForLoadState(\"networkidle\")\n    expect(await codeServerPage.page.isVisible(\"text=Missing password\"))\n  })\n\n  test(\"should see an error message for incorrect password\", async ({ codeServerPage }) => {\n    // Type in password\n    await codeServerPage.page.fill(\".password\", \"password123\")\n    // Click the submit button and login\n    await codeServerPage.page.click(\".submit\")\n    await codeServerPage.page.waitForLoadState(\"networkidle\")\n    expect(await codeServerPage.page.isVisible(\"text=Incorrect password\"))\n  })\n\n  test(\"should hit the rate limiter for too many unsuccessful logins\", async ({ codeServerPage }) => {\n    // Type in password\n    await codeServerPage.page.fill(\".password\", \"password123\")\n    // Click the submit button and login\n    // The current RateLimiter allows 2 logins per minute plus\n    // 12 logins per hour for a total of 14\n    // See: src/node/routes/login.ts\n    for (let i = 1; i <= 14; i++) {\n      await codeServerPage.page.click(\".submit\")\n      await codeServerPage.page.waitForLoadState(\"networkidle\")\n      // We double-check that the correct error message shows\n      // which should be for incorrect password\n      expect(await codeServerPage.page.isVisible(\"text=Incorrect password\"))\n    }\n\n    // The 15th should fail for a different reason:\n    // login rate\n    await codeServerPage.page.click(\".submit\")\n    await codeServerPage.page.waitForLoadState(\"networkidle\")\n    expect(await codeServerPage.page.isVisible(\"text=Login rate limited!\"))\n  })\n})\n"
  },
  {
    "path": "test/e2e/logout.test.ts",
    "content": "// NOTE@jsjoeio commenting out until we can figure out what's wrong\n// import { describe, test, expect } from \"./baseFixture\"\n\n// describe(\"logout\", true, [\"--disable-workspace-trust\"], {}, () => {\n//   test(\"should be able logout\", async ({ codeServerPage }) => {\n//     // Recommended by Playwright for async navigation\n//     // https://github.com/microsoft/playwright/issues/1987#issuecomment-620182151\n//     await Promise.all([codeServerPage.page.waitForNavigation(), codeServerPage.navigateMenus([\"Log Out\"])])\n//     const currentUrl = codeServerPage.page.url()\n//     expect(currentUrl).toBe(`${await codeServerPage.address()}/login`)\n//   })\n// })\n"
  },
  {
    "path": "test/e2e/models/CodeServer.ts",
    "content": "import { field, Logger, logger } from \"@coder/logger\"\nimport * as cp from \"child_process\"\nimport { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { Page } from \"playwright\"\nimport * as util from \"util\"\nimport { logError, normalize, plural } from \"../../../src/common/util\"\nimport { onLine } from \"../../../src/node/util\"\nimport { PASSWORD, workspaceDir } from \"../../utils/constants\"\nimport { getMaybeProxiedCodeServer, idleTimer, tmpdir } from \"../../utils/helpers\"\n\ninterface CodeServerProcess {\n  process: cp.ChildProcess\n  address: string\n}\n\nclass Context {\n  private _canceled = false\n  private _done = false\n  public canceled(): boolean {\n    return this._canceled\n  }\n  public finished(): boolean {\n    return this._done\n  }\n  public cancel(): void {\n    this._canceled = true\n  }\n  public finish(): void {\n    this._done = true\n  }\n}\n\n/**\n * Class for spawning and managing code-server.\n */\nexport class CodeServer {\n  private process: Promise<CodeServerProcess> | undefined\n  public readonly logger: Logger\n  private closed = false\n\n  constructor(\n    name: string,\n    private readonly args: string[],\n    private readonly env: NodeJS.ProcessEnv,\n    private _workspaceDir: Promise<string> | string | undefined,\n    private readonly entry = process.env.CODE_SERVER_TEST_ENTRY || \".\",\n  ) {\n    this.logger = logger.named(name)\n  }\n\n  /**\n   * The address at which code-server can be accessed. Spawns code-server if it\n   * has not yet been spawned.\n   */\n  async address(): Promise<string> {\n    if (!this.process) {\n      this.process = this.spawn()\n    }\n    const { address } = await this.process\n\n    return address\n  }\n\n  /**\n   * The workspace directory code-server opens with.\n   */\n  get workspaceDir(): Promise<string> | string {\n    if (!this._workspaceDir) {\n      this._workspaceDir = tmpdir(workspaceDir)\n    }\n    return this._workspaceDir\n  }\n\n  /**\n   * Create a random workspace and seed it with settings.\n   */\n  private async createWorkspace(): Promise<string> {\n    const dir = await this.workspaceDir\n    await fs.mkdir(path.join(dir, \"Machine\"), { recursive: true })\n    await fs.writeFile(\n      path.join(dir, \"Machine/settings.json\"),\n      JSON.stringify({\n        \"workbench.startupEditor\": \"none\",\n      }),\n      \"utf8\",\n    )\n\n    const extensionsDir = path.join(__dirname, \"../extensions\")\n    const languagepacksContent = {\n      es: {\n        hash: \"8d919a946475223861fa0c62665a4c50\",\n        extensions: [\n          {\n            extensionIdentifier: {\n              id: \"ms-ceintl.vscode-language-pack-es\",\n              uuid: \"47e020a1-33db-4cc0-a1b4-42f97781749a\",\n            },\n            version: \"1.70.0\",\n          },\n        ],\n        translations: {\n          vscode: `${extensionsDir}/ms-ceintl.vscode-language-pack-es-1.70.0/translations/main.i18n.json`,\n        },\n        label: \"español\",\n      },\n    }\n\n    // NOTE@jsjoeio - code-server should automatically generate the languagepacks.json for\n    // using different display languages. This is a temporary workaround until we fix that.\n    await fs.writeFile(path.join(dir, \"languagepacks.json\"), JSON.stringify(languagepacksContent))\n    return dir\n  }\n\n  /**\n   * Spawn a new code-server process with its own workspace and data\n   * directories.\n   */\n  private async spawn(): Promise<CodeServerProcess> {\n    const dir = await this.createWorkspace()\n    const args = await this.argsWithDefaults([\n      \"--auth\",\n      \"none\",\n      // The workspace to open.\n      ...(this.args.includes(\"--ignore-last-opened\") ? [] : [dir]),\n      ...this.args,\n      // Using port zero will spawn on a random port.\n      \"--bind-addr\",\n      \"127.0.0.1:0\",\n    ])\n    return new Promise((resolve, reject) => {\n      this.logger.debug(\"spawning `node \" + args.join(\" \") + \"`\")\n      const proc = cp.spawn(\"node\", args, {\n        cwd: path.join(__dirname, \"../../..\"),\n        env: {\n          ...process.env,\n          ...this.env,\n          // Prevent code-server from using the existing instance when running\n          // the e2e tests from an integrated terminal.\n          VSCODE_IPC_HOOK_CLI: \"\",\n          PASSWORD,\n        },\n      })\n\n      const timer = idleTimer(\"Failed to extract address; did the format change?\", reject)\n\n      proc.on(\"error\", (error) => {\n        this.logger.error(error.message)\n        timer.dispose()\n        reject(error)\n      })\n\n      proc.on(\"close\", (code) => {\n        const error = new Error(\"code-server closed unexpectedly. Try running with LOG_LEVEL=debug to see more info.\")\n        if (!this.closed) {\n          this.logger.error(error.message, field(\"code\", code))\n        }\n        timer.dispose()\n        reject(error)\n      })\n\n      // Tracks when the HTTP and session servers are ready.\n      let httpAddress: string | undefined\n      let sessionAddress: string | undefined\n\n      let resolved = false\n      proc.stdout.setEncoding(\"utf8\")\n      onLine(proc, (line) => {\n        // As long as we are actively getting input reset the timer.  If we stop\n        // getting input and still have not found the addresses the timer will\n        // reject.\n        timer.reset()\n\n        // Log the line without the timestamp.\n        this.logger.debug(line.replace(/\\[.+\\]/, \"\"))\n        if (resolved) {\n          return\n        }\n\n        let match = line.trim().match(/HTTPS? server listening on (https?:\\/\\/[.:\\d]+)\\/?$/)\n        if (match) {\n          // Cookies don't seem to work on IP addresses so swap to localhost.\n          // TODO: Investigate whether this is a bug with code-server.\n          httpAddress = match[1].replace(\"127.0.0.1\", \"localhost\")\n        }\n\n        match = line.trim().match(/Session server listening on (.+)$/)\n        if (match) {\n          sessionAddress = match[1]\n        }\n\n        if (typeof httpAddress !== \"undefined\" && typeof sessionAddress !== \"undefined\") {\n          resolved = true\n          timer.dispose()\n          this.logger.debug(`code-server is ready: ${httpAddress} ${sessionAddress}`)\n          resolve({ process: proc, address: httpAddress })\n        }\n      })\n    })\n  }\n\n  /**\n   * Execute a short-lived command.\n   */\n  async run(args: string[]): Promise<void> {\n    args = await this.argsWithDefaults(args)\n    this.logger.debug(\"executing `node \" + args.join(\" \") + \"`\")\n    await util.promisify(cp.exec)(\"node \" + args.join(\" \"), {\n      cwd: path.join(__dirname, \"../../..\"),\n      env: {\n        ...process.env,\n        ...this.env,\n        // Prevent code-server from using the existing instance when running\n        // the e2e tests from an integrated terminal.\n        VSCODE_IPC_HOOK_CLI: \"\",\n      },\n    })\n  }\n\n  /**\n   * Combine arguments with defaults.\n   */\n  private async argsWithDefaults(args: string[]): Promise<string[]> {\n    // This will be used both as the workspace and data directory to ensure\n    // instances don't bleed into each other.\n    const dir = await this.workspaceDir\n    return [\n      this.entry,\n      \"--extensions-dir\",\n      path.join(dir, \"extensions\"),\n      ...args,\n      // Setting the XDG variables would be easier and more thorough but the\n      // modules we import ignores those variables for non-Linux operating\n      // systems so use these flags instead.\n      \"--config\",\n      path.join(dir, \"config.yaml\"),\n      \"--user-data-dir\",\n      dir,\n    ]\n  }\n\n  /**\n   * Close the code-server process.\n   */\n  async close(): Promise<void> {\n    logger.debug(\"closing\")\n    if (this.process) {\n      const proc = (await this.process).process\n      this.closed = true // To prevent the close handler from erroring.\n      proc.kill()\n    }\n  }\n\n  /**\n   * Whether or not authentication is enabled.\n   */\n  authEnabled(): boolean {\n    return this.args.includes(\"password\")\n  }\n}\n\n/**\n * This is a \"Page Object Model\" (https://playwright.dev/docs/pom/) meant to\n * wrap over a page and represent actions on that page in a more readable way.\n * This targets a specific code-server instance which must be passed in.\n * Navigation and setup performed by this model will cause the code-server\n * process to spawn if it hasn't yet.\n */\nexport class CodeServerPage {\n  private readonly editorSelector = \"div.monaco-workbench\"\n\n  constructor(\n    private readonly codeServer: CodeServer,\n    public readonly page: Page,\n  ) {\n    this.page.on(\"console\", (message) => {\n      this.codeServer.logger.debug(message.text())\n    })\n    this.page.on(\"pageerror\", (error) => {\n      logError(this.codeServer.logger, \"page\", error)\n    })\n  }\n\n  address() {\n    return this.codeServer.address()\n  }\n\n  /**\n   * The workspace directory code-server opens with.\n   */\n  get workspaceDir() {\n    return this.codeServer.workspaceDir\n  }\n\n  /**\n   * Navigate to a code-server endpoint (root by default).  Then wait for the\n   * editor to become available.\n   */\n  async navigate(endpoint = \"/\") {\n    const address = await getMaybeProxiedCodeServer(this.codeServer)\n    const noramlizedUrl = normalize(address + endpoint, true)\n    const to = new URL(noramlizedUrl)\n\n    this.codeServer.logger.info(`navigating to ${to}`)\n    await this.page.goto(to.toString())\n\n    // Only reload editor if auth is not enabled. Otherwise we'll get stuck\n    // reloading the login page.\n    if (!this.codeServer.authEnabled()) {\n      await this.reloadUntilEditorIsReady()\n    }\n  }\n\n  /**\n   * Checks if the editor is visible\n   * and that we are connected to the host\n   *\n   * Reload until both checks pass\n   */\n  async reloadUntilEditorIsReady() {\n    this.codeServer.logger.debug(\"Waiting for editor to be ready...\")\n\n    const editorIsVisible = await this.isEditorVisible()\n    let reloadCount = 0\n\n    // Occassionally code-server timeouts in Firefox\n    // we're not sure why\n    // but usually a reload or two fixes it\n    // TODO@jsjoeio @oxy look into Firefox reconnection/timeout issues\n    while (!editorIsVisible) {\n      // When a reload happens, we want to wait for all resources to be\n      // loaded completely. Hence why we use that instead of DOMContentLoaded\n      // Read more: https://thisthat.dev/dom-content-loaded-vs-load/\n      await this.page.waitForLoadState(\"load\")\n      // Give it an extra second just in case it's feeling extra slow\n      await this.page.waitForTimeout(1000)\n      reloadCount += 1\n      if (await this.isEditorVisible()) {\n        this.codeServer.logger.debug(`editor became ready after ${reloadCount} reloads`)\n        break\n      }\n      await this.page.reload()\n    }\n\n    this.codeServer.logger.debug(\"Editor is ready!\")\n  }\n\n  /**\n   * Checks if the editor is visible\n   */\n  async isEditorVisible() {\n    this.codeServer.logger.debug(\"Waiting for editor to be visible...\")\n    // Make sure the editor actually loaded\n    await this.page.waitForSelector(this.editorSelector)\n    const visible = await this.page.isVisible(this.editorSelector)\n\n    this.codeServer.logger.debug(`Editor is ${visible ? \"not visible\" : \"visible\"}!`)\n\n    return visible\n  }\n\n  /**\n   * Checks if the test extension loaded\n   */\n  async waitForTestExtensionLoaded(): Promise<void> {\n    const selector = \"text=test extension loaded\"\n    this.codeServer.logger.debug(\"Waiting for test extension to load...\")\n\n    await this.page.waitForSelector(selector)\n  }\n\n  /**\n   * Focuses the integrated terminal by navigating through the command palette.\n   *\n   * This should focus the terminal no matter if it already has focus and/or is\n   * or isn't visible already.  It will always create a new terminal to avoid\n   * clobbering parallel tests.\n   */\n  async focusTerminal() {\n    const doFocus = async (): Promise<boolean> => {\n      await this.executeCommandViaMenus(\"Terminal: Create New Terminal\")\n      try {\n        await this.page.waitForLoadState(\"load\")\n        await this.page.waitForSelector(\"textarea.xterm-helper-textarea:focus-within\", { timeout: 5000 })\n        return true\n      } catch (error) {\n        return false\n      }\n    }\n\n    let attempts = 1\n    while (!(await doFocus())) {\n      ++attempts\n      this.codeServer.logger.debug(`no focused terminal textarea, retrying (${attempts}/∞)`)\n    }\n\n    this.codeServer.logger.debug(`opening terminal took ${attempts} ${plural(attempts, \"attempt\")}`)\n  }\n\n  /**\n   * Open a file by using menus.\n   */\n  async openFile(file: string) {\n    await this.navigateMenus([\"File\", \"Open File...\"])\n    await this.navigateQuickInput([path.basename(file)])\n    await this.waitForTab(file)\n  }\n\n  /**\n   * Open a file through an external command.\n   */\n  async openFileExternally(file: string) {\n    await this.codeServer.run([\"--reuse-window\", file])\n  }\n\n  /**\n   * Wait for a tab to open for the specified file.\n   */\n  async waitForTab(file: string): Promise<void> {\n    await this.page.waitForSelector(`.tab :text(\"${path.basename(file)}\")`)\n  }\n\n  /**\n   * See if the specified tab is open.\n   */\n  async tabIsVisible(file: string): Promise<boolean> {\n    return this.page.isVisible(`.tab :text(\"${path.basename(file)}\")`)\n  }\n\n  /**\n   * Navigate to the command palette via menus then execute a command by typing\n   * it then clicking the match from the results.\n   */\n  async executeCommandViaMenus(command: string) {\n    await this.navigateMenus([\"View\", \"Command Palette...\"])\n\n    await this.page.keyboard.type(command)\n\n    await this.page.hover(`text=${command}`)\n    await this.page.click(`text=${command}`)\n  }\n\n  /**\n   * Navigate through the items in the selector.  `open` is a function that will\n   * open the menu/popup containing the items through which to navigation.\n   */\n  async navigateItems(items: string[], selector: string, open?: (selector: string) => void): Promise<void> {\n    const logger = this.codeServer.logger.named(selector)\n\n    /**\n     * If the selector loses focus or gets removed this will resolve with false,\n     * signaling we need to try again.\n     */\n    const openThenWaitClose = async (ctx: Context) => {\n      if (open) {\n        await open(selector)\n      }\n      this.codeServer.logger.debug(`watching ${selector}`)\n      try {\n        await this.page.waitForSelector(`${selector}:not(:focus-within)`)\n      } catch (error) {\n        if (!ctx.finished()) {\n          this.codeServer.logger.debug(`${selector} navigation: ${(error as any).message || error}`)\n        }\n      }\n      return false\n    }\n\n    /**\n     * This will step through each item, aborting and returning false if\n     * canceled or if any navigation step has an error which signals we need to\n     * try again.\n     */\n    const navigate = async (ctx: Context) => {\n      const steps: Array<{ fn: () => Promise<unknown>; name: string }> = [\n        {\n          fn: () => this.page.waitForSelector(`${selector}:focus-within`),\n          name: \"focus\",\n        },\n      ]\n\n      for (const item of items) {\n        // Normally these will wait for the item to be visible and then execute\n        // the action. The problem is that if the menu closes these will still\n        // be waiting and continue to execute once the menu is visible again,\n        // potentially conflicting with the new set of navigations (for example\n        // if the old promise clicks logout before the new one can). By\n        // splitting them into two steps each we can cancel before running the\n        // action.\n        steps.push({\n          fn: () => this.page.hover(`${selector} :text-is(\"${item}\")`, { trial: true }),\n          name: `${item}:hover:trial`,\n        })\n        steps.push({\n          fn: () => this.page.hover(`${selector} :text-is(\"${item}\")`, { force: true }),\n          name: `${item}:hover:force`,\n        })\n        steps.push({\n          fn: () => this.page.click(`${selector} :text-is(\"${item}\")`, { trial: true }),\n          name: `${item}:click:trial`,\n        })\n        steps.push({\n          fn: () => this.page.click(`${selector} :text-is(\"${item}\")`, { force: true }),\n          name: `${item}:click:force`,\n        })\n      }\n\n      for (const step of steps) {\n        try {\n          logger.debug(`navigation step: ${step.name}`)\n          await step.fn()\n          if (ctx.canceled()) {\n            logger.debug(\"navigation canceled\")\n            return false\n          }\n        } catch (error) {\n          logger.debug(`navigation: ${(error as any).message || error}`)\n          return false\n        }\n      }\n      return true\n    }\n\n    // We are seeing the menu closing after opening if we open it too soon and\n    // the picker getting recreated in the middle of trying to select an item.\n    // To counter this we will keep trying to navigate through the items every\n    // time we lose focus or there is an error.\n    let attempts = 1\n    let context = new Context()\n    while (!(await Promise.race([openThenWaitClose(context), navigate(context)]))) {\n      ++attempts\n      logger.debug(`closed, retrying (${attempts}/∞)`)\n      context.cancel()\n      context = new Context()\n    }\n\n    context.finish()\n    logger.debug(`navigation took ${attempts} ${plural(attempts, \"attempt\")}`)\n  }\n\n  /**\n   * Navigate through a currently opened \"quick input\" widget, retrying on\n   * failure.\n   */\n  async navigateQuickInput(items: string[]): Promise<void> {\n    await this.navigateItems(items, \".quick-input-widget\")\n  }\n\n  /**\n   * Navigate through the menu, retrying on failure.\n   */\n  async navigateMenus(menus: string[]): Promise<void> {\n    await this.navigateItems(menus, '[aria-label=\"Application Menu\"]', async (selector) => {\n      await this.page.click(selector)\n    })\n  }\n\n  /**\n   * Open context menu on the specified selector.\n   */\n  async openContextMenu(selector: string): Promise<void> {\n    const el = await this.page.waitForSelector(selector)\n    await el.click({ button: \"right\" })\n    await this.page.waitForSelector(\".context-view-block\")\n  }\n\n  /**\n   * Execute a command in the root of the instance's workspace directory.\n   */\n  async exec(command: string): Promise<void> {\n    await util.promisify(cp.exec)(command, {\n      cwd: await this.workspaceDir,\n    })\n  }\n\n  /**\n   * Install an extension by ID to the instance's temporary extension\n   * directory.\n   */\n  async installExtension(id: string): Promise<void> {\n    const dir = path.join(await this.workspaceDir, \"extensions\")\n    await util.promisify(cp.exec)(`node . --install-extension ${id} --extensions-dir ${dir}`, {\n      cwd: path.join(__dirname, \"../../..\"),\n    })\n  }\n\n  /**\n   * Wait for state to be flushed to the database.\n   */\n  async stateFlush(): Promise<void> {\n    // If we reload too quickly VS Code will be unable to save the state changes\n    // so wait until those have been written to the database.  It flushes every\n    // five seconds so we need to wait at least that long.\n    // TODO@asher: There must be a better way.\n    await this.page.waitForTimeout(5500)\n  }\n}\n"
  },
  {
    "path": "test/e2e/openHelpAbout.test.ts",
    "content": "import { version } from \"../../src/node/constants\"\nimport { describe, test, expect } from \"./baseFixture\"\n\ndescribe(\"Open Help > About\", [\"--disable-workspace-trust\"], {}, () => {\n  test(\"should see code-server version in about dialog\", async ({ codeServerPage }) => {\n    // Open using the menu.\n    await codeServerPage.navigateMenus([\"Help\", \"About\"])\n\n    const isDevMode = process.env.VSCODE_DEV === \"1\"\n\n    // Look for code-server info div.\n    const element = await codeServerPage.page.waitForSelector(\n      `div[role=\"dialog\"] >> text=code-server: ${isDevMode ? \"Unknown\" : \"v\" + version}`,\n    )\n    expect(element).not.toBeNull()\n  })\n})\n"
  },
  {
    "path": "test/e2e/routes.test.ts",
    "content": "import { clean, getMaybeProxiedPathname } from \"../utils/helpers\"\nimport { describe, test, expect } from \"./baseFixture\"\n\nconst routes = {\n  \"/\": [\n    /\\.\\/manifest.json/,\n    /\\.\\/_static\\//,\n    /[a-z]+-[0-9a-z]+\\/static\\//,\n    /http:\\/\\/localhost:[0-9]+\\/[a-z]+-[0-9a-z]+\\/static\\//,\n  ],\n  \"/vscode\": [\n    /\\.\\/vscode\\/manifest.json/,\n    /\\.\\/_static\\//,\n    /vscode\\/[a-z]+-[0-9a-z]+\\/static\\//,\n    /http:\\/\\/localhost:[0-9]+\\/vscode\\/[a-z]+-[0-9a-z]+\\/static\\//,\n  ],\n  \"/vscode/\": [\n    /\\.\\/manifest.json/,\n    /\\.\\/\\.\\.\\/_static\\//,\n    /[a-z]+-[0-9a-z]+\\/static\\//,\n    /http:\\/\\/localhost:[0-9]+\\/vscode\\/[a-z]+-[0-9a-z]+\\/static\\//,\n  ],\n}\n\ndescribe(\"VS Code Routes\", [\"--disable-workspace-trust\"], {}, async () => {\n  const testName = \"vscode-routes-default\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should load all route variations\", async ({ codeServerPage }) => {\n    for (const [route, matchers] of Object.entries(routes)) {\n      await codeServerPage.navigate(route)\n\n      // Check there were no redirections\n      const url = new URL(codeServerPage.page.url())\n      const pathname = getMaybeProxiedPathname(url)\n      expect(pathname).toBe(route)\n\n      // Check that assets are pointing to the right spot.  Some will be\n      // relative, without a leading dot (VS Code's assets).  Some will be\n      // relative with a leading dot (our assets).  Others will have been\n      // resolved against the origin.\n      const elements = await codeServerPage.page.locator(\"[src]\").all()\n      for (const element of elements) {\n        const src = await element.getAttribute(\"src\")\n        if (src && !matchers.some((m) => m.test(src))) {\n          throw new Error(`${src} did not match any validators for route ${route}`)\n        }\n      }\n    }\n  })\n})\n\nconst CODE_WORKSPACE_DIR = process.env.CODE_WORKSPACE_DIR || \"\"\ndescribe(\"VS Code Routes with code-workspace\", [\"--disable-workspace-trust\", CODE_WORKSPACE_DIR], {}, async () => {\n  test(\"should redirect to the passed in workspace using human-readable query\", async ({ codeServerPage }) => {\n    const url = new URL(codeServerPage.page.url())\n    const pathname = getMaybeProxiedPathname(url)\n    expect(pathname).toBe(\"/\")\n    expect(url.search).toBe(`?workspace=${CODE_WORKSPACE_DIR}`)\n  })\n})\n\nconst CODE_FOLDER_DIR = process.env.CODE_FOLDER_DIR || \"\"\ndescribe(\"VS Code Routes with code-workspace\", [\"--disable-workspace-trust\", CODE_FOLDER_DIR], {}, async () => {\n  test(\"should redirect to the passed in folder using human-readable query\", async ({ codeServerPage }) => {\n    const url = new URL(codeServerPage.page.url())\n    const pathname = getMaybeProxiedPathname(url)\n    expect(pathname).toBe(\"/\")\n    expect(url.search).toBe(`?folder=${CODE_FOLDER_DIR}`)\n  })\n})\n\ndescribe(\n  \"VS Code Routes with ignore-last-opened\",\n  [\"--disable-workspace-trust\", \"--ignore-last-opened\"],\n  {},\n  async () => {\n    test(\"should not redirect\", async ({ codeServerPage }) => {\n      const folder = process.env.CODE_FOLDER_DIR\n\n      await codeServerPage.navigate(`/?folder=${folder}`)\n      await codeServerPage.navigate(`/`)\n\n      const url = new URL(codeServerPage.page.url())\n      const pathname = getMaybeProxiedPathname(url)\n      expect(pathname).toBe(\"/\")\n      expect(url.search).toBe(\"\")\n    })\n  },\n)\n\ndescribe(\"VS Code Routes with no workspace or folder\", [\"--disable-workspace-trust\"], {}, async () => {\n  test(\"should redirect to last query folder/workspace\", async ({ codeServerPage }) => {\n    const folder = process.env.CODE_FOLDER_DIR\n    const workspace = process.env.CODE_WORKSPACE_DIR\n    await codeServerPage.navigate(`/?folder=${folder}&workspace=${workspace}`)\n\n    // If you visit again without query parameters it will re-attach them by\n    // redirecting.  It should always redirect to the same route.\n    for (const route of Object.keys(routes)) {\n      await codeServerPage.navigate(route)\n      const url = new URL(codeServerPage.page.url())\n      const pathname = getMaybeProxiedPathname(url)\n      expect(pathname).toBe(route)\n      expect(url.search).toBe(`?folder=${folder}&workspace=${workspace}`)\n    }\n  })\n})\n\ndescribe(\"VS Code Routes with no workspace or folder\", [\"--disable-workspace-trust\"], {}, async () => {\n  test(\"should not redirect if ew passed in\", async ({ codeServerPage }) => {\n    const folder = process.env.CODE_FOLDER_DIR\n    const workspace = process.env.CODE_WORKSPACE_DIR\n    await codeServerPage.navigate(`/?folder=${folder}&workspace=${workspace}`)\n\n    // Closing the folder should stop the redirecting.\n    await codeServerPage.navigate(\"/?ew=true\")\n    const url = new URL(codeServerPage.page.url())\n    const pathname = getMaybeProxiedPathname(url)\n    expect(pathname).toBe(\"/\")\n    expect(url.search).toBe(\"?ew=true\")\n  })\n})\n"
  },
  {
    "path": "test/e2e/terminal.test.ts",
    "content": "import * as cp from \"child_process\"\nimport { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport util from \"util\"\nimport { clean, getMaybeProxiedCodeServer, tmpdir } from \"../utils/helpers\"\nimport { describe, expect, test } from \"./baseFixture\"\n\ndescribe(\"Integrated Terminal\", [\"--disable-workspace-trust\"], {}, () => {\n  const testName = \"integrated-terminal\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should have access to VSCODE_PROXY_URI\", async ({ codeServerPage }) => {\n    const tmpFolderPath = await tmpdir(testName)\n    const tmpFile = path.join(tmpFolderPath, \"pipe\")\n\n    const command = `mkfifo '${tmpFile}' && cat '${tmpFile}'`\n    const exec = util.promisify(cp.exec)\n    const output = exec(command, { encoding: \"utf8\" })\n\n    // Open terminal and type in value\n    await codeServerPage.focusTerminal()\n\n    await codeServerPage.page.keyboard.type(`printenv VSCODE_PROXY_URI > ${tmpFile}`)\n    await codeServerPage.page.keyboard.press(\"Enter\")\n\n    const { stdout } = await output\n    const address = await getMaybeProxiedCodeServer(codeServerPage)\n    expect(stdout).toMatch(address)\n  })\n\n  // TODO@jsjoeio - add test to make sure full code-server path works\n  test(\"should be able to invoke `code-server` to open a file\", async ({ codeServerPage }) => {\n    const tmpFolderPath = await tmpdir(testName)\n    const tmpFile = path.join(tmpFolderPath, \"test-file\")\n    await fs.writeFile(tmpFile, \"test\")\n\n    await codeServerPage.focusTerminal()\n\n    await codeServerPage.page.keyboard.type(`code-server ${tmpFile}`)\n    await codeServerPage.page.keyboard.press(\"Enter\")\n\n    await codeServerPage.waitForTab(path.basename(tmpFile))\n\n    const externalTmpFile = path.join(tmpFolderPath, \"test-external-file\")\n    await fs.writeFile(externalTmpFile, \"foobar\")\n\n    await codeServerPage.openFileExternally(externalTmpFile)\n\n    await codeServerPage.waitForTab(path.basename(externalTmpFile))\n  })\n})\n"
  },
  {
    "path": "test/e2e/uploads.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { clean } from \"../utils/helpers\"\nimport { describe, test, expect } from \"./baseFixture\"\n\ndescribe(\"Uploads (enabled)\", [\"--disable-workspace-trust\"], {}, () => {\n  const testName = \"uploads-enabled\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should see the 'Upload...' option\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const tmpDirPath = path.join(workspaceDir, \"test-directory\")\n    await fs.mkdir(tmpDirPath)\n\n    // Action\n    await codeServerPage.openContextMenu('span:has-text(\"test-directory\")')\n\n    expect(await codeServerPage.page.isVisible(\"text=Upload...\")).toBe(true)\n  })\n\n  test(\"should see the 'Show Local' button on Open File\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"Open File...\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(true)\n  })\n})\n\ndescribe(\"Uploads (disabled)\", [\"--disable-workspace-trust\", \"--disable-file-uploads\"], {}, () => {\n  const testName = \"uploads-disabled\"\n  test.beforeAll(async () => {\n    await clean(testName)\n  })\n\n  test(\"should not see the 'Upload...' option\", async ({ codeServerPage }) => {\n    // Setup\n    const workspaceDir = await codeServerPage.workspaceDir\n    const tmpDirPath = path.join(workspaceDir, \"test-directory\")\n    await fs.mkdir(tmpDirPath)\n\n    // Action\n    await codeServerPage.openContextMenu('span:has-text(\"test-directory\")')\n\n    expect(await codeServerPage.page.isVisible(\"text=Upload...\")).toBe(false)\n  })\n\n  test(\"should not see the 'Show Local' button on Open File\", async ({ codeServerPage }) => {\n    // Action\n    await codeServerPage.navigateMenus([\"File\", \"Open File...\"])\n    await codeServerPage.page.waitForSelector(\".quick-input-widget\")\n    expect(await codeServerPage.page.isVisible(\"text=Show Local\")).toBe(false)\n  })\n})\n"
  },
  {
    "path": "test/e2e/webview.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { describe, test, expect } from \"./baseFixture\"\n\ndescribe(\"Webviews\", [\"--disable-workspace-trust\"], {}, () => {\n  test(\"should preview a Markdown file\", async ({ codeServerPage }) => {\n    // Create Markdown file\n    const heading = \"Hello world\"\n    const dir = await codeServerPage.workspaceDir\n    const file = path.join(dir, \"text.md\")\n    await fs.writeFile(file, `# ${heading}`)\n    await codeServerPage.openFile(file)\n\n    // Open Preview\n    await codeServerPage.executeCommandViaMenus(\"Markdown: Open Preview to the Side\")\n    // Wait for the iframe to open and load\n    await codeServerPage.waitForTab(`Preview ${file}`)\n\n    // It's an iframe within an iframe\n    // so we have to do .frameLocator twice\n    await expect(\n      codeServerPage.page.frameLocator(\"iframe.webview.ready\").frameLocator(\"#active-frame\").getByText(\"Hello world\"),\n    ).toBeVisible()\n  })\n})\n"
  },
  {
    "path": "test/integration/help.test.ts",
    "content": "import { runCodeServerCommand } from \"../utils/runCodeServerCommand\"\n\n// NOTE@jsjoeio\n// We have this test to ensure that native modules\n// work as expected. If this is called on the wrong\n// platform, the test will fail.\ndescribe(\"--help\", () => {\n  it(\"should list code-server usage\", async () => {\n    const expectedOutput = \"Usage: code-server [options] [path]\"\n    const { stdout } = await runCodeServerCommand([\"--help\"])\n    expect(stdout).toMatch(expectedOutput)\n  }, 20000)\n})\n"
  },
  {
    "path": "test/integration/installExtension.test.ts",
    "content": "import { clean, tmpdir } from \"../utils/helpers\"\nimport { runCodeServerCommand } from \"../utils/runCodeServerCommand\"\n\ndescribe(\"--install-extension\", () => {\n  const testName = \"installExtension\"\n  let tempDir: string\n  let setupFlags: string[]\n\n  beforeEach(async () => {\n    await clean(testName)\n    tempDir = await tmpdir(testName)\n    setupFlags = [\"--extensions-dir\", tempDir]\n  })\n  it(\"should use EXTENSIONS_GALLERY when set\", async () => {\n    const extName = \"author.extension\"\n    await expect(\n      runCodeServerCommand([...setupFlags, \"--install-extension\", extName], {\n        EXTENSIONS_GALLERY: \"{}\",\n      }),\n    ).rejects.toThrow(\"No extension gallery service configured\")\n  })\n})\n"
  },
  {
    "path": "test/package.json",
    "content": "{\n  \"license\": \"MIT\",\n  \"#\": \"We must put jest in a sub-directory otherwise VS Code somehow picks up the types and generates conflicts with mocha.\",\n  \"devDependencies\": {\n    \"@jest-mock/express\": \"^1.4.5\",\n    \"@playwright/test\": \"^1.56.1\",\n    \"@types/jest\": \"^27.0.2\",\n    \"@types/jsdom\": \"^16.2.13\",\n    \"@types/node-fetch\": \"^2.5.8\",\n    \"@types/wtfnode\": \"^0.7.0\",\n    \"argon2\": \"^0.44.0\",\n    \"extract-zip\": \"^2.0.1\",\n    \"jest\": \"^27.3.1\",\n    \"jest-fetch-mock\": \"^3.0.3\",\n    \"jsdom\": \"^16.4.0\",\n    \"node-fetch\": \"^2.6.7\",\n    \"playwright\": \"^1.56.1\",\n    \"ts-jest\": \"^27.0.7\",\n    \"wtfnode\": \"^0.9.1\"\n  },\n  \"resolutions\": {\n    \"ansi-regex\": \"^5.0.1\",\n    \"set-value\": \"^4.0.1\",\n    \"tmpl\": \"^1.0.5\",\n    \"path-parse\": \"^1.0.7\",\n    \"json-schema\": \"^0.4.0\"\n  }\n}\n"
  },
  {
    "path": "test/playwright.config.ts",
    "content": "import { PlaywrightTestConfig } from \"@playwright/test\"\n\nimport path from \"path\"\n\n// The default configuration runs all tests in three browsers with workers equal\n// to half the available threads. See 'npm run test:e2e --help' to customize\n// from the command line. For example:\n//   npm run test:e2e --workers 1        # Run with one worker\n//   npm run test:e2e --project Chromium # Only run on Chromium\n//   npm run test:e2e --grep login       # Run tests matching \"login\"\n//   PWDEBUG=1 npm run test:e2e          # Run Playwright inspector\nconst config: PlaywrightTestConfig = {\n  testDir: path.join(__dirname, \"e2e\"), // Search for tests in this directory.\n  timeout: 60000, // Each test is given 60 seconds.\n  retries: process.env.CI ? 2 : 1, // Retry in CI due to flakiness.\n  // Limit the number of failures on CI to save resources\n  maxFailures: process.env.CI ? 3 : undefined,\n  globalSetup: require.resolve(\"./utils/globalE2eSetup.ts\"),\n  reporter: \"list\",\n  // Put any shared options on the top level.\n  use: {\n    headless: true, // Run tests in headless browsers.\n    video: \"retain-on-failure\",\n  },\n\n  projects: [\n    {\n      name: \"Chromium\",\n      use: { browserName: \"chromium\" },\n    },\n    // Firefox seems to have bugs with opening context menus in the file tree.\n    // {\n    //   name: \"Firefox\",\n    //   use: { browserName: \"firefox\" },\n    // },\n    {\n      name: \"WebKit\",\n      use: { browserName: \"webkit\" },\n    },\n  ],\n}\n\nexport default config\n"
  },
  {
    "path": "test/scripts/build-lib.bats",
    "content": "#!/usr/bin/env bats\n\nSCRIPT_NAME=\"build-lib.sh\"\nSCRIPT=\"$BATS_TEST_DIRNAME/../../ci/build/$SCRIPT_NAME\"\n\nsource \"$SCRIPT\"\n\n@test \"get_nfpm_arch should return armhfp for rpm on armv7l\" {\n  run get_nfpm_arch rpm armv7l\n  [ \"$output\" = \"armhfp\" ]\n}\n\n@test \"get_nfpm_arch should return armhf for deb on armv7l\" {\n  run get_nfpm_arch deb armv7l\n  [ \"$output\" = \"armhf\" ]\n}\n\n@test \"get_nfpm_arch should return arch if no arch override exists \" {\n  run get_nfpm_arch deb i386\n  [ \"$output\" = \"i386\" ]\n}"
  },
  {
    "path": "test/scripts/install.bats",
    "content": "#!/usr/bin/env bats\n\nSCRIPT_NAME=\"install.sh\"\nSCRIPT=\"$BATS_TEST_DIRNAME/../../$SCRIPT_NAME\"\n\n# Override version so it doesn't have to curl and to avoid caching in case the\n# user already has the latest version installed.\nexport VERSION=\"9999.99.9\"\n\nfunction should-use-deb() {\n  DISTRO=$1 ARCH=$2 OS=linux run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing v$VERSION of the $2 deb package from GitHub.\" ]\n  [ \"${lines[-6]}\" = \"deb package has been installed.\" ]\n}\n\nfunction should-use-rpm() {\n  DISTRO=$1 ARCH=$2 OS=linux run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing v$VERSION of the $2 rpm package from GitHub.\" ]\n  [ \"${lines[-6]}\" = \"rpm package has been installed.\" ]\n}\n\nfunction should-fallback-npm() {\n  YARN_PATH=true DISTRO=$1 ARCH=$2 OS=linux run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"No standalone releases for $2.\" ]\n  [ \"${lines[2]}\" = \"Falling back to installation from npm.\" ]\n  [ \"${lines[3]}\" = \"Installing v$VERSION from npm.\" ]\n  [ \"${lines[-6]}\" = \"npm package has been installed.\" ]\n}\n\nfunction should-use-npm() {\n  YARN_PATH=true DISTRO=$1 ARCH=$2 OS=linux run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing v$VERSION from npm.\" ]\n  [ \"${lines[-6]}\" = \"npm package has been installed.\" ]\n}\n\nfunction should-use-aur() {\n  DISTRO=$1 ARCH=$2 OS=linux run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing latest from the AUR.\" ]\n  [ \"${lines[-6]}\" = \"AUR package has been installed.\" ]\n}\n\nfunction should-fallback-npm-brew() {\n  YARN_PATH=true BREW_PATH= OS=macos ARCH=$1 run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Homebrew not installed.\" ]\n  [ \"${lines[2]}\" = \"Falling back to standalone installation.\" ]\n  [ \"${lines[3]}\" = \"No standalone releases for $1.\" ]\n  [ \"${lines[4]}\" = \"Falling back to installation from npm.\" ]\n  [ \"${lines[5]}\" = \"Installing v$VERSION from npm.\" ]\n  [ \"${lines[-6]}\" = \"npm package has been installed.\" ]\n}\n\nfunction should-use-brew() {\n  BREW_PATH=true OS=macos ARCH=$1 run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing latest from Homebrew.\" ]\n  [ \"${lines[-4]}\" = \"Brew release has been installed.\" ]\n}\n\nfunction should-use-standalone() {\n  DISTRO=$1 ARCH=$2 OS=$3 run \"$SCRIPT\" --method standalone --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Installing v$VERSION of the $2 release from GitHub.\" ]\n  [[ \"${lines[-6]}\" = \"Standalone release has been installed\"* ]]\n}\n\n@test \"$SCRIPT_NAME: usage with --help\" {\n  run \"$SCRIPT\" --help\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[0]}\" = \"Installs code-server.\" ]\n  [[ \"${lines[-1]}\" = \"More installation docs are at\"* ]]\n}\n\n# These use the deb but fall back to npm for unsupported architectures.\n@test \"$SCRIPT_NAME: debian arm64\" {\n  should-use-deb \"debian\" \"arm64\"\n}\n@test \"$SCRIPT_NAME: debian amd64\" {\n  should-use-deb \"debian\" \"amd64\"\n}\n@test \"$SCRIPT_NAME: debian i386\" {\n  should-fallback-npm \"debian\" \"i386\"\n}\n\n# These use the rpm but fall back to npm for unsupported architectures.\n@test \"$SCRIPT_NAME: fedora arm64\" {\n  should-use-rpm \"fedora\" \"arm64\"\n}\n@test \"$SCRIPT_NAME: fedora amd64\" {\n  should-use-rpm \"fedora\" \"amd64\"\n}\n@test \"$SCRIPT_NAME: fedora i386\" {\n  should-fallback-npm \"fedora\" \"i386\"\n}\n\n# These always use npm regardless of the architecture.\n@test \"$SCRIPT_NAME: alpine arm64\" {\n  should-use-npm \"alpine\" \"arm64\"\n}\n@test \"$SCRIPT_NAME: alpine amd64\" {\n  should-use-npm \"alpine\" \"amd64\"\n}\n@test \"$SCRIPT_NAME: alpine i386\" {\n  should-use-npm \"alpine\" \"i386\"\n}\n\n@test \"$SCRIPT_NAME: freebsd arm64\" {\n  should-use-npm \"freebsd\" \"arm64\"\n}\n@test \"$SCRIPT_NAME: freebsd amd64\" {\n  should-use-npm \"freebsd\" \"amd64\"\n}\n@test \"$SCRIPT_NAME: freebsd i386\" {\n  should-use-npm \"freebsd\" \"i386\"\n}\n\n# Arch Linux uses AUR but falls back to npm for unsuppported architectures.\n@test \"$SCRIPT_NAME: arch arm64\" {\n  should-use-aur \"arch\" \"arm64\"\n}\n@test \"$SCRIPT_NAME: arch amd64\" {\n  should-use-aur \"arch\" \"amd64\"\n}\n@test \"$SCRIPT_NAME: arch i386\" {\n  should-fallback-npm \"arch\" \"i386\"\n}\n\n# macOS use homebrew but falls back to standalone when brew is unavailable then\n# to npm for unsupported architectures.\n@test \"$SCRIPT_NAME: macos amd64 (no brew)\" {\n  should-fallback-npm-brew \"amd64\"\n}\n@test \"$SCRIPT_NAME: macos arm64 (no brew)\" {\n  BREW_PATH= OS=macos ARCH=arm64 run \"$SCRIPT\" --dry-run\n  [ \"$status\" -eq 0 ]\n  [ \"${lines[1]}\" = \"Homebrew not installed.\" ]\n  [ \"${lines[2]}\" = \"Falling back to standalone installation.\" ]\n  [ \"${lines[3]}\" = \"Installing v$VERSION of the arm64 release from GitHub.\" ]\n  [[ \"${lines[-6]}\" = \"Standalone release has been installed\"* ]]\n}\n@test \"$SCRIPT_NAME: macos i386 (no brew)\" {\n  should-fallback-npm-brew \"i386\"\n}\n\n@test \"$SCRIPT_NAME: macos arm64 (brew)\" {\n  should-use-brew \"arm64\"\n}\n@test \"$SCRIPT_NAME: macos amd64 (brew)\" {\n  should-use-brew \"amd64\"\n}\n@test \"$SCRIPT_NAME: macos i386 (brew)\" {\n  should-use-brew \"i386\"\n}\n\n# Force standalone.\n@test \"$SCRIPT_NAME: debian amd64 --method standalone\" {\n  should-use-standalone \"debian\" \"amd64\" \"linux\"\n}\n"
  },
  {
    "path": "test/scripts/steps-lib.bats",
    "content": "#!/usr/bin/env bats\n\nSCRIPT_NAME=\"steps-lib.sh\"\nSCRIPT=\"$BATS_TEST_DIRNAME/../../ci/steps/$SCRIPT_NAME\"\n\nsource \"$SCRIPT\"\n\n@test \"is_env_var_set should return 1 if env var is not set\" {\n  run is_env_var_set \"ASDF_TEST_SET\"\n  [ \"$status\" = 1 ]\n}\n\n@test \"is_env_var_set should return 0 if env var is set\" {\n  ASDF_TEST_SET=\"test\" run is_env_var_set \"ASDF_TEST_SET\"\n  [ \"$status\" = 0 ]\n}\n\n@test \"directory_exists should 1 if directory doesn't exist\" {\n  run directory_exists \"/tmp/asdfasdfasdf\"\n  [ \"$status\" = 1 ]\n}\n\n@test \"directory_exists should 0 if directory exists\" {\n  run directory_exists \"$(pwd)\"\n  [ \"$status\" = 0 ]\n}\n\n@test \"file_exists should 1 if file doesn't exist\" {\n  run file_exists \"hello-asfd.sh\"\n  [ \"$status\" = 1 ]\n}\n\n@test \"file_exists should 0 if file exists\" {\n  run file_exists \"$SCRIPT\"\n  [ \"$status\" = 0 ]\n}\n\n@test \"is_executable should 1 if file isn't executable\" {\n  run is_executable \"hello-asfd.sh\"\n  [ \"$status\" = 1 ]\n}\n\n@test \"is_executable should 0 if file is executable\" {\n  run is_executable \"$SCRIPT\"\n  [ \"$status\" = 0 ]\n}"
  },
  {
    "path": "test/tsconfig.json",
    "content": "{\n  \"extends\": \"../tsconfig.json\",\n  \"include\": [\"./**/*.ts\"]\n}\n"
  },
  {
    "path": "test/unit/common/emitter.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { Emitter } from \"../../../src/common/emitter\"\nimport { mockLogger } from \"../../utils/helpers\"\n\ndescribe(\"emitter\", () => {\n  beforeEach(() => {\n    mockLogger()\n  })\n\n  afterEach(() => {\n    jest.clearAllMocks()\n  })\n\n  it(\"should run the correct callbacks\", async () => {\n    const HELLO_WORLD = \"HELLO_WORLD\"\n    const GOODBYE_WORLD = \"GOODBYE_WORLD\"\n    const mockCallback = jest.fn(() => \"Mock function called\")\n    const mockSecondCallback = jest.fn(() => undefined)\n\n    const emitter = new Emitter<{ event: string; callback: () => void }>()\n\n    const onHelloWorld = ({ event, callback }: { event: string; callback: () => void }): void => {\n      if (event === HELLO_WORLD) {\n        callback()\n      }\n    }\n\n    const onGoodbyeWorld = ({ event, callback }: { event: string; callback: () => void }): void => {\n      if (event === GOODBYE_WORLD) {\n        callback()\n      }\n    }\n\n    // Register the onHelloWorld listener\n    // and the onGoodbyeWorld\n    const _onHelloWorld = emitter.event(onHelloWorld)\n    emitter.event(onGoodbyeWorld)\n\n    await emitter.emit({ event: HELLO_WORLD, callback: mockCallback })\n\n    // Double-check that our callback is called only once\n    expect(mockCallback).toHaveBeenCalled()\n    expect(mockCallback).toHaveBeenCalledTimes(1)\n\n    await emitter.emit({ event: GOODBYE_WORLD, callback: mockSecondCallback })\n\n    // Check that it works with multiple listeners\n    expect(mockSecondCallback).toHaveBeenCalled()\n    expect(mockSecondCallback).toHaveBeenCalledTimes(1)\n\n    // Dispose of individual listener\n    _onHelloWorld.dispose()\n\n    // Try disposing twice\n    _onHelloWorld.dispose()\n\n    // Dispose of all the listeners\n    emitter.dispose()\n  })\n\n  it(\"should log an error if something goes wrong\", async () => {\n    const HELLO_WORLD = \"HELLO_WORLD\"\n    const mockCallback = jest.fn(() => \"Mock function called\")\n    const message = \"You don't have access to that folder.\"\n\n    const emitter = new Emitter<{ event: string; callback: () => void }>()\n\n    const onHelloWorld = ({ event, callback }: { event: string; callback: () => void }): void => {\n      if (event === HELLO_WORLD) {\n        callback()\n        throw new Error(message)\n      }\n    }\n\n    emitter.event(onHelloWorld)\n\n    await emitter.emit({ event: HELLO_WORLD, callback: mockCallback })\n\n    // Check that error was called\n    expect(logger.error).toHaveBeenCalled()\n    expect(logger.error).toHaveBeenCalledTimes(1)\n    expect(logger.error).toHaveBeenCalledWith(message)\n  })\n})\n"
  },
  {
    "path": "test/unit/common/http.test.ts",
    "content": "import { HttpCode, HttpError } from \"../../../src/common/http\"\n\ndescribe(\"http\", () => {\n  describe(\"HttpCode\", () => {\n    it(\"should return the correct HTTP codes\", () => {\n      expect(HttpCode.Ok).toBe(200)\n      expect(HttpCode.Redirect).toBe(302)\n      expect(HttpCode.NotFound).toBe(404)\n      expect(HttpCode.BadRequest).toBe(400)\n      expect(HttpCode.Unauthorized).toBe(401)\n      expect(HttpCode.LargePayload).toBe(413)\n      expect(HttpCode.ServerError).toBe(500)\n    })\n  })\n\n  describe(\"HttpError\", () => {\n    it(\"should work as expected\", () => {\n      const message = \"Bad request from client\"\n      const httpError = new HttpError(message, HttpCode.BadRequest)\n\n      expect(httpError.message).toBe(message)\n      expect(httpError.statusCode).toBe(400)\n      expect(httpError.details).toBeUndefined()\n    })\n    it(\"should have details if provided\", () => {\n      const details = {\n        message: \"User needs to be signed-in in order to perform action\",\n      }\n      const message = \"Unauthorized\"\n      const httpError = new HttpError(message, HttpCode.BadRequest, details)\n\n      expect(httpError.details).toStrictEqual(details)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/common/util.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { JSDOM } from \"jsdom\"\nimport * as util from \"../../../src/common/util\"\nimport { mockLogger } from \"../../utils/helpers\"\n\nconst dom = new JSDOM()\nglobal.document = dom.window.document\n\nexport type LocationLike = Pick<Location, \"pathname\" | \"origin\">\n\ndescribe(\"util\", () => {\n  describe(\"normalize\", () => {\n    it(\"should remove multiple slashes\", () => {\n      expect(util.normalize(\"//foo//bar//baz///mumble\")).toBe(\"/foo/bar/baz/mumble\")\n    })\n\n    it(\"should remove trailing slashes\", () => {\n      expect(util.normalize(\"qux///\")).toBe(\"qux\")\n    })\n\n    it(\"should preserve trailing slash if it exists\", () => {\n      expect(util.normalize(\"qux///\", true)).toBe(\"qux/\")\n      expect(util.normalize(\"qux\", true)).toBe(\"qux\")\n    })\n  })\n\n  describe(\"plural\", () => {\n    it(\"should add an s if count is greater than 1\", () => {\n      expect(util.plural(2, \"dog\")).toBe(\"dogs\")\n    })\n    it(\"should NOT add an s if the count is 1\", () => {\n      expect(util.plural(1, \"dog\")).toBe(\"dog\")\n    })\n  })\n\n  describe(\"generateUuid\", () => {\n    it(\"should generate a unique uuid\", () => {\n      const uuid = util.generateUuid()\n      const uuid2 = util.generateUuid()\n      expect(uuid).toHaveLength(24)\n      expect(typeof uuid).toBe(\"string\")\n      expect(uuid).not.toBe(uuid2)\n    })\n    it(\"should generate a uuid of a specific length\", () => {\n      const uuid = util.generateUuid(10)\n      expect(uuid).toHaveLength(10)\n    })\n  })\n\n  describe(\"logError\", () => {\n    beforeAll(() => {\n      mockLogger()\n    })\n\n    afterEach(() => {\n      jest.clearAllMocks()\n    })\n\n    it(\"should log an error with the message and stack trace\", () => {\n      const message = \"You don't have access to that folder.\"\n      const error = new Error(message)\n\n      util.logError(logger, \"ui\", error)\n\n      expect(logger.error).toHaveBeenCalled()\n      expect(logger.error).toHaveBeenCalledWith(`ui: ${error.message} ${error.stack}`)\n    })\n\n    it(\"should log an error, even if not an instance of error\", () => {\n      util.logError(logger, \"api\", \"oh no\")\n\n      expect(logger.error).toHaveBeenCalled()\n      expect(logger.error).toHaveBeenCalledWith(\"api: oh no\")\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/helpers.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport { clean, getAvailablePort, getMaybeProxiedPathname, tmpdir, useEnv } from \"../../test/utils/helpers\"\nimport { REVERSE_PROXY_BASE_PATH } from \"../utils/constants\"\n\n/**\n * This file is for testing test helpers (not core code).\n */\ndescribe(\"test helpers\", () => {\n  const testName = \"temp-dir\"\n  beforeAll(async () => {\n    await clean(testName)\n  })\n\n  it(\"should return a temp directory\", async () => {\n    const pathToTempDir = await tmpdir(testName)\n    expect(pathToTempDir).toContain(testName)\n    expect(fs.access(pathToTempDir)).resolves.toStrictEqual(undefined)\n  })\n})\n\ndescribe(\"useEnv\", () => {\n  beforeAll(() => {\n    jest.resetModules()\n    process.env.TEST_USE_ENV = \"test environment variable\"\n  })\n  afterAll(() => {\n    delete process.env.TEST_USE_ENV\n  })\n  it(\"should set and reset the env var\", () => {\n    const envKey = \"TEST_ENV_VAR\"\n    const [setValue, resetValue] = useEnv(envKey)\n    setValue(\"hello-world\")\n    expect(process.env[envKey]).toEqual(\"hello-world\")\n    resetValue()\n    expect(process.env[envKey]).toEqual(undefined)\n  })\n  it(\"should set and reset the env var where a value was already set\", () => {\n    const envKey = \"TEST_USE_ENV\"\n    expect(process.env[envKey]).toEqual(\"test environment variable\")\n    const [setValue, resetValue] = useEnv(envKey)\n    setValue(\"hello there\")\n    expect(process.env[envKey]).toEqual(\"hello there\")\n    resetValue()\n    expect(process.env[envKey]).toEqual(\"test environment variable\")\n  })\n})\n\ndescribe(\"getAvailablePort\", () => {\n  it(\"should return a valid port\", async () => {\n    const port = await getAvailablePort()\n    expect(port).toBeGreaterThan(0)\n    expect(port).toBeLessThanOrEqual(65535)\n  })\n  it(\"should return different ports for different calls\", async () => {\n    const portOne = await getAvailablePort()\n    const portTwo = await getAvailablePort()\n    expect(portOne).not.toEqual(portTwo)\n  })\n})\n\ndescribe(\"getMaybeProxiedPathname\", () => {\n  it(\"should return the route\", () => {\n    const route = \"/vscode\"\n    const url = new URL(`http://localhost:3000${route}`)\n    const actual = getMaybeProxiedPathname(url)\n    expect(actual).toBe(route)\n  })\n  it(\"should strip proxy if env var set\", () => {\n    const envKey = \"USE_PROXY\"\n    const [setValue, resetValue] = useEnv(envKey)\n    setValue(\"1\")\n    const route = \"/vscode\"\n    const url = new URL(`http://localhost:3000/8000/${REVERSE_PROXY_BASE_PATH}${route}`)\n    const actual = getMaybeProxiedPathname(url)\n    expect(actual).toBe(route)\n    resetValue()\n  })\n})\n"
  },
  {
    "path": "test/unit/node/app.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { promises } from \"fs\"\nimport * as http from \"http\"\nimport * as https from \"https\"\nimport * as path from \"path\"\nimport { createApp, ensureAddress, handleArgsSocketCatchError, listen } from \"../../../src/node/app\"\nimport { OptionalString, setDefaults } from \"../../../src/node/cli\"\nimport { generateCertificate } from \"../../../src/node/util\"\nimport { clean, mockLogger, getAvailablePort, tmpdir } from \"../../utils/helpers\"\n\ndescribe(\"createApp\", () => {\n  let unlinkSpy: jest.SpyInstance\n  let port: number\n  let tmpDirPath: string\n  let tmpFilePath: string\n\n  beforeAll(async () => {\n    mockLogger()\n\n    const testName = \"app\"\n    await clean(testName)\n    tmpDirPath = await tmpdir(testName)\n    tmpFilePath = path.join(tmpDirPath, \"unlink-socket-file\")\n  })\n\n  beforeEach(async () => {\n    // NOTE:@jsjoeio\n    // Be mindful when spying.\n    // You can't spy on fs functions if you do import * as fs\n    // You have to import individually, like we do here with promises\n    // then you can spy on those modules methods, like unlink.\n    // See: https://github.com/aelbore/esbuild-jest/issues/26#issuecomment-893763840\n    unlinkSpy = jest.spyOn(promises, \"unlink\")\n    port = await getAvailablePort()\n  })\n\n  afterEach(() => {\n    jest.clearAllMocks()\n  })\n\n  it(\"should return an Express app, a WebSockets Express app and an http server\", async () => {\n    const defaultArgs = await setDefaults({\n      port,\n    })\n    const app = await createApp(defaultArgs)\n\n    // This doesn't check much, but it's a good sanity check\n    // to ensure we actually get back values from createApp\n    expect(app.router).not.toBeNull()\n    expect(app.wsRouter).not.toBeNull()\n    expect(app.server).toBeInstanceOf(http.Server)\n\n    // Cleanup\n    app.dispose()\n  })\n\n  it(\"should handle error events on the server\", async () => {\n    const defaultArgs = await setDefaults({\n      port,\n    })\n\n    const app = await createApp(defaultArgs)\n\n    const testError = new Error(\"Test error\")\n    // We can easily test how the server handles errors\n    // By emitting an error event\n    // Ref: https://stackoverflow.com/a/33872506/3015595\n    app.server.emit(\"error\", testError)\n    expect(logger.error).toHaveBeenCalledTimes(1)\n    expect(logger.error).toHaveBeenCalledWith(`http server error: ${testError.message} ${testError.stack}`)\n\n    // Cleanup\n    app.dispose()\n  })\n\n  it(\"should reject errors that happen before the server can listen\", async () => {\n    // We listen on an invalid port\n    // causing the app to reject the Promise called at startup\n    const port = 2\n    const defaultArgs = await setDefaults({\n      port,\n    })\n\n    async function masterBall() {\n      const app = await createApp(defaultArgs)\n\n      const testError = new Error(\"Test error\")\n\n      app.server.emit(\"error\", testError)\n\n      // Cleanup\n      app.dispose()\n    }\n\n    expect(() => masterBall()).rejects.toThrow(\"listen EACCES: permission denied\")\n  })\n\n  it(\"should unlink a socket before listening on the socket\", async () => {\n    await promises.writeFile(tmpFilePath, \"\")\n    const defaultArgs = await setDefaults({\n      socket: tmpFilePath,\n    })\n\n    const app = await createApp(defaultArgs)\n\n    expect(unlinkSpy).toHaveBeenCalledWith(tmpFilePath)\n    app.dispose()\n  })\n\n  it(\"should change the file mode of a socket\", async () => {\n    const defaultArgs = await setDefaults({\n      socket: tmpFilePath,\n      \"socket-mode\": \"777\",\n    })\n\n    const app = await createApp(defaultArgs)\n\n    expect((await promises.stat(tmpFilePath)).mode & 0o777).toBe(0o777)\n    app.dispose()\n  })\n\n  it(\"should create an https server if args.cert exists\", async () => {\n    const testCertificate = await generateCertificate(\"localhost\")\n    const cert = new OptionalString(testCertificate.cert)\n    const defaultArgs = await setDefaults({\n      port,\n      cert,\n      [\"cert-key\"]: testCertificate.certKey,\n    })\n    const app = await createApp(defaultArgs)\n\n    // This doesn't check much, but it's a good sanity check\n    // to ensure we actually get an https.Server\n    expect(app.server).toBeInstanceOf(https.Server)\n\n    // Cleanup\n    app.dispose()\n  })\n})\n\ndescribe(\"ensureAddress\", () => {\n  let mockServer: http.Server\n\n  beforeEach(() => {\n    mockServer = http.createServer()\n  })\n\n  afterEach(() => {\n    mockServer.close()\n  })\n\n  it(\"should throw and error if no address\", () => {\n    expect(() => ensureAddress(mockServer, \"http\")).toThrow(\"Server has no address\")\n  })\n  it(\"should return the address if it's a string\", async () => {\n    mockServer.address = () => \"/path/to/unix.sock\"\n    const address = ensureAddress(mockServer, \"http\")\n    expect(address.toString()).toBe(`/path/to/unix.sock`)\n  })\n  it(\"should construct URL with an IPv4 address\", async () => {\n    mockServer.address = () => ({ address: \"1.2.3.4\", port: 5678, family: \"IPv4\" })\n    const address = ensureAddress(mockServer, \"http\")\n    expect(address.toString()).toBe(`http://1.2.3.4:5678/`)\n  })\n  it(\"should construct URL with an IPv6 address\", async () => {\n    mockServer.address = () => ({ address: \"a:b:c:d::1234\", port: 5678, family: \"IPv6\" })\n    const address = ensureAddress(mockServer, \"http\")\n    expect(address.toString()).toBe(`http://[a:b:c:d::1234]:5678/`)\n  })\n})\n\ndescribe(\"handleArgsSocketCatchError\", () => {\n  beforeAll(() => {\n    mockLogger()\n  })\n\n  afterEach(() => {\n    jest.clearAllMocks()\n  })\n\n  it(\"should log an error if its not an NodeJS.ErrnoException\", () => {\n    const message = \"other message\"\n    const error = new Error(message)\n\n    expect(() => {\n      handleArgsSocketCatchError(error)\n    }).toThrowError(error)\n  })\n\n  it(\"should log an error if its not an NodeJS.ErrnoException (and the error has a message)\", () => {\n    const errorMessage = \"handleArgsSocketCatchError Error\"\n    const error = new Error(errorMessage)\n\n    expect(() => {\n      handleArgsSocketCatchError(error)\n    }).toThrowError(error)\n  })\n\n  it(\"should not log an error if its a NodeJS.ErrnoException\", () => {\n    const code = \"ENOENT\"\n    const error: NodeJS.ErrnoException = new Error(code)\n    error.code = code\n\n    handleArgsSocketCatchError(error)\n\n    expect(() => {\n      handleArgsSocketCatchError(error)\n    }).not.toThrowError()\n  })\n\n  it(\"should log an error if the code is not ENOENT (and the error has a message)\", () => {\n    const errorMessage = \"no access\"\n    const error: NodeJS.ErrnoException = new Error()\n    error.code = \"EACCESS\"\n    error.message = errorMessage\n\n    expect(() => {\n      handleArgsSocketCatchError(error)\n    }).toThrowError(error)\n  })\n\n  it(\"should log an error if the code is not ENOENT\", () => {\n    const code = \"EACCESS\"\n    const error: NodeJS.ErrnoException = new Error(code)\n    error.code = code\n\n    expect(() => {\n      handleArgsSocketCatchError(error)\n    }).toThrowError(error)\n  })\n})\n\ndescribe(\"listen\", () => {\n  let tmpDirPath: string\n  let mockServer: http.Server\n\n  const testName = \"listen\"\n\n  beforeEach(async () => {\n    await clean(testName)\n    mockLogger()\n    tmpDirPath = await tmpdir(testName)\n    mockServer = http.createServer()\n  })\n\n  afterEach(() => {\n    mockServer.close()\n    jest.clearAllMocks()\n  })\n\n  it(\"should throw an error if a directory is passed in instead of a file\", async () => {\n    const errorMessage = \"EISDIR: illegal operation on a directory, unlink\"\n    const port = await getAvailablePort()\n    const mockArgs = { port, host: \"0.0.0.0\", socket: tmpDirPath }\n\n    try {\n      await listen(mockServer, mockArgs)\n    } catch (error) {\n      expect(error).toBeInstanceOf(Error)\n      expect((error as any).message).toMatch(errorMessage)\n    }\n  })\n})\n"
  },
  {
    "path": "test/unit/node/cli.test.ts",
    "content": "import { Level, logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport {\n  UserProvidedArgs,\n  bindAddrFromArgs,\n  defaultConfigFile,\n  parse,\n  parseConfigFile,\n  setDefaults,\n  shouldOpenInExistingInstance,\n  toCodeArgs,\n  optionDescriptions,\n  options,\n  Options,\n  AuthType,\n  OptionalString,\n} from \"../../../src/node/cli\"\nimport { shouldSpawnCliProcess } from \"../../../src/node/main\"\nimport { generatePassword, paths } from \"../../../src/node/util\"\nimport {\n  EditorSessionManager,\n  EditorSessionManagerClient,\n  makeEditorSessionManagerServer,\n} from \"../../../src/node/vscodeSocket\"\nimport { clean, useEnv, tmpdir, listenOn } from \"../../utils/helpers\"\n\n// The parser should not set any defaults so the caller can determine what\n// values the user actually set. These are only set after explicitly calling\n// `setDefaults`.\nconst defaults = {\n  auth: \"password\",\n  host: \"localhost\",\n  port: 8080,\n  \"proxy-domain\": [],\n  usingEnvPassword: false,\n  usingEnvHashedPassword: false,\n  \"extensions-dir\": path.join(paths.data, \"extensions\"),\n  \"user-data-dir\": paths.data,\n  \"session-socket\": path.join(paths.data, \"code-server-ipc.sock\"),\n  \"app-name\": \"code-server\",\n  _: [],\n}\n\ndescribe(\"parser\", () => {\n  beforeEach(() => {\n    delete process.env.LOG_LEVEL\n    delete process.env.PASSWORD\n    delete process.env.CS_DISABLE_FILE_DOWNLOADS\n    delete process.env.CS_DISABLE_GETTING_STARTED_OVERRIDE\n    delete process.env.VSCODE_PROXY_URI\n    delete process.env.CS_DISABLE_PROXY\n    console.log = jest.fn()\n  })\n\n  it(\"should parse nothing\", async () => {\n    expect(parse([])).toStrictEqual({})\n  })\n\n  it(\"should parse all available options\", async () => {\n    expect(\n      parse(\n        [\n          [\"--enable\", \"feature1\"],\n          [\"--enable\", \"feature2\"],\n\n          \"--bind-addr=192.169.0.1:8080\",\n\n          [\"--auth\", \"none\"],\n\n          [\"--extensions-dir\", \"path/to/ext/dir\"],\n\n          [\"--builtin-extensions-dir\", \"path/to/builtin/ext/dir\"],\n\n          \"1\",\n          \"--verbose\",\n          [\"--app-name\", \"custom instance name\"],\n          [\"--welcome-text\", \"welcome to code\"],\n          [\"--i18n\", \"path/to/custom-strings.json\"],\n          \"2\",\n\n          [\"--locale\", \"ja\"],\n\n          [\"--log\", \"error\"],\n\n          \"--help\",\n\n          \"--open\",\n\n          \"--socket=mumble\",\n\n          \"--socket-mode=777\",\n\n          \"3\",\n\n          [\"--user-data-dir\", \"path/to/user/dir\"],\n\n          [\"--cert=path/to/cert\", \"--cert-key\", \"path/to/cert/key\"],\n\n          \"--version\",\n\n          \"--json\",\n\n          \"--port=8081\",\n\n          \"--disable-file-downloads\",\n\n          \"--disable-getting-started-override\",\n\n          \"--disable-proxy\",\n\n          [\"--abs-proxy-base-path\", \"/codeserver/app1\"],\n\n          \"--skip-auth-preflight\",\n\n          [\"--session-socket\", \"/tmp/override-code-server-ipc-socket\"],\n\n          [\"--host\", \"0.0.0.0\"],\n          \"4\",\n          \"--\",\n          \"--5\",\n        ].flat(),\n      ),\n    ).toEqual({\n      _: [\"1\", \"2\", \"3\", \"4\", \"--5\"],\n      auth: \"none\",\n      \"builtin-extensions-dir\": path.resolve(\"path/to/builtin/ext/dir\"),\n      \"extensions-dir\": path.resolve(\"path/to/ext/dir\"),\n      \"user-data-dir\": path.resolve(\"path/to/user/dir\"),\n      \"cert-key\": path.resolve(\"path/to/cert/key\"),\n      cert: {\n        value: path.resolve(\"path/to/cert\"),\n      },\n      \"disable-file-downloads\": true,\n      \"disable-getting-started-override\": true,\n      \"disable-proxy\": true,\n      enable: [\"feature1\", \"feature2\"],\n      help: true,\n      host: \"0.0.0.0\",\n      json: true,\n      locale: \"ja\",\n      log: \"error\",\n      open: true,\n      port: 8081,\n      socket: path.resolve(\"mumble\"),\n      \"socket-mode\": \"777\",\n      verbose: true,\n      \"app-name\": \"custom instance name\",\n      \"welcome-text\": \"welcome to code\",\n      i18n: path.resolve(\"path/to/custom-strings.json\"),\n      version: true,\n      \"bind-addr\": \"192.169.0.1:8080\",\n      \"session-socket\": \"/tmp/override-code-server-ipc-socket\",\n      \"abs-proxy-base-path\": \"/codeserver/app1\",\n      \"skip-auth-preflight\": true,\n    })\n  })\n\n  it(\"should work with short options\", async () => {\n    expect(parse([\"-vvv\", \"-v\"])).toEqual({\n      verbose: true,\n      version: true,\n    })\n  })\n\n  it(\"should use log level env var\", async () => {\n    const args = parse([])\n    expect(args).toEqual({})\n\n    process.env.LOG_LEVEL = \"debug\"\n    const defaults = await setDefaults(args)\n    expect(defaults).toStrictEqual({\n      ...defaults,\n      log: \"debug\",\n      verbose: false,\n    })\n    expect(process.env.LOG_LEVEL).toEqual(\"debug\")\n    expect(logger.level).toEqual(Level.Debug)\n\n    process.env.LOG_LEVEL = \"trace\"\n    const updated = await setDefaults(args)\n    expect(updated).toStrictEqual({\n      ...updated,\n      log: \"trace\",\n      verbose: true,\n    })\n    expect(process.env.LOG_LEVEL).toEqual(\"trace\")\n    expect(logger.level).toEqual(Level.Trace)\n  })\n\n  it(\"should prefer --log to env var and --verbose to --log\", async () => {\n    let args = parse([\"--log\", \"info\"])\n    expect(args).toEqual({\n      log: \"info\",\n    })\n\n    process.env.LOG_LEVEL = \"debug\"\n    const defaults = await setDefaults(args)\n    expect(defaults).toEqual({\n      ...defaults,\n      log: \"info\",\n      verbose: false,\n    })\n    expect(process.env.LOG_LEVEL).toEqual(\"info\")\n    expect(logger.level).toEqual(Level.Info)\n\n    process.env.LOG_LEVEL = \"trace\"\n    const updated = await setDefaults(args)\n    expect(updated).toEqual({\n      ...defaults,\n      log: \"info\",\n      verbose: false,\n    })\n    expect(process.env.LOG_LEVEL).toEqual(\"info\")\n    expect(logger.level).toEqual(Level.Info)\n\n    args = parse([\"--log\", \"info\", \"--verbose\"])\n    expect(args).toEqual({\n      log: \"info\",\n      verbose: true,\n    })\n\n    process.env.LOG_LEVEL = \"warn\"\n    const updatedAgain = await setDefaults(args)\n    expect(updatedAgain).toEqual({\n      ...defaults,\n      log: \"trace\",\n      verbose: true,\n    })\n    expect(process.env.LOG_LEVEL).toEqual(\"trace\")\n    expect(logger.level).toEqual(Level.Trace)\n  })\n\n  it(\"should set valid log level env var\", async () => {\n    process.env.LOG_LEVEL = \"error\"\n    const defaults = await setDefaults(parse([]))\n    expect(defaults).toEqual({\n      ...defaults,\n      log: \"error\",\n    })\n  })\n\n  it(\"should ignore invalid log level env var\", async () => {\n    process.env.LOG_LEVEL = \"bogus\"\n    const defaults = await setDefaults(parse([]))\n    expect(defaults).toEqual({\n      ...defaults,\n    })\n  })\n\n  it(\"should error if value isn't provided\", () => {\n    expect(() => parse([\"--auth\"])).toThrowError(/--auth requires a value/)\n    expect(() => parse([\"--auth=\", \"--log=debug\"])).toThrowError(/--auth requires a value/)\n    expect(() => parse([\"--auth\", \"--log\"])).toThrowError(/--auth requires a value/)\n    expect(() => parse([\"--auth\", \"--invalid\"])).toThrowError(/--auth requires a value/)\n    expect(() => parse([\"--bind-addr\"])).toThrowError(/--bind-addr requires a value/)\n  })\n\n  it(\"should error if value is invalid\", () => {\n    expect(() => parse([\"--port\", \"foo\"])).toThrowError(/--port must be a number/)\n    expect(() => parse([\"--auth\", \"invalid\"])).toThrowError(/--auth valid values: \\[password, none\\]/)\n    expect(() => parse([\"--log\", \"invalid\"])).toThrowError(/--log valid values: \\[trace, debug, info, warn, error\\]/)\n  })\n\n  it(\"should error if the option doesn't exist\", () => {\n    expect(() => parse([\"--foo\"])).toThrowError(/Unknown option --foo/)\n  })\n\n  it(\"should not error if the value is optional\", async () => {\n    expect(parse([\"--cert\"])).toEqual({\n      cert: {\n        value: undefined,\n      },\n    })\n  })\n\n  it(\"should not allow option-like values\", () => {\n    expect(() => parse([\"--socket\", \"--socket-path-value\"])).toThrowError(/--socket requires a value/)\n    // If you actually had a path like this you would do this instead:\n    expect(parse([\"--socket\", \"./--socket-path-value\"])).toEqual({\n      socket: path.resolve(\"--socket-path-value\"),\n    })\n    expect(() => parse([\"--cert\", \"--socket-path-value\"])).toThrowError(/Unknown option --socket-path-value/)\n  })\n\n  it(\"should allow positional arguments before options\", async () => {\n    expect(parse([\"test\", \"--auth\", \"none\"])).toEqual({\n      _: [\"test\"],\n      auth: \"none\",\n    })\n  })\n\n  it(\"should support repeatable flags\", async () => {\n    expect(() => parse([\"--proxy-domain\", \"\"])).toThrowError(/--proxy-domain requires a value/)\n    expect(parse([\"--proxy-domain\", \"*.coder.com\"])).toEqual({\n      \"proxy-domain\": [\"*.coder.com\"],\n    })\n    expect(parse([\"--proxy-domain\", \"*.coder.com\", \"--proxy-domain\", \"test.com\"])).toEqual({\n      \"proxy-domain\": [\"*.coder.com\", \"test.com\"],\n    })\n    // Commas are literal, at the moment.\n    expect(parse([\"--proxy-domain\", \"*.coder.com,test.com\"])).toEqual({\n      \"proxy-domain\": [\"*.coder.com,test.com\"],\n    })\n  })\n\n  it(\"should enforce cert-key with cert value or otherwise generate one\", async () => {\n    const args = parse([\"--cert\"])\n    expect(args).toEqual({\n      cert: {\n        value: undefined,\n      },\n    })\n    expect(() => parse([\"--cert\", \"test\"])).toThrowError(/--cert-key is missing/)\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      cert: {\n        value: path.join(paths.data, \"localhost.crt\"),\n      },\n      \"cert-key\": path.join(paths.data, \"localhost.key\"),\n    })\n  })\n\n  it(\"should use env var password\", async () => {\n    process.env.PASSWORD = \"test\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      password: \"test\",\n      usingEnvPassword: true,\n    })\n  })\n\n  it(\"should use env var hashed password\", async () => {\n    process.env.HASHED_PASSWORD =\n      \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\" // test\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"hashed-password\":\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n      usingEnvHashedPassword: true,\n    })\n  })\n\n  it(\"should parse i18n flag with file path\", async () => {\n    // Test with file path (no validation at CLI parsing level)\n    const args = parse([\"--i18n\", \"/path/to/custom-strings.json\"])\n    expect(args).toEqual({\n      i18n: \"/path/to/custom-strings.json\",\n    })\n  })\n\n  it(\"should parse i18n flag with relative file path\", async () => {\n    // Test with relative file path\n    expect(() => parse([\"--i18n\", \"./custom-strings.json\"])).not.toThrow()\n    expect(() => parse([\"--i18n\", \"strings.json\"])).not.toThrow()\n  })\n\n  it(\"should support app-name and deprecated welcome-text flags\", async () => {\n    const args = parse([\"--app-name\", \"My App\", \"--welcome-text\", \"Welcome!\"])\n    expect(args).toEqual({\n      \"app-name\": \"My App\",\n      \"welcome-text\": \"Welcome!\",\n    })\n  })\n\n  it(\"should use env var github token\", async () => {\n    process.env.GITHUB_TOKEN = \"ga-foo\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"github-auth\": \"ga-foo\",\n    })\n    expect(process.env.GITHUB_TOKEN).toBe(undefined)\n  })\n\n  it(\"should use env var CS_DISABLE_FILE_DOWNLOADS\", async () => {\n    process.env.CS_DISABLE_FILE_DOWNLOADS = \"1\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-file-downloads\": true,\n    })\n  })\n\n  it(\"should use env var CS_DISABLE_FILE_DOWNLOADS set to true\", async () => {\n    process.env.CS_DISABLE_FILE_DOWNLOADS = \"true\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-file-downloads\": true,\n    })\n  })\n\n  it(\"should use env var CS_DISABLE_GETTING_STARTED_OVERRIDE\", async () => {\n    process.env.CS_DISABLE_GETTING_STARTED_OVERRIDE = \"1\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-getting-started-override\": true,\n    })\n  })\n\n  it(\"should use env var CS_DISABLE_GETTING_STARTED_OVERRIDE set to true\", async () => {\n    process.env.CS_DISABLE_GETTING_STARTED_OVERRIDE = \"true\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-getting-started-override\": true,\n    })\n  })\n\n  it(\"should use env var CS_DISABLE_PROXY\", async () => {\n    process.env.CS_DISABLE_PROXY = \"1\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-proxy\": true,\n    })\n  })\n\n  it(\"should use env var CS_DISABLE_PROXY set to true\", async () => {\n    process.env.CS_DISABLE_PROXY = \"true\"\n    const args = parse([])\n    expect(args).toEqual({})\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"disable-proxy\": true,\n    })\n  })\n\n  it(\"should error if password passed in\", () => {\n    expect(() => parse([\"--password\", \"supersecret123\"])).toThrowError(\n      \"--password can only be set in the config file or passed in via $PASSWORD\",\n    )\n  })\n\n  it(\"should error if hashed-password passed in\", () => {\n    expect(() => parse([\"--hashed-password\", \"fdas423fs8a\"])).toThrowError(\n      \"--hashed-password can only be set in the config file or passed in via $HASHED_PASSWORD\",\n    )\n  })\n\n  it(\"should error if github-auth passed in\", () => {\n    expect(() => parse([\"--github-auth\", \"fdas423fs8a\"])).toThrowError(\n      \"--github-auth can only be set in the config file or passed in via $GITHUB_TOKEN\",\n    )\n  })\n\n  it(\"should filter proxy domains\", async () => {\n    const args = parse([\"--proxy-domain\", \"*.coder.com\", \"--proxy-domain\", \"coder.com\", \"--proxy-domain\", \"coder.org\"])\n    expect(args).toEqual({\n      \"proxy-domain\": [\"*.coder.com\", \"coder.com\", \"coder.org\"],\n    })\n\n    const defaultArgs = await setDefaults(args)\n    expect(defaultArgs).toEqual({\n      ...defaults,\n      \"proxy-domain\": [\"{{port}}.coder.com\", \"{{port}}.coder.org\"],\n    })\n  })\n  it(\"should allow '=,$/' in strings\", async () => {\n    const args = parse([\n      \"--disable-update-check\",\n      \"$argon2i$v=19$m=4096,t=3,p=1$0qr/o+0t00hsbjfqcksfdq$ofcm4rl6o+b7oxpua4qlxubypbbpsf+8l531u7p9hyy\",\n    ])\n    expect(args).toEqual({\n      \"disable-update-check\": true,\n      _: [\"$argon2i$v=19$m=4096,t=3,p=1$0qr/o+0t00hsbjfqcksfdq$ofcm4rl6o+b7oxpua4qlxubypbbpsf+8l531u7p9hyy\"],\n    })\n  })\n  it(\"should parse options with double-dash and multiple equal signs \", async () => {\n    const args = parse(\n      [\n        \"--hashed-password=$argon2i$v=19$m=4096,t=3,p=1$0qr/o+0t00hsbjfqcksfdq$ofcm4rl6o+b7oxpua4qlxubypbbpsf+8l531u7p9hyy\",\n      ],\n      {\n        configFile: \"/pathtoconfig\",\n      },\n    )\n    expect(args).toEqual({\n      \"hashed-password\":\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qr/o+0t00hsbjfqcksfdq$ofcm4rl6o+b7oxpua4qlxubypbbpsf+8l531u7p9hyy\",\n    })\n  })\n  it(\"should throw an error for invalid config values\", async () => {\n    const fakePath = \"/fake-config-path\"\n    const expectedErrMsg = `error reading ${fakePath}: `\n\n    expect(() =>\n      parse([\"--foo\"], {\n        configFile: fakePath,\n      }),\n    ).toThrowError(expectedErrMsg)\n  })\n  it(\"should fail to parse invalid config\", () => {\n    expect(() => parseConfigFile(\"test\", \"/fake-config-path\")).toThrowError(\"invalid config: test\")\n  })\n  it(\"should parse repeatable options\", () => {\n    const configContents = `\n      install-extension:\n        - extension.number1\n        - extension.number2\n    `\n    expect(parseConfigFile(configContents, \"/fake-config-path\")).toEqual({\n      config: \"/fake-config-path\",\n      \"install-extension\": [\"extension.number1\", \"extension.number2\"],\n    })\n  })\n  it(\"should ignore optional strings set to false\", async () => {\n    expect(parse([\"--cert=false\"])).toEqual({})\n  })\n  it(\"should use last flag\", async () => {\n    expect(parse([\"--port\", \"8081\", \"--port\", \"8082\"])).toEqual({\n      port: 8082,\n    })\n  })\n\n  it(\"should not set proxy uri\", async () => {\n    await setDefaults(parse([]))\n    expect(process.env.VSCODE_PROXY_URI).toBeUndefined()\n  })\n\n  it(\"should set proxy uri\", async () => {\n    await setDefaults(parse([\"--proxy-domain\", \"coder.org\"]))\n    expect(process.env.VSCODE_PROXY_URI).toEqual(\"//{{port}}.coder.org\")\n  })\n\n  it(\"should set proxy uri to first domain\", async () => {\n    await setDefaults(\n      parse([\"--proxy-domain\", \"*.coder.com\", \"--proxy-domain\", \"coder.com\", \"--proxy-domain\", \"coder.org\"]),\n    )\n    expect(process.env.VSCODE_PROXY_URI).toEqual(\"//{{port}}.coder.com\")\n  })\n\n  it(\"should not override existing proxy uri\", async () => {\n    process.env.VSCODE_PROXY_URI = \"foo\"\n    await setDefaults(\n      parse([\"--proxy-domain\", \"*.coder.com\", \"--proxy-domain\", \"coder.com\", \"--proxy-domain\", \"coder.org\"]),\n    )\n    expect(process.env.VSCODE_PROXY_URI).toEqual(\"foo\")\n  })\n})\n\ndescribe(\"cli\", () => {\n  const testName = \"cli\"\n  let tmpDirPath: string\n\n  beforeAll(async () => {\n    await clean(testName)\n  })\n\n  beforeEach(async () => {\n    delete process.env.VSCODE_IPC_HOOK_CLI\n    tmpDirPath = await tmpdir(testName)\n  })\n\n  it(\"should use existing if inside code-server\", async () => {\n    process.env.VSCODE_IPC_HOOK_CLI = \"test\"\n    const args: UserProvidedArgs = {}\n    expect(await shouldOpenInExistingInstance(args, \"\")).toStrictEqual(\"test\")\n\n    args.port = 8081\n    args._ = [\"./file\"]\n    expect(await shouldOpenInExistingInstance(args, \"\")).toStrictEqual(\"test\")\n  })\n\n  it(\"should use existing if --reuse-window is set\", async () => {\n    const sessionSocket = path.join(tmpDirPath, \"session-socket\")\n    const server = await makeEditorSessionManagerServer(sessionSocket, new EditorSessionManager())\n\n    const args: UserProvidedArgs = {}\n    args[\"reuse-window\"] = true\n    await expect(shouldOpenInExistingInstance(args, sessionSocket)).rejects.toThrow()\n\n    const socketPath = path.join(tmpDirPath, \"socket\")\n    const client = new EditorSessionManagerClient(sessionSocket)\n    await client.addSession({\n      entry: {\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath,\n      },\n    })\n    const vscodeSockets = listenOn(socketPath)\n\n    await expect(shouldOpenInExistingInstance(args, sessionSocket)).resolves.toStrictEqual(socketPath)\n\n    args.port = 8081\n    await expect(shouldOpenInExistingInstance(args, sessionSocket)).resolves.toStrictEqual(socketPath)\n\n    server.close()\n    vscodeSockets.close()\n  })\n\n  it(\"should use existing if --new-window is set\", async () => {\n    const sessionSocket = path.join(tmpDirPath, \"session-socket\")\n    const server = await makeEditorSessionManagerServer(sessionSocket, new EditorSessionManager())\n\n    const args: UserProvidedArgs = {}\n    args[\"new-window\"] = true\n    await expect(shouldOpenInExistingInstance(args, sessionSocket)).rejects.toThrow()\n\n    const socketPath = path.join(tmpDirPath, \"socket\")\n    const client = new EditorSessionManagerClient(sessionSocket)\n    await client.addSession({\n      entry: {\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath,\n      },\n    })\n    const vscodeSockets = listenOn(socketPath)\n\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(socketPath)\n\n    args.port = 8081\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(socketPath)\n\n    server.close()\n    vscodeSockets.close()\n  })\n\n  it(\"should use existing if no unrelated flags are set, has positional, and socket is active\", async () => {\n    const sessionSocket = path.join(tmpDirPath, \"session-socket\")\n    const server = await makeEditorSessionManagerServer(sessionSocket, new EditorSessionManager())\n\n    const args: UserProvidedArgs = {}\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(undefined)\n\n    args._ = [\"./file\"]\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(undefined)\n\n    const client = new EditorSessionManagerClient(sessionSocket)\n    const socketPath = path.join(tmpDirPath, \"socket\")\n    await client.addSession({\n      entry: {\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath,\n      },\n    })\n    const vscodeSockets = listenOn(socketPath)\n\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(socketPath)\n\n    args.port = 8081\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(undefined)\n\n    server.close()\n    vscodeSockets.close()\n  })\n\n  it(\"should prefer matching sessions for only the first path\", async () => {\n    const sessionSocket = path.join(tmpDirPath, \"session-socket\")\n    const server = await makeEditorSessionManagerServer(sessionSocket, new EditorSessionManager())\n    const client = new EditorSessionManagerClient(sessionSocket)\n    await client.addSession({\n      entry: {\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      },\n    })\n    await client.addSession({\n      entry: {\n        workspace: {\n          id: \"bbb\",\n          folders: [\n            {\n              uri: {\n                path: \"/bbb\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-bbb.sock`,\n      },\n    })\n    listenOn(`${tmpDirPath}/vscode-ipc-aaa.sock`, `${tmpDirPath}/vscode-ipc-bbb.sock`)\n\n    const args: UserProvidedArgs = {}\n    args._ = [\"/aaa/file\", \"/bbb/file\"]\n    expect(await shouldOpenInExistingInstance(args, sessionSocket)).toStrictEqual(`${tmpDirPath}/vscode-ipc-aaa.sock`)\n\n    server.close()\n  })\n})\n\ndescribe(\"shouldSpawnCliProcess\", () => {\n  it(\"should return false if no 'extension' related args passed in\", async () => {\n    const args = {}\n    const actual = await shouldSpawnCliProcess(args)\n    const expected = false\n\n    expect(actual).toBe(expected)\n  })\n\n  it(\"should return true if 'list-extensions' passed in\", async () => {\n    const args = {\n      [\"list-extensions\"]: true,\n    }\n    const actual = await shouldSpawnCliProcess(args)\n    const expected = true\n\n    expect(actual).toBe(expected)\n  })\n\n  it(\"should return true if 'install-extension' passed in\", async () => {\n    const args = {\n      [\"install-extension\"]: [\"hello.world\"],\n    }\n    const actual = await shouldSpawnCliProcess(args)\n    const expected = true\n\n    expect(actual).toBe(expected)\n  })\n\n  it(\"should return true if 'uninstall-extension' passed in\", async () => {\n    const args: UserProvidedArgs = {\n      [\"uninstall-extension\"]: [\"hello.world\"],\n    }\n    const actual = await shouldSpawnCliProcess(args)\n    const expected = true\n\n    expect(actual).toBe(expected)\n  })\n})\n\ndescribe(\"bindAddrFromArgs\", () => {\n  it(\"should return the bind address\", () => {\n    const args: UserProvidedArgs = {}\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = addr\n\n    expect(actual).toStrictEqual(expected)\n  })\n\n  it(\"should use the bind-address if set in args\", () => {\n    const args: UserProvidedArgs = {\n      [\"bind-addr\"]: \"localhost:3000\",\n    }\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"localhost\",\n      port: 3000,\n    }\n\n    expect(actual).toStrictEqual(expected)\n  })\n\n  it(\"should use the host if set in args\", () => {\n    const args: UserProvidedArgs = {\n      [\"host\"]: \"coder\",\n    }\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"coder\",\n      port: 8080,\n    }\n\n    expect(actual).toStrictEqual(expected)\n  })\n\n  it(\"should use process.env.CODE_SERVER_HOST if set\", () => {\n    const [setValue, resetValue] = useEnv(\"CODE_SERVER_HOST\")\n    setValue(\"coder\")\n\n    const args: UserProvidedArgs = {}\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"coder\",\n      port: 8080,\n    }\n\n    expect(actual).toStrictEqual(expected)\n    resetValue()\n  })\n\n  it(\"should use the args.host over process.env.CODE_SERVER_HOST if both set\", () => {\n    const [setValue, resetValue] = useEnv(\"CODE_SERVER_HOST\")\n    setValue(\"coder\")\n\n    const args: UserProvidedArgs = {\n      host: \"123.123.123.123\",\n    }\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"123.123.123.123\",\n      port: 8080,\n    }\n\n    expect(actual).toStrictEqual(expected)\n    resetValue()\n  })\n\n  it(\"should use process.env.PORT if set\", () => {\n    const [setValue, resetValue] = useEnv(\"PORT\")\n    setValue(\"8000\")\n\n    const args: UserProvidedArgs = {}\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"localhost\",\n      port: 8000,\n    }\n\n    expect(actual).toStrictEqual(expected)\n    resetValue()\n  })\n\n  it(\"should set port if in args\", () => {\n    const args: UserProvidedArgs = {\n      port: 3000,\n    }\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"localhost\",\n      port: 3000,\n    }\n\n    expect(actual).toStrictEqual(expected)\n  })\n\n  it(\"should use the args.port over process.env.PORT if both set\", () => {\n    const [setValue, resetValue] = useEnv(\"PORT\")\n    setValue(\"8000\")\n\n    const args: UserProvidedArgs = {\n      port: 3000,\n    }\n\n    const addr = {\n      host: \"localhost\",\n      port: 8080,\n    }\n\n    const actual = bindAddrFromArgs(addr, args)\n    const expected = {\n      host: \"localhost\",\n      port: 3000,\n    }\n\n    expect(actual).toStrictEqual(expected)\n    resetValue()\n  })\n})\n\ndescribe(\"defaultConfigFile\", () => {\n  it(\"should return the default config file as a string\", async () => {\n    const password = await generatePassword()\n    const actual = defaultConfigFile(password)\n\n    expect(actual).toMatch(`bind-addr: 127.0.0.1:8080\nauth: password\npassword: ${password}\ncert: false`)\n  })\n})\n\ndescribe(\"toCodeArgs\", () => {\n  const vscodeDefaults = {\n    ...defaults,\n    help: false,\n    port: \"8080\",\n    version: false,\n    log: undefined,\n  }\n\n  const testName = \"vscode-args\"\n  beforeAll(async () => {\n    // Clean up temporary directories from the previous run.\n    await clean(testName)\n  })\n\n  it(\"should convert empty args\", async () => {\n    expect(await toCodeArgs(await setDefaults(parse([])))).toStrictEqual({\n      ...vscodeDefaults,\n    })\n  })\n\n  it(\"should ignore regular file\", async () => {\n    const file = path.join(await tmpdir(testName), \"file\")\n    await fs.writeFile(file, \"foobar\")\n    expect(await toCodeArgs(await setDefaults(parse([file])))).toStrictEqual({\n      ...vscodeDefaults,\n      _: [file],\n    })\n  })\n})\n\ndescribe(\"optionDescriptions\", () => {\n  it(\"should return the descriptions of all the available options\", () => {\n    const expectedOptionDescriptions = Object.entries(options)\n      .flat()\n      .filter((item: any) => {\n        if (item.description) {\n          return item.description\n        }\n      })\n      .map((item: any) => item.description)\n    const actualOptionDescriptions = optionDescriptions()\n    // We need both the expected and the actual\n    // Both of these are string[]\n    // We then loop through the expectedOptionDescriptions\n    // and check that this expectedDescription exists in the\n    // actualOptionDescriptions\n\n    // To do that we need to loop through actualOptionDescriptions\n    // and make sure we have a substring match\n    expectedOptionDescriptions.forEach((expectedDescription) => {\n      const exists = actualOptionDescriptions.find((desc) => {\n        if (\n          desc.replace(/\\n/g, \" \").replace(/ /g, \"\").includes(expectedDescription.replace(/\\n/g, \" \").replace(/ /g, \"\"))\n        ) {\n          return true\n        }\n        return false\n      })\n      expect(exists).toBeTruthy()\n    })\n  })\n  it(\"should visually align multiple options\", () => {\n    const opts: Partial<Options<Required<UserProvidedArgs>>> = {\n      \"cert-key\": { type: \"string\", path: true, description: \"Path to certificate key when using non-generated cert.\" },\n      \"cert-host\": {\n        type: \"string\",\n        description: \"Hostname to use when generating a self signed certificate.\",\n      },\n      \"disable-update-check\": {\n        type: \"boolean\",\n        description:\n          \"Disable update check. Without this flag, code-server checks every 6 hours against the latest github release and \\n\" +\n          \"then notifies you once every week that a new release is available.\",\n      },\n    }\n    expect(optionDescriptions(opts)).toStrictEqual([\n      \"  --cert-key             Path to certificate key when using non-generated cert.\",\n      \"  --cert-host            Hostname to use when generating a self signed certificate.\",\n      `  --disable-update-check Disable update check. Without this flag, code-server checks every 6 hours against the latest github release and\n                          then notifies you once every week that a new release is available.`,\n    ])\n  })\n  it(\"should add all valid options for enumerated types\", () => {\n    const opts: Partial<Options<Required<UserProvidedArgs>>> = {\n      auth: { type: AuthType, description: \"The type of authentication to use.\" },\n    }\n    expect(optionDescriptions(opts)).toStrictEqual([\"  --auth The type of authentication to use. [password, none]\"])\n  })\n\n  it(\"should show if an option is deprecated\", () => {\n    const opts: Partial<Options<Required<UserProvidedArgs>>> = {\n      cert: {\n        type: OptionalString,\n        description: \"foo\",\n        deprecated: true,\n      },\n    }\n    expect(optionDescriptions(opts)).toStrictEqual([\"  --cert (deprecated) foo\"])\n  })\n\n  it(\"should show newlines in description\", () => {\n    const opts: Partial<Options<Required<UserProvidedArgs>>> = {\n      \"install-extension\": {\n        type: \"string[]\",\n        description:\n          \"Install or update a VS Code extension by id or vsix. The identifier of an extension is `${publisher}.${name}`.\\n\" +\n          \"To install a specific version provide `@${version}`. For example: 'vscode.csharp@1.2.3'.\",\n      },\n    }\n    expect(optionDescriptions(opts)).toStrictEqual([\n      `  --install-extension Install or update a VS Code extension by id or vsix. The identifier of an extension is \\`\\${publisher}.\\${name}\\`.\n                       To install a specific version provide \\`@\\${version}\\`. For example: 'vscode.csharp@1.2.3'.`,\n    ])\n  })\n})\n"
  },
  {
    "path": "test/unit/node/constants.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport path from \"path\"\nimport * as semver from \"semver\"\nimport { mockLogger } from \"../../utils/helpers\"\n\ndescribe(\"constants\", () => {\n  let constants: typeof import(\"../../../src/node/constants\")\n\n  describe(\"with package.json defined\", () => {\n    const mockPackageJson = {\n      name: \"mock-code-server\",\n      description: \"Run VS Code on a remote server.\",\n      repository: \"https://github.com/coder/code-server\",\n      version: \"1.0.0\",\n      commit: \"f6b2be2838f4afb217c2fd8f03eafedd8d55ef9b\",\n    }\n\n    const mockCodePackageJson = {\n      name: \"mock-vscode\",\n      version: \"1.2.3\",\n    }\n\n    beforeAll(() => {\n      jest.clearAllMocks()\n      mockLogger()\n      jest.mock(path.resolve(__dirname, \"../../../package.json\"), () => mockPackageJson, { virtual: true })\n      jest.mock(path.resolve(__dirname, \"../../../lib/vscode/package.json\"), () => mockCodePackageJson, {\n        virtual: true,\n      })\n      constants = require(\"../../../src/node/constants\")\n    })\n\n    afterAll(() => {\n      jest.resetModules()\n    })\n\n    it(\"should provide the commit\", () => {\n      expect(constants.commit).toBe(mockPackageJson.commit)\n    })\n\n    it(\"should return the package.json version\", () => {\n      expect(constants.version).toBe(mockPackageJson.version)\n\n      // Ensure the version is parseable as semver and equal\n      const actual = semver.parse(constants.version)\n      const expected = semver.parse(mockPackageJson.version)\n      expect(actual).toBeTruthy()\n      expect(actual).toStrictEqual(expected)\n    })\n\n    it(\"should include embedded Code version information\", () => {\n      expect(constants.codeVersion).toBe(mockCodePackageJson.version)\n\n      // Ensure the version is parseable as semver and equal\n      const actual = semver.parse(constants.codeVersion)\n      const expected = semver.parse(mockCodePackageJson.version)\n      expect(actual).toBeTruthy()\n      expect(actual).toStrictEqual(expected)\n    })\n\n    it(\"should return a human-readable version string\", () => {\n      expect(constants.getVersionString()).toStrictEqual(\n        `${mockPackageJson.version} ${mockPackageJson.commit} with Code ${mockCodePackageJson.version}`,\n      )\n    })\n\n    it(\"should return a machine-readable version string\", () => {\n      expect(constants.getVersionJsonString()).toStrictEqual(\n        JSON.stringify({\n          codeServer: mockPackageJson.version,\n          commit: mockPackageJson.commit,\n          vscode: mockCodePackageJson.version,\n        }),\n      )\n    })\n\n    describe(\"getPackageJson\", () => {\n      it(\"should log a warning if package.json not found\", () => {\n        const expectedErrorMessage = \"Cannot find module './package.json' from 'src/node/constants.ts'\"\n\n        constants.getPackageJson(\"./package.json\")\n\n        expect(logger.warn).toHaveBeenCalled()\n        expect(logger.warn).toHaveBeenCalledWith(expectedErrorMessage)\n      })\n\n      it(\"should find the package.json\", () => {\n        // the function calls require from src/node/constants\n        // so to get the root package.json we need to use ../../\n        const packageJson = constants.getPackageJson(\"../../package.json\")\n        expect(packageJson).toStrictEqual(mockPackageJson)\n\n        const codePackageJson = constants.getPackageJson(\"../../lib/vscode/package.json\")\n        expect(codePackageJson).toStrictEqual(mockCodePackageJson)\n      })\n    })\n  })\n\n  describe(\"with incomplete package.json\", () => {\n    const mockPackageJson = {\n      name: \"mock-code-server\",\n    }\n    const mockCodePackageJson = {\n      name: \"mock-vscode\",\n    }\n\n    beforeAll(() => {\n      jest.clearAllMocks()\n      jest.mock(path.resolve(__dirname, \"../../../package.json\"), () => mockPackageJson, { virtual: true })\n      jest.mock(path.resolve(__dirname, \"../../../lib/vscode/package.json\"), () => mockCodePackageJson, {\n        virtual: true,\n      })\n      constants = require(\"../../../src/node/constants\")\n    })\n\n    afterAll(() => {\n      jest.resetModules()\n    })\n\n    it(\"version should return 'development'\", () => {\n      expect(constants.version).toBe(\"development\")\n    })\n\n    it(\"commit should return 'development'\", () => {\n      expect(constants.commit).toBe(\"development\")\n    })\n\n    it(\"should return a human-readable version string\", () => {\n      // this string is not super useful\n      expect(constants.getVersionString()).toStrictEqual(\"development development with Code development\")\n    })\n\n    it(\"should return a machine-readable version string\", () => {\n      expect(constants.getVersionJsonString()).toStrictEqual(\n        JSON.stringify({\n          codeServer: \"development\",\n          commit: \"development\",\n          vscode: \"development\",\n        }),\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/heart.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { readFile, writeFile, stat, utimes } from \"fs/promises\"\nimport { Heart } from \"../../../src/node/heart\"\nimport { clean, mockLogger, tmpdir } from \"../../utils/helpers\"\n\nconst mockIsActive = (resolveTo: boolean) => jest.fn().mockResolvedValue(resolveTo)\n\ndescribe(\"Heart\", () => {\n  const testName = \"heartTests\"\n  let testDir = \"\"\n  let heart: Heart\n\n  beforeAll(async () => {\n    mockLogger()\n    await clean(testName)\n    testDir = await tmpdir(testName)\n  })\n  beforeEach(() => {\n    heart = new Heart(`${testDir}/shutdown.txt`, mockIsActive(true))\n  })\n  afterAll(() => {\n    jest.restoreAllMocks()\n  })\n  afterEach(() => {\n    jest.resetAllMocks()\n    jest.useRealTimers()\n    if (heart) {\n      heart.dispose()\n    }\n  })\n  it(\"should write to a file when given a valid file path\", async () => {\n    // Set up heartbeat file with contents\n    const text = \"test\"\n    const pathToFile = `${testDir}/file.txt`\n    await writeFile(pathToFile, text)\n    const fileContents = await readFile(pathToFile, { encoding: \"utf8\" })\n    // Explicitly set the modified time to 0 so that we can check\n    // that the file was indeed modified after calling heart.beat().\n    // This works around any potential race conditions.\n    // Docs: https://nodejs.org/api/fs.html#fspromisesutimespath-atime-mtime\n    await utimes(pathToFile, 0, 0)\n\n    expect(fileContents).toBe(text)\n\n    heart = new Heart(pathToFile, mockIsActive(true))\n    await heart.beat()\n    // Check that the heart wrote to the heartbeatFilePath and overwrote our text\n    const fileContentsAfterBeat = await readFile(pathToFile, { encoding: \"utf8\" })\n    expect(fileContentsAfterBeat).not.toBe(text)\n    // Make sure the modified timestamp was updated.\n    const fileStatusAfterEdit = await stat(pathToFile)\n    expect(fileStatusAfterEdit.mtimeMs).toBeGreaterThan(0)\n  })\n  it(\"should log a warning when given an invalid file path\", async () => {\n    heart = new Heart(`fakeDir/fake.txt`, mockIsActive(false))\n    await heart.beat()\n    expect(logger.warn).toHaveBeenCalled()\n  })\n  it(\"should be active after calling beat\", async () => {\n    await heart.beat()\n\n    const isAlive = heart.alive()\n    expect(isAlive).toBe(true)\n  })\n  it(\"should not be active after dispose is called\", () => {\n    heart.dispose()\n\n    const isAlive = heart.alive()\n    expect(isAlive).toBe(false)\n  })\n  it(\"should beat twice without warnings\", async () => {\n    // Use fake timers so we can speed up setTimeout\n    jest.useFakeTimers()\n    heart = new Heart(`${testDir}/hello.txt`, mockIsActive(true))\n    await heart.beat()\n    // we need to speed up clocks, timeouts\n    // call heartbeat again (and it won't be alive I think)\n    // then assert no warnings were called\n    jest.runAllTimers()\n    expect(logger.warn).not.toHaveBeenCalled()\n  })\n})\n\ndescribe(\"heartbeatTimer\", () => {\n  const testName = \"heartbeatTimer\"\n  let testDir = \"\"\n  beforeAll(async () => {\n    await clean(testName)\n    testDir = await tmpdir(testName)\n    mockLogger()\n  })\n  afterAll(() => {\n    jest.restoreAllMocks()\n  })\n  beforeEach(() => {\n    jest.useFakeTimers()\n  })\n  afterEach(() => {\n    jest.resetAllMocks()\n    jest.clearAllTimers()\n    jest.useRealTimers()\n  })\n  it(\"should call isActive when timeout expires\", async () => {\n    const isActive = true\n    const mockIsActive = jest.fn().mockResolvedValue(isActive)\n    const heart = new Heart(`${testDir}/shutdown.txt`, mockIsActive)\n    await heart.beat()\n    jest.advanceTimersByTime(60 * 1000)\n    expect(mockIsActive).toHaveBeenCalled()\n  })\n  it(\"should log a warning when isActive rejects\", async () => {\n    const errorMsg = \"oh no\"\n    const error = new Error(errorMsg)\n    const mockIsActive = jest.fn().mockRejectedValue(error)\n    const heart = new Heart(`${testDir}/shutdown.txt`, mockIsActive)\n    await heart.beat()\n    jest.advanceTimersByTime(60 * 1000)\n\n    expect(mockIsActive).toHaveBeenCalled()\n    expect(logger.warn).toHaveBeenCalledWith(errorMsg)\n  })\n})\n\ndescribe(\"stateChange\", () => {\n  const testName = \"stateChange\"\n  let testDir = \"\"\n  let heart: Heart\n  beforeAll(async () => {\n    await clean(testName)\n    testDir = await tmpdir(testName)\n    mockLogger()\n  })\n  afterAll(() => {\n    jest.restoreAllMocks()\n  })\n  afterEach(() => {\n    jest.resetAllMocks()\n    if (heart) {\n      heart.dispose()\n    }\n  })\n  it(\"should change to alive after a beat\", async () => {\n    heart = new Heart(`${testDir}/shutdown.txt`, mockIsActive(true))\n    const mockOnChange = jest.fn()\n    heart.onChange(mockOnChange)\n    await heart.beat()\n\n    expect(mockOnChange.mock.calls[0][0]).toBe(\"alive\")\n  })\n  it.only(\"should change to expired when not active\", async () => {\n    jest.useFakeTimers()\n    heart = new Heart(`${testDir}/shutdown.txt`, () => new Promise((resolve) => resolve(false)))\n    const mockOnChange = jest.fn()\n    heart.onChange(mockOnChange)\n    await heart.beat()\n\n    await jest.advanceTimersByTime(60 * 1000)\n    expect(mockOnChange.mock.calls[1][0]).toBe(\"expired\")\n    jest.clearAllTimers()\n    jest.useRealTimers()\n  })\n})\n"
  },
  {
    "path": "test/unit/node/http.test.ts",
    "content": "import { getMockReq } from \"@jest-mock/express\"\nimport * as http from \"../../../src/node/http\"\nimport { mockLogger } from \"../../utils/helpers\"\n\ndescribe(\"http\", () => {\n  beforeEach(() => {\n    mockLogger()\n  })\n\n  afterEach(() => {\n    jest.clearAllMocks()\n  })\n\n  it(\"should construct a relative path to the root\", () => {\n    expect(http.relativeRoot(\"/\")).toStrictEqual(\".\")\n    expect(http.relativeRoot(\"/foo\")).toStrictEqual(\".\")\n    expect(http.relativeRoot(\"/foo/\")).toStrictEqual(\"./..\")\n    expect(http.relativeRoot(\"/foo/bar \")).toStrictEqual(\"./..\")\n    expect(http.relativeRoot(\"/foo/bar/\")).toStrictEqual(\"./../..\")\n  })\n\n  describe(\"origin\", () => {\n    ;[\n      {\n        origin: \"\",\n        host: \"\",\n      },\n      {\n        origin: \"http://localhost:8080\",\n        host: \"\",\n        expected: \"no host headers\",\n      },\n      {\n        origin: \"http://localhost:8080\",\n        host: \" \",\n        expected: \"does not match\",\n      },\n      {\n        origin: \"http://localhost:8080\",\n        host: \"localhost:8080\",\n      },\n      {\n        origin: \"http://localhost:8080\",\n        host: \"localhost:8081\",\n        expected: \"does not match\",\n      },\n      {\n        origin: \"localhost:8080\",\n        host: \"localhost:8080\",\n        expected: \"does not match\", // Gets parsed as host: localhost and path: 8080.\n      },\n      {\n        origin: \"test.org\",\n        host: \"localhost:8080\",\n        expected: \"malformed\", // Parsing fails completely.\n      },\n    ].forEach((test) => {\n      ;[\n        [\"host\", test.host],\n        [\"x-forwarded-host\", test.host],\n        [\"x-forwarded-host\", `${test.host}, ${test.host}`],\n        [\"forwarded\", `for=127.0.0.1, host=${test.host}, proto=http`],\n        [\"forwarded\", `for=127.0.0.1;proto=http;host=${test.host}`],\n        [\"forwarded\", `proto=http;host=${test.host}, for=127.0.0.1`],\n      ].forEach(([key, value]) => {\n        it(`${test.origin} -> [${key}: ${value}]`, () => {\n          const req = getMockReq({\n            originalUrl: \"localhost:8080\",\n            headers: {\n              origin: test.origin,\n              [key]: value,\n            },\n            args: {},\n          })\n          if (typeof test.expected === \"string\") {\n            expect(() => http.authenticateOrigin(req)).toThrow(test.expected)\n          } else {\n            expect(() => http.authenticateOrigin(req)).not.toThrow()\n          }\n        })\n      })\n    })\n  })\n\n  describe(\"constructRedirectPath\", () => {\n    it(\"should preserve slashes in queryString so they are human-readable\", () => {\n      const mockReq = getMockReq({\n        originalUrl: \"localhost:8080\",\n      })\n      const mockQueryParams = { folder: \"/Users/jp/dev/coder\" }\n      const mockTo = \"\"\n      const actual = http.constructRedirectPath(mockReq, mockQueryParams, mockTo)\n      const expected = \"./?folder=/Users/jp/dev/coder\"\n      expect(actual).toBe(expected)\n    })\n    it(\"should use an empty string if no query params\", () => {\n      const mockReq = getMockReq({\n        originalUrl: \"localhost:8080\",\n      })\n      const mockQueryParams = {}\n      const mockTo = \"\"\n      const actual = http.constructRedirectPath(mockReq, mockQueryParams, mockTo)\n      const expected = \"./\"\n      expect(actual).toBe(expected)\n    })\n    it(\"should append the 'to' path relative to the originalUrl\", () => {\n      const mockReq = getMockReq({\n        originalUrl: \"localhost:8080\",\n      })\n      const mockQueryParams = {}\n      const mockTo = \"vscode\"\n      const actual = http.constructRedirectPath(mockReq, mockQueryParams, mockTo)\n      const expected = \"./vscode\"\n      expect(actual).toBe(expected)\n    })\n    it(\"should append append queryParams after 'to' path\", () => {\n      const mockReq = getMockReq({\n        originalUrl: \"localhost:8080\",\n      })\n      const mockQueryParams = { folder: \"/Users/jp/dev/coder\" }\n      const mockTo = \"vscode\"\n      const actual = http.constructRedirectPath(mockReq, mockQueryParams, mockTo)\n      const expected = \"./vscode?folder=/Users/jp/dev/coder\"\n      expect(actual).toBe(expected)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/i18n.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as os from \"os\"\nimport * as path from \"path\"\nimport { loadCustomStrings } from \"../../../src/node/i18n\"\n\ndescribe(\"i18n\", () => {\n  let tempDir: string\n  let validJsonFile: string\n  let invalidJsonFile: string\n  let nonExistentFile: string\n\n  beforeEach(async () => {\n    // Create temporary directory for test files\n    tempDir = await fs.mkdtemp(path.join(os.tmpdir(), \"code-server-i18n-test-\"))\n\n    // Create test files\n    validJsonFile = path.join(tempDir, \"valid.json\")\n    invalidJsonFile = path.join(tempDir, \"invalid.json\")\n    nonExistentFile = path.join(tempDir, \"does-not-exist.json\")\n\n    // Write valid JSON file\n    await fs.writeFile(\n      validJsonFile,\n      JSON.stringify({\n        WELCOME: \"Custom Welcome\",\n        LOGIN_TITLE: \"My Custom App\",\n        LOGIN_BELOW: \"Please log in to continue\",\n      }),\n    )\n\n    // Write invalid JSON file\n    await fs.writeFile(invalidJsonFile, '{\"WELCOME\": \"Missing closing quote}')\n  })\n\n  afterEach(async () => {\n    // Clean up temporary directory\n    await fs.rmdir(tempDir, { recursive: true })\n  })\n\n  describe(\"loadCustomStrings\", () => {\n    it(\"should load valid JSON file successfully\", async () => {\n      // Should not throw an error\n      await expect(loadCustomStrings(validJsonFile)).resolves.toBeUndefined()\n    })\n\n    it(\"should throw clear error for non-existent file\", async () => {\n      await expect(loadCustomStrings(nonExistentFile)).rejects.toThrow(\n        `Custom strings file not found: ${nonExistentFile}\\nPlease ensure the file exists and is readable.`,\n      )\n    })\n\n    it(\"should throw clear error for invalid JSON\", async () => {\n      await expect(loadCustomStrings(invalidJsonFile)).rejects.toThrow(\n        `Invalid JSON in custom strings file: ${invalidJsonFile}`,\n      )\n    })\n\n    it(\"should handle empty JSON object\", async () => {\n      const emptyJsonFile = path.join(tempDir, \"empty.json\")\n      await fs.writeFile(emptyJsonFile, \"{}\")\n\n      await expect(loadCustomStrings(emptyJsonFile)).resolves.toBeUndefined()\n    })\n\n    it(\"should handle nested JSON objects\", async () => {\n      const nestedJsonFile = path.join(tempDir, \"nested.json\")\n      await fs.writeFile(\n        nestedJsonFile,\n        JSON.stringify({\n          WELCOME: \"Hello World\",\n          NESTED: {\n            KEY: \"Value\",\n          },\n        }),\n      )\n\n      await expect(loadCustomStrings(nestedJsonFile)).resolves.toBeUndefined()\n    })\n\n    it(\"should handle special characters and unicode\", async () => {\n      const unicodeJsonFile = path.join(tempDir, \"unicode.json\")\n      await fs.writeFile(\n        unicodeJsonFile,\n        JSON.stringify({\n          WELCOME: \"欢迎来到 code-server\",\n          LOGIN_TITLE: \"Willkommen bei {{app}}\",\n          SPECIAL: \"Special chars: àáâãäåæçèéêë 🚀 ♠️ ∆\",\n        }),\n        \"utf8\",\n      )\n\n      await expect(loadCustomStrings(unicodeJsonFile)).resolves.toBeUndefined()\n    })\n\n    it(\"should handle generic errors that are not ENOENT or SyntaxError\", async () => {\n      const testFile = path.join(tempDir, \"test.json\")\n      await fs.writeFile(testFile, \"{}\")\n\n      // Mock fs.readFile to throw a generic error\n      const originalReadFile = fs.readFile\n      const mockError = new Error(\"Permission denied\")\n      fs.readFile = jest.fn().mockRejectedValue(mockError)\n\n      await expect(loadCustomStrings(testFile)).rejects.toThrow(\n        `Failed to load custom strings from ${testFile}: Permission denied`,\n      )\n\n      // Restore original function\n      fs.readFile = originalReadFile\n    })\n\n    it(\"should handle errors that are not Error instances\", async () => {\n      const testFile = path.join(tempDir, \"test.json\")\n      await fs.writeFile(testFile, \"{}\")\n\n      // Mock fs.readFile to throw a non-Error object\n      const originalReadFile = fs.readFile\n      fs.readFile = jest.fn().mockRejectedValue(\"String error\")\n\n      await expect(loadCustomStrings(testFile)).rejects.toThrow(\n        `Failed to load custom strings from ${testFile}: String error`,\n      )\n\n      // Restore original function\n      fs.readFile = originalReadFile\n    })\n\n    it(\"should handle null/undefined errors\", async () => {\n      const testFile = path.join(tempDir, \"test.json\")\n      await fs.writeFile(testFile, \"{}\")\n\n      // Mock fs.readFile to throw null\n      const originalReadFile = fs.readFile\n      fs.readFile = jest.fn().mockRejectedValue(null)\n\n      await expect(loadCustomStrings(testFile)).rejects.toThrow(`Failed to load custom strings from ${testFile}: null`)\n\n      // Restore original function\n      fs.readFile = originalReadFile\n    })\n\n    it(\"should complete without errors for valid input\", async () => {\n      const testFile = path.join(tempDir, \"resource-test.json\")\n      const customStrings = {\n        WELCOME: \"Custom Welcome Message\",\n        LOGIN_TITLE: \"Custom Login Title\",\n      }\n      await fs.writeFile(testFile, JSON.stringify(customStrings))\n\n      // Should not throw any errors\n      await expect(loadCustomStrings(testFile)).resolves.toBeUndefined()\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/main.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { setDefaults, parse } from \"../../../src/node/cli\"\nimport { loadCustomStrings } from \"../../../src/node/i18n\"\nimport { tmpdir } from \"../../utils/helpers\"\n\n// Mock the i18n module\njest.mock(\"../../../src/node/i18n\", () => ({\n  loadCustomStrings: jest.fn(),\n}))\n\n// Mock logger to avoid console output during tests\njest.mock(\"@coder/logger\", () => ({\n  logger: {\n    info: jest.fn(),\n    debug: jest.fn(),\n    warn: jest.fn(),\n    error: jest.fn(),\n    named: jest.fn(),\n    level: 0,\n  },\n  field: jest.fn(),\n  Level: {\n    Trace: 0,\n    Debug: 1,\n    Info: 2,\n    Warn: 3,\n    Error: 4,\n  },\n}))\n\nconst mockedLoadCustomStrings = loadCustomStrings as jest.MockedFunction<typeof loadCustomStrings>\n\ndescribe(\"main\", () => {\n  let tempDir: string\n  let mockServer: any\n\n  beforeEach(async () => {\n    tempDir = await tmpdir(\"code-server-main-test\")\n\n    // Reset mocks\n    jest.clearAllMocks()\n\n    // Mock the server creation to avoid actually starting a server\n    mockServer = {\n      server: {\n        listen: jest.fn(),\n        address: jest.fn(() => ({ address: \"127.0.0.1\", port: 8080 })),\n        close: jest.fn(),\n      },\n      editorSessionManagerServer: {\n        address: jest.fn(() => null),\n      },\n      dispose: jest.fn(),\n    }\n  })\n\n  afterEach(async () => {\n    // Clean up temp directory\n    try {\n      await fs.rmdir(tempDir, { recursive: true })\n    } catch (error) {\n      // Ignore cleanup errors\n    }\n  })\n\n  describe(\"runCodeServer\", () => {\n    it(\"should load custom strings when i18n flag is provided\", async () => {\n      // Create a test custom strings file\n      const customStringsFile = path.join(tempDir, \"custom-strings.json\")\n      await fs.writeFile(\n        customStringsFile,\n        JSON.stringify({\n          WELCOME: \"Custom Welcome\",\n          LOGIN_TITLE: \"My App\",\n        }),\n      )\n\n      // Create args with i18n flag\n      const cliArgs = parse([\n        `--config=${path.join(tempDir, \"config.yaml\")}`,\n        `--user-data-dir=${tempDir}`,\n        \"--bind-addr=localhost:0\",\n        \"--log=warn\",\n        \"--auth=none\",\n        `--i18n=${customStringsFile}`,\n      ])\n      const args = await setDefaults(cliArgs)\n\n      // Mock the app module\n      jest.doMock(\"../../../src/node/app\", () => ({\n        createApp: jest.fn().mockResolvedValue(mockServer),\n        ensureAddress: jest.fn().mockReturnValue(new URL(\"http://localhost:8080\")),\n      }))\n\n      // Mock routes module\n      jest.doMock(\"../../../src/node/routes\", () => ({\n        register: jest.fn().mockResolvedValue({ disposeRoutes: jest.fn() }),\n      }))\n\n      // Mock loadCustomStrings to succeed\n      mockedLoadCustomStrings.mockResolvedValue(undefined)\n\n      // Import runCodeServer after mocking\n      const mainModule = await import(\"../../../src/node/main\")\n      const result = await mainModule.runCodeServer(args)\n\n      // Verify that loadCustomStrings was called with the correct file path\n      expect(mockedLoadCustomStrings).toHaveBeenCalledWith(customStringsFile)\n      expect(mockedLoadCustomStrings).toHaveBeenCalledTimes(1)\n\n      // Clean up\n      await result.dispose()\n    })\n\n    it(\"should not load custom strings when i18n flag is not provided\", async () => {\n      // Create args without i18n flag\n      const cliArgs = parse([\n        `--config=${path.join(tempDir, \"config.yaml\")}`,\n        `--user-data-dir=${tempDir}`,\n        \"--bind-addr=localhost:0\",\n        \"--log=warn\",\n        \"--auth=none\",\n      ])\n      const args = await setDefaults(cliArgs)\n\n      // Mock the app module\n      jest.doMock(\"../../../src/node/app\", () => ({\n        createApp: jest.fn().mockResolvedValue(mockServer),\n        ensureAddress: jest.fn().mockReturnValue(new URL(\"http://localhost:8080\")),\n      }))\n\n      // Mock routes module\n      jest.doMock(\"../../../src/node/routes\", () => ({\n        register: jest.fn().mockResolvedValue({ disposeRoutes: jest.fn() }),\n      }))\n\n      // Import runCodeServer after mocking\n      const mainModule = await import(\"../../../src/node/main\")\n      const result = await mainModule.runCodeServer(args)\n\n      // Verify that loadCustomStrings was NOT called\n      expect(mockedLoadCustomStrings).not.toHaveBeenCalled()\n\n      // Clean up\n      await result.dispose()\n    })\n\n    it(\"should handle errors when loadCustomStrings fails\", async () => {\n      // Create args with i18n flag pointing to non-existent file\n      const nonExistentFile = path.join(tempDir, \"does-not-exist.json\")\n      const cliArgs = parse([\n        `--config=${path.join(tempDir, \"config.yaml\")}`,\n        `--user-data-dir=${tempDir}`,\n        \"--bind-addr=localhost:0\",\n        \"--log=warn\",\n        \"--auth=none\",\n        `--i18n=${nonExistentFile}`,\n      ])\n      const args = await setDefaults(cliArgs)\n\n      // Mock loadCustomStrings to throw an error\n      const mockError = new Error(\"Custom strings file not found\")\n      mockedLoadCustomStrings.mockRejectedValue(mockError)\n\n      // Import runCodeServer after mocking\n      const mainModule = await import(\"../../../src/node/main\")\n\n      // Verify that runCodeServer throws the error from loadCustomStrings\n      await expect(mainModule.runCodeServer(args)).rejects.toThrow(\"Custom strings file not found\")\n\n      // Verify that loadCustomStrings was called\n      expect(mockedLoadCustomStrings).toHaveBeenCalledWith(nonExistentFile)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/proxy.test.ts",
    "content": "import * as express from \"express\"\nimport * as http from \"http\"\nimport nodeFetch from \"node-fetch\"\nimport { HttpCode } from \"../../../src/common/http\"\nimport { proxy } from \"../../../src/node/proxy\"\nimport { wss, Router as WsRouter } from \"../../../src/node/wsRouter\"\nimport { getAvailablePort, mockLogger } from \"../../utils/helpers\"\nimport * as httpserver from \"../../utils/httpserver\"\nimport * as integration from \"../../utils/integration\"\n\ndescribe(\"proxy\", () => {\n  const nhooyrDevServer = new httpserver.HttpServer()\n  const wsApp = express.default()\n  const wsRouter = WsRouter()\n  let codeServer: httpserver.HttpServer | undefined\n  let proxyPath: string\n  let absProxyPath: string\n  let e: express.Express\n\n  beforeAll(async () => {\n    wsApp.use(\"/\", wsRouter.router)\n    await nhooyrDevServer.listen((req, res) => {\n      e(req, res)\n    })\n    nhooyrDevServer.listenUpgrade(wsApp)\n    proxyPath = `/proxy/${nhooyrDevServer.port()}/wsup`\n    absProxyPath = proxyPath.replace(\"/proxy/\", \"/absproxy/\")\n  })\n\n  afterAll(async () => {\n    await nhooyrDevServer.dispose()\n  })\n\n  beforeEach(() => {\n    e = express.default()\n    mockLogger()\n  })\n\n  afterEach(async () => {\n    if (codeServer) {\n      await codeServer.dispose()\n      codeServer = undefined\n    }\n    jest.clearAllMocks()\n  })\n\n  it(\"should return 403 Forbidden if proxy is disabled\", async () => {\n    e.get(\"/wsup\", (req, res) => {\n      res.json(\"you cannot see this\")\n    })\n    codeServer = await integration.setup([\"--auth=none\", \"--disable-proxy\"], \"\")\n    const resp = await codeServer.fetch(proxyPath)\n    expect(resp.status).toBe(403)\n    const json = await resp.json()\n    expect(json).toEqual({ error: \"Forbidden\" })\n  })\n\n  it(\"should rewrite the base path\", async () => {\n    e.get(\"/wsup\", (req, res) => {\n      res.json(\"asher is the best\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath)\n    expect(resp.status).toBe(200)\n    const json = await resp.json()\n    expect(json).toBe(\"asher is the best\")\n  })\n\n  it(\"should not rewrite the base path\", async () => {\n    e.get(absProxyPath, (req, res) => {\n      res.json(\"joe is the best\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(absProxyPath)\n    expect(resp.status).toBe(200)\n    const json = await resp.json()\n    expect(json).toBe(\"joe is the best\")\n  })\n\n  it(\"should rewrite redirects\", async () => {\n    e.post(\"/wsup\", (req, res) => {\n      res.redirect(307, \"/finale\")\n    })\n    e.post(\"/finale\", (req, res) => {\n      res.json(\"redirect success\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath, {\n      method: \"POST\",\n    })\n    expect(resp.status).toBe(200)\n    expect(await resp.json()).toBe(\"redirect success\")\n  })\n\n  it(\"should not rewrite redirects\", async () => {\n    const finalePath = absProxyPath.replace(\"/wsup\", \"/finale\")\n    e.post(absProxyPath, (req, res) => {\n      res.redirect(307, finalePath)\n    })\n    e.post(finalePath, (req, res) => {\n      res.json(\"redirect success\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(absProxyPath, {\n      method: \"POST\",\n    })\n    expect(resp.status).toBe(200)\n    expect(await resp.json()).toBe(\"redirect success\")\n  })\n\n  it(\"should allow post bodies\", async () => {\n    e.use(express.json({ strict: false }))\n    e.post(\"/wsup\", (req, res) => {\n      res.json(req.body)\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath, {\n      method: \"post\",\n      body: JSON.stringify(\"coder is the best\"),\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n    })\n    expect(resp.status).toBe(200)\n    expect(await resp.json()).toBe(\"coder is the best\")\n  })\n\n  it(\"should handle bad requests\", async () => {\n    e.use(express.json({ strict: false }))\n    e.post(\"/wsup\", (req, res) => {\n      res.json(req.body)\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath, {\n      method: \"post\",\n      body: \"coder is the best\",\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n    })\n    expect(resp.status).toBe(400)\n    expect(resp.statusText).toMatch(\"Bad Request\")\n  })\n\n  it(\"should handle invalid routes\", async () => {\n    e.post(\"/wsup\", (req, res) => {\n      res.json(req.body)\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(`${proxyPath}/hello`)\n    expect(resp.status).toBe(404)\n    expect(resp.statusText).toMatch(\"Not Found\")\n  })\n\n  it(\"should handle errors\", async () => {\n    e.use(express.json({ strict: false }))\n    e.post(\"/wsup\", (req, res) => {\n      throw new Error(\"BROKEN\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath, {\n      method: \"post\",\n      body: JSON.stringify(\"coder is the best\"),\n      headers: {\n        \"Content-Type\": \"application/json\",\n      },\n    })\n    expect(resp.status).toBe(500)\n    expect(resp.statusText).toMatch(\"Internal Server Error\")\n  })\n\n  it(\"should pass origin check\", async () => {\n    wsRouter.ws(\"/wsup\", async (req) => {\n      wss.handleUpgrade(req, req.ws, req.head, (ws) => {\n        ws.send(\"hello\")\n        req.ws.resume()\n      })\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const ws = await codeServer.wsWait(proxyPath, {\n      headers: {\n        host: \"localhost:8080\",\n        origin: \"https://localhost:8080\",\n      },\n    })\n    ws.terminate()\n  })\n\n  it(\"should fail origin check\", async () => {\n    await expect(async () => {\n      codeServer = await integration.setup([\"--auth=none\"], \"\")\n      await codeServer.wsWait(proxyPath, {\n        headers: {\n          host: \"localhost:8080\",\n          origin: \"https://evil.org\",\n        },\n      })\n    }).rejects.toThrow()\n  })\n\n  it(\"should proxy non-ASCII\", async () => {\n    e.get(/.*/, (req, res) => {\n      res.json(\"ほげ\")\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(proxyPath.replace(\"wsup\", \"ほげ\"))\n    expect(resp.status).toBe(200)\n    const json = await resp.json()\n    expect(json).toBe(\"ほげ\")\n  })\n\n  it(\"should not double-encode query variables\", async () => {\n    const spy = jest.fn()\n    e.get(/.*/, (req, res) => {\n      spy([req.originalUrl, req.query])\n      res.end()\n    })\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    for (const test of [\n      {\n        endpoint: proxyPath,\n        query: { foo: \"bar with spaces\" },\n        expected: \"/wsup?foo=bar+with+spaces\",\n      },\n      {\n        endpoint: absProxyPath,\n        query: { foo: \"bar with spaces\" },\n        expected: absProxyPath + \"?foo=bar+with+spaces\",\n      },\n      {\n        endpoint: proxyPath,\n        query: { foo: \"with-&-ampersand\" },\n        expected: \"/wsup?foo=with-%26-ampersand\",\n      },\n      {\n        endpoint: absProxyPath,\n        query: { foo: \"with-&-ampersand\" },\n        expected: absProxyPath + \"?foo=with-%26-ampersand\",\n      },\n      {\n        endpoint: absProxyPath,\n        query: { foo: \"ほげ ほげ\" },\n        expected: absProxyPath + \"?foo=%E3%81%BB%E3%81%92+%E3%81%BB%E3%81%92\",\n      },\n      {\n        endpoint: proxyPath,\n        query: { foo: \"ほげ ほげ\" },\n        expected: \"/wsup?foo=%E3%81%BB%E3%81%92+%E3%81%BB%E3%81%92\",\n      },\n    ]) {\n      spy.mockClear()\n      const resp = await codeServer.fetch(test.endpoint, undefined, test.query)\n      expect(resp.status).toBe(200)\n      await resp.text()\n      expect(spy).toHaveBeenCalledTimes(1)\n      expect(spy).toHaveBeenCalledWith([test.expected, test.query])\n    }\n  })\n\n  it(\"should allow specifying an absproxy path\", async () => {\n    const prefixedPath = `/codeserver/app1${absProxyPath}`\n    e.get(prefixedPath, (req, res) => {\n      res.send(\"app being served behind a prefixed path\")\n    })\n    codeServer = await integration.setup([\"--auth=none\", \"--abs-proxy-base-path=/codeserver/app1\"], \"\")\n    const resp = await codeServer.fetch(absProxyPath)\n    expect(resp.status).toBe(200)\n    const text = await resp.text()\n    expect(text).toBe(\"app being served behind a prefixed path\")\n  })\n\n  it(\"should not allow OPTIONS without authentication by default\", async () => {\n    process.env.PASSWORD = \"test\"\n    codeServer = await integration.setup([\"--auth=password\"])\n    const resp = await codeServer.fetch(proxyPath, { method: \"OPTIONS\" })\n    expect(resp.status).toBe(401)\n  })\n\n  it(\"should allow OPTIONS with `skip-auth-preflight` flag\", async () => {\n    process.env.PASSWORD = \"test\"\n    codeServer = await integration.setup([\"--auth=password\", \"--skip-auth-preflight\"])\n    e.post(\"/wsup\", (req, res) => {})\n    const resp = await codeServer.fetch(proxyPath, { method: \"OPTIONS\" })\n    expect(resp.status).toBe(200)\n  })\n})\n\n// NOTE@jsjoeio\n// Both this test suite and the one above it are very similar\n// The main difference is this one uses http and node-fetch\n// and specifically tests the proxy in isolation vs. using\n// the httpserver abstraction we've built.\n//\n// Leaving this as a separate test suite for now because\n// we may consider refactoring the httpserver abstraction\n// in the future.\n//\n// If you're writing a test specifically for code in\n// src/node/proxy.ts, you should probably add it to\n// this test suite.\ndescribe(\"proxy (standalone)\", () => {\n  let URL = \"\"\n  let PROXY_URL = \"\"\n  let testServer: http.Server\n  let proxyTarget: http.Server\n\n  beforeEach(async () => {\n    const PORT = await getAvailablePort()\n    const PROXY_PORT = await getAvailablePort()\n    URL = `http://localhost:${PORT}`\n    PROXY_URL = `http://localhost:${PROXY_PORT}`\n    // Define server and a proxy server\n    testServer = http.createServer((req, res) => {\n      proxy.web(req, res, {\n        target: PROXY_URL,\n      })\n    })\n\n    proxyTarget = http.createServer((req, res) => {\n      res.writeHead(200, { \"Content-Type\": \"text/plain\" })\n      res.end()\n    })\n\n    // Start both servers\n    proxyTarget.listen(PROXY_PORT)\n    testServer.listen(PORT)\n  })\n\n  afterEach(async () => {\n    testServer.close()\n    proxyTarget.close()\n  })\n\n  it(\"should return a 500 when proxy target errors \", async () => {\n    // Close the proxy target so that proxy errors\n    proxyTarget.close()\n    const errorResp = await nodeFetch(`${URL}/error`)\n    expect(errorResp.status).toBe(HttpCode.ServerError)\n    expect(errorResp.statusText).toBe(\"Internal Server Error\")\n  })\n\n  it(\"should proxy correctly\", async () => {\n    const resp = await nodeFetch(`${URL}/route`)\n    expect(resp.status).toBe(200)\n    expect(resp.statusText).toBe(\"OK\")\n  })\n})\n"
  },
  {
    "path": "test/unit/node/routes/errors.test.ts",
    "content": "import express from \"express\"\nimport { UserProvidedArgs, setDefaults } from \"../../../../src/node/cli\"\nimport { errorHandler } from \"../../../../src/node/routes/errors\"\n\ndescribe(\"error page is rendered for text/html requests\", () => {\n  it(\"escapes any html in the error messages\", async () => {\n    const next = jest.fn()\n    const err = {\n      code: \"ENOENT\",\n      statusCode: 404,\n      message: \";>hello<script>alert(1)</script>\",\n    }\n    const req = await createRequest()\n    const res = {\n      status: jest.fn().mockReturnValue(this),\n      send: jest.fn().mockReturnValue(this),\n      set: jest.fn().mockReturnValue(this),\n    } as unknown as express.Response\n\n    await errorHandler(err, req, res, next)\n    expect(res.status).toHaveBeenCalledWith(404)\n    expect(res.send).toHaveBeenCalledWith(expect.not.stringContaining(\"<script>\"))\n  })\n\n  it(\"should use custom app-name in error page title\", async () => {\n    const err = {\n      statusCode: 404,\n      message: \"Not found\",\n    }\n    const req = await createRequest({ \"app-name\": \"MyCodeServer\" })\n    const res = {\n      status: jest.fn().mockReturnValue(this),\n      send: jest.fn().mockReturnValue(this),\n      set: jest.fn().mockReturnValue(this),\n    } as unknown as express.Response\n\n    await errorHandler(err, req, res, jest.fn())\n    expect(res.send).toHaveBeenCalledWith(expect.stringContaining(\"<title>404 - MyCodeServer</title>\"))\n  })\n\n  it(\"should use default 'code-server' when app-name is not set\", async () => {\n    const err = {\n      statusCode: 500,\n      message: \"Internal error\",\n    }\n    const req = await createRequest()\n    const res = {\n      status: jest.fn().mockReturnValue(this),\n      send: jest.fn().mockReturnValue(this),\n      set: jest.fn().mockReturnValue(this),\n    } as unknown as express.Response\n\n    await errorHandler(err, req, res, jest.fn())\n    expect(res.send).toHaveBeenCalledWith(expect.stringContaining(\"<title>500 - code-server</title>\"))\n  })\n})\n\nasync function createRequest(args: UserProvidedArgs = {}): Promise<express.Request> {\n  return {\n    headers: {\n      accept: [\"text/html\"],\n    },\n    originalUrl: \"http://example.com/test\",\n    query: {\n      to: \"test\",\n    },\n    args: await setDefaults(args),\n  } as unknown as express.Request\n}\n"
  },
  {
    "path": "test/unit/node/routes/health.test.ts",
    "content": "import * as httpserver from \"../../../utils/httpserver\"\nimport * as integration from \"../../../utils/integration\"\n\ndescribe(\"health\", () => {\n  let codeServer: httpserver.HttpServer | undefined\n\n  afterEach(async () => {\n    if (codeServer) {\n      await codeServer.dispose()\n      codeServer = undefined\n    }\n  })\n\n  it(\"/healthz\", async () => {\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const resp = await codeServer.fetch(\"/healthz\")\n    expect(resp.status).toBe(200)\n    const json = await resp.json()\n    expect(json).toStrictEqual({ lastHeartbeat: 0, status: \"expired\" })\n  })\n\n  it(\"/healthz (websocket)\", async () => {\n    codeServer = await integration.setup([\"--auth=none\"], \"\")\n    const ws = codeServer.ws(\"/healthz\")\n    const message = await new Promise((resolve, reject) => {\n      ws.on(\"error\", (err) => {\n        console.error(\"[healthz]\", err)\n      })\n      ws.on(\"message\", (message) => {\n        try {\n          const j = JSON.parse(message.toString())\n          resolve(j)\n        } catch (error) {\n          reject(error)\n        }\n      })\n      ws.on(\"open\", () => ws.send(JSON.stringify({ event: \"health\" })))\n    })\n    ws.terminate()\n    expect(message).toStrictEqual({ event: \"health\", status: \"expired\", lastHeartbeat: 0 })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/routes/login.test.ts",
    "content": "import { RateLimiter } from \"../../../../src/node/routes/login\"\nimport { mockLogger } from \"../../../utils/helpers\"\nimport * as httpserver from \"../../../utils/httpserver\"\nimport * as integration from \"../../../utils/integration\"\n\ndescribe(\"login\", () => {\n  beforeAll(() => {\n    mockLogger()\n  })\n\n  describe(\"RateLimiter\", () => {\n    it(\"should allow one try \", () => {\n      const limiter = new RateLimiter()\n      expect(limiter.removeToken()).toBe(true)\n    })\n\n    it(\"should pull tokens from both limiters (minute & hour)\", () => {\n      const limiter = new RateLimiter()\n\n      // Try twice, which pulls two from the minute bucket\n      limiter.removeToken()\n      limiter.removeToken()\n\n      // Check that we can still try\n      // which should be true since there are 12 remaining in the hour bucket\n      expect(limiter.canTry()).toBe(true)\n      expect(limiter.removeToken()).toBe(true)\n    })\n\n    it(\"should not allow more than 14 tries in less than an hour\", () => {\n      const limiter = new RateLimiter()\n\n      // The limiter allows 2 tries per minute plus 12 per hour\n      // so if we run it 15 times, 14 should return true and the last\n      // should return false\n      for (let i = 1; i <= 14; i++) {\n        expect(limiter.removeToken()).toBe(true)\n      }\n\n      expect(limiter.canTry()).toBe(false)\n      expect(limiter.removeToken()).toBe(false)\n    })\n  })\n  describe(\"/login\", () => {\n    let _codeServer: httpserver.HttpServer | undefined\n    function codeServer(): httpserver.HttpServer {\n      if (!_codeServer) {\n        throw new Error(\"tried to use code-server before setting it up\")\n      }\n      return _codeServer\n    }\n\n    // Store whatever might be in here so we can restore it afterward.\n    // TODO: We should probably pass this as an argument somehow instead of\n    // manipulating the environment.\n    const previousEnvPassword = process.env.PASSWORD\n\n    beforeEach(async () => {\n      process.env.PASSWORD = \"test\"\n      _codeServer = await integration.setup([\"--auth=password\"], \"\")\n    })\n\n    afterEach(async () => {\n      process.env.PASSWORD = previousEnvPassword\n      if (_codeServer) {\n        await _codeServer.dispose()\n        _codeServer = undefined\n      }\n    })\n\n    it(\"should return 'Missing password' without body\", async () => {\n      const resp = await codeServer().fetch(\"/login\", { method: \"POST\" })\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(\"Missing password\")\n    })\n\n    it(\"should return HTML with 'Incorrect password' message\", async () => {\n      const params = new URLSearchParams()\n      params.append(\"password\", \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")\n      const resp = await codeServer().fetch(\"/login\", {\n        method: \"POST\",\n        body: params,\n      })\n\n      expect(resp.status).toBe(200)\n\n      const htmlContent = await resp.text()\n\n      expect(htmlContent).toContain(\"Incorrect password\")\n    })\n\n    it(\"should return correct app-name\", async () => {\n      process.env.PASSWORD = previousEnvPassword\n      const appName = \"testnäme\"\n      const codeServer = await integration.setup([`--app-name=${appName}`], \"\")\n      const resp = await codeServer.fetch(\"/login\", { method: \"GET\" })\n\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(`${appName}</h1>`)\n      expect(htmlContent).toContain(`<title>${appName} login</title>`)\n    })\n\n    it(\"should return correct app-name when unset\", async () => {\n      process.env.PASSWORD = previousEnvPassword\n      const appName = \"code-server\"\n      const codeServer = await integration.setup([], \"\")\n      const resp = await codeServer.fetch(\"/login\", { method: \"GET\" })\n\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(`${appName}</h1>`)\n      expect(htmlContent).toContain(`<title>${appName} login</title>`)\n    })\n\n    it(\"should return correct welcome text\", async () => {\n      process.env.PASSWORD = previousEnvPassword\n      const welcomeText = \"Welcome to your code workspace! öäü🔐\"\n      const codeServer = await integration.setup([`--welcome-text=${welcomeText}`], \"\")\n      const resp = await codeServer.fetch(\"/login\", { method: \"GET\" })\n\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(welcomeText)\n    })\n\n    it(\"should return correct welcome text when none is set but app-name is\", async () => {\n      process.env.PASSWORD = previousEnvPassword\n      const appName = \"testnäme\"\n      const codeServer = await integration.setup([`--app-name=${appName}`], \"\")\n      const resp = await codeServer.fetch(\"/login\", { method: \"GET\" })\n\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(`Welcome to ${appName}`)\n    })\n\n    it(\"should return correct welcome text when locale is set to non-English\", async () => {\n      process.env.PASSWORD = previousEnvPassword\n      const locale = \"zh-cn\"\n      const codeServer = await integration.setup([`--locale=${locale}`], \"\")\n      const resp = await codeServer.fetch(\"/login\", { method: \"GET\" })\n\n      const htmlContent = await resp.text()\n      expect(resp.status).toBe(200)\n      expect(htmlContent).toContain(`欢迎来到 code-server`)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/routes/static.test.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { rootPath } from \"../../../../src/node/constants\"\nimport { clean, tmpdir } from \"../../../utils/helpers\"\nimport * as httpserver from \"../../../utils/httpserver\"\nimport * as integration from \"../../../utils/integration\"\n\nconst NOT_FOUND = {\n  code: 404,\n  message: /not found/i,\n}\n\ndescribe(\"/_static\", () => {\n  let _codeServer: httpserver.HttpServer | undefined\n  function codeServer(): httpserver.HttpServer {\n    if (!_codeServer) {\n      throw new Error(\"tried to use code-server before setting it up\")\n    }\n    return _codeServer\n  }\n\n  let testFile: string | undefined\n  let testFileContent: string | undefined\n  let nonExistentTestFile: string | undefined\n\n  const testName = \"_static\"\n  beforeAll(async () => {\n    await clean(testName)\n    const testDir = await tmpdir(testName)\n    testFile = path.join(testDir, \"test\")\n    testFileContent = \"static file contents\"\n    nonExistentTestFile = path.join(testDir, \"i-am-not-here\")\n    await fs.writeFile(testFile, testFileContent)\n  })\n\n  afterEach(async () => {\n    if (_codeServer) {\n      await _codeServer.dispose()\n      _codeServer = undefined\n    }\n  })\n\n  function commonTests() {\n    it(\"should return a 404 when a file is not provided\", async () => {\n      const resp = await codeServer().fetch(`/_static/`)\n      expect(resp.status).toBe(NOT_FOUND.code)\n\n      const content = await resp.json()\n      expect(content.error).toMatch(NOT_FOUND.message)\n    })\n  }\n\n  describe(\"disabled authentication\", () => {\n    beforeEach(async () => {\n      _codeServer = await integration.setup([\"--auth=none\"], \"\")\n    })\n\n    commonTests()\n\n    it(\"should return a 404 for a nonexistent file\", async () => {\n      const filePath = path.join(\"/_static/\", nonExistentTestFile!)\n\n      const resp = await codeServer().fetch(filePath)\n      expect(resp.status).toBe(NOT_FOUND.code)\n    })\n\n    it(\"should return a 200 and file contents for an existent file\", async () => {\n      const resp = await codeServer().fetch(\"/_static/src/browser/robots.txt\")\n      expect(resp.status).toBe(200)\n\n      const localFilePath = path.join(rootPath, \"src/browser/robots.txt\")\n      const localFileContent = await fs.readFile(localFilePath, \"utf8\")\n\n      // console.log(localFileContent)\n      const content = await resp.text()\n      expect(content).toStrictEqual(localFileContent)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/routes/vscode.test.ts",
    "content": "import { mockLogger } from \"../../../utils/helpers\"\nimport * as httpserver from \"../../../utils/httpserver\"\nimport * as integration from \"../../../utils/integration\"\n\ndescribe(\"vscode\", () => {\n  let codeServer: httpserver.HttpServer | undefined\n  beforeEach(() => {\n    mockLogger()\n  })\n\n  afterEach(async () => {\n    if (codeServer) {\n      await codeServer.dispose()\n      codeServer = undefined\n    }\n    jest.clearAllMocks()\n  })\n\n  it(\"should fail origin check\", async () => {\n    await expect(async () => {\n      codeServer = await integration.setup([\"--auth=none\"], \"\")\n      await codeServer.wsWait(\"/vscode\", {\n        headers: {\n          host: \"localhost:8080\",\n          origin: \"https://evil.org\",\n        },\n      })\n    }).rejects.toThrow()\n  })\n})\n"
  },
  {
    "path": "test/unit/node/settings.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport path from \"path\"\nimport { SettingsProvider, CoderSettings } from \"../../../src/node/settings\"\nimport { clean, mockLogger, tmpdir } from \"../../utils/helpers\"\n\ndescribe(\"settings\", () => {\n  const testName = \"settingsTests\"\n  let testDir = \"\"\n\n  beforeAll(async () => {\n    mockLogger()\n    await clean(testName)\n    testDir = await tmpdir(testName)\n  })\n  describe(\"with invalid JSON in settings file\", () => {\n    const mockSettingsFile = \"coder.json\"\n    let pathToMockSettingsFile = \"\"\n\n    beforeEach(async () => {\n      pathToMockSettingsFile = path.join(testDir, mockSettingsFile)\n      // Missing a quote, which makes it invalid intentionally\n      await fs.writeFile(pathToMockSettingsFile, '{\"fakeKey\":true,\"helloWorld:\"test\"}')\n    })\n    afterEach(async () => {\n      jest.clearAllMocks()\n    })\n    it(\"should log a warning\", async () => {\n      const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)\n      await settings.read()\n      // This happens when we can't parse a JSON (usually error in file)\n      expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/Expected ':'/))\n    })\n  })\n  describe(\"with invalid settings file path\", () => {\n    const mockSettingsFile = \"nonExistent.json\"\n    let pathToMockSettingsFile = \"\"\n\n    beforeEach(async () => {\n      // Add hello so it's a directory that doesn't exist\n      // NOTE: if we don't have that, it fails the test\n      // That's because it will write a file if it doesn't exist\n      // but it throws if there's a directory in the path that\n      // doesn't exist.\n      pathToMockSettingsFile = path.join(testDir, \"hello\", mockSettingsFile)\n    })\n    afterEach(async () => {\n      jest.clearAllMocks()\n    })\n    it(\"should log a warning\", async () => {\n      const settings = new SettingsProvider<CoderSettings>(pathToMockSettingsFile)\n      await settings.write({\n        update: {\n          checked: 2,\n          version: \"4.0.1\",\n        },\n      })\n      // This happens if it tries to writeFile to a nonexistent path\n      expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining(\"ENOENT: no such file or directory\"))\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/socket.test.ts",
    "content": "import { field, logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport * as net from \"net\"\nimport * as path from \"path\"\nimport * as tls from \"tls\"\nimport { Emitter } from \"../../../src/common/emitter\"\nimport { tmpdir } from \"../../../src/node/constants\"\nimport { SocketProxyProvider } from \"../../../src/node/socket\"\nimport { generateCertificate } from \"../../../src/node/util\"\n\ndescribe(\"SocketProxyProvider\", () => {\n  const provider = new SocketProxyProvider()\n\n  const onServerError = new Emitter<{ event: string; error: Error }>()\n  const onClientError = new Emitter<{ event: string; error: Error }>()\n  const onProxyError = new Emitter<{ event: string; error: Error }>()\n  const fromServerToClient = new Emitter<Buffer>()\n  const fromClientToServer = new Emitter<Buffer>()\n  const fromClientToProxy = new Emitter<Buffer>()\n\n  let errors = 0\n  let close = false\n  const onError = ({ event, error }: { event: string; error: Error }): void => {\n    if (!close || event === \"error\") {\n      logger.error(event, field(\"error\", error.message))\n      ++errors\n    }\n  }\n  onServerError.event(onError)\n  onClientError.event(onError)\n  onProxyError.event(onError)\n\n  let server: tls.TLSSocket\n  let proxy: net.Socket\n  let client: tls.TLSSocket\n\n  const getData = <T>(emitter: Emitter<T>): Promise<T> => {\n    return new Promise((resolve) => {\n      const d = emitter.event((t) => {\n        d.dispose()\n        resolve(t)\n      })\n    })\n  }\n\n  beforeAll(async () => {\n    const cert = await generateCertificate(\"localhost\")\n    const options = {\n      cert: await fs.readFile(cert.cert),\n      key: await fs.readFile(cert.certKey),\n      rejectUnauthorized: false,\n    }\n\n    await fs.mkdir(path.join(tmpdir, \"tests\"), { recursive: true })\n    const socketPath = await provider.findFreeSocketPath(path.join(tmpdir, \"tests/tls-socket-proxy\"))\n    await fs.rm(socketPath, { force: true, recursive: true })\n\n    return new Promise<void>((_resolve) => {\n      const resolved: { [key: string]: boolean } = { client: false, server: false }\n      const resolve = (type: \"client\" | \"server\"): void => {\n        resolved[type] = true\n        if (resolved.client && resolved.server) {\n          // We don't need any more connections.\n          main.close()\n          _resolve()\n        }\n      }\n      const main = tls\n        .createServer(options, (s) => {\n          server = s\n          server\n            .on(\"data\", (d) => fromClientToServer.emit(d))\n            .on(\"error\", (error) => onServerError.emit({ event: \"error\", error }))\n            .on(\"end\", () => onServerError.emit({ event: \"end\", error: new Error(\"unexpected end\") }))\n            .on(\"close\", () => onServerError.emit({ event: \"close\", error: new Error(\"unexpected close\") }))\n          resolve(\"server\")\n        })\n        .on(\"error\", (error) => onServerError.emit({ event: \"error\", error }))\n        .on(\"end\", () => onServerError.emit({ event: \"end\", error: new Error(\"unexpected end\") }))\n        .on(\"close\", () => onServerError.emit({ event: \"close\", error: new Error(\"unexpected close\") }))\n        .listen(socketPath, () => {\n          client = tls\n            .connect({ ...options, path: socketPath })\n            .on(\"data\", (d) => fromServerToClient.emit(d))\n            .on(\"error\", (error) => onClientError.emit({ event: \"error\", error }))\n            .on(\"end\", () => onClientError.emit({ event: \"end\", error: new Error(\"unexpected end\") }))\n            .on(\"close\", () => onClientError.emit({ event: \"close\", error: new Error(\"unexpected close\") }))\n            .once(\"connect\", () => resolve(\"client\"))\n        })\n    })\n  })\n\n  it(\"should work without a proxy\", async () => {\n    server.write(\"server->client\")\n    const dataFromServerToClient = (await getData(fromServerToClient)).toString()\n    expect(dataFromServerToClient).toBe(\"server->client\")\n    client.write(\"client->server\")\n    const dataFromClientToServer = (await getData(fromClientToServer)).toString()\n    expect(dataFromClientToServer).toBe(\"client->server\")\n    expect(errors).toEqual(0)\n  })\n\n  it(\"should work with a proxy\", async () => {\n    expect(server instanceof tls.TLSSocket).toBe(true)\n    proxy = (await provider.createProxy(server))\n      .on(\"data\", (d) => fromClientToProxy.emit(d))\n      .on(\"error\", (error) => onProxyError.emit({ event: \"error\", error }))\n      .on(\"end\", () => onProxyError.emit({ event: \"end\", error: new Error(\"unexpected end\") }))\n      .on(\"close\", () => onProxyError.emit({ event: \"close\", error: new Error(\"unexpected close\") }))\n\n    provider.stop() // We don't need more proxies.\n\n    proxy.write(\"server proxy->client\")\n    const dataFromServerToClient = (await getData(fromServerToClient)).toString()\n    expect(dataFromServerToClient).toBe(\"server proxy->client\")\n    client.write(\"client->server proxy\")\n    const dataFromClientToProxy = (await getData(fromClientToProxy)).toString()\n    expect(dataFromClientToProxy).toBe(\"client->server proxy\")\n    expect(errors).toEqual(0)\n  })\n\n  it(\"should close\", async () => {\n    close = true\n    client.end()\n    proxy.end()\n  })\n})\n"
  },
  {
    "path": "test/unit/node/update.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport * as http from \"http\"\nimport * as path from \"path\"\nimport { ensureAddress } from \"../../../src/node/app\"\nimport { SettingsProvider, UpdateSettings } from \"../../../src/node/settings\"\nimport { LatestResponse, UpdateProvider } from \"../../../src/node/update\"\nimport { clean, mockLogger, tmpdir } from \"../../utils/helpers\"\n\ndescribe(\"update\", () => {\n  let version = \"1.0.0\"\n  let spy: string[] = []\n  const server = http.createServer((request: http.IncomingMessage, response: http.ServerResponse) => {\n    if (!request.url) {\n      throw new Error(\"no url\")\n    }\n\n    spy.push(request.url)\n\n    // Return the latest version.\n    if (request.url === \"/latest\") {\n      const latest: LatestResponse = {\n        name: version,\n      }\n      response.writeHead(200)\n      return response.end(JSON.stringify(latest))\n    }\n\n    if (request.url === \"/reject-status-code\") {\n      response.writeHead(500)\n      return response.end(\"rejected status code test\")\n    }\n\n    if (request.url === \"/no-location-header\") {\n      response.writeHead(301, \"testing\", {\n        location: \"\",\n      })\n      return response.end(\"rejected status code test\")\n    }\n\n    if (request.url === \"/with-location-header\") {\n      response.writeHead(301, \"testing\", {\n        location: \"/latest\",\n      })\n\n      return response.end()\n    }\n\n    // Checks if url matches /redirect/${number}\n    // with optional trailing slash\n    const match = request.url.match(/\\/redirect\\/([0-9]+)\\/?$/)\n    if (match) {\n      if (request.url === \"/redirect/0\") {\n        response.writeHead(200)\n        return response.end(\"done\")\n      }\n\n      // Subtract 1 from the current redirect number\n      // i.e. /redirect/10 -> /redirect/9 -> /redirect/8\n      const currentRedirectNumber = parseInt(match[1])\n      const newRedirectNumber = currentRedirectNumber - 1\n\n      response.writeHead(302, \"testing\", {\n        location: `/redirect/${String(newRedirectNumber)}`,\n      })\n      return response.end(\"\")\n    }\n\n    // Anything else is a 404.\n    response.writeHead(404)\n    return response.end(\"not found\")\n  })\n\n  let _settings: SettingsProvider<UpdateSettings> | undefined\n  const settings = (): SettingsProvider<UpdateSettings> => {\n    if (!_settings) {\n      throw new Error(\"Settings provider has not been created\")\n    }\n    return _settings\n  }\n\n  let _provider: UpdateProvider | undefined\n  const provider = (): UpdateProvider => {\n    if (!_provider) {\n      throw new Error(\"Update provider has not been created\")\n    }\n    return _provider\n  }\n\n  let address = new URL(\"http://localhost\")\n  beforeAll(async () => {\n    mockLogger()\n\n    const testName = \"update\"\n    await clean(testName)\n    const testDir = await tmpdir(testName)\n    const jsonPath = path.join(testDir, \"update.json\")\n    _settings = new SettingsProvider<UpdateSettings>(jsonPath)\n\n    await new Promise((resolve, reject) => {\n      server.on(\"error\", reject)\n      server.on(\"listening\", resolve)\n      server.listen({\n        port: 0,\n        host: \"localhost\",\n      })\n    })\n\n    const addr = ensureAddress(server, \"http\")\n    if (typeof addr === \"string\") {\n      throw new Error(\"unable to run update tests with unix sockets\")\n    }\n    address = addr\n    address.pathname = \"/latest\"\n    _provider = new UpdateProvider(address.toString(), _settings)\n  })\n\n  afterAll(() => {\n    server.close()\n  })\n\n  beforeEach(() => {\n    jest.clearAllMocks()\n    spy = []\n  })\n\n  it(\"should get the latest\", async () => {\n    version = \"2.1.0\"\n\n    const p = provider()\n    const now = Date.now()\n    const update = await p.getUpdate()\n\n    await expect(settings().read()).resolves.toEqual({ update })\n    expect(isNaN(update.checked)).toEqual(false)\n    expect(update.checked).toBeGreaterThanOrEqual(now)\n    expect(update.checked).toBeLessThanOrEqual(Date.now())\n    expect(update.version).toStrictEqual(\"2.1.0\")\n    expect(spy).toEqual([\"/latest\"])\n  })\n\n  it(\"should keep existing information\", async () => {\n    version = \"3.0.1\"\n\n    const p = provider()\n    const now = Date.now()\n    const update = await p.getUpdate()\n\n    await expect(settings().read()).resolves.toEqual({ update })\n    expect(isNaN(update.checked)).toStrictEqual(false)\n    expect(update.checked).toBeLessThanOrEqual(now)\n    expect(update.version).toStrictEqual(\"2.1.0\")\n    expect(spy).toEqual([])\n  })\n\n  it(\"should force getting the latest\", async () => {\n    version = \"4.1.1\"\n\n    const p = provider()\n    const now = Date.now()\n    const update = await p.getUpdate(true)\n\n    await expect(settings().read()).resolves.toEqual({ update })\n    expect(isNaN(update.checked)).toStrictEqual(false)\n    expect(update.checked).toBeGreaterThanOrEqual(now)\n    expect(update.checked).toBeLessThanOrEqual(Date.now())\n    expect(update.version).toStrictEqual(\"4.1.1\")\n    expect(spy).toStrictEqual([\"/latest\"])\n  })\n\n  it(\"should get latest after interval passes\", async () => {\n    const p = provider()\n    await p.getUpdate()\n    expect(spy).toEqual([])\n\n    let checked = Date.now() - 1000 * 60 * 60 * 23\n    await settings().write({ update: { checked, version } })\n    await p.getUpdate()\n    expect(spy).toEqual([])\n\n    checked = Date.now() - 1000 * 60 * 60 * 25\n    await settings().write({ update: { checked, version } })\n\n    const update = await p.getUpdate()\n    expect(update.checked).not.toStrictEqual(checked)\n    expect(spy).toStrictEqual([\"/latest\"])\n  })\n\n  it(\"should check if it's the current version\", async () => {\n    version = \"9999999.99999.9999\"\n\n    const p = provider()\n    let update = await p.getUpdate(true)\n    expect(p.isLatestVersion(update)).toStrictEqual(false)\n\n    version = \"0.0.0\"\n    update = await p.getUpdate(true)\n    expect(p.isLatestVersion(update)).toStrictEqual(true)\n\n    // Old version format; make sure it doesn't report as being later.\n    version = \"999999.9999-invalid999.99.9\"\n    update = await p.getUpdate(true)\n    expect(p.isLatestVersion(update)).toStrictEqual(true)\n  })\n\n  it(\"should not reject if unable to fetch\", async () => {\n    let provider = new UpdateProvider(\"invalid\", settings())\n    let now = Date.now()\n    let update = await provider.getUpdate(true)\n    expect(isNaN(update.checked)).toStrictEqual(false)\n    expect(update.checked).toBeGreaterThanOrEqual(now)\n    expect(update.checked).toBeLessThanOrEqual(Date.now())\n    expect(update.version).toStrictEqual(\"unknown\")\n\n    provider = new UpdateProvider(\"http://probably.invalid.dev.localhost/latest\", settings())\n    now = Date.now()\n    update = await provider.getUpdate(true)\n    expect(isNaN(update.checked)).toStrictEqual(false)\n    expect(update.checked).toBeGreaterThanOrEqual(now)\n    expect(update.checked).toBeLessThanOrEqual(Date.now())\n    expect(update.version).toStrictEqual(\"unknown\")\n  })\n\n  it(\"should reject if response has status code 500\", async () => {\n    address.pathname = \"/reject-status-code\"\n    const provider = new UpdateProvider(address.toString(), settings())\n    const update = await provider.getUpdate(true)\n\n    expect(update.version).toBe(\"unknown\")\n    expect(logger.error).toHaveBeenCalled()\n    expect(logger.error).toHaveBeenCalledWith(\"Failed to get latest version\", {\n      identifier: \"error\",\n      value: `${address.toString()}: 500`,\n    })\n  })\n\n  it(\"should reject if no location header provided\", async () => {\n    address.pathname = \"/no-location-header\"\n    const provider = new UpdateProvider(address.toString(), settings())\n    const update = await provider.getUpdate(true)\n\n    expect(update.version).toBe(\"unknown\")\n    expect(logger.error).toHaveBeenCalled()\n    expect(logger.error).toHaveBeenCalledWith(\"Failed to get latest version\", {\n      identifier: \"error\",\n      value: `received redirect with no location header`,\n    })\n  })\n\n  it(\"should resolve the request with response.headers.location\", async () => {\n    version = \"4.1.1\"\n    address.pathname = \"/with-location-header\"\n    const provider = new UpdateProvider(address.toString(), settings())\n    const update = await provider.getUpdate(true)\n\n    expect(logger.error).not.toHaveBeenCalled()\n    expect(update.version).toBe(\"4.1.1\")\n  })\n\n  it(\"should reject if more than 10 redirects\", async () => {\n    address.pathname = \"/redirect/11\"\n    const provider = new UpdateProvider(address.toString(), settings())\n    const update = await provider.getUpdate(true)\n\n    expect(update.version).toBe(\"unknown\")\n    expect(logger.error).toHaveBeenCalled()\n    expect(logger.error).toHaveBeenCalledWith(\"Failed to get latest version\", {\n      identifier: \"error\",\n      value: `reached max redirects`,\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/util.test.ts",
    "content": "import * as cp from \"child_process\"\nimport { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { generateUuid } from \"../../../src/common/util\"\nimport { tmpdir } from \"../../../src/node/constants\"\nimport * as util from \"../../../src/node/util\"\nimport { clean, tmpdir as tempDirHelper } from \"../../utils/helpers\"\n\ndescribe(\"getEnvPaths\", () => {\n  describe(\"on darwin\", () => {\n    beforeEach(() => {\n      jest.resetModules()\n      jest.mock(\"env-paths\", () => {\n        return () => ({\n          data: \"/home/envPath/.local/share\",\n          config: \"/home/envPath/.config\",\n          temp: \"/tmp/envPath/runtime\",\n        })\n      })\n    })\n    it(\"should return the env paths using xdgBasedir\", () => {\n      jest.mock(\"xdg-basedir\", () => ({\n        data: \"/home/usr/.local/share\",\n        config: \"/home/usr/.config\",\n        runtime: \"/tmp/runtime\",\n      }))\n      const getEnvPaths = require(\"../../../src/node/util\").getEnvPaths\n      const envPaths = getEnvPaths(\"darwin\")\n\n      expect(envPaths.data).toEqual(\"/home/usr/.local/share/code-server\")\n      expect(envPaths.config).toEqual(\"/home/usr/.config/code-server\")\n      expect(envPaths.runtime).toEqual(\"/tmp/runtime/code-server\")\n    })\n\n    it(\"should return the env paths using envPaths when xdgBasedir is undefined\", () => {\n      jest.mock(\"xdg-basedir\", () => ({}))\n      const getEnvPaths = require(\"../../../src/node/util\").getEnvPaths\n      const envPaths = getEnvPaths(\"darwin\")\n\n      expect(envPaths.data).toEqual(\"/home/envPath/.local/share\")\n      expect(envPaths.config).toEqual(\"/home/envPath/.config\")\n      expect(envPaths.runtime).toEqual(\"/tmp/envPath/runtime\")\n    })\n  })\n  describe(\"on win32\", () => {\n    beforeEach(() => {\n      jest.resetModules()\n      jest.mock(\"env-paths\", () => {\n        return () => ({\n          data: \"/windows/envPath/.local/share\",\n          config: \"/windows/envPath/.config\",\n          temp: \"/tmp/envPath/runtime\",\n        })\n      })\n    })\n\n    it(\"should return the env paths using envPaths\", () => {\n      const getEnvPaths = require(\"../../../src/node/util\").getEnvPaths\n      const envPaths = getEnvPaths(\"win32\")\n\n      expect(envPaths.data).toEqual(\"/windows/envPath/.local/share\")\n      expect(envPaths.config).toEqual(\"/windows/envPath/.config\")\n      expect(envPaths.runtime).toEqual(\"/tmp/envPath/runtime\")\n    })\n  })\n  describe(\"on other platforms\", () => {\n    beforeEach(() => {\n      jest.resetModules()\n      jest.mock(\"env-paths\", () => {\n        return () => ({\n          data: \"/linux/envPath/.local/share\",\n          config: \"/linux/envPath/.config\",\n          temp: \"/tmp/envPath/runtime\",\n        })\n      })\n    })\n\n    it(\"should return the runtime using xdgBasedir if it exists\", () => {\n      jest.mock(\"xdg-basedir\", () => ({\n        runtime: \"/tmp/runtime\",\n      }))\n      const getEnvPaths = require(\"../../../src/node/util\").getEnvPaths\n      const envPaths = getEnvPaths(\"linux\")\n\n      expect(envPaths.data).toEqual(\"/linux/envPath/.local/share\")\n      expect(envPaths.config).toEqual(\"/linux/envPath/.config\")\n      expect(envPaths.runtime).toEqual(\"/tmp/runtime/code-server\")\n    })\n\n    it(\"should return the env paths using envPaths when xdgBasedir is undefined\", () => {\n      jest.mock(\"xdg-basedir\", () => ({}))\n      const getEnvPaths = require(\"../../../src/node/util\").getEnvPaths\n      const envPaths = getEnvPaths(\"linux\")\n\n      expect(envPaths.data).toEqual(\"/linux/envPath/.local/share\")\n      expect(envPaths.config).toEqual(\"/linux/envPath/.config\")\n      expect(envPaths.runtime).toEqual(\"/tmp/envPath/runtime\")\n    })\n  })\n})\n\ndescribe(\"hash\", () => {\n  it(\"should return a hash of the string passed in\", async () => {\n    const plainTextPassword = \"mySecretPassword123\"\n    const hashed = await util.hash(plainTextPassword)\n    expect(hashed).not.toBe(plainTextPassword)\n  })\n  it(\"should return a hash for an empty string\", async () => {\n    const hashed = await util.hash(\"\")\n    expect(hashed).not.toBe(\"\")\n  })\n})\n\ndescribe(\"isHashMatch\", () => {\n  it(\"should return true if the password matches the hash\", async () => {\n    const password = \"codeserver1234\"\n    const _hash = await util.hash(password)\n    const actual = await util.isHashMatch(password, _hash)\n    expect(actual).toBe(true)\n  })\n  it(\"should return false if the password does not match the hash\", async () => {\n    const password = \"password123\"\n    const _hash = await util.hash(password)\n    const actual = await util.isHashMatch(\"otherPassword123\", _hash)\n    expect(actual).toBe(false)\n  })\n  it(\"should return true with actual hash\", async () => {\n    const password = \"password123\"\n    const _hash = \"$argon2i$v=19$m=4096,t=3,p=1$EAoczTxVki21JDfIZpTUxg$rkXgyrW4RDGoDYrxBFD4H2DlSMEhP4h+Api1hXnGnFY\"\n    const actual = await util.isHashMatch(password, _hash)\n    expect(actual).toBe(true)\n  })\n  it(\"should return false if the password is empty\", async () => {\n    const password = \"\"\n    const _hash = \"$argon2i$v=19$m=4096,t=3,p=1$EAoczTxVki21JDfIZpTUxg$rkXgyrW4RDGoDYrxBFD4H2DlSMEhP4h+Api1hXnGnFY\"\n    const actual = await util.isHashMatch(password, _hash)\n    expect(actual).toBe(false)\n  })\n  it(\"should return false if the hash is empty\", async () => {\n    const password = \"hellowpasssword\"\n    const _hash = \"\"\n    const actual = await util.isHashMatch(password, _hash)\n    expect(actual).toBe(false)\n  })\n  it(\"should return false and not throw an error if the hash doesn't start with a $\", async () => {\n    const password = \"hellowpasssword\"\n    const _hash = \"n2i$v=19$m=4096,t=3,p=1$EAoczTxVki21JDfIZpTUxg$rkXgyrW4RDGoDYrxBFD4H2DlSMEhP4h+Api1hXnGnFY\"\n    expect(async () => await util.isHashMatch(password, _hash)).not.toThrow()\n    expect(await util.isHashMatch(password, _hash)).toBe(false)\n  })\n  it(\"should reject the promise and throw if error\", async () => {\n    const password = \"hellowpasssword\"\n    const _hash = \"$ar2i\"\n    expect(async () => await util.isHashMatch(password, _hash)).rejects.toThrow()\n  })\n})\n\ndescribe(\"hashLegacy\", () => {\n  it(\"should return a hash of the string passed in\", () => {\n    const plainTextPassword = \"mySecretPassword123\"\n    const hashed = util.hashLegacy(plainTextPassword)\n    expect(hashed).not.toBe(plainTextPassword)\n  })\n})\n\ndescribe(\"isHashLegacyMatch\", () => {\n  it(\"should return true if is match\", () => {\n    const password = \"password123\"\n    const _hash = util.hashLegacy(password)\n    expect(util.isHashLegacyMatch(password, _hash)).toBe(true)\n  })\n  it(\"should return false if is match\", () => {\n    const password = \"password123\"\n    const _hash = util.hashLegacy(password)\n    expect(util.isHashLegacyMatch(\"otherPassword123\", _hash)).toBe(false)\n  })\n  it(\"should return true if hashed from command line\", () => {\n    const password = \"password123\"\n    // Hashed using printf \"password123\" | sha256sum | cut -d' ' -f1\n    const _hash = \"ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f\"\n    expect(util.isHashLegacyMatch(password, _hash)).toBe(true)\n  })\n})\n\ndescribe(\"getPasswordMethod\", () => {\n  it(\"should return PLAIN_TEXT for no hashed password\", () => {\n    const hashedPassword = undefined\n    const passwordMethod = util.getPasswordMethod(hashedPassword)\n    const expected: util.PasswordMethod = \"PLAIN_TEXT\"\n    expect(passwordMethod).toEqual(expected)\n  })\n  it(\"should return ARGON2 for password with 'argon2'\", () => {\n    const hashedPassword =\n      \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\"\n    const passwordMethod = util.getPasswordMethod(hashedPassword)\n    const expected: util.PasswordMethod = \"ARGON2\"\n    expect(passwordMethod).toEqual(expected)\n  })\n  it(\"should return SHA256 for password with legacy hash\", () => {\n    const hashedPassword = \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\"\n    const passwordMethod = util.getPasswordMethod(hashedPassword)\n    const expected: util.PasswordMethod = \"SHA256\"\n    expect(passwordMethod).toEqual(expected)\n  })\n})\n\ndescribe(\"handlePasswordValidation\", () => {\n  it(\"should return true with a hashedPassword for a PLAIN_TEXT password\", async () => {\n    const p = \"password\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"PLAIN_TEXT\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: p,\n      hashedPasswordFromArgs: undefined,\n    })\n\n    const matchesHash = await util.isHashMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(true)\n    expect(matchesHash).toBe(true)\n  })\n  it(\"should return false when PLAIN_TEXT password doesn't match args\", async () => {\n    const p = \"password\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"PLAIN_TEXT\",\n      passwordFromRequestBody: \"password1\",\n      passwordFromArgs: p,\n      hashedPasswordFromArgs: undefined,\n    })\n\n    const matchesHash = await util.isHashMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(false)\n    expect(matchesHash).toBe(false)\n  })\n  it(\"should return true with a hashedPassword for a SHA256 password\", async () => {\n    const p = \"helloworld\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"SHA256\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: undefined,\n      hashedPasswordFromArgs: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\",\n    })\n\n    const matchesHash = util.isHashLegacyMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(true)\n    expect(matchesHash).toBe(true)\n  })\n  it(\"should return false when SHA256 password doesn't match hash\", async () => {\n    const p = \"helloworld1\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"SHA256\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: undefined,\n      hashedPasswordFromArgs: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\",\n    })\n\n    const matchesHash = util.isHashLegacyMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(false)\n    expect(matchesHash).toBe(false)\n  })\n  it(\"should return true with a hashedPassword for a ARGON2 password\", async () => {\n    const p = \"password\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"ARGON2\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: undefined,\n      hashedPasswordFromArgs:\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n    })\n\n    const matchesHash = await util.isHashMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(true)\n    expect(matchesHash).toBe(true)\n  })\n  it(\"should return false when ARGON2 password doesn't match hash\", async () => {\n    const p = \"password1\"\n    const passwordValidation = await util.handlePasswordValidation({\n      passwordMethod: \"ARGON2\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: undefined,\n      hashedPasswordFromArgs:\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n    })\n\n    const matchesHash = await util.isHashMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(false)\n    expect(matchesHash).toBe(false)\n  })\n})\n\ndescribe(\"isCookieValid\", () => {\n  it(\"should be valid if hashed-password for SHA256 matches cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"SHA256\",\n      cookieKey: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\",\n      hashedPasswordFromArgs: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\",\n      passwordFromArgs: undefined,\n    })\n    expect(isValid).toBe(true)\n  })\n  it(\"should be invalid if hashed-password for SHA256 does not match cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"SHA256\",\n      cookieKey: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb9442bb6f8f8f07af\",\n      hashedPasswordFromArgs: \"936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af\",\n      passwordFromArgs: undefined,\n    })\n    expect(isValid).toBe(false)\n  })\n  it(\"should be valid if hashed-password for ARGON2 matches cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"ARGON2\",\n      cookieKey: \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n      hashedPasswordFromArgs:\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n      passwordFromArgs: undefined,\n    })\n    expect(isValid).toBe(true)\n  })\n  it(\"should be invalid if hashed-password for ARGON2 does not match cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"ARGON2\",\n      cookieKey: \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9H\",\n      hashedPasswordFromArgs:\n        \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n      passwordFromArgs: undefined,\n    })\n    expect(isValid).toBe(false)\n  })\n  it(\"should be valid if password for PLAIN_TEXT matches cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"PLAIN_TEXT\",\n      cookieKey: \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY\",\n      passwordFromArgs: \"password\",\n      hashedPasswordFromArgs: undefined,\n    })\n    expect(isValid).toBe(true)\n  })\n  it(\"should be invalid if hashed-password for PLAIN_TEXT does not match cookie.key\", async () => {\n    const isValid = await util.isCookieValid({\n      passwordMethod: \"PLAIN_TEXT\",\n      cookieKey: \"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9H\",\n      passwordFromArgs: \"password1234\",\n      hashedPasswordFromArgs: undefined,\n    })\n    expect(isValid).toBe(false)\n  })\n  it(\"should return false and empty string as hashedPassword when passwordMethod is invalid\", async () => {\n    const p = \"password1\"\n    const passwordValidation = await util.handlePasswordValidation({\n      // @ts-expect-error although this shouldn't ever happen, it ensures the default case in this function\n      // works as expected.\n      passwordMethod: \"INVALID\",\n      passwordFromRequestBody: p,\n      passwordFromArgs: undefined,\n      hashedPasswordFromArgs: undefined,\n    })\n\n    const matchesHash = await util.isHashMatch(p, passwordValidation.hashedPassword)\n\n    expect(passwordValidation.isPasswordValid).toBe(false)\n    expect(matchesHash).toBe(false)\n  })\n})\n\ndescribe(\"sanitizeString\", () => {\n  it(\"should return an empty string if passed a type other than a string\", () => {\n    expect(util.sanitizeString({} as string)).toBe(\"\")\n  })\n  it(\"should trim whitespace\", () => {\n    expect(util.sanitizeString(\" hello   \")).toBe(\"hello\")\n  })\n  it(\"should always return an empty string\", () => {\n    expect(util.sanitizeString(\"   \")).toBe(\"\")\n  })\n})\n\ndescribe(\"onLine\", () => {\n  // Spawn a process that outputs anything given on stdin.\n  let proc: cp.ChildProcess | undefined\n\n  beforeAll(() => {\n    proc = cp.spawn(\"node\", [\"-e\", 'process.stdin.setEncoding(\"utf8\");process.stdin.on(\"data\", console.log)'])\n  })\n\n  afterAll(() => {\n    proc?.kill()\n  })\n\n  it(\"should call with individual lines\", async () => {\n    const size = 100\n    const received = new Promise<string[]>((resolve) => {\n      const lines: string[] = []\n      util.onLine(proc!, (line) => {\n        lines.push(line)\n        if (lines.length === size) {\n          resolve(lines)\n        }\n      })\n    })\n\n    const expected: string[] = []\n    for (let i = 0; i < size; ++i) {\n      expected.push(generateUuid(i))\n    }\n\n    proc?.stdin?.write(expected.join(\"\\n\"))\n\n    expect(await received).toEqual(expected)\n  })\n\n  describe(\"used with a process missing stdout \", () => {\n    it(\"should throw an error\", async () => {\n      // Initialize a process that does not have stdout.\n      // \"If the child was spawned with stdio set to anything\n      // other than 'pipe', then subprocess.stdout will be null.\"\n      // Source: https://stackoverflow.com/a/46024006/3015595\n      // Other source: https://nodejs.org/api/child_process.html#child_process_subprocess_stdout\n      // NOTE@jsjoeio - I'm not sure if this actually happens though\n      // which is why I have to set proc.stdout = null\n      // a couple lines below.\n      const proc = cp.spawn(\"node\", [], {\n        stdio: \"ignore\",\n      })\n      const mockCallback = jest.fn()\n\n      expect(() => util.onLine(proc, mockCallback)).toThrowError(/stdout/)\n\n      // Cleanup\n      proc?.kill()\n    })\n  })\n})\n\ndescribe(\"escapeHtml\", () => {\n  it(\"should escape HTML\", () => {\n    expect(util.escapeHtml(`<div class=\"error\">\"'ello & world\"</div>`)).toBe(\n      \"&lt;div class=&quot;error&quot;&gt;&quot;&apos;ello &amp; world&quot;&lt;/div&gt;\",\n    )\n  })\n})\n\ndescribe(\"isFile\", () => {\n  const testDir = path.join(tmpdir, \"tests\", \"isFile\")\n  let pathToFile = \"\"\n\n  beforeEach(async () => {\n    pathToFile = path.join(testDir, \"foo.txt\")\n    await fs.mkdir(testDir, { recursive: true })\n    await fs.writeFile(pathToFile, \"hello\")\n  })\n  afterEach(async () => {\n    await fs.rm(testDir, { recursive: true, force: true })\n  })\n  it(\"should return false if is directory\", async () => {\n    expect(await util.isFile(testDir)).toBe(false)\n  })\n  it(\"should return true if is file\", async () => {\n    expect(await util.isFile(pathToFile)).toBe(true)\n  })\n  it(\"should return false if the path doesn't exist\", async () => {\n    expect(await util.isFile(\"fakefile.txt\")).toBe(false)\n  })\n})\n\ndescribe(\"isDirectory\", () => {\n  const testDir = path.join(tmpdir, \"tests\", \"isDirectory\")\n  let pathToFile = \"\"\n\n  beforeEach(async () => {\n    pathToFile = path.join(testDir, \"foo.txt\")\n    await fs.mkdir(testDir, { recursive: true })\n    await fs.writeFile(pathToFile, \"hello\")\n  })\n  afterEach(async () => {\n    await fs.rm(testDir, { recursive: true, force: true })\n  })\n  it(\"should return false if is a file\", async () => {\n    expect(await util.isDirectory(pathToFile)).toBe(false)\n  })\n  it(\"should return true if is directory\", async () => {\n    expect(await util.isDirectory(testDir)).toBe(true)\n  })\n  it(\"should return false if the path doesn't exist\", async () => {\n    expect(await util.isDirectory(\"fakefile.txt\")).toBe(false)\n  })\n})\n\ndescribe(\"isWsl\", () => {\n  const testName = \"wsl\"\n\n  beforeAll(async () => {\n    await clean(testName)\n  })\n\n  describe(\"on Linux (microsoft)\", () => {\n    it(\"should return true\", async () => {\n      const fileName = \"proc-version\"\n      const osRelease = \"5.4.0-1066-gke\"\n      const pathToFile = path.join(await tempDirHelper(testName), fileName)\n      await fs.writeFile(\n        pathToFile,\n        \"Linux version 3.4.0-Microsoft (Microsoft@Microsoft.com) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Wed Dec 31 14:42:53 PST 2014\",\n      )\n      expect(await util.isWsl(\"linux\", osRelease, pathToFile)).toBe(true)\n    })\n  })\n  describe(\"on Linux (non-microsoft)\", () => {\n    it(\"should return false\", async () => {\n      const fileName = \"proc-version2\"\n      const osRelease = \"Linux\"\n      const pathToFile = path.join(await tempDirHelper(testName), fileName)\n      await fs.writeFile(\n        pathToFile,\n        \"Linux version 5.4.0-1066-gke (buildd@lcy02-amd64-039) (gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04)) #69-Ubuntu SMP Fri Mar 11 13:52:45 UTC 202\",\n      )\n      expect(await util.isWsl(\"linux\", osRelease, pathToFile)).toBe(false)\n    })\n  })\n  describe(\"on Win32 with microsoft in /proc/version\", () => {\n    it(\"should return false\", async () => {\n      const fileName = \"proc-version3\"\n      const osRelease = \"3.4.0-Microsoft\"\n      const pathToFile = path.join(await tempDirHelper(testName), fileName)\n      await fs.writeFile(\n        pathToFile,\n        \"Linux version 3.4.0-Microsoft (Microsoft@Microsoft.com) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Wed Dec 31 14:42:53 PST 2014\",\n      )\n      expect(await util.isWsl(\"win32\", osRelease, pathToFile)).toBe(false)\n    })\n  })\n  describe(\"on Darwin\", () => {\n    it(\"should return false\", async () => {\n      const fileName = \"proc-version4\"\n      const osRelease =\n        \"Darwin Roadrunner.local 10.3.0 Darwin Kernel Version 10.3.0: Fri Feb 26 11:58:09 PST 2010; root:xnu-1504.3.12~1/RELEASE_I386 i386\"\n      const pathToFile = path.join(await tempDirHelper(testName), fileName)\n      expect(await util.isWsl(\"darwin\", osRelease, pathToFile)).toBe(false)\n    })\n  })\n})\n\ndescribe(\"open\", () => {\n  it(\"should throw an error if address is a string\", async () => {\n    const address = \"localhost:3000\"\n    await expect(util.open(address)).rejects.toThrow(\"Cannot open socket paths\")\n  })\n})\ndescribe(\"constructOpenOptions\", () => {\n  it(\"should return options for darwin\", () => {\n    const platform: NodeJS.Platform | \"wsl\" = \"darwin\"\n    const url = new URL(\"localhost:8080\")\n    const { args, command, urlSearch } = util.constructOpenOptions(platform, url.search)\n    expect(args).toStrictEqual([])\n    expect(command).toBe(\"open\")\n    expect(urlSearch).toBe(\"\")\n  })\n  it(\"should return options for linux\", () => {\n    const platform: NodeJS.Platform | \"wsl\" = \"linux\"\n    const url = new URL(\"localhost:8080\")\n    const { args, command, urlSearch } = util.constructOpenOptions(platform, url.search)\n    expect(args).toStrictEqual([])\n    expect(command).toBe(\"xdg-open\")\n    expect(urlSearch).toBe(\"\")\n  })\n  it(\"should return options for win32\", () => {\n    const platform: NodeJS.Platform | \"wsl\" = \"win32\"\n    const url = new URL(\"localhost:8080?q=&test\")\n    const { args, command, urlSearch } = util.constructOpenOptions(platform, url.search)\n    expect(args).toStrictEqual([\"/c\", \"start\", '\"\"', \"/b\"])\n    expect(command).toBe(\"cmd\")\n    expect(urlSearch).toBe(\"?q=^&test\")\n  })\n  it(\"should return options for wsl\", () => {\n    const platform: NodeJS.Platform | \"wsl\" = \"wsl\"\n    const url = new URL(\"localhost:8080?q=&test\")\n    const { args, command, urlSearch } = util.constructOpenOptions(platform, url.search)\n    expect(args).toStrictEqual([\"/c\", \"start\", '\"\"', \"/b\"])\n    expect(command).toBe(\"cmd.exe\")\n    expect(urlSearch).toBe(\"?q=^&test\")\n  })\n})\n\ndescribe(\"splitOnFirstEquals\", () => {\n  const tests = [\n    {\n      name: \"empty\",\n      key: \"\",\n      value: \"\",\n    },\n    {\n      name: \"split on first equals\",\n      key: \"foo\",\n      value: \"bar\",\n    },\n    {\n      name: \"split on first equals even with multiple equals\",\n      key: \"foo\",\n      value: \"bar=baz\",\n    },\n    {\n      name: \"split with empty value\",\n      key: \"foo\",\n      value: \"\",\n    },\n    {\n      name: \"split with no value\",\n      key: \"foo\",\n      value: undefined,\n    },\n  ]\n  tests.forEach((test) => {\n    it(\"should ${test.name}\", () => {\n      const input = test.key && typeof test.value !== \"undefined\" ? `${test.key}=${test.value}` : test.key\n      const [key, value] = util.splitOnFirstEquals(input)\n      expect(key).toStrictEqual(test.key)\n      expect(value).toStrictEqual(test.value || undefined)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/vscodeSocket.test.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport * as app from \"../../../src/node/app\"\nimport { EditorSessionManager, makeEditorSessionManagerServer } from \"../../../src/node/vscodeSocket\"\nimport { clean, tmpdir, listenOn, mockLogger } from \"../../utils/helpers\"\n\ndescribe(\"makeEditorSessionManagerServer\", () => {\n  let tmpDirPath: string\n\n  const testName = \"mesms\"\n\n  beforeAll(async () => {\n    jest.clearAllMocks()\n    mockLogger()\n    await clean(testName)\n  })\n\n  afterAll(() => {\n    jest.resetModules()\n  })\n\n  beforeEach(async () => {\n    tmpDirPath = await tmpdir(testName)\n  })\n\n  it(\"warns if socket cannot be created\", async () => {\n    jest.spyOn(app, \"listen\").mockImplementation(() => {\n      throw new Error()\n    })\n    const server = await makeEditorSessionManagerServer(\n      `${tmpDirPath}/code-server-ipc.sock`,\n      new EditorSessionManager(),\n    )\n    expect(logger.warn).toHaveBeenCalledWith(`Could not create socket at ${tmpDirPath}/code-server-ipc.sock`)\n    server.close()\n  })\n})\n\ndescribe(\"EditorSessionManager\", () => {\n  let tmpDirPath: string\n\n  const testName = \"esm\"\n\n  beforeAll(async () => {\n    await clean(testName)\n  })\n\n  beforeEach(async () => {\n    tmpDirPath = await tmpdir(testName)\n  })\n\n  describe(\"getCandidatesForFile\", () => {\n    it(\"should prefer the last added socket path for a matching path\", async () => {\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa-1.sock`,\n      })\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa-2.sock`,\n      })\n      manager.addSession({\n        workspace: {\n          id: \"bbb\",\n          folders: [\n            {\n              uri: {\n                path: \"/bbb\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-bbb.sock`,\n      })\n      const socketPaths = manager.getCandidatesForFile(\"/aaa/some-file:1:1\")\n      expect(socketPaths.map((x) => x.socketPath)).toEqual([\n        // Matches\n        `${tmpDirPath}/vscode-ipc-aaa-2.sock`,\n        `${tmpDirPath}/vscode-ipc-aaa-1.sock`,\n        // Non-matches\n        `${tmpDirPath}/vscode-ipc-bbb.sock`,\n      ])\n    })\n\n    it(\"should return the last added socketPath if there are no matches\", async () => {\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      })\n      manager.addSession({\n        workspace: {\n          id: \"bbb\",\n          folders: [\n            {\n              uri: {\n                path: \"/bbb\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-bbb.sock`,\n      })\n      const socketPaths = manager.getCandidatesForFile(\"/ccc/some-file:1:1\")\n      expect(socketPaths.map((x) => x.socketPath)).toEqual([\n        `${tmpDirPath}/vscode-ipc-bbb.sock`,\n        `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      ])\n    })\n\n    it(\"does not just directly do a substring match\", async () => {\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      })\n      manager.addSession({\n        workspace: {\n          id: \"bbb\",\n          folders: [\n            {\n              uri: {\n                path: \"/bbb\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-bbb.sock`,\n      })\n      const entries = manager.getCandidatesForFile(\"/aaaxxx/some-file:1:1\")\n      expect(entries.map((x) => x.socketPath)).toEqual([\n        `${tmpDirPath}/vscode-ipc-bbb.sock`,\n        `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      ])\n    })\n  })\n\n  describe(\"getConnectedSocketPath\", () => {\n    it(\"should return socket path if socket is active\", async () => {\n      listenOn(`${tmpDirPath}/vscode-ipc-aaa.sock`).once()\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      })\n      const socketPath = await manager.getConnectedSocketPath(\"/aaa/some-file:1:1\")\n      expect(socketPath).toBe(`${tmpDirPath}/vscode-ipc-aaa.sock`)\n    })\n\n    it(\"should return undefined if socket is inactive\", async () => {\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      })\n      const socketPath = await manager.getConnectedSocketPath(\"/aaa/some-file:1:1\")\n      expect(socketPath).toBeUndefined()\n    })\n\n    it(\"should return undefined given no matching active sockets\", async () => {\n      const vscodeSockets = listenOn(`${tmpDirPath}/vscode-ipc-bbb.sock`)\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa.sock`,\n      })\n      const socketPath = await manager.getConnectedSocketPath(\"/aaa/some-file:1:1\")\n      expect(socketPath).toBeUndefined()\n      vscodeSockets.close()\n    })\n\n    it(\"should return undefined if there are no entries\", async () => {\n      const manager = new EditorSessionManager()\n      const socketPath = await manager.getConnectedSocketPath(\"/aaa/some-file:1:1\")\n      expect(socketPath).toBeUndefined()\n    })\n\n    it(\"should return most recently used socket path available\", async () => {\n      listenOn(`${tmpDirPath}/vscode-ipc-aaa-1.sock`).once()\n      const manager = new EditorSessionManager()\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa-1.sock`,\n      })\n      manager.addSession({\n        workspace: {\n          id: \"aaa\",\n          folders: [\n            {\n              uri: {\n                path: \"/aaa\",\n              },\n            },\n          ],\n        },\n        socketPath: `${tmpDirPath}/vscode-ipc-aaa-2.sock`,\n      })\n\n      const socketPath = await manager.getConnectedSocketPath(\"/aaa/some-file:1:1\")\n      expect(socketPath).toBe(`${tmpDirPath}/vscode-ipc-aaa-1.sock`)\n      // Failed sockets should be removed from the entries.\n      expect((manager as any).entries.has(`${tmpDirPath}/vscode-ipc-aaa-2.sock`)).toBe(false)\n    })\n  })\n})\n"
  },
  {
    "path": "test/unit/node/wrapper.test.ts",
    "content": "import { ChildProcess, ParentProcess, isChild } from \"../../../src/node/wrapper\"\n\ndescribe(\"wrapper\", () => {\n  describe(\"isChild\", () => {\n    it(\"should return false for parent process\", () => {\n      const p = new ParentProcess(\"1\")\n      expect(isChild(p)).toBe(false)\n    })\n  })\n  it(\"should return false for parent process\", () => {\n    const childProc = new ChildProcess(1)\n    expect(isChild(childProc)).toBe(true)\n  })\n})\n"
  },
  {
    "path": "test/utils/constants.ts",
    "content": "export const PASSWORD = \"e45432jklfdsab\"\nexport const workspaceDir = \"workspaces\"\nexport const REVERSE_PROXY_BASE_PATH = process.env.CS_TEST_REVERSE_PROXY_BASE_PATH || \"ide\"\nexport const REVERSE_PROXY_PORT = process.env.CS_TEST_REVERSE_PROXY_PORT || \"8000\"\n"
  },
  {
    "path": "test/utils/cssStub.ts",
    "content": "// Note: this is needed for the register.test.ts\n// This is because inside src/browser/register.ts\n// we import CSS files, which Jest can't handle unless we tell it how to\n// See: https://stackoverflow.com/a/39434579/3015595\nmodule.exports = {}\n"
  },
  {
    "path": "test/utils/globalE2eSetup.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { workspaceDir } from \"./constants\"\nimport { clean, tmpdir } from \"./helpers\"\nimport * as wtfnode from \"./wtfnode\"\n\n/**\n * Perform workspace cleanup and authenticate. This should be ran before e2e\n * tests execute.\n */\nexport default async function () {\n  console.log(\"\\n🚨 Running Global Setup for Playwright End-to-End Tests\")\n  console.log(\"   Please hang tight...\")\n\n  // Cleanup workspaces from previous tests.\n  await clean(workspaceDir)\n\n  if (process.env.WTF_NODE) {\n    wtfnode.setup()\n  }\n\n  // Create dummy code-workspace for routes.test.ts\n  const codeWorkspace = path.join(await tmpdir(workspaceDir), \"test.code-workspace\")\n  await fs.writeFile(codeWorkspace, \"\")\n  process.env.CODE_WORKSPACE_DIR = codeWorkspace\n\n  // Create dummy folder for routes.test.ts\n  const folder = await tmpdir(workspaceDir)\n  process.env.CODE_FOLDER_DIR = folder\n\n  console.log(\"✅ Global Setup for Playwright End-to-End Tests is now complete.\")\n}\n"
  },
  {
    "path": "test/utils/globalUnitSetup.ts",
    "content": "import { workspaceDir } from \"./constants\"\nimport { clean } from \"./helpers\"\n\n/**\n * Perform workspace cleanup. This should be ran before unit tests execute.\n */\nexport default async function () {\n  await clean(workspaceDir)\n}\n"
  },
  {
    "path": "test/utils/helpers.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport { promises as fs } from \"fs\"\nimport * as net from \"net\"\nimport * as os from \"os\"\nimport * as path from \"path\"\nimport { CodeServer, CodeServerPage } from \"../e2e/models/CodeServer\"\nimport { REVERSE_PROXY_PORT, REVERSE_PROXY_BASE_PATH } from \"./constants\"\n\n/**\n * Spy on the logger and console and replace with mock implementations to\n * suppress the output.\n */\nexport function mockLogger() {\n  jest.spyOn(logger, \"debug\").mockImplementation()\n  jest.spyOn(logger, \"error\").mockImplementation()\n  jest.spyOn(logger, \"info\").mockImplementation()\n  jest.spyOn(logger, \"trace\").mockImplementation()\n  jest.spyOn(logger, \"warn\").mockImplementation()\n\n  jest.spyOn(console, \"log\").mockImplementation()\n  jest.spyOn(console, \"debug\").mockImplementation()\n  jest.spyOn(console, \"error\").mockImplementation()\n  jest.spyOn(console, \"info\").mockImplementation()\n  jest.spyOn(console, \"trace\").mockImplementation()\n  jest.spyOn(console, \"warn\").mockImplementation()\n}\n\n/**\n * Clean up directories left by a test. It is recommended to do this when a test\n * starts to avoid potentially accumulating infinite test directories.\n */\nexport async function clean(testName: string): Promise<void> {\n  const dir = path.join(os.tmpdir(), `code-server/tests/${testName}`)\n  await fs.rm(dir, { force: true, recursive: true })\n}\n\n/**\n * Create a uniquely named temporary directory for a test.\n *\n * `tmpdir` should usually be preceeded by at least one call to `clean`.\n */\nexport async function tmpdir(testName: string): Promise<string> {\n  const dir = path.join(os.tmpdir(), `code-server/tests/${testName}`)\n  await fs.mkdir(dir, { recursive: true })\n\n  return await fs.mkdtemp(path.join(dir, `${testName}-`), { encoding: \"utf8\" })\n}\n\n/**\n * @description Helper function to use an environment variable.\n *\n * @returns an array (similar to useState in React) with a function\n * to set the value and reset the value\n */\nexport function useEnv(key: string): [(nextValue: string | undefined) => string | undefined, () => void] {\n  const initialValue = process.env[key]\n  const setValue = (nextValue: string | undefined) => (process.env[key] = nextValue)\n  // Node automatically converts undefined to string 'undefined'\n  // when assigning an environment variable.\n  // which is why we need to delete it if it's supposed to be undefined\n  // Source: https://stackoverflow.com/a/60147167\n  const resetValue = () => {\n    if (initialValue !== undefined) {\n      process.env[key] = initialValue\n    } else {\n      delete process.env[key]\n    }\n  }\n\n  return [setValue, resetValue]\n}\n\n/**\n * Helper function to get a random port.\n *\n * Source: https://github.com/sindresorhus/get-port/blob/main/index.js#L23-L33\n */\nexport const getAvailablePort = (options?: net.ListenOptions): Promise<number> =>\n  new Promise((resolve, reject) => {\n    const server = net.createServer()\n    server.unref()\n    server.on(\"error\", reject)\n    server.listen(options, () => {\n      // NOTE@jsjoeio: not a huge fan of the type assertion\n      // but it works for now.\n      const { port } = server.address() as net.AddressInfo\n      server.close(() => {\n        resolve(port)\n      })\n    })\n  })\n\n/**\n * Return a timer that will not reject as long as it is disposed or continually\n * reset before the delay elapses.\n */\nexport function idleTimer(message: string, reject: (error: Error) => void, delay = 5000) {\n  const start = () => setTimeout(() => reject(new Error(message)), delay)\n  let timeout = start()\n  return {\n    reset: () => {\n      clearTimeout(timeout)\n      timeout = start()\n    },\n    dispose: () => {\n      clearTimeout(timeout)\n    },\n  }\n}\n\n/**\n * If using a proxy, return the address of the proxy.\n *\n * Otherwise, return the direct address of code-server.\n */\nexport async function getMaybeProxiedCodeServer(codeServer: CodeServerPage | CodeServer): Promise<string> {\n  const address = await codeServer.address()\n  if (process.env.USE_PROXY === \"1\") {\n    const uri = new URL(address)\n    return `http://${uri.hostname}:${REVERSE_PROXY_PORT}/${uri.port}/${REVERSE_PROXY_BASE_PATH}/`\n  }\n\n  return address\n}\n\n/**\n * Stripes proxy base from url.pathname\n * i.e. /<port>/ide + route returns just route\n */\nexport function getMaybeProxiedPathname(url: URL): string {\n  if (process.env.USE_PROXY === \"1\") {\n    // Behind proxy, path will be /<port>/ide + route\n    const pathWithoutProxy = url.pathname.split(`/${REVERSE_PROXY_BASE_PATH}`)[1]\n    return pathWithoutProxy\n  }\n\n  return url.pathname\n}\n\ninterface FakeVscodeSockets {\n  /* If called, closes all servers after the first connection. */\n  once(): FakeVscodeSockets\n\n  /* Manually close all servers. */\n  close(): Promise<void>\n}\n\n/**\n * Creates servers for each socketPath specified.\n */\nexport function listenOn(...socketPaths: string[]): FakeVscodeSockets {\n  let once = false\n  const servers = socketPaths.map((socketPath) => {\n    const server = net.createServer(() => {\n      if (once) {\n        close()\n      }\n    })\n    server.listen(socketPath)\n    return server\n  })\n\n  async function close() {\n    await Promise.all(\n      servers.map(\n        (server) =>\n          new Promise<void>((resolve, reject) => {\n            server.close((err) => {\n              if (err) {\n                reject(err)\n                return\n              }\n              resolve()\n            })\n          }),\n      ),\n    )\n  }\n  const fakeVscodeSockets = {\n    close,\n    once: () => {\n      once = true\n      return fakeVscodeSockets\n    },\n  }\n  return fakeVscodeSockets\n}\n"
  },
  {
    "path": "test/utils/httpserver.ts",
    "content": "import { logger } from \"@coder/logger\"\nimport * as express from \"express\"\nimport * as http from \"http\"\nimport nodeFetch, { RequestInit, Response } from \"node-fetch\"\nimport Websocket from \"ws\"\nimport { Disposable } from \"../../src/common/emitter\"\nimport * as util from \"../../src/common/util\"\nimport { ensureAddress } from \"../../src/node/app\"\nimport { disposer } from \"../../src/node/http\"\nimport { handleUpgrade } from \"../../src/node/wsRouter\"\n\n// Perhaps an abstraction similar to this should be used in app.ts as well.\nexport class HttpServer {\n  private hs: http.Server\n  public dispose: Disposable[\"dispose\"]\n\n  /**\n   * Expects a server and a disposal that cleans up the server (and anything\n   * else that may need cleanup).\n   *\n   * Otherwise a new server is created.\n   */\n  public constructor(server?: { server: http.Server; dispose: Disposable[\"dispose\"] }) {\n    this.hs = server?.server || http.createServer()\n    this.dispose = server?.dispose || disposer(this.hs)\n  }\n\n  /**\n   * listen starts the server on a random localhost port.\n   * Use close to cleanup when done.\n   */\n  public listen(fn: http.RequestListener): Promise<void> {\n    this.hs.on(\"request\", fn)\n\n    return new Promise((resolve, reject) => {\n      this.hs.on(\"error\", reject)\n\n      this.hs.listen(0, \"127.0.0.1\", () => {\n        this.hs.off(\"error\", reject)\n        resolve()\n\n        this.hs.on(\"error\", (err) => {\n          // Promise resolved earlier so this is some other error.\n          util.logError(logger, \"http server error\", err)\n        })\n      })\n    })\n  }\n\n  /**\n   * Send upgrade requests to an Express app.\n   */\n  public listenUpgrade(app: express.Express): void {\n    handleUpgrade(app, this.hs)\n  }\n\n  /**\n   * fetch fetches the request path.\n   * The request path must be rooted!\n   */\n  public fetch(requestPath: string, opts?: RequestInit, query?: { [key: string]: string }): Promise<Response> {\n    const address = ensureAddress(this.hs, \"http\")\n    if (typeof address === \"string\") {\n      throw new Error(\"Cannot fetch socket path\")\n    }\n    address.pathname = requestPath\n    if (query) {\n      Object.keys(query).forEach((key) => {\n        address.searchParams.append(key, query[key])\n      })\n    }\n    return nodeFetch(address.toString(), opts)\n  }\n\n  /**\n   * Open a websocket against the request path.\n   */\n  public ws(requestPath: string, options?: Websocket.ClientOptions): Websocket {\n    const address = ensureAddress(this.hs, \"ws\")\n    if (typeof address === \"string\") {\n      throw new Error(\"Cannot open websocket to socket path\")\n    }\n    address.pathname = requestPath\n\n    return new Websocket(address.toString(), options)\n  }\n\n  /**\n   * Open a websocket and wait for it to fully open.\n   */\n  public wsWait(requestPath: string, options?: Websocket.ClientOptions): Promise<Websocket> {\n    const ws = this.ws(requestPath, options)\n    return new Promise<Websocket>((resolve, reject) => {\n      ws.on(\"error\", (err) => reject(err))\n      ws.on(\"open\", () => resolve(ws))\n    })\n  }\n\n  public port(): number {\n    const addr = this.hs.address()\n    if (addr && typeof addr === \"object\") {\n      return addr.port\n    }\n    throw new Error(\"server not listening or listening on unix socket\")\n  }\n}\n"
  },
  {
    "path": "test/utils/integration.ts",
    "content": "import { promises as fs } from \"fs\"\nimport * as path from \"path\"\nimport { parse, parseConfigFile, setDefaults } from \"../../src/node/cli\"\nimport { runCodeServer } from \"../../src/node/main\"\nimport { workspaceDir } from \"./constants\"\nimport { tmpdir } from \"./helpers\"\nimport * as httpserver from \"./httpserver\"\n\nexport async function setup(argv: string[], configFile?: string): Promise<httpserver.HttpServer> {\n  // This will be used as the data directory to ensure instances do not bleed\n  // into each other.\n  const dir = await tmpdir(workspaceDir)\n\n  // VS Code complains if the logs dir is missing which spams the output.\n  // TODO: Does that mean we are not creating it when we should be?\n  await fs.mkdir(path.join(dir, \"logs\"))\n\n  const cliArgs = parse([\n    `--config=${path.join(dir, \"config.yaml\")}`,\n    `--user-data-dir=${dir}`,\n    \"--bind-addr=localhost:0\",\n    \"--log=warn\",\n    ...argv,\n  ])\n  const configArgs = parseConfigFile(configFile || \"\", \"test/integration.ts\")\n  const args = await setDefaults(cliArgs, configArgs)\n\n  const server = await runCodeServer(args)\n\n  return new httpserver.HttpServer(server)\n}\n"
  },
  {
    "path": "test/utils/runCodeServerCommand.ts",
    "content": "import { exec } from \"child_process\"\nimport path from \"path\"\nimport { promisify } from \"util\"\n\n/**\n *\n * A helper function for integration tests to run code-server commands.\n */\nexport async function runCodeServerCommand(\n  argv: string[],\n  env?: NodeJS.ProcessEnv,\n): Promise<{ stdout: string; stderr: string }> {\n  const CODE_SERVER_COMMAND = process.env.CODE_SERVER_PATH || path.resolve(\"../../release-standalone/bin/code-server\")\n  const { stdout, stderr } = await promisify(exec)(`${CODE_SERVER_COMMAND} ${argv.join(\" \")}`, {\n    env: { ...process.env, ...env },\n  })\n\n  return { stdout, stderr }\n}\n"
  },
  {
    "path": "test/utils/wtfnode.ts",
    "content": "import * as util from \"util\"\nimport * as wtfnode from \"wtfnode\"\n\n// Jest seems to hijack console.log in a way that makes the output difficult to\n// read. So we'll write directly to process.stderr instead.\nconst write = (...args: [any, ...any]) => {\n  if (args.length > 0) {\n    process.stderr.write(util.format(...args) + \"\\n\")\n  }\n}\nwtfnode.setLogger(\"info\", write)\nwtfnode.setLogger(\"warn\", write)\nwtfnode.setLogger(\"error\", write)\n\nlet active = false\n\n/**\n * Start logging open handles periodically. This can be used to see what is\n * hanging open if anything.\n */\nexport function setup(): void {\n  if (active) {\n    return\n  }\n  active = true\n\n  const interval = 5000\n  const wtfnodeDump = () => {\n    wtfnode.dump()\n    const t = setTimeout(wtfnodeDump, interval)\n    t.unref()\n  }\n  const t = setTimeout(wtfnodeDump, interval)\n  t.unref()\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es6\",\n    \"lib\": [\"es2020\", \"dom\", \"dom.iterable\"],\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"strict\": true,\n    \"noImplicitReturns\": true,\n    \"noUnusedLocals\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"outDir\": \"./out\",\n    \"declaration\": false,\n    \"experimentalDecorators\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"sourceMap\": true,\n    \"tsBuildInfoFile\": \"./.cache/tsbuildinfo\",\n    \"incremental\": true,\n    \"typeRoots\": [\n      \"./node_modules/@types\",\n      \"./typings\",\n      \"./test/node_modules/@types\",\n      \"./lib/vscode/src/vs/server/@types\"\n    ],\n    \"downlevelIteration\": true,\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"./src/**/*\"],\n  \"exclude\": [\"/test\", \"/lib\", \"/ci\", \"/doc\"]\n}\n"
  },
  {
    "path": "typings/httpolyglot/index.d.ts",
    "content": "declare module \"httpolyglot\" {\n  import * as http from \"http\"\n  import * as https from \"https\"\n\n  function createServer(requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void): http.Server\n  function createServer(\n    options: https.ServerOptions,\n    requestListener?: (req: http.IncomingMessage, res: http.ServerResponse) => void,\n  ): https.Server\n}\n"
  }
]