diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/codespace-env.sh b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/codespace-env.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e06bd97dd4972d468a675b04b54d9bd28ae465a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/codespace-env.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +[[ -n "${CODESPACE_NAME:-}" ]] || exit 0 + +set_env() { + local key=$1 value=$2 tmp + tmp=$(mktemp) + trap 'rm -f "$tmp"' RETURN + awk -v k="$key" -v v="$value" ' + index($0, k "=") == 1 { print k "=" v; found = 1; next } + { print } + END { if (!found) print k "=" v } + ' .env >"$tmp" + cat "$tmp" >.env +} + +domain=${GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN:-app.github.dev} +set_env HOME_LOCATION "https://${CODESPACE_NAME}-8000.${domain}" +set_env API_LOCATION "https://${CODESPACE_NAME}-3000.${domain}" +printf 'Codespace detected. HOME_LOCATION and API_LOCATION in .env now use %s.\n' "$domain" diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/devcontainer.json b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..8cae7d417cb19b939a10ad8e7eba0145d0793968 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/devcontainer.json @@ -0,0 +1,51 @@ +{ + "name": "freeCodeCamp", + "dockerComposeFile": ["../docker/docker-compose.yml", "docker-compose.yml"], + "service": "devcontainer", + "workspaceFolder": "/workspaces/freeCodeCamp", + "hostRequirements": { + "cpus": 4, + "memory": "16gb", + "storage": "32gb" + }, + "mounts": [ + "source=fcc-node-modules,target=${containerWorkspaceFolder}/node_modules,type=volume" + ], + "forwardPorts": [8000, 3000, 8025], + "portsAttributes": { + "8000": { "label": "Client", "onAutoForward": "notify" }, + "3000": { "label": "API", "onAutoForward": "silent" }, + "8025": { "label": "Mailpit", "onAutoForward": "silent" } + }, + "otherPortsAttributes": { "onAutoForward": "silent" }, + "onCreateCommand": ".devcontainer/on-create.sh", + "updateContentCommand": "pnpm install --prefer-offline", + // post-create.sh runs codespace-env.sh. That rewrite must not move to + // onCreateCommand: a prebuild snapshots the container after onCreateCommand + // and would freeze the wrong hostname. + "postCreateCommand": ".devcontainer/post-create.sh", + // Codespaces resets port visibility on stop, and postCreateCommand does + // not run again on a restart. + "postStartCommand": ".devcontainer/post-start.sh", + "postAttachCommand": ".devcontainer/welcome.sh", + "customizations": { + "vscode": { + "extensions": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"], + "settings": { + "tasks": { + "version": "2.0.0", + "tasks": [ + { + "label": "Start freeCodeCamp", + "type": "shell", + "command": "pnpm run develop", + "isBackground": true, + "problemMatcher": [], + "presentation": { "reveal": "always", "panel": "dedicated" } + } + ] + } + } + } + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/docker-compose.yml b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c9b263526d1e5338f196e273e360a095cff63e1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/docker-compose.yml @@ -0,0 +1,33 @@ +name: freecodecamp-devcontainer + +services: + devcontainer: + image: ghcr.io/freecodecamp/devcontainer:latest + # gatsby develop defaults to host `localhost`. Where the network namespace + # has IPv6, glibc RFC 6724 precedence resolves that to ::1 first, so the + # dev server binds IPv6 loopback only and port forwarding, which connects + # over IPv4, is refused. 0.0.0.0 needs no AF_INET6 socket, so it also holds + # where IPv6 is switched off. + environment: + GATSBY_HOST: 0.0.0.0 + volumes: + - ..:/workspaces/freeCodeCamp:cached + # Shares the db network namespace so MONGOHQ_URL and MAILPIT_HOST in + # sample.env resolve on localhost. A service in that namespace cannot + # publish a port, which is why the host ports live in a separate overlay. + network_mode: service:db + command: sleep infinity + depends_on: + db: + condition: service_healthy + setup: + condition: service_completed_successfully + mailpit: + condition: service_started + + mailpit: + # Same namespace, for MAILPIT_HOST=localhost. + network_mode: service:db + depends_on: + db: + condition: service_healthy diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/on-create.sh b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/on-create.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb53ef43054dad6b473194201fdf85aaa6b4213d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/on-create.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +sudo chown node:node node_modules + +[[ -f .env ]] || cp sample.env .env diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-create.sh b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-create.sh new file mode 100644 index 0000000000000000000000000000000000000000..908abb3b5dca00b28603d69fe2b66a7bf70e3789 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-create.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +wait_for_primary() { + for _ in $(seq 1 30); do + if mongosh --quiet --eval 'if (!db.hello().isWritablePrimary) quit(1)' >/dev/null 2>&1; then + return 0 + fi + sleep 2 + done + return 1 +} + +rsync -a --include='*/' --include='.turbo/***' --exclude='*' /home/node/.cache/fcc/ ./ + +.devcontainer/codespace-env.sh + +if ! wait_for_primary; then + printf 'MongoDB did not become writable. Run "docker compose ps" to inspect the services.\n' >&2 + exit 1 +fi + +set -a +# shellcheck disable=SC1091 +. ./.env +set +a + +pnpm seed diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-start.sh b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-start.sh new file mode 100644 index 0000000000000000000000000000000000000000..9957e563f3095369a5d2f1e345cefc66e98c5904 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/post-start.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs on every start, including a resume. Codespaces resets port visibility +# when a codespace stops, and postCreateCommand does not run again. +[[ -n "${CODESPACE_NAME:-}" ]] || exit 0 + +for attempt in 1 2; do + status=0 + err=$(timeout 20 gh codespace ports visibility 3000:public -c "$CODESPACE_NAME" 2>&1) || status=$? + + if [[ $status -eq 0 ]]; then + printf 'Port 3000 is public, so the client can reach the API.\n' + printf 'Anybody with the URL can reach it, and the development sign-in\n' + printf 'route needs no password. Stop the codespace when you finish.\n' + exit 0 + fi + + if [[ $status -eq 124 ]]; then + err="gh timed out after 20 seconds" + fi + + if [[ $status -eq 127 ]]; then + err="gh is not installed" + break + fi + + if [[ $attempt -lt 2 ]]; then + sleep 5 + fi +done + +printf 'gh could not set the port: %s\n' "$err" >&2 +cat <<'MSG' + +Port 3000 is private, so the client cannot reach the API yet. +Open the Ports panel, right click port 3000, then choose Port Visibility, +then Public. + +A public port is reachable by anybody who has the URL, and the development +sign-in route needs no password. Stop the codespace when you finish working. + +MSG diff --git a/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/welcome.sh b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/welcome.sh new file mode 100644 index 0000000000000000000000000000000000000000..e73933e10956dcdd4f3d479ca4d6b312f740076c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.devcontainer/welcome.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +cat <<'MSG' + + freeCodeCamp is ready. Dependencies are installed, MongoDB is running, + and a test user is seeded. + + Open a new terminal and start the development script: + + pnpm run develop + + Read the setup and troubleshooting guide before you begin: + + https://contribute.freecodecamp.org/how-to-setup-freecodecamp-locally/ + +MSG diff --git a/github_code/freeCodeCamp__freeCodeCamp/.dockerignore b/github_code/freeCodeCamp__freeCodeCamp/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..355b70c46de98c5c0e77f66bd0fa46a8f8c57efc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.dockerignore @@ -0,0 +1,11 @@ +client/.cache +client/public +.env +.git +.gitignore +.dockerignore +docker/**/Dockerfile +**/*docker-compose* +**/node_modules +.eslintcache + diff --git a/github_code/freeCodeCamp__freeCodeCamp/.editorconfig b/github_code/freeCodeCamp__freeCodeCamp/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..2c6f376d342e690a1675f50abef0a13897a6c933 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[package.json] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false diff --git a/github_code/freeCodeCamp__freeCodeCamp/.gitattributes b/github_code/freeCodeCamp__freeCodeCamp/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..40ba3b6eaec637d95f80be977c0fddc5c342e52e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.gitattributes @@ -0,0 +1,15 @@ +* text=auto eol=lf + +# These files are binary and should be left untouched +*.eot binary +*.gif binary +*.ico binary +*.jpeg binary +*.jpg binary +*.mov binary +*.mp3 binary +*.mp4 binary +*.pdf binary +*.png binary +*.ttf binary +*.woff binary diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/.well-known/funding-manifest-urls b/github_code/freeCodeCamp__freeCodeCamp/.github/.well-known/funding-manifest-urls new file mode 100644 index 0000000000000000000000000000000000000000..570d41968ffb18b3ad3b814bf0d5b8eb4247252f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/.well-known/funding-manifest-urls @@ -0,0 +1 @@ +https://www.freecodecamp.org/funding.json diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/CODEOWNERS b/github_code/freeCodeCamp__freeCodeCamp/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..a2003a4f811247c1b4b3d45f4e64919ecf1f64eb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/CODEOWNERS @@ -0,0 +1,36 @@ +# ------------------------------------------------- +# CODEOWNERS - For automated review request for +# high impact files. +# +# Important: The order in this file cascades. +# +# https://help.github.com/articles/about-codeowners +# ------------------------------------------------- + +# ------------------------------------------------- +# Files that need attention from primary teams +# ------------------------------------------------- + +# --- All files +* @freecodecamp/dev-team @freecodecamp/curriculum + +# --- Package files for negation --- + +**/package.json @freecodecamp/none +**/pnpm-lock.yaml @freecodecamp/none + +# ------------------------------------------------- +# Files that need attention from i18n & dev team +# ------------------------------------------------- + +# i18n Quotes +**/motivation.json @freeCodeCamp/dev-team @freeCodeCamp/i18n + + +# ------------------------------------------------- +# Files that need attention from the mobile team +# ------------------------------------------------- + +/client/src/redux/prop-types.ts @freeCodeCamp/dev-team @freeCodeCamp/mobile +/client/tools/external-curriculum/* @freeCodeCamp/dev-team @freeCodeCamp/mobile +/curriculum/schema/challenge-schema.js @freeCodeCamp/dev-team @freeCodeCamp/mobile diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/FUNDING.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..ef35c76704f8a741b73f4bf1b457b30e430d76b2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/FUNDING.yml @@ -0,0 +1,3 @@ +github: freecodecamp +patreon: freecodecamp +custom: [www.freecodecamp.org/donate] diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/01--issues-with-coding-challenges.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/01--issues-with-coding-challenges.yml new file mode 100644 index 0000000000000000000000000000000000000000..d0e4030634461f7bca0ab1d02bac09c8446db9b7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/01--issues-with-coding-challenges.yml @@ -0,0 +1,61 @@ +name: Issue - Content in our Coding Challenges +description: Report issues with a specific challenge, like broken tests, unclear instructions, etc. +type: Bug +labels: ['scope: curriculum', 'status: waiting triage'] +body: + - type: markdown + attributes: + value: If you're reporting a security issue, don't create a GitHub issue. Instead, visit https://contribute.freecodecamp.org/#/security. + - type: textarea + attributes: + label: Describe the Issue + description: A clear and concise description of the issue you encountered. + validations: + required: true + - type: input + attributes: + label: Affected Page + description: Add a link to the coding challenge with the problem. + validations: + required: true + - type: textarea + attributes: + label: Your code + description: Copy and paste the code from the editor that you used in between the back-ticks. + value: | + ``` + + + + ``` + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: Add a clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. You can drag and drop `png`, `jpg`, `gif`, etc. in this box. + validations: + required: false + - type: textarea + attributes: + label: System + description: Please complete the following information. + value: | + - Device: [e.g. iPhone 6, Laptop] + - OS: [e.g. iOS 14, Windows 10, Ubuntu 20.04] + - Browser: [e.g. Chrome, Safari] + - Version: [e.g. 22] + validations: + required: true + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/02--issues-with-software-on-platforms.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/02--issues-with-software-on-platforms.yml new file mode 100644 index 0000000000000000000000000000000000000000..5cce34013026d5829c47296bbf5cce9aca226a19 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/02--issues-with-software-on-platforms.yml @@ -0,0 +1,60 @@ +name: Issue - User Interface on our Platforms +description: Report a software bug on /learn, /news, Community Forum, Code Radio, or any of the platforms. +type: Bug +labels: ['status: waiting triage'] +body: + - type: markdown + attributes: + value: If you're reporting a security issue, don't create a GitHub issue. Instead, visit https://contribute.freecodecamp.org/#/security. + - type: textarea + attributes: + label: Describe the Issue + description: A clear and concise description of the issue you encountered. + validations: + required: true + - type: input + attributes: + label: Affected Page + description: Add a link to the page with the problem. + validations: + required: true + - type: textarea + attributes: + label: Steps to Reproduce + description: Please provide the steps to reproduce the issue. + value: | + 1. Go to '...' + 2. Click on '...' + 3. Scroll down to '...' + 4. See error + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: Add a clear and concise description of what you expected to happen. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. You can drag and drop `png`, `jpg`, `gif`, etc. in this box. + validations: + required: false + - type: textarea + attributes: + label: System + description: Please complete the following information. + value: | + - Device: [e.g. iPhone 6, Laptop] + - OS: [e.g. iOS 14, Windows 10, Ubuntu 20.04] + - Browser: [e.g. Chrome, Safari] + - Version: [e.g. 22] + validations: + required: true + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + validations: + required: false diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/03--issues-with-content-on-articles-and-docs.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/03--issues-with-content-on-articles-and-docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ad7fffc20a8e6e05e9dfed5031cde7d71c4bb8d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/03--issues-with-content-on-articles-and-docs.yml @@ -0,0 +1,41 @@ +name: Issues - Content in our Articles and other Documentation +description: Report issues with content on a specific article, like broken links, typos, missing parts, etc. +type: Bug +labels: ['status: waiting triage'] +body: + - type: markdown + attributes: + value: 'NOTE: If you want to become an author on freeCodeCamp, you can find everything here: https://www.freecodecamp.org/news/developer-news-style-guide' + - type: markdown + attributes: + value: If you are reporting an issue with an article on our news publication, please follow this link to send an email to our editorial team https://mailxto.com/lkj5n7 + - type: textarea + attributes: + label: Describe the Issue + description: A clear and concise description of the issue you encountered. + validations: + required: true + - type: input + attributes: + label: Affected Page + description: Add a link to the article or documentation page with the problem. + validations: + required: true + - type: textarea + attributes: + label: Steps to Reproduce + description: Please describe the problem and provide the steps to reproduce the issue. + validations: + required: true + - type: textarea + attributes: + label: Recommended fix or suggestions + description: A clear and concise description of how you want to update it. + validations: + required: true + - type: textarea + attributes: + label: Screenshots + description: If applicable, add screenshots to help explain your problem. You can drag and drop `png`, `jpg`, `gif`, etc. in this box. + validations: + required: false diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/04--feature-request-for-freecodecamp-org-s-platforms.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/04--feature-request-for-freecodecamp-org-s-platforms.yml new file mode 100644 index 0000000000000000000000000000000000000000..713335678686e09998e30d84632cf4d913c9bc26 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/04--feature-request-for-freecodecamp-org-s-platforms.yml @@ -0,0 +1,29 @@ +name: New Feature - Request a new feature for our Platforms +description: Suggest an idea for freeCodeCamp.org's /learn, /news, Community Forum, Code Radio, or other platforms. +type: Enhancement +labels: ['status: waiting triage'] +body: + - type: textarea + attributes: + label: Is your feature request related to a problem? Please describe. + description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + validations: + required: true + - type: textarea + attributes: + label: Describe the solution you'd like + description: A clear and concise description of what you want to happen. + validations: + required: true + - type: textarea + attributes: + label: Describe alternatives you've considered + description: A clear and concise description of any alternative solutions or features you've considered. + validations: + required: true + - type: textarea + attributes: + label: Additional context + description: Add any other context or screenshots about the feature request here. + validations: + required: false diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/config.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..54f6815e20dd697a0637b4a850aa4da4e31fb808 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: true +contact_links: + - name: Request programming help with coding challenges + url: https://forum.freecodecamp.org + about: Please visit this page for general support and programming help on coding challenges. + - name: Report issues with content on /news articles + url: https://mailxto.com/lkj5n7 + about: Please fill out an email to our editorial team to report issues on specific articles on our technical publication (link opens an email template) + - name: Request technical support for your freeCodeCamp account + url: https://www.freecodecamp.org/support + about: Please visit this page for requesting technical support related to your freeCodeCamp account. diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/PULL_REQUEST_TEMPLATE.md b/github_code/freeCodeCamp__freeCodeCamp/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..bec5ec98051a3d4a606aef867928939c4b120ab5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +Checklist: + + + +- [ ] I have read and followed the [contribution guidelines](https://contribute.freecodecamp.org). +- [ ] I have read and followed the [how to open a pull request guide](https://contribute.freecodecamp.org/how-to-open-a-pull-request/). +- [ ] My pull request targets the `main` branch of freeCodeCamp. +- [ ] I have tested these changes either locally on my machine, or GitHub Codespaces. + + + +Closes #XXXXX + + diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/actions/setup-turbo-cache/action.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/actions/setup-turbo-cache/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..35d712a6d5c14881fa2bc79bbfd74bace0a10d72 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/actions/setup-turbo-cache/action.yml @@ -0,0 +1,75 @@ +# Caching Behaviour: +# ┌─────────────────────────┬─────────────────┬──────────────────┐ +# │ Context │ Can Read Cache? │ Can Write Cache? │ +# ├─────────────────────────┼─────────────────┼──────────────────┤ +# │ main (push) │ YES │ YES │ +# ├─────────────────────────┼─────────────────┼──────────────────┤ +# │ PRs / temp-* / hotfix-* │ YES │ NO │ +# ├─────────────────────────┼─────────────────┼──────────────────┤ +# │ prod-* │ NO │ NO │ +# ├─────────────────────────┼─────────────────┼──────────────────┤ +# │ Fork PRs │ NO │ NO │ +# └─────────────────────────┴─────────────────┴──────────────────┘ + +name: 'Setup Turbo Remote Cache' +description: 'Conditionally configure Turbo remote cache based on branch and event context' + +inputs: + turbo-token: + description: 'Turbo remote cache authentication token' + required: true + turbo-signature-key: + description: 'Turbo remote cache signature key for artifact signing/verification' + required: true + +runs: + using: 'composite' + steps: + - name: Configure Turbo Remote Cache + shell: bash + env: + TURBO_TOKEN: ${{ inputs.turbo-token }} + TURBO_SIGNATURE_KEY: ${{ inputs.turbo-signature-key }} + GITHUB_REF_NAME: ${{ github.ref_name }} + GITHUB_EVENT_NAME: ${{ github.event_name }} + GITHUB_BASE_REF: ${{ github.base_ref }} + run: | + echo "::group::Turbo Cache Configuration" + echo "Branch: $GITHUB_REF_NAME" + echo "Event: $GITHUB_EVENT_NAME" + echo "Base ref: $GITHUB_BASE_REF" + + # Skip for deployment branches (pure builds) + if [[ "$GITHUB_REF_NAME" == prod-* ]]; then + echo "::notice::Deployment branch detected - Turbo cache DISABLED for pure build" + echo "::endgroup::" + exit 0 + fi + + # Skip if secrets are not available (fork PRs) + if [[ -z "$TURBO_TOKEN" || -z "$TURBO_SIGNATURE_KEY" ]]; then + echo "::notice::Turbo secrets not available (likely a fork PR) - Turbo cache DISABLED" + echo "::endgroup::" + exit 0 + fi + + # Base configuration for all other contexts + echo "TURBO_API=https://turbo-cache.freecodecamp.net" >> $GITHUB_ENV + echo "TURBO_TEAM=team_freecodecamp" >> $GITHUB_ENV + echo "TURBO_TOKEN=$TURBO_TOKEN" >> $GITHUB_ENV + echo "TURBO_REMOTE_CACHE_SIGNATURE_KEY=$TURBO_SIGNATURE_KEY" >> $GITHUB_ENV + echo "TURBO_TELEMETRY_DISABLED=1" >> $GITHUB_ENV + + # Determine if this context should have write access + # Write access: main branch push + # Read-only: PRs and other branches (can read from cache, can't pollute it) + if [[ "$GITHUB_REF_NAME" == "main" && "$GITHUB_EVENT_NAME" == "push" ]]; then + echo "::notice::Main branch push - Turbo cache READ/WRITE enabled" + else + # All other contexts: read-only + # Use TURBO_CACHE=remote:r for read-only remote cache (local still read/write) + echo "TURBO_CACHE=local:rw,remote:r" >> $GITHUB_ENV + echo "::notice::PR/other branch - Turbo cache READ-ONLY enabled" + fi + + echo "::endgroup::" diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/copilot-instructions.md b/github_code/freeCodeCamp__freeCodeCamp/.github/copilot-instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..f84c24bbf31dca1c580ad10a0f39ea2d41d0377b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/copilot-instructions.md @@ -0,0 +1,186 @@ +# GitHub Copilot Code Review Instructions + +## Core Principles + +**BE EXTREMELY MINIMAL.** Only provide actionable feedback. + +**Skip all non-essential content:** +- Do not generate "Pull request overview" sections +- Do not create "Changes:" lists describing what was changed +- Do not create "Reviewed changes" sections or tables +- Do not list files with change descriptions +- Do not count how many files were reviewed +- Do not summarize what the PR does (visible in the diff) + +**Focus only on problems:** +- Comment ONLY on actual issues that need fixing +- Keep each comment 1-3 sentences +- If everything is correct, provide no output + +**Bad example (from PR 65578):** +``` +## Pull request overview +This PR addresses issue 65331 by replacing em dash characters... + +### Reviewed changes +Copilot reviewed 4 out of 4 changed files... + +| File | Description | +| ---- | ----------- | +| file1.md | Updated em dash in seed content | +``` + +**Good example (actionable feedback only):** +``` +Line 46: Test will fail - `innerText` returns rendered `—`, not `—`. +``` + +--- + +## Focus Areas + +1. **Test Coverage** - Ensuring adequate testing for code changes +2. **Pull Request Guidelines** - Compliance with contribution standards + +--- + +## Focus Area 1: Test Coverage + +When reviewing pull requests, ensure adequate test coverage for code changes in JavaScript, TypeScript, JSX, and TSX files. + +> Detailed test coverage rules are in `.github/instructions/testing.instructions.md` + +### Quick Reference + +| Location | Framework | File Pattern | +|----------|-----------|--------------| +| `api/` | Vitest | `*.test.ts` | +| `client/` | Vitest | `*.test.{ts,tsx}` | +| `e2e/` | Playwright | `*.spec.ts` | + +### When to Comment + +Only leave a comment if: + +- The PR modifies JavaScript/TypeScript/JSX/TSX code (bug fixes or new features) +- AND there are no corresponding test additions or updates + +### When NOT to Comment + +Do not comment if: + +- Changes are only to documentation, configuration, or non-JS/TS files +- The PR includes appropriate test coverage for the changes +- Changes are test-only modifications + +### Comment Style + +If tests are missing, provide ONE brief comment: + +``` +Missing tests for [specific file]. Consider: +- [specific scenario] +- [edge case] +``` + +If test coverage is sufficient, **DO NOT COMMENT**. No "LGTM" needed. + +--- + +## Focus Area 2: Pull Request Guidelines + +When reviewing pull requests, verify compliance with [freeCodeCamp's contribution standards](https://contribute.freecodecamp.org/how-to-open-a-pull-request). + +### PR Title Format + +Check that the title follows conventional commits format: +`([optional scope]): ` + +**Valid types:** `fix`, `feat`, `refactor`, `docs`, `test` + +**Common scopes:** `curriculum`, `client`, `api`, `i18n`, `a11y`, `tools` + +Flag if: + +- Title is vague (e.g., "Update file", "Fix bug", "Changes") +- Missing type prefix +- Description exceeds ~50 characters +- Type doesn't match the actual changes + +Example of good title: + +``` +fix(client): resolve login button alignment on mobile +``` + +Example of bad title: + +``` +Fixed stuff +``` + +### PR Description & Issue Linking + +Check for: + +- Meaningful description explaining what changes were made and why +- Proper issue linking using `Closes #XXXXX` format (not just `#XXXXX`) +- Screenshots included for UI/visual changes + +Flag if: + +- Description is empty or only contains template boilerplate +- Issue reference uses incorrect format (e.g., `fixes XXXXX` without `#`) +- UI changes lack screenshots + +### Checklist Completion + +Verify the PR template checklist items are completed: + +- Boxes should be checked (`[x]`) not left unchecked (`[ ]`) +- Placeholder text like `#XXXXX` should be replaced with actual issue numbers + +Flag if: + +- Checklist boxes are left unchecked +- Placeholder issue number `#XXXXX` remains unchanged + +### Comment Style + +Keep feedback minimal (one line when possible): + +``` +Update PR title to format: `(scope): description` +See: https://contribute.freecodecamp.org/how-to-open-a-pull-request +``` + +``` +Link issue using: `Closes #XXXXX` +``` + +If PR guidelines are followed, **DO NOT COMMENT**. No "LGTM" needed. + +--- + +## General Guidelines + +**Focus on Actionable Issues Only** + +### Strict Rules + +- NO summaries, overviews, or descriptions of changes +- NO tables or file listings +- NO "LGTM" or affirmative comments when everything is fine +- Only comment when action is required +- Keep each comment brief and actionable + +### Prioritization + +When multiple issues exist, address them in order of severity: + +1. Security vulnerabilities or critical bugs +2. Missing test coverage for new functionality +3. Outdated tests for modified functionality +4. PR title/description compliance + +Comment on all legitimate issues, but keep each comment concise. diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/instructions/testing.instructions.md b/github_code/freeCodeCamp__freeCodeCamp/.github/instructions/testing.instructions.md new file mode 100644 index 0000000000000000000000000000000000000000..45515b2723c1f6b5c418fa72e1b38b793af03b7c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/instructions/testing.instructions.md @@ -0,0 +1,98 @@ +--- +applyTo: "**/*.{ts,tsx,js,jsx}" +--- + +# Test Coverage Review Instructions + +Review code changes for adequate test coverage using freeCodeCamp's testing conventions. + +## Testing Framework Reference + +| Location | Framework | File Pattern | Notes | +|----------|-----------|--------------|-------| +| `api/` | Vitest | `*.test.ts` | Co-located with source | +| `client/` | Vitest | `*.test.{ts,tsx}` | Co-located with source | +| `e2e/` | Playwright | `*.spec.ts` | Dedicated directory | + +## When to Flag Missing Tests + +Comment on missing tests if ALL of these are true: + +- PR modifies functional code (bug fix or new feature) +- No corresponding test additions or modifications exist +- Changes are not test-only or config-only + +### Examples Requiring Tests + +- New utility functions in `api/src/utils/` or `client/src/utils/` +- New API route handlers in `api/src/routes/` +- New React components with logic in `client/src/components/` +- Bug fixes that change application behavior +- New validation logic or data transformations + +## When NOT to Flag + +Do not comment on test coverage if: + +- Changes are documentation, configuration, or non-functional +- PR already includes appropriate test coverage +- Changes are to test files themselves +- Changes are trivial: + - Import reorganization + - Formatting changes + - Type-only changes (interfaces, type definitions) + - Comment updates +- Changes are in areas without existing test patterns: + - Curriculum markdown files + - Configuration files + - Build scripts + +## Detecting Outdated Tests + +Flag if existing tests may be outdated: + +- Test file exists for modified source but doesn't cover the changed functionality +- Test assertions reference behavior that is being changed +- Mock data doesn't reflect new data structures or API responses +- Test descriptions no longer match actual test behavior + +### Example Comment for Outdated Tests + +``` +Tests in `src/utils/validate.test.ts` need updates for new validation rules. +``` + +## Comment Format + +### Missing Tests + +Brief, actionable feedback only: + +``` +Missing tests for `src/utils/validate.ts`: +- Valid input case +- Invalid input error +- Empty string edge case +``` + +### Sufficient Coverage + +**DO NOT COMMENT.** Silence means approval. + +### Outdated Tests + +``` +Tests in `[test file]` need updates for `[source file]` changes: +- [specific change] +``` + +## Test Quality Indicators + +When tests are present, briefly verify: + +- Tests cover the happy path +- Tests cover at least one error/edge case +- Test descriptions are meaningful (not just "test 1", "test 2") +- Mocks are appropriate (not mocking the thing being tested) + +Do not block PRs for test style preferences if coverage is adequate. diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/labeler.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/labeler.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c83e1b6231273c656189c9fc43287fb69bdd4da --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/labeler.yml @@ -0,0 +1,26 @@ +'scope: curriculum': + - changed-files: + - any-glob-to-any-file: curriculum/challenges/**/* + +'platform: learn': + - changed-files: + - any-glob-to-any-file: client/**/* + +'platform: api': + - changed-files: + - any-glob-to-any-file: api/**/* + +'scope: tools/scripts': + - changed-files: + - any-glob-to-any-file: + - tools/**/* + - .github/**/* + - utils/**/* + - e2e/**/* + +'scope: i18n': + - changed-files: + - any-glob-to-any-file: + - client/i18n/**/* + - config/crowdin/**/* + - shared/config/i18n/**/* diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-allow-list.js b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-allow-list.js new file mode 100644 index 0000000000000000000000000000000000000000..6005f121763a0cd0e43a6a44b5d88ff6f05b94de --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-allow-list.js @@ -0,0 +1,24 @@ +'use strict'; + +module.exports = async ({ github, context, core }) => { + const prAuthor = context.payload.pull_request.user.login; + + const teamSlugs = ['dev-team', 'curriculum', 'staff', 'moderators']; + const membershipChecks = teamSlugs.map(team_slug => + github.rest.teams + .getMembershipForUserInOrg({ + org: 'freeCodeCamp', + team_slug, + username: prAuthor + }) + .then(({ data }) => data.state === 'active') + .catch(() => false) + ); + const results = await Promise.all(membershipChecks); + const isOrgTeamMember = results.some(Boolean); + + const isAllowListed = + isOrgTeamMember || ['camperbot', 'renovate[bot]'].includes(prAuthor); + + core.setOutput('is_allow_listed', isAllowListed); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-pr-template.js b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-pr-template.js new file mode 100644 index 0000000000000000000000000000000000000000..1637f5159b8c72fa2352afb24a70f7e48359ee32 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/check-pr-template.js @@ -0,0 +1,39 @@ +'use strict'; + +module.exports = async ({ github, context, core, isAllowListed }) => { + if (isAllowListed === 'true') return; + + const body = (context.payload.pull_request.body || '').toLowerCase(); + + // The template must be present and the first 3 checkboxes must be + // ticked. The last checkbox (tested locally) is acceptable to leave + // unticked. + const templatePresent = body.includes('checklist:'); + const requiredTicked = [ + 'i have read and followed the contribution guidelines', + 'i have read and followed the how to open a pull request guide', + 'my pull request targets the' + ]; + // Strip markdown links ([text](url) → text) before matching so contributors + // who omit the link syntax (e.g. type plain text) still pass the check. + const normalizedBody = body + .replace(/\[\s*x\s*\]/g, '[x]') + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1'); + const allRequiredTicked = requiredTicked.every(item => + normalizedBody.includes(`[x] ${item}`) + ); + + if (templatePresent && allRequiredTicked) return; + + core.setOutput('failure_reason', 'incomplete_checklist'); + core.setFailed( + 'PR description is missing the required checklist or some items are incomplete.' + ); + + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.payload.pull_request.number, + labels: ['deprioritized'] + }); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/fix-pr-title.js b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/fix-pr-title.js new file mode 100644 index 0000000000000000000000000000000000000000..08f00c96d28a35aca53397ddb004898ca8d9091c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/fix-pr-title.js @@ -0,0 +1,79 @@ +'use strict'; + +// Returns the minimum number of single-character edits (insert, delete, substitute) +// needed to turn string `a` into string `b`. +function levenshtein(a, b) { + const dp = Array.from({ length: a.length + 1 }, (_, i) => + Array.from({ length: b.length + 1 }, (_, j) => + i === 0 ? j : j === 0 ? i : 0 + ) + ); + for (let i = 1; i <= a.length; i++) { + for (let j = 1; j <= b.length; j++) { + dp[i][j] = + a[i - 1] === b[j - 1] + ? dp[i - 1][j - 1] + : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]); + } + } + return dp[a.length][b.length]; +} + +module.exports = async ({ github, context }) => { + const title = context.payload.pull_request.title; + const ccRegex = + /^(feat|fix|refactor|docs|chore|build|ci|test|perf|revert)(\([^)]+\))?: .+/; + + if (ccRegex.test(title)) return; + + const types = [ + 'feat', + 'fix', + 'refactor', + 'docs', + 'chore', + 'build', + 'ci', + 'test', + 'perf', + 'revert' + ]; + + let newTitle = title; + + // Fix 1: space between type and scope — "feat (scope):" → "feat(scope):" + newTitle = newTitle.replace(/^(\w+)\s+(\([^)]+\):)/, '$1$2'); + + // Fix 2: missing colon after scope — "feat(scope) desc" → "feat(scope): desc" + newTitle = newTitle.replace(/^(\w+\([^)]+\)) ([^:])/, '$1: $2'); + + // Fix 3: typo in type — "refator(scope):" → "refactor(scope):" (distance ≤ 2) + const typoMatch = newTitle.match(/^(\w+)(\([^)]+\))?:/); + if (typoMatch) { + const candidate = typoMatch[1]; + if (!types.includes(candidate)) { + const closest = types + .map(t => ({ t, d: levenshtein(candidate, t) })) + .filter(x => x.d <= 2) + .sort((a, b) => a.d - b.d)[0]; + if (closest) newTitle = newTitle.replace(candidate, closest.t); + } + } + + // Fix 4: missing space after colon — "fix:desc" → "fix: desc" + newTitle = newTitle.replace(/^(\w+(?:\([^)]+\))?):(\S)/, '$1: $2'); + + // Catch-all: prefix with "fix: " if still not a valid CC title + if (!ccRegex.test(newTitle)) { + newTitle = `fix: ${newTitle}`; + } + + if (newTitle !== title) { + await github.rest.pulls.update({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.payload.pull_request.number, + title: newTitle + }); + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/report-results.js b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/report-results.js new file mode 100644 index 0000000000000000000000000000000000000000..c4fc82ef82a4d1dd0fc003d6b9c77b974260ce21 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/scripts/pr-guidelines/report-results.js @@ -0,0 +1,83 @@ +'use strict'; + +const FOOTER = + '\n\n---\nJoin us in our [chat room](https://discord.gg/PRyKn3Vbay) or our [forum](https://forum.freecodecamp.org/c/contributors/3) if you have any questions or need help with contributing.'; + +const TEMPLATE_BLOCK = [ + '```md', + 'Checklist:', + '', + '', + '', + '- [ ] I have read and followed the [contribution guidelines](https://contribute.freecodecamp.org).', + '- [ ] I have read and followed the [how to open a pull request guide](https://contribute.freecodecamp.org/how-to-open-a-pull-request/).', + "- [ ] My pull request targets the `main` branch of freeCodeCamp.", + '- [ ] I have tested these changes either locally on my machine, or GitHub Codespaces.', + '', + '', + '', + 'Closes #XXXXX', + '', + '', + '```' +].join('\n'); + +const MESSAGES = { + incomplete_checklist: [ + '**Checklist:** The PR description is missing the required checklist or some of its items are not completed:', + '', + '1. The `Checklist:` heading is present in the PR description.', + '2. The checkbox items are ticked (changed from `[ ]` to `[x]`).', + '3. You have actually completed the items in the checklist.', + '', + 'Please edit your PR description to include the following template with the checklist items completed.', + '', + TEMPLATE_BLOCK + ].join('\n') +}; + +module.exports = async ({ github, context, templateResult, templateReason }) => { + const allPassed = templateResult === 'success'; + + if (allPassed) { + try { + await github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + name: 'deprioritized' + }); + } catch { + // Label may not exist — ignore. + } + return; + } + + // On edit, don't re-comment — the original comment is already there. + if (context.payload.action === 'edited') return; + + const sections = []; + if (templateResult === 'failure' && MESSAGES[templateReason]) { + sections.push(MESSAGES[templateReason]); + } + + if (sections.length === 0) return; + + const body = + [ + 'Hi there,', + '', + 'Thanks for opening this pull request.', + '', + 'The automated checks found some issues:', + '', + sections.join('\n\n') + ].join('\n') + FOOTER; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body + }); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-download.client-ui.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-download.client-ui.yml new file mode 100644 index 0000000000000000000000000000000000000000..a32c34ab01c9e721869d9bdb71ae6bba72d28499 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-download.client-ui.yml @@ -0,0 +1,342 @@ +name: i18n - Download Client UI +on: + workflow_dispatch: + schedule: + # runs Monday and Wednesday at 12:15 PM UTC + - cron: '15 12 * * 1,3' + +env: + GITHUB_TOKEN: ${{ secrets.CROWDIN_CAMPERBOT_PAT }} + CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_CAMPERBOT_SERVICE_TOKEN }} + CROWDIN_API_URL: 'https://freecodecamp.crowdin.com/api/v2/' + CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID_CLIENT }} + +permissions: + contents: read + +jobs: + i18n-download-client-ui-translations: + name: Client + runs-on: ubuntu-24.04 + + steps: + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + token: ${{ secrets.CROWDIN_CAMPERBOT_PAT }} + + - name: Generate Crowdin Config + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'generate-config' + PROJECT_NAME: 'client' + + ##### Download Chinese ##### + - name: Crowdin Download Chinese Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: zh-CN + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + # Convert Simplified Chinese to Traditional # + - name: Convert Chinese + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'convert-chinese' + FILE_PATHS: '["client/i18n/locales/chinese"]' + + ##### Download Espanol ##### + - name: Crowdin Download Espanol Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: es-EM + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Italian ##### + - name: Crowdin Download Italian Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: it + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Brazilian Portuguese ##### + - name: Crowdin Download Portuguese (Brazilian) Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: pt-BR + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Ukrainian ##### + - name: Crowdin Download Ukrainian Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: uk + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Japanese ##### + - name: Crowdin Download Japanese Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: ja + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download German ##### + - name: Crowdin Download German Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: de + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Swahili ##### + - name: Crowdin Download Swahili Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: sw + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ##### Download Korean ##### + - name: Crowdin Download Korean Translations + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: false + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: true + download_language: ko + skip_untranslated_files: false + export_only_approved: true + + push_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + ###### Format JSON ##### + # Crowdin gives the files read-only permissions, so we first have to allow + # writes. + - name: Format JSON + run: | + sudo chown -R $(whoami): client/i18n/locales + npx --yes prettier --write client/i18n/locales/**/*.json + + ###### Lowercase directory names ##### + + - name: Lowercase Directories + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'lowercase-directories' + FILE_PATH: 'client/i18n/locales' + # Crowdin translators might have the directories + # Create Commit + - name: Commit Changes + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'commit-changes' + GH_USERNAME: 'camperbot' + GH_EMAIL: ${{ secrets.ACTIONS_CAMPERBOT_EMAIL }} + GH_BRANCH: 'i18n-sync-client' + GH_MESSAGE: 'chore(i18n,client): processed translations' + + # Generate PR # + # All languages should go ABOVE this. # + + - name: Create PR + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'pull-request' + GH_TOKEN: ${{ secrets.CROWDIN_CAMPERBOT_PAT }} + BRANCH: 'i18n-sync-client' + REPOSITORY: 'freecodecamp/freecodecamp' + BASE: 'main' + TITLE: 'chore(i18n,client): processed translations' + BODY: 'This PR was opened auto-magically by Crowdin.' + LABELS: 'crowdin-sync' + TEAM_REVIEWERS: 'i18n' diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.client-ui.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.client-ui.yml new file mode 100644 index 0000000000000000000000000000000000000000..958322d31af61edeba941b730c8f97953b923dd9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.client-ui.yml @@ -0,0 +1,55 @@ +name: i18n - Upload Client UI +on: + workflow_dispatch: + schedule: + # runs every weekday at 7:15 AM UTC + - cron: '15 7 * * 1-5' + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_CAMPERBOT_SERVICE_TOKEN }} + CROWDIN_API_URL: 'https://freecodecamp.crowdin.com/api/v2/' + CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID_ClIENT }} + +permissions: + contents: read + +jobs: + i18n-upload-client-ui-files: + name: Client + runs-on: ubuntu-24.04 + + steps: + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + + - name: Generate Crowdin Config + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'generate-config' + PROJECT_NAME: 'client' + + - name: Crowdin Upload + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: true + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.curriculum.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.curriculum.yml new file mode 100644 index 0000000000000000000000000000000000000000..af6d3df23184a749d83afbe3ec31394081aa0600 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/crowdin-upload.curriculum.yml @@ -0,0 +1,80 @@ +name: i18n - Upload Curriculum +on: + workflow_dispatch: + schedule: + # runs every weekday at 7:30 AM UTC + - cron: '30 7 * * 1-5' + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CROWDIN_PERSONAL_TOKEN: ${{ secrets.CROWDIN_CAMPERBOT_SERVICE_TOKEN }} + CROWDIN_API_URL: 'https://freecodecamp.crowdin.com/api/v2/' + CROWDIN_PROJECT_ID: ${{ secrets.CROWDIN_PROJECT_ID_CURRICULUM }} + +permissions: + contents: read + +jobs: + i18n-upload-curriculum-files: + name: Learn + runs-on: ubuntu-24.04 + + steps: + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false + + - name: Generate Crowdin Config + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'generate-config' + PROJECT_NAME: 'curriculum' + + - name: Crowdin Upload + uses: crowdin/github-action@c7af9bc98b01694653031fef2a0dc6c7888ce9bc # v2.17.0 + # options: https://github.com/crowdin/github-action/blob/master/action.yml + with: + # uploads + upload_sources: true + upload_translations: false + auto_approve_imported: false + import_eq_suggestions: false + + # downloads + download_translations: false + + # pull-request + create_pull_request: false + + # global options + config: './crowdin-config.yml' + base_url: ${{ secrets.CROWDIN_BASE_URL_FCC }} + + # Uncomment below to debug + # dryrun_action: true + + - name: Remove deleted files + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'remove-deleted-files' + FILE_PATHS: '["curriculum/challenges/english", "curriculum/dictionaries/english"]' + + - name: Hide Non-Translated Strings + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'hide-curriculum-strings' + + - name: Hide a String + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'hide-string' + FILE_NAME: 'basic-html-and-html5/nest-an-anchor-element-within-a-paragraph.md' + STRING_CONTENT: Here's a link to www.freecodecamp.org for you to follow. + + - name: Unhide Title of Use && For a More Concise Conditional + uses: freecodecamp/crowdin-action@36a78cbf92f5a6c05a3a32dc8bf434a19a7c59e2 # main + env: + PLUGIN: 'unhide-string' + FILE_NAME: 'react/use--for-a-more-concise-conditional.md' + STRING_CONTENT: 'Use && for a More Concise Conditional' diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/curriculum-i18n-submodule.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/curriculum-i18n-submodule.yml new file mode 100644 index 0000000000000000000000000000000000000000..a2f05cfc52db60eabc616090200f6153ed602d3a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/curriculum-i18n-submodule.yml @@ -0,0 +1,78 @@ +name: CI - Node.js - i18n - Submodule + +on: + # Run on push events, but only for the below branches + push: + branches: + - 'chore/update-i18n-curriculum-submodule' + workflow_dispatch: + +permissions: + contents: read + +jobs: + test-curriculum: + name: Test Curriculum + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + node-version: [24] + # Exclude the languages that we currently run in the full CI suite. + locale: + - 'chinese' + - 'espanol' + - 'ukrainian' + - 'japanese' + - 'german' + - 'swahili' + - 'korean' + - 'arabic' + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set Environment variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + + - name: Install node_modules + run: pnpm install + + # DONT REMOVE THIS STEP. + # TODO: Refactor and use re-usable workflow and shared artifacts + - name: Build Client in ${{ matrix.locale }} + env: + CURRICULUM_LOCALE: ${{ matrix.locale }} + CLIENT_LOCALE: ${{ matrix.locale }} + run: | + pnpm run build + + - name: Install Chrome for Puppeteer + run: pnpm -F=curriculum install-puppeteer + + - name: Run Tests + env: + CURRICULUM_LOCALE: ${{ matrix.locale }} + CLIENT_LOCALE: ${{ matrix.locale }} + run: pnpm -F=curriculum test-content diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-api.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-api.yml new file mode 100644 index 0000000000000000000000000000000000000000..8449fdb9f06c4d0e139f7d2586be5cc5e54a2d7b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-api.yml @@ -0,0 +1,353 @@ +name: CD - Deploy - API + +on: + workflow_dispatch: + inputs: + api_log_lvl: + description: 'Log level for the API' + type: choice + options: + - debug + - info + - warn + default: debug + show_upcoming_changes: + description: 'Show upcoming changes (enables upcoming certifications and challenges)' + type: boolean + default: false + dump_stack_config: + description: 'Dump the docker stack config' + type: boolean + default: false + +concurrency: + group: deploy-api-${{ github.ref_name }} + cancel-in-progress: false + +jobs: + setup-jobs: + name: Setup Jobs + runs-on: ubuntu-24.04 + outputs: + site_tld: ${{ steps.setup.outputs.site_tld }} + tgt_env_short: ${{ steps.setup.outputs.tgt_env_short }} + tgt_env_long: ${{ steps.setup.outputs.tgt_env_long }} + api_log_lvl: ${{ steps.setup.outputs.api_log_lvl }} + show_upcoming_changes: ${{ steps.setup.outputs.show_upcoming_changes }} + dump_stack_config: ${{ steps.setup.outputs.dump_stack_config }} + steps: + - name: Setup + id: setup + env: + BRANCH: ${{ github.ref_name }} + SHOW_UPCOMING_CHANGES: ${{ inputs.show_upcoming_changes }} + API_LOG_LVL: ${{ inputs.api_log_lvl || 'debug' }} + DUMP_STACK_CONFIG: ${{ inputs.dump_stack_config }} + run: | + echo "Current branch: $BRANCH" + + # Convert boolean input to string 'true' or 'false' + if [[ "$SHOW_UPCOMING_CHANGES" == "true" ]]; then + echo "show_upcoming_changes=true" >> "$GITHUB_OUTPUT" + else + echo "show_upcoming_changes=false" >> "$GITHUB_OUTPUT" + fi + + # Convert boolean input to string 'true' or 'false' + if [[ "$DUMP_STACK_CONFIG" == "true" ]]; then + echo "dump_stack_config=true" >> "$GITHUB_OUTPUT" + else + echo "dump_stack_config=false" >> "$GITHUB_OUTPUT" + fi + + case "$BRANCH" in + "prod-current") + echo "site_tld=org" >> "$GITHUB_OUTPUT" + echo "tgt_env_short=prd" >> "$GITHUB_OUTPUT" + echo "tgt_env_long=production" >> "$GITHUB_OUTPUT" + echo "api_log_lvl=$API_LOG_LVL" >> "$GITHUB_OUTPUT" + ;; + *) + echo "site_tld=dev" >> "$GITHUB_OUTPUT" + echo "tgt_env_short=stg" >> "$GITHUB_OUTPUT" + echo "tgt_env_long=staging" >> "$GITHUB_OUTPUT" + echo "api_log_lvl=$API_LOG_LVL" >> "$GITHUB_OUTPUT" + ;; + esac + + build: + name: Build & Push + needs: setup-jobs + uses: ./.github/workflows/docker-docr.yml + with: + site_tld: ${{ needs.setup-jobs.outputs.site_tld }} + app: api + show_upcoming_changes: ${{ needs.setup-jobs.outputs.show_upcoming_changes }} + secrets: + DIGITALOCEAN_ACCESS_TOKEN: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} + DOCR_NAME: ${{ secrets.DOCR_NAME }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + + deploy: + name: Deploy to Docker Swarm -- ${{ needs.setup-jobs.outputs.tgt_env_short }} + runs-on: ubuntu-24.04 + needs: [setup-jobs, build] + env: + TS_USERNAME: ${{ secrets.TS_USERNAME }} + TS_MACHINE_NAME: ${{ secrets.TS_MACHINE_NAME }} + permissions: + deployments: write + environment: + name: ${{ needs.setup-jobs.outputs.tgt_env_short }}-api + + steps: + - name: Setup and connect to Tailscale network + uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4 + with: + oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }} + oauth-secret: ${{ secrets.TS_OAUTH_SECRET }} + hostname: gha-${{needs.setup-jobs.outputs.tgt_env_short}}-api-ci-${{ github.run_id }} + tags: tag:ci + version: latest + + - name: Wait for Tailscale Network Readiness + run: | + echo "Waiting for Tailscale network to be ready..." + max_wait=60 + elapsed=0 + + while [ $elapsed -lt $max_wait ]; do + if tailscale status --json | jq -e '.BackendState == "Running"' > /dev/null 2>&1; then + echo "Tailscale network is ready" + break + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + + if [ $elapsed -ge $max_wait ]; then + echo "Tailscale network not ready after ${max_wait}s" + exit 1 + fi + + - name: Configure SSH & Check Connection + run: | + mkdir -p ~/.ssh + echo "Host * + UserKnownHostsFile=/dev/null + StrictHostKeyChecking no" > ~/.ssh/config + chmod 644 ~/.ssh/config + + scrub_ips() { + sed -E 's/100(\.[0-9]{1,3}){3}/100.x.x.x/g' + } + + validate_connection() { + local machine_name=$1 + local max_retries=3 + local retry_delay=5 + local ping_output ssh_output + + for attempt in $(seq 1 $max_retries); do + echo "Connection attempt $attempt/$max_retries to $machine_name" + + if ! ping_output=$(tailscale ping -c 1 --until-direct=false --timeout=5s "$machine_name" 2>&1); then + ping_output=$(printf '%s' "$ping_output" | scrub_ips) + echo "No Tailscale data path to $machine_name: $ping_output" + if [ "$attempt" -eq "$max_retries" ]; then + return 1 + fi + sleep "$retry_delay" + continue + fi + + MACHINE_IP=$(tailscale ip -4 "$machine_name") + if ssh_output=$(ssh -o ConnectTimeout=10 -o BatchMode=yes "$TS_USERNAME@$MACHINE_IP" "echo 'Connection test'; docker --version" 2>&1); then + echo "Successfully validated connection to $machine_name" + return 0 + fi + + ssh_output=$(printf '%s' "$ssh_output" | scrub_ips) + echo "SSH validation failed for $machine_name: $ssh_output" + if [ "$attempt" -lt "$max_retries" ]; then + sleep "$retry_delay" + fi + done + + echo "Failed to establish connection to $machine_name after $max_retries attempts" + return 1 + } + + echo -e "\nLOG:Validating connection to $TS_MACHINE_NAME..." + if ! validate_connection "$TS_MACHINE_NAME"; then + echo "Error: Failed to establish reliable connection to $TS_MACHINE_NAME" + exit 1 + fi + + - name: Deploy with Docker Stack + env: + AGE_ENCRYPTED_ASC_SECRETS: ${{ secrets.AGE_ENCRYPTED_ASC_SECRETS }} + AGE_SECRET_KEY: ${{ secrets.AGE_SECRET_KEY }} + # Variable set from GitHub "Environment" secrets (AGE encrypted) + # DOCKER_REGISTRY + # MONGOHQ_URL + # SENTRY_DSN + # SENTRY_ENVIRONMENT + # AUTH0_CLIENT_ID + # AUTH0_CLIENT_SECRET + # AUTH0_DOMAIN + # JWT_SECRET + # COOKIE_SECRET + # COOKIE_DOMAIN + # SES_ID + # SES_SECRET + # SES_SMTP_USERNAME + # SES_SMTP_PASSWORD + # GROWTHBOOK_FASTIFY_API_HOST + # GROWTHBOOK_FASTIFY_CLIENT_KEY + # HOME_LOCATION + # API_LOCATION + # SOCRATES_API_KEY + # SOCRATES_ENDPOINT + # STRIPE_SECRET_KEY + # Variables set from SetupJob + DEPLOYMENT_VERSION: ${{ needs.build.outputs.tagname }} + DEPLOYMENT_ENV: ${{ needs.setup-jobs.outputs.tgt_env_long }} + DEPLOYMENT_TLD: ${{ needs.setup-jobs.outputs.site_tld }} + FCC_API_LOG_LEVEL: ${{ needs.setup-jobs.outputs.api_log_lvl }} + SHOW_UPCOMING_CHANGES: ${{ needs.setup-jobs.outputs.show_upcoming_changes }} + DUMP_STACK_CONFIG: ${{ needs.setup-jobs.outputs.dump_stack_config }} + # Stack name + STACK_NAME: ${{ needs.setup-jobs.outputs.tgt_env_short }}-api + run: | + REMOTE_SCRIPT=" + set -e + trap 'rm -f .env age.key secrets.age.asc .env.tmp' EXIT + echo -e '\nLOG:Deploying API to $TS_MACHINE_NAME...' + cd /home/$TS_USERNAME/docker-swarm-config/stacks/api + + echo -e '\nLOG:Checking if age is installed...' + which age > /dev/null + + echo -e '\nLOG:Decrypting secrets...' + echo \"$AGE_ENCRYPTED_ASC_SECRETS\" > secrets.age.asc + echo \"$AGE_SECRET_KEY\" > age.key && chmod 600 age.key + age --identity age.key --decrypt secrets.age.asc > .env + rm -f age.key secrets.age.asc + + echo -e '\nLOG:Cleaning up .env file...' + touch .env.tmp + while IFS= read -r line; do + if [[ \$line =~ ^[A-Za-z0-9_]+=.*$ ]]; then + # Extract the key (part before the first =) + key=\${line%%=*} + # Remove any previous line with this key + sed -i \"/^\${key}=/d\" .env.tmp + fi + # Append the current line + echo \"\$line\" >> .env.tmp + done < .env + mv .env.tmp .env + + echo -e '\nLOG:Adding deployment variables...' + { + echo \"DEPLOYMENT_VERSION=$DEPLOYMENT_VERSION\" + echo \"DEPLOYMENT_TLD=$DEPLOYMENT_TLD\" + echo \"DEPLOYMENT_ENV=$DEPLOYMENT_ENV\" + echo \"FCC_API_LOG_LEVEL=$FCC_API_LOG_LEVEL\" + echo \"SHOW_UPCOMING_CHANGES=$SHOW_UPCOMING_CHANGES\" + } >> .env + + echo -e '\nLOG:Sourcing environment...' + REQUIRED_VARS=( + \"DOCKER_REGISTRY\" + \"MONGOHQ_URL\" + \"SENTRY_DSN\" + \"SENTRY_ENVIRONMENT\" + \"AUTH0_CLIENT_ID\" + \"AUTH0_CLIENT_SECRET\" + \"AUTH0_DOMAIN\" + \"JWT_SECRET\" + \"COOKIE_SECRET\" + \"COOKIE_DOMAIN\" + \"SES_ID\" + \"SES_SECRET\" + \"SES_SMTP_USERNAME\" + \"SES_SMTP_PASSWORD\" + \"GROWTHBOOK_FASTIFY_API_HOST\" + \"GROWTHBOOK_FASTIFY_CLIENT_KEY\" + \"HOME_LOCATION\" + \"API_LOCATION\" + \"SOCRATES_API_KEY\" + \"SOCRATES_ENDPOINT\" + \"STRIPE_SECRET_KEY\" + \"DEPLOYMENT_VERSION\" + \"DEPLOYMENT_TLD\" + \"DEPLOYMENT_ENV\" + \"FCC_API_LOG_LEVEL\" + ) + + while IFS='=' read -r key value; do + if [[ -n \"\$key\" && ! \"\$key\" =~ ^# ]]; then + export \"\${key}=\${value}\" + fi + done < .env + + MISSING_VARS=() + for var in \"\${REQUIRED_VARS[@]}\"; do + if [[ -z \"\${!var}\" ]]; then + MISSING_VARS+=(\"\$var\") + fi + done + + if [[ \${#MISSING_VARS[@]} -gt 0 ]]; then + echo \"ERROR: The following required environment variables are missing or empty:\" + for var in \"\${MISSING_VARS[@]}\"; do + echo \" - \$var\" + done + exit 1 + fi + + rm -rf .env + + echo -e '\nLOG:Validating deployment version...' + if [[ \"\$DEPLOYMENT_VERSION\" != \"$DEPLOYMENT_VERSION\" ]]; then + echo \"Error: Version mismatch. Expected: $DEPLOYMENT_VERSION, Got: \$DEPLOYMENT_VERSION\" + exit 1 + fi + env | grep -E 'DEPLOYMENT_VERSION' + + echo -e '\nLOG:Checking stack configuration...' + CONFIG_OUTPUT=\"/dev/null\" + if [[ \"$DUMP_STACK_CONFIG\" == \"true\" ]]; then + CONFIG_FILENAME=\"docker-stack-config-\${DEPLOYMENT_VERSION}.yml\" + echo -e '\nLOG:Saving stack configuration for debugging...' + CONFIG_OUTPUT=\"\$CONFIG_FILENAME\" + fi + docker stack config -c stack-api.yml > \$CONFIG_OUTPUT + + echo -e '\nLOG:Deploying stack...' + docker stack deploy -c stack-api.yml --prune --with-registry-auth --detach=false $STACK_NAME + + echo -e '\nLOG:Finished deployment.' + " + MACHINE_IP=$(tailscale ip -4 "$TS_MACHINE_NAME") + # shellcheck disable=SC2029 # client-side expansion of REMOTE_SCRIPT is intended + ssh "$TS_USERNAME@$MACHINE_IP" "$REMOTE_SCRIPT" + + # TODO(o11y): Sentry release finalize disabled pending a follow-up PR with + # a stable release-id scheme (source-map upload in docker-docr.yml is + # disabled alongside). Re-enabling should also gate on a rollback-safe + # convergence check (docker service state) before finalizing, since + # `docker stack deploy --detach=false` exits 0 through a healthcheck + # rollback. See .scratchpad/o11y-cutover-review-2026-07-10.md. + # - name: Finalize Sentry release + # env: + # SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + # SENTRY_ORG: freecodecamp + # SENTRY_PROJECT: api-fastify + # RELEASE: ${{ needs.build.outputs.tagname }} + # DEPLOY_ENV: ${{ needs.setup-jobs.outputs.tgt_env_long }} + # run: | + # npx --yes @sentry/cli@3.6.0 releases finalize "$RELEASE" + # npx --yes @sentry/cli@3.6.0 releases deploys "$RELEASE" new -e "$DEPLOY_ENV" diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-client.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-client.yml new file mode 100644 index 0000000000000000000000000000000000000000..b46a79edd3f810f29f3f4b198b3f1d3b0a532fa0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/deploy-client.yml @@ -0,0 +1,393 @@ +name: CD - Deploy - Clients + +on: + workflow_dispatch: + inputs: + target_language: + description: 'Target language (or "all" for all languages)' + type: choice + options: + - all + - english + - chinese + - espanol + - chinese-traditional + - italian + - portuguese + - ukrainian + - japanese + - german + - swahili + - korean + - arabic + default: all + show_upcoming_changes: + description: 'Show upcoming changes (enables upcoming certifications and challenges)' + type: boolean + default: false + +concurrency: + group: deploy-client-${{ github.ref_name }} + cancel-in-progress: false + +jobs: + setup-jobs: + name: Setup Jobs + runs-on: ubuntu-24.04 + outputs: + site_tld: ${{ steps.setup.outputs.site_tld }} # org, dev + tgt_env_short: ${{ steps.setup.outputs.tgt_env_short }} # prd, stg + tgt_env_long: ${{ steps.setup.outputs.tgt_env_long }} # production, staging + tgt_env_branch: ${{ steps.setup.outputs.tgt_env_branch }} # prod-current, prod-staging + show_upcoming_changes: ${{ steps.setup.outputs.show_upcoming_changes }} + steps: + - name: Setup + id: setup + env: + BRANCH: ${{ github.ref_name }} + SHOW_UPCOMING_CHANGES: ${{ inputs.show_upcoming_changes }} + run: | + echo "Current branch: $BRANCH" + + # Convert boolean input to string 'true' or 'false' + if [[ "$SHOW_UPCOMING_CHANGES" == "true" ]]; then + echo "show_upcoming_changes=true" >> $GITHUB_OUTPUT + else + echo "show_upcoming_changes=false" >> $GITHUB_OUTPUT + fi + + case "$BRANCH" in + "prod-current") + echo "site_tld=org" >> $GITHUB_OUTPUT + echo "tgt_env_short=prd" >> $GITHUB_OUTPUT + echo "tgt_env_long=production" >> $GITHUB_OUTPUT + echo "tgt_env_branch=prod-current" >> $GITHUB_OUTPUT + ;; + *) + echo "site_tld=dev" >> $GITHUB_OUTPUT + echo "tgt_env_short=stg" >> $GITHUB_OUTPUT + echo "tgt_env_long=staging" >> $GITHUB_OUTPUT + echo "tgt_env_branch=prod-staging" >> $GITHUB_OUTPUT + ;; + esac + + setup-matrix: + name: Setup Matrix + runs-on: ubuntu-24.04 + needs: setup-jobs + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + - name: Setup Matrix + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + id: matrix + env: + TARGET_LANG: ${{ inputs.target_language }} + with: + script: | + // Constants + const NODE_VERSION = 24; + + // Input sanitization and validation + const rawTargetLang = process.env.TARGET_LANG || 'all'; + const targetLang = rawTargetLang.trim().toLowerCase(); + console.log(`Target language: ${targetLang}`); + + // Language mappings (single source of truth) + const languageMap = { + 'english': 'eng', + 'chinese': 'chn', + 'espanol': 'esp', + 'chinese-traditional': 'cnt', + 'italian': 'ita', + 'portuguese': 'por', + 'ukrainian': 'ukr', + 'japanese': 'jpn', + 'german': 'ger', + 'swahili': 'swa', + 'korean': 'kor', + 'arabic': 'ara' + }; + + const allLanguages = Object.keys(languageMap); + let matrix; + + if (targetLang === 'all') { + console.log('Building matrix for all languages'); + console.log(`Available languages: ${allLanguages.join(', ')}`); + + // Build include array for all languages + const include = allLanguages.map(lang => ({ + 'node-version': NODE_VERSION, + 'lang-name-full': lang, + 'lang-name-short': languageMap[lang] + })); + + matrix = { + include: include + }; + + } else { + console.log(`Building matrix for single language: ${targetLang}`); + + // Validate language selection + if (!languageMap[targetLang]) { + const errorMsg = `Unknown language '${targetLang}'. Available: ${allLanguages.join(', ')}`; + console.error(errorMsg); + core.setFailed(errorMsg); + return; + } + + console.log(`Processing: ${targetLang} -> ${languageMap[targetLang]}`); + + // Create single language matrix + matrix = { + include: [{ + 'node-version': NODE_VERSION, + 'lang-name-full': targetLang, + 'lang-name-short': languageMap[targetLang] + }] + }; + } + + // Final validation + if (!matrix || !matrix.include || matrix.include.length === 0) { + core.setFailed('Generated matrix is empty or invalid'); + return; + } + + console.log('Generated matrix:'); + console.log(JSON.stringify(matrix, null, 2)); + console.log(`Matrix will create ${matrix.include.length} job(s)`); + + // Set output for GitHub Actions + core.setOutput('matrix', JSON.stringify(matrix)); + + client: + name: Clients - [${{ needs.setup-jobs.outputs.tgt_env_short }}] [${{ matrix.lang-name-short }}] + needs: [setup-jobs, setup-matrix] + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: ${{ fromJson(needs.setup-matrix.outputs.matrix) }} + permissions: + deployments: write + contents: read + environment: + name: ${{ needs.setup-jobs.outputs.tgt_env_short }}-clients + env: + TS_USERNAME: ${{ secrets.TS_USERNAME }} + TS_MACHINE_NAME_PREFIX: ${{ secrets.TS_MACHINE_NAME_PREFIX }} + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Language specific ENV - [${{ matrix.lang-name-full }}] + run: | + if [ "${{ matrix.lang-name-full }}" = "english" ]; then + echo "HOME_LOCATION=https://www.freecodecamp.${{ needs.setup-jobs.outputs.site_tld }}" >> $GITHUB_ENV + echo "NEWS_LOCATION=https://www.freecodecamp.${{ needs.setup-jobs.outputs.site_tld }}/news" >> $GITHUB_ENV + else + echo "HOME_LOCATION=https://www.freecodecamp.${{ needs.setup-jobs.outputs.site_tld }}/${{ matrix.lang-name-full }}" >> $GITHUB_ENV + echo "NEWS_LOCATION=https://www.freecodecamp.${{ needs.setup-jobs.outputs.site_tld }}/${{ matrix.lang-name-full }}/news" >> $GITHUB_ENV + fi + echo "CLIENT_LOCALE=${{ matrix.lang-name-full }}" >> $GITHUB_ENV + echo "CURRICULUM_LOCALE=${{ matrix.lang-name-full }}" >> $GITHUB_ENV + + - name: Create deployment version + id: deployment-version + run: | + DEPLOYMENT_VERSION=$(git rev-parse --short HEAD)-$(date +%Y%m%d)-$(date +%H%M) + echo "DEPLOYMENT_VERSION=$DEPLOYMENT_VERSION" >> $GITHUB_ENV + echo "DEPLOYMENT_VERSION=$DEPLOYMENT_VERSION" >> $GITHUB_OUTPUT + + - name: Install and Build + env: + API_LOCATION: 'https://api.freecodecamp.${{ needs.setup-jobs.outputs.site_tld }}' + ALGOLIA_API_KEY: ${{ secrets.ALGOLIA_API_KEY }} + ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }} + GROWTHBOOK_URI: ${{ secrets.GROWTHBOOK_URI }} + FORUM_LOCATION: 'https://forum.freecodecamp.org' + PATREON_CLIENT_ID: ${{ secrets.PATREON_CLIENT_ID }} + PAYPAL_CLIENT_ID: ${{ secrets.PAYPAL_CLIENT_ID }} + STRIPE_PUBLIC_KEY: ${{ secrets.STRIPE_PUBLIC_KEY }} + SHOW_UPCOMING_CHANGES: ${{ needs.setup-jobs.outputs.show_upcoming_changes }} + FREECODECAMP_NODE_ENV: production + # The below is used in ecosystem.config.js file for the API -- to be removed later + DEPLOYMENT_ENV: ${{ needs.setup-jobs.outputs.tgt_env_long }} + # The above is used in ecosystem.config.js file for the API -- to be removed later + run: | + pnpm install + pnpm run build + + - name: Free up space + run: pnpm run clean:packages + + - name: Tar Files + run: tar -czf client-${{ matrix.lang-name-short }}.tar client/public + + - name: Setup and connect to Tailscale network + uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4 + with: + oauth-client-id: ${{ secrets.TS_OAUTH_CLIENT_ID }} + oauth-secret: ${{ secrets.TS_OAUTH_SECRET }} + hostname: gha-${{needs.setup-jobs.outputs.tgt_env_short}}-clients-ci-${{ github.run_id }} + tags: tag:ci + version: latest + + - name: Wait for Tailscale Network Readiness + run: | + echo "Waiting for Tailscale network to be ready..." + max_wait=60 + elapsed=0 + + while [ $elapsed -lt $max_wait ]; do + if tailscale status --json | jq -e '.BackendState == "Running"' > /dev/null 2>&1; then + echo "Tailscale network is ready" + break + fi + sleep 2 + elapsed=$((elapsed + 2)) + done + + if [ $elapsed -ge $max_wait ]; then + echo "Tailscale network not ready after ${max_wait}s" + exit 1 + fi + + - name: Configure SSH & Check Connection + run: | + mkdir -p ~/.ssh + echo "Host * + UserKnownHostsFile=/dev/null + StrictHostKeyChecking no" > ~/.ssh/config + chmod 644 ~/.ssh/config + + scrub_ips() { + sed -E 's/100(\.[0-9]{1,3}){3}/100.x.x.x/g' + } + + validate_connection() { + local machine_name=$1 + local max_retries=3 + local retry_delay=5 + local ping_output ssh_output + + for attempt in $(seq 1 $max_retries); do + echo "Connection attempt $attempt/$max_retries to $machine_name" + + if ! ping_output=$(tailscale ping -c 1 --until-direct=false --timeout=5s "$machine_name" 2>&1); then + ping_output=$(printf '%s' "$ping_output" | scrub_ips) + echo "No Tailscale data path to $machine_name: $ping_output" + if [ $attempt -eq $max_retries ]; then + return 1 + fi + sleep $retry_delay + continue + fi + + MACHINE_IP=$(tailscale ip -4 $machine_name) + if ssh_output=$(ssh -o ConnectTimeout=10 -o BatchMode=yes $TS_USERNAME@$MACHINE_IP "echo 'Connection test'; uptime" 2>&1); then + echo "Successfully validated connection to $machine_name" + return 0 + fi + + ssh_output=$(printf '%s' "$ssh_output" | scrub_ips) + echo "SSH validation failed for $machine_name: $ssh_output" + if [ $attempt -lt $max_retries ]; then + sleep $retry_delay + fi + done + + echo "Failed to establish connection to $machine_name after $max_retries attempts" + return 1 + } + + echo -e "\nLOG:Validating connections to all machines..." + for i in {0..1}; do + TS_MACHINE_NAME=${TS_MACHINE_NAME_PREFIX}-${{ matrix.lang-name-short }}-${i} + echo "Validating connection to $TS_MACHINE_NAME" + if ! validate_connection "$TS_MACHINE_NAME"; then + echo "Error: Failed to establish reliable connection to $TS_MACHINE_NAME" + exit 1 + fi + done + echo "All machine connections validated successfully" + + - name: Upload and Deploy + run: | + for i in {0..1}; do + TS_MACHINE_NAME=${TS_MACHINE_NAME_PREFIX}-${{ matrix.lang-name-short }}-${i} + CURRENT_DATE=$(date +%Y%m%d) + CLIENT_SRC=client-${{ matrix.lang-name-short }}.tar + CLIENT_DST=/tmp/client-${{ matrix.lang-name-short }}-${CURRENT_DATE}-${{ github.run_id }}.tar + CLIENT_BINARIES=${{needs.setup-jobs.outputs.tgt_env_short}}-release-$CURRENT_DATE-${{ github.run_id }} + + echo -e "\nLOG:Uploading client archive to $TS_MACHINE_NAME..." + MACHINE_IP=$(tailscale ip -4 $TS_MACHINE_NAME) + scp $CLIENT_SRC $TS_USERNAME@$MACHINE_IP:$CLIENT_DST + + REMOTE_SCRIPT=" + set -e + echo -e '\nLOG: Deploying client - $CLIENT_BINARIES to $TS_MACHINE_NAME...' + + echo -e '\nLOG:Extracting client archive...' + mkdir -p /home/$TS_USERNAME/client/releases/$CLIENT_BINARIES + tar -xzf $CLIENT_DST -C /home/$TS_USERNAME/client/releases/$CLIENT_BINARIES --strip-components=2 + + echo -e '\nLOG:Cleaning up client archive...' + rm $CLIENT_DST + + echo -e '\nLOG:Checking client archive size...' + du -sh /home/$TS_USERNAME/client/releases/$CLIENT_BINARIES + + echo -e '\nLOG:Environment setup...' + cd /home/$TS_USERNAME/client + export NVM_DIR=\$HOME/.nvm && [ -s "\$NVM_DIR/nvm.sh" ] && source "\$NVM_DIR/nvm.sh" + echo -e '\nLOG:Checking available Node.js versions...' + nvm ls | grep 'default' + echo -e '\nLOG:Checking Node.js version...' + node --version + + echo -e '\nLOG:Installing serve...' + npm install -g serve@13 + + echo -e '\nLOG:Primary client setup...' + rm -f client-start-primary.sh + echo \"serve -c ../../serve.json releases/$CLIENT_BINARIES -p 50505\" >> client-start-primary.sh + chmod +x client-start-primary.sh + pm2 delete client-primary || true + pm2 start ./client-start-primary.sh --name client-primary + echo -e '\nLOG:Primary client setup completed.' + + pm2 ls + + echo -e '\nLOG:Secondary client setup...' + rm -f client-start-secondary.sh + echo \"serve -c ../../serve.json releases/$CLIENT_BINARIES -p 52525\" >> client-start-secondary.sh + chmod +x client-start-secondary.sh + pm2 delete client-secondary || true + pm2 start ./client-start-secondary.sh --name client-secondary + echo -e '\nLOG:Secondary client setup completed.' + + pm2 ls + pm2 save + + echo -e '\nLOG:Finished deployment.' + " + ssh $TS_USERNAME@$MACHINE_IP "$REMOTE_SCRIPT" + done diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/devcontainer-ci.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/devcontainer-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..0c60034f2732c750b268d93cc4b2c32bbfd636b7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/devcontainer-ci.yml @@ -0,0 +1,112 @@ +name: CI - Devcontainer + +on: + pull_request: + paths: + - '.devcontainer/**' + - 'docker/devcontainer/**' + - 'docker/docker-compose.yml' + - '.github/workflows/devcontainer-ci.yml' + - 'sample.env' + - 'package.json' + - 'turbo.json' + - 'pnpm-lock.yaml' + - 'client/package.json' + - 'client/turbo.json' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + validate: + name: Validate + runs-on: ubuntu-24.04 + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4 + + - name: Install devcontainer CLI + # renovate: datasource=npm depName=@devcontainers/cli + run: npm install -g @devcontainers/cli@0.83.0 + + - name: Build the devcontainer image from this branch + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7 + with: + files: docker/devcontainer/docker-bake.hcl + targets: local-devcontainer + load: true + + - name: Start devcontainer + run: devcontainer up --workspace-folder . + + - name: Validate required tools + run: | + devcontainer exec --workspace-folder . pnpm --version + devcontainer exec --workspace-folder . rsync --version + devcontainer exec --workspace-folder . mongosh --version + devcontainer exec --workspace-folder . node --version + devcontainer exec --workspace-folder . git --version + devcontainer exec --workspace-folder . gh --version + + - name: Validate MongoDB is writable + run: | + for i in $(seq 1 30); do + if devcontainer exec --workspace-folder . mongosh --quiet --eval 'if (!db.hello().isWritablePrimary) quit(1)'; then + echo "Replica set is writable" + exit 0 + fi + echo "Waiting for a writable primary... (attempt $i/30)" + sleep 2 + done + echo "Replica set failed to initialize" + exit 1 + + - name: Validate Mailpit is reachable + run: | + devcontainer exec --workspace-folder . bash -c 'exec 3<>/dev/tcp/localhost/1025 && head -1 <&3' + devcontainer exec --workspace-folder . bash -c 'exec 3<>/dev/tcp/localhost/8025' + + - name: Validate the generated .env + run: | + devcontainer exec --workspace-folder . grep -q '^MAILPIT_HOST=localhost$' .env + devcontainer exec --workspace-folder . grep -q '^HOME_LOCATION=http://localhost:8000$' .env + + - name: Validate the client answers on IPv4 loopback + run: | + devcontainer exec --workspace-folder . bash -c ' + FCC_SUPERBLOCK=responsive-web-design pnpm run develop > /tmp/develop.log 2>&1 & + pid=$! + deadline=$((SECONDS + 2400)) + while [ "$SECONDS" -lt "$deadline" ]; do + if ! kill -0 "$pid" 2>/dev/null; then + echo "pnpm run develop exited before the client answered" + cat /tmp/develop.log + exit 1 + fi + if curl -sf -o /dev/null --max-time 10 http://127.0.0.1:8000/; then + echo "The client answers on 127.0.0.1:8000" + exit 0 + fi + sleep 5 + done + echo "The client never answered on 127.0.0.1:8000" + cat /tmp/develop.log + exit 1' + + - name: Validate the Codespaces URL rewrite + run: | + devcontainer exec --workspace-folder . env \ + CODESPACE_NAME=ci-probe \ + GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN=app.github.dev \ + .devcontainer/codespace-env.sh + devcontainer exec --workspace-folder . grep -q '^HOME_LOCATION=https://ci-probe-8000.app.github.dev$' .env + devcontainer exec --workspace-folder . grep -q '^API_LOCATION=https://ci-probe-3000.app.github.dev$' .env diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr-cleanup.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr-cleanup.yml new file mode 100644 index 0000000000000000000000000000000000000000..a3c9c7b89f6a21b6648b73dd274ef7f2677b4f1e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr-cleanup.yml @@ -0,0 +1,35 @@ +name: CD - Docker - DOCR Cleanup Container Images +on: + workflow_dispatch: + schedule: + - cron: '5 0 * * 3,6' # 12:05 UTC on Wednesdays and Saturdays (6 hour maintenance window) + +jobs: + remove: + name: Delete Old Images + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + repos: + - learn-api + variants: + - dev + - org + + steps: + - name: Install doctl + uses: digitalocean/action-doctl@3cb3953159719656269e044e0e24ca16dd2a690f # v2.5.2 + with: + token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} + + - name: Log in to DigitalOcean Container Registry with short-lived credentials + run: doctl registry login --expiry-seconds 1200 + + - name: Delete Images + uses: raisedadead/action-docr-cleanup@1c7d87369bccfdf5da03a9ae3b00eacc3f2a9b51 # v1 + with: + repository_name: '${{ matrix.variants }}/${{ matrix.repos }}' + days: '7' + keep_last: '3' + diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr.yml new file mode 100644 index 0000000000000000000000000000000000000000..bf34dc3e55364783f8101d94848c8d6b7329ea38 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-docr.yml @@ -0,0 +1,125 @@ +name: CD - Docker - DOCR + +on: + workflow_dispatch: + inputs: + site_tld: + required: true + type: choice + description: 'Input: The site tld (variant) to build' + options: + - dev + - org + default: 'dev' + app: + required: true + type: string + description: 'Input: The app (component) to build' + default: 'api' + show_upcoming_changes: + required: false + type: string + description: 'Input: Show upcoming changes flag (true/false)' + default: 'false' + workflow_call: + inputs: + site_tld: + required: true + type: string + description: 'Input: The site tld (variant) to build' + app: + required: true + type: string + description: 'Input: The app (component) to build' + show_upcoming_changes: + required: false + type: string + description: 'Input: Show upcoming changes flag (true/false)' + default: 'false' + secrets: + DIGITALOCEAN_ACCESS_TOKEN: + required: true + description: 'DigitalOcean API token for registry authentication' + DOCR_NAME: + required: true + description: 'DigitalOcean Container Registry name' + SENTRY_AUTH_TOKEN: + required: false + description: 'Sentry auth token for source map upload (api app only)' + outputs: + tagname: + description: 'Output: The tagname for the image built' + value: ${{ jobs.build.outputs.tagname }} + +jobs: + build: + name: Build & Push + runs-on: ubuntu-24.04 + permissions: + contents: read + outputs: + tagname: ${{ steps.tagname.outputs.tagname }} + + steps: + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + + - name: Create a tagname + id: tagname + run: | + tagname=$(git rev-parse --short HEAD)-$(date +%Y%m%d)-$(date +%H%M) + echo "tagname=$tagname" >> "$GITHUB_ENV" + echo "tagname=$tagname" >> "$GITHUB_OUTPUT" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4 + + - name: Install doctl + uses: digitalocean/action-doctl@3cb3953159719656269e044e0e24ca16dd2a690f # v2.5.2 + with: + token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} + + - name: Log in to DigitalOcean Container Registry with short-lived credentials + run: doctl registry login --expiry-seconds 1200 + + - name: Build & Push Image + uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + with: + context: . + file: docker/${{ inputs.app }}/Dockerfile + push: true + build-args: | + SHOW_UPCOMING_CHANGES=${{ inputs.show_upcoming_changes }} + tags: | + registry.digitalocean.com/${{ secrets.DOCR_NAME }}/${{ inputs.site_tld }}/learn-${{ inputs.app }}:${{ env.tagname }} + registry.digitalocean.com/${{ secrets.DOCR_NAME }}/${{ inputs.site_tld }}/learn-${{ inputs.app }}:latest + cache-from: type=gha + cache-to: type=gha,mode=max + + # TODO(o11y): source-map upload + release marking disabled pending a + # follow-up PR with a stable release-id scheme. Also fix the upload path + # when re-enabling: the image ships /home/node/fcc/api/src (dist flattened + # by the COPY in docker/api/Dockerfile), so `docker cp .../fcc/api` yields + # sentry-dist/api/src — the old upload pointed at sentry-dist/api/dist, + # which never exists (silent no-op, so maps never uploaded). Path below is + # pre-corrected to sentry-dist/api/src. See + # .scratchpad/o11y-cutover-review-2026-07-10.md. + # - name: Extract API dist for Sentry source maps + # if: inputs.app == 'api' + # run: | + # IMAGE="registry.digitalocean.com/${{ secrets.DOCR_NAME }}/${{ inputs.site_tld }}/learn-${{ inputs.app }}:${{ env.tagname }}" + # docker pull "$IMAGE" + # container_id=$(docker create "$IMAGE") + # mkdir -p sentry-dist + # docker cp "$container_id:/home/node/fcc/api" sentry-dist/ + # docker rm "$container_id" + # + # - name: Upload source maps to Sentry (unfinalized) + # if: inputs.app == 'api' + # env: + # SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + # SENTRY_ORG: freecodecamp + # SENTRY_PROJECT: api-fastify + # run: | + # npx --yes @sentry/cli@3.6.0 releases new "${{ env.tagname }}" + # npx --yes @sentry/cli@3.6.0 sourcemaps upload --release "${{ env.tagname }}" sentry-dist/api/src diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-ghcr.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-ghcr.yml new file mode 100644 index 0000000000000000000000000000000000000000..4216dc7a7f9645518d6e37c232af74b77752770d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/docker-ghcr.yml @@ -0,0 +1,50 @@ +name: CD - Docker - GHCR Images + +on: + workflow_dispatch: + push: + branches: + - main + paths: + - 'pnpm-lock.yaml' + - 'package.json' + - 'docker/devcontainer/**' + - '.github/workflows/docker-ghcr.yml' + +permissions: + contents: read + packages: write + +jobs: + build-and-push: + name: Build and Push Images + runs-on: ubuntu-24.04 + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + + - name: Set up QEMU + uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4 + + - name: Log in to GHCR + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push images + uses: docker/bake-action@d3418bd7d0e9324001bca92fa8ba175ea7e6dc9b # v7 + with: + files: docker/devcontainer/docker-bake.hcl + targets: devcontainer + push: true + env: + TAG: ${{ github.sha }} + TAG_LATEST: ${{ github.ref_name == 'main' }} diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/e2e-playwright.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/e2e-playwright.yml new file mode 100644 index 0000000000000000000000000000000000000000..edfce24a306af68c12e09d1ad19398fe73560e01 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/e2e-playwright.yml @@ -0,0 +1,98 @@ +name: CI - E2E - Playwright +on: + workflow_call: + +permissions: + contents: read + +jobs: + playwright-run: + name: Run Playwright Tests + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + # Extend this to include firefox and webkit once chromium is working. + browsers: [chromium] + node-version: [24] + + steps: + - name: Set Action Environment Variables + run: | + echo "GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }}" >> $GITHUB_ENV + + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + + - name: Download Client Artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: client-artifact + path: client/public + + - name: Checkout client-config + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + repository: freeCodeCamp/client-config + path: client-config + persist-credentials: false + + - name: Move serve.json to Public Folder + run: cp client-config/serve.json client/public/serve.json + + - name: Download Api Artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: api-artifact + path: api-artifact + + - name: Load API Image + run: | + docker load < api-artifact/api-artifact.tar + rm api-artifact/api-artifact.tar + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Install Dependencies + run: pnpm install + + - name: Set freeCodeCamp Environment Variables (needed by api) + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + cp sample.env .env # for docker compose + + - name: Install playwright dependencies + run: npx playwright install --with-deps + + - name: Install + run: pnpm install + + - name: Start apps + run: | + docker compose -f docker/docker-compose.yml -f docker/docker-compose.ports.yml -f docker/docker-compose.e2e.yml up -d + pnpm run serve:client-ci & + sleep 10 + + - name: Seed Database with Certified User + run: pnpm run seed:certified-user + + - name: Run playwright tests + run: pnpm run playwright:run --project=${{ matrix.browsers }} + + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + if: ${{ !cancelled() }} + with: + name: playwright-report-${{ matrix.browsers }} + path: e2e/playwright/reporter + retention-days: 7 diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-autoclose.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-autoclose.yml new file mode 100644 index 0000000000000000000000000000000000000000..526af481516589afffbfd311a3b04afafb6cf784 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-autoclose.yml @@ -0,0 +1,74 @@ +name: GitHub - Autoclose Invalid PRs +on: + pull_request_target: + branches: + - 'main' + paths: + - '.gitignore' + +permissions: + issues: write + pull-requests: write +jobs: + autoclose: + runs-on: ubuntu-24.04 + steps: + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{secrets.GITHUB_TOKEN}} + script: | + const files = await github.rest.pulls.listFiles({ + owner: context.payload.repository.owner.login, + repo: context.payload.repository.name, + pull_number: context.payload.pull_request.number, + }); + if ( + files.data.length !== 1 || + (files.data[0].filename !== ".gitignore" && + // We've had four PRs make this same (irrelevant) change already. + !(files.data[0].filename === "664ef4623946e65e18d59764.md" && + files.data[0].patch.includes("return re.sub('(? ({status: 404})); + if (context.payload.pull_request.user.login !== "camperbot" && isDev.status !== 200) { + core.setFailed('This PR appears to touch translated curriculum files.') + await github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: "Thanks for your pull request.\n\n**Please remove the changes made to the non-English versions of the files. No need to close this pull request; just add more commits as needed.**\n\nWe require you to change **only English** versions of files in the codebase. Translations to corresponding files in other world languages are managed on our translation platform. Once your pull request is merged, changes will be synced automatically to other world languages.\n\nPlease visit [our contributing guidelines](https://contribute.freecodecamp.org) to learn more about translating freeCodeCamp's resources.\n\nAs always, we value all of your contributions.\n\nHappy contributing!\n\n---\n_**Note:** This message was automatically generated by a bot. If you feel this message is in error or would like help resolving it, feel free to reach us [in our contributor chat](https://discord.gg/PRyKn3Vbay)._" + }) + } else if (isDev.status === 200) { + core.setFailed('This PR appears to touch translated curriculum files, but since you are on the dev team there is no message.'); + } diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-pr-guidelines.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-pr-guidelines.yml new file mode 100644 index 0000000000000000000000000000000000000000..12a63141305997ddb78fa18dd0a47aaf918754cc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-pr-guidelines.yml @@ -0,0 +1,209 @@ +name: GitHub - PR Contribution Guidelines + +on: + pull_request_target: + types: [opened, reopened, edited] + +jobs: + # Ensures PR commits were not added via the GitHub Web UI, which typically indicates + # the contributor hasn't tested their changes in a local development environment. + no-web-commits: + name: No Commits on GitHub Web + runs-on: ubuntu-24.04 + outputs: + is_allow_listed: ${{ steps.pr_author.outputs.is_allow_listed }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + sparse-checkout: .github/scripts/pr-guidelines + sparse-checkout-cone-mode: false + + - name: Check if PR author is allow-listed + id: pr_author + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + # GITHUB_TOKEN does not have the read:org permission needed for this call + # while CAMPERBOT_NO_TRANSLATE does, since it is a PAT for the camperbot account with read:org scope + github-token: ${{ secrets.CAMPERBOT_NO_TRANSLATE }} + script: | + const fn = require('./.github/scripts/pr-guidelines/check-allow-list.js'); + await fn({ github, context, core }); + + - name: Check if commits are made on GitHub Web UI + id: check-commits + if: steps.pr_author.outputs.is_allow_listed == 'false' && github.event.action != 'edited' + env: + HEAD_REF: ${{ github.head_ref }} + run: | + PR_NUMBER=$(jq --raw-output .pull_request.number "$GITHUB_EVENT_PATH") + COMMITS_URL="https://api.github.com/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/commits" + HAS_GITHUB_SIGNED_COMMIT=$(curl --header "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" "$COMMITS_URL" | jq '[.[] | select(.commit.committer.name == "GitHub") | select(.commit.message | test("revert"; "i") | not)] | length > 0') + # GitHub Codespaces also produces GitHub-signed commits, but Codespaces users + # work on descriptively named branches. The web editor defaults to patch-N branches. + IS_PATCH_BRANCH=false + if [[ "$HEAD_REF" =~ ^patch-[0-9]+$ ]]; then + IS_PATCH_BRANCH=true + fi + if [ "$HAS_GITHUB_SIGNED_COMMIT" = "true" ] && [ "$IS_PATCH_BRANCH" = "true" ]; then + echo "IS_GITHUB_COMMIT=true" >> $GITHUB_ENV + fi + + - name: Add comment on PR if commits are made on GitHub Web UI + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + if: steps.pr_author.outputs.is_allow_listed == 'false' && env.IS_GITHUB_COMMIT == 'true' && github.event.action != 'edited' + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + core.setFailed("Commits were added via the GitHub Web UI."); + await github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: "Thanks for your pull request.\n\n**Please do not add commits via the GitHub Web UI.**\n\nIt generally means you have yet to test these changes in a development setup or complete any prerequisites. We need you to follow the guides mentioned in the checklist. Please revalidate these changes in a developer environment and confirm how you validated your changes.\n\nHappy contributing!\n\n---\n_**Note:** This message was automatically generated by a bot. If you feel this message is in error or would like help resolving it, feel free to reach us [in our contributor chat](https://discord.gg/PRyKn3Vbay)._" + }); + + - name: Add deprioritized label + if: failure() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + labels: ['deprioritized'] + }); + + # Ensures PRs are not opened directly from the contributor's main branch, which makes + # it hard to keep the PR up to date as the upstream repository progresses. + # Kept as a standalone job so it does not depend on the web-commit checks. + no-main-branch: + name: No PRs from Main Branch + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + sparse-checkout: .github/scripts/pr-guidelines + sparse-checkout-cone-mode: false + + - name: Check if PR author is allow-listed + id: pr_author + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + # GITHUB_TOKEN does not have the read:org permission needed for this call + # while CAMPERBOT_NO_TRANSLATE does, since it is a PAT for the camperbot account with read:org scope + github-token: ${{ secrets.CAMPERBOT_NO_TRANSLATE }} + script: | + const fn = require('./.github/scripts/pr-guidelines/check-allow-list.js'); + await fn({ github, context, core }); + + - name: Check if PR is opened from the main branch + id: check-main-branch + if: steps.pr_author.outputs.is_allow_listed == 'false' + env: + HEAD_REF: ${{ github.head_ref }} + run: | + if [ "$HEAD_REF" = "main" ]; then + echo "IS_MAIN_BRANCH=true" >> $GITHUB_ENV + fi + + - name: Add comment on PR if head branch is main + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + if: steps.pr_author.outputs.is_allow_listed == 'false' && env.IS_MAIN_BRANCH == 'true' && github.event.action != 'edited' + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: "Thanks for your pull request.\n\n**We recommend opening pull requests from a dedicated branch rather than your `main` branch.**\n\nUsing a separate branch for each change lets you work on multiple things at the same time without them interfering with one another. Since this PR is opened from your `main` branch, any new commits you push to `main` will be added to this PR while it stays open. After it is merged, you will need to reset your `main` branch as described in the [basic Git workflow guide](https://contribute.freecodecamp.org/basic-git-workflow/) to keep it in sync with the upstream repository.\n\nHappy contributing!\n\n---\n_**Note:** This message was automatically generated by a bot. If you feel this message is in error or would like help resolving it, feel free to reach us [in our contributor chat](https://discord.gg/PRyKn3Vbay)._" + }); + + - name: Fail if head branch is main + if: steps.pr_author.outputs.is_allow_listed == 'false' && env.IS_MAIN_BRANCH == 'true' + run: exit 1 + + - name: Add deprioritized label + if: failure() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.addLabels({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + labels: ['deprioritized'] + }); + + # Normalizes PR titles to follow Conventional Commits format, applying fuzzy fixes + # for common mistakes like typos, missing colons, or incorrect spacing. + fix-pr-title: + name: Fix PR Title + runs-on: ubuntu-24.04 + needs: [no-web-commits, no-main-branch] + if: needs.no-web-commits.result == 'success' && needs.no-main-branch.result == 'success' && github.event.action != 'edited' + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + sparse-checkout: .github/scripts/pr-guidelines + sparse-checkout-cone-mode: false + + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fn = require('./.github/scripts/pr-guidelines/fix-pr-title.js'); + await fn({ github, context }); + + # Checks that the PR description still contains the required template. + # The first 3 checkboxes must be ticked ([x] or [X]). + # The last checkbox (tested locally) is acceptable to leave unticked + # but removing the entire template is not. + check-pr-template: + name: Check PR Template + runs-on: ubuntu-24.04 + needs: [no-web-commits, no-main-branch] + if: needs.no-web-commits.result == 'success' && needs.no-main-branch.result == 'success' + outputs: + failure_reason: ${{ steps.check.outputs.failure_reason }} + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + sparse-checkout: .github/scripts/pr-guidelines + sparse-checkout-cone-mode: false + + - id: check + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fn = require('./.github/scripts/pr-guidelines/check-pr-template.js'); + await fn({ github, context, core, isAllowListed: '${{ needs.no-web-commits.outputs.is_allow_listed }}' }); + + # Coordinates reporting: posts a single combined comment when checks fail, + # or removes the deprioritized label when all checks pass. + report: + name: Report + runs-on: ubuntu-24.04 + needs: [no-web-commits, no-main-branch, check-pr-template] + if: always() && needs.no-web-commits.result == 'success' && needs.no-main-branch.result == 'success' + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + sparse-checkout: .github/scripts/pr-guidelines + sparse-checkout-cone-mode: false + + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fn = require('./.github/scripts/pr-guidelines/report-results.js'); + await fn({ + github, + context, + templateResult: '${{ needs.check-pr-template.result }}', + templateReason: '${{ needs.check-pr-template.outputs.failure_reason }}' + }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-spam.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-spam.yml new file mode 100644 index 0000000000000000000000000000000000000000..c915e1203feba14d3cf11e6b87d357b0aefab8b1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/github-spam.yml @@ -0,0 +1,27 @@ +name: GitHub - Spam PR +on: + pull_request_target: + types: + - labeled + +permissions: {} +jobs: + is-spam: + runs-on: ubuntu-24.04 + steps: + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{secrets.CAMPERBOT_NO_TRANSLATE}} + script: | + if (context.payload.label.name === "spam") { + try { + await github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: "We are marking this pull request as spam. Please note that if you are participating in Hacktoberfest, two or more PRs marked as spam will result in your permanent disqualification.\n\nIf you are interested in making quality and genuine contributions to our projects, check out our [contributing guidelines](https://contribute.freecodecamp.org)." + }); + } catch { + // Conversation may already be locked — ignore. + } + } diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-builds.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-builds.yml new file mode 100644 index 0000000000000000000000000000000000000000..71c6e40b0c9fe62b32057623440b34f22fca7fb9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-builds.yml @@ -0,0 +1,50 @@ +name: i18n - Build Validation +on: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.workflow_run.head_branch || github.ref }} + cancel-in-progress: true + +jobs: + ci: + name: Validate i18n Builds + runs-on: ubuntu-24.04 + strategy: + matrix: + node-version: [24] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set freeCodeCamp Environment Variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + + - name: Install Dependencies + run: pnpm install + + - name: Validate Challenge Files + run: pnpm run audit-challenges diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-prs.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-prs.yml new file mode 100644 index 0000000000000000000000000000000000000000..e2b4a39d62c227b058b3cf494d1c97ac86d7a1a0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/i18n-validate-prs.yml @@ -0,0 +1,61 @@ +name: i18n - Curriculum PR Validation +on: + pull_request: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.workflow_run.head_branch || github.ref }} + cancel-in-progress: true + +jobs: + ci: + name: Validate i18n Builds + # run only on PRs that camperbot opens with title that matches the curriculum sync + if: ${{ github.event.pull_request.user.login == 'camperbot' && contains(github.event.pull_request.title, 'chore(i18n,learn)') }} + runs-on: ubuntu-24.04 + strategy: + matrix: + node-version: [24] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Set freeCodeCamp Environment Variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + + - name: Install Dependencies + run: pnpm install + + - name: Validate Challenge Files + id: validate + run: pnpm run audit-challenges + + - name: Create Comment + # Run if the validate challenge files step fails, specifically. Note that we need the failure() call for this step to trigger if the action fails. + if: ${{ failure() && steps.validate.conclusion == 'failure' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + github-token: ${{secrets.CAMPERBOT_NO_TRANSLATE}} + script: | + await github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: "Hey @freecodecamp/i18n, it looks like we have new English curriculum files that need to be translated." + }) diff --git a/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/node.js-tests.yml b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/node.js-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..71711b1e0d3e49226ea895b149ba0d178c45a206 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.github/workflows/node.js-tests.yml @@ -0,0 +1,357 @@ +name: CI - Node.js + +on: + push: + branches: + - 'main' + - 'prod-**' + - 'renovate/**' + - 'hotfix-**' + - 'temp-**' + pull_request: + branches: + - 'main' + - 'temp-**' # Temporary branches allowed on Upstream + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.workflow_run.head_branch || github.ref }} + cancel-in-progress: ${{ !contains(github.ref, 'main') && !contains(github.ref, 'prod-') }} + +permissions: + contents: read + +jobs: + lint: + name: Lint + # Skip PR runs for Renovate since push already triggered CI + if: github.event_name != 'pull_request' || github.event.pull_request.user.login != 'renovate[bot]' + runs-on: ubuntu-24.04 + strategy: + matrix: + node-version: [24] + fail-fast: false + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + persist-credentials: false + + - name: Check number of lockfiles + run: | + if [ $(find . -name 'package-lock.json' | grep -vc -e 'node_modules') -gt 0 ] + then + echo -e 'Error: found package-lock files in the repository.\nWe use pnpm workspaces to manage packages so all dependencies should be added via pnpm add' + exit 1 + fi + + - name: Check format of sample.env + run: docker run --rm -v `pwd`:/app -w /app dotenvlinter/dotenv-linter check --ignore-checks UnorderedKey sample.env + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set Environment variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + + - name: Install node_modules + run: pnpm install + + - name: Check formatting + run: | + pnpm prettier --check . || [ $? -eq 1 ] && printf "\nTip: Run 'pnpm run format' in your terminal to fix this.\n\n" + + - name: Lint Source Files + run: | + echo pnpm version $(pnpm -v) + pnpm lint + + # This is populate the cache, otherwise local runs with upcoming changes + # will not benefit. + - name: Set UPCOMING_CHANGES + run: | + echo 'SHOW_UPCOMING_CHANGES=true' >> $GITHUB_ENV + + - name: Lint Upcoming Changes + run: | + pnpm lint + + # DONT REMOVE THIS JOB. + build: + name: Build + runs-on: ubuntu-24.04 + strategy: + matrix: + node-version: [24] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + persist-credentials: false + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set freeCodeCamp Environment Variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + + - name: Install and Build + run: | + pnpm install + pnpm run build + + - name: Upload Client Artifact + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: client-artifact + path: client/public + retention-days: 1 + + build-e2e-api: + name: Build E2E API (Container) + if: github.event_name == 'pull_request' + runs-on: ubuntu-24.04 + + steps: + - name: Checkout Source Files + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + submodules: 'recursive' + + - name: Create Image + run: | + docker build \ + -t fcc-api \ + -f docker/api/Dockerfile . + + - name: Save Image + run: docker save fcc-api > api-artifact.tar + + - name: Upload API Artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: api-artifact + path: api-artifact.tar + retention-days: 1 + + e2e: + name: E2E + if: github.event_name == 'pull_request' + needs: [build, build-e2e-api] + uses: ./.github/workflows/e2e-playwright.yml + secrets: inherit + + test: + name: Test + needs: build + runs-on: ubuntu-24.04 + + strategy: + fail-fast: false + matrix: + node-version: [24] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + persist-credentials: false + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set Environment variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + cat sample.env + + - name: Start MongoDB + run: docker compose -f docker/docker-compose.yml -f docker/docker-compose.ports.yml up -d + + - name: Install Dependencies + run: | + echo pnpm version $(pnpm -v) + pnpm install + + - name: Install Chrome for Puppeteer + run: pnpm -F=curriculum install-puppeteer + + - name: Run Tests + run: pnpm test + + test-upcoming: + name: Test - Upcoming Changes + needs: build + runs-on: ubuntu-24.04 + + strategy: + fail-fast: false + matrix: + node-version: [24] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + persist-credentials: false + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set Environment variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + echo 'SHOW_UPCOMING_CHANGES=true' >> $GITHUB_ENV + + - name: Start MongoDB + run: docker compose -f docker/docker-compose.yml -f docker/docker-compose.ports.yml up -d + + - name: Install Dependencies + run: | + echo pnpm version $(pnpm -v) + pnpm install + + - name: Install Chrome for Puppeteer + run: pnpm -F=curriculum install-puppeteer + + - name: Run Tests + run: pnpm test + + test-localization: + name: Test - i18n + needs: build + runs-on: ubuntu-24.04 + if: github.event.pull_request.user.login == 'camperbot' && github.head_ref == 'chore/update-i18n-curriculum-submodule' + + strategy: + fail-fast: false + matrix: + node-version: [24] + locale: [portuguese, italian] + + steps: + - name: Checkout + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + submodules: 'recursive' + persist-credentials: false + + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: ${{ matrix.node-version }} + + - name: Install pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + id: pnpm-install + with: + run_install: false + + - name: Setup Turbo Cache + uses: ./.github/actions/setup-turbo-cache + with: + turbo-token: ${{ secrets.TURBO_TOKEN }} + turbo-signature-key: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }} + + - name: Set Environment variables + run: | + sed '/^[[:space:]]*#/d; /^$/d' sample.env >> $GITHUB_ENV + cat sample.env + + - name: Start MongoDB + uses: supercharge/mongodb-github-action@315db7fe45ac2880b7758f1933e6e5d59afd5e94 # 1.12.1 + with: + mongodb-version: 8.0 + mongodb-replica-set: test-rs + mongodb-port: 27017 + + - name: Install Dependencies + env: + CURRICULUM_LOCALE: ${{ matrix.locale }} + CLIENT_LOCALE: ${{ matrix.locale }} + run: | + echo pnpm version $(pnpm -v) + pnpm install + + # DONT REMOVE THIS STEP. + # TODO: Refactor and use re-usable workflow and shared artifacts + - name: Build Client in ${{ matrix.locale }} + env: + CURRICULUM_LOCALE: ${{ matrix.locale }} + CLIENT_LOCALE: ${{ matrix.locale }} + run: | + pnpm run build + + - name: Install Chrome for Puppeteer + run: pnpm -F=curriculum install-puppeteer + + - name: Run Tests + env: + CURRICULUM_LOCALE: ${{ matrix.locale }} + CLIENT_LOCALE: ${{ matrix.locale }} + run: pnpm test diff --git a/github_code/freeCodeCamp__freeCodeCamp/.gitignore b/github_code/freeCodeCamp__freeCodeCamp/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c3f559c0fde1e1330e42215cd220fdb1e33f87ab --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.gitignore @@ -0,0 +1,206 @@ +### VisualStudioCode ### +.vscode/* + +### WebStorm ### +.idea/* + +### VisualStudioCode Patch ### + +# Ignore all local history of files +.history + +### Windows ### + +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Linux ### + +# General +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### + +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Node ### + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env +.env.test + +# gatsby files +.cache/ + +### Netlify ### +.netlify + +### Old Generated files ### +# These files are no longer generated by the client, but can +# exist on older branches. Continuing to ignore them ensures they +# are not erroneously committed by contributors (or Naomi) who +# aren't as familiar with our codebase. +config/superblock-order.js +config/superblock-order.test.js +utils/slugs.js +utils/slugs.test.js + +### vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### Additional Files ### +*.csv +*.dat +*.out +*.gz +curriculum/curricula.json + +### Additional Folders ### +curriculum/dist +curriculum/build +curriculum/src/test/blocks-generated + +### Playwright ### + +/playwright + +### Shadow Testing Log Files Folder ### +api/logs/ + +### Turborepo +.turbo +test-results diff --git a/github_code/freeCodeCamp__freeCodeCamp/.gitmodules b/github_code/freeCodeCamp__freeCodeCamp/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..fc8e491adcf6a994c8b458117e38f3736e416872 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.gitmodules @@ -0,0 +1,8 @@ +[submodule "curriculum/i18n-curriculum"] + path = curriculum/i18n-curriculum + url = https://github.com/freeCodeCamp/i18n-curriculum.git + ignore = dirty +[submodule "tools/challenge-editor"] + path = tools/challenge-editor + url = https://github.com/freeCodeCamp/challenge-editor.git + ignore = dirty diff --git a/github_code/freeCodeCamp__freeCodeCamp/.husky/pre-commit b/github_code/freeCodeCamp__freeCodeCamp/.husky/pre-commit new file mode 100644 index 0000000000000000000000000000000000000000..909c3ed086dcd988c7cd4b9999f71e05e9c7c22b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.husky/pre-commit @@ -0,0 +1 @@ +NODE_OPTIONS=\"--max-old-space-size=7168\" pnpm lint-staged diff --git a/github_code/freeCodeCamp__freeCodeCamp/.nvmrc b/github_code/freeCodeCamp__freeCodeCamp/.nvmrc new file mode 100644 index 0000000000000000000000000000000000000000..a45fd52cc5891570d6299fab38643103c3955474 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.nvmrc @@ -0,0 +1 @@ +24 diff --git a/github_code/freeCodeCamp__freeCodeCamp/.prettierignore b/github_code/freeCodeCamp__freeCodeCamp/.prettierignore new file mode 100644 index 0000000000000000000000000000000000000000..f01c40e8036cabfb3a74520623388131522bfbf6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.prettierignore @@ -0,0 +1,17 @@ +.*/* +**/.cache +**/*fixtures* +/client/**/trending.json +/client/**/search-bar.json +/client/config/*.json +/client/static +/client/public +/curriculum/challenges/_meta/*/* +/curriculum/challenges/**/* +/curriculum/i18n-curriculum +/curriculum/generated +/curriculum/src/test/stubs +/e2e/playwright +/pnpm-lock.yaml +/tools/challenge-editor +dist diff --git a/github_code/freeCodeCamp__freeCodeCamp/.prettierrc b/github_code/freeCodeCamp__freeCodeCamp/.prettierrc new file mode 100644 index 0000000000000000000000000000000000000000..2c652feab9fa5ddc61ec6f81d77431bd38ccdc45 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.prettierrc @@ -0,0 +1,9 @@ +{ + "endOfLine": "lf", + "semi": true, + "singleQuote": true, + "jsxSingleQuote": true, + "tabWidth": 2, + "trailingComma": "none", + "arrowParens": "avoid" +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/.stylelintignore b/github_code/freeCodeCamp__freeCodeCamp/.stylelintignore new file mode 100644 index 0000000000000000000000000000000000000000..ca00abd8a3870a98d661df7c8cb3676dabb7ade7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.stylelintignore @@ -0,0 +1,2 @@ +playwright +client/public diff --git a/github_code/freeCodeCamp__freeCodeCamp/.stylelintrc.json b/github_code/freeCodeCamp__freeCodeCamp/.stylelintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..34369a47fd353ecec720717ba8426aee6f75bf39 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/.stylelintrc.json @@ -0,0 +1,23 @@ +{ + "rules": { + "no-invalid-double-slash-comments": true, + "no-duplicate-selectors": true, + "font-family-no-duplicate-names": true, + "declaration-block-no-shorthand-property-overrides": true, + "declaration-block-no-duplicate-custom-properties": true, + "declaration-block-no-duplicate-properties": [ + true, + { + "ignore": ["consecutive-duplicates-with-different-values"] + } + ], + "comment-no-empty": true, + "color-no-invalid-hex": true, + "block-no-empty": true, + "shorthand-property-no-redundant-values": true, + "keyframe-declaration-no-important": true, + "no-duplicate-at-import-rules": true, + "named-grid-areas-no-invalid": true, + "no-invalid-position-at-import-rule": true + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/LICENSE.md b/github_code/freeCodeCamp__freeCodeCamp/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c61d66f5a8c407d57d4cb304760f04931dffe452 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/LICENSE.md @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2014, freeCodeCamp. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +- Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/github_code/freeCodeCamp__freeCodeCamp/README.md b/github_code/freeCodeCamp__freeCodeCamp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c82f1a4976d0a58963641054598aebeb4e3f124f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/README.md @@ -0,0 +1,94 @@ +[![freeCodeCamp Social Banner](https://cdn.freecodecamp.org/platform/universal/fcc_banner_new.png)](https://www.freecodecamp.org/) + +[![first-timers-only Friendly](https://img.shields.io/badge/first--timers--only-friendly-blue.svg)](https://www.firsttimersonly.com/) +[![Discord](https://img.shields.io/discord/692816967895220344?logo=discord&label=Discord&color=5865F2)](https://discord.gg/PRyKn3Vbay) +[![LFX Active Contributors](https://insights.linuxfoundation.org/api/badge/active-contributors?project=freecodecamp&repos=https://github.com/freeCodeCamp/freeCodeCamp)](https://insights.linuxfoundation.org/project/freecodecamp/repository/freecodecamp-freecodecamp) + +## freeCodeCamp.org's open-source codebase and curriculum + +[freeCodeCamp.org](https://www.freecodecamp.org) is a friendly community where you can learn to code for free. It is run by a [donor-supported 501(c)(3) charity](https://www.freecodecamp.org/donate) to help millions of busy adults transition into tech. Our community has already helped more than 100,000 people get their first developer job. + +Our full-stack web development and machine learning curriculum is completely free and self-paced. We have thousands of interactive coding challenges to help you expand your skills. + +## Table of Contents + +- [Certifications](#certifications) +- [The Learning Platform](#the-learning-platform) +- [Reporting Bugs and Issues](#reporting-bugs-and-issues) +- [Reporting Security Issues and Responsible Disclosure](#reporting-security-issues-and-responsible-disclosure) +- [Contributing](#contributing) +- [License](#license) + +### Certifications + +freeCodeCamp.org offers several free developer certifications that make up the [Full-Stack Developer Curriculum](https://www.freecodecamp.org/learn/full-stack-developer-v9/): + +- [Responsive Web Design](https://www.freecodecamp.org/learn/responsive-web-design-v9/) +- [JavaScript](https://www.freecodecamp.org/learn/javascript-v9/) +- [Front-End Development Libraries](https://www.freecodecamp.org/learn/front-end-development-libraries-v9/) +- [Python](https://www.freecodecamp.org/learn/python-v9/) +- [Relational Databases](https://www.freecodecamp.org/learn/relational-databases-v9/) +- [Back-End Development and APIs](https://www.freecodecamp.org/learn/back-end-development-and-apis-v9/) + +Each of these certifications involves completing interactive lessons, workshops, labs, reviews, and quizzes. Throughout the certification, you'll need to complete 5 required projects to qualify for the exam. Once you pass the exam, then you can claim the certification. + +freeCodeCamp.org also offers free language certifications designed around internationally recognized proficiency levels: + +- [A2 English for Developers (Beta)](https://www.freecodecamp.org/learn/a2-english-for-developers/) +- [B1 English for Developers (Beta)](https://www.freecodecamp.org/learn/b1-english-for-developers/) +- [A1 Professional Spanish (Beta)](https://www.freecodecamp.org/learn/a1-professional-spanish/) +- [A1 Professional Chinese (Beta)](https://www.freecodecamp.org/learn/a1-professional-chinese/) + +Each of these certifications is organized into modules, with sections for warm-ups, lessons, practice exercises, review pages, and quizzes to ensure you fully grasp the material before progressing to the next module. You'll need to complete all of the quizzes in order to qualify for the exam at the end of the certification. + +Once you've earned a certification, you will always have it. You will always be able to link to it from your LinkedIn or resume. And when your prospective employers or freelance clients click that link, they'll see a verified certification specific to you. + +The one exception to this is if we discover violations of our [Academic Honesty Policy](https://www.freecodecamp.org/news/academic-honesty-policy/). When we catch people unambiguously plagiarizing (submitting other people's code or projects as their own without citation), we do what all rigorous institutions of learning should do - we revoke their certifications and ban those people. + +In addition, to help prepare for job interviews, freeCodeCamp.org includes The Odin Project (freeCodeCamp Remix), Coding Interview Prep, Project Euler, and Rosetta Code. + +A free, professional Foundational C# with Microsoft Certification is also available. + +### The Learning Platform + +This code is running live at [freeCodeCamp.org](https://www.freecodecamp.org). + +Our community also has: + +- A [forum](https://forum.freecodecamp.org) where you can usually get programming help or project feedback within hours. +- A [YouTube channel](https://youtube.com/freecodecamp) with free courses on Python, SQL, Android, and a wide variety of other technologies. +- A [technical publication](https://www.freecodecamp.org/news) with thousands of programming tutorials and articles about mathematics and computer science. +- A [Discord server](https://discord.gg/Z7Fm39aNtZ) where you can hang out and talk with developers and people who are learning to code. + +> #### [Join the community here](https://www.freecodecamp.org/signin). + +### Reporting Bugs and Issues + +If you think you've found a bug, first read the [how to report a bug](https://forum.freecodecamp.org/t/how-to-report-a-bug/19543) article and follow its instructions. + +If you're confident it's a new bug and have confirmed that someone else is facing the same issue, go ahead and create a new GitHub issue. Be sure to include as much information as possible so we can reproduce the bug. + +### Reporting Security Issues and Responsible Disclosure + +We appreciate responsible disclosure of vulnerabilities that might impact the integrity of our platforms and users. + +> #### [Read our security policy and follow these steps to report a vulnerability](https://contribute.freecodecamp.org/#/security). + +### Contributing + +The freeCodeCamp.org community is possible thanks to thousands of kind volunteers like you. We welcome all contributions to the community and are excited to welcome you aboard. + +> #### [Please follow these steps to contribute](https://contribute.freecodecamp.org). + +Recent Contributions: + +![Alt](https://repobeats.axiom.co/api/embed/89be0a1a1c8f641c54f9234a7423e7755352c746.svg 'Repobeats analytics image') + +### License + +Copyright © 2014 freeCodeCamp.org + +The content of this repository is bound by the following licenses: + +- The computer software is licensed under the [BSD-3-Clause](LICENSE.md) license. +- The learning resources in the [`/curriculum`](/curriculum) directory including their subdirectories therein are copyright © 2014 freeCodeCamp.org diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/.gitignore b/github_code/freeCodeCamp__freeCodeCamp/api/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..849ddff3b7ec917b5f4563e9a6d3ea63ea512a70 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/.gitignore @@ -0,0 +1 @@ +dist/ diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/.lintstagedrc.mjs b/github_code/freeCodeCamp__freeCodeCamp/api/.lintstagedrc.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2cb8879f45f5371b6d5d5f6845e87c02e1564f7e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/.lintstagedrc.mjs @@ -0,0 +1,4 @@ +/* eslint-disable filenames-simple/naming-convention */ +import { createLintStagedConfig } from '@freecodecamp/eslint-config/lintstaged'; + +export default createLintStagedConfig(import.meta.dirname); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam-environment-exam.ts b/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam-environment-exam.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf8877d8099a4392261c5113f7d69cab0bb77c34 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam-environment-exam.ts @@ -0,0 +1,400 @@ +/* eslint-disable jsdoc/require-jsdoc */ +import { Static } from '@fastify/type-provider-typebox'; +import { + ExamEnvironmentConfig, + ExamEnvironmentQuestionType, + ExamEnvironmentExamAttempt, + ExamEnvironmentExam, + ExamEnvironmentGeneratedExam, + ExamEnvironmentQuestionSet, + ExamEnvironmentChallenge +} from '@prisma/client'; +import { ObjectId } from 'bson'; +import { examEnvironmentPostExamAttempt } from '../src/exam-environment/schemas/index.js'; + +const defaultUserId = '5bd30e0f1caf6ac3ddddddb5'; + +export const oid = () => new ObjectId().toString(); + +export const examId = oid(); + +export const config = { + totalTimeInS: 2 * 60 * 60, + tags: [], + name: 'Test Exam', + note: 'Some exam note...', + passingPercent: 80, + questionSets: [ + { + type: ExamEnvironmentQuestionType.MultipleChoice, + numberOfSet: 1, + numberOfQuestions: 1, + numberOfCorrectAnswers: 1, + numberOfIncorrectAnswers: 1 + }, + { + type: ExamEnvironmentQuestionType.MultipleChoice, + numberOfSet: 1, + numberOfQuestions: 1, + numberOfCorrectAnswers: 2, + numberOfIncorrectAnswers: 1 + }, + { + type: ExamEnvironmentQuestionType.Dialogue, + numberOfSet: 1, + numberOfQuestions: 2, + numberOfCorrectAnswers: 1, + numberOfIncorrectAnswers: 1 + } + ], + retakeTimeInS: 24 * 60 * 60 +} satisfies ExamEnvironmentConfig; + +export const questionSets: ExamEnvironmentQuestionSet[] = [ + { + id: oid(), + type: ExamEnvironmentQuestionType.MultipleChoice, + context: null, + questions: [ + { + id: oid(), + tags: ['q1t1'], + text: 'Question 1', + deprecated: false, + audio: null, + answers: [ + { + id: oid(), + text: 'Answer 1', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 2', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 3', + isCorrect: false + } + ] + } + ] + }, + { + id: oid(), + type: ExamEnvironmentQuestionType.MultipleChoice, + context: null, + questions: [ + { + id: oid(), + tags: [], + text: 'Question 1', + deprecated: false, + audio: null, + answers: [ + { + id: oid(), + text: 'Answer 1', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 2', + isCorrect: false + }, + { + id: oid(), + text: 'Answer 3', + isCorrect: false + } + ] + } + ] + }, + { + id: oid(), + type: ExamEnvironmentQuestionType.Dialogue, + context: 'Dialogue 1 context', + questions: [ + { + id: oid(), + tags: ['q1t1'], + text: 'Question 1', + deprecated: false, + audio: null, + answers: [ + { + id: oid(), + text: 'Answer 1', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 2', + isCorrect: false + }, + { + id: oid(), + text: 'Answer 3', + isCorrect: false + } + ] + }, + { + id: oid(), + tags: ['q2t1', 'q2t2'], + text: 'Question 2', + deprecated: true, + audio: { + url: 'https://freecodecamp.org', + captions: null + }, + answers: [ + { + id: oid(), + text: 'Answer 1', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 2', + isCorrect: false + }, + { + id: oid(), + text: 'Answer 3', + isCorrect: false + } + ] + }, + { + id: oid(), + tags: ['q3t1', 'q3t2'], + text: 'Question 3', + deprecated: false, + audio: null, + answers: [ + { + id: oid(), + text: 'Answer 1', + isCorrect: true + }, + { + id: oid(), + text: 'Answer 2', + isCorrect: false + }, + { + id: oid(), + text: 'Answer 3', + isCorrect: false + } + ] + } + ] + } +]; + +export const generatedExam: ExamEnvironmentGeneratedExam = { + examId, + id: oid(), + deprecated: false, + questionSets: [ + { + id: questionSets[0]!.id, + questions: [ + { + id: questionSets[0]!.questions[0]!.id, + answers: [ + questionSets[0]!.questions[0]!.answers[0]!.id, + questionSets[0]!.questions[0]!.answers[1]!.id + ] + } + ] + }, + { + id: questionSets[1]!.id, + questions: [ + { + id: questionSets[1]!.questions[0]!.id, + answers: [ + questionSets[1]!.questions[0]!.answers[0]!.id, + questionSets[1]!.questions[0]!.answers[1]!.id, + questionSets[1]!.questions[0]!.answers[2]!.id + ] + } + ] + }, + { + id: questionSets[2]!.id, + questions: [ + { + id: questionSets[2]!.questions[0]!.id, + answers: [ + questionSets[2]!.questions[0]!.answers[0]!.id, + questionSets[2]!.questions[0]!.answers[1]!.id, + questionSets[2]!.questions[0]!.answers[2]!.id + ] + }, + { + id: questionSets[2]!.questions[1]!.id, + answers: [ + questionSets[2]!.questions[1]!.answers[0]!.id, + questionSets[2]!.questions[1]!.answers[1]!.id, + questionSets[2]!.questions[1]!.answers[2]!.id + ] + } + ] + } + ], + version: 2 +}; + +export const examAttempt: ExamEnvironmentExamAttempt = { + examId, + generatedExamId: generatedExam.id, + examModerationId: null, + id: oid(), + questionSets: [ + { + id: generatedExam.questionSets[0]!.id, + questions: [ + { + id: generatedExam.questionSets[0]!.questions[0]!.id, + answers: [generatedExam.questionSets[0]!.questions[0]!.answers[0]!], + submissionTime: new Date() + } + ] + }, + { + id: generatedExam.questionSets[1]!.id, + questions: [ + { + id: generatedExam.questionSets[1]!.questions[0]!.id, + answers: [generatedExam.questionSets[1]!.questions[0]!.answers[1]!], + submissionTime: new Date() + } + ] + }, + { + id: generatedExam.questionSets[2]!.id, + questions: [ + { + id: generatedExam.questionSets[2]!.questions[0]!.id, + answers: [generatedExam.questionSets[2]!.questions[0]!.answers[1]!], + submissionTime: new Date() + }, + { + id: generatedExam.questionSets[2]!.questions[1]!.id, + answers: [generatedExam.questionSets[2]!.questions[1]!.answers[0]!], + submissionTime: new Date() + } + ] + } + ], + startTime: new Date(), + userId: defaultUserId, + version: 2 +}; + +export const examAttemptSansSubmissionTime: Static< + typeof examEnvironmentPostExamAttempt.body +>['attempt'] = { + examId, + questionSets: [ + { + id: generatedExam.questionSets[0]!.id, + questions: [ + { + id: generatedExam.questionSets[0]!.questions[0]!.id, + answers: [generatedExam.questionSets[0]!.questions[0]!.answers[0]!] + } + ] + }, + { + id: generatedExam.questionSets[1]!.id, + questions: [ + { + id: generatedExam.questionSets[1]!.questions[0]!.id, + answers: [generatedExam.questionSets[1]!.questions[0]!.answers[1]!] + } + ] + }, + { + id: generatedExam.questionSets[2]!.id, + questions: [ + { + id: generatedExam.questionSets[2]!.questions[0]!.id, + answers: [generatedExam.questionSets[2]!.questions[0]!.answers[1]!] + }, + { + id: generatedExam.questionSets[2]!.questions[1]!.id, + answers: [generatedExam.questionSets[2]!.questions[1]!.answers[0]!] + } + ] + } + ] +}; + +export const exam = { + id: examId, + config, + questionSets, + prerequisites: ['67112fe1c994faa2c26d0b1d'], + deprecated: false, + version: 2 +} satisfies ExamEnvironmentExam; + +export const examEnvironmentChallenge: ExamEnvironmentChallenge = { + id: oid(), + examId, + // Id of the certified full stack developer exam challenge page + challengeId: '645147516c245de4d11eb7ba', + version: 1 +}; + +export async function seedEnvExam() { + await clearEnvExam(); + + await fastifyTestInstance.prisma.examEnvironmentExam.create({ + data: exam + }); + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.create({ + data: generatedExam + }); + + // TODO: This would be nice to use, but the test logic for examAttempt need to account + // for dynamic ids. + // let numberOfExamsGenerated = 0; + // while (numberOfExamsGenerated < 2) { + // try { + // const generatedExam = generateExam(exam); + // await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.create({ + // data: generatedExam + // }); + // numberOfExamsGenerated++; + // } catch (_e) { + // // + // } + // } +} + +export async function clearEnvExam() { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany({}); + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.deleteMany({}); + await fastifyTestInstance.prisma.examEnvironmentExam.deleteMany({}); +} + +export async function seedEnvExamAttempt() { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: examAttempt + }); +} + +export async function seedExamEnvExamAuthToken() { + return fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.create({ + data: { userId: defaultUserId, expireAt: new Date(Date.now() + 60000) } + }); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam.ts b/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam.ts new file mode 100644 index 0000000000000000000000000000000000000000..301cfd7a8992da7ba07ae8c166f5e4d8a290a3be --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/__fixtures__/exam.ts @@ -0,0 +1,233 @@ +import { expect } from 'vitest'; + +export const examChallengeId = '647e22d18acb466c97ccbef8'; + +export const examJson = { + id: examChallengeId, + title: 'Exam Certification', + numberOfQuestionsInExam: 3, + passingPercent: 10, + prerequisites: [ + { + id: '647f85d407d29547b3bee1bb', + title: 'challenge-title' + } + ], + questions: [ + { + id: '3bbl2mx2mq', + question: 'Question 1?', + wrongAnswers: [ + { id: 'ex7hii9zup', answer: 'Q1: Wrong Answer 1' }, + { id: 'lmr1ew7m67', answer: 'Q1: Wrong Answer 2' }, + { id: 'qh5sz9qdiq', answer: 'Q1: Wrong Answer 3' }, + { id: 'g489kbwn6a', answer: 'Q1: Wrong Answer 4' }, + { id: '7vu84wl4lc', answer: 'Q1: Wrong Answer 5' }, + { id: 'em59kw6avu', answer: 'Q1: Wrong Answer 6' } + ], + correctAnswers: [ + { id: 'dzlokqdc73', answer: 'Q1: Correct Answer 1' }, + { id: 'f5gk39ske9', answer: 'Q1: Correct Answer 2' } + ] + }, + { + id: 'oqis5gzs0h', + question: 'Question 2?', + wrongAnswers: [ + { id: 'ojhnoxh5r5', answer: 'Q2: Wrong Answer 1' }, + { id: 'onx06if0uh', answer: 'Q2: Wrong Answer 2' }, + { id: 'zbxnsko712', answer: 'Q2: Wrong Answer 3' }, + { id: 'bqv5y68jyp', answer: 'Q2: Wrong Answer 4' }, + { id: 'i5xipitiss', answer: 'Q2: Wrong Answer 5' }, + { id: 'wycrnloajd', answer: 'Q2: Wrong Answer 6' } + ], + correctAnswers: [ + { id: 't9ezcsupdl', answer: 'Q2: Correct Answer 1' }, + { id: 'agert35dk0', answer: 'Q2: Correct Answer 2' } + ] + }, + { + id: 'oqis5gzs0a', + question: 'Question 3?', + wrongAnswers: [ + { id: 'ojhnoxh5ra', answer: 'Q3: Wrong Answer 1' }, + { id: 'onx06if0ub', answer: 'Q3: Wrong Answer 2' }, + { id: 'zbxnsko71c', answer: 'Q3: Wrong Answer 3' }, + { id: 'bqv5y68jyd', answer: 'Q3: Wrong Answer 4' }, + { id: 'i5xipitise', answer: 'Q3: Wrong Answer 5' }, + { id: 'wycrnloajf', answer: 'Q3: Wrong Answer 6' } + ], + correctAnswers: [ + { id: 't9ezcsupda', answer: 'Q3: Correct Answer 1' }, + { id: 'agert35dkb', answer: 'Q3: Correct Answer 2' } + ] + } + ] +}; + +export const completedTrophyChallenges = [ + { + id: '647f85d407d29547b3bee1bb', + solution: 'challenge-solution', + completedDate: 1695064765244, + files: [] + } +]; + +export type ExamSubmission = { + userExamQuestions: { + id: string; + question: string; + answer: { + id: string; + answer: string; + }; + }[]; + examTimeInSeconds: number; +}; + +// failed: 0 correct +export const examWithZeroCorrect: ExamSubmission = { + userExamQuestions: [ + { + id: '3bbl2mx2mq', + question: 'Question 1?', + answer: { id: 'g489kbwn6a', answer: 'Q1: Wrong Answer 4' } + }, + { + id: 'oqis5gzs0h', + question: 'Question 2?', + answer: { id: 'i5xipitiss', answer: 'Q2: Wrong Answer 5' } + }, + { + id: 'oqis5gzs0a', + question: 'Question 3?', + answer: { id: 'ojhnoxh5ra', answer: 'Q3: Wrong Answer 1' } + } + ], + examTimeInSeconds: 20 +}; + +// passed: 1 correct +export const examWithOneCorrect: ExamSubmission = { + userExamQuestions: [ + { + id: '3bbl2mx2mq', + question: 'Question 1?', + answer: { id: 'dzlokqdc73', answer: 'Q1: Correct Answer 1' } + }, + { + id: 'oqis5gzs0h', + question: 'Question 2?', + answer: { id: 'i5xipitiss', answer: 'Q2: Wrong Answer 5' } + }, + { + id: 'oqis5gzs0a', + question: 'Question 3?', + answer: { id: 'ojhnoxh5ra', answer: 'Q3: Wrong Answer 1' } + } + ], + examTimeInSeconds: 20 +}; + +// passed: 2 correct +export const examWithTwoCorrect: ExamSubmission = { + userExamQuestions: [ + { + id: '3bbl2mx2mq', + question: 'Question 1?', + answer: { id: 'dzlokqdc73', answer: 'Q1: Correct Answer 1' } + }, + { + id: 'oqis5gzs0h', + question: 'Question 2?', + answer: { id: 't9ezcsupdl', answer: 'Q2: Correct Answer 1' } + }, + { + id: 'oqis5gzs0a', + question: 'Question 3?', + answer: { id: 'ojhnoxh5ra', answer: 'Q3: Wrong Answer 1' } + } + ], + examTimeInSeconds: 20 +}; + +// passed: 3 correct +export const examWithAllCorrect: ExamSubmission = { + userExamQuestions: [ + { + id: '3bbl2mx2mq', + question: 'Question 1?', + answer: { id: 'dzlokqdc73', answer: 'Q1: Correct Answer 1' } + }, + { + id: 'oqis5gzs0h', + question: 'Question 2?', + answer: { id: 't9ezcsupdl', answer: 'Q2: Correct Answer 1' } + }, + { + id: 'oqis5gzs0a', + question: 'Question 3?', + answer: { id: 'agert35dkb', answer: 'Q3: Correct Answer 2' } + } + ], + examTimeInSeconds: 20 +}; + +export const mockResultsZeroCorrect = { + numberOfCorrectAnswers: 0, + numberOfQuestionsInExam: 3, + percentCorrect: 0, + passingPercent: 10, + passed: false, + examTimeInSeconds: 20 +}; + +export const mockResultsOneCorrect = { + numberOfCorrectAnswers: 1, + numberOfQuestionsInExam: 3, + percentCorrect: 33.3, + passingPercent: 10, + passed: true, + examTimeInSeconds: 20 +}; + +export const mockResultsTwoCorrect = { + numberOfCorrectAnswers: 2, + numberOfQuestionsInExam: 3, + percentCorrect: 66.7, + passingPercent: 10, + passed: true, + examTimeInSeconds: 20 +}; + +export const mockResultsAllCorrect = { + numberOfCorrectAnswers: 3, + numberOfQuestionsInExam: 3, + percentCorrect: 100, + passingPercent: 10, + passed: true, + examTimeInSeconds: 20 +}; + +const completedExamChallenge = { + id: examChallengeId, + challengeType: 17, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + completedDate: expect.any(Number) +}; + +export const completedExamChallengeOneCorrect = { + ...completedExamChallenge, + examResults: mockResultsOneCorrect +}; + +export const completedExamChallengeTwoCorrect = { + ...completedExamChallenge, + examResults: mockResultsTwoCorrect +}; + +export const completedExamChallengeAllCorrect = { + ...completedExamChallenge, + examResults: mockResultsAllCorrect +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/eslint.config.js b/github_code/freeCodeCamp__freeCodeCamp/api/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..039bd56bfbfbc45777a1f68b4b71fe828bd4905e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/eslint.config.js @@ -0,0 +1,36 @@ +import { configTypeChecked, tsFiles } from '@freecodecamp/eslint-config/base'; + +import jsdoc from 'eslint-plugin-jsdoc'; + +/** + * A shared ESLint configuration for the repository. + * + * @type {import("eslint").Linter.Config[]} + * */ +export default [ + ...configTypeChecked, + { + ...jsdoc.configs['flat/recommended-typescript-error'], + rules: { + 'jsdoc/require-jsdoc': [ + 'error', + { + require: { + ArrowFunctionExpression: true, + ClassDeclaration: true, + ClassExpression: true, + FunctionDeclaration: true, + FunctionExpression: true, + MethodDefinition: true + }, + + publicOnly: true + } + ], + + 'jsdoc/require-description-complete-sentence': 'error', + 'jsdoc/tag-lines': 'off' + }, + files: tsFiles + } +]; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/package.json b/github_code/freeCodeCamp__freeCodeCamp/api/package.json new file mode 100644 index 0000000000000000000000000000000000000000..908f94d8ea681378b12927691b7eeb88f4ee7646 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/package.json @@ -0,0 +1,95 @@ +{ + "author": "freeCodeCamp ", + "bugs": { + "url": "https://github.com/freeCodeCamp/freeCodeCamp/issues" + }, + "dependencies": { + "@fastify/accepts": "5.0.4", + "@fastify/cookie": "11.0.2", + "@fastify/csrf-protection": "7.1.0", + "@fastify/oauth2": "8.2.0", + "@fastify/swagger": "9.7.0", + "@fastify/swagger-ui": "5.2.6", + "@fastify/type-provider-typebox": "6.1.0", + "@freecodecamp/shared": "workspace:*", + "@growthbook/growthbook": "1.6.5", + "@prisma/client": "6.19.3", + "@sentry/node": "10.55.0", + "@sentry/profiling-node": "10.55.0", + "ajv": "8.20.0", + "ajv-formats": "3.0.1", + "bson": "7.2.0", + "date-fns": "4.1.0", + "date-fns-tz": "3.2.0", + "dotenv": "16.6.1", + "fast-uri": "2.4.0", + "fastify": "5.8.5", + "fastify-plugin": "5.1.0", + "joi": "17.13.3", + "jsonwebtoken": "9.0.3", + "lodash": "4.18.1", + "lodash-es": "4.18.1", + "nanoid": "3", + "no-profanity": "1.5.1", + "nodemailer": "6.10.1", + "pino": "9.14.0", + "pino-pretty": "10.3.1", + "query-string": "7.1.3", + "stripe": "16.12.0", + "typebox": "1.1.35", + "validator": "13.15.35" + }, + "description": "The freeCodeCamp.org open-source codebase and curriculum", + "devDependencies": { + "@freecodecamp/curriculum": "workspace:*", + "@freecodecamp/eslint-config": "workspace:*", + "@freecodecamp/shared": "workspace:*", + "@total-typescript/ts-reset": "0.6.1", + "@types/jsonwebtoken": "9.0.5", + "@types/lodash-es": "^4.17.12", + "@types/node": "^24.10.8", + "@types/nodemailer": "6.4.23", + "@types/supertest": "2.0.16", + "@types/validator": "13.15.10", + "@vitest/ui": "^4.0.15", + "dotenv-cli": "7.4.4", + "eslint": "^9.39.1", + "eslint-plugin-jsdoc": "48.11.0", + "msw": "^2.12.10", + "prisma": "6.19.3", + "supertest": "6.3.4", + "tsx": "4.21.0", + "typescript": "5.9.3", + "vitest": "^4.0.15" + }, + "engines": { + "node": ">=24", + "npm": ">=8" + }, + "homepage": "https://github.com/freeCodeCamp/freeCodeCamp#readme", + "license": "BSD-3-Clause", + "main": "none", + "name": "@freecodecamp/api", + "type": "module", + "private": true, + "repository": { + "type": "git", + "url": "git+https://github.com/freeCodeCamp/freeCodeCamp.git" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "clean": "rm -rf dist", + "develop": "tsx watch --clear-screen=false src/server.ts", + "start": "FREECODECAMP_NODE_ENV=production node dist/server.js", + "lint": "eslint --max-warnings 0", + "test": "vitest run", + "test:watch": "vitest", + "test:ui": "vitest --ui", + "type-check": "tsc --noEmit", + "prisma": "dotenv -e ../.env prisma", + "postinstall": "prisma generate", + "exam-env:seed": "tsx tools/exam-environment/seed/index.ts", + "exam-env:test": "tsx tools/exam-environment/test/index.ts" + }, + "version": "0.0.1" +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/prisma.config.ts b/github_code/freeCodeCamp__freeCodeCamp/api/prisma.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6fbe2e51db65a3acac3182ea5bdc35d850bbf07 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/prisma.config.ts @@ -0,0 +1,5 @@ +import type { PrismaConfig } from 'prisma'; + +export default { + schema: 'prisma' +} satisfies PrismaConfig; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-creator.prisma b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-creator.prisma new file mode 100644 index 0000000000000000000000000000000000000000..c575e91eb0b2f7d66f7f92997ea1272ce841b150 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-creator.prisma @@ -0,0 +1,58 @@ +/// A copy of `ExamEnvironmentExam` used as a staging collection for updates to the curriculum. +/// +/// This collection schema must be kept in sync with `ExamEnvironmentExam`. +model ExamCreatorExam { + /// Globally unique exam id + id String @id @default(auto()) @map("_id") @db.ObjectId + /// All questions for a given exam + questionSets ExamEnvironmentQuestionSet[] + /// Configuration for exam metadata + config ExamEnvironmentConfig + /// ObjectIds for required challenges/blocks to take the exam + prerequisites String[] @db.ObjectId + /// If `deprecated`, the exam should no longer be considered for users + deprecated Boolean + /// Version of the record + /// The default must be incremented by 1, if anything in the schema changes + version Int @default(3) +} + +/// Exam Creator application collection to store authZ users. +/// +/// Currently, this is manually created in order to grant access to the application. +model ExamCreatorUser { + id String @id @default(auto()) @map("_id") @db.ObjectId + email String + /// Unique id from GitHub for an account. + /// + /// Currently, this is unused. Consider removing. + github_id Int? + name String + picture String? + settings ExamCreatorUserSettings + version Int @default(2) + + ExamCreatorSession ExamCreatorSession[] +} + +type ExamCreatorUserSettings { + databaseEnvironment ExamCreatorDatabaseEnvironment +} + +enum ExamCreatorDatabaseEnvironment { + Production + Staging +} + +/// Exam Creator application collection to store auth sessions. +model ExamCreatorSession { + id String @id @default(auto()) @map("_id") @db.ObjectId + user_id String @db.ObjectId + session_id String + /// Expiration date for record. + expires_at DateTime + + version Int @default(1) + + ExamCreatorUser ExamCreatorUser @relation(fields: [user_id], references: [id]) +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-environment.prisma b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-environment.prisma new file mode 100644 index 0000000000000000000000000000000000000000..6e2c70081b2714727ea0b0f64a9cdb3ab3d289d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/exam-environment.prisma @@ -0,0 +1,255 @@ +/// An exam for the Exam Environment App as designed by the examiners +model ExamEnvironmentExam { + /// Globally unique exam id + id String @id @default(auto()) @map("_id") @db.ObjectId + /// All questions for a given exam + questionSets ExamEnvironmentQuestionSet[] + /// Configuration for exam metadata + config ExamEnvironmentConfig + /// ObjectIds for required challenges/blocks to take the exam + prerequisites String[] @db.ObjectId + /// If `deprecated`, the exam should no longer be considered for users + deprecated Boolean + /// Version of the record + /// The default must be incremented by 1, if anything in the schema changes + version Int @default(3) + + // Relations + generatedExams ExamEnvironmentGeneratedExam[] + examAttempts ExamEnvironmentExamAttempt[] + ExamEnvironmentChallenge ExamEnvironmentChallenge[] +} + +/// A grouping of one or more questions of a given type +type ExamEnvironmentQuestionSet { + /// Unique question type id + id String @db.ObjectId + type ExamEnvironmentQuestionType + /// Content related to all questions in set + context String? + questions ExamEnvironmentMultipleChoiceQuestion[] +} + +/// A multiple choice question for the Exam Environment App +type ExamEnvironmentMultipleChoiceQuestion { + /// Unique question id + id String @db.ObjectId + /// Main question paragraph + text String + /// Zero or more tags given to categorize a question + tags String[] + /// Optional audio for a question + audio ExamEnvironmentAudio? + /// Available possible answers for an exam + answers ExamEnvironmentAnswer[] + /// TODO Possible "deprecated_time" to remove after all exams could possibly have been taken + deprecated Boolean +} + +/// Audio for an Exam Environment App multiple choice question +type ExamEnvironmentAudio { + /// Optional text for audio + captions String? + /// URL to audio file + /// + /// Expected in the format: `#t=,` + /// Where `start_time_in_seconds` and `end_time_in_seconds` are optional floats. + url String +} + +/// Type of question for the Exam Environment App +enum ExamEnvironmentQuestionType { + /// Single question with one or more answers + MultipleChoice + /// Mass text + Dialogue +} + +/// Answer for an Exam Environment App multiple choice question +type ExamEnvironmentAnswer { + /// Unique answer id + id String @db.ObjectId + /// Whether the answer is correct + isCorrect Boolean + /// Answer paragraph + text String +} + +/// Configuration for an exam in the Exam Environment App +type ExamEnvironmentConfig { + /// Human-readable exam name + name String + /// Notes given about exam + note String + /// Category configuration for question selection + tags ExamEnvironmentTagConfig[] + /// Total time allocated for exam in seconds + totalTimeInS Int + /// Configuration for sets of questions + questionSets ExamEnvironmentQuestionSetConfig[] + /// Duration after exam completion before a retake is allowed in seconds + retakeTimeInS Int + /// Passing percent for the exam + passingPercent Float +} + +/// Configuration for a set of questions in the Exam Environment App +type ExamEnvironmentQuestionSetConfig { + type ExamEnvironmentQuestionType + /// Number of this grouping of questions per exam + numberOfSet Int + /// Number of multiple choice questions per grouping matching this set config + numberOfQuestions Int + /// Number of correct answers given per multiple choice question + numberOfCorrectAnswers Int + /// Number of incorrect answers given per multiple choice question + numberOfIncorrectAnswers Int +} + +/// Configuration for tags in the Exam Environment App +/// +/// This configures the number of questions that should resolve to a given tag set criteria. +type ExamEnvironmentTagConfig { + /// Group of multiple choice question tags + group String[] + /// Number of multiple choice questions per exam that should meet the group criteria + numberOfQuestions Int +} + +/// An attempt at an exam in the Exam Environment App +model ExamEnvironmentExamAttempt { + id String @id @default(auto()) @map("_id") @db.ObjectId + /// Foriegn key to user + userId String @db.ObjectId + /// Foreign key to exam + examId String @db.ObjectId + /// Foreign key to generated exam id + generatedExamId String @db.ObjectId + /// Un-enforced foreign key to moderation + examModerationId String? @db.ObjectId + + questionSets ExamEnvironmentQuestionSetAttempt[] + /// Time exam was started + startTime DateTime + /// Version of the record + /// The default must be incremented by 1, if anything in the schema changes + version Int @default(4) + + // Relations + user user @relation(fields: [userId], references: [id], onDelete: Cascade) + exam ExamEnvironmentExam @relation(fields: [examId], references: [id], onDelete: Cascade) + generatedExam ExamEnvironmentGeneratedExam @relation(fields: [generatedExamId], references: [id]) + // Ideally, there could be a way to add a one-way optional relation here, but Prisma does not allow that: + // Error parsing attribute "@relation": The relation fields `examAttempt` on Model `ExamEnvironmentExamModeration` and `examModeration` on Model `ExamEnvironmentExamAttempt` both provide the `references` argument in the @relation attribute. You have to provide it only on one of the two fields. + // examModeration ExamEnvironmentExamModeration? @relation(fields: [examModerationId], references: [id]) + examEnvironmentExamModeration ExamEnvironmentExamModeration? +} + +type ExamEnvironmentQuestionSetAttempt { + id String @db.ObjectId + questions ExamEnvironmentMultipleChoiceQuestionAttempt[] +} + +type ExamEnvironmentMultipleChoiceQuestionAttempt { + /// Foreign key to question + id String @db.ObjectId + /// An array of foreign keys to answers + answers String[] @db.ObjectId + /// Time answers to question were submitted + /// + /// If the question is later revisited, this field is updated + submissionTime DateTime +} + +/// A generated exam for the Exam Environment App +/// +/// This is the user-facing information for an exam. +model ExamEnvironmentGeneratedExam { + id String @id @default(auto()) @map("_id") @db.ObjectId + /// Foreign key to exam + examId String @db.ObjectId + questionSets ExamEnvironmentGeneratedQuestionSet[] + /// If `deprecated`, the generation should not longer be considered for users + deprecated Boolean + /// Version of the record + /// The default must be incremented by 1, if anything in the schema changes + version Int @default(1) + + // Relations + exam ExamEnvironmentExam @relation(fields: [examId], references: [id], onDelete: Cascade) + EnvExamAttempt ExamEnvironmentExamAttempt[] +} + +type ExamEnvironmentGeneratedQuestionSet { + id String @db.ObjectId + questions ExamEnvironmentGeneratedMultipleChoiceQuestion[] +} + +type ExamEnvironmentGeneratedMultipleChoiceQuestion { + /// Foreign key to question id + id String @db.ObjectId + /// Each item is a foreign key to an answer + answers String[] @db.ObjectId +} + +/// A map between challenge ids and exam ids +/// +/// This is expected to be used for relating challenge pages AND/OR certifications to exams +model ExamEnvironmentChallenge { + id String @id @default(auto()) @map("_id") @db.ObjectId + examId String @db.ObjectId + challengeId String @db.ObjectId + + version Int @default(1) + + exam ExamEnvironmentExam @relation(fields: [examId], references: [id], onDelete: Cascade) +} + +model ExamEnvironmentAuthorizationToken { + /// An ObjectId is used to provide access to the created timestamp + id String @id @default(auto()) @map("_id") @db.ObjectId + /// Used to set an `expireAt` index to delete documents + expireAt DateTime @db.Date + userId String @unique @db.ObjectId + version Int @default(1) + + // Relations + user user @relation(fields: [userId], references: [id], onDelete: Cascade) +} + +model ExamEnvironmentExamModeration { + id String @id @default(auto()) @map("_id") @db.ObjectId + /// Whether or not the item is approved + status ExamEnvironmentExamModerationStatus + /// Foreign key to exam attempt + examAttemptId String @unique @db.ObjectId + /// Optional feedback/note about the moderation decision + feedback String? + /// Date the exam attempt was moderated + moderationDate DateTime? + /// Foreign key to moderator. This is `null` until the item is moderated. + moderatorId String? @db.ObjectId + + /// Date the exam attempt expired + submissionDate DateTime @default(now()) @db.Date + /// Whether the `challengeId` for the `ExamEnvironmentChallenge` has been awarded to the user + challengesAwarded Boolean @default(false) + /// Score between 0 and 1 calculated by Exam Services + moderationScore Float? + + /// Version of the record + /// The default must be incremented by 1, if anything in the schema changes + version Int @default(3) + + // Relations + examAttempt ExamEnvironmentExamAttempt @relation(fields: [examAttemptId], references: [id], onDelete: Cascade) +} + +enum ExamEnvironmentExamModerationStatus { + /// Attempt is determined to be valid + Approved + /// Attempt is determined to be invalid + Denied + /// Attempt has yet to be moderated + Pending +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/prisma/schema.prisma b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/schema.prisma new file mode 100644 index 0000000000000000000000000000000000000000..28082d5e1aa0a35595611281b7563267087c6138 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/prisma/schema.prisma @@ -0,0 +1,376 @@ +generator client { + provider = "prisma-client-js" + binaryTargets = ["native", "linux-musl-openssl-3.0.x"] +} + +datasource db { + provider = "mongodb" + url = env("MONGOHQ_URL") +} + +// USER COLLECTION --------------------- + +type File { + contents String + ext String + key String + name String + path String? // Undefined | Null +} + +type CompletedChallenge { + challengeType Json? // Null | Undefined | String | Int + completedDate Json // DateTime | Float, but not, as far as we know, Null + files File[] + githubLink String? // Undefined + id String + isManuallyApproved Boolean? // Undefined + solution String? // Null | Undefined + examResults ExamResults? // Undefined +} + +enum DailyCodingChallengeLanguage { + javascript + python +} + +type CompletedDailyCodingChallenge { + id String @db.ObjectId + /// Date in milliseconds since epoch + /// This is not a DateTime, because DateTime does not serialize directly to JSON + completedDate Int + languages DailyCodingChallengeLanguage[] +} + +type PartiallyCompletedChallenge { + id String + completedDate Float +} + +type Portfolio { + description String + id String + image String + title String + url String +} + +type Experience { + id String + title String + company String + location String? + startDate String + endDate String? + description String +} + +type ProfileUI { + isLocked Boolean? // Undefined + showAbout Boolean? // Undefined + showCerts Boolean? // Undefined + showDonation Boolean? // Undefined + showHeatMap Boolean? // Undefined + showLocation Boolean? // Undefined + showName Boolean? // Undefined + showPoints Boolean? // Undefined + showPortfolio Boolean? // Undefined + showExperience Boolean? // Undefined + showTimeLine Boolean? // Undefined +} + +type SavedChallengeFile { + contents String + ext String + history String[] + key String + name String +} + +type SavedChallenge { + files SavedChallengeFile[] + id String + lastSavedDate Float +} + +type QuizAttempt { + challengeId String + quizId String + timestamp Float +} + +/// Corresponds to the `user` collection. +model user { + id String @id @default(auto()) @map("_id") @db.ObjectId + about String + acceptedPrivacyTerms Boolean + completedChallenges CompletedChallenge[] + completedDailyCodingChallenges CompletedDailyCodingChallenge[] + completedExams CompletedExam[] // Undefined + quizAttempts QuizAttempt[] // Undefined + currentChallengeId String? + donationEmails String[] // Undefined | String[] (only possible for built in Types like String) + email String? + emailAuthLinkTTL DateTime? // Null | Undefined + emailVerified Boolean? + emailVerifyTTL DateTime? // Null | Undefined + externalId String + githubProfile String? // Undefined + isA2EnglishCert Boolean? // Undefined + isApisMicroservicesCert Boolean? // Undefined + isBackEndCert Boolean? // Undefined + isBanned Boolean? // Undefined + isCheater Boolean? // Undefined + isDataAnalysisPyCertV7 Boolean? // Undefined + isDataVisCert Boolean? // Undefined + isDonating Boolean + isFoundationalCSharpCertV8 Boolean? // Undefined + isFrontEndCert Boolean? // Undefined + isFrontEndLibsCert Boolean? // Undefined + isFullStackCert Boolean? // Undefined + isHonest Boolean? + isInfosecCertV7 Boolean? // Undefined + isInfosecQaCert Boolean? // Undefined + isJavascriptCertV9 Boolean? // Undefined + isJsAlgoDataStructCert Boolean? // Undefined + isJsAlgoDataStructCertV8 Boolean? // Undefined + isMachineLearningPyCertV7 Boolean? // Undefined + isPythonCertV9 Boolean? // Undefined + isQaCertV7 Boolean? // Undefined + isRelationalDatabaseCertV8 Boolean? // Undefined + isRelationalDatabaseCertV9 Boolean? // Undefined + isRespWebDesignCert Boolean? // Undefined + isRespWebDesignCertV9 Boolean? // Undefined + isSciCompPyCertV7 Boolean? // Undefined + is2018DataVisCert Boolean? // Undefined + is2018FullStackCert Boolean? // Undefined + isCollegeAlgebraPyCertV8 Boolean? // Undefined + isFrontEndLibsCertV9 Boolean? // Undefined + isBackEndDevApisCertV9 Boolean? // Undefined + isFullStackDeveloperCertV9 Boolean? // Undefined + isB1EnglishCert Boolean? // Undefined + isA2SpanishCert Boolean? // Undefined + isA2ChineseCert Boolean? // Undefined + isA1ChineseCert Boolean? // Undefined + // isUpcomingPythonCertV8 Boolean? // Undefined. It is in the db but has never been used. + keyboardShortcuts Boolean? // Undefined + linkedin String? // Null | Undefined + location String? // Null + name String? // Null + needsModeration Boolean? // Undefined + newEmail String? // Null | Undefined + partiallyCompletedChallenges PartiallyCompletedChallenge[] // Undefined | PartiallyCompletedChallenge[] + password String? // Undefined + picture String? + portfolio Portfolio[] + experience Experience[] + profileUI ProfileUI? // Undefined + progressTimestamps Json? // ProgressTimestamp[] | Null[] | Int64[] | Double[] - TODO: NORMALIZE + /// A random number between 0 and 1. + /// + /// Valuable for selectively performing random logic. + rand Float? + savedChallenges SavedChallenge[] // Undefined | SavedChallenge[] + // Nullable tri-state: null (likely new user), true (subscribed), false (unsubscribed) + sendQuincyEmail Boolean? + socrates Boolean? + theme String? // Undefined + timezone String? // Undefined + twitter String? // Null | Undefined + bluesky String? // Null | Undefined + unsubscribeId String + /// Used to track the number of times the user's record was written to. + /// + /// This has the main benefit of allowing concurrent ops to check for race conditions. + updateCount Int? @default(0) + username String // TODO(Post-MVP): make this unique + usernameDisplay String? // Undefined + verificationToken String? // Undefined + website String? // Undefined + yearsTopContributor String[] // Undefined | String[] + isClassroomAccount Boolean? // Undefined + + // Relations + examAttempts ExamEnvironmentExamAttempt[] + examEnvironmentAuthorizationToken ExamEnvironmentAuthorizationToken? +} + +// ----------------------------------- + +model AccessToken { + id String @id @map("_id") + created DateTime @db.Date + ttl Int + userId String @db.ObjectId + + @@index([userId], map: "userId_1") +} + +model AuthToken { + id String @id @map("_id") + created DateTime @db.Date + ttl Int + userId String @db.ObjectId +} + +model Donation { + id String @id @default(auto()) @map("_id") @db.ObjectId + amount Int @db.Int + customerId String + duration String? + email String + endDate DonationEndDate? + provider String + startDate DonationStartDate + subscriptionId String + userId String @db.ObjectId + + @@index([email], map: "email_1") + @@index([userId], map: "userId_1") +} + +model SocratesUsage { + id String @id @default(auto()) @map("_id") @db.ObjectId + userId String @db.ObjectId + /// UTC date representing the day of usage (midnight). + date DateTime @db.Date + /// Number of hints used on this day. + count Int @default(0) + + @@unique([userId, date]) +} + +model UserToken { + id String @id @map("_id") + created DateTime @db.Date + ttl Float + userId String @db.ObjectId + + @@index([userId], map: "userId_1") +} + +model sessions { + id String @id @map("_id") + expires DateTime @db.Date + session String + + @@index([expires], map: "expires_1") +} + +model MsUsername { + id String @id @default(auto()) @map("_id") @db.ObjectId + userId String @db.ObjectId + ttl Int + msUsername String + + @@index([userId, id], map: "userId_1__id_1") + @@index([msUsername], map: "msUsername_1") +} + +model Exam { + id String @id @map("_id") @db.ObjectId + numberOfQuestionsInExam Int @db.Int + passingPercent Int @db.Int + prerequisites Prerequisite[] // undefined | Prerequisite[] + title String + questions Question[] +} + +type CompletedExam { + id String + challengeType Int + completedDate Float // TODO(Post-MVP): Change to DateTime? + examResults ExamResults +} + +type ExamResults { + numberOfCorrectAnswers Int + numberOfQuestionsInExam Int + percentCorrect Float + passingPercent Int + passed Boolean + examTimeInSeconds Int +} + +type Question { + id String + question String + wrongAnswers Answer[] + correctAnswers Answer[] + deprecated Boolean? // undefined +} + +type Answer { + id String + answer String + deprecated Boolean? // undefined +} + +type Prerequisite { + id String @db.ObjectId + title String +} + +type DonationEndDate { + date DateTime @map("_date") @db.Date + when String @map("_when") +} + +type DonationStartDate { + date DateTime @map("_date") @db.Date + when String @map("_when") +} + +model Survey { + id String @id @default(auto()) @map("_id") @db.ObjectId + userId String @db.ObjectId + title String + responses SurveyResponse[] + + @@index([userId], map: "userId_1") +} + +type SurveyResponse { + question String + response String +} + +// ---------------------- + +model DailyCodingChallenges { + id String @id @default(auto()) @map("_id") @db.ObjectId + challengeNumber Int + date DateTime + title String + description String + javascript DailyCodingChallengeApiLanguage + python DailyCodingChallengeApiLanguage +} + +type DailyCodingChallengeApiLanguage { + tests DailyCodingChallengeApiLanguageTests[] + challengeFiles DailyCodingChallengeApiLanguageChallengeFiles[] +} + +type DailyCodingChallengeApiLanguageTests { + text String + testString String +} + +type DailyCodingChallengeApiLanguageChallengeFiles { + contents String + fileKey String +} + +// ---------------------- + +model DripCampaign { + id String @id @default(auto()) @map("_id") @db.ObjectId + userId String @db.ObjectId + creationDate DateTime @default(now()) @db.Date + email String + variant String + + @@index([userId], map: "userId_1") + @@index([email], map: "email_1") +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/app.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/app.ts new file mode 100644 index 0000000000000000000000000000000000000000..73ff20ce39105152269e537846c6d4650f0a320a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/app.ts @@ -0,0 +1,250 @@ +import fastifyAccepts from '@fastify/accepts'; +import fastifySwagger from '@fastify/swagger'; +import fastifySwaggerUI from '@fastify/swagger-ui'; +import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox'; +import uriResolver from 'fast-uri'; +import Fastify, { + FastifyBaseLogger, + FastifyHttpOptions, + FastifyInstance, + RawReplyDefaultExpression, + RawRequestDefaultExpression, + RawServerDefault +} from 'fastify'; +import { Ajv } from 'ajv'; +import addFormats from 'ajv-formats'; + +import prismaPlugin from './db/prisma.js'; +import cookies from './plugins/cookies.js'; +import cors from './plugins/cors.js'; +import { createMailProvider } from './plugins/mail-providers/nodemailer.js'; +import mailer from './plugins/mailer.js'; +import redirectWithMessage from './plugins/redirect-with-message.js'; +import security from './plugins/security.js'; +import auth from './plugins/auth.js'; +import bouncer from './plugins/bouncer.js'; +import errorHandling from './plugins/error-handling.js'; +import runtimeMetrics from './plugins/runtime-metrics.js'; +import csrf from './plugins/csrf.js'; +import notFound from './plugins/not-found.js'; +import growthBook from './plugins/growth-book.js'; +import serviceBearerAuth from './plugins/service-bearer-auth.js'; + +import * as publicRoutes from './routes/public/index.js'; +import * as protectedRoutes from './routes/protected/index.js'; +import { classroomRoutes } from './routes/apps/classroom.js'; + +import { + API_LOCATION, + FCC_ENABLE_DEV_LOGIN_MODE, + FCC_ENABLE_SWAGGER_UI, + FCC_ENABLE_SENTRY_ROUTES, + FCC_ENABLE_CLASSROOM, + FREECODECAMP_NODE_ENV, + GROWTHBOOK_FASTIFY_API_HOST, + GROWTHBOOK_FASTIFY_CLIENT_KEY +} from './utils/env.js'; +import { isObjectID } from './utils/validation.js'; +import { bindRouteToLogger, genReqId, getLogger } from './utils/logger.js'; +import { recordHttpMetrics } from './utils/http-metrics.js'; +import { + examEnvironmentOpenRoutes, + examEnvironmentValidatedTokenRoutes +} from './exam-environment/routes/exam-environment.js'; +import { dailyCodingChallengeRoutes } from './daily-coding-challenge/routes/daily-coding-challenge.js'; + +type FastifyInstanceWithTypeProvider = FastifyInstance< + RawServerDefault, + RawRequestDefaultExpression, + RawReplyDefaultExpression, + FastifyBaseLogger, + TypeBoxTypeProvider +>; + +// Options that fastify uses +const ajv = new Ajv({ + coerceTypes: 'array', // change data type of data to match type keyword + useDefaults: true, // replace missing properties and items with the values from corresponding default keyword + removeAdditional: 'all', // remove additional properties + uriResolver, + addUsedSchema: false, + // Explicitly set allErrors to `false`. + // When set to `true`, a DoS attack is possible. + allErrors: false +}); + +// add the default formatters from avj-formats +addFormats.default(ajv); +ajv.addFormat('objectid', { + type: 'string', + validate: (str: string) => isObjectID(str) +}); + +export const buildOptions: FastifyHttpOptions< + RawServerDefault, + FastifyBaseLogger +> = { + loggerInstance: getLogger(), + genReqId, + // destroy all connections on close to avoid EADDRINUSE + // on restart, in development. Leave default in production. + forceCloseConnections: + FREECODECAMP_NODE_ENV === 'production' ? ('idle' as const) : true +}; + +/** + * Top-level wrapper to instantiate the API server. This is where all middleware and + * routes should be mounted. + * + * @param options The options to pass to the Fastify constructor. + * @returns The instantiated Fastify server, with TypeBox. + */ +export const build = async ( + options: FastifyHttpOptions = {} +): Promise => { + // TODO: Old API returns 403s for failed validation. We now return 400 (default) from AJV. + // Watch when implementing in client + const fastify = Fastify(options).withTypeProvider(); + + fastify.setValidatorCompiler(({ schema }) => ajv.compile(schema)); + + fastify.addHook('onRequest', bindRouteToLogger); + fastify.addHook('onResponse', recordHttpMetrics); + + void fastify.register(redirectWithMessage); + void fastify.register(security); + void fastify.register(fastifyAccepts); + void fastify.register(errorHandling); + void fastify.register(runtimeMetrics); + + await fastify.register(cors); + await fastify.register(cookies); + await fastify.register(csrf); + + await fastify.register(growthBook, { + apiHost: GROWTHBOOK_FASTIFY_API_HOST, + clientKey: GROWTHBOOK_FASTIFY_CLIENT_KEY + }); + + void fastify.register(mailer, { provider: createMailProvider() }); + + // Swagger plugin + if (FCC_ENABLE_SWAGGER_UI ?? fastify.gb.isOn('swagger-ui')) { + void fastify.register(fastifySwagger, { + openapi: { + openapi: '3.1.0', + info: { + title: 'freeCodeCamp API', + version: '1.0.0' // API version + } + } + }); + void fastify.register(fastifySwaggerUI, { + uiConfig: { + // Convert csrf_token cookie to csrf-token header + requestInterceptor: req => { + const csrfTokenCookie = document.cookie + .split(';') + .find(str => str.includes('csrf_token')); + const [_key, csrfToken] = csrfTokenCookie?.split('=') ?? []; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (csrfToken) req.headers['csrf-token'] = csrfToken.trim(); + return req; + } + } + }); + fastify.log.info(`Swagger UI available at ${API_LOCATION}/documentation`); + } + + void fastify.register(auth); + void fastify.register(notFound); + void fastify.register(prismaPlugin); + void fastify.register(bouncer); + await fastify.register(serviceBearerAuth); + + // Routes requiring authentication: + void fastify.register(async function (fastify, _opts) { + fastify.addHook('onRequest', fastify.authorize); + // CSRF protection enabled: + await fastify.register(async function (fastify, _opts) { + // TODO: bounce unauthed requests before checking CSRF token. This will + // mean moving csrfProtection into custom plugin and testing separately, + // because it's a pain to mess around with other cookies/hook order. + // eslint-disable-next-line @typescript-eslint/unbound-method + fastify.addHook('onRequest', fastify.csrfProtection); + fastify.addHook('onRequest', fastify.send401IfNoUser); + + await fastify.register(protectedRoutes.challengeRoutes); + await fastify.register(protectedRoutes.donateRoutes); + await fastify.register(protectedRoutes.socratesRoutes); + await fastify.register(protectedRoutes.protectedCertificateRoutes); + await fastify.register(protectedRoutes.settingRoutes); + await fastify.register(protectedRoutes.userRoutes); + }); + + // Routes that redirect if access is denied: + await fastify.register(async function (fastify, _opts) { + fastify.addHook('onRequest', fastify.redirectIfNoUser); + + await fastify.register(protectedRoutes.settingRedirectRoutes); + }); + }); + + // TODO: The route should not handle its own AuthZ + await fastify.register(protectedRoutes.challengeTokenRoutes); + + // CSRF protection disabled: + // Routes that work for both authenticated and unauthenticated users: + void fastify.register(async function (fastify) { + fastify.addHook('onRequest', fastify.authorize); + + await fastify.register(protectedRoutes.userGetRoutes); + }); + + // Routes for signed out users: + void fastify.register(async function (fastify) { + fastify.addHook('onRequest', fastify.authorize); + // TODO(Post-MVP): add the redirectIfSignedIn hook here, rather than in the + // mobileAuth0Routes and authRoutes plugins. + await fastify.register(publicRoutes.mobileAuth0Routes); + if (FCC_ENABLE_DEV_LOGIN_MODE) { + await fastify.register(publicRoutes.devAuthRoutes); + } else { + await fastify.register(publicRoutes.authRoutes); + } + }); + + void fastify.register(function (fastify, _opts, done) { + fastify.addHook('onRequest', fastify.authorizeExamEnvironmentToken); + fastify.addHook('onRequest', fastify.send401IfNoUser); + + void fastify.register(examEnvironmentValidatedTokenRoutes); + done(); + }); + void fastify.register(examEnvironmentOpenRoutes); + + // Service-to-service app routes (API key auth), gated by the classroom flag: + if (FCC_ENABLE_CLASSROOM ?? fastify.gb.isOn('classroom-mode')) { + void fastify.register(async function (fastify) { + fastify.addHook('onRequest', fastify.validateBearerToken); + await fastify.register(classroomRoutes, { prefix: '/apps/classroom' }); + }); + } + + if (FCC_ENABLE_SENTRY_ROUTES ?? fastify.gb.isOn('sentry-routes')) { + void fastify.register(publicRoutes.sentryRoutes); + } + + void fastify.register(publicRoutes.chargeStripeRoute); + void fastify.register(publicRoutes.signoutRoute); + void fastify.register(publicRoutes.emailSubscribtionRoutes); + void fastify.register(publicRoutes.userPublicGetRoutes); + void fastify.register(publicRoutes.unprotectedCertificateRoutes); + void fastify.register(publicRoutes.deprecatedEndpoints); + void fastify.register(publicRoutes.statusRoute); + void fastify.register(publicRoutes.unsubscribeDeprecated); + void fastify.register(dailyCodingChallengeRoutes); + + return fastify; +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/README.md b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfc547c9e3a0f92c67473b02174e3a522e45e03 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/README.md @@ -0,0 +1 @@ +Endpoints to get daily coding challenge info. Daily challenge submission still lives in the main part of the API. diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..bbd5fdbb7577601150939189132737deefad8b45 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.test.ts @@ -0,0 +1,803 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { addDays } from 'date-fns'; + +import { setupServer, superRequest } from '../../../vitest.utils.js'; + +function dateToDateParam(date: Date): string { + return date.toISOString().split('T')[0] as string; +} + +const todayUsCentral = new Date(Date.UTC(2025, 9, 2, 5)); // 2025-10-02 00:00:00 in US Central +const todayUtcMidnight = new Date(Date.UTC(2025, 9, 2, 0, 0, 0)); + +const todayDateParam = dateToDateParam(todayUtcMidnight); + +const yesterdayUtcMidnight = addDays(todayUtcMidnight, -1); + +const twoDaysAgoUtcMidnight = addDays(todayUtcMidnight, -2); +const twoDaysAgoDateParam = dateToDateParam(twoDaysAgoUtcMidnight); + +const tomorrowUtcMidnight = addDays(todayUtcMidnight, 1); +const tomorrowDateParam = dateToDateParam(tomorrowUtcMidnight); + +const yesterdaysChallenge = { + id: '111111111111111111111111', + challengeNumber: 1, + date: yesterdayUtcMidnight, + title: "Yesterday's Challenge", + description: "Yesterday's Description", + javascript: { + tests: [{ text: 'JS Test Yesterday', testString: 'jsTestYesterday()' }], + challengeFiles: [{ contents: 'JS Files Yesterday', fileKey: 'scriptjs' }] + }, + python: { + tests: [{ text: 'Py Test Yesterday', testString: 'py_test_yesterday()' }], + challengeFiles: [{ contents: 'Py Files Yesterday', fileKey: 'mainpy' }] + } +}; + +const todaysChallenge = { + id: '222222222222222222222222', + challengeNumber: 2, + date: todayUtcMidnight, + title: "Today's Challenge", + description: "Today's Description", + javascript: { + tests: [{ text: 'JS Test Today', testString: 'jsTestToday()' }], + challengeFiles: [{ contents: 'JS Files Today', fileKey: 'scriptjs' }] + }, + python: { + tests: [{ text: 'Py Test Today', testString: 'py_test_today()' }], + challengeFiles: [{ contents: 'Py Files Today', fileKey: 'mainpy' }] + } +}; + +const tomorrowsChallenge = { + id: '333333333333333333333333', + challengeNumber: 3, + date: tomorrowUtcMidnight, + title: "Tomorrow's Challenge", + description: "Tomorrow's Description", + javascript: { + tests: [{ text: 'JS Test Tomorrow', testString: 'jsTestTomorrow()' }], + challengeFiles: [{ contents: 'JS Files Tomorrow', fileKey: 'scriptjs' }] + }, + python: { + tests: [{ text: 'Py Test Tomorrow', testString: 'py_test_tomorrow()' }], + challengeFiles: [{ contents: 'Py Files Tomorrow', fileKey: 'mainpy' }] + } +}; + +const mockChallenges = [ + tomorrowsChallenge, + todaysChallenge, + yesterdaysChallenge +]; + +describe('/daily-coding-challenge', () => { + setupServer(); + // This has to happen after setupServer since it needs real timers. + beforeEach(() => { + vi.useFakeTimers({ now: todayUsCentral }); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + describe('GET /daily-coding-challenge/date/:date', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: mockChallenges + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it('should return 400 for an invalid date format', async () => { + const invalidFormats = [ + 'invalid-format', + '2025-07', + '07-18-2025', + '25-07-18', + '2025-7-18', + '2025-07-8' + ]; + + for (const invalidFormat of invalidFormats) { + const res = await superRequest( + `/daily-coding-challenge/date/${invalidFormat}`, + { + method: 'GET' + } + ).send({}); + + expect(res.status).toBe(400); + expect(res.body).toEqual({ + type: 'error', + message: 'Invalid date format. Please use YYYY-MM-DD.' + }); + } + }); + + it('should return 404 for a date without a challenge', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest( + `/daily-coding-challenge/date/${twoDaysAgoDateParam}`, + { + method: 'GET' + } + ).send({}); + + expect(res.status).toBe(404); + expect(res.body).toEqual({ + type: 'error', + message: 'Challenge not found.' + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return a challenge for a valid date', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest( + `/daily-coding-challenge/date/${todayDateParam}`, + { + method: 'GET' + } + ).send({}); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + ...todaysChallenge, + date: todaysChallenge.date.toISOString() + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should not return a challenge for a future date relative to US Central', async () => { + const res = await superRequest( + `/daily-coding-challenge/date/${tomorrowDateParam}`, + { + method: 'GET' + } + ).send({}); + expect(res.body).toEqual({ + type: 'error', + message: 'Challenge not found.' + }); + }); + }); + + describe('GET /daily-coding-challenge/day/:day', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: mockChallenges + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it('should return 400 for an invalid day format', async () => { + const invalidFormats = [ + 'invalid-format', + '2025-10-02', + '010-02', + '2025-10', + '10-2', + '1-02', + '13-45', + '04-31', + '00-15' + ]; + + for (const invalidFormat of invalidFormats) { + const res = await superRequest( + `/daily-coding-challenge/day/${invalidFormat}`, + { + method: 'GET' + } + ).send({}); + + expect(res.status).toBe(400); + expect(res.body).toEqual({ + type: 'error', + message: 'Invalid date format. Please use MM-DD.' + }); + } + }); + + it('should return 404 for a day without a challenge', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/day/09-30', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(404); + expect(res.body).toEqual({ + type: 'error', + message: 'Challenge not found.' + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/day/:day' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return a challenge for a valid day request', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/day/10-02', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + ...todaysChallenge, + date: todaysChallenge.date.toISOString() + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/day/:day' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should map a Feb 29 day request to the Feb 28 challenge', async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + + const feb28UtcMidnight = new Date(Date.UTC(2026, 1, 28)); + const feb28Challenge = { + ...todaysChallenge, + date: feb28UtcMidnight + }; + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: [feb28Challenge] + }); + + vi.setSystemTime(new Date(Date.UTC(2028, 1, 29, 6))); + + const res = await superRequest('/daily-coding-challenge/day/02-29', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + ...feb28Challenge, + date: feb28UtcMidnight.toISOString() + }); + }); + }); + + describe('GET /daily-coding-challenge/today', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: mockChallenges + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it("should return today's challenge", async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/today', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + ...todaysChallenge, + date: todaysChallenge.date.toISOString() + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return 404 when no challenge exists for today', async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/today', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(404); + expect(res.body).toEqual({ + type: 'error', + message: 'Challenge not found.' + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it("should loop back to last year's challenge on the same month/day, returning the source date rather than a real requested year", async () => { + vi.setSystemTime(addDays(todayUsCentral, 365)); + + const res = await superRequest('/daily-coding-challenge/today', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ + ...todaysChallenge, + date: todaysChallenge.date.toISOString() + }); + }); + }); + + describe('GET /daily-coding-challenge/month/:month', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: mockChallenges + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it('should return 400 for invalid month format', async () => { + const invalidFormats = ['invalid-month', '2025-13', '2025-1', '25-07']; + + for (const invalidFormat of invalidFormats) { + const res = await superRequest( + `/daily-coding-challenge/month/${invalidFormat}`, + { + method: 'GET' + } + ).send({}); + + expect(res.status).toBe(400); + expect(res.body).toEqual({ + type: 'error', + message: 'Invalid date format. Please use YYYY-MM.' + }); + } + }); + + it('should return two challenges on the second day of the month', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest(`/daily-coding-challenge/month/2025-10`, { + method: 'GET' + }).send({}); + + // Should include yesterday's and today's challenges, but not tomorrow's + const expectedResponse = [ + { + id: todaysChallenge.id, + challengeNumber: todaysChallenge.challengeNumber, + date: todaysChallenge.date.toISOString(), + title: todaysChallenge.title + }, + { + id: yesterdaysChallenge.id, + challengeNumber: yesterdaysChallenge.challengeNumber, + date: yesterdaysChallenge.date.toISOString(), + title: yesterdaysChallenge.title + } + ]; + + expect(res.body).toEqual(expectedResponse); + expect(res.status).toBe(200); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return one challenge on the first day of the month', async () => { + vi.setSystemTime(new Date(Date.UTC(2025, 9, 1, 5))); // 2025-10-01 00:00:00 in US Central + + const res = await superRequest(`/daily-coding-challenge/month/2025-10`, { + method: 'GET' + }).send({}); + + // Should include yesterday's challenges + const expectedResponse = [ + { + id: yesterdaysChallenge.id, + challengeNumber: yesterdaysChallenge.challengeNumber, + date: yesterdaysChallenge.date.toISOString(), + title: yesterdaysChallenge.title + } + ]; + + expect(res.body).toEqual(expectedResponse); + expect(res.status).toBe(200); + }); + + it('should return 200 with an empty array when no challenges exist for the given month', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/month/2024-01', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toEqual([]); + expect(count).toHaveBeenCalledWith('dcc.empty_result', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('GET /daily-coding-challenge/all', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: mockChallenges + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it('should return { _id, date, challengeNumber, title } for all challenges up to today US Central', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/all', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(Array.isArray(res.body)).toBe(true); + + // Should include yesterday's and today's challenges, but not tomorrow's + const expectedResponse = [ + { + id: todaysChallenge.id, + challengeNumber: todaysChallenge.challengeNumber, + date: todaysChallenge.date.toISOString(), + title: todaysChallenge.title + }, + { + id: yesterdaysChallenge.id, + challengeNumber: yesterdaysChallenge.challengeNumber, + date: yesterdaysChallenge.date.toISOString(), + title: yesterdaysChallenge.title + } + ]; + + expect(res.body).toHaveLength(2); + expect(res.body).toEqual(expectedResponse); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return 200 with an empty array when no challenges exist', async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/all', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toEqual([]); + expect(count).toHaveBeenCalledWith('dcc.empty_result', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should include every challenge once real time has passed all of their release dates', async () => { + vi.setSystemTime(addDays(todayUsCentral, 365)); + + const res = await superRequest('/daily-coding-challenge/all', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + + const expectedResponse = [ + { + id: tomorrowsChallenge.id, + challengeNumber: tomorrowsChallenge.challengeNumber, + date: tomorrowsChallenge.date.toISOString(), + title: tomorrowsChallenge.title + }, + { + id: todaysChallenge.id, + challengeNumber: todaysChallenge.challengeNumber, + date: todaysChallenge.date.toISOString(), + title: todaysChallenge.title + }, + { + id: yesterdaysChallenge.id, + challengeNumber: yesterdaysChallenge.challengeNumber, + date: yesterdaysChallenge.date.toISOString(), + title: yesterdaysChallenge.title + } + ]; + + expect(res.body).toHaveLength(3); + expect(res.body).toEqual(expectedResponse); + }); + }); + + describe('GET /daily-coding-challenge/newest', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.createMany({ + data: [yesterdaysChallenge, todaysChallenge, tomorrowsChallenge] + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + }); + + it('should return { date } of the newest challenge in the database', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/newest', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(200); + expect(res.body).toEqual({ + date: tomorrowsChallenge.date.toISOString() + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return 404 when no challenges exist', async () => { + await fastifyTestInstance.prisma.dailyCodingChallenges.deleteMany(); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superRequest('/daily-coding-challenge/newest', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(404); + expect(res.body).toEqual({ + type: 'error', + message: 'No challenges found.' + }); + expect(count).toHaveBeenCalledWith('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('Sentry Issue reporting', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('captures unexpected errors when getting a challenge by date', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + vi.spyOn( + fastifyTestInstance.prisma.dailyCodingChallenges, + 'findFirst' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superRequest( + `/daily-coding-challenge/date/${todayDateParam}`, + { method: 'GET' } + ).send({}); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it("captures unexpected errors when getting today's challenge", async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + vi.spyOn( + fastifyTestInstance.prisma.dailyCodingChallenges, + 'findFirst' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superRequest('/daily-coding-challenge/today', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('captures unexpected errors when getting a month of challenges', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + vi.spyOn( + fastifyTestInstance.prisma.dailyCodingChallenges, + 'findMany' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superRequest('/daily-coding-challenge/month/2025-10', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('captures unexpected errors when getting all challenges', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + vi.spyOn( + fastifyTestInstance.prisma.dailyCodingChallenges, + 'findMany' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superRequest('/daily-coding-challenge/all', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('captures unexpected errors when getting the newest challenge', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + vi.spyOn( + fastifyTestInstance.prisma.dailyCodingChallenges, + 'findFirst' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superRequest('/daily-coding-challenge/newest', { + method: 'GET' + }).send({}); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.ts new file mode 100644 index 0000000000000000000000000000000000000000..5222a06b099d2b8995bf1bf1243e0e1d1a175eba --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/routes/daily-coding-challenge.ts @@ -0,0 +1,385 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import * as schemas from '../schemas/index.js'; +import { + getNowUsCentral, + getUtcMidnight, + dateStringToUtcMidnight, + monthDayStringToUtcDate, + getSourceDate +} from '../utils/helpers.js'; + +/** + * Plugin containing public GET routes for the daily coding challenges. + * Note that they are only for getting challenge info, challenges are still + * submitted via the main challenge completion routes. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +export const dailyCodingChallengeRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get( + // Will stop returning challenges if param is after aug 10, 2026 - the last challenge date. + '/daily-coding-challenge/date/:date', + { + schema: schemas.dailyCodingChallenge.date + }, + async (req, reply) => { + req.log.info( + { date: req.params.date }, + 'Received request for daily coding challenge' + ); + + const { date } = req.params; + + try { + const parsedDate = dateStringToUtcMidnight(date); + + if (!parsedDate) { + req.log.warn({ date }, 'Invalid date format requested'); + return reply.status(400).send({ + type: 'error', + message: 'Invalid date format. Please use YYYY-MM-DD.' + }); + } + + const challenge = await fastify.prisma.dailyCodingChallenges.findFirst({ + where: { + date: parsedDate + } + }); + + // don't return challenges > today US Central + if (!challenge || challenge.date > getUtcMidnight(getNowUsCentral())) { + req.log.warn({ date: parsedDate }, 'Challenge not found for date'); + fastify.Sentry?.metrics?.count('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + return reply + .status(404) + .send({ type: 'error', message: 'Challenge not found.' }); + } + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + return reply.send({ + ...challenge, + date: challenge.date.toISOString() + }); + } catch (error) { + req.log.error(error, 'Failed to get daily coding challenge.'); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/date/:date' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + fastify.get( + '/daily-coding-challenge/day/:day', + { + schema: schemas.dailyCodingChallenge.day + }, + async (req, reply) => { + req.log.info( + { day: req.params.day }, + 'Received request for daily coding challenge by day' + ); + + const { day } = req.params; + + try { + const monthDay = monthDayStringToUtcDate(day); + + if (!monthDay) { + req.log.warn({ day }, 'Invalid day format requested'); + return reply.status(400).send({ + type: 'error', + message: 'Invalid date format. Please use MM-DD.' + }); + } + + const sourceDate = getSourceDate(monthDay); + + const challenge = await fastify.prisma.dailyCodingChallenges.findFirst({ + where: { + date: sourceDate + } + }); + + if (!challenge) { + req.log.warn({ day }, 'Challenge not found for day'); + fastify.Sentry?.metrics?.count('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/day/:day' } + }); + return reply + .status(404) + .send({ type: 'error', message: 'Challenge not found.' }); + } + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/day/:day' } + }); + return reply.send({ + ...challenge, + date: challenge.date.toISOString() + }); + } catch (error) { + req.log.error(error, 'Failed to get daily coding challenge by day.'); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/day/:day' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + fastify.get( + '/daily-coding-challenge/today', + { + schema: schemas.dailyCodingChallenge.today + }, + async (req, reply) => { + req.log.info("Received request for today's daily coding challenge"); + + const today = getUtcMidnight(getNowUsCentral()); + const sourceDate = getSourceDate(today); + + try { + const todaysChallenge = + await fastify.prisma.dailyCodingChallenges.findFirst({ + where: { + date: sourceDate + } + }); + + if (!todaysChallenge) { + req.log.warn({ date: today }, 'Challenge not found for today'); + fastify.Sentry?.metrics?.count('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + return reply + .status(404) + .send({ type: 'error', message: 'Challenge not found.' }); + } + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + return reply.send({ + ...todaysChallenge, + date: todaysChallenge.date.toISOString() + }); + } catch (error) { + req.log.error(error, "Failed to get today's daily coding challenge."); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/today' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + fastify.get( + '/daily-coding-challenge/month/:month', + { + schema: schemas.dailyCodingChallenge.month + }, + async (req, reply) => { + req.log.info( + { month: req.params.month }, + 'Received request for month of daily coding challenges' + ); + + const { month } = req.params; + + try { + // Month is guaranteed YYYY-MM format from schema validation + const parts = month.split('-'); + const parsedYear = parseInt(parts[0]!, 10); + const parsedMonth = parseInt(parts[1]!, 10); + + // Validate month range + if (parsedMonth < 1 || parsedMonth > 12) { + req.log.warn({ month }, 'Invalid month value requested'); + return reply.status(400).send({ + type: 'error', + message: 'Invalid date format. Please use YYYY-MM.' + }); + } + + const monthStart = new Date(Date.UTC(parsedYear, parsedMonth - 1, 1)); + const monthEnd = new Date(Date.UTC(parsedYear, parsedMonth, 1)); + const todayUsCentral = getUtcMidnight(getNowUsCentral()); + + const challenges = await fastify.prisma.dailyCodingChallenges.findMany({ + where: { + date: { + gte: monthStart, + lt: monthEnd, + lte: todayUsCentral + } + }, + orderBy: { + date: 'desc' + }, + select: { + id: true, + challengeNumber: true, + date: true, + title: true + } + }); + + if (!challenges || challenges.length === 0) { + fastify.Sentry?.metrics?.count('dcc.empty_result', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + return reply.send([]); + } + + const response = challenges.map(challenge => ({ + ...challenge, + date: challenge.date.toISOString() + })); + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + return reply.send(response); + } catch (error) { + req.log.error(error, 'Failed to get monthly daily coding challenges.'); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/month/:month' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + fastify.get( + '/daily-coding-challenge/all', + { + schema: schemas.dailyCodingChallenge.all + }, + async (req, reply) => { + req.log.info('Received request for all daily coding challenges'); + + const today = getUtcMidnight(getNowUsCentral()); + + try { + const allChallenges = + await fastify.prisma.dailyCodingChallenges.findMany({ + // only where date <= today US Central + where: { + date: { + lte: today + } + }, + orderBy: { + date: 'desc' + }, + select: { + id: true, + challengeNumber: true, + date: true, + title: true + } + }); + + if (!allChallenges || allChallenges.length === 0) { + fastify.Sentry?.metrics?.count('dcc.empty_result', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + return reply.send([]); + } + + const response = allChallenges.map(challenge => ({ + ...challenge, + date: challenge.date.toISOString() + })); + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + return reply.send(response); + } catch (error) { + req.log.error(error, 'Failed to get all daily coding challenges.'); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/all' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + fastify.get( + '/daily-coding-challenge/newest', + { + schema: schemas.dailyCodingChallenge.newest + }, + async (req, reply) => { + req.log.info('Received request for newest daily coding challenge'); + + try { + const newestChallenge = + await fastify.prisma.dailyCodingChallenges.findFirst({ + orderBy: { + date: 'desc' + }, + select: { + date: true + } + }); + + if (!newestChallenge) { + req.log.warn('No challenges found.'); + fastify.Sentry?.metrics?.count('dcc.challenge_not_found', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + return reply + .status(404) + .send({ type: 'error', message: 'No challenges found.' }); + } + + fastify.Sentry?.metrics?.count('dcc.challenge_viewed', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + return reply.send({ date: newestChallenge.date.toISOString() }); + } catch (error) { + req.log.error(error, 'Failed to get newest daily coding challenge.'); + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('dcc.request_failed', 1, { + attributes: { route: '/daily-coding-challenge/newest' } + }); + await reply + .status(500) + .send({ type: 'error', message: 'Internal server error.' }); + } + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/daily-coding-challenge.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/daily-coding-challenge.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ea600edaec63fbb529d8ec05410e19fd62447ed --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/daily-coding-challenge.ts @@ -0,0 +1,143 @@ +import { Type } from '@fastify/type-provider-typebox'; + +const challengeLanguage = Type.Object({ + tests: Type.Array( + Type.Object({ + text: Type.String(), + testString: Type.String() + }) + ), + challengeFiles: Type.Array( + Type.Object({ + contents: Type.String(), + fileKey: Type.String() + }) + ) +}); + +const singleChallengeResponse = Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + date: Type.String({ format: 'date-time' }), + challengeNumber: Type.Number(), + title: Type.String(), + description: Type.String(), + javascript: challengeLanguage, + python: challengeLanguage +}); + +const date = { + params: Type.Object({ + date: Type.String({ format: 'date' }) + }), + response: { + 200: singleChallengeResponse, + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Invalid date format. Please use YYYY-MM-DD.') + }), + 404: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Challenge not found.') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +const day = { + params: Type.Object({ + day: Type.String({ pattern: '^\\d{2}-\\d{2}$' }) + }), + response: { + 200: singleChallengeResponse, + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Invalid date format. Please use MM-DD.') + }), + 404: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Challenge not found.') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +const today = { + response: { + 200: singleChallengeResponse, + 404: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Challenge not found.') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +const manyChallengesResponse = Type.Array( + Type.Object({ + id: Type.String(), + date: Type.String({ format: 'date-time' }), + challengeNumber: Type.Number(), + title: Type.String() + }) +); + +const month = { + params: Type.Object({ + month: Type.String({ pattern: '^\\d{4}-\\d{2}$' }) + }), + response: { + 200: manyChallengesResponse, + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Invalid date format. Please use YYYY-MM.') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +const all = { + response: { + 200: manyChallengesResponse, + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +const newest = { + response: { + 200: Type.Object({ + date: Type.String({ format: 'date-time' }) + }), + 404: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('No challenges found.') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('Internal server error.') + }) + } +}; + +export const dailyCodingChallenge = { + date, + day, + today, + month, + all, + newest +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d5f34f91dd14715fea69e3c73cac8b9727c082c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/schemas/index.ts @@ -0,0 +1 @@ +export { dailyCodingChallenge } from './daily-coding-challenge.js'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/utils/helpers.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/utils/helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a6df8199c02b61d84a7f5c8f1768471855b1634 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/daily-coding-challenge/utils/helpers.ts @@ -0,0 +1,94 @@ +import { getTimezoneOffset } from 'date-fns-tz'; + +/** + * @returns Now US Central time. + */ +export function getNowUsCentral() { + const offset = getTimezoneOffset('America/Chicago', new Date()); + return new Date(Date.now() + offset); +} + +/** + * Returns a Date object set to UTC midnight of the given date. + * @param date - Date Object. + * @returns UTC midnight of the given date. + */ +export function getUtcMidnight(date: Date): Date { + return new Date( + Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()) + ); +} + +/** + * Parses a date string in the format "YYYY-MM-DD" and returns a Date object set to UTC midnight. + * Returns null if the input is not in the correct format. + * @param dateStr - Date string in "YYYY-MM-DD" format. + * @returns Date object set to UTC midnight or null if invalid. + */ +export function dateStringToUtcMidnight(dateStr: string): Date | null { + if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) { + return null; + } + + const [year, month, day] = dateStr.split('-').map(Number) as [ + number, + number, + number + ]; + + return new Date(Date.UTC(year, month - 1, day)); +} + +/** + * Parses a date string in the format "MM-DD" and returns a UTC-midnight date. + * @param monthDayStr - Date string in "MM-DD" format. + * @returns Date object set to UTC midnight (placeholder year) or null if invalid. + */ +export function monthDayStringToUtcDate(monthDayStr: string): Date | null { + if (!/^\d{2}-\d{2}$/.test(monthDayStr)) { + return null; + } + + const [month, day] = monthDayStr.split('-').map(Number) as [number, number]; + + // 2000 is a leap year, so Date.UTC keeps Feb 29 instead of rolling it over + const date = new Date(Date.UTC(2000, month - 1, day)); + + // Date.UTC silently rolls over out-of-range values - this catches that. + if (date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { + return null; + } + + return date; +} + +// A single year of challenges (2025-08-11 - 2026-08-10) was created. +const ORIGINAL_START_MONTH = 8; +const ORIGINAL_START_DAY = 11; +const ORIGINAL_START_YEAR = 2025; +const ORIGINAL_END_YEAR = 2026; + +/** + * Maps any UTC-midnight date to the original challenge date. + * @param date - UTC-midnight date. + * @returns UTC-midnight date within the source challenge range. + */ +export function getSourceDate(date: Date): Date { + const month = date.getUTCMonth() + 1; + let day = date.getUTCDate(); + + // Show the Feb 28 challenge for Feb 29 requests. + if (month === 2 && day === 29) { + day = 28; + } + + const isOnOrAfterCycleStart = + month > ORIGINAL_START_MONTH || + (month === ORIGINAL_START_MONTH && day >= ORIGINAL_START_DAY); + + const sourceYear = isOnOrAfterCycleStart + ? ORIGINAL_START_YEAR + : ORIGINAL_END_YEAR; + + return new Date(Date.UTC(sourceYear, month - 1, day)); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/db/extensions.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/extensions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f0a3bceb1be2faa88877169d6dbf55c5953b54b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/extensions.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect, beforeEach, afterAll } from 'vitest'; +import { defaultUserEmail, setupServer } from '../../vitest.utils.js'; + +import { createUserInput } from '../utils/create-user.js'; + +describe('prisma client extensions', () => { + setupServer(); + + beforeEach(async () => { + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: defaultUserEmail } + }); + }); + + afterAll(async () => { + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: defaultUserEmail } + }); + }); + + describe('updateCount', () => { + it('should default to 0', async () => { + const user = await fastifyTestInstance.prisma.user.create({ + data: createUserInput(defaultUserEmail) + }); + + expect(user).toMatchObject({ + updateCount: 0 + }); + }); + + it('should increment by one for updates and creates', async () => { + const user = await fastifyTestInstance.prisma.user.create({ + data: createUserInput(defaultUserEmail) + }); + + const updateUser = await fastifyTestInstance.prisma.user.update({ + where: { id: user.id }, + data: { username: 'any-change' } + }); + + expect(updateUser).toMatchObject({ + username: 'any-change', + updateCount: 1 + }); + + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: user.id }, + // Even no change to values updates the updateCount + data: { username: 'any-change' } + }); + + const updateManyUser = await fastifyTestInstance.prisma.user.findUnique({ + where: { id: user.id } + }); + + expect(updateManyUser).toMatchObject({ + username: 'any-change', + updateCount: 2 + }); + + const upsertUser = await fastifyTestInstance.prisma.user.upsert({ + where: { id: user.id }, + create: createUserInput(defaultUserEmail), + update: { username: 'upser-user' } + }); + + expect(upsertUser).toMatchObject({ + username: 'upser-user', + updateCount: 3 + }); + }); + + it("should not increment for 'find' queries", async () => { + const user = await fastifyTestInstance.prisma.user.create({ + data: createUserInput(defaultUserEmail) + }); + + const findUniqueUser = await fastifyTestInstance.prisma.user.findUnique({ + where: { id: user.id } + }); + + expect(findUniqueUser).toMatchObject({ + updateCount: 0 + }); + + const findManyUsers = await fastifyTestInstance.prisma.user.findMany(); + + expect(findManyUsers).toHaveLength(1); + expect(findManyUsers[0]).toMatchObject({ + updateCount: 0 + }); + + const findFirstUser = await fastifyTestInstance.prisma.user.findFirst(); + + expect(findFirstUser).toMatchObject({ + updateCount: 0 + }); + + const findRawUser = await fastifyTestInstance.prisma.user.findRaw({ + filter: { email: defaultUserEmail } + }); + + expect(findRawUser[0]).toMatchObject({ + updateCount: 0 + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/db/prisma.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/prisma.ts new file mode 100644 index 0000000000000000000000000000000000000000..646cdfee6a0313c003ed9902725a38d9175e0b85 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/prisma.ts @@ -0,0 +1,89 @@ +import fp from 'fastify-plugin'; +import { FastifyPluginAsync } from 'fastify'; +import { PrismaClient } from '@prisma/client'; +import * as Sentry from '@sentry/node'; + +// importing MONGOHQ_URL so we can mock it in testing. +import { MONGOHQ_URL } from '../utils/env.js'; +import { timeOperation } from './query-timing.js'; + +declare module 'fastify' { + interface FastifyInstance { + prisma: ReturnType; + } +} + +const prismaPlugin: FastifyPluginAsync = fp(async (server, _options) => { + const prisma = extendClient( + new PrismaClient({ + datasources: { + db: { + url: MONGOHQ_URL + } + } + }) + ); + + await prisma.$connect().catch((err: unknown) => { + Sentry.metrics.count('db.connect_failed', 1); + server.log.error(err, 'Prisma connection failed'); + throw err; + }); + + server.decorate('prisma', prisma); + + server.addHook('onClose', async server => { + await server.prisma.$disconnect(); + }); +}); + +// TODO: It would be nice to split this up into multiple update functions, +// but the types are a pain. +// TODO: Multiple extended clients can be used for different restrictions (e.g. session vs non-session users) +// TODO: Could be used to add other _easily forgotten_ fields like `progressTimestamp` +function extendClient(prisma: PrismaClient) { + return prisma + .$extends({ + query: { + user: { + async update({ args, query }) { + args.data.updateCount = { increment: 1 }; + return query(args); + }, + async updateMany({ args, query }) { + args.data.updateCount = { increment: 1 }; + return query(args); + }, + async upsert({ args, query }) { + args.update.updateCount = { increment: 1 }; + return query(args); + } + // NOTE: raw ops are untouched, as it is meant to be a direct passthrough to mongodb + // async findRaw({ model, operation, args, query }) {} + // async aggregateRaw({ model, operation, args, query }) {} + } + } + }) + .$extends({ + query: { + $allModels: { + $allOperations({ model, operation, args, query }) { + return timeOperation( + () => query(args), + (result, durationMs) => + Sentry.metrics.distribution( + 'db.query_duration_ms', + durationMs, + { + unit: 'millisecond', + attributes: { model: model ?? 'raw', operation, result } + } + ) + ); + } + } + } + }); +} + +export default prismaPlugin; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d8a7277c579403523ee820846e5ac54601e2ec27 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.test.ts @@ -0,0 +1,24 @@ +import { describe, it, expect, vi } from 'vitest'; + +import { timeOperation } from './query-timing.js'; + +describe('timeOperation', () => { + it('returns the result and emits success with a numeric duration', async () => { + const emit = vi.fn(); + + const result = await timeOperation(() => Promise.resolve('ok'), emit); + + expect(result).toBe('ok'); + expect(emit).toHaveBeenCalledWith('success', expect.any(Number)); + }); + + it('re-throws and emits failure when the operation rejects', async () => { + const emit = vi.fn(); + const boom = new Error('boom'); + + await expect(timeOperation(() => Promise.reject(boom), emit)).rejects.toBe( + boom + ); + expect(emit).toHaveBeenCalledWith('failure', expect.any(Number)); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.ts new file mode 100644 index 0000000000000000000000000000000000000000..9fb3b1cd0d27c0f0cb81088e65fd0b9cc87091d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/db/query-timing.ts @@ -0,0 +1,17 @@ +import { performance } from 'node:perf_hooks'; + +// eslint-disable-next-line jsdoc/require-jsdoc +export const timeOperation = async ( + op: () => Promise, + emit: (result: 'success' | 'failure', durationMs: number) => void +): Promise => { + const start = performance.now(); + try { + const result = await op(); + emit('success', performance.now() - start); + return result; + } catch (err) { + emit('failure', performance.now() - start); + throw err; + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9a3d5c0d717e61f684252c5a8a03683f17cb938f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.test.ts @@ -0,0 +1,1824 @@ +import { + describe, + it, + expect, + beforeAll, + afterAll, + beforeEach, + afterEach, + vi +} from 'vitest'; +import { ExamEnvironmentExamModerationStatus } from '@prisma/client'; +import { PrismaClientValidationError } from '@prisma/client/runtime/library.js'; +import { Static } from '@fastify/type-provider-typebox'; +import jwt from 'jsonwebtoken'; + +import { + createSuperRequest, + defaultUserId, + devLogin, + serializeDates, + setupServer +} from '../../../vitest.utils.js'; +import { + examEnvironmentPostExamAttempt, + examEnvironmentPostExamGeneratedExam +} from '../schemas/index.js'; +import * as mock from '../../../__fixtures__/exam-environment-exam.js'; +import { constructUserExam } from '../utils/exam-environment.js'; +import { getExamAttemptsHandler } from './exam-environment.js'; +import { JWT_SECRET } from '../../utils/env.js'; +import { ExamAttemptStatus } from '../schemas/exam-environment-exam-attempt.js'; + +vi.mock('../../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + DEPLOYMENT_ENV: 'production' + }; +}); + +describe('/exam-environment/', () => { + setupServer(); + describe('Authenticated user with exam environment authorization token', () => { + let superPost: ReturnType; + let superGet: ReturnType; + let examEnvironmentAuthorizationToken: string; + + // Authenticate user + beforeAll(async () => { + const setCookies = await devLogin(); + superPost = createSuperRequest({ method: 'POST', setCookies }); + superGet = createSuperRequest({ method: 'GET', setCookies }); + // Add exam environment authorization token + const res = await superPost('/user/exam-environment/token'); + if (res.status !== 201) { + throw new Error( + `Expected exam environment token request to return 201, got ${res.status}` + ); + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + examEnvironmentAuthorizationToken = + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + res.body.examEnvironmentAuthorizationToken; + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isHonest: true } + }); + }); + + afterAll(async () => { + await mock.clearEnvExam(); + }); + + beforeEach(async () => { + await mock.seedEnvExam(); + }); + + describe('POST /exam-environment/exam/attempt', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany(); + }); + + it('should return an error if there are no current exam attempts matching the given id', async () => { + const body: Static = { + attempt: { + examId: mock.oid(), + questionSets: [] + } + }; + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.body).toStrictEqual({ + code: 'FCC_ERR_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // NOTE: message may not necessarily be a part of the api compatability guarantee. + // That is, it could be changed without requiring a major version bump, because it is just + // a human-readable/debug message. + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return an error if the given exam id does not match an existing exam', async () => { + const examId = mock.oid(); + // Create exam attempt with bad exam id + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + examId, + generatedExamId: mock.oid(), + startTime: new Date(), + userId: defaultUserId + } + }); + const body: Static = { + attempt: { + examId, + questionSets: [] + } + }; + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return an error if the attempt has expired', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + // Create exam attempt with expired time + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + examId: mock.examId, + generatedExamId: mock.oid(), + startTime: new Date(Date.now() - (1000 * 60 * 60 * 2 + 1000)), + userId: defaultUserId + } + }); + const body: Static = { + attempt: { + examId: mock.examId, + questionSets: [] + } + }; + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.body).toStrictEqual({ + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(403); + + expect(count).toHaveBeenCalledWith( + 'exam.attempt_submission_expired', + 1 + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return an error if there is no matching generated exam', async () => { + // Create exam attempt with no matching generated exam + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + examId: mock.examId, + generatedExamId: mock.oid(), + startTime: new Date(), + userId: defaultUserId + } + }); + const body: Static = { + attempt: { + examId: mock.examId, + questionSets: [] + } + }; + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_GENERATED_EXAM', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return an error if the attempt does not match the generated exam', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId } + }); + + attempt.questionSets[0]!.id = mock.oid(); + + const body: Static = { + attempt + }; + + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.body).toStrictEqual({ + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(400); + + // Database should have moderation record for attempt + const examModeration = + await fastifyTestInstance.prisma.examEnvironmentExamModeration.findUnique( + { + where: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + } + ); + expect(examModeration).not.toBeNull(); + + expect(count).toHaveBeenCalledWith('exam.moderation_flagged', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should not error if an invalid attempt is submitted when the attempt is already linked to a moderation record', async () => { + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId } + }); + + attempt.questionSets[0]!.id = mock.oid(); + + const body: Static = { + attempt + }; + + // First invalid submission creates moderation record, and links it to attempt + const firstRes = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(firstRes.status).toBe(400); + + const examModeration = + await fastifyTestInstance.prisma.examEnvironmentExamModeration.findUnique( + { + where: { + examAttemptId: attempt.id + } + } + ); + expect(examModeration).not.toBeNull(); + + const linkedAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findUnique( + { + where: { id: attempt.id } + } + ); + expect(linkedAttempt?.examModerationId).toBe(examModeration!.id); + + // Second invalid submission must not 500 trying to re-link the moderation record + const secondRes = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(secondRes.body).toStrictEqual({ + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(secondRes.status).toBe(400); + + const relinkedAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findUnique( + { + where: { id: attempt.id } + } + ); + expect(relinkedAttempt?.examModerationId).toBe(examModeration!.id); + }); + + it('should return 200 if request is valid, and update attempt in database', async () => { + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + userId: defaultUserId, + examId: mock.examId, + generatedExamId: mock.generatedExam.id, + startTime: new Date(), + questionSets: [] + } + }); + + const body: Static = { + attempt: mock.examAttemptSansSubmissionTime + }; + + const res = await superPost('/exam-environment/exam/attempt') + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ) + .send(body); + + expect(res.status).toBe(200); + + // Database should update attempt + const updatedAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findUnique( + { + where: { id: attempt.id } + } + ); + + expect(updatedAttempt).toMatchObject(body.attempt); + }); + }); + + describe('POST /exam-environment/generated-exam', () => { + beforeEach(async () => { + // Add prerequisite id to user completed challenge + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + completedChallenges: [ + { id: mock.exam.prerequisites.at(0)!, completedDate: Date.now() } + ] + } + }); + await mock.seedEnvExam(); + }); + afterEach(async () => { + await mock.clearEnvExam(); + const a = + await fastifyTestInstance.prisma.examEnvironmentExamModeration.findMany( + {} + ); + // Verifies cascading cleanup of moderation records when attempt data is removed in teardown. + // eslint-disable-next-line vitest/no-standalone-expect + expect(a).toHaveLength(0); + }); + + it('should return an error if the given exam id is invalid', async () => { + const body: Static = { + examId: mock.oid() + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should respond with the error, not hang, when a request fails schema validation', async () => { + const res = await superPost('/exam-environment/exam/generated-exam') + .send({}) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ + code: 'FST_ERR_VALIDATION', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + }, 10000); + + it('should return an error if the exam prerequisites are not met', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + completedChallenges: [] + } + }); + + const body: Static = { + examId: mock.exam.id + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual({ + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(403); + }); + + it('should track a metric when an attempt is blocked due to pending moderation', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: mock.examAttempt + }); + + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const body: Static = { + examId: mock.examId + }; + + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res).toMatchObject({ + status: 403, + body: { + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT' + } + }); + + expect(count).toHaveBeenCalledWith( + 'exam.attempt_blocked_pending_moderation', + 1 + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return an error if the exam has been attempted too recently to retake', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + const recentExamAttempt = { + ...mock.examAttempt, + // Set start time such that exam has just expired + startTime: new Date(Date.now() - examTotalTimeInMS) + }; + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: recentExamAttempt + }); + + const body: Static = { + examId: mock.examId + }; + + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res).toMatchObject({ + status: 429, + body: { + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES' + } + }); + + const examRetakeTimeInMS = mock.exam.config.retakeTimeInS * 1000; + + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.update({ + where: { + id: recentExamAttempt.id + }, + data: { + // Set start time such that exam has expired, but retake time -1s has passed + startTime: new Date( + Date.now() - (examTotalTimeInMS + (examRetakeTimeInMS - 1000)) + ) + } + }); + + const body2: Static = + { + examId: mock.examId + }; + + const res2 = await superPost('/exam-environment/exam/generated-exam') + .send(body2) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res2).toMatchObject({ + status: 429, + body: { + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES' + } + }); + + expect(count).toHaveBeenCalledWith('exam.retake_cooldown_blocked', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should use a new exam attempt if all previous attempts were started > 24 hours ago', async () => { + const recentExamAttempt = structuredClone(mock.examAttempt); + // Set start time such that exam has expired, but 24 hours + 1s has passed + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + recentExamAttempt.startTime = new Date( + Date.now() - (examTotalTimeInMS + (24 * 60 * 60 * 1000 + 1000)) + ); + + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: recentExamAttempt + }); + + // Generate new exam for user to be assigned + const newGeneratedExam = structuredClone(mock.generatedExam); + newGeneratedExam.id = mock.oid(); + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.create({ + data: newGeneratedExam + }); + + const body: Static = { + examId: mock.examId + }; + + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + // Time is greater than 24 hours. So, request should pass, and new exam should be generated + expect(res).toMatchObject({ + status: 200, + body: { + examAttempt: { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + id: expect.not.stringMatching(mock.examAttempt.id) + } + } + }); + }); + + it('should return the current attempt if it is still ongoing', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const latestAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: mock.examAttempt + }); + + const body: Static = { + examId: mock.examId + }; + + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res).toMatchObject({ + status: 200, + body: { + examAttempt: serializeDates(latestAttempt) + } + }); + + expect(count).toHaveBeenCalledWith('exam.attempt_resumed', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should prioritise not-yet-taken generated exams, and reuse completed ones if necessary', async () => { + // Create a second generated exams for the user + const genExam1 = structuredClone(mock.generatedExam); + genExam1.id = mock.oid(); + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.create({ + data: genExam1 + }); + + // Request generated exam, thereby creating an attempt with one of the generated exam ids + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(200); + + // Finish attempt + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.update({ + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + where: { id: res.body.examAttempt.id }, + data: { + startTime: new Date( + Date.now() - + mock.exam.config.totalTimeInS * 1000 - + mock.exam.config.retakeTimeInS * 1000 + ) + } + }); + + // Request generated exam again, which should use the other generated exam + const res2 = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res2.status).toBe(200); + + // Expect examEnvironmentExamAttempt to include 2 records + const eas = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findMany({ + where: { + userId: defaultUserId + } + }); + + expect(eas).toHaveLength(2); + // Expect eas[].generatedExamId to not be the same + const geIds = eas.map(ea => ea.generatedExamId); + expect(geIds[0]).not.toBe(geIds[1]); + + // Finish attempt + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.update({ + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + where: { id: res2.body.examAttempt.id }, + data: { + startTime: new Date( + Date.now() - + mock.exam.config.totalTimeInS * 1000 - + mock.exam.config.retakeTimeInS * 1000 + ) + } + }); + + // Request generated exam again, which should reuse one of the generated exams + const res3 = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res3.status).toBe(200); + + // Expect examEnvironmentExamAttempt to include 3 records, with only 2 unique `generatedExamId`s + const eas2 = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findMany({ + where: { userId: defaultUserId } + }); + + expect(eas2).toHaveLength(3); + const geIds2 = eas2.map(ea => ea.generatedExamId); + expect(new Set(geIds2).size).toBe(2); + }); + + it('should record the fact the user has started an exam by creating an exam attempt', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(200); + + const generatedExam = + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.findFirst( + { + where: { examId: mock.examId } + } + ); + + expect(generatedExam).toBeDefined(); + + const examAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findFirst( + { + where: { generatedExamId: generatedExam!.id } + } + ); + + expect(examAttempt).toEqual({ + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + id: expect.any(String), + userId: defaultUserId, + examId: mock.examId, + generatedExamId: generatedExam!.id, + examModerationId: null, + questionSets: [], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + startTime: expect.any(Date), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number) + }); + + expect(count).toHaveBeenCalledWith('exam.attempt_created', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should unwind (delete) the exam attempt if the user exam cannot be constructed', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + + const _mockConstructUserExam = vi + .spyOn( + await import('../utils/exam-environment.js'), + 'constructUserExam' + ) + .mockImplementationOnce(() => { + throw new Error('Test error'); + }); + + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + const examAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findFirst( + { + where: { examId: mock.examId } + } + ); + + expect(examAttempt).toBeNull(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should track a metric when the generated exam pool is exhausted', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.deleteMany( + {} + ); + + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(500); + expect(count).toHaveBeenCalledWith( + 'exam.generated_exam_pool_exhausted', + 1 + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return the user exam with the exam attempt', async () => { + // Mock Math.random for `shuffleArray` to be equivalent between `/generated-exam` and `constructUserExam` + vi.spyOn(Math, 'random').mockReturnValue(0.123456789); + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(200); + + const generatedExam = + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.findFirst( + { + where: { examId: mock.examId } + } + ); + + expect(generatedExam).toBeDefined(); + + const examAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.findFirst( + { + where: { generatedExamId: generatedExam!.id } + } + ); + + const userExam = constructUserExam(generatedExam!, mock.exam); + + expect(res.body).toMatchObject( + serializeDates({ + examAttempt, + exam: userExam + }) + ); + }); + }); + + describe('GET /exam-environment/exams', () => { + beforeEach(async () => { + // Reset user prerequisites + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + completedChallenges: [ + { id: mock.exam.prerequisites.at(0)!, completedDate: Date.now() } + ] + } + }); + }); + + afterEach(async () => { + // Clean up exam attempts and moderation records + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany(); + + // Reset exam deprecated status + await fastifyTestInstance.prisma.examEnvironmentExam.update({ + where: { id: mock.examId }, + data: { deprecated: false } + }); + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isHonest: true } + }); + }); + + it('should return 200', async () => { + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual([ + { + canTake: true, + config: { + name: mock.exam.config.name, + note: mock.exam.config.note, + passingPercent: mock.exam.config.passingPercent, + totalTimeInS: mock.exam.config.totalTimeInS, + retakeTimeInS: mock.exam.config.retakeTimeInS + }, + id: mock.examId, + prerequisites: mock.exam.prerequisites + } + ]); + + expect(res.status).toBe(200); + }); + + it('should return all exams as unable to take, if user has not accepted academic honesty policy', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isHonest: false } + }); + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual([ + { + canTake: false, + config: { + name: mock.exam.config.name, + note: mock.exam.config.note, + passingPercent: mock.exam.config.passingPercent, + totalTimeInS: mock.exam.config.totalTimeInS, + retakeTimeInS: mock.exam.config.retakeTimeInS + }, + id: mock.examId, + prerequisites: mock.exam.prerequisites + } + ]); + + expect(res.status).toBe(200); + }); + + it('should not return any deprecated exams', async () => { + await fastifyTestInstance.prisma.examEnvironmentExam.update({ + where: { id: mock.examId }, + data: { deprecated: true } + }); + + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual([]); + + expect(res.status).toBe(200); + }); + + it("should indicate an exam's availability based on prerequisites", async () => { + // Remove prerequisites from user + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + completedChallenges: [] + } + }); + + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toMatchObject([{ canTake: false }]); + expect(res.status).toBe(200); + + // Add prerequisites back to user + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + completedChallenges: [ + { id: mock.exam.prerequisites.at(0)!, completedDate: Date.now() } + ] + } + }); + + const res2 = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res2.body).toMatchObject([{ canTake: true }]); + expect(res2.status).toBe(200); + }); + + it('should indicate an exam may be taken if the user has no prior attempts', async () => { + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual([ + { + canTake: true, + config: { + name: mock.exam.config.name, + note: mock.exam.config.note, + passingPercent: mock.exam.config.passingPercent, + totalTimeInS: mock.exam.config.totalTimeInS, + retakeTimeInS: mock.exam.config.retakeTimeInS + }, + id: mock.examId, + prerequisites: mock.exam.prerequisites + } + ]); + expect(res.body).toMatchObject([{ canTake: true }]); + expect(res.status).toBe(200); + }); + + it("should indicate an exam's availability based on the last attempt's start time, and the exam retake time", async () => { + // Create a recent exam attempt that's within the retake time + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + const recentExamAttempt = { + ...mock.examAttempt, + userId: defaultUserId, + startTime: new Date(Date.now() - examTotalTimeInMS) + }; + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: recentExamAttempt + }); + + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toMatchObject([{ canTake: false }]); + expect(res.status).toBe(200); + + const examRetakeTimeInMS = mock.exam.config.retakeTimeInS * 1000; + + // Update the attempt to be outside the retake time + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.update({ + where: { id: recentExamAttempt.id }, + data: { + startTime: new Date( + Date.now() - (examTotalTimeInMS + examRetakeTimeInMS + 1000) + ) + } + }); + + const res2 = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res2.body).toMatchObject([{ canTake: true }]); + + expect(res2.status).toBe(200); + }); + + it('should indicate an exam is unavailable if there are any pending moderation records for the exam attempts', async () => { + // Create an exam attempt that's outside the retake time + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + const examRetakeTimeInMS = mock.exam.config.retakeTimeInS * 1000; + const examAttempt = { + ...mock.examAttempt, + userId: defaultUserId, + startTime: new Date( + Date.now() - (examTotalTimeInMS + examRetakeTimeInMS + 1000) + ) + }; + const createdAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: examAttempt + }); + + // Create a pending moderation record for the attempt + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: createdAttempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toMatchObject([{ canTake: false }]); + expect(res.status).toBe(200); + }); + }); + + describe('GET /exam-environment/exam/attempt/:attemptId', () => { + afterEach(async () => { + // If attempt is deleted, moderation record should cascade + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany(); + const moderationRecords = + await fastifyTestInstance.prisma.examEnvironmentExamModeration.findMany( + {} + ); + // eslint-disable-next-line vitest/no-standalone-expect + expect(moderationRecords).toHaveLength(0); + }); + + it('should return 404 if the attempt does not exist', async () => { + const attemptId = mock.oid(); + const res = await superGet( + `/exam-environment/exam/attempt/${attemptId}` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return 404 if the attempt belongs to another user', async () => { + const otherUserAttempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: mock.oid() } + }); + const res = await superGet( + `/exam-environment/exam/attempt/${otherUserAttempt.id}` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT', // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return 200 with the examEnvironmentExamAttempt if the attempt exists and belongs to the user', async () => { + const startTime = new Date( + Date.now() - mock.exam.config.totalTimeInS * 1000 + ); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId, startTime } + }); + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const res = await superGet( + `/exam-environment/exam/attempt/${attempt.id}` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + status: ExamAttemptStatus.PendingModeration, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number) + }; + + expect(res.body).toEqual(serializeDates(examEnvironmentExamAttempt)); + expect(res.status).toBe(200); + }); + + it.todo( + '(once serialization is serializable) should return 400 if no attempt id is given', + async () => { + const res = await superGet('/exam-environment/exam/attempt/').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(400); + } + ); + it('should return the attempt without results, if the attempt has not been moderated', async () => { + const startTime = new Date( + Date.now() - mock.exam.config.totalTimeInS * 1000 + ); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId, startTime } + }); + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const res = await superGet( + `/exam-environment/exam/attempt/${attempt.id}` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + status: ExamAttemptStatus.PendingModeration, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number) + }; + + expect(res.body).toEqual(serializeDates(examEnvironmentExamAttempt)); + expect(res.status).toBe(200); + }); + + it('should return the attempt with results, if the attempt has been moderated', async () => { + const examAttempt = structuredClone(mock.examAttempt); + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + examAttempt.startTime = new Date(Date.now() - examTotalTimeInMS); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: examAttempt + }); + + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Approved, + challengesAwarded: true + } + }); + + const res = await superGet( + `/exam-environment/exam/attempt/${attempt.id}` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: { + score: 25, + passingPercent: 80 + }, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.Approved + }; + + expect(res.body).toEqual(serializeDates(examEnvironmentExamAttempt)); + expect(res.status).toBe(200); + }); + }); + + describe('GET /exam-environment/exam/attempts', () => { + afterEach(async () => { + // If attempt is deleted, moderation record should cascade + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany(); + const moderationRecords = + await fastifyTestInstance.prisma.examEnvironmentExamModeration.findMany( + {} + ); + // eslint-disable-next-line vitest/no-standalone-expect + expect(moderationRecords).toHaveLength(0); + }); + + it('should return 404 if no attempts exist', async () => { + const res = await superGet(`/exam-environment/exam/attempts`).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.body).toStrictEqual({ + code: 'FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + message: expect.any(String) + }); + expect(res.status).toBe(404); + }); + + it('should return 200 with the attempts if they exist and belong to the user', async () => { + const startTime = new Date( + Date.now() - mock.exam.config.totalTimeInS * 1000 + ); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId, startTime } + }); + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const res = await superGet(`/exam-environment/exam/attempts`).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.PendingModeration + }; + + expect(res.body).toEqual([serializeDates(examEnvironmentExamAttempt)]); + expect(res.status).toBe(200); + }); + + it('should return the attempts without results, if they have not been moderated', async () => { + const startTime = new Date( + Date.now() - mock.exam.config.totalTimeInS * 1000 + ); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { ...mock.examAttempt, userId: defaultUserId, startTime } + }); + + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + + const res = await superGet(`/exam-environment/exam/attempts`).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.PendingModeration + }; + + expect(res.body).toEqual([serializeDates(examEnvironmentExamAttempt)]); + expect(res.status).toBe(200); + }); + + it('should return the attempts without results, if they have been moderated && challenges have not been awarded', async () => { + const examAttempt = structuredClone(mock.examAttempt); + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + examAttempt.startTime = new Date(Date.now() - examTotalTimeInMS); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: examAttempt + }); + + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Approved, + challengesAwarded: false + } + }); + + const res = await superGet(`/exam-environment/exam/attempts`).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.AwaitingChallenges + }; + + expect(res.body).toEqual([serializeDates(examEnvironmentExamAttempt)]); + expect(res.status).toBe(200); + }); + + it('should return the attempts with results, if they have been moderated && challenges have been awarded', async () => { + const examAttempt = structuredClone(mock.examAttempt); + const examTotalTimeInMS = mock.exam.config.totalTimeInS * 1000; + + examAttempt.startTime = new Date(Date.now() - examTotalTimeInMS); + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: examAttempt + }); + + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Approved, + challengesAwarded: true + } + }); + + const res = await superGet(`/exam-environment/exam/attempts`).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: { + score: 25, + passingPercent: 80 + }, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.Approved + }; + + expect(res.body).toEqual([serializeDates(examEnvironmentExamAttempt)]); + expect(res.status).toBe(200); + }); + }); + + describe('GET /exam-environment/exams/:examId/attempts', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany(); + }); + + it('should return 200 if no attempts exist for the exam and user', async () => { + const res = await superGet( + `/exam-environment/exams/${mock.examId}/attempts` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + expect(res.body).toEqual([]); + expect(res.status).toBe(200); + }); + + it('should return 200 with attempts for the given examId and user', async () => { + const attempt = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + ...mock.examAttempt, + userId: defaultUserId, + examId: mock.examId + } + }); + await fastifyTestInstance.prisma.examEnvironmentExamModeration.create({ + data: { + examAttemptId: attempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }); + const res = await superGet( + `/exam-environment/exams/${mock.examId}/attempts` + ).set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + const examEnvironmentExamAttempt = { + id: attempt.id, + examId: mock.exam.id, + result: null, + startTime: attempt.startTime, + questionSets: attempt.questionSets, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + version: expect.any(Number), + status: ExamAttemptStatus.InProgress + }; + + expect(res.body).toEqual([serializeDates(examEnvironmentExamAttempt)]); + expect(res.status).toBe(200); + }); + }); + + describe('Sentry Issue reporting', () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('captures unexpected errors when querying exams fails', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + vi.spyOn( + fastifyTestInstance.prisma.examEnvironmentExam, + 'findMany' + ).mockRejectedValueOnce(new Error('DB error')); + + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('does not capture an expected invalid exam id error', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + vi.spyOn( + fastifyTestInstance.prisma.examEnvironmentExam, + 'findUnique' + ).mockRejectedValueOnce( + new PrismaClientValidationError('Invalid exam id', { + clientVersion: '5.0.0' + }) + ); + + const body: Static = { + examId: mock.examId + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set( + 'exam-environment-authorization-token', + examEnvironmentAuthorizationToken + ); + + expect(res.status).toBe(400); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('captures an exception when no user is present on the request', async () => { + const captureException = vi.fn(); + const fastify = { + ...fastifyTestInstance, + Sentry: { ...fastifyTestInstance.Sentry, captureException } + }; + const req = { + user: null, + log: fastifyTestInstance.log + } as unknown as Parameters[0]; + const send = vi.fn(); + const reply = { + code: vi.fn(), + send + } as unknown as Parameters[1]; + + await getExamAttemptsHandler.call(fastify, req, reply); + + expect(captureException).toHaveBeenCalledWith( + 'No user found in request.' + ); + // eslint-disable-next-line @typescript-eslint/unbound-method + expect(reply.code).toHaveBeenCalledWith(500); + expect(send).toHaveBeenCalledOnce(); + }); + }); + }); + + describe('Authenticated user without exam environment authorization token', () => { + let superPost: ReturnType; + let superGet: ReturnType; + + // Authenticate user + beforeAll(async () => { + const setCookies = await devLogin(); + superPost = createSuperRequest({ method: 'POST', setCookies }); + superGet = createSuperRequest({ method: 'GET', setCookies }); + await mock.seedEnvExam(); + }); + describe('POST /exam-environment/exam/attempt', () => { + it('should return 401', async () => { + const body: Static = { + attempt: { + examId: mock.oid(), + questionSets: [] + } + }; + const res = await superPost('/exam-environment/exam/attempt') + .send(body) + .set('exam-environment-authorization-token', 'invalid-token'); + + expect(res.status).toBe(401); + }); + }); + + describe('POST /exam-environment/exam/generated-exam', () => { + it('should return 401', async () => { + const body: Static = { + examId: mock.oid() + }; + const res = await superPost('/exam-environment/exam/generated-exam') + .send(body) + .set('exam-environment-authorization-token', 'invalid-token'); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /exam-environment/token-meta', () => { + it('should reject invalid tokens', async () => { + const res = await superGet('/exam-environment/token-meta').set( + 'exam-environment-authorization-token', + 'invalid-token' + ); + + expect(res).toMatchObject({ + status: 418, + body: { + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN' + } + }); + }); + + it('should tell the requester if the token does not exist', async () => { + const validToken = jwt.sign( + { examEnvironmentAuthorizationToken: 'does-not-exist' }, + JWT_SECRET + ); + const res = await superGet('/exam-environment/token-meta').set( + 'exam-environment-authorization-token', + validToken + ); + + expect(res).toMatchObject({ + status: 418, + body: { + code: 'FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN' + } + }); + }); + }); + + describe('GET /exam-environment/exams', () => { + it('should return 401', async () => { + const res = await superGet('/exam-environment/exams').set( + 'exam-environment-authorization-token', + 'invalid-token' + ); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /exam-environment/exam/attempt/:attemptId', () => { + it('should return 401', async () => { + const res = await superGet( + `/exam-environment/exam/attempt/${mock.oid()}` + ).set('exam-environment-authorization-token', 'invalid-token'); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /exam-environment/exam/attempts', () => { + it('should return 401', async () => { + const res = await superGet('/exam-environment/exam/attempts').set( + 'exam-environment-authorization-token', + 'invalid-token' + ); + + expect(res.status).toBe(401); + }); + }); + + describe('GET /exam-environment/exam-challenge', () => { + afterAll(async () => { + await fastifyTestInstance.prisma.examEnvironmentChallenge.deleteMany( + {} + ); + }); + it('should return 200 and an empty array if no mapping exists', async () => { + const challengeId = mock.oid(); + const examId = mock.oid(); + + const res1 = await superGet( + `/exam-environment/exam-challenge?challengeId=${challengeId}` + ); + expect(res1.body).toStrictEqual([]); + expect(res1.status).toBe(200); + + const res2 = await superGet( + `/exam-environment/exam-challenge?examId=${examId}` + ); + expect(res2.body).toStrictEqual([]); + expect(res2.status).toBe(200); + + const res3 = await superGet( + `/exam-environment/exam-challenge?challengeId=${challengeId}&examId=${examId}` + ); + expect(res3.body).toStrictEqual([]); + expect(res3.status).toBe(200); + }); + + it('should return 200 and a list of challenge-exam mappings if one exists', async () => { + await fastifyTestInstance.prisma.examEnvironmentChallenge.create({ + data: mock.examEnvironmentChallenge + }); + const res1 = await superGet( + `/exam-environment/exam-challenge?challengeId=${mock.examEnvironmentChallenge.challengeId}` + ); + expect(res1.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + examId: mock.examId, + challengeId: mock.examEnvironmentChallenge.challengeId + }) + ]) + ); + expect(res1.status).toBe(200); + + const res2 = await superGet( + `/exam-environment/exam-challenge?examId=${mock.examId}` + ); + expect(res2.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + examId: mock.examId, + challengeId: mock.examEnvironmentChallenge.challengeId + }) + ]) + ); + expect(res2.status).toBe(200); + + const res3 = await superGet( + `/exam-environment/exam-challenge?challengeId=${mock.examEnvironmentChallenge.challengeId}&examId=${mock.examId}` + ); + expect(res3.body).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + examId: mock.examId, + challengeId: mock.examEnvironmentChallenge.challengeId + }) + ]) + ); + expect(res3.status).toBe(200); + }); + + it('should return 400 if neither challengeId or examId are provided', async () => { + const res = await superGet(`/exam-environment/exam-challenge`); + expect(res).toMatchObject({ + status: 400, + body: { + code: 'FCC_ERR_EXAM_ENVIRONMENT' + } + }); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.ts new file mode 100644 index 0000000000000000000000000000000000000000..b78cf98bbbf1598fa1dff2ffaae6a41fa2a9870a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/routes/exam-environment.ts @@ -0,0 +1,1181 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { PrismaClientValidationError } from '@prisma/client/runtime/library.js'; +import { type FastifyInstance, type FastifyReply } from 'fastify'; +import { ExamEnvironmentExamModerationStatus } from '@prisma/client'; +import jwt from 'jsonwebtoken'; + +import * as schemas from '../schemas/index.js'; +import { mapErr, syncMapErr, UpdateReqType } from '../../utils/index.js'; +import { JWT_SECRET } from '../../utils/env.js'; +import { + checkPrerequisites, + constructEnvExamAttempt, + constructUserExam, + userAttemptToDatabaseAttemptQuestionSets, + validateAttempt +} from '../utils/exam-environment.js'; +import { ERRORS } from '../utils/errors.js'; +import { isObjectID } from '../../utils/validation.js'; + +/** + * Wrapper for endpoints related to the exam environment desktop app. + * + * Requires exam environment authorization token to be validated. + */ +export const examEnvironmentValidatedTokenRoutes: FastifyPluginCallbackTypebox = + (fastify, _options, done) => { + fastify.setErrorHandler((error, req, res) => { + if ( + Object.hasOwnProperty.call(error, 'code') && + Object.hasOwnProperty.call(error, 'message') + ) { + const { code, message, statusCode } = error as { + code: string; + message: string; + statusCode?: number; + }; + res.code( + typeof statusCode === 'number' && statusCode >= 400 ? statusCode : 500 + ); + return res.send({ code, message }); + } + + req.log.error(error, 'Unhandled error in exam environment routes.'); + const str = JSON.stringify(error); + res.code(500); + return res.send(ERRORS.FCC_ERR_UNKNOWN_STATE(str)); + }); + + fastify.get( + '/exam-environment/exams', + { + schema: schemas.examEnvironmentExams + }, + getExams + ); + fastify.post( + '/exam-environment/exam/generated-exam', + { + schema: schemas.examEnvironmentPostExamGeneratedExam + }, + postExamGeneratedExamHandler + ); + fastify.post( + '/exam-environment/exam/attempt', + { + schema: schemas.examEnvironmentPostExamAttempt + }, + postExamAttemptHandler + ); + fastify.get( + '/exam-environment/exam/attempts', + { + schema: schemas.examEnvironmentGetExamAttempts + }, + getExamAttemptsHandler + ); + fastify.get( + '/exam-environment/exam/attempt/:attemptId', + { + schema: schemas.examEnvironmentGetExamAttempt + }, + getExamAttemptHandler + ); + fastify.get( + '/exam-environment/exams/:examId/attempts', + { + schema: schemas.examEnvironmentGetExamAttemptsByExamId + }, + getExamAttemptsByExamIdHandler + ); + + done(); + }; + +/** + * Wrapper for endpoints related to the exam environment desktop app. + * + * Does not require exam environment authorization token to be validated. + */ +export const examEnvironmentOpenRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get( + '/exam-environment/token-meta', + { + schema: schemas.examEnvironmentTokenMeta + }, + tokenMetaHandler + ); + fastify.get( + '/exam-environment/exam-challenge', + { + schema: schemas.examEnvironmentGetExamChallenge + }, + getExamChallenge + ); + done(); +}; + +interface JwtPayload { + examEnvironmentAuthorizationToken: string; +} + +/** + * Verify an authorization token has been generated for a user. + * + * Does not require any authentication. + * + * **Note**: This has no guarantees of which user the token is for. Just that one exists in the database. + */ +async function tokenMetaHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const { 'exam-environment-authorization-token': encodedToken } = req.headers; + req.log.debug('Received exam environment token meta request.'); + + let payload: JwtPayload; + try { + payload = jwt.verify(encodedToken, JWT_SECRET) as JwtPayload; + } catch (e) { + // Server refuses to brew (verify) coffee (jwts) with a teapot (random strings) + req.log.warn(e, 'Invalid token provided.'); + void reply.code(418); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN(JSON.stringify(e)) + ); + } + + if (!isObjectID(payload.examEnvironmentAuthorizationToken)) { + req.log.warn('Token is not an object id.'); + void reply.code(418); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + 'Token is not valid' + ) + ); + } + + const token = await this.prisma.examEnvironmentAuthorizationToken.findUnique({ + where: { + id: payload.examEnvironmentAuthorizationToken + } + }); + + if (!token) { + // Endpoint is valid, but resource does not exists + req.log.warn('Token does not appear to exist.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + 'Token does not appear to exist' + ) + ); + } else { + void reply.code(200); + return reply.send({ + expireAt: token.expireAt + }); + } +} + +/** + * Generates an exam for the user. + * + * Requires token to be validated and TODO: live longer than the exam attempt. + */ +async function postExamGeneratedExamHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + + req.log.debug('Generating exam for user.'); + // Get exam from DB + const examId = req.body.examId; + const maybeExam = await mapErr( + this.prisma.examEnvironmentExam.findUnique({ + where: { + id: examId + } + }) + ); + if (maybeExam.hasError) { + if (maybeExam.error instanceof PrismaClientValidationError) { + req.log.warn(maybeExam.error, 'Invalid exam id given.'); + void reply.code(400); + return reply.send(ERRORS.FCC_EINVAL_EXAM_ID(maybeExam.error.message)); + } + + this.Sentry?.captureException(maybeExam.error); + req.log.error(maybeExam.error, 'Unable to query exam.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExam.error)) + ); + } + + const exam = maybeExam.data; + + if (!exam) { + req.log.warn({ examId }, 'No exam with given id.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM('Invalid exam id given.') + ); + } + + // Check user has completed prerequisites + const isExamPrerequisitesMet = checkPrerequisites(user, exam.prerequisites); + + if (!isExamPrerequisitesMet) { + req.log.warn( + { examId: exam.id }, + 'User has not completed prerequisites to take exam.' + ); + void reply.code(403); + // TODO: Consider sending unmet prerequisites + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES( + 'User has not completed prerequisites.' + ) + ); + } + + // Check user has not completed exam within cooldown period, and + // user does not have an existing attempt awaiting grading + const maybeExamAttempts = await mapErr( + this.prisma.examEnvironmentExamAttempt.findMany({ + where: { + userId: user.id, + examId: exam.id + } + }) + ); + + if (maybeExamAttempts.hasError) { + this.Sentry?.captureException(maybeExamAttempts.error); + req.log.error(maybeExamAttempts.error, 'Unable to query exam attempts.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExamAttempts.error)) + ); + } + + const examAttempts = maybeExamAttempts.data; + + const lastAttempt = examAttempts.length + ? examAttempts.reduce((latest, current) => { + const latestStartTime = latest.startTime; + const currentStartTime = current.startTime; + return latestStartTime > currentStartTime ? latest : current; + }) + : null; + + if (lastAttempt) { + // Camper may not take the exam again, until the previous attempt is graded. + const maybeMod = await mapErr( + this.prisma.examEnvironmentExamModeration.findFirst({ + where: { + examAttemptId: lastAttempt.id, + status: ExamEnvironmentExamModerationStatus.Pending + } + }) + ); + + if (maybeMod.hasError) { + this.Sentry?.captureException(maybeMod.error); + req.log.error(maybeMod.error, 'Unable to query exam moderation.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeMod.error)) + ); + } + + const moderation = maybeMod.data; + + if (moderation !== null) { + req.log.warn( + { examAttemptId: lastAttempt.id }, + 'User has an exam attempt awaiting grading.' + ); + this.Sentry?.metrics?.count('exam.attempt_blocked_pending_moderation', 1); + void reply.code(403); + return reply.send( + // TODO: Better error type + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT( + 'User has an exam attempt awaiting grading.' + ) + ); + } + + const lastAttemptStartTime = lastAttempt.startTime.getTime(); + const examTotalTimeInMS = exam.config.totalTimeInS * 1000; + const examExpirationTime = lastAttemptStartTime + examTotalTimeInMS; + + if (examExpirationTime < Date.now()) { + const examRetakeTimeInMS = exam.config.retakeTimeInS * 1000; + const retakeAllowed = + examExpirationTime + examRetakeTimeInMS < Date.now(); + + if (!retakeAllowed) { + req.log.warn( + { examExpirationTime }, + 'User has completed exam too recently to retake.' + ); + this.Sentry?.metrics?.count('exam.retake_cooldown_blocked', 1); + void reply.code(429); + // TODO: Consider sending last completed time + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES( + 'User has completed exam too recently to retake.' + ) + ); + } + } else { + // Camper has started an attempt, but not submitted it, and there is still time left to complete it. + // This is most likely to happen if the Camper's app closes and is reopened. + // Send the Camper back to the exam they were working on. + const generated = await mapErr( + this.prisma.examEnvironmentGeneratedExam.findFirst({ + where: { + id: lastAttempt.generatedExamId + } + }) + ); + + if (generated.hasError) { + this.Sentry?.captureException(generated.error); + req.log.error(generated.error, 'Unable to query generated exam.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(generated.error)) + ); + } + + if (generated.data === null) { + this.Sentry?.captureException( + new Error('Unreachable. Generated exam not found.'), + { extra: { generatedExamId: lastAttempt.generatedExamId } } + ); + req.log.error( + { generatedExamId: lastAttempt.generatedExamId }, + 'Unreachable. Generated exam not found.' + ); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + 'Unreachable. Generated exam not found.' + ) + ); + } + + const userExam = constructUserExam(generated.data, exam); + + this.Sentry?.metrics?.count('exam.attempt_resumed', 1); + return reply.send({ + exam: userExam, + examAttempt: lastAttempt + }); + } + } + + // Randomly pick a generated exam for user + const maybeGeneratedExams = await mapErr( + this.prisma.examEnvironmentGeneratedExam.findMany({ + where: { + examId: exam.id, + deprecated: false + }, + select: { + id: true + } + }) + ); + + if (maybeGeneratedExams.hasError) { + this.Sentry?.captureException(maybeGeneratedExams.error); + req.log.error( + maybeGeneratedExams.error, + 'Unable to query generated exams.' + ); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(maybeGeneratedExams.error) + ); + } + + const generatedExams = maybeGeneratedExams.data; + + if (generatedExams.length === 0) { + const message = + 'Unable to provide a generated exam. Either no generations exist, or all generated exams are deprecated.'; + this.Sentry?.captureException(new Error(message), { + extra: { examId: exam.id } + }); + req.log.error({ examId: exam.id }, message); + this.Sentry?.metrics?.count('exam.generated_exam_pool_exhausted', 1); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_EXAM_ENVIRONMENT(message)); + } + + // Randomly pick an exam from available generations, prioritising generations not already taken + const untakenGeneratedExams = generatedExams.filter( + ge => !examAttempts.find(ea => ea.generatedExamId === ge.id) + ); + let randomGeneratedExamId: string; + if (untakenGeneratedExams.length === 0) { + this.Sentry?.metrics?.count('exam.generated_exam_reused', 1, { + attributes: { examId: exam.id } + }); + randomGeneratedExamId = + generatedExams[Math.floor(Math.random() * generatedExams.length)]!.id; + } else { + randomGeneratedExamId = + untakenGeneratedExams[ + Math.floor(Math.random() * untakenGeneratedExams.length) + ]!.id; + } + + const maybeGeneratedExam = await mapErr( + this.prisma.examEnvironmentGeneratedExam.findFirst({ + where: { + id: randomGeneratedExamId + } + }) + ); + + if (maybeGeneratedExam.hasError) { + this.Sentry?.captureException(maybeGeneratedExam.error); + req.log.error(maybeGeneratedExam.error, 'Unable to query generated exam.'); + void reply.code(500); + return reply.send( + // TODO: Consider more specific code + ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + 'Unable to query generated exam, due to: ' + + JSON.stringify(maybeGeneratedExam.error) + ) + ); + } + + const generatedExam = maybeGeneratedExam.data; + + if (generatedExam === null) { + this.Sentry?.captureException( + new Error('Unreachable. Generated exam not found.'), + { extra: { generatedExamId: randomGeneratedExamId } } + ); + req.log.error( + { generatedExamId: randomGeneratedExamId }, + 'Unreachable. Generated exam not found.' + ); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT('Unreachable. Generated exam not found.') + ); + } + + // Create exam attempt so, even if user disconnects, their attempt is still recorded: + const attempt = await mapErr( + this.prisma.examEnvironmentExamAttempt.create({ + data: { + userId: user.id, + examId: exam.id, + generatedExamId: generatedExam.id, + examModerationId: null, + startTime: new Date(), + questionSets: [] + } + }) + ); + + if (attempt.hasError) { + this.Sentry?.captureException(attempt.error); + req.log.error(attempt.error, 'Unable to create exam attempt.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT_CREATE_EXAM_ATTEMPT( + JSON.stringify(attempt.error) + ) + ); + } + // NOTE: Anything that goes wrong after this point needs to unwind the exam attempt. + + const maybeUserExam = syncMapErr(() => + constructUserExam(generatedExam, exam) + ); + + if (maybeUserExam.hasError) { + this.Sentry?.captureException(maybeUserExam.error); + req.log.error(maybeUserExam.error, 'Unable to construct user exam.'); + // TODO: Consider handling this failing + await this.prisma.examEnvironmentExamAttempt.delete({ + where: { + id: attempt.data.id + } + }); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeUserExam.error)) + ); + } + + const userExam = maybeUserExam.data; + + this.Sentry?.metrics?.count('exam.attempt_created', 1); + void reply.code(200); + return reply.send({ + exam: userExam, + examAttempt: attempt.data + }); +} + +/** + * Handles updates to an exam attempt. + * + * Requires token to be validated. + * + * TODO: Consider validating req.user.id == lastAttempt.user_id? + * + * NOTE: Currently, questions can be _unanswered_ - taken away from a previous attempt submission. + * Theoretically, this is fine. Practically, it is unclear when that would be useful. + */ +async function postExamAttemptHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + + req.log.debug('Updating exam attempt for user.'); + + const { attempt } = req.body; + + const maybeAttempts = await mapErr( + this.prisma.examEnvironmentExamAttempt.findMany({ + where: { + examId: attempt.examId, + userId: user.id + } + }) + ); + + if (maybeAttempts.hasError) { + this.Sentry?.captureException(maybeAttempts.error); + req.log.error(maybeAttempts.error, 'Unable to query exam attempts.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeAttempts.error)) + ); + } + + const attempts = maybeAttempts.data; + + if (attempts.length === 0) { + req.log.warn({ examId: attempt.examId }, 'No attempts found for user.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT_EXAM_ATTEMPT( + `No attempts found for user '${user.id}' with attempt id '${attempt.examId}'.` + ) + ); + } + + const latestAttempt = attempts.reduce((latest, current) => { + const latestStartTime = latest.startTime; + const currentStartTime = current.startTime; + return latestStartTime > currentStartTime ? latest : current; + }); + + const maybeExam = await mapErr( + this.prisma.examEnvironmentExam.findUnique({ + where: { + id: attempt.examId + }, + select: { + config: true + } + }) + ); + + if (maybeExam.hasError) { + this.Sentry?.captureException(maybeExam.error); + req.log.error(maybeExam.error, 'Unable to query exam.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExam.error)) + ); + } + + const exam = maybeExam.data; + + if (exam === null) { + req.log.warn({ examId: attempt.examId }, 'Invalid exam id given.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM('Invalid exam id given.') + ); + } + + const latestAttemptStartTime = latestAttempt.startTime.getTime(); + const examTotalTimeInMS = exam.config.totalTimeInS * 1000; + const isAttemptExpired = + latestAttemptStartTime + examTotalTimeInMS < Date.now(); + + if (isAttemptExpired) { + req.log.warn( + { examAttemptId: latestAttempt.id }, + 'Attempt has exceeded submission time.' + ); + this.Sentry?.metrics?.count('exam.attempt_submission_expired', 1); + void reply.code(403); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT( + 'Attempt has exceeded submission time.' + ) + ); + } + + // Get generated exam from database + const maybeGeneratedExam = await mapErr( + this.prisma.examEnvironmentGeneratedExam.findUnique({ + where: { + id: latestAttempt.generatedExamId + } + }) + ); + + if (maybeGeneratedExam.hasError) { + this.Sentry?.captureException(maybeGeneratedExam.error); + req.log.error(maybeGeneratedExam.error, 'Unable to query generated exam.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeGeneratedExam.error)) + ); + } + + const generatedExam = maybeGeneratedExam.data; + + if (generatedExam === null) { + req.log.warn( + { generatedExamId: latestAttempt.generatedExamId }, + 'Generated exam not found.' + ); + void reply.code(404); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_GENERATED_EXAM( + 'Generated exam not found.' + ) + ); + } + + const databaseAttemptQuestionSets = userAttemptToDatabaseAttemptQuestionSets( + attempt, + latestAttempt + ); + // Ensure attempt matches generated exam + const maybeValidExamAttempt = syncMapErr(() => + validateAttempt(generatedExam, databaseAttemptQuestionSets) + ); + + if (maybeValidExamAttempt.hasError) { + const message = + maybeValidExamAttempt.error instanceof Error + ? maybeValidExamAttempt.error.message + : 'Unknown attempt validation error'; + req.log.warn({ validExamAttemptError: message }, 'Invalid exam attempt.'); + // As attempt is invalid, create moderation record to investigate or update existing record + const moderation = await this.prisma.examEnvironmentExamModeration.upsert({ + where: { examAttemptId: latestAttempt.id }, + create: { + examAttemptId: latestAttempt.id, + status: ExamEnvironmentExamModerationStatus.Pending, + feedback: message + }, + update: { + feedback: message + } + }); + + this.Sentry?.metrics?.count('exam.moderation_flagged', 1); + + // Link attempt with moderation id if it has not already been done + await this.prisma.examEnvironmentExamAttempt.updateMany({ + where: { + id: latestAttempt.id, + examModerationId: null + }, + data: { + examModerationId: moderation.id + } + }); + + void reply.code(400); + return reply.send(ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT(message)); + } + + // Update attempt in database + const maybeUpdatedAttempt = await mapErr( + this.prisma.examEnvironmentExamAttempt.update({ + where: { + id: latestAttempt.id + }, + data: { + questionSets: databaseAttemptQuestionSets + } + }) + ); + + if (maybeUpdatedAttempt.hasError) { + this.Sentry?.captureException(maybeUpdatedAttempt.error); + req.log.error(maybeUpdatedAttempt.error, 'Unable to update exam attempt.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeUpdatedAttempt.error)) + ); + } + + this.Sentry?.metrics?.count('exam.attempt_updated', 1, { + attributes: { attemptId: latestAttempt.id } + }); + return reply.code(200).send(); +} + +/** + * Get all the public information about all exams. + * @returns Public information about exams + whether Camper may take the exam or not. + */ +export async function getExams( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + + req.log.debug('Fetching available exams for user.'); + + const maybeExams = await mapErr( + this.prisma.examEnvironmentExam.findMany({ + where: { + deprecated: false + }, + select: { + id: true, + config: true, + prerequisites: true + } + }) + ); + + if (maybeExams.hasError) { + this.Sentry?.captureException(maybeExams.error); + req.log.error(maybeExams.error, 'Unable to query exams.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExams.error)) + ); + } + + const exams = maybeExams.data; + + const maybeAttempts = await mapErr( + this.prisma.examEnvironmentExamAttempt.findMany({ + where: { + userId: user.id + }, + select: { + id: true, + examId: true, + startTime: true + } + }) + ); + + if (maybeAttempts.hasError) { + this.Sentry?.captureException(maybeAttempts.error); + req.log.error(maybeAttempts.error, 'Unable to query exam attempts.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeAttempts.error)) + ); + } + + const attempts = maybeAttempts.data; + + const availableExams = []; + + for (const exam of exams) { + const availableExam = { + id: exam.id, + config: { + name: exam.config.name, + note: exam.config.note, + totalTimeInS: exam.config.totalTimeInS, + retakeTimeInS: exam.config.retakeTimeInS, + passingPercent: exam.config.passingPercent + }, + canTake: false, + prerequisites: exam.prerequisites + }; + + const isExamPrerequisitesMet = checkPrerequisites(user, exam.prerequisites); + req.log.debug( + { examId: exam.id, isExamPrerequisitesMet }, + 'Evaluated exam prerequisites.' + ); + + if (!isExamPrerequisitesMet) { + availableExam.canTake = false; + availableExams.push(availableExam); + continue; + } + // Latest attempt must be: + // a) Moderated + // b) Past exam config retake time + const attemptsForExam = attempts.filter(a => a.examId === exam.id); + + const lastAttempt = attemptsForExam.length + ? attemptsForExam.reduce((latest, current) => { + const latestStartTime = latest.startTime; + const currentStartTime = current.startTime; + return latestStartTime > currentStartTime ? latest : current; + }) + : null; + + if (!lastAttempt) { + req.log.debug({ examId: exam.id }, 'No prior attempts for exam.'); + availableExam.canTake = true; + availableExams.push(availableExam); + continue; + } + + const lastAttemptStartTime = lastAttempt.startTime.getTime(); + const examTotalTimeInMS = exam.config.totalTimeInS * 1000; + const examRetakeTimeInMS = exam.config.retakeTimeInS * 1000; + const retakeDateInMS = + lastAttemptStartTime + examTotalTimeInMS + examRetakeTimeInMS; + + const lastAttemptExpired = + Date.now() > lastAttemptStartTime + examTotalTimeInMS; + if (!lastAttemptExpired) { + req.log.debug({ examId: exam.id }, 'Exam in progress.'); + availableExam.canTake = true; + availableExams.push(availableExam); + continue; + } + + const isRetakeTimePassed = Date.now() > retakeDateInMS; + if (!isRetakeTimePassed) { + req.log.debug( + { examId: exam.id, retakeInMs: retakeDateInMS - Date.now() }, + 'Exam retake time has not yet passed.' + ); + availableExam.canTake = false; + availableExams.push(availableExam); + continue; + } + + const maybeModerations = await mapErr( + this.prisma.examEnvironmentExamModeration.findMany({ + where: { + examAttemptId: { in: attemptsForExam.map(a => a.id) }, + status: ExamEnvironmentExamModerationStatus.Pending + } + }) + ); + + if (maybeModerations.hasError) { + this.Sentry?.captureException(maybeModerations.error); + req.log.error( + maybeModerations.error, + 'Unable to query exam moderations.' + ); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeModerations.error)) + ); + } + + const moderations = maybeModerations.data; + + if (moderations.length > 0) { + req.log.debug( + { examId: exam.id, count: moderations.length }, + 'Exam moderation records found.' + ); + availableExam.canTake = false; + availableExams.push(availableExam); + continue; + } + + availableExam.canTake = true; + availableExams.push(availableExam); + } + + return reply.send(availableExams); +} + +/** + * Gets all exam attempts owned by authz user. + * + * If an attempt is completed, the result is included. + */ +export async function getExamAttemptsHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + + req.log.debug('Fetching exam attempts for user.'); + + // Send all relevant exam attempts + const envExamAttempts = []; + const maybeAttempts = await mapErr( + this.prisma.examEnvironmentExamAttempt.findMany({ + where: { + userId: user.id + } + }) + ); + + if (maybeAttempts.hasError) { + this.Sentry?.captureException(maybeAttempts.error); + req.log.error(maybeAttempts.error, 'Unable to query exam attempts.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeAttempts.error)) + ); + } + + const attempts = maybeAttempts.data; + + if (!attempts.length) { + req.log.warn('No exam attempts found.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT('No exam attempt found.') + ); + } + + for (const attempt of attempts) { + const { error, examEnvironmentExamAttempt } = await constructEnvExamAttempt( + this, + attempt, + req.log + ); + if (error) { + void reply.code(error.code); + return reply.send(error.data); + } + envExamAttempts.push(examEnvironmentExamAttempt); + } + + return reply.send(envExamAttempts); +} + +/** + * Gets the requested exam attempt by id owned by authz user. + * + * If the attempt is completed, the result is included. + */ +export async function getExamAttemptHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + req.log.debug('Fetching exam attempt for user.'); + + const { attemptId } = req.params; + + // If attempt id is given, only return that attempt + const maybeAttempt = await mapErr( + this.prisma.examEnvironmentExamAttempt.findUnique({ + where: { + id: attemptId, + userId: user.id + } + }) + ); + + if (maybeAttempt.hasError) { + this.Sentry?.captureException(maybeAttempt.error); + req.log.error(maybeAttempt.error, 'Unable to query exam attempt.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeAttempt.error)) + ); + } + + const attempt = maybeAttempt.data; + + if (!attempt) { + req.log.warn({ attemptId }, 'No exam attempt found.'); + void reply.code(404); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT('No exam attempt found.') + ); + } + + const { error, examEnvironmentExamAttempt } = await constructEnvExamAttempt( + this, + attempt, + req.log + ); + + if (error) { + void reply.code(error.code); + return reply.send(error.data); + } + + return reply.send(examEnvironmentExamAttempt); +} + +/** + * Gets the requested exam attempt by id owned by authz user. + * + * If the attempt is completed, the result is included. + */ +export async function getExamAttemptsByExamIdHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const user = req.user; + + if (!user) { + this.Sentry?.captureException('No user found in request.'); + req.log.error('No user found in request.'); + void reply.code(500); + return reply.send(ERRORS.FCC_ERR_UNKNOWN_STATE('No user found.')); + } + + const { examId } = req.params; + + req.log.debug({ examId }, 'Fetching exam attempts by exam id.'); + + // If attempt id is given, only return that attempt + const maybeAttempts = await mapErr( + this.prisma.examEnvironmentExamAttempt.findMany({ + where: { + examId: examId, + userId: user.id + } + }) + ); + + if (maybeAttempts.hasError) { + this.Sentry?.captureException(maybeAttempts.error); + req.log.error(maybeAttempts.error, 'Unable to query exam attempts.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeAttempts.error)) + ); + } + + const attempts = maybeAttempts.data; + + const examEnvironmentExamAttempts = []; + for (const attempt of attempts) { + const { error, examEnvironmentExamAttempt } = await constructEnvExamAttempt( + this, + attempt, + req.log + ); + + if (error) { + void reply.code(error.code); + return reply.send(error.data); + } + + examEnvironmentExamAttempts.push(examEnvironmentExamAttempt); + } + + return reply.send(examEnvironmentExamAttempts); +} + +/** + * Gets all the relations for a given challenge and exam(s). + */ +export async function getExamChallenge( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + const { challengeId, examId } = req.query; + + req.log.debug({ challengeId, examId }, 'Fetching exam challenge relations.'); + + if (!challengeId && !examId) { + req.log.warn('No challenge or exam id provided.'); + void reply.code(400); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + 'Must provide either a challengeId or examId.' + ) + ); + } + + const maybeData = await mapErr( + this.prisma.examEnvironmentChallenge.findMany({ + where: { + challengeId: challengeId ?? undefined, + examId: examId ?? undefined + } + }) + ); + + if (maybeData.hasError) { + this.Sentry?.captureException(maybeData.error); + req.log.error(maybeData.error, 'Unable to query exam challenge relations.'); + void reply.code(500); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeData.error)) + ); + } + + const data = maybeData.data; + + return reply.send(data); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/challenges.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/challenges.ts new file mode 100644 index 0000000000000000000000000000000000000000..db2a756dd68f21338a46098d5413617bb75492ae --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/challenges.ts @@ -0,0 +1,13 @@ +import { Type } from '@fastify/type-provider-typebox'; +// import { STANDARD_ERROR } from '../utils/errors'; + +export const examEnvironmentGetExamChallenge = { + querystring: Type.Object({ + challengeId: Type.Optional(Type.String({ format: 'objectid' })), + examId: Type.Optional(Type.String({ format: 'objectid' })) + }) + // response: { + // 200: examEnvAttempt, + // default: STANDARD_ERROR + // } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-attempt.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-attempt.ts new file mode 100644 index 0000000000000000000000000000000000000000..1df150eb70bbd4152d4229261a26e166392a5d95 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-attempt.ts @@ -0,0 +1,111 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { STANDARD_ERROR } from '../utils/errors.js'; + +export const examEnvironmentPostExamAttempt = { + body: Type.Object({ + attempt: Type.Object({ + examId: Type.String({ format: 'objectid' }), + questionSets: Type.Array( + Type.Object({ + id: Type.String({ format: 'objectid' }), + questions: Type.Array( + Type.Object({ + id: Type.String({ format: 'objectid' }), + answers: Type.Array(Type.String({ format: 'objectid' })) + }) + ) + }) + ) + }) + }), + headers: Type.Object({ + 'exam-environment-authorization-token': Type.String() + }), + response: { + default: STANDARD_ERROR + } +}; + +export enum ExamAttemptStatus { + // Attempt has not expired yet. + InProgress = 'InProgress', + // Moderation record is not created for practice exam. Also, it might not exist until exam service cron is run. + Expired = 'Expired', + // Attempt has expired && moderation record has been created but not yet moderated + PendingModeration = 'PendingModeration', + // Attempt has been approved + Approved = 'Approved', + // Attempt has been denied + Denied = 'Denied', + /// Attempt has been approved, but challenges have not been awarded to `user.completedChallenges` + AwaitingChallenges = 'AwaitingChallenges' +} + +const examEnvAttempt = Type.Object({ + id: Type.String(), + examId: Type.String(), + startTime: Type.String({ format: 'date-time' }), + questionSets: Type.Array( + Type.Object({ + id: Type.String(), + questions: Type.Array( + Type.Object({ + id: Type.String(), + answers: Type.Array(Type.String()), + submissionTime: Type.String({ format: 'date-time' }) + }) + ) + }) + ), + result: Type.Union([ + Type.Null(), + Type.Object({ + score: Type.Number(), + passingPercent: Type.Number() + }) + ]), + version: Type.Number(), + status: Type.Enum(ExamAttemptStatus) +}); + +export const examEnvironmentGetExamAttempts = { + headers: Type.Object({ + // Optional, because the handler is used in both the `/user/` base and `/exam-environment/` base + // If it is missing, auth will catch. + 'exam-environment-authorization-token': Type.Optional(Type.String()) + }), + response: { + 200: Type.Array(examEnvAttempt), + default: STANDARD_ERROR + } +}; + +export const examEnvironmentGetExamAttempt = { + params: Type.Object({ + attemptId: Type.String({ format: 'objectid' }) + }), + headers: Type.Object({ + // Optional, because the handler is used in both the `/user/` base and `/exam-environment/` base. + // If it is missing, auth will catch. + 'exam-environment-authorization-token': Type.Optional(Type.String()) + }), + response: { + 200: examEnvAttempt, + default: STANDARD_ERROR + } +}; + +export const examEnvironmentGetExamAttemptsByExamId = { + params: Type.Object({ + examId: Type.String({ format: 'objectid' }) + }), + headers: Type.Object({ + // Optional, because the handler is used in both the `/user/` base and `/exam-environment/` base. + // If it is missing, auth will catch. + 'exam-environment-authorization-token': Type.Optional(Type.String()) + }), + response: { + 200: Type.Array(examEnvAttempt) + // default: STANDARD_ERROR + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-generated-exam.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-generated-exam.ts new file mode 100644 index 0000000000000000000000000000000000000000..18cfdcd668847d7bf60e6f1ddd0d650f930c2697 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exam-generated-exam.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { STANDARD_ERROR } from '../utils/errors.js'; + +export const examEnvironmentPostExamGeneratedExam = { + body: Type.Object({ + examId: Type.String() + }), + headers: Type.Object({ + 'exam-environment-authorization-token': Type.String() + }), + response: { + 200: Type.Object({ + exam: Type.Record(Type.String(), Type.Unknown()), + examAttempt: Type.Record(Type.String(), Type.Unknown()) + }), + 403: STANDARD_ERROR, + 404: STANDARD_ERROR, + 429: STANDARD_ERROR, + 500: STANDARD_ERROR + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exams.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exams.ts new file mode 100644 index 0000000000000000000000000000000000000000..984059ad371c4163b37dafd1567625a7b786e3ad --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/exam-environment-exams.ts @@ -0,0 +1,24 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { STANDARD_ERROR } from '../utils/errors.js'; +export const examEnvironmentExams = { + headers: Type.Object({ + 'exam-environment-authorization-token': Type.Optional(Type.String()) + }), + response: { + 200: Type.Array( + Type.Object({ + id: Type.String(), + config: Type.Object({ + name: Type.String(), + note: Type.String(), + totalTimeInS: Type.Number(), + retakeTimeInS: Type.Number(), + passingPercent: Type.Number() + }), + canTake: Type.Boolean(), + prerequisites: Type.Array(Type.String()) + }) + ), + 500: STANDARD_ERROR + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..9f62893a28a9cdc84dec59f40eabf9e52075a093 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/index.ts @@ -0,0 +1,10 @@ +export { + examEnvironmentPostExamAttempt, + examEnvironmentGetExamAttempts, + examEnvironmentGetExamAttempt, + examEnvironmentGetExamAttemptsByExamId +} from './exam-environment-exam-attempt.js'; +export { examEnvironmentPostExamGeneratedExam } from './exam-environment-exam-generated-exam.js'; +export { examEnvironmentTokenMeta } from './token-meta.js'; +export { examEnvironmentExams } from './exam-environment-exams.js'; +export { examEnvironmentGetExamChallenge } from './challenges.js'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/token-meta.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/token-meta.ts new file mode 100644 index 0000000000000000000000000000000000000000..0df2f718d197f43218f866a6fa447497880f1294 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/schemas/token-meta.ts @@ -0,0 +1,15 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { STANDARD_ERROR } from '../utils/errors.js'; + +export const examEnvironmentTokenMeta = { + headers: Type.Object({ + 'exam-environment-authorization-token': Type.String() + }), + response: { + 200: Type.Object({ + expireAt: Type.String({ format: 'date-time' }) + }), + 404: STANDARD_ERROR, + 418: STANDARD_ERROR + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/errors.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/errors.ts new file mode 100644 index 0000000000000000000000000000000000000000..7ca34379c5cac44fc2d3d2caaf661d6d2a6654c6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/errors.ts @@ -0,0 +1,64 @@ +import { format } from 'util'; +import { Type } from '@fastify/type-provider-typebox'; + +export const ERRORS = { + FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN: createError( + 'FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN', + '%s' + ), + FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES: createError( + 'FCC_EINVAL_EXAM_ENVIRONMENT_PREREQUISITES', + '%s' + ), + FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM: createError( + 'FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM', + '%s' + ), + FCC_ERR_EXAM_ENVIRONMENT_CREATE_EXAM_ATTEMPT: createError( + 'FCC_ERR_EXAM_ENVIRONMENT_CREATE_EXAM_ATTEMPT', + '%s' + ), + FCC_ERR_EXAM_ENVIRONMENT: createError('FCC_ERR_EXAM_ENVIRONMENT', '%s'), + FCC_ENOENT_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN: createError( + 'FCC_ENOENT_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN', + '%s' + ), + FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT: createError( + 'FCC_EINVAL_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + '%s' + ), + FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT: createError( + 'FCC_ENOENT_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + '%s' + ), + FCC_ERR_EXAM_ENVIRONMENT_EXAM_ATTEMPT: createError( + 'FCC_ERR_EXAM_ENVIRONMENT_EXAM_ATTEMPT', + '%s' + ), + FCC_ENOENT_EXAM_ENVIRONMENT_GENERATED_EXAM: createError( + 'FCC_ENOENT_EXAM_ENVIRONMENT_GENERATED_EXAM', + '%s' + ), + FCC_EINVAL_EXAM_ID: createError('FCC_EINVAL_EXAM_ID', '%s'), + FCC_ERR_UNKNOWN_STATE: createError('FCC_ERR_UNKNOWN_STATE', '%s') +}; + +/** + * Returns a function which optionally takes arguments to format an error message. + * @param code - Identifier for the error. + * @param message - Human-readable error message. + * @returns Function which optionally takes arguments to format an error message. + */ +function createError(code: string, message: string) { + return (...args: unknown[]) => { + return { + code, + message: format(message, ...args) + }; + }; +} + +export const STANDARD_ERROR = Type.Object({ + code: Type.String(), + message: Type.String() +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3475994b99d43e29b0b9e4409d17bd6f01ee90be --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.test.ts @@ -0,0 +1,440 @@ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import type { MockInstance } from 'vitest'; +import { + ExamEnvironmentAnswer, + ExamEnvironmentQuestionType +} from '@prisma/client'; +import { type Static } from '@fastify/type-provider-typebox'; +import { + exam, + examAttempt, + generatedExam, + oid +} from '../../../__fixtures__/exam-environment-exam.js'; +import * as schemas from '../schemas/index.js'; +import { setupServer } from '../../../vitest.utils.js'; +import { + checkAttemptAgainstGeneratedExam, + checkPrerequisites, + constructUserExam, + userAttemptToDatabaseAttemptQuestionSets, + validateAttempt, + compareAnswers, + shuffleArray +} from './exam-environment.js'; + +// NOTE: Whilst the tests could be run against a single generation of exam, +// it is more useful to run the tests against a new generation each time. +// This helps ensure the config/logic is _reasonably_ likely to be able to +// generate a valid exam. +// Another option is to call `generateExam` hundreds of times in a loop test :shrug: +describe('Exam Environment mocked Math.random', () => { + let spy: MockInstance; + beforeAll(() => { + spy = vi.spyOn(Math, 'random').mockReturnValue(0.123456789); + }); + afterAll(() => { + spy.mockRestore(); + }); + describe('checkAttemptAgainstGeneratedExam()', () => { + it('should return true if all questions are answered', () => { + expect( + checkAttemptAgainstGeneratedExam( + examAttempt.questionSets, + generatedExam + ) + ).toBe(true); + }); + + it('should return false if one or more questions are not answered', () => { + const badExamAttempt = structuredClone(examAttempt); + + badExamAttempt.questionSets[0]!.questions[0]!.answers = []; + expect( + checkAttemptAgainstGeneratedExam( + badExamAttempt.questionSets, + generatedExam + ) + ).toBe(false); + + badExamAttempt.questionSets[0]!.questions[0]!.answers = ['bad-answer']; + expect( + checkAttemptAgainstGeneratedExam( + badExamAttempt.questionSets, + generatedExam + ) + ).toBe(false); + + badExamAttempt.questionSets[0]!.questions = []; + expect( + checkAttemptAgainstGeneratedExam( + badExamAttempt.questionSets, + generatedExam + ) + ).toBe(false); + }); + }); + + describe('checkPrequisites()', () => { + it("should return true if all items in the second argument exist in the first argument's `.completedChallenges[].id`", () => { + const user = { + completedChallenges: [{ id: '1' }, { id: '2' }], + isHonest: true + }; + const prerequisites = ['1', '2']; + + expect(checkPrerequisites(user, prerequisites)).toBe(true); + }); + + it("should return false if any items in the second argument do not exist in the first argument's `.completedChallenges[].id`", () => { + const user = { + completedChallenges: [{ id: '2' }], + isHonest: false + }; + const prerequisites = ['1', '2']; + + expect(checkPrerequisites(user, prerequisites)).toBe(false); + }); + }); + + describe('validateAttempt()', () => { + it('should validate a correct attempt', () => { + expect(() => + validateAttempt(generatedExam, examAttempt.questionSets) + ).not.toThrow(); + }); + + it('should invalidate an incorrect attempt', () => { + const badExamAttempt = structuredClone(examAttempt); + badExamAttempt.questionSets[0]!.questions[0]!.answers = ['bad-answer']; + expect(() => + validateAttempt(generatedExam, badExamAttempt.questionSets) + ).toThrow(); + }); + }); + + describe('userAttemptToDatabaseAttemptQuestionSets()', () => { + it('should add submission time to all questions', () => { + const userAttempt: Static< + typeof schemas.examEnvironmentPostExamAttempt.body.properties.attempt + > = { + examId: '0', + questionSets: [ + { + id: '0', + questions: [{ id: '00', answers: ['000'] }] + }, + { + id: '1', + questions: [{ id: '10', answers: ['100'] }] + } + ] + }; + const latestAttempt = structuredClone(examAttempt); + latestAttempt.questionSets = []; + + const databaseAttemptQuestionSets = + userAttemptToDatabaseAttemptQuestionSets(userAttempt, latestAttempt); + + const allQuestions = databaseAttemptQuestionSets.flatMap( + qs => qs.questions + ); + expect(allQuestions.every(q => q.submissionTime)).toBe(true); + }); + + it('should not change the submission time of any questions that have not changed', () => { + const userAttempt: Static< + typeof schemas.examEnvironmentPostExamAttempt.body.properties.attempt + > = { + examId: '0', + questionSets: [ + { + id: '0', + questions: [{ id: '00', answers: ['000'] }] + }, + { + id: '1', + questions: [{ id: '10', answers: ['100'] }] + } + ] + }; + const latestAttempt = structuredClone(examAttempt); + + const databaseAttemptQuestionSets = + userAttemptToDatabaseAttemptQuestionSets(userAttempt, latestAttempt); + + const submissionTimes = databaseAttemptQuestionSets.flatMap(qs => + qs.questions.map(q => q.submissionTime) + ); + + const sameAttempt = userAttemptToDatabaseAttemptQuestionSets( + userAttempt, + { ...latestAttempt, questionSets: databaseAttemptQuestionSets } + ); + + const sameSubmissionTimes = sameAttempt.flatMap(qs => + qs.questions.map(q => q.submissionTime) + ); + + expect(submissionTimes).toEqual(sameSubmissionTimes); + }); + + it('should change all submission times of questions that have changed', async () => { + const userAttempt: Static< + typeof schemas.examEnvironmentPostExamAttempt.body.properties.attempt + > = { + examId: '0', + questionSets: [ + { + id: '0', + questions: [{ id: '00', answers: ['000'] }] + }, + { + id: '1', + questions: [{ id: '10', answers: ['100'] }] + } + ] + }; + const latestAttempt = structuredClone(examAttempt); + + const databaseAttemptQuestionSets = + userAttemptToDatabaseAttemptQuestionSets(userAttempt, latestAttempt); + userAttempt.questionSets[0]!.questions[0]!.answers = ['001']; + + // The `userAttemptToDatabaseAttemptQuestionSets` function uses `Date.now()` + // to set the submission time, so we need to wait a bit to ensure differences. + await new Promise(resolve => setTimeout(resolve, 10)); + + const newAttemptQuestionSets = userAttemptToDatabaseAttemptQuestionSets( + userAttempt, + { + ...latestAttempt, + questionSets: databaseAttemptQuestionSets + } + ); + + expect( + newAttemptQuestionSets[0]?.questions[0]?.submissionTime + ).not.toEqual( + databaseAttemptQuestionSets[0]?.questions[0]?.submissionTime + ); + }); + }); + + describe('compareAnswers()', () => { + it('should return true when only all correct answers are attempted', () => { + const examAnswers: ExamEnvironmentAnswer[] = [ + { + id: '0', + isCorrect: true, + text: '' + }, + { + id: '1', + isCorrect: true, + text: '' + }, + { + id: '2', + isCorrect: false, + text: '' + }, + { + id: '3', + isCorrect: false, + text: '' + } + ]; + const generatedAnswers = ['0', '1', '2', '3']; + const attemptAnswers = ['0', '1']; + const isCorrect = compareAnswers( + examAnswers, + generatedAnswers, + attemptAnswers + ); + + expect(isCorrect).toBe(true); + }); + + it('should return false when any incorrect answers are attempted', () => { + const examAnswers: ExamEnvironmentAnswer[] = [ + { + id: '0', + isCorrect: true, + text: '' + }, + { + id: '1', + isCorrect: true, + text: '' + }, + { + id: '2', + isCorrect: false, + text: '' + }, + { + id: '3', + isCorrect: false, + text: '' + } + ]; + const generatedAnswers = ['0', '1', '2', '3']; + const attemptAnswers = ['0', '2']; + const isCorrect = compareAnswers( + examAnswers, + generatedAnswers, + attemptAnswers + ); + + expect(isCorrect).toBe(false); + }); + }); +}); + +describe('Exam Environment', () => { + describe('constructUserExam()', () => { + it('should not provide the answers', () => { + const userExam = constructUserExam(generatedExam, exam); + expect(userExam).not.toHaveProperty('answers.isCorrect'); + }); + }); + + describe('shuffleArray()', () => { + it('reasonably shuffles an array', () => { + const unshuff = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + const shuff = shuffleArray(unshuff); + + expect(shuff).not.toEqual(unshuff); + }); + + it('does not mutate the input', () => { + const unshuff = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + shuffleArray(unshuff); + + expect(unshuff).toEqual(unshuff); + }); + }); +}); + +describe('Exam Environment Schema', () => { + setupServer(); + describe('ExamEnvironmentExam', () => { + afterAll(async () => { + await fastifyTestInstance.prisma.examEnvironmentExam.deleteMany({}); + }); + + // eslint-disable-next-line vitest/expect-expect + it("If this test fails and you've deliberately altered the schema, then increment the `version` field by 1", async () => { + const configQuestionSets = [ + { + numberOfCorrectAnswers: 0, + numberOfIncorrectAnswers: 0, + numberOfQuestions: 0, + numberOfSet: 0, + type: ExamEnvironmentQuestionType.MultipleChoice + } + ]; + const tags = [ + { + group: [''], + numberOfQuestions: 0 + } + ]; + const config = { + name: '', + note: '', + passingPercent: 0.0, + questionSets: configQuestionSets, + retakeTimeInS: 0, + tags, + totalTimeInS: 0 + }; + + const questions = [ + { + answers: [ + { + id: oid(), + isCorrect: false, + text: '' + } + ], + audio: { captions: '', url: '' }, + deprecated: false, + id: oid(), + tags: [''], + text: '' + } + ]; + const questionSets = [ + { + context: '', + id: oid(), + questions, + type: ExamEnvironmentQuestionType.MultipleChoice + } + ]; + const data = { + config, + deprecated: false, + prerequisites: [oid()], + questionSets + }; + + await fastifyTestInstance.prisma.examEnvironmentExam.create({ + data + }); + }); + }); + describe('ExamEnvironmentGeneratedExam', () => { + afterAll(async () => { + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.deleteMany( + {} + ); + }); + // eslint-disable-next-line vitest/expect-expect + it("If this test fails and you've deliberately altered the schema, then increment the `version` field by 1", async () => { + await fastifyTestInstance.prisma.examEnvironmentGeneratedExam.create({ + data: { + deprecated: false, + examId: oid(), + questionSets: [ + { id: oid(), questions: [{ answers: [oid()], id: oid() }] } + ] + } + }); + }); + }); + describe('ExamEnvironmentExamAttempt', () => { + afterAll(async () => { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.deleteMany( + {} + ); + }); + // eslint-disable-next-line vitest/expect-expect + it("If this test fails and you've deliberately altered the schema, then increment the `version` field by 1", async () => { + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.create({ + data: { + examId: oid(), + generatedExamId: oid(), + examModerationId: null, + questionSets: [ + { + id: oid(), + questions: [ + { + answers: [oid()], + id: oid(), + submissionTime: new Date() + } + ] + } + ], + startTime: new Date(), + userId: oid() + } + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bc3d786cb773053941f22f687d6601b19237741 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/exam-environment/utils/exam-environment.ts @@ -0,0 +1,642 @@ +/* eslint-disable jsdoc/require-description-complete-sentence */ +// TODO: enable this, since strings don't make good errors. +import { + ExamEnvironmentAnswer, + ExamEnvironmentExam, + ExamEnvironmentExamAttempt, + ExamEnvironmentExamModerationStatus, + ExamEnvironmentGeneratedExam, + ExamEnvironmentGeneratedMultipleChoiceQuestion, + ExamEnvironmentMultipleChoiceQuestion, + ExamEnvironmentMultipleChoiceQuestionAttempt, + ExamEnvironmentQuestionSet, + ExamEnvironmentQuestionSetAttempt +} from '@prisma/client'; +import type { FastifyBaseLogger, FastifyInstance } from 'fastify'; +import { type Static } from '@fastify/type-provider-typebox'; +import { omit } from 'lodash-es'; +import * as schemas from '../schemas/index.js'; +import { mapErr } from '../../utils/index.js'; +import { ExamAttemptStatus } from '../schemas/exam-environment-exam-attempt.js'; +import { ERRORS } from './errors.js'; + +interface PartialUser { + completedChallenges: { id: string }[]; + isHonest: boolean | null; +} + +/** + * Checks if all exam prerequisites have been met by the user: + * - completed challenges linked to exam + * - user is required to have accepted the academic honesty policy + */ +export function checkPrerequisites( + user: PartialUser, + prerequisites: ExamEnvironmentExam['prerequisites'] +) { + return ( + user.isHonest && + prerequisites.every(p => user.completedChallenges.some(c => c.id === p)) + ); +} + +export type UserExam = Omit< + ExamEnvironmentExam, + 'questionSets' | 'config' | 'id' | 'prerequisites' | 'deprecated' | 'version' +> & { + config: Omit; + questionSets: (Omit & { + questions: (Omit< + ExamEnvironmentMultipleChoiceQuestion, + 'answers' | 'tags' | 'deprecated' + > & { + answers: Omit[]; + })[]; + })[]; +} & { generatedExamId: string; examId: string }; + +/** + * Takes the generated exam and the original exam, and creates the user-facing exam. + */ +export function constructUserExam( + generatedExam: ExamEnvironmentGeneratedExam, + exam: ExamEnvironmentExam +): UserExam { + // Map generated exam to user exam (a.k.a. public exam information for user) + const userQuestionSets = generatedExam.questionSets.map(gqs => { + // Get matching question from `exam`, but remove `is_correct` from `exam.questions[].answers[]` + const examQuestionSet = exam.questionSets.find(eqs => eqs.id === gqs.id); + if (!examQuestionSet) { + throw new Error( + `Unreachable. Generated question set id ${gqs.id} not found in exam ${exam.id}.` + ); + } + + const { questions } = examQuestionSet; + + const userQuestions = gqs.questions.map(gq => { + const examQuestion = questions.find(eq => eq.id === gq.id); + if (!examQuestion) { + throw new Error( + `Unreachable. Generated question id ${gq.id} not found in exam question set ${examQuestionSet.id}.` + ); + } + + // Remove `isCorrect` from question answers + const answers = gq.answers.map(generatedAnswerId => { + const examAnswer = examQuestion.answers.find( + ea => ea.id === generatedAnswerId + ); + if (!examAnswer) { + throw new Error( + `Unreachable. Generated answer id ${generatedAnswerId} not found in exam question ${examQuestion.id}.` + ); + } + + const { isCorrect: _, ...answer } = examAnswer; + return answer; + }); + + // NOTE: Shuffling here means when saved attempt is re-fetched, answers will be in different order. + const shuffledAnswers = shuffleArray(answers); + + return { + id: examQuestion.id, + audio: examQuestion.audio, + text: examQuestion.text, + answers: shuffledAnswers + }; + }); + + const userQuestionSet = { + type: examQuestionSet.type, + questions: userQuestions, + id: examQuestionSet.id, + context: examQuestionSet.context + }; + return userQuestionSet; + }); + + // Order questionSets in same order as original exam + const orderedUserQuestionSets = userQuestionSets.sort((a, b) => { + return ( + exam.questionSets.findIndex(qs => qs.id === a.id) - + exam.questionSets.findIndex(qs => qs.id === b.id) + ); + }); + + const config = { + totalTimeInS: exam.config.totalTimeInS, + name: exam.config.name, + note: exam.config.note, + retakeTimeInS: exam.config.retakeTimeInS, + passingPercent: exam.config.passingPercent + }; + + const userExam: UserExam = { + examId: exam.id, + generatedExamId: generatedExam.id, + config, + questionSets: orderedUserQuestionSets + }; + + return userExam; +} + +/** + * Ensures all questions and answers in the attempt are from the generated exam. + */ +export function validateAttempt( + generatedExam: ExamEnvironmentGeneratedExam, + questionSets: ExamEnvironmentExamAttempt['questionSets'] +) { + for (const attemptQuestionSet of questionSets) { + const generatedQuestionSet = generatedExam.questionSets.find( + qt => qt.id === attemptQuestionSet.id + ); + if (!generatedQuestionSet) { + throw new Error( + `Question type ${attemptQuestionSet.id} not found in generated exam.` + ); + } + + for (const attemptQuestion of attemptQuestionSet.questions) { + const generatedQuestion = generatedQuestionSet.questions.find( + q => q.id === attemptQuestion.id + ); + if (!generatedQuestion) { + throw new Error( + `Question ${attemptQuestion.id} not found in generated exam.` + ); + } + + for (const attemptAnswer of attemptQuestion.answers) { + const generatedAnswer = generatedQuestion.answers.find( + a => a === attemptAnswer + ); + if (!generatedAnswer) { + throw new Error( + `Answer ${attemptAnswer} not found in generated exam.` + ); + } + } + } + } + + return true; +} + +/** + * Checks all question sets and questions in the generated exam are in the attempt. + * + * TODO: Consider throwing with specific issue. + * + * @param questionSets An exam attempt. + * @param generatedExam The corresponding generated exam. + * @returns Whether or not the attempt can be considered finished. + */ +export function checkAttemptAgainstGeneratedExam( + questionSets: ExamEnvironmentQuestionSetAttempt[], + generatedExam: Pick +): boolean { + // Check all question sets and questions are in generated exam + for (const generatedQuestionSet of generatedExam.questionSets) { + const attemptQuestionSet = questionSets.find( + q => q.id === generatedQuestionSet.id + ); + if (!attemptQuestionSet) { + return false; + } + + for (const generatedQuestion of generatedQuestionSet.questions) { + const attemptQuestion = attemptQuestionSet.questions.find( + q => q.id === generatedQuestion.id + ); + if (!attemptQuestion) { + return false; + } + + const atLeastOneAnswer = attemptQuestion.answers.length > 0; + if (!atLeastOneAnswer) { + return false; + } + + // All answers in attempt must be in generated exam + const allAnswersInGeneratedExam = attemptQuestion.answers.every(a => + generatedQuestion.answers.includes(a) + ); + if (!allAnswersInGeneratedExam) { + return false; + } + } + } + + return true; +} + +/** + * Adds the current time submission time to all questions in the attempt if the question answer has changed. + */ +export function userAttemptToDatabaseAttemptQuestionSets( + userAttempt: Static< + typeof schemas.examEnvironmentPostExamAttempt.body.properties.attempt + >, + latestAttempt: ExamEnvironmentExamAttempt +): ExamEnvironmentExamAttempt['questionSets'] { + const databaseAttemptQuestionSets: ExamEnvironmentExamAttempt['questionSets'] = + []; + + for (const questionSet of userAttempt.questionSets) { + const latestQuestionSet = latestAttempt.questionSets.find( + qs => qs.id === questionSet.id + ); + + // If no latest attempt, add submission time to all questions + if (!latestQuestionSet) { + databaseAttemptQuestionSets.push({ + ...questionSet, + questions: questionSet.questions.map(q => { + return { + ...q, + submissionTime: new Date() + }; + }) + }); + } else { + const databaseAttemptQuestionSet = { + ...questionSet, + questions: questionSet.questions.map(q => { + const latestQuestion = latestQuestionSet.questions.find( + lq => lq.id === q.id + ); + + // If no latest question, add submission time + if (!latestQuestion) { + return { + ...q, + submissionTime: new Date() + }; + } + + // If answers have changed, add submission time + if ( + JSON.stringify(q.answers) !== JSON.stringify(latestQuestion.answers) + ) { + return { + ...q, + submissionTime: new Date() + }; + } + + return latestQuestion; + }) + }; + + databaseAttemptQuestionSets.push(databaseAttemptQuestionSet); + } + } + + return databaseAttemptQuestionSets; +} + +/** + * Calculates the number of correct questions over the number of the total questions given for an attempt. + * @returns The score of the exam attempt as a percentage. + */ +export function calculateScore( + exam: ExamEnvironmentExam, + generatedExam: ExamEnvironmentGeneratedExam, + attempt: ExamEnvironmentExamAttempt +) { + const attemptQuestionSets = attempt.questionSets; + const generatedQuestionSets = generatedExam.questionSets; + + const totalQuestions = generatedQuestionSets.reduce( + (total, attemptQuestionSet) => total + attemptQuestionSet.questions.length, + 0 + ); + let correctQuestions = 0; + for (const attemptQuestionSet of attemptQuestionSets) { + const examQuestionSet = exam.questionSets.find( + ({ id }) => id === attemptQuestionSet.id + ); + if (!examQuestionSet) { + throw new Error( + `Attempt question set ${attemptQuestionSet.id} must exist in exam ${exam.id}` + ); + } + + const generatedQuestionSet = generatedQuestionSets.find( + ({ id }) => id === attemptQuestionSet.id + ); + if (!generatedQuestionSet) { + throw new Error( + `Generated question set ${attemptQuestionSet.id} must exist in generated exam ${generatedExam.id}` + ); + } + + const attemptQuestions = attemptQuestionSet.questions; + const examQuestions = examQuestionSet.questions; + const generatedQuestions = generatedQuestionSet.questions; + for (const attemptQuestion of attemptQuestions) { + const examQuestion = examQuestions.find( + ({ id }) => id === attemptQuestion.id + ); + if (!examQuestion) { + throw new Error( + `Attempt question ${attemptQuestion.id} must exist in exam ${exam.id}` + ); + } + + const generatedQuestion = generatedQuestions.find( + ({ id }) => id === attemptQuestion.id + ); + if (!generatedQuestion) { + throw new Error( + `Generated question ${attemptQuestion.id} must exist in generated exam ${generatedExam.id}` + ); + } + + const isQuestionCorrect = compareAnswers( + examQuestion.answers, + generatedQuestion.answers, + attemptQuestion.answers + ); + + if (isQuestionCorrect) { + correctQuestions += 1; + } + } + } + + return (correctQuestions / totalQuestions) * 100; +} + +/** + * NOTE: The answers of an attempt is an array for future-proofing when + * checkbox questions are needed. + * + * This calculation takes x / y , x < y as wholey incorrect. + */ +export function compareAnswers( + examAnswers: ExamEnvironmentAnswer[], + generatedAnswers: ExamEnvironmentGeneratedMultipleChoiceQuestion['answers'], + attemptAnswers: ExamEnvironmentMultipleChoiceQuestionAttempt['answers'] +): boolean { + const correctGeneratedAnswers = generatedAnswers.filter(generatedAnswer => { + return examAnswers.some( + examAnswer => examAnswer.isCorrect && examAnswer.id === generatedAnswer + ); + }); + // Check every attempt question answer == every generated question answer + const isQuestionCorrect = + correctGeneratedAnswers.every(correctAnswer => + attemptAnswers.includes(correctAnswer) + ) && correctGeneratedAnswers.length == attemptAnswers.length; + + return isQuestionCorrect; +} + +/* eslint-disable jsdoc/require-description-complete-sentence */ +/** + * Shuffles an array using the Fisher-Yates algorithm. + * + * https://bost.ocks.org/mike/shuffle/ + */ +export function shuffleArray(array: Array) { + const arr = structuredClone(array); + let m = arr.length; + let t; + let i; + + // While there remain elements to shuffle… + while (m) { + // Pick a remaining element… + i = Math.floor(Math.random() * m--); + + // And swap it with the current element. + t = arr[m]!; + arr[m] = arr[i]!; + arr[i] = t; + } + + return arr; +} +/* eslint-enable jsdoc/require-description-complete-sentence */ + +/** + * From an exam attempt, construct the attempt with result (if ready). + * + * @param fastify - Fastify instance. + * @param attempt - The exam attempt. + * @param logger - Logger instance. + * @returns The exam attempt with result or an error. + */ +export async function constructEnvExamAttempt( + fastify: FastifyInstance, + attempt: ExamEnvironmentExamAttempt, + logger: FastifyBaseLogger +) { + const maybeExam = await mapErr( + fastify.prisma.examEnvironmentExam.findUnique({ + where: { + id: attempt.examId + } + }) + ); + + if (maybeExam.hasError) { + fastify.Sentry?.captureException(maybeExam.error); + logger.error( + { err: maybeExam.error, attemptId: attempt.id, examId: attempt.examId }, + 'Unable to query exam.' + ); + return { + error: { + code: 500, + data: ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExam.error)) + } + }; + } + + const exam = maybeExam.data; + + if (exam === null) { + fastify.Sentry?.captureException({ + data: { examId: attempt.examId, attemptId: attempt.id }, + message: 'Unreachable. Invalid exam id in attempt.' + }); + logger.error( + { examId: attempt.examId, attemptId: attempt.id }, + 'Unreachable. Invalid exam id in attempt.' + ); + + return { + error: { + code: 500, + data: ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_MISSING_EXAM( + 'Unreachable. Invalid exam id in attempt.' + ) + } + }; + } + + // If attempt is still in progress, return without result + const attemptStartTimeInMS = attempt.startTime.getTime(); + const examTotalTimeInMS = exam.config.totalTimeInS * 1000; + const isAttemptExpired = + attemptStartTimeInMS + examTotalTimeInMS < Date.now(); + if (!isAttemptExpired) { + return { + examEnvironmentExamAttempt: { + ...omitAttemptReferenceIds(attempt), + result: null, + status: ExamAttemptStatus.InProgress + }, + error: null + }; + } + + const maybeMod = await mapErr( + fastify.prisma.examEnvironmentExamModeration.findFirst({ + where: { + examAttemptId: attempt.id + } + }) + ); + + if (maybeMod.hasError) { + fastify.Sentry?.captureException(maybeMod.error); + logger.error( + { err: maybeMod.error, attemptId: attempt.id }, + 'Unable to query exam moderation.' + ); + return { + error: { + code: 500, + data: ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeMod.error)) + } + }; + } + + const moderation = maybeMod.data; + + // Attempt has expired, but moderation record does not exist + if (moderation === null) { + return { + examEnvironmentExamAttempt: { + ...omitAttemptReferenceIds(attempt), + result: null, + status: ExamAttemptStatus.Expired + }, + error: null + }; + } + + // If attempt is completed, but has not been graded, return without result + if (moderation.status === ExamEnvironmentExamModerationStatus.Pending) { + return { + examEnvironmentExamAttempt: { + ...omitAttemptReferenceIds(attempt), + result: null, + status: ExamAttemptStatus.PendingModeration + }, + error: null + }; + } + + // If attempt is completed, but has been determined to need a retake + // TODO: Send moderation.feedback? + if (moderation.status === ExamEnvironmentExamModerationStatus.Denied) { + return { + examEnvironmentExamAttempt: { + ...omitAttemptReferenceIds(attempt), + result: null, + status: ExamAttemptStatus.Denied + }, + error: null + }; + } + + // Handle case where attempt is approved, but the cron to award completed challenges has not run yet - result should not be shown, as certification is not claimable + if ( + moderation.status === ExamEnvironmentExamModerationStatus.Approved && + moderation.challengesAwarded === false + ) { + return { + examEnvironmentExamAttempt: { + ...omitAttemptReferenceIds(attempt), + result: null, + status: ExamAttemptStatus.AwaitingChallenges + }, + error: null + }; + } + + const maybeGeneratedExam = await mapErr( + fastify.prisma.examEnvironmentGeneratedExam.findUnique({ + where: { + id: attempt.generatedExamId + } + }) + ); + + if (maybeGeneratedExam.hasError) { + fastify.Sentry?.captureException(maybeGeneratedExam.error); + logger.error( + { err: maybeGeneratedExam.error, attemptId: attempt.id }, + 'Unable to query generated exam.' + ); + return { + error: { + code: 500, + data: ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + JSON.stringify(maybeGeneratedExam.error) + ) + } + }; + } + + const generatedExam = maybeGeneratedExam.data; + + if (!generatedExam) { + fastify.Sentry?.captureException({ + data: { + attemptId: attempt.id, + generatedExamId: attempt.generatedExamId + }, + message: + 'Unreachable. Unable to find generated exam associated with exam attempt' + }); + logger.error( + { attemptId: attempt.id, generatedExamId: attempt.generatedExamId }, + 'Unreachable. Unable to find generated exam associated with exam attempt.' + ); + return { + error: { + code: 500, + data: ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + 'Unreachable. Unable to find generated exam associated with exam attempt' + ) + } + }; + } + + const score = calculateScore(exam, generatedExam, attempt); + + const result = { + score, + passingPercent: exam.config.passingPercent + }; + + const examEnvironmentExamAttempt = { + ...omitAttemptReferenceIds(attempt), + result, + status: ExamAttemptStatus.Approved + }; + return { error: null, examEnvironmentExamAttempt }; +} + +function omitAttemptReferenceIds(attempt: ExamEnvironmentExamAttempt) { + return omit(attempt, ['generatedExamId', 'userId']); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/instrument.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/instrument.ts new file mode 100644 index 0000000000000000000000000000000000000000..8e6730ea0fc6f186fd6817f8a11090ee782f523b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/instrument.ts @@ -0,0 +1,48 @@ +import * as Sentry from '@sentry/node'; +import { nodeProfilingIntegration } from '@sentry/profiling-node'; + +import { + DEPLOYMENT_VERSION, + SENTRY_DSN, + SENTRY_ENVIRONMENT, + SENTRY_SERVER_NAME, + SENTRY_LOGS_DEBUG_SAMPLE_RATE, + SENTRY_LOGS_INFO_SAMPLE_RATE, + SENTRY_PROFILE_SESSION_SAMPLE_RATE, + SENTRY_TRACES_SAMPLE_RATE +} from './utils/env.js'; +import { + makeShouldSendLog, + makeTracesSampler, + scrubRedundantLogAttributes, + scrubRequestPii, + scrubSpanDescriptions +} from './utils/sentry.js'; + +const shouldSendLog = makeShouldSendLog( + SENTRY_LOGS_DEBUG_SAMPLE_RATE, + SENTRY_LOGS_INFO_SAMPLE_RATE +); + +Sentry.init({ + dsn: SENTRY_DSN, + environment: SENTRY_ENVIRONMENT, + serverName: SENTRY_SERVER_NAME, + maxValueLength: 8192, // the default is 250, which is too small. + release: DEPLOYMENT_VERSION, + tracesSampler: makeTracesSampler(SENTRY_TRACES_SAMPLE_RATE), + profileSessionSampleRate: SENTRY_PROFILE_SESSION_SAMPLE_RATE, + profileLifecycle: 'trace', + enableLogs: true, + integrations: [ + nodeProfilingIntegration(), + Sentry.pinoIntegration({ + log: { levels: ['info', 'warn', 'error', 'fatal', 'debug'] } + }), + Sentry.requestDataIntegration({ include: { cookies: false } }) + ], + beforeSend: event => scrubRequestPii(event), + beforeSendTransaction: event => scrubSpanDescriptions(event), + beforeSendLog: log => + shouldSendLog(log) ? scrubRedundantLogAttributes(log) : null +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/__fixtures__/user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/__fixtures__/user.ts new file mode 100644 index 0000000000000000000000000000000000000000..5883ad3375aabf89beb43b0633f18f6bc67e48a3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/__fixtures__/user.ts @@ -0,0 +1,109 @@ +import { expect } from 'vitest'; + +import { nanoidCharSet } from '../../utils/create-user.js'; + +const uuidRe = /^[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$/; +const fccUuidRe = /^fcc-[a-f0-9]{8}-([a-f0-9]{4}-){3}[a-f0-9]{12}$/; +const unsubscribeIdRe = new RegExp(`^[${nanoidCharSet}]{21}$`); +const mongodbIdRe = /^[a-f0-9]{24}$/; + +// eslint-disable-next-line jsdoc/require-jsdoc +export const newUser = (email: string) => ({ + about: '', + acceptedPrivacyTerms: false, + completedChallenges: [], + completedDailyCodingChallenges: [], + completedExams: [], + quizAttempts: [], + currentChallengeId: '', + donationEmails: [], + email, + emailAuthLinkTTL: null, + emailVerified: true, + emailVerifyTTL: null, + experience: [], + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + externalId: expect.stringMatching(uuidRe), + githubProfile: null, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + id: expect.stringMatching(mongodbIdRe), + is2018DataVisCert: false, + is2018FullStackCert: false, + isA2EnglishCert: false, + isApisMicroservicesCert: false, + isBackEndCert: false, + isBanned: false, + isCheater: false, + isClassroomAccount: null, + isDataAnalysisPyCertV7: false, + isDataVisCert: false, + isDonating: false, + isFoundationalCSharpCertV8: false, + isFrontEndCert: false, + isFrontEndLibsCert: false, + isFullStackCert: false, + isHonest: false, + isInfosecCertV7: false, + isInfosecQaCert: false, + isJavascriptCertV9: false, + isJsAlgoDataStructCert: false, + isJsAlgoDataStructCertV8: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isQaCertV7: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isCollegeAlgebraPyCertV8: false, + isRespWebDesignCert: false, + isRespWebDesignCertV9: false, + isSciCompPyCertV7: false, + isFrontEndLibsCertV9: false, + isBackEndDevApisCertV9: false, + isFullStackDeveloperCertV9: false, + isB1EnglishCert: false, + isA2SpanishCert: false, + isA2ChineseCert: false, + isA1ChineseCert: false, + keyboardShortcuts: false, + linkedin: null, + location: '', + name: '', + needsModeration: false, + newEmail: null, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + unsubscribeId: expect.stringMatching(unsubscribeIdRe), + partiallyCompletedChallenges: [], + password: null, + picture: '', + portfolio: [], + profileUI: { + isLocked: false, + showAbout: false, + showCerts: false, + showDonation: false, + showExperience: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false + }, + progressTimestamps: [expect.any(Number)], + rand: null, // TODO(Post-MVP): delete from schema (it's not used or required). + savedChallenges: [], + sendQuincyEmail: null, + socrates: null, + theme: 'default', + timezone: null, + twitter: null, + bluesky: null, + updateCount: 0, // see extendClient in prisma.ts + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + username: expect.stringMatching(fccUuidRe), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + usernameDisplay: expect.stringMatching(fccUuidRe), + verificationToken: null, + website: null, + yearsTopContributor: [] +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f37401aa1ee45cde448126cae60a2ff2c60834a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.test.ts @@ -0,0 +1,180 @@ +import { + describe, + test, + expect, + beforeAll, + beforeEach, + afterAll +} from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; + +import { checkCanConnectToDb, defaultUserEmail } from '../../vitest.utils.js'; +import { + HOME_LOCATION, + GROWTHBOOK_FASTIFY_API_HOST, + GROWTHBOOK_FASTIFY_CLIENT_KEY +} from '../utils/env.js'; +import { devAuth } from '../plugins/auth-dev.js'; +import prismaPlugin from '../db/prisma.js'; +import auth from './auth.js'; +import cookies from './cookies.js'; +import growthBook from './growth-book.js'; + +import { newUser } from './__fixtures__/user.js'; + +const requestedUserEmail = 'isolated-e2e-user@example.com'; + +describe('dev login', () => { + let fastify: FastifyInstance; + + beforeAll(async () => { + fastify = Fastify(); + + await fastify.register(cookies); + await fastify.register(auth); + await fastify.register(devAuth); + await fastify.register(prismaPlugin); + await checkCanConnectToDb(fastify.prisma); + await fastify.register(growthBook, { + apiHost: GROWTHBOOK_FASTIFY_API_HOST, + clientKey: GROWTHBOOK_FASTIFY_CLIENT_KEY + }); + }); + + beforeEach(async () => { + await fastify.prisma.user.deleteMany({ + where: { email: { in: [defaultUserEmail, requestedUserEmail] } } + }); + }); + + afterAll(async () => { + await fastify.prisma.user.deleteMany({ + where: { email: { in: [defaultUserEmail, requestedUserEmail] } } + }); + await fastify.prisma.$runCommandRaw({ dropDatabase: 1 }); + await fastify.close(); + }); + + describe('GET /signin', () => { + test('should create an account if one does not exist', async () => { + const before = await fastify.prisma.user.count({}); + await fastify.inject({ + method: 'GET', + url: '/signin' + }); + + const after = await fastify.prisma.user.count({}); + + expect(before).toBe(0); + expect(after).toBe(before + 1); + }); + + test('should populate the user with the correct data', async () => { + await fastify.inject({ + method: 'GET', + url: '/signin' + }); + + const user = await fastify.prisma.user.findFirstOrThrow({ + where: { email: defaultUserEmail } + }); + + expect(user).toEqual(newUser(defaultUserEmail)); + expect(user.username).toBe(user.usernameDisplay); + }); + + test('should sign in with the requested email', async () => { + await fastify.inject({ + method: 'GET', + url: `/signin?email=${requestedUserEmail}` + }); + + const user = await fastify.prisma.user.findFirstOrThrow({ + where: { email: requestedUserEmail } + }); + + expect(user).toEqual(newUser(requestedUserEmail)); + }); + + test('should reject an invalid requested email', async () => { + const response = await fastify.inject({ + method: 'GET', + url: '/signin?email=not-an-email' + }); + + expect(response.statusCode).toBe(400); + }); + + test('should set the jwt_access_token cookie', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin' + }); + + expect(res.statusCode).toBe(302); + + expect(res.cookies).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: 'jwt_access_token' }) + ]) + ); + }); + + test.todo('should create a session'); + + test('should redirect to the Referer (if it is a valid origin)', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: 'https://www.freecodecamp.org/some-path/or/other' + } + }); + + expect(res.statusCode).toBe(302); + expect(res.headers.location).toBe( + 'https://www.freecodecamp.org/some-path/or/other' + ); + }); + + test('should redirect to /valid-language/learn when signing in from /valid-language', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: 'https://www.freecodecamp.org/espanol' + } + }); + + expect(res.statusCode).toBe(302); + expect(res.headers.location).toBe( + 'https://www.freecodecamp.org/espanol/learn' + ); + }); + + test('should handle referers with trailing slahes', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: 'https://www.freecodecamp.org/espanol/' + } + }); + + expect(res.statusCode).toBe(302); + expect(res.headers.location).toBe( + 'https://www.freecodecamp.org/espanol/learn' + ); + }); + + test('should redirect to /learn by default', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin' + }); + + expect(res.statusCode).toBe(302); + expect(res.headers.location).toBe(`${HOME_LOCATION}/learn`); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.ts new file mode 100644 index 0000000000000000000000000000000000000000..df01cd49c182a336ef428e2a9365eb867f8f1fc1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth-dev.ts @@ -0,0 +1,57 @@ +import { + Type, + type FastifyPluginCallbackTypebox +} from '@fastify/type-provider-typebox'; +import type { FastifyReply, FastifyRequest } from 'fastify'; +import { + getRedirectParams, + getPrefixedLandingPath, + haveSamePath +} from '../utils/redirection.js'; +import { findOrCreateUser } from '../routes/helpers/auth-helpers.js'; +import { createAccessToken } from '../utils/tokens.js'; + +const trimTrailingSlash = (str: string) => + str.endsWith('/') ? str.slice(0, -1) : str; + +const signInSchema = { + querystring: Type.Object({ + email: Type.Optional(Type.String({ format: 'email', maxLength: 1024 })) + }) +}; + +async function handleRedirects(req: FastifyRequest, reply: FastifyReply) { + const params = getRedirectParams(req); + const { origin, pathPrefix } = params; + const returnTo = trimTrailingSlash(params.returnTo); + const landingUrl = getPrefixedLandingPath(origin, pathPrefix); + + return await reply.redirect( + haveSamePath(landingUrl, returnTo) ? `${returnTo}/learn` : returnTo + ); +} + +/** + * Fastify plugin for dev authentication. + * + * @param fastify - The Fastify instance. + * @param _options - The plugin options. + * @param done - The callback function. + */ +export const devAuth: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get('/signin', { schema: signInSchema }, async (req, reply) => { + const email = req.query.email ?? 'foo@bar.com'; + + const { id } = await findOrCreateUser(fastify, email); + + reply.setAccessTokenCookie(createAccessToken(id)); + + await handleRedirects(req, reply); + }); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0c0b1ae6cc977427b6519490066bb87a732a177 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.test.ts @@ -0,0 +1,649 @@ +import { Writable } from 'stream'; +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; +import { pino } from 'pino'; +import jwt from 'jsonwebtoken'; + +import { COOKIE_DOMAIN, JWT_SECRET } from '../utils/env.js'; +import { type Token, createAccessToken } from '../utils/tokens.js'; +import { getLoggerOptions } from '../utils/logger.js'; +import cookies, { + sign as signCookie, + unsign as unsignCookie +} from './cookies.js'; +import auth from './auth.js'; + +async function setupServer() { + const fastify = Fastify(); + await fastify.register(cookies); + await fastify.register(auth); + return fastify; +} + +const THIRTY_DAYS_IN_SECONDS = 2592000; + +describe('auth', () => { + let fastify: FastifyInstance; + + beforeEach(async () => { + fastify = await setupServer(); + }); + + afterEach(async () => { + await fastify.close(); + }); + + describe('setAccessTokenCookie', () => { + // We won't need to keep doubly signing the cookie when we migrate the + // authentication, but for the MVP we have to be able to read the cookies + // set by the api-server. So, double signing: + test('should doubly sign the cookie', async () => { + const token = createAccessToken('test-id'); + fastify.get('/test', async (req, reply) => { + reply.setAccessTokenCookie(token); + return { ok: true }; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + const { value, ...rest } = res.cookies[0]!; + const unsignedOnce = unsignCookie(value); + const unsignedTwice = jwt.verify(unsignedOnce.value!, JWT_SECRET) as { + accessToken: Token; + }; + expect(unsignedTwice.accessToken).toEqual(token); + expect(rest).toEqual({ + name: 'jwt_access_token', + path: '/', + sameSite: 'Lax', + domain: COOKIE_DOMAIN, + maxAge: THIRTY_DAYS_IN_SECONDS, + httpOnly: true, + secure: true + }); + }); + }); + + describe('authorize', () => { + beforeEach(() => { + fastify.get('/test', (_req, reply) => { + void reply.send({ ok: true }); + }); + fastify.addHook('onRequest', fastify.authorize); + }); + + test('should deny if the access token is missing', async () => { + expect.assertions(4); + + fastify.addHook('onRequest', (req, _reply, done) => { + expect(req.accessDeniedMessage).toEqual({ + type: 'info', + content: 'Access token is required for this request' + }); + expect(req.user).toBeNull(); + done(); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('should deny if the access token is not signed', async () => { + expect.assertions(4); + + fastify.addHook('onRequest', (req, _reply, done) => { + expect(req.accessDeniedMessage).toEqual({ + type: 'info', + content: 'Access token is required for this request' + }); + expect(req.user).toBeNull(); + done(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: token + } + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('should deny if the access token is invalid', async () => { + expect.assertions(4); + + fastify.addHook('onRequest', (req, _reply, done) => { + expect(req.accessDeniedMessage).toEqual({ + type: 'info', + content: 'Your access token is invalid' + }); + expect(req.user).toBeNull(); + done(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + 'invalid-secret' + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('should deny if the access token has expired', async () => { + expect.assertions(4); + + fastify.addHook('onRequest', (req, _reply, done) => { + expect(req.accessDeniedMessage).toEqual({ + type: 'info', + content: 'Access token is no longer valid' + }); + expect(req.user).toBeNull(); + done(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123', -1) }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('should deny if the user is not found', async () => { + expect.assertions(4); + + fastify.addHook('onRequest', (req, _reply, done) => { + expect(req.accessDeniedMessage).toEqual({ + type: 'info', + content: 'Your access token is invalid' + }); + expect(req.user).toBeNull(); + done(); + }); + + // @ts-expect-error prisma isn't defined, since we're not building the + // full application here. + fastify.prisma = { user: { findUnique: () => null } }; + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('should populate the request with the user if the token is valid', async () => { + const fakeUser = { id: '123', username: 'test-user' }; + // @ts-expect-error prisma isn't defined, since we're not building the + // full application here. + fastify.prisma = { user: { findUnique: () => fakeUser } }; + fastify.get('/test-user', req => { + expect(req.user).toEqual(fakeUser); + return { ok: true }; + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + const res = await fastify.inject({ + method: 'GET', + url: '/test-user', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ ok: true }); + expect(res.statusCode).toEqual(200); + }); + + test('identifies the Sentry user by id only, never email', async () => { + const setUser = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { setUser }; + const fakeUser = { + id: '123', + username: 'test-user', + email: 'foo@bar.com' + }; + // @ts-expect-error prisma isn't built in this minimal test app. + fastify.prisma = { user: { findUnique: () => fakeUser } }; + fastify.get('/test-pii', () => ({ ok: true })); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + await fastify.inject({ + method: 'GET', + url: '/test-pii', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(setUser).toHaveBeenLastCalledWith({ id: '123' }); + }); + }); + + describe('req.getAuthedUser', () => { + test('returns message when access token is missing', async () => { + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.json()).toEqual({ + message: 'Access token is required for this request' + }); + }); + + test('returns message when access token is not signed', async () => { + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: token + } + }); + + expect(res.json()).toEqual({ + message: 'Access token is required for this request' + }); + }); + + test('returns message when access token is invalid', async () => { + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + 'invalid-secret' + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ + message: 'Your access token is invalid' + }); + }); + + test('returns message when access token has expired', async () => { + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123', -1) }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ + message: 'Access token is no longer valid' + }); + }); + + test('returns message when user is not found', async () => { + // @ts-expect-error prisma isn't defined, since we're not building the + // full application here. + fastify.prisma = { user: { findUnique: () => null } }; + + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ + message: 'Your access token is invalid' + }); + }); + + test('returns user when token is valid', async () => { + const fakeUser = { id: '123', username: 'test-user' }; + // @ts-expect-error prisma isn't defined, since we're not building the + // full application here. + fastify.prisma = { user: { findUnique: () => fakeUser } }; + + fastify.get('/test', async req => { + return req.getAuthedUser(); + }); + + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + JWT_SECRET + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(token) + } + }); + + expect(res.json()).toEqual({ + user: fakeUser + }); + }); + }); + + describe('authorizeExamEnvironmentToken', () => { + beforeEach(() => { + fastify.get('/test', (_req, reply) => { + void reply.send({ ok: true }); + }); + fastify.addHook('onRequest', fastify.authorizeExamEnvironmentToken); + }); + + test('captures an Error if the decoded payload is not an object', async () => { + const captureException = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { captureException }; + + const token = jwt.sign('just-a-string-payload', JWT_SECRET); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { 'exam-environment-authorization-token': token } + }); + + expect(res.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: + 'Unreachable: exam-environment token decoded payload is not an object' + }) + ); + }); + + test('does not capture an exception for expected token verification failures', async () => { + const captureException = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { captureException }; + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { 'exam-environment-authorization-token': 'invalid-token' } + }); + + expect(res.statusCode).toBe(401); + expect(captureException).not.toHaveBeenCalled(); + }); + + test('logs a warning when the token is revoked or not found', async () => { + const lines: string[] = []; + const sink = new Writable({ + write(chunk: Buffer, _enc, cb) { + lines.push(chunk.toString()); + cb(); + } + }); + const app = Fastify({ + loggerInstance: pino(getLoggerOptions('info'), sink) + }); + await app.register(cookies); + await app.register(auth); + const prismaMock = { + examEnvironmentAuthorizationToken: { findFirst: () => null } + }; + // @ts-expect-error prisma isn't built in this minimal test app. + app.prisma = prismaMock; + app.addHook('onRequest', app.authorizeExamEnvironmentToken); + app.get('/test', () => ({ ok: true })); + + const token = jwt.sign( + { examEnvironmentAuthorizationToken: 'nonexistent-token-id' }, + JWT_SECRET + ); + const res = await app.inject({ + method: 'GET', + url: '/test', + headers: { 'exam-environment-authorization-token': token } + }); + await app.close(); + + expect(res.statusCode).toBe(401); + const warned = lines + .map(line => JSON.parse(line) as Record) + .find( + entry => + entry.msg === + 'Exam environment authorization token revoked or not found' + ); + expect(warned).toBeDefined(); + expect(warned?.level).toBe(40); + }); + }); + + describe('onRequest Hook', () => { + test('should update the jwt_access_token to httpOnly and secure', async () => { + const rawValue = 'should-not-change'; + fastify.get('/test', (req, reply) => { + reply.send({ ok: true }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + cookies: { + jwt_access_token: signCookie(rawValue) + } + }); + + expect(res.cookies[0]).toMatchObject({ + httpOnly: true, + secure: true, + value: signCookie(rawValue), + maxAge: THIRTY_DAYS_IN_SECONDS + }); + + expect(res.json()).toStrictEqual({ ok: true }); + expect(res.statusCode).toBe(200); + }); + + test('should do nothing if there is no jwt_access_token', async () => { + fastify.get('/test', (req, reply) => { + reply.send({ ok: true }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.cookies).toHaveLength(0); + expect(res.json()).toStrictEqual({ ok: true }); + expect(res.statusCode).toBe(200); + }); + }); + + describe('request logging', () => { + test('binds the userId onto logs for authed requests', async () => { + const lines: string[] = []; + const sink = new Writable({ + write(chunk: Buffer, _enc, cb) { + lines.push(chunk.toString()); + cb(); + } + }); + const app = Fastify({ + loggerInstance: pino(getLoggerOptions('info'), sink) + }); + await app.register(cookies); + await app.register(auth); + const fakeUser = { id: 'user-42', username: 'test-user' }; + // @ts-expect-error prisma isn't built in this minimal test app. + app.prisma = { user: { findUnique: () => fakeUser } }; + app.addHook('onRequest', app.authorize); + app.get('/me', () => ({ ok: true })); + + const token = jwt.sign( + { accessToken: createAccessToken('user-42') }, + JWT_SECRET + ); + await app.inject({ + method: 'GET', + url: '/me', + cookies: { + jwt_access_token: signCookie(token) + } + }); + await app.close(); + + const completed = lines + .map(line => JSON.parse(line) as Record) + .find(entry => entry.msg === 'request completed'); + expect(completed?.userId).toBe('user-42'); + }); + }); + + describe('auth.access_denied metric', () => { + let count: ReturnType; + + beforeEach(() => { + count = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { metrics: { count } }; + fastify.get('/user/session-user', (_req, reply) => { + void reply.send({ ok: true }); + }); + fastify.get('/other', (_req, reply) => { + void reply.send({ ok: true }); + }); + fastify.addHook('onRequest', fastify.authorize); + }); + + test('skips the metric for the anonymous session-user poll', async () => { + await fastify.inject({ method: 'GET', url: '/user/session-user' }); + + expect(count).not.toHaveBeenCalled(); + }); + + test('still counts an invalid token on the session-user route', async () => { + const token = jwt.sign( + { accessToken: createAccessToken('123') }, + 'invalid-secret' + ); + + await fastify.inject({ + method: 'GET', + url: '/user/session-user', + cookies: { jwt_access_token: signCookie(token) } + }); + + expect(count).toHaveBeenCalledExactlyOnceWith('auth.access_denied', 1, { + attributes: { reason: 'Your access token is invalid' } + }); + }); + + test('still counts an expired token on the session-user route', async () => { + const token = jwt.sign( + { accessToken: createAccessToken('123', -1) }, + JWT_SECRET + ); + + await fastify.inject({ + method: 'GET', + url: '/user/session-user', + cookies: { jwt_access_token: signCookie(token) } + }); + + expect(count).toHaveBeenCalledExactlyOnceWith('auth.access_denied', 1, { + attributes: { reason: 'Access token is no longer valid' } + }); + }); + + test('counts a missing token on other routes', async () => { + await fastify.inject({ method: 'GET', url: '/other' }); + + expect(count).toHaveBeenCalledExactlyOnceWith('auth.access_denied', 1, { + attributes: { reason: 'Access token is required for this request' } + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..a46ebbc86712036f77082db909d00aadc5eb9346 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth.ts @@ -0,0 +1,250 @@ +import { FastifyPluginCallback, FastifyRequest, FastifyReply } from 'fastify'; +import fp from 'fastify-plugin'; +import jwt from 'jsonwebtoken'; +import { type user } from '@prisma/client'; + +import { JWT_SECRET } from '../utils/env.js'; +import { type Token, isExpired } from '../utils/tokens.js'; +import { ERRORS } from '../exam-environment/utils/errors.js'; + +type AuthResult = + | { + message: string; + user?: never; + } + | { + message?: never; + user: user; + }; + +declare module 'fastify' { + interface FastifyReply { + setAccessTokenCookie: (this: FastifyReply, accessToken: Token) => void; + } + + interface FastifyRequest { + // TODO: is the full user the correct type here? + user: user | null; + accessDeniedMessage: { type: 'info'; content: string } | null; + getAuthedUser: () => Promise; + } + + interface FastifyInstance { + authorize: (req: FastifyRequest, reply: FastifyReply) => Promise; + authorizeExamEnvironmentToken: ( + req: FastifyRequest, + reply: FastifyReply + ) => void; + } +} + +const auth: FastifyPluginCallback = (fastify, _options, done) => { + const cookieOpts = { + httpOnly: true, + secure: true, + maxAge: 2592000 // thirty days in seconds + }; + fastify.decorateReply('setAccessTokenCookie', function (accessToken: Token) { + const signedToken = jwt.sign({ accessToken }, JWT_SECRET); + void this.setCookie('jwt_access_token', signedToken, cookieOpts); + }); + + // update existing jwt_access_token cookie properties + fastify.addHook('onRequest', (req, reply, done) => { + const rawCookie = req.cookies['jwt_access_token']; + if (rawCookie) { + const jwtAccessToken = req.unsignCookie(rawCookie); + if (jwtAccessToken.valid) { + reply.setCookie('jwt_access_token', jwtAccessToken.value, cookieOpts); + } + } + done(); + }); + + fastify.decorateRequest('accessDeniedMessage', null); + fastify.decorateRequest('user', null); + + const TOKEN_REQUIRED = 'Access token is required for this request'; + const TOKEN_INVALID = 'Your access token is invalid'; + const TOKEN_EXPIRED = 'Access token is no longer valid'; + + const setAccessDenied = (req: FastifyRequest, content: string) => { + const isAnonymousPoll = + req.routeOptions?.url === '/user/session-user' && + content === TOKEN_REQUIRED; + if (!isAnonymousPoll) { + fastify.Sentry?.metrics?.count('auth.access_denied', 1, { + attributes: { reason: content } + }); + } + req.accessDeniedMessage = { type: 'info', content }; + }; + + async function getAuthedUser(this: FastifyRequest): Promise { + const tokenCookie = this.cookies.jwt_access_token; + if (!tokenCookie) return { message: TOKEN_REQUIRED }; + + const unsignedToken = this.unsignCookie(tokenCookie); + if (!unsignedToken.valid) return { message: TOKEN_REQUIRED }; + + const jwtAccessToken = unsignedToken.value; + + try { + jwt.verify(jwtAccessToken, JWT_SECRET); + } catch { + return { message: TOKEN_INVALID }; + } + + const { accessToken } = jwt.decode(jwtAccessToken) as { + accessToken: Token; + }; + + if (isExpired(accessToken)) return { message: TOKEN_EXPIRED }; + // We're using token.userId since it's possible for the user record to be + // malformed and for prisma to throw while trying to find the user. + fastify.Sentry?.setUser({ + id: accessToken.userId + }); + + const user = await fastify.prisma.user.findUnique({ + where: { id: accessToken.userId } + }); + if (user) { + fastify.Sentry?.setUser({ id: user.id }); + } + + return user ? { user } : { message: TOKEN_INVALID }; + } + + fastify.decorateRequest('getAuthedUser', getAuthedUser); + + const handleAuth = async ( + req: FastifyRequest, + reply: FastifyReply + ): Promise => { + const { message, user } = await req.getAuthedUser(); + + if (user) { + req.user = user; + req.log = reply.log = req.log.child({ userId: user.id }); + } else { + req.log.debug({ reason: message }, 'Request not authenticated'); + setAccessDenied(req, message); + } + }; + + async function handleExamEnvironmentTokenAuth( + req: FastifyRequest, + reply: FastifyReply + ) { + const { 'exam-environment-authorization-token': encodedToken } = + req.headers; + + if (!encodedToken || typeof encodedToken !== 'string') { + void reply.code(400); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + 'EXAM-ENVIRONMENT-AUTHORIZATION-TOKEN header is a required string.' + ) + ); + } + + try { + jwt.verify(encodedToken, JWT_SECRET); + } catch (e) { + req.log.warn({ err: e }, 'Exam environment token verification failed'); + void reply.code(401); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + JSON.stringify(e) + ) + ); + } + + const payload = jwt.decode(encodedToken); + + if (typeof payload !== 'object' || payload === null) { + req.log.error( + 'Unreachable: exam-environment token verified but decoded payload is not an object' + ); + fastify.Sentry?.captureException( + new Error( + 'Unreachable: exam-environment token decoded payload is not an object' + ) + ); + void reply.code(500); + return reply.send( + ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + 'Unreachable. Decoded token has been verified.' + ) + ); + } + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const examEnvironmentAuthorizationToken = + payload['examEnvironmentAuthorizationToken']; + + // if (typeof examEnvironmentAuthorizationToken !== 'string') { + // // TODO: This code is debatable, because the token would have to have been signed by the api + // // which means it is valid, but, somehow, got signed as an object instead of a string. + // void reply.code(400+500); + // return reply.send( + // ERRORS.FCC_EINVAL_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + // 'EXAM-ENVIRONMENT-AUTHORIZATION-TOKEN is not valid.' + // ) + // ); + // } + + assertIsString(examEnvironmentAuthorizationToken); + + const token = + await fastify.prisma.examEnvironmentAuthorizationToken.findFirst({ + where: { + id: examEnvironmentAuthorizationToken + } + }); + + if (!token) { + req.log.warn( + { tokenId: examEnvironmentAuthorizationToken }, + 'Exam environment authorization token revoked or not found' + ); + void reply.code(401); + return reply.send( + ERRORS.FCC_ENOENT_EXAM_ENVIRONMENT_AUTHORIZATION_TOKEN( + 'Provided token is revoked.' + ) + ); + } + // We're using token.userId since it's possible for the user record to be + // malformed and for prisma to throw while trying to find the user. + + fastify.Sentry?.setUser({ + id: token.userId + }); + + const user = await fastify.prisma.user.findUnique({ + where: { id: token.userId } + }); + if (!user) return setAccessDenied(req, TOKEN_INVALID); + fastify.Sentry?.setUser({ id: user.id }); + req.user = user; + req.log = reply.log = req.log.child({ userId: user.id }); + } + + fastify.decorate('authorize', handleAuth); + fastify.decorate( + 'authorizeExamEnvironmentToken', + handleExamEnvironmentTokenAuth + ); + + done(); +}; + +function assertIsString(some: unknown): asserts some is string { + if (typeof some !== 'string') { + throw new Error('Expected a string'); + } +} + +export default fp(auth, { name: 'auth', dependencies: ['cookies'] }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..58420d56e84fad3d22fa8a0177266df2a155700a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.test.ts @@ -0,0 +1,522 @@ +import { + describe, + test, + expect, + beforeAll, + afterAll, + beforeEach, + afterEach, + vi, + MockInstance +} from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; + +import { createUserInput } from '../utils/create-user.js'; +import { + AUTH0_DOMAIN, + HOME_LOCATION, + GROWTHBOOK_FASTIFY_API_HOST, + GROWTHBOOK_FASTIFY_CLIENT_KEY +} from '../utils/env.js'; +import prismaPlugin from '../db/prisma.js'; +import cookies, { sign, unsign } from './cookies.js'; +import { auth0Client } from './auth0.js'; +import redirectWithMessage, { formatMessage } from './redirect-with-message.js'; +import auth from './auth.js'; +import bouncer from './bouncer.js'; +import growthBook from './growth-book.js'; +import { newUser } from './__fixtures__/user.js'; + +const COOKIE_DOMAIN = 'test.com'; + +vi.mock('../utils/env', async importOriginal => ({ + ...(await importOriginal()), + COOKIE_DOMAIN: 'test.com' +})); + +describe('auth0 plugin', () => { + let fastify: FastifyInstance; + + beforeAll(async () => { + fastify = Fastify(); + + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException: () => '' }; + + await fastify.register(cookies); + await fastify.register(redirectWithMessage); + await fastify.register(auth); + await fastify.register(bouncer); + await fastify.register(auth0Client); + await fastify.register(prismaPlugin); + await fastify.register(growthBook, { + apiHost: GROWTHBOOK_FASTIFY_API_HOST, + clientKey: GROWTHBOOK_FASTIFY_CLIENT_KEY + }); + }); + + describe('GET /signin/google', () => { + test('should redirect directly to Google via Auth0 with connection param', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin/google' + }); + const redirectUrl = new URL(res.headers.location!); + expect(redirectUrl.host).toMatch(AUTH0_DOMAIN); + expect(redirectUrl.pathname).toBe('/authorize'); + expect(redirectUrl.searchParams.get('connection')).toBe('google-oauth2'); + expect(res.statusCode).toBe(302); + }); + + test('sets a login-returnto cookie', async () => { + const returnTo = 'http://localhost:3000/learn'; + const res = await fastify.inject({ + method: 'GET', + url: '/signin/google', + headers: { referer: returnTo } + }); + const cookie = res.cookies.find(c => c.name === 'login-returnto'); + expect(unsign(cookie!.value).value).toBe(returnTo); + expect(cookie).toMatchObject({ + domain: COOKIE_DOMAIN, + httpOnly: true, + secure: true, + sameSite: 'Lax' + }); + }); + }); + + afterAll(async () => { + await fastify.prisma.$runCommandRaw({ dropDatabase: 1 }); + await fastify.close(); + }); + + describe('GET /signin', () => { + test('should redirect to the auth0 login page', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/signin' + }); + + const redirectUrl = new URL(res.headers.location!); + expect(redirectUrl.host).toMatch(AUTH0_DOMAIN); + expect(redirectUrl.pathname).toBe('/authorize'); + expect(res.statusCode).toBe(302); + }); + + test('sets a login-returnto cookie', async () => { + const returnTo = 'http://localhost:3000/learn'; + const res = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: returnTo + } + }); + + const cookie = res.cookies.find(c => c.name === 'login-returnto'); + expect(unsign(cookie!.value).value).toBe(returnTo); + expect(cookie).toMatchObject({ + domain: COOKIE_DOMAIN, + httpOnly: true, + secure: true, + sameSite: 'Lax' + }); + }); + }); + + describe('GET /auth/auth0/callback', () => { + const email = 'new@user.com'; + let getAccessTokenFromAuthorizationCodeFlowSpy: MockInstance; + let userinfoSpy: MockInstance; + let captureException: ReturnType; + + const mockAuthSuccess = () => { + getAccessTokenFromAuthorizationCodeFlowSpy.mockResolvedValueOnce({ + token: 'any token' + }); + userinfoSpy.mockResolvedValueOnce(Promise.resolve({ email })); + }; + + beforeEach(() => { + getAccessTokenFromAuthorizationCodeFlowSpy = vi.spyOn( + fastify.auth0OAuth, + 'getAccessTokenFromAuthorizationCodeFlow' + ); + userinfoSpy = vi.spyOn(fastify.auth0OAuth, 'userinfo'); + captureException = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException }; + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await fastify.prisma.user.deleteMany({ where: { email } }); + }); + + test('should redirect to the client if authentication fails', async () => { + getAccessTokenFromAuthorizationCodeFlowSpy.mockRejectedValueOnce( + 'any error' + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback' + }); + + expect(res.headers.location).toMatch( + `${HOME_LOCATION}/?${formatMessage({ type: 'danger', content: 'flash.generic-error' })}` + ); + expect(res.statusCode).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + }); + + test('should redirect to the client if the state is invalid', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(res.headers.location).toMatch( + `${HOME_LOCATION}/?${formatMessage({ type: 'danger', content: 'flash.generic-error' })}` + ); + expect(res.statusCode).toBe(302); + }); + + test('should log a warning if the state is invalid', async () => { + vi.spyOn(fastify.log, 'warn'); + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(fastify.log.warn).toHaveBeenCalledWith( + expect.any(Error), + 'Auth failed: invalid state' + ); + expect(res.statusCode).toBe(302); + expect(captureException).not.toHaveBeenCalled(); + }); + + test('should log expected Auth0 errors', async () => { + vi.spyOn(fastify.log, 'error'); + const auth0Error = Error('Response Error: 403 Forbidden'); + // @ts-expect-error - mocking a hapi/boom error + auth0Error.data = { + payload: { + error: 'invalid_grant' + } + }; + + getAccessTokenFromAuthorizationCodeFlowSpy.mockRejectedValueOnce( + auth0Error + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(fastify.log.error).toHaveBeenCalledWith( + auth0Error, + 'Auth failed: invalid_grant' + ); + + expect(res.statusCode).toBe(302); + expect(captureException).not.toHaveBeenCalled(); + }); + + test('should capture Auth0 errors with reason invalid_request', async () => { + vi.spyOn(fastify.log, 'error'); + const auth0Error = Error('Response Error: 400 Bad Request'); + // @ts-expect-error - mocking a hapi/boom error + auth0Error.data = { + payload: { + error: 'invalid_request' + } + }; + + getAccessTokenFromAuthorizationCodeFlowSpy.mockRejectedValueOnce( + auth0Error + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(fastify.log.error).toHaveBeenCalledWith( + auth0Error, + 'Auth failed: invalid_request' + ); + + expect(res.statusCode).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + }); + + test('should capture unexpected Auth0 errors', async () => { + vi.spyOn(fastify.log, 'error'); + const auth0Error = Error('Response Error: 500 Internal Server Error'); + // @ts-expect-error - mocking a hapi/boom error + auth0Error.data = { + payload: { + error: 'server_error' + } + }; + + getAccessTokenFromAuthorizationCodeFlowSpy.mockRejectedValueOnce( + auth0Error + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(fastify.log.error).toHaveBeenCalledWith( + auth0Error, + 'Auth failed: server_error' + ); + + expect(res.statusCode).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + }); + + test('should not create a user if the state is invalid', async () => { + await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=invalid' + }); + + expect(await fastify.prisma.user.count()).toBe(0); + }); + + test('should block requests with "access_denied" error', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?error=access_denied&error_description=Access denied from your location' + }); + + expect(res.statusCode).toBe(302); + expect(res.headers.location).toMatch(`${HOME_LOCATION}/blocked`); + + const resWithoutDescription = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?error=access_denied' + }); + + expect(resWithoutDescription.statusCode).toBe(302); + expect(resWithoutDescription.headers.location).toMatch( + `${HOME_LOCATION}/learn?messages=` + ); + }); + + test('creates a user if the state is valid', async () => { + mockAuthSuccess(); + await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid' + }); + + expect(await fastify.prisma.user.count()).toBe(1); + }); + + test('handles userinfo errors', async () => { + getAccessTokenFromAuthorizationCodeFlowSpy.mockResolvedValueOnce({ + token: 'any token' + }); + userinfoSpy.mockResolvedValueOnce(Promise.reject(Error('any error'))); + const returnTo = 'https://www.freecodecamp.org/espanol/learn'; + const count = vi.fn(); + const distribution = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { ...fastify.Sentry, metrics: { count, distribution } }; + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { 'login-returnto': sign(returnTo) } + }); + + expect(res.headers.location).toMatch( + returnTo + + `?${formatMessage({ type: 'danger', content: 'flash.generic-error' })}` + ); + expect(res.statusCode).toBe(302); + expect(await fastify.prisma.user.count()).toBe(0); + expect(captureException).toHaveBeenCalledOnce(); + expect(distribution).toHaveBeenCalledWith( + 'auth.login_latency_ms', + expect.any(Number), + { + unit: 'millisecond', + attributes: { provider: 'auth0', result: 'failure' } + } + ); + }); + + test('captures userinfo errors carrying innerError', async () => { + getAccessTokenFromAuthorizationCodeFlowSpy.mockResolvedValueOnce({ + token: 'any token' + }); + userinfoSpy.mockRejectedValueOnce( + Object.assign(new Error('upstream'), { innerError: new Error('inner') }) + ); + const returnTo = 'https://www.freecodecamp.org/espanol/learn'; + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { 'login-returnto': sign(returnTo) } + }); + + expect(res.statusCode).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + }); + + test('handles invalid userinfo responses', async () => { + getAccessTokenFromAuthorizationCodeFlowSpy.mockResolvedValueOnce({ + token: 'any token' + }); + userinfoSpy.mockResolvedValueOnce(Promise.resolve({})); + const returnTo = 'https://www.freecodecamp.org/espanol/learn'; + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { 'login-returnto': sign(returnTo) } + }); + + expect(res.headers.location).toMatch( + returnTo + + `?${formatMessage({ type: 'danger', content: 'flash.no-email-in-userinfo' })}` + ); + expect(res.statusCode).toBe(302); + expect(await fastify.prisma.user.count()).toBe(0); + }); + + test('redirects with the signin-success message on success', async () => { + mockAuthSuccess(); + const count = vi.fn(); + const distribution = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { ...fastify.Sentry, metrics: { count, distribution } }; + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid' + }); + + expect(res.headers.location).toMatch( + `?${formatMessage({ type: 'success', content: 'flash.signin-success' })}` + ); + expect(res.statusCode).toBe(302); + expect(count).toHaveBeenCalledWith('auth.login_succeeded', 1, { + attributes: { provider: 'auth0' } + }); + expect(distribution).toHaveBeenCalledWith( + 'auth.login_latency_ms', + expect.any(Number), + { + unit: 'millisecond', + attributes: { provider: 'auth0', result: 'success' } + } + ); + }); + + test('should set the jwt_access_token cookie', async () => { + mockAuthSuccess(); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid' + }); + + expect(res.headers['set-cookie']).toEqual( + expect.stringMatching(/jwt_access_token=/) + ); + }); + + test('should use the login-returnto cookie if present and valid', async () => { + mockAuthSuccess(); + await fastify.prisma.user.create({ + data: { ...createUserInput(email), acceptedPrivacyTerms: true } + }); + const returnTo = 'https://www.freecodecamp.org/espanol/learn'; + // /signin sets the cookie + const req = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: returnTo + } + }); + const returnToCookie = req.cookies.find(c => c.name === 'login-returnto'); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { 'login-returnto': returnToCookie!.value } + }); + + expect(res.headers.location).toBe( + `${returnTo}?${formatMessage({ type: 'success', content: 'flash.signin-success' })}` + ); + }); + + test('should redirect to learn if the user has signed in from the landing page', async () => { + mockAuthSuccess(); + + const returnTo = 'https://www.freecodecamp.org/'; + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { + 'login-returnto': sign(returnTo) + } + }); + + expect(res.headers.location).toEqual( + expect.stringContaining('https://www.freecodecamp.org/learn?') + ); + }); + + test('should redirect home if the login-returnto cookie is invalid', async () => { + mockAuthSuccess(); + const returnTo = 'https://www.evilcodecamp.org/espanol/learn'; + // /signin sets the cookie + const req = await fastify.inject({ + method: 'GET', + url: '/signin', + headers: { + referer: returnTo + } + }); + const returnToCookie = req.cookies.find(c => c.name === 'login-returnto'); + + const res = await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid', + cookies: { 'login-returnto': returnToCookie!.value } + }); + + expect(res.headers.location).toMatch(HOME_LOCATION); + }); + + test('should populate the user with the correct data', async () => { + mockAuthSuccess(); + + await fastify.inject({ + method: 'GET', + url: '/auth/auth0/callback?state=valid' + }); + + const user = await fastify.prisma.user.findFirstOrThrow({ + where: { email } + }); + + expect(user).toEqual(newUser(email)); + expect(user.username).toBe(user.usernameDisplay); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.ts new file mode 100644 index 0000000000000000000000000000000000000000..1daa9e05cde2826719ae4b36c07a38905091c5a0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/auth0.ts @@ -0,0 +1,241 @@ +import { performance } from 'node:perf_hooks'; +import fastifyOauth2, { type OAuth2Namespace } from '@fastify/oauth2'; +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { Type } from 'typebox'; +import { Value } from 'typebox/value'; +import fp from 'fastify-plugin'; + +import { isError } from 'lodash-es'; +import { + API_LOCATION, + AUTH0_CLIENT_ID, + AUTH0_CLIENT_SECRET, + AUTH0_DOMAIN, + COOKIE_DOMAIN, + HOME_LOCATION +} from '../utils/env.js'; +import { findOrCreateUser } from '../routes/helpers/auth-helpers.js'; +import { createAccessToken } from '../utils/tokens.js'; +import { getLoginRedirectParams } from '../utils/redirection.js'; +import { clientNetInfo } from '../utils/logger.js'; + +declare module 'fastify' { + interface FastifyInstance { + auth0OAuth: OAuth2Namespace; + } +} + +const Auth0ErrorSchema = Type.Object({ + data: Type.Object({ + payload: Type.Object({ + error: Type.String() + }) + }) +}); + +/** + * Fastify plugin for Auth0 authentication. This uses fastify-plugin to expose + * the auth0OAuth decorator (for easier testing), but to maintain encapsulation + * it should be registered in a plugin. That prevents auth0OAuth from being + * available globally. + * + * @param fastify - The Fastify instance. + * @param _options - The plugin options. + * @param done - The callback function. + */ +export const auth0Client: FastifyPluginCallbackTypebox = fp( + (fastify, _options, done) => { + void fastify.register(fastifyOauth2, { + name: 'auth0OAuth', + scope: ['openid', 'email', 'profile'], + credentials: { + client: { + id: AUTH0_CLIENT_ID, + secret: AUTH0_CLIENT_SECRET + } + }, + discovery: { issuer: `https://${AUTH0_DOMAIN}` }, + callbackUri: `${API_LOCATION}/auth/auth0/callback`, + cookie: { + // It's important not to sign the cookie, since the OAuth2 plugin will + // not unsign it. + signed: false + } + }); + + void fastify.register(function (fastify, _options, done) { + // TODO(Post-MVP): move this into the app, so that we add this hook once for + // all auth routes. + fastify.addHook('onRequest', fastify.redirectIfSignedIn); + + fastify.get('/signin', async function (request, reply) { + const returnTo = request.headers.referer ?? `${HOME_LOCATION}/learn`; + void reply.setCookie('login-returnto', returnTo, { + domain: COOKIE_DOMAIN, + httpOnly: true, + secure: true, + signed: true, + sameSite: 'lax' + }); + + const redirectUrl = await this.auth0OAuth.generateAuthorizationUri( + request, + reply + ); + void reply.redirect(redirectUrl); + }); + + fastify.get('/signin/google', async function (request, reply) { + const returnTo = request.headers.referer ?? `${HOME_LOCATION}/learn`; + void reply.setCookie('login-returnto', returnTo, { + domain: COOKIE_DOMAIN, + httpOnly: true, + secure: true, + signed: true, + sameSite: 'lax' + }); + + const authorizationEndpoint = + await this.auth0OAuth.generateAuthorizationUri(request, reply); + + const url = new URL(authorizationEndpoint); + url.searchParams.set('connection', 'google-oauth2'); + + void reply.redirect(url.toString()); + }); + done(); + }); + + // TODO: use a schema to validate the query params. + fastify.get('/auth/auth0/callback', async function (req, reply) { + const { error, error_description } = req.query as Record; + if (error === 'access_denied') { + const blockedByLaw = + error_description === 'Access denied from your location'; + if (blockedByLaw) { + req.log.info('Access denied due to user location'); + return reply.redirect(`${HOME_LOCATION}/blocked`); + } else { + req.log.info( + { errorDescription: error_description, ...clientNetInfo(req) }, + 'Authentication failed for user' + ); + return reply.redirectWithMessage(`${HOME_LOCATION}/learn`, { + type: 'info', + content: error_description ?? 'Authentication failed' + }); + } + } + + const { returnTo, origin } = getLoginRedirectParams(req); + + let token; + try { + token = ( + await this.auth0OAuth.getAccessTokenFromAuthorizationCodeFlow(req) + ).token; + } catch (error) { + fastify.Sentry?.metrics?.count('auth.failed', 1, { + attributes: { stage: 'token' } + }); + // This is the plugin's error message. If it changes, we will either + // have to update the test or write custom state create/verify + // functions. + if (error instanceof Error && error.message === 'Invalid state') { + req.log.warn(error, 'Auth failed: invalid state'); + } else if (Value.Check(Auth0ErrorSchema, error)) { + const errorType = error.data.payload.error; + const expectedErrorTypes = ['invalid_grant', 'access_denied']; + if (!expectedErrorTypes.includes(errorType)) { + fastify.Sentry?.captureException(error); + } + req.log.error(error, 'Auth failed: ' + errorType); + } else { + fastify.Sentry?.captureException(error); + req.log.error(error, 'Failed to get access token from Auth0'); + } + // It's important _not_ to redirect to /signin here, as that could + // create an infinite loop. + return reply.redirectWithMessage(returnTo, { + type: 'danger', + content: 'flash.generic-error' + }); + } + + let email; + const __userinfoStart = performance.now(); + try { + const userinfo = (await fastify.auth0OAuth.userinfo(token)) as { + email: string; + }; + fastify.Sentry?.metrics?.distribution( + 'auth.login_latency_ms', + performance.now() - __userinfoStart, + { + unit: 'millisecond', + attributes: { provider: 'auth0', result: 'success' } + } + ); + req.log.debug( + { hasEmail: !!userinfo.email }, + 'Received Auth0 userinfo' + ); + email = userinfo.email; + if (typeof email !== 'string') { + req.log.warn('Auth0 userinfo missing email'); + return reply.redirectWithMessage(returnTo, { + type: 'danger', + content: 'flash.no-email-in-userinfo' + }); + } + } catch (error) { + fastify.Sentry?.metrics?.distribution( + 'auth.login_latency_ms', + performance.now() - __userinfoStart, + { + unit: 'millisecond', + attributes: { provider: 'auth0', result: 'failure' } + } + ); + fastify.Sentry?.metrics?.count('auth.failed', 1, { + attributes: { stage: 'userinfo' } + }); + if (isError(error) && 'innerError' in error) { + // This is a specific error from the @fastify/oauth2 plugin. + const innerError = error.innerError as Error; + innerError.message = `Auth0 userinfo error: ${innerError.message}`; + fastify.Sentry?.captureException(innerError); + req.log.error(innerError, 'Failed to get userinfo from Auth0'); + } else { + fastify.Sentry?.captureException(error); + req.log.error(error, 'Failed to get userinfo from Auth0'); + } + return reply.redirectWithMessage(returnTo, { + type: 'danger', + content: 'flash.generic-error' + }); + } + + const { id } = await findOrCreateUser(fastify, email); + + reply.setAccessTokenCookie(createAccessToken(id)); + + fastify.Sentry?.metrics?.count('auth.login_succeeded', 1, { + attributes: { provider: 'auth0' } + }); + + const returnPath = new URL(returnTo).pathname; + const returnURL = returnPath === '/' ? `${origin}/learn` : returnTo; + + void reply.redirectWithMessage(returnURL, { + type: 'success', + content: 'flash.signin-success' + }); + }); + + done(); + }, + // TODO(Post-MVP): remove bouncer dependency when moving redirectIfSignedIn + // out of this plugin. + { dependencies: ['redirect-with-message', 'bouncer'] } +); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..307ae569b815a07844a122f2c53a01548bb097a5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.test.ts @@ -0,0 +1,168 @@ +/* eslint-disable @typescript-eslint/require-await */ +import { + describe, + test, + expect, + beforeEach, + afterEach, + vi, + MockInstance +} from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import { type user } from '@prisma/client'; + +import { HOME_LOCATION } from '../utils/env.js'; +import bouncer from './bouncer.js'; +import auth from './auth.js'; +import cookies from './cookies.js'; +import redirectWithMessage, { formatMessage } from './redirect-with-message.js'; + +let authorizeSpy: MockInstance; + +async function setupServer() { + const fastify = Fastify(); + await fastify.register(cookies); + await fastify.register(auth); + authorizeSpy = vi.spyOn(fastify, 'authorize'); + + await fastify.register(redirectWithMessage); + await fastify.register(bouncer); + fastify.addHook('onRequest', fastify.authorize); + fastify.get('/', (_req, reply) => { + void reply.send({ foo: 'bar' }); + }); + return fastify; +} + +describe('bouncer', () => { + let fastify: FastifyInstance; + beforeEach(async () => { + fastify = await setupServer(); + }); + + afterEach(async () => { + await fastify.close(); + }); + + describe('send401IfNoUser', () => { + beforeEach(() => { + fastify.addHook('onRequest', fastify.send401IfNoUser); + }); + + test('should return 401 if NO user is present', async () => { + const message = { + type: 'info' as const, + content: 'Something undesirable occurred' + }; + authorizeSpy.mockImplementationOnce(async req => { + req.accessDeniedMessage = message; + }); + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.json()).toStrictEqual({ + type: message.type, + message: message.content + }); + expect(res.statusCode).toEqual(401); + }); + + test('should not alter the response if a user is present', async () => { + authorizeSpy.mockImplementationOnce(async req => { + req.user = { id: '123' } as user; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.json()).toEqual({ foo: 'bar' }); + expect(res.statusCode).toEqual(200); + }); + }); + + describe('redirectIfNoUser', () => { + beforeEach(() => { + fastify.addHook('onRequest', fastify.redirectIfNoUser); + }); + const redirectLocation = `${HOME_LOCATION}?${formatMessage({ type: 'info', content: 'Only authenticated users can access this route. Please sign in and try again.' })}`; + + // TODO(Post-MVP): make the redirects consistent between redirectIfNoUser + // and redirectIfSignedIn. Either both should redirect to the referer or + // both should redirect to HOME_LOCATION. + test('should redirect to HOME_LOCATION if NO user is present', async () => { + const message = { + type: 'info' as const, + content: 'At the moment, content is ignored' + }; + authorizeSpy.mockImplementationOnce(async req => { + req.accessDeniedMessage = message; + }); + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.headers.location).toBe(redirectLocation); + expect(res.statusCode).toEqual(302); + }); + + test('should not alter the response if a user is present', async () => { + authorizeSpy.mockImplementationOnce(async req => { + req.user = { id: '123' } as user; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.json()).toEqual({ foo: 'bar' }); + expect(res.statusCode).toEqual(200); + }); + }); + + describe('redirectIfSignedIn', () => { + beforeEach(() => { + fastify.addHook('onRequest', fastify.redirectIfSignedIn); + }); + + test('should redirect to the referer if a user is present', async () => { + authorizeSpy.mockImplementationOnce(async req => { + req.user = { id: '123' } as user; + }); + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + referer: 'https://www.freecodecamp.org/some/other/path' + } + }); + + expect(res.headers.location).toBe( + 'https://www.freecodecamp.org/some/other/path' + ); + expect(res.statusCode).toEqual(302); + }); + + test('should not alter the response if NO user is present', async () => { + const message = { + type: 'info' as const, + content: 'At the moment, content is ignored' + }; + authorizeSpy.mockImplementationOnce(async req => { + req.accessDeniedMessage = message; + }); + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.json()).toEqual({ foo: 'bar' }); + expect(res.statusCode).toEqual(200); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.ts new file mode 100644 index 0000000000000000000000000000000000000000..17a883983c26281fe06b57af7b8c7b7247268d4a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/bouncer.ts @@ -0,0 +1,70 @@ +import type { + FastifyPluginCallback, + FastifyRequest, + FastifyReply +} from 'fastify'; +import fp from 'fastify-plugin'; +import { getRedirectParams } from '../utils/redirection.js'; + +declare module 'fastify' { + interface FastifyInstance { + send401IfNoUser: (req: FastifyRequest, reply: FastifyReply) => void; + redirectIfNoUser: (req: FastifyRequest, reply: FastifyReply) => void; + redirectIfSignedIn: (req: FastifyRequest, reply: FastifyReply) => void; + } +} + +const plugin: FastifyPluginCallback = (fastify, _options, done) => { + fastify.decorate( + 'send401IfNoUser', + async function (req: FastifyRequest, reply: FastifyReply) { + if (!req.user) { + req.log.trace( + 'Protected route accessed by unauthenticated user. Sent 401.' + ); + + await reply.status(401).send({ + type: req.accessDeniedMessage?.type, + message: req.accessDeniedMessage?.content + }); + } + } + ); + + fastify.decorate( + 'redirectIfNoUser', + async function (req: FastifyRequest, reply: FastifyReply) { + if (!req.user) { + req.log.trace( + 'Protected route accessed by unauthenticated user. Redirecting to login.' + ); + const { origin } = getRedirectParams(req); + await reply.redirectWithMessage(origin, { + type: 'info', + content: + 'Only authenticated users can access this route. Please sign in and try again.' + }); + } + } + ); + + fastify.decorate( + 'redirectIfSignedIn', + async function (req: FastifyRequest, reply: FastifyReply) { + if (req.user) { + const { returnTo } = getRedirectParams(req); + + req.log.trace({ returnTo }, 'Signed-in user redirected'); + + await reply.redirect(returnTo); + } + } + ); + + done(); +}; + +export default fp(plugin, { + dependencies: ['auth', 'redirect-with-message'], + name: 'bouncer' +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..938d8a3a863bc6be4782b682369f624d0c9e41b9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.test.ts @@ -0,0 +1,116 @@ +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; +import cookies, { type CookieSerializeOptions, sign } from './cookies.js'; +import { cookieUpdate } from './cookie-update.js'; + +vi.mock('../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + COOKIE_DOMAIN: 'www.example.com', + FREECODECAMP_NODE_ENV: 'not-development' + }; +}); + +describe('Cookie updates', () => { + let fastify: FastifyInstance; + + const setup = async (attributes: CookieSerializeOptions) => { + // Since register creates a new scope, we need to create a route inside the + // scope for the plugin to be applied. + await fastify.register(cookieUpdate, fastify => { + // eslint-disable-next-line @typescript-eslint/require-await + fastify.get('/', async () => { + return { hello: 'world' }; + }); + return { + cookies: ['cookie_name'], + attributes + }; + }); + }; + + beforeEach(async () => { + fastify = Fastify(); + await fastify.register(cookies); + }); + + afterEach(async () => { + await fastify.close(); + }); + + test('should not set cookies that are not in the request', async () => { + await setup({}); + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + cookie: 'cookie_name_two=cookie_value' + } + }); + + expect(res.headers['set-cookie']).toBeUndefined(); + }); + + test("should update the cookie's attributes without changing the value", async () => { + await setup({ sameSite: 'strict' }); + const signedCookie = sign('cookie_value'); + const encodedCookie = encodeURIComponent(signedCookie); + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + cookie: `cookie_name=${signedCookie}` + } + }); + + const updatedCookie = res.headers['set-cookie'] as string; + expect(updatedCookie).toEqual( + expect.stringContaining(`cookie_name=${encodedCookie}`) + ); + expect(updatedCookie).toEqual(expect.stringContaining('SameSite=Strict')); + }); + + test('should unsign the cookie if required', async () => { + await setup({ signed: false }); + const signedCookie = sign('cookie_value'); + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + cookie: `cookie_name=${signedCookie}` + } + }); + + const updatedCookie = res.headers['set-cookie'] as string; + expect(updatedCookie).toEqual( + expect.stringContaining('cookie_name=cookie_value') + ); + }); + + test('should respect the default cookie config if not overriden', async () => { + await setup({}); + + const res = await fastify.inject({ + method: 'GET', + url: '/', + headers: { + cookie: 'cookie_name=anything' + } + }); + + expect(res.cookies[0]).toEqual({ + domain: 'www.example.com', + httpOnly: true, + name: 'cookie_name', + path: '/', + sameSite: 'Lax', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + value: expect.any(String), + secure: true + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fd8dca360d0d2bde0a600cf9f3cfeaa1a24e306 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookie-update.ts @@ -0,0 +1,40 @@ +import { FastifyPluginCallback } from 'fastify'; + +import type { CookieSerializeOptions } from './cookies.js'; + +type Options = { cookies: string[]; attributes: CookieSerializeOptions }; + +/** + * Plugin that updates the attributes of cookies in the response, without + * changing the value. + * + * @param fastify The Fastify instance. + * @param options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param options.cookies The names of the cookies to update. + * @param options.attributes The attributes to update the cookies with. NOTE: + * The attributes are merged with the default values given to \@fastify/cookie. + * @param done Callback to signal that the logic has completed. + */ +export const cookieUpdate: FastifyPluginCallback = ( + fastify, + options, + done +) => { + fastify.addHook('onSend', (request, reply, _payload, next) => { + for (const cookie of options.cookies) { + const oldCookie = request.cookies[cookie]; + if (!oldCookie) continue; + + const unsigned = reply.unsignCookie(oldCookie); + const raw = unsigned.valid ? unsigned.value : oldCookie; + void reply.setCookie(cookie, raw, options.attributes); + } + + request.log.trace('Updated cookies'); + + next(); + }); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c401685018b5a400d0b21c79273aacac601ed30d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.test.ts @@ -0,0 +1,140 @@ +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import fastifyCookie from '@fastify/cookie'; + +import { COOKIE_SECRET } from '../utils/env.js'; +import cookies from './cookies.js'; + +vi.mock('../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + COOKIE_DOMAIN: 'www.example.com', + FREECODECAMP_NODE_ENV: 'not-development' + }; +}); + +describe('cookies', () => { + let fastify: FastifyInstance; + + beforeEach(async () => { + fastify = Fastify(); + await fastify.register(cookies); + }); + + afterEach(async () => { + await fastify.close(); + }); + + test('should prefix signed cookies with "s:" (url-encoded)', async () => { + fastify.get('/test', async (req, reply) => { + void reply.setCookie('test', 'value', { signed: true }); + return { ok: true }; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.headers['set-cookie']).toMatch(/test=s%3Avalue\.\w*/); + }); + + test('should be able to unsign cookies', async () => { + const signedCookie = `test=s%3A${fastifyCookie.sign('value', COOKIE_SECRET)}`; + fastify.get('/test', (req, reply) => { + void reply.send({ unsigned: req.unsignCookie(req.cookies.test!) }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + cookie: signedCookie + } + }); + + expect(res.json()).toEqual({ + unsigned: { value: 'value', renew: false, valid: true } + }); + }); + + test('should reject cookies not prefixed with "s:"', async () => { + const signedCookie = `test=${fastifyCookie.sign('value', COOKIE_SECRET)}`; + fastify.get('/test', (req, reply) => { + void reply.send({ unsigned: req.unsignCookie(req.cookies.test!) }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + cookie: signedCookie + } + }); + + expect(res.json()).toEqual({ + unsigned: { value: null, renew: false, valid: false } + }); + }); + + test('should have reasonable defaults', async () => { + fastify.get('/test', async (req, reply) => { + void reply.setCookie('test', 'value'); + return { ok: true }; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + // No max-age, so we default to a session cookie. + expect(res.cookies[0]).toEqual({ + name: 'test', + // defaults: + domain: 'www.example.com', + httpOnly: true, + path: '/', + sameSite: 'Lax', + secure: true, + // sign by default: + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + value: expect.stringMatching(/s:value\.\w*/) + }); + }); + + // TODO(Post-MVP): Clear all cookies rather than just three specific ones? + // Then it should be called something like clearAllCookies. + test('clearOurCookies should clear cookies that we set', async () => { + fastify.get('/test', async (req, reply) => { + void reply.clearOurCookies(); + return { ok: true }; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.cookies).toStrictEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: 'jwt_access_token', + expires: new Date(0), + value: '' + }), + expect.objectContaining({ + name: '_csrf', + expires: new Date(0), + value: '' + }), + expect.objectContaining({ + name: 'csrf_token', + expires: new Date(0), + value: '' + }) + ]) + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.ts new file mode 100644 index 0000000000000000000000000000000000000000..663fdef2987be14764a986b8d68e6cef343de81f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cookies.ts @@ -0,0 +1,81 @@ +import fastifyCookie, { type UnsignResult } from '@fastify/cookie'; +import { FastifyPluginCallback } from 'fastify'; +import fp from 'fastify-plugin'; + +import { + COOKIE_DOMAIN, + COOKIE_SECRET, + FREECODECAMP_NODE_ENV +} from '../utils/env.js'; +import { CSRF_COOKIE, CSRF_SECRET_COOKIE } from './csrf.js'; + +export { type CookieSerializeOptions } from '@fastify/cookie'; + +declare module 'fastify' { + interface FastifyReply { + clearOurCookies: () => void; + } +} + +/** + * Signs a cookie value by prefixing it with "s:" and using the COOKIE_SECRET. + * + * @param value The value to sign. + * @returns The signed cookie value. + */ +export const sign = (value: string) => + 's:' + fastifyCookie.sign(value, COOKIE_SECRET); + +/** + * Unsigns a cookie value by removing the "s:" prefix and using the COOKIE_SECRET. + * + * @param rawValue The signed cookie value. + * @returns The unsigned cookie value. + */ +export const unsign = (rawValue: string): UnsignResult => { + const prefix = rawValue.slice(0, 2); + if (prefix !== 's:') return { valid: false, renew: false, value: null }; + + const value = rawValue.slice(2); + return fastifyCookie.unsign(value, COOKIE_SECRET); +}; + +/** + * Compatibility plugin for using cookies signed by express. By prefixing with + * "s:" and removing it when unsigning, we can continue to use the same cookies + * in Fastify. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +const cookies: FastifyPluginCallback = (fastify, _options, done) => { + void fastify.register(fastifyCookie, { + secret: { + sign, + unsign + }, + parseOptions: { + domain: COOKIE_DOMAIN, + httpOnly: FREECODECAMP_NODE_ENV !== 'development', + // Path is necessary to ensure that only one cookie is set and it is valid + // for all routes. + path: '/', + sameSite: 'lax', + secure: FREECODECAMP_NODE_ENV !== 'development', + signed: true + } + }); + + void fastify.decorateReply('clearOurCookies', function () { + void this.clearCookie('jwt_access_token'); + void this.clearCookie(CSRF_SECRET_COOKIE); + void this.clearCookie(CSRF_COOKIE); + + this.request.log.trace('Clearing cookies for user'); + }); + + done(); +}; + +export default fp(cookies, { name: 'cookies' }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f74131d3b7167fdf0425100b450281e6a6ff06d7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.test.ts @@ -0,0 +1,78 @@ +import { + describe, + test, + expect, + beforeAll, + afterAll, + afterEach, + vi +} from 'vitest'; +import Fastify, { FastifyInstance, LogLevel } from 'fastify'; +import cors from './cors.js'; + +const NON_DEBUG_LOG_LEVELS: LogLevel[] = [ + 'fatal', + 'error', + 'warn', + 'info', + 'trace' +]; + +describe('cors', () => { + let fastify: FastifyInstance; + beforeAll(async () => { + fastify = Fastify({ disableRequestLogging: true }); + await fastify.register(cors); + }); + + afterAll(async () => { + await fastify.close(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + test('should only debug log for /status/* routes', async () => { + const spies = NON_DEBUG_LOG_LEVELS.map(level => + vi.spyOn(fastify.log, level) + ); + const debugSpy = vi.spyOn(fastify.log, 'debug'); + await fastify.inject({ + url: '/status/ping' + }); + + spies.forEach(spy => { + expect(spy).not.toHaveBeenCalled(); + }); + expect(debugSpy).toHaveBeenCalled(); + }); + + test('should debug log if the origin is undefined', async () => { + const spies = NON_DEBUG_LOG_LEVELS.map(level => + vi.spyOn(fastify.log, level) + ); + const debugSpy = vi.spyOn(fastify.log, 'debug'); + await fastify.inject({ + url: '/api/some-endpoint' + }); + + spies.forEach(spy => { + expect(spy).not.toHaveBeenCalled(); + }); + expect(debugSpy).toHaveBeenCalled(); + }); + + test('should warn on a request from a disallowed origin', async () => { + const warnSpy = vi.spyOn(fastify.log, 'warn'); + await fastify.inject({ + url: '/api/some-endpoint', + headers: { origin: 'https://disallowed.example.com' } + }); + + expect(warnSpy).toHaveBeenCalledWith( + { _origin: 'https://disallowed.example.com' }, + 'Received request from disallowed origin' + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.ts new file mode 100644 index 0000000000000000000000000000000000000000..5519ea7d457c18b238520e2a0091f98fbb3846e4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/cors.ts @@ -0,0 +1,50 @@ +import { FastifyPluginCallback } from 'fastify'; +import fp from 'fastify-plugin'; + +import { HOME_LOCATION } from '../utils/env.js'; +import { allowedOrigins } from '../utils/allowed-origins.js'; + +const cors: FastifyPluginCallback = (fastify, _options, done) => { + fastify.options('*', (_req, reply) => { + void reply.send(); + }); + + fastify.addHook('onRequest', async (req, reply) => { + // `origin` is an undocumented reserved keyword in Sentry + // if used as attribute name in logs, it is overwritten in queries + // https://github.com/getsentry/sentry/issues/120640 + const _origin = req.headers.origin; + if (_origin && allowedOrigins.includes(_origin)) { + req.log.debug({ _origin }, 'Allowing access to origin'); + void reply.header('Access-Control-Allow-Origin', _origin); + } else { + // TODO: Discuss if this is the correct approach. Standard practice is to + // reflect one of a list of allowed origins and handle development + // separately. If we switch to that approach we can replace use + // @fastify/cors instead. + void reply.header('Access-Control-Allow-Origin', HOME_LOCATION); + + if (_origin && !req.url?.startsWith('/status/')) { + req.log.warn({ _origin }, 'Received request from disallowed origin'); + } else { + req.log.debug({ _origin }, 'Unknown or missing origin'); + } + } + + void reply + .header( + 'Access-Control-Allow-Headers', + 'Origin, X-Requested-With, Content-Type, Accept, Csrf-Token, Coderoad-User-Token, Exam-Environment-Authorization-Token' + ) + .header('Access-Control-Allow-Credentials', true) + // These 4 are the only methods we use + .header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE') + // Vary: Origin to prevent cache poisoning + // TODO: do we need Vary: Accept-Encoding? + .header('Vary', 'Origin, Accept-Encoding'); + }); + + done(); +}; + +export default fp(cors); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d6e918a26a7a6bd7a9194895f1b95216e3dbfaaf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.test.ts @@ -0,0 +1,109 @@ +import { describe, test, expect, beforeEach, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; + +import { COOKIE_DOMAIN } from '../utils/env.js'; +import cookies from './cookies.js'; +import csrf, { CSRF_COOKIE, CSRF_SECRET_COOKIE } from './csrf.js'; + +vi.mock('../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + COOKIE_DOMAIN: 'www.example.com', + FREECODECAMP_NODE_ENV: 'production' + }; +}); + +async function setupServer() { + const fastify = Fastify({ logger: true, disableRequestLogging: true }); + await fastify.register(cookies); + await fastify.register(csrf); + // eslint-disable-next-line @typescript-eslint/unbound-method + fastify.addHook('onRequest', fastify.csrfProtection); + + fastify.get('/', (_req, reply) => { + void reply.send({ foo: 'bar' }); + }); + return fastify; +} + +describe('CSRF protection', () => { + let fastify: FastifyInstance; + beforeEach(async () => { + fastify = await setupServer(); + }); + test('should receive a new CSRF token with the expected properties', async () => { + const response = await fastify.inject({ + method: 'GET', + url: '/' + }); + const newCookies = response.cookies; + const csrfTokenCookie = newCookies.find( + cookie => cookie.name === CSRF_COOKIE + ); + + const { value, ...rest } = csrfTokenCookie!; + + // The value is a random string - it's enough to check that it's not empty + expect(value).toHaveLength(52); + + expect(rest).toStrictEqual({ + name: CSRF_COOKIE, + path: '/', + sameSite: 'Strict', + domain: COOKIE_DOMAIN, + secure: true + }); + }); + + test('should return 403 if the _csrf secret is missing', async () => { + const response = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(response.statusCode).toEqual(403); + // The response body is determined by the error-handling plugin, so we don't + // check it here. + }); + + test('should return 403 if the csrf_token is invalid', async () => { + const response = await fastify.inject({ + method: 'GET', + url: '/', + cookies: { + _csrf: 'foo', + csrf_token: 'bar' + } + }); + expect(response.statusCode).toEqual(403); + }); + + test('should allow the request if the csrf_token is valid', async () => { + const csrfResponse = await fastify.inject({ + method: 'GET', + url: '/' + }); + + const csrfTokenCookie = csrfResponse.cookies.find( + cookie => cookie.name === CSRF_COOKIE + ); + const csrfSecretCookie = csrfResponse.cookies.find( + cookie => cookie.name === CSRF_SECRET_COOKIE + ); + + const res = await fastify.inject({ + method: 'GET', + url: '/', + cookies: { + _csrf: csrfSecretCookie!.value + }, + headers: { + 'csrf-token': csrfTokenCookie!.value + } + }); + + expect(res.json()).toEqual({ foo: 'bar' }); + expect(res.statusCode).toEqual(200); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.ts new file mode 100644 index 0000000000000000000000000000000000000000..86b78f96f56678ed15028d03f0f3e27d0f08d2e8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/csrf.ts @@ -0,0 +1,50 @@ +import type { FastifyPluginCallback } from 'fastify'; +import fastifyCsrfProtection from '@fastify/csrf-protection'; + +import fp from 'fastify-plugin'; + +export const CSRF_COOKIE = 'csrf_token'; +export const CSRF_HEADER = 'csrf-token'; +export const CSRF_SECRET_COOKIE = '_csrf'; + +/** + * Plugin for preventing CSRF attacks. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +const csrf: FastifyPluginCallback = (fastify, _options, done) => { + void fastify.register(fastifyCsrfProtection, { + // TODO: consider signing cookies. We don't on the api-server, but we could + // as an extra layer of security. + + ///Ignore all other possible sources of CSRF + // tokens since we know we can provide this one + getToken: req => req.headers[CSRF_HEADER] as string, + cookieOpts: { signed: false, sameSite: 'strict' }, + logLevel: 'silent' + }); + + // All routes except signout should add a CSRF token to the response + fastify.addHook('onRequest', (req, reply, done) => { + const isSignout = req.url === '/signout' || req.url === '/signout/'; + + if (!isSignout) { + req.log.trace('Adding CSRF token to response'); + const token = reply.generateCsrf(); + void reply.setCookie(CSRF_COOKIE, token, { + sameSite: 'strict', + signed: false, + // it needs to be read by the client, so that it can be sent in the + // header of the next request: + httpOnly: false + }); + } + done(); + }); + + done(); +}; + +export default fp(csrf, { dependencies: ['cookies'] }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..24bafe95c313a1157a94451fe9c96d696a10cc37 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.test.ts @@ -0,0 +1,356 @@ +import { + describe, + test, + expect, + beforeEach, + afterEach, + beforeAll, + afterAll, + vi +} from 'vitest'; +import Fastify, { FastifyError, type FastifyInstance } from 'fastify'; +import accepts from '@fastify/accepts'; +import { http, HttpResponse } from 'msw'; +import { setupServer } from 'msw/node'; + +vi.mock('../utils/env.js', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + SENTRY_DSN: 'https://anything@goes/123' + }; +}); + +import '../instrument'; +import errorHandling, { isExpectedClientError } from './error-handling.js'; +import redirectWithMessage, { formatMessage } from './redirect-with-message.js'; + +const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +describe('errorHandling', () => { + let fastify: FastifyInstance; + + beforeEach(async () => { + fastify = Fastify(); + await fastify.register(redirectWithMessage); + await fastify.register(accepts); + await fastify.register(errorHandling); + + fastify.get('/test', async (_req, _reply) => { + const error = Error('a very bad thing happened') as FastifyError; + error.statusCode = 500; + throw error; + }); + fastify.get('/test-bad-request', async (_req, _reply) => { + const error = Error('a very bad thing happened') as FastifyError; + error.statusCode = 400; + throw error; + }); + fastify.get('/test-csrf-token', async (_req, _reply) => { + const error = Error() as FastifyError; + error.code = 'FST_CSRF_INVALID_TOKEN'; + error.statusCode = 403; + throw error; + }); + + fastify.get('/test-csrf-secret', async (_req, _reply) => { + const error = Error() as FastifyError; + error.code = 'FST_CSRF_MISSING_SECRET'; + error.statusCode = 403; + throw error; + }); + }); + + afterEach(async () => { + await fastify.close(); + vi.clearAllMocks(); + }); + + test('should redirect to the referer if the request does not Accept json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + accept: 'text/plain' + } + }); + + expect(res.statusCode).toEqual(302); + }); + + test('should add a generic flash message if it is a server error (i.e. 500+)', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + accept: 'text/plain' + } + }); + + expect(res.headers['location']).toEqual( + 'https://www.freecodecamp.org/anything?' + + formatMessage({ + type: 'danger', + content: 'flash.generic-error' + }) + ); + }); + + test('should return a json response if the request does Accept json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + accept: 'application/json,text/plain' + } + }); + + expect(res.statusCode).toEqual(500); + expect(res.json()).toEqual({ + message: 'flash.generic-error', + type: 'danger' + }); + }); + + test('should redirect if the request prefers text/html to json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + // this does accept json, (via the */*), but prefers text/html + accept: 'text/html,*/*' + } + }); + + expect(res.statusCode).toEqual(302); + }); + + test('should respect the error status code', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test-bad-request' + }); + + expect(res.statusCode).toEqual(400); + }); + + test('should return the error message if the status is not 500', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test-bad-request' + }); + + expect(res.json()).toEqual({ + message: 'a very bad thing happened', + type: 'danger' + }); + }); + + test('should convert CSRF errors to a generic error message', async () => { + const resToken = await fastify.inject({ + method: 'GET', + url: '/test-csrf-token' + }); + const resSecret = await fastify.inject({ + method: 'GET', + url: '/test-csrf-secret' + }); + + expect(resToken.json()).toEqual({ + message: 'flash.generic-error', + type: 'danger' + }); + expect(resSecret.json()).toEqual({ + message: 'flash.generic-error', + type: 'danger' + }); + }); + + test('should call fastify.log.error when an unhandled error occurs', async () => { + const logSpy = vi.spyOn(fastify.log, 'error'); + + await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + 'x-forwarded-for': '203.0.113.7', + 'cf-ipcountry': 'US' + } + }); + + expect(logSpy).toHaveBeenCalledWith( + expect.objectContaining({ + err: expect.objectContaining({ + message: 'a very bad thing happened' + }) as unknown, + ip: '203.0.113.7', + country: 'US' + }), + 'Error in request' + ); + }); + + test('should call fastify.log.warn when a bad request error occurs', async () => { + const logSpy = vi.spyOn(fastify.log, 'warn'); + + await fastify.inject({ + method: 'GET', + url: '/test-bad-request' + }); + + expect(logSpy).toHaveBeenCalledWith( + expect.objectContaining({ + err: expect.objectContaining({ + message: 'a very bad thing happened' + }) as unknown + }), + 'Client error in request' + ); + }); + + test('should NOT log when a CSRF error is thrown', async () => { + const errorLogSpy = vi.spyOn(fastify.log, 'error'); + const warnLogSpy = vi.spyOn(fastify.log, 'warn'); + + await fastify.inject({ + method: 'GET', + url: '/test-csrf-token' + }); + + expect(errorLogSpy).not.toHaveBeenCalled(); + expect(warnLogSpy).not.toHaveBeenCalled(); + + await fastify.inject({ + method: 'GET', + url: '/test-csrf-secret' + }); + + expect(errorLogSpy).not.toHaveBeenCalled(); + expect(warnLogSpy).not.toHaveBeenCalled(); + }); + + test('counts a security.csrf_rejected metric with the error code as reason', async () => { + const count = vi.fn(); + fastify.Sentry = { + ...fastify.Sentry, + metrics: { ...fastify.Sentry.metrics, count } + }; + + await fastify.inject({ method: 'GET', url: '/test-csrf-token' }); + + expect(count).toHaveBeenCalledWith('security.csrf_rejected', 1, { + attributes: { reason: 'FST_CSRF_INVALID_TOKEN' } + }); + }); + + describe('Sentry integration', () => { + let mockServer: ReturnType; + + beforeAll(() => { + // The assumption is that Sentry is the only library making requests. Also, we + // only want to know if a request was made, not what it was. + const sentryHandler = http.post('*', () => + HttpResponse.json({ success: true }) + ); + mockServer = setupServer(sentryHandler); + mockServer.listen(); + }); + + afterEach(() => { + mockServer.resetHandlers(); + }); + + afterAll(() => { + mockServer.close(); + }); + + const createRequestListener = () => + new Promise(resolve => { + mockServer.events.on('request:start', () => { + resolve(true); + }); + }); + + test.todo('should capture the error with Sentry', async () => { + const receivedRequest = createRequestListener(); + + await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(await Promise.race([receivedRequest, delay(2000)])).toBe(true); + }); + + test('should NOT capture CSRF token errors with Sentry', async () => { + const receivedRequest = createRequestListener(); + + await fastify.inject({ + method: 'GET', + url: '/test-csrf-token' + }); + + expect(await Promise.race([receivedRequest, delay(200)])).toBeUndefined(); + }); + + test('should NOT capture CSRF secret errors with Sentry', async () => { + const receivedRequest = createRequestListener(); + + await fastify.inject({ + method: 'GET', + url: '/test-csrf-secret' + }); + + expect(await Promise.race([receivedRequest, delay(200)])).toBeUndefined(); + }); + + test('should NOT capture bad requests with Sentry', async () => { + const receivedRequest = createRequestListener(); + + await fastify.inject({ + method: 'GET', + url: '/test-bad-request' + }); + + expect(await Promise.race([receivedRequest, delay(200)])).toBeUndefined(); + }); + }); +}); + +describe('isExpectedClientError', () => { + test('should return true for a 404 status code', () => { + expect(isExpectedClientError({ statusCode: 404 })).toBe(true); + }); + + test('should return true for a 400 status code', () => { + expect(isExpectedClientError({ statusCode: 400 })).toBe(true); + }); + + test('should return false for a 500 status code', () => { + expect(isExpectedClientError({ statusCode: 500 })).toBe(false); + }); + + test('should return false for a 503 status code', () => { + expect(isExpectedClientError({ statusCode: 503 })).toBe(false); + }); + + test('should return false for an error with no status code', () => { + expect(isExpectedClientError(new Error())).toBe(false); + }); + + test('should return false for null', () => { + expect(isExpectedClientError(null)).toBe(false); + }); + + test('should return false for undefined', () => { + expect(isExpectedClientError(undefined)).toBe(false); + }); + + test('should return false for a non-numeric status code', () => { + expect(isExpectedClientError({ statusCode: '404' })).toBe(false); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf5f5843acea46e4fc8a325879d5d1a29f111f8b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/error-handling.ts @@ -0,0 +1,85 @@ +import type { FastifyError, FastifyPluginCallback } from 'fastify'; +import * as Sentry from '@sentry/node'; +import fp from 'fastify-plugin'; + +import { getRedirectParams } from '../utils/redirection.js'; +import { clientNetInfo } from '../utils/logger.js'; + +declare module 'fastify' { + interface FastifyInstance { + Sentry: typeof Sentry; + } +} + +/** + * Plugin to handle errors and send them to Sentry. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +export const isExpectedClientError = (error: unknown): boolean => + typeof error === 'object' && + error !== null && + 'statusCode' in error && + typeof (error as { statusCode?: unknown }).statusCode === 'number' && + (error as { statusCode: number }).statusCode < 500; + +const errorHandling: FastifyPluginCallback = (fastify, _options, done) => { + Sentry.setupFastifyErrorHandler(fastify, { + shouldHandleError: error => !isExpectedClientError(error) + }); + + fastify.decorate('Sentry', Sentry); + + fastify.setErrorHandler((error: FastifyError, request, reply) => { + const accepts = request.accepts().type(['json', 'html']); + const { returnTo } = getRedirectParams(request); + + if (!reply.statusCode || reply.statusCode === 200) { + const statusCode = + error.statusCode && error.statusCode >= 400 ? error.statusCode : 500; + reply.code(statusCode); + } + + const isCSRFError = + error.code === 'FST_CSRF_INVALID_TOKEN' || + error.code === 'FST_CSRF_MISSING_SECRET'; + + if (!isCSRFError) { + const context = { err: error, ...clientNetInfo(request) }; + if (reply.statusCode >= 500) { + request.log.error(context, 'Error in request'); + } else { + request.log.warn(context, 'Client error in request'); + } + } else { + fastify.Sentry?.metrics?.count('security.csrf_rejected', 1, { + attributes: { reason: error.code } + }); + } + + const message = + reply.statusCode === 500 || isCSRFError + ? 'flash.generic-error' + : error.message; + if (accepts === 'json') { + void reply.send({ + message, + type: 'danger' + }); + } else { + void reply.status(302); + void reply.redirectWithMessage(returnTo, { + type: 'danger', + content: message + }); + } + }); + + done(); +}; + +export default fp(errorHandling, { + dependencies: ['redirect-with-message', '@fastify/accepts'] +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f09cc11ea7eba151b1c98fa1538932d85fc02c6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.test.ts @@ -0,0 +1,32 @@ +import { describe, test, expect, beforeAll, afterAll, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import growthBook from './growth-book.js'; + +const captureException = vi.fn(); +const count = vi.fn(); + +describe('growth-book', () => { + let fastify: FastifyInstance; + beforeAll(() => { + fastify = Fastify(); + // @ts-expect-error we're mocking the Sentry plugin + fastify.Sentry = { captureException, metrics: { count } }; + }); + + afterAll(async () => { + await fastify.close(); + }); + + test('should log and capture the error if the GrowthBook initialization fails', async () => { + const spy = vi.spyOn(fastify.log, 'error'); + + await fastify.register(growthBook, { + apiHost: 'invalid-url', + clientKey: 'invalid-key' + }); + + expect(spy).toHaveBeenCalled(); + expect(captureException).toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith('growthbook.init_failed', 1); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f6199d769a18f4471ea6df0406704353831509e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/growth-book.ts @@ -0,0 +1,33 @@ +import { GrowthBook, Options } from '@growthbook/growthbook'; +import { FastifyPluginAsync } from 'fastify'; +import fp from 'fastify-plugin'; + +declare module 'fastify' { + interface FastifyInstance { + gb: GrowthBook; + } +} + +const growthBook: FastifyPluginAsync = async (fastify, options) => { + const gb = new GrowthBook(options); + + const hasRequiredConfig = Boolean(options.clientKey && options.apiHost); + + if (hasRequiredConfig) { + const res = await gb.init({ timeout: 3000 }); + + if (res.error) { + fastify.log.error(res.error, 'Failed to initialize GrowthBook'); + fastify.Sentry?.captureException(res.error); + fastify.Sentry?.metrics?.count('growthbook.init_failed', 1); + } + } + + fastify.decorate('gb', gb); + + fastify.addHook('onClose', () => { + gb.destroy(); + }); +}; + +export default fp(growthBook); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mail-providers/nodemailer.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mail-providers/nodemailer.ts new file mode 100644 index 0000000000000000000000000000000000000000..944d4502c700d5afca7fb495d59179a6abd85421 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mail-providers/nodemailer.ts @@ -0,0 +1,78 @@ +import nodemailer, { Transporter } from 'nodemailer'; + +import { MailProvider, SendEmailArgs } from '../mailer.js'; +import { + EMAIL_PROVIDER, + MAILPIT_HOST, + SES_SMTP_HOST, + SES_SMTP_USERNAME, + SES_SMTP_PASSWORD +} from '../../utils/env.js'; + +export type NodemailerConfig = { + host: string; + port: number; + secure: boolean; + auth: { user: string; pass: string }; + tls?: { rejectUnauthorized: boolean }; +}; + +/** + * NodemailerProvider is a wrapper around nodemailer that provides a clean + * interface for sending email. + */ +export class NodemailerProvider implements MailProvider { + private transporter: Transporter; + + /** + * Sets up nodemailer with the provided configuration. + * + * @param config - The nodemailer transport configuration. + */ + constructor(config: NodemailerConfig) { + this.transporter = nodemailer.createTransport(config); + } + + /** + * Sends an email using nodemailer. + * + * @param param Email options. + * @param param.to Email address to send to. + * @param param.from Email address to send from. + * @param param.subject Email subject. + * @param param.text Email body (raw text only). + * @param param.cc [Optional] Email address to CC. + */ + async send({ to, from, subject, text, cc }: SendEmailArgs) { + await this.transporter.sendMail({ + from, + to, + subject, + text, + cc + }); + } +} + +/** + * Creates a mail provider based on the EMAIL_PROVIDER environment variable. + */ +export function createMailProvider(): NodemailerProvider { + return EMAIL_PROVIDER === 'ses' + ? new NodemailerProvider({ + host: SES_SMTP_HOST, + port: 465, + secure: true, + auth: { + user: SES_SMTP_USERNAME ?? '', + pass: SES_SMTP_PASSWORD ?? '' + } + }) + : new NodemailerProvider({ + host: MAILPIT_HOST, + port: 1025, + secure: false, + auth: { user: 'test', pass: 'test' }, + tls: { rejectUnauthorized: false } + }); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..580187da46a7e76de882258a6dd80ce460031d7c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.test.ts @@ -0,0 +1,47 @@ +import { describe, test, expect, vi } from 'vitest'; +import Fastify from 'fastify'; + +import mailer from './mailer.js'; + +describe('mailer', () => { + test('should send an email via the provider', async () => { + const fastify = Fastify(); + const send = vi.fn(); + await fastify.register(mailer, { provider: { send } }); + + const data = { + to: 'test@add.ress', + from: 'team@freecodecamp.org', + subject: 'test', + text: 'test' + }; + + await fastify.sendEmail(data); + + expect(send).toHaveBeenCalledWith(data); + }); + + test('should emit a Sentry counter and re-throw when the provider fails to send', async () => { + const fastify = Fastify(); + const sendError = new Error('send failed'); + const send = vi.fn().mockRejectedValue(sendError); + await fastify.register(mailer, { provider: { send } }); + + const count = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { metrics: { count } }; + + const data = { + to: 'test@add.ress', + from: 'team@freecodecamp.org', + subject: 'test', + text: 'test' + }; + + await expect(fastify.sendEmail(data)).rejects.toThrow(sendError); + + expect(count).toHaveBeenCalledWith('mailer.send_failed', 1, { + attributes: { result: 'error' } + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.ts new file mode 100644 index 0000000000000000000000000000000000000000..e16248b54cc5924e48f5811ff49dc3e5b104d736 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/mailer.ts @@ -0,0 +1,46 @@ +import type { FastifyPluginCallback } from 'fastify'; +import fp from 'fastify-plugin'; + +declare module 'fastify' { + interface FastifyInstance { + sendEmail: SendEmail; + } +} + +export type SendEmailArgs = { + to: string; + from: string; + subject: string; + text: string; + cc?: string; +}; + +type SendEmail = (args: SendEmailArgs) => Promise; + +export interface MailProvider { + send: SendEmail; +} + +const plugin: FastifyPluginCallback<{ provider: MailProvider }> = ( + fastify, + options, + done +) => { + const { provider } = options; + + fastify.decorate('sendEmail', async (args: SendEmailArgs) => { + fastify.log.info({ subject: args.subject }, 'Sending email'); + try { + return await provider.send(args); + } catch (error) { + fastify.Sentry?.metrics?.count('mailer.send_failed', 1, { + attributes: { result: 'error' } + }); + throw error; + } + }); + + done(); +}; + +export default fp(plugin); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2eb533fda54bc0451230020b65e860552676f24f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.test.ts @@ -0,0 +1,76 @@ +import { describe, beforeEach, afterEach, it, expect } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import accepts from '@fastify/accepts'; + +import notFound from './not-found.js'; +import redirectWithMessage, { formatMessage } from './redirect-with-message.js'; + +describe('fourOhFour', () => { + let fastify: FastifyInstance; + + beforeEach(async () => { + fastify = Fastify(); + await fastify.register(redirectWithMessage); + await fastify.register(accepts); + await fastify.register(notFound); + }); + + afterEach(async () => { + await fastify.close(); + }); + + it('should redirect to origin/404 if the request does not Accept json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + accept: 'text/plain' + } + }); + + expect(res.headers['location']).toEqual( + 'https://www.freecodecamp.org/404?' + + formatMessage({ + type: 'danger', + content: "We couldn't find path /test" + }) + ); + expect(res.statusCode).toEqual(302); + }); + + it('should return a 404 json response if the request does Accept json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + accept: 'application/json,text/plain' + } + }); + + expect(res.json()).toEqual({ error: 'path not found' }); + expect(res.statusCode).toEqual(404); + }); + + it('should redirect if the request prefers text/html to json', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + referer: 'https://www.freecodecamp.org/anything', + // this does accept json, (via the */*), but prefers text/html + accept: 'text/html,*/*' + } + }); + + expect(res.headers['location']).toEqual( + 'https://www.freecodecamp.org/404?' + + formatMessage({ + type: 'danger', + content: "We couldn't find path /test" + }) + ); + expect(res.statusCode).toEqual(302); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.ts new file mode 100644 index 0000000000000000000000000000000000000000..385d7cb09488e80222891cd12698ea2a4a75f1cc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/not-found.ts @@ -0,0 +1,37 @@ +import type { FastifyPluginCallback } from 'fastify'; + +import fp from 'fastify-plugin'; + +import { getRedirectParams } from '../utils/redirection.js'; + +/** + * Plugin for handling missing endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +const fourOhFour: FastifyPluginCallback = (fastify, _options, done) => { + // If the request accepts JSON and does not specifically prefer text/html, + // this will return a 404 JSON response. Everything else will be redirected. + fastify.setNotFoundHandler((req, reply) => { + req.log.debug('User requested path that does not exist'); + + const accepted = req.accepts().type(['json', 'html']); + if (accepted == 'json') { + void reply.code(404).send({ error: 'path not found' }); + } else { + const { origin } = getRedirectParams(req); + void reply.status(302); + void reply.redirectWithMessage(`${origin}/404`, { + type: 'danger', + content: `We couldn't find path ${req.url}` + }); + } + }); + done(); +}; + +export default fp(fourOhFour, { + dependencies: ['redirect-with-message', '@fastify/accepts'] +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a01ee397bb0acc1fcb7e040abd551f8c43c0cf0b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.test.ts @@ -0,0 +1,102 @@ +import { describe, test, expect, beforeEach } from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; +import qs from 'query-string'; + +import redirectWithMessage from './redirect-with-message.js'; + +async function setupServer() { + const fastify = Fastify(); + await fastify.register(redirectWithMessage); + return fastify; +} + +const isString = (value: unknown): value is string => { + return typeof value === 'string'; +}; + +describe('redirectWithMessage plugin', () => { + test('should decorate reply object with redirectWithMessage method', async () => { + expect.assertions(3); + + const fastify = await setupServer(); + + fastify.get('/', (_req, reply) => { + expect(reply).toHaveProperty('redirectWithMessage'); + expect(reply.redirectWithMessage).toBeInstanceOf(Function); + return { foo: 'bar' }; + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.statusCode).toEqual(200); + }); + + describe('redirectWithMessage method', () => { + let fastify: FastifyInstance; + beforeEach(async () => { + fastify = await setupServer(); + }); + + test('should redirect to the first argument', async () => { + fastify.get('/', (_req, reply) => { + return reply.redirectWithMessage('/target', { + type: 'info', + content: 'foo' + }); + }); + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.headers.location).toMatch(/^\/target/); + expect(res.statusCode).toEqual(302); + }); + + test('should convert the second argument into a query string', async () => { + fastify.get('/', (_req, reply) => { + return reply.redirectWithMessage('/target', { + type: 'info', + content: 'foo' + }); + }); + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + + expect(res.headers.location).toMatch(/^\/target\?messages=info/); + }); + + test('should encode the message twice when creating the query string', async () => { + const expectedMessage = { danger: ['foo bar'] }; + + fastify.get('/', (_req, reply) => { + return reply.redirectWithMessage('/target', { + type: 'danger', + content: 'foo bar' + }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/' + }); + if (!isString(res.headers.location)) + throw new Error('Location is not a string'); + const { search } = new URL(res.headers.location, 'http://localhost'); + + // The query string itself is encoded: + const { messages } = qs.parse(search, { arrayFormat: 'index' }); + if (!isString(messages)) throw new Error('Messages is not a string'); + + // As is the message embedded in it: + expect(qs.parse(messages, { arrayFormat: 'index' })).toEqual( + expectedMessage + ); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.ts new file mode 100644 index 0000000000000000000000000000000000000000..683f589b8dddd5dfacbab2ee00db8310a7fb2765 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/redirect-with-message.ts @@ -0,0 +1,60 @@ +import { FastifyPluginCallback, type FastifyReply } from 'fastify'; +import fp from 'fastify-plugin'; +// TODO: (POST MVP)use node's querystring and just JSON stringify the message. +// No need for query-string on either side. +import qs from 'query-string'; + +declare module 'fastify' { + interface FastifyReply { + redirectWithMessage: typeof redirectWithMessage; + } +} + +type Message = { + type: 'info' | 'danger' | 'success' | 'errors'; + content: string; +}; + +type MessageQuery = { + info?: string[]; + danger?: string[]; + success?: string[]; + errors?: string[]; +}; + +// The client expects a message like { info: ['foo'] }, { danger: ['bar'] } etc. +const prepareMessage = (message: Message): MessageQuery => ({ + [message.type]: [message.content] +}); + +function redirectWithMessage( + this: FastifyReply, + url: string, + message: Message +) { + return this.redirect(`${url}?${formatMessage(message)}`); +} + +/** + * Formats the message into a querystring. + * @param message The message to format. + * @returns The formatted message string. + */ +export function formatMessage(message: Message): string { + return qs.stringify( + { + messages: qs.stringify(prepareMessage(message), { + arrayFormat: 'index' + }) + }, + { arrayFormat: 'index' } + ); +} + +const plugin: FastifyPluginCallback = (fastify, _options, done) => { + fastify.decorateReply('redirectWithMessage', redirectWithMessage); + + done(); +}; + +export default fp(plugin, { name: 'redirect-with-message' }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..13cd1a5f4060d30670952968175cd64cedbfa68b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.test.ts @@ -0,0 +1,44 @@ +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; +import runtimeMetrics from './runtime-metrics.js'; + +const gauge = vi.fn(); + +describe('runtime-metrics', () => { + let fastify: FastifyInstance; + + beforeEach(() => { + vi.useFakeTimers(); + gauge.mockClear(); + fastify = Fastify(); + // @ts-expect-error we're mocking the Sentry plugin + fastify.Sentry = { metrics: { gauge } }; + }); + + afterEach(async () => { + await fastify.close(); + vi.useRealTimers(); + }); + + test('emits the memory rss gauge tagged with the byte unit', async () => { + await fastify.register(runtimeMetrics); + await vi.advanceTimersByTimeAsync(15_000); + + expect(gauge).toHaveBeenCalledWith( + 'runtime.memory_rss_bytes', + expect.any(Number), + { unit: 'byte' } + ); + }); + + test('emits the event loop delay gauge tagged with the millisecond unit', async () => { + await fastify.register(runtimeMetrics); + await vi.advanceTimersByTimeAsync(15_000); + + expect(gauge).toHaveBeenCalledWith( + 'runtime.event_loop_delay_p99_ms', + expect.any(Number), + { unit: 'millisecond' } + ); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.ts new file mode 100644 index 0000000000000000000000000000000000000000..0274fc6643bc07ba9c32916e7dfda5ef31025ecc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/runtime-metrics.ts @@ -0,0 +1,35 @@ +import { monitorEventLoopDelay } from 'node:perf_hooks'; +import type { FastifyPluginCallback } from 'fastify'; +import fp from 'fastify-plugin'; + +const SAMPLE_INTERVAL_MS = 15_000; + +const runtimeMetrics: FastifyPluginCallback = (fastify, _options, done) => { + const loopDelay = monitorEventLoopDelay({ resolution: 20 }); + loopDelay.enable(); + + const timer = setInterval(() => { + fastify.Sentry?.metrics?.gauge( + 'runtime.memory_rss_bytes', + process.memoryUsage().rss, + { unit: 'byte' } + ); + fastify.Sentry?.metrics?.gauge( + 'runtime.event_loop_delay_p99_ms', + loopDelay.percentile(99) / 1e6, + { unit: 'millisecond' } + ); + loopDelay.reset(); + }, SAMPLE_INTERVAL_MS); + timer.unref(); + + fastify.addHook('onClose', (_instance, hookDone) => { + clearInterval(timer); + loopDelay.disable(); + hookDone(); + }); + + done(); +}; + +export default fp(runtimeMetrics, { name: 'runtime-metrics' }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/security.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/security.ts new file mode 100644 index 0000000000000000000000000000000000000000..da9efd51cfc17e5485fa4bc90f554007e1fd9322 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/security.ts @@ -0,0 +1,27 @@ +import { FastifyPluginCallback } from 'fastify'; +import fp from 'fastify-plugin'; + +import { FREECODECAMP_NODE_ENV } from '../utils/env.js'; + +const securityHeaders: FastifyPluginCallback = (fastify, _options, done) => { + // OWASP recommended headers + fastify.addHook('onRequest', async (req, reply) => { + void reply + .header('Cache-Control', 'no-store') + .header('Content-Security-Policy', "frame-ancestors 'none'") + .header('X-Content-Type-Options', 'nosniff') + .header('X-Frame-Options', 'DENY'); + // TODO: Increase this gradually to 2 years. Include preload once it is + // at least 1 year. + if (FREECODECAMP_NODE_ENV === 'production') { + void reply.header( + 'Strict-Transport-Security', + 'max-age=300; includeSubDomains' + ); + } + }); + + done(); +}; + +export default fp(securityHeaders); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..26753901ea0765bf58b4aeac57d9dedd28e673f1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.test.ts @@ -0,0 +1,156 @@ +import { describe, test, expect, beforeEach, afterEach, vi } from 'vitest'; +import Fastify, { type FastifyInstance } from 'fastify'; + +vi.mock('../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + TPA_API_BEARER_TOKEN: 'test-api-secret-key' + }; +}); + +import serviceBearerAuth from './service-bearer-auth.js'; + +describe('service-bearer-auth plugin', () => { + let fastify: FastifyInstance; + + let captureException: ReturnType; + + beforeEach(async () => { + fastify = Fastify(); + await fastify.register(serviceBearerAuth); + captureException = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { captureException }; + fastify.addHook('onRequest', fastify.validateBearerToken); + fastify.get('/test', (_req, reply) => { + void reply.send({ ok: true }); + }); + }); + + afterEach(async () => { + await fastify.close(); + }); + + test('should allow request with valid bearer token', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: 'Bearer test-api-secret-key' + } + }); + + expect(res.statusCode).toEqual(200); + expect(res.json()).toEqual({ ok: true }); + expect(captureException).not.toHaveBeenCalled(); + }); + + test('should return 401 when authorization header is missing', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test' + }); + + expect(res.statusCode).toEqual(401); + expect(res.json()).toEqual({ error: 'Bearer token is required' }); + }); + + test('should return 401 when authorization header has no Bearer prefix', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: 'test-api-secret-key' + } + }); + + expect(res.statusCode).toEqual(401); + expect(res.json()).toEqual({ error: 'Bearer token is required' }); + }); + + test('should return 401 when bearer token is empty', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: 'Bearer ' + } + }); + + expect(res.statusCode).toEqual(401); + expect(res.json()).toEqual({ error: 'Invalid bearer token' }); + }); + + test('should return 401 when bearer token is wrong', async () => { + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: 'Bearer wrong-key' + } + }); + + expect(res.statusCode).toEqual(401); + expect(res.json()).toEqual({ error: 'Invalid bearer token' }); + }); + + test('should return 401 when bearer token is the same length but wrong', async () => { + const sameLengthWrongToken = 'x'.repeat('test-api-secret-key'.length); + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: `Bearer ${sameLengthWrongToken}` + } + }); + + expect(res.statusCode).toEqual(401); + expect(res.json()).toEqual({ error: 'Invalid bearer token' }); + }); +}); + +describe('service-bearer-auth plugin without a configured token', () => { + afterEach(() => { + vi.doUnmock('../utils/env'); + vi.resetModules(); + }); + + test('should return 500 when TPA_API_BEARER_TOKEN is not configured', async () => { + vi.resetModules(); + vi.doMock('../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { ...actual, TPA_API_BEARER_TOKEN: '' }; + }); + + const { default: plugin } = await import('./service-bearer-auth.js'); + const fastify = Fastify(); + await fastify.register(plugin); + const captureException = vi.fn(); + // @ts-expect-error Sentry isn't decorated in this minimal test app. + fastify.Sentry = { captureException }; + fastify.addHook('onRequest', fastify.validateBearerToken); + fastify.get('/test', (_req, reply) => { + void reply.send({ ok: true }); + }); + + const res = await fastify.inject({ + method: 'GET', + url: '/test', + headers: { + authorization: 'Bearer anything' + } + }); + + expect(res.statusCode).toEqual(500); + expect(res.json()).toEqual({ + error: 'Service authentication not configured' + }); + expect(captureException).toHaveBeenCalledTimes(1); + expect(captureException).toHaveBeenCalledWith( + new Error('TPA_API_BEARER_TOKEN is not configured') + ); + + await fastify.close(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d9713e7033d454f511086b25291312aae11593b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/plugins/service-bearer-auth.ts @@ -0,0 +1,59 @@ +import crypto from 'node:crypto'; +import type { + FastifyPluginCallback, + FastifyRequest, + FastifyReply +} from 'fastify'; +import fp from 'fastify-plugin'; + +import { TPA_API_BEARER_TOKEN } from '../utils/env.js'; + +declare module 'fastify' { + interface FastifyInstance { + validateBearerToken: ( + req: FastifyRequest, + reply: FastifyReply + ) => Promise; + } +} + +const plugin: FastifyPluginCallback = (fastify, _options, done) => { + fastify.decorate( + 'validateBearerToken', + async function (req: FastifyRequest, reply: FastifyReply) { + const secret = TPA_API_BEARER_TOKEN ?? ''; + if (secret.length === 0) { + req.log.error('TPA_API_BEARER_TOKEN is not configured'); + fastify.Sentry?.captureException( + new Error('TPA_API_BEARER_TOKEN is not configured') + ); + await reply + .status(500) + .send({ error: 'Service authentication not configured' }); + return; + } + + const authHeader = req.headers.authorization; + + if (!authHeader || !authHeader.startsWith('Bearer ')) { + await reply.status(401).send({ error: 'Bearer token is required' }); + return; + } + + const token = authHeader.slice(7); + const tokenBuf = Buffer.from(token); + const secretBuf = Buffer.from(secret); + if ( + tokenBuf.length !== secretBuf.length || + !crypto.timingSafeEqual(tokenBuf, secretBuf) + ) { + await reply.status(401).send({ error: 'Invalid bearer token' }); + return; + } + } + ); + + done(); +}; + +export default fp(plugin, { name: 'service-bearer-auth' }); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/reset.d.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/reset.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..12bd3edc94a4541c3a0438c72612d19b226c33aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/reset.d.ts @@ -0,0 +1 @@ +import '@total-typescript/ts-reset'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f91d43cbdbffa36a410c8bae60c3e8c2a18a903 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.test.ts @@ -0,0 +1,334 @@ +import { describe, test, expect, afterEach, vi } from 'vitest'; + +vi.mock('../../utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + TPA_API_BEARER_TOKEN: 'test-classroom-api-secret', + FCC_ENABLE_CLASSROOM: true + }; +}); + +import request from 'supertest'; + +import { createUserInput } from '../../utils/create-user.js'; +import { + defaultUserEmail, + defaultUserId, + resetDefaultUser, + setupServer +} from '../../../vitest.utils.js'; + +const BEARER_TOKEN = 'test-classroom-api-secret'; + +const classroomUserEmail = 'student1@example.com'; +const nonClassroomUserEmail = 'student2@example.com'; +const classroomUserId = '000000000000000000000001'; +const nonClassroomUserId = '000000000000000000000002'; + +function post(url: string) { + return request(fastifyTestInstance.server) + .post(url) + .set('authorization', `Bearer ${BEARER_TOKEN}`); +} + +describe('classroom routes', () => { + setupServer(); + + afterEach(async () => { + vi.restoreAllMocks(); + + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: { in: [classroomUserEmail, nonClassroomUserEmail] } } + }); + + await resetDefaultUser(); + }); + + describe('Without bearer token', () => { + test('POST get-user-id returns 401', async () => { + const res = await request(fastifyTestInstance.server) + .post('/apps/classroom/get-user-id') + .send({ email: 'someone@example.com' }); + + expect(res.status).toBe(401); + expect(res.body).toStrictEqual({ error: 'Bearer token is required' }); + }); + + test('POST get-user-data returns 401', async () => { + const res = await request(fastifyTestInstance.server) + .post('/apps/classroom/get-user-data') + .send({ userIds: [defaultUserId] }); + + expect(res.status).toBe(401); + expect(res.body).toStrictEqual({ error: 'Bearer token is required' }); + }); + }); + + describe('With wrong bearer token', () => { + test('POST get-user-id returns 401', async () => { + const res = await request(fastifyTestInstance.server) + .post('/apps/classroom/get-user-id') + .set('authorization', 'Bearer wrong-key') + .send({ email: 'someone@example.com' }); + + expect(res.status).toBe(401); + expect(res.body).toStrictEqual({ error: 'Invalid bearer token' }); + }); + + test('POST get-user-data returns 401', async () => { + const res = await request(fastifyTestInstance.server) + .post('/apps/classroom/get-user-data') + .set('authorization', 'Bearer wrong-key') + .send({ userIds: [defaultUserId] }); + + expect(res.status).toBe(401); + expect(res.body).toStrictEqual({ error: 'Invalid bearer token' }); + }); + }); + + describe('Authenticated with API key', () => { + describe('POST /apps/classroom/get-user-id', () => { + test('returns 400 for missing email', async () => { + const res = await post('/apps/classroom/get-user-id').send({}); + + expect(res.status).toBe(400); + }); + + test('returns 400 for invalid email format', async () => { + const res = await post('/apps/classroom/get-user-id').send({ + email: 'not-an-email' + }); + + expect(res.status).toBe(400); + }); + + test('returns 200 with empty userId when no classroom account matches email', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await post('/apps/classroom/get-user-id').send({ + email: defaultUserEmail + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.status).toBe(200); + expect(res.body).toStrictEqual({ userId: '' }); + expect(count).toHaveBeenCalledWith('classroom.user_looked_up', 1, { + attributes: { result: 'not_found' } + }); + }); + + test('returns 200 with userId for a classroom account', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isClassroomAccount: true } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await post('/apps/classroom/get-user-id').send({ + email: defaultUserEmail + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.status).toBe(200); + expect(res.body).toStrictEqual({ userId: defaultUserId }); + expect(count).toHaveBeenCalledWith('classroom.user_looked_up', 1, { + attributes: { result: 'found' } + }); + }); + + test('returns 500 and captures when the database query fails', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + + const original = fastifyTestInstance.prisma.user.findFirst; + fastifyTestInstance.prisma.user.findFirst = vi + .fn() + .mockRejectedValue(new Error('test')) as typeof original; + + const res = await post('/apps/classroom/get-user-id').send({ + email: defaultUserEmail + }); + + fastifyTestInstance.prisma.user.findFirst = original; + fastifyTestInstance.Sentry = originalSentry; + + expect(res.status).toBe(500); + expect(res.body).toStrictEqual({ + error: 'Failed to retrieve user id' + }); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'test' }) + ); + }); + }); + + describe('POST /apps/classroom/get-user-data', () => { + test('returns 400 when more than 50 userIds are provided', async () => { + const tooMany = Array.from( + { length: 51 }, + (_, i) => `${String(i).padStart(24, '0')}` + ); + + const res = await post('/apps/classroom/get-user-data').send({ + userIds: tooMany + }); + + expect(res.status).toBe(400); + }); + + test('returns 200 with empty data for empty userIds array', async () => { + const res = await post('/apps/classroom/get-user-data').send({ + userIds: [] + }); + + expect(res.status).toBe(200); + expect(res.body).toStrictEqual({ data: {} }); + }); + + test('returns data only for classroom accounts', async () => { + const now = Date.now(); + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + isClassroomAccount: true, + completedChallenges: [ + { + id: 'challenge-default', + completedDate: now, + files: [] + } + ] + } + }); + + await fastifyTestInstance.prisma.user.create({ + data: { + ...createUserInput(classroomUserEmail), + id: classroomUserId, + isClassroomAccount: true, + completedChallenges: [ + { + id: 'challenge-student', + completedDate: now + 1, + files: [] + } + ] + } + }); + + await fastifyTestInstance.prisma.user.create({ + data: { + ...createUserInput(nonClassroomUserEmail), + id: nonClassroomUserId, + isClassroomAccount: false, + completedChallenges: [] + } + }); + + const res = await post('/apps/classroom/get-user-data').send({ + userIds: [defaultUserId, classroomUserId, nonClassroomUserId] + }); + + expect(res.status).toBe(200); + const responseBody = res.body as { + data: Record< + string, + Array<{ id: string; completedDate: number }> | undefined + >; + }; + expect(Object.keys(responseBody.data)).toEqual( + expect.arrayContaining([defaultUserId, classroomUserId]) + ); + expect(responseBody.data).not.toHaveProperty(nonClassroomUserId); + + expect(responseBody.data[defaultUserId]?.[0]).toStrictEqual({ + id: 'challenge-default', + completedDate: now + }); + expect(responseBody.data[classroomUserId]?.[0]).toStrictEqual({ + id: 'challenge-student', + completedDate: now + 1 + }); + }); + + test('response contains only id and completedDate', async () => { + const now = Date.now(); + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + isClassroomAccount: true, + completedChallenges: [ + { + id: 'challenge-shape-test', + completedDate: now, + solution: 'http://example.com/solution', + files: [ + { + contents: 'some code', + ext: 'js', + key: 'indexjs', + name: 'index' + } + ] + } + ] + } + }); + + const res = await post('/apps/classroom/get-user-data').send({ + userIds: [defaultUserId] + }); + + expect(res.status).toBe(200); + const responseBody = res.body as { + data: Record>>; + }; + const challenge = responseBody.data[defaultUserId]![0]!; + expect(Object.keys(challenge)).toStrictEqual(['id', 'completedDate']); + }); + + test('returns 500 and captures when the database query fails', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + + const original = fastifyTestInstance.prisma.user.findMany; + fastifyTestInstance.prisma.user.findMany = vi + .fn() + .mockRejectedValue(new Error('test')) as typeof original; + + const res = await post('/apps/classroom/get-user-data').send({ + userIds: [defaultUserId] + }); + + fastifyTestInstance.prisma.user.findMany = original; + fastifyTestInstance.Sentry = originalSentry; + + expect(res.status).toBe(500); + expect(res.body).toStrictEqual({ + error: 'Failed to retrieve user data' + }); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'test' }) + ); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.ts new file mode 100644 index 0000000000000000000000000000000000000000..23c25a4ae215d0588e1bb61573e3d7a393d57aa9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/apps/classroom.ts @@ -0,0 +1,97 @@ +import { FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { normalizeDate } from '../../utils/normalize.js'; +import * as schemas from '../../schemas.js'; + +/** + * Routes for the classroom app integration. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const classroomRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.post( + '/get-user-id', + { + schema: schemas.classroomGetUserIdSchema + }, + async (request, reply) => { + const { email } = request.body; + + try { + const user = await fastify.prisma.user.findFirst({ + where: { email, isClassroomAccount: true }, + select: { id: true } + }); + + if (!user) { + fastify.Sentry?.metrics?.count('classroom.user_looked_up', 1, { + attributes: { result: 'not_found' } + }); + return reply.send({ userId: '' }); + } + + fastify.Sentry?.metrics?.count('classroom.user_looked_up', 1, { + attributes: { result: 'found' } + }); + + return reply.send({ + userId: user.id + }); + } catch (error) { + fastify.Sentry?.captureException(error); + request.log.error(error, 'Failed to retrieve user id'); + return reply.code(500).send({ error: 'Failed to retrieve user id' }); + } + } + ); + + fastify.post( + '/get-user-data', + { + schema: schemas.classroomGetUserDataSchema + }, + async (request, reply) => { + const { userIds } = request.body; + + try { + const users = await fastify.prisma.user.findMany({ + where: { + id: { in: userIds }, + isClassroomAccount: true + }, + select: { + id: true, + completedChallenges: true + } + }); + + const userData: Record< + string, + { id: string; completedDate: number }[] + > = {}; + + users.forEach(user => { + userData[user.id] = user.completedChallenges.map(challenge => ({ + id: challenge.id, + completedDate: normalizeDate(challenge.completedDate) + })); + }); + + return reply.send({ + data: userData + }); + } catch (error) { + fastify.Sentry?.captureException(error); + request.log.error(error, 'Failed to retrieve user data'); + return reply.code(500).send({ error: 'Failed to retrieve user data' }); + } + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..7138cd946ca93baad6766da82e974794a0737767 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.test.ts @@ -0,0 +1,221 @@ +import { + describe, + test, + expect, + beforeAll, + afterEach, + afterAll, + vi +} from 'vitest'; +import Fastify, { FastifyInstance } from 'fastify'; + +import db from '../../db/prisma.js'; +import { createUserInput } from '../../utils/create-user.js'; +import { checkCanConnectToDb } from '../../../vitest.utils.js'; +import { findOrCreateUser } from './auth-helpers.js'; +import { assignVariantBucket } from '../../utils/drip-campaign.js'; +import growthBook from '../../plugins/growth-book.js'; +import { + GROWTHBOOK_FASTIFY_API_HOST, + GROWTHBOOK_FASTIFY_CLIENT_KEY +} from '../../utils/env.js'; + +async function setupServer() { + const fastify = Fastify(); + await fastify.register(db); + await checkCanConnectToDb(fastify.prisma); + await fastify.register(growthBook, { + apiHost: GROWTHBOOK_FASTIFY_API_HOST, + clientKey: GROWTHBOOK_FASTIFY_CLIENT_KEY + }); + return fastify; +} + +describe('findOrCreateUser', () => { + let fastify: FastifyInstance; + const email = 'test@user.com'; + beforeAll(async () => { + fastify = await setupServer(); + }); + + afterAll(async () => { + await fastify.prisma.$runCommandRaw({ dropDatabase: 1 }); + await fastify.close(); + }); + + afterEach(async () => { + await fastify.prisma.user.deleteMany({ where: { email } }); + await fastify.prisma.dripCampaign.deleteMany({ where: { email } }); + vi.restoreAllMocks(); + }); + + test('should log an error and capture an exception if there are multiple users with the same email', async () => { + const user1 = await fastify.prisma.user.create({ + data: createUserInput(email) + }); + const user2 = await fastify.prisma.user.create({ + data: createUserInput(email) + }); + + const userIds = [user1.id, user2.id]; + + const logError = vi.spyOn(fastify.log, 'error'); + const captureException = vi.fn(); + const count = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException, metrics: { count } }; + + await findOrCreateUser(fastify, email); + + expect(logError).toHaveBeenCalledWith( + { audit: true, userIds, email }, + 'Multiple user records found' + ); + expect(captureException).toHaveBeenCalledWith( + new Error('Multiple user records found for the same email'), + { + extra: { userIds }, + fingerprint: ['dup-account-multiple-user-records'] + } + ); + expect(count).toHaveBeenCalledWith('user.duplicate_email_detected', 1); + }); + + test('should NOT log an error or capture an exception if there is only one user with the email', async () => { + await fastify.prisma.user.create({ data: createUserInput(email) }); + + const logError = vi.spyOn(fastify.log, 'error'); + const captureException = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException }; + + await findOrCreateUser(fastify, email); + + expect(logError).not.toHaveBeenCalled(); + expect(captureException).not.toHaveBeenCalled(); + }); + + test('should NOT log an error or capture an exception if there are no users with the email', async () => { + const logError = vi.spyOn(fastify.log, 'error'); + const captureException = vi.fn(); + const count = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException, metrics: { count } }; + + await findOrCreateUser(fastify, email); + + expect(logError).not.toHaveBeenCalled(); + expect(captureException).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith('user.created', 1); + }); + + describe('drip campaign logic', () => { + test('should create a drip campaign record when a new user is created and feature flag is enabled', async () => { + vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true); + + const count = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { ...fastify.Sentry, metrics: { count } }; + + const user = await findOrCreateUser(fastify, email); + + const dripCampaign = await fastify.prisma.dripCampaign.findFirst({ + where: { userId: user.id } + }); + + expect(dripCampaign).toBeDefined(); + expect(dripCampaign?.userId).toBe(user.id); + expect(dripCampaign?.email).toBe(email); + expect(['A', 'B']).toContain(dripCampaign?.variant); + expect(count).toHaveBeenCalledWith( + 'growthbook.signup_flag_evaluated', + 1, + { + attributes: { flag: 'drip-campaign', result: 'success' } + } + ); + }); + + test('should assign a consistent variant based on userId', async () => { + vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true); + + const user = await findOrCreateUser(fastify, email); + const expectedVariant = assignVariantBucket(user.id); + + const dripCampaign = await fastify.prisma.dripCampaign.findFirst({ + where: { userId: user.id } + }); + + expect(dripCampaign?.variant).toBe(expectedVariant); + }); + + test('should not create a drip campaign record when feature flag is disabled', async () => { + vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => false); + + const user = await findOrCreateUser(fastify, email); + + const dripCampaign = await fastify.prisma.dripCampaign.findFirst({ + where: { userId: user.id } + }); + + expect(dripCampaign).toBeNull(); + }); + + test('should not prevent user creation if drip campaign record creation fails', async () => { + vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true); + + const captureException = vi.fn(); + const count = vi.fn(); + // @ts-expect-error - Only mocks part of the Sentry object. + fastify.Sentry = { captureException, metrics: { count } }; + + const originalCreate = fastify.prisma.dripCampaign.create; + + fastify.prisma.dripCampaign.create = vi + .fn() + .mockRejectedValueOnce(new Error('Database error')); + + const logError = vi.spyOn(fastify.log, 'error'); + + const user = await findOrCreateUser(fastify, email); + + expect(user).toBeDefined(); + expect(user.id).toBeTruthy(); + + const dbError: unknown = expect.objectContaining({ + message: 'Database error' + }); + expect(logError).toHaveBeenCalledWith( + { err: dbError, userId: user.id }, + 'Failed to create drip campaign record for user' + ); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith( + 'growthbook.signup_flag_evaluated', + 1, + { + attributes: { flag: 'drip-campaign', result: 'failed' } + } + ); + + fastify.prisma.dripCampaign.create = originalCreate; + }); + + test('should not create drip campaign for existing users', async () => { + vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true); + + // Create user first + await fastify.prisma.user.create({ data: createUserInput(email) }); + + // Call findOrCreateUser for existing user + await findOrCreateUser(fastify, email); + + // Verify no drip campaign record was created + const dripCampaigns = await fastify.prisma.dripCampaign.findMany({ + where: { email } + }); + + expect(dripCampaigns).toHaveLength(0); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffd85358865098a386e60e810e0633ee315fbe6a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/auth-helpers.ts @@ -0,0 +1,80 @@ +import { FastifyInstance } from 'fastify'; +import { createUserInput } from '../../utils/create-user.js'; +import { assignVariantBucket } from '../../utils/drip-campaign.js'; + +/** + * Finds an existing user with the given email or creates a new user if none exists. + * @param fastify - The Fastify instance. + * @param email - The email of the user. + * @returns The existing or newly created user. + */ +export const findOrCreateUser = async ( + fastify: FastifyInstance, + email: string +): Promise<{ id: string; acceptedPrivacyTerms: boolean }> => { + // TODO: handle the case where there are multiple users with the same email. + // e.g. use findMany and throw an error if more than one is found. + const existingUser = await fastify.prisma.user.findMany({ + where: { email }, + select: { id: true, acceptedPrivacyTerms: true } + }); + if (existingUser.length > 1) { + const userIds = existingUser.map(user => user.id); + fastify.log.error( + { audit: true, userIds, email }, + 'Multiple user records found' + ); + fastify.Sentry?.captureException( + new Error('Multiple user records found for the same email'), + { + extra: { userIds }, + fingerprint: ['dup-account-multiple-user-records'] + } + ); + fastify.Sentry?.metrics?.count('user.duplicate_email_detected', 1); + } + + if (existingUser[0]) { + return existingUser[0]; + } + + // Create new user + const newUser = await fastify.prisma.user.create({ + data: createUserInput(email), + select: { id: true, acceptedPrivacyTerms: true } + }); + + fastify.Sentry?.metrics?.count('user.created', 1); + + // Create drip campaign record if feature flag is enabled + if (fastify.gb.isOn('drip-campaign')) { + try { + const variant = assignVariantBucket(newUser.id); + await fastify.prisma.dripCampaign.create({ + data: { + userId: newUser.id, + email, + variant + } + }); + fastify.log.info( + { userId: newUser.id, variant }, + 'Drip campaign record created for user' + ); + fastify.Sentry?.metrics?.count('growthbook.signup_flag_evaluated', 1, { + attributes: { flag: 'drip-campaign', result: 'success' } + }); + } catch (err) { + fastify.Sentry?.captureException(err); + fastify.log.error( + { err, userId: newUser.id }, + 'Failed to create drip campaign record for user' + ); + fastify.Sentry?.metrics?.count('growthbook.signup_flag_evaluated', 1, { + attributes: { flag: 'drip-campaign', result: 'failed' } + }); + } + } + + return newUser; +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..84863c4c97280e13d73bc6f424737b2cb802e61a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.test.ts @@ -0,0 +1,50 @@ +import { describe, test, expect } from 'vitest'; + +import { getFallbackFullStackDate } from './certificate-utils.js'; + +const fullStackChallenges = [ + { + completedDate: 1585210952511, + id: '5a553ca864b52e1d8bceea14' + }, + { + completedDate: 1585210952511, + id: '561add10cb82ac38a17513bc' + }, + { + completedDate: 1588665778679, + id: '561acd10cb82ac38a17513bc' + }, + { + completedDate: 1685210952511, + id: '561abd10cb81ac38a17513bc' + }, + { + completedDate: 1585210952511, + id: '561add10cb82ac38a17523bc' + }, + { + completedDate: 1588665778679, + id: '561add10cb82ac38a17213bc' + } +]; + +describe('helper functions', () => { + describe('getFallbackFullStackDate', () => { + test('should return the date of the latest completed challenge', () => { + expect(getFallbackFullStackDate(fullStackChallenges, 123)).toBe( + 1685210952511 + ); + }); + + test('should fall back to completedDate if no certifications are provided', () => { + expect(getFallbackFullStackDate([], 123)).toBe(123); + }); + + test('should fall back to completedDate if none of the certifications have been completed', () => { + expect( + getFallbackFullStackDate([{ completedDate: 567, id: 'abc' }], 123) + ).toBe(123); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..f38d7c4444329c79a3fb5b6e69463fb1775c11db --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/certificate-utils.ts @@ -0,0 +1,48 @@ +import { Prisma } from '@prisma/client'; +import { + certSlugTypeMap, + certToIdMap, + Certification +} from '@freecodecamp/shared/config/certification-settings'; +import { normalizeDate } from '../../utils/normalize.js'; + +const fullStackCertificateIds = [ + certToIdMap[Certification.RespWebDesign], + certToIdMap[Certification.JsAlgoDataStruct], + certToIdMap[Certification.FrontEndDevLibs], + certToIdMap[Certification.DataVis], + certToIdMap[Certification.BackEndDevApis], + certToIdMap[Certification.LegacyInfoSecQa] +]; + +/** + * Checks if the given certification slug is known. + * + * @param certSlug - The certification slug to check. + * @returns True if the certification slug is known, otherwise false. + */ +export function isKnownCertSlug(certSlug: string): certSlug is Certification { + return certSlug in certSlugTypeMap; +} + +/** + * Retrieves the completion date for the full stack certification, if it exists. + * + * @param completedChallenges - The array of completed challenges. + * @param completedDate - The fallback completed date. + * @returns The latest certification date or the completed date if no certification is found. + */ +export function getFallbackFullStackDate( + completedChallenges: { id: string; completedDate: Prisma.JsonValue }[], + completedDate: Prisma.JsonValue +): number { + const latestCertDate = completedChallenges + .filter(chal => fullStackCertificateIds.includes(chal.id)) + .map(chal => ({ + ...chal, + completedDate: normalizeDate(chal.completedDate) + })) + .sort((a, b) => b.completedDate - a.completedDate)[0]?.completedDate; + + return latestCertDate ?? normalizeDate(completedDate); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..0b3c6c0f7f265b4c45608430c318a65ecd09a771 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.test.ts @@ -0,0 +1,251 @@ +import { describe, test, expect, afterEach, vi } from 'vitest'; +import type { + PartiallyCompletedChallenge, + CompletedChallenge +} from '@prisma/client'; + +import { createFetchMock } from '../../../vitest.utils.js'; +import { + canSubmitCodeRoadCertProject, + verifyTrophyWithMicrosoft, + decodeFiles, + decodeBase64, + encodeBase64 +} from './challenge-helpers.js'; + +const id = 'abc'; + +const partiallyCompletedChallenges: PartiallyCompletedChallenge[] = [ + { + id, + completedDate: 1 + } +]; +const completedChallenges: CompletedChallenge[] = [ + { + id, + completedDate: 1, + challengeType: 1, + files: [], + githubLink: null, + solution: null, + isManuallyApproved: false, + examResults: null + } +]; + +describe('Challenge Helpers', () => { + describe('canSubmitCodeRoadCertProject', () => { + test('returns true if the user has completed the required challenges or partially completed them', () => { + expect( + canSubmitCodeRoadCertProject(id, { + partiallyCompletedChallenges, + completedChallenges + }) + ).toBe(true); + + expect( + canSubmitCodeRoadCertProject(id, { + partiallyCompletedChallenges: [], + completedChallenges + }) + ).toBe(true); + + expect( + canSubmitCodeRoadCertProject(id, { + partiallyCompletedChallenges, + completedChallenges: [] + }) + ).toBe(true); + }); + + test('returns false if the user has not completed the required challenges', () => { + expect( + canSubmitCodeRoadCertProject(id, { + partiallyCompletedChallenges: [], + completedChallenges: [] + }) + ).toBe(false); + }); + + test('returns false if the id is undefined', () => { + expect( + canSubmitCodeRoadCertProject(undefined, { + partiallyCompletedChallenges, + completedChallenges + }) + ).toBe(false); + }); + }); + + describe('verifyTrophyWithMicrosoft', () => { + const userId = 'abc123'; + const msUsername = 'ANRandom'; + const msTrophyId = 'learn.wwl.get-started-c-sharp-part-3.trophy'; + const verifyData = { msUsername, msTrophyId }; + const achievementsUrl = `https://learn.microsoft.com/api/achievements/user/${userId}`; + + afterEach(() => vi.clearAllMocks()); + + test("handles failure to reach Microsoft's profile api", async () => { + const notOk = createFetchMock({ ok: false }); + vi.spyOn(globalThis, 'fetch').mockImplementation(notOk); + + const verification = await verifyTrophyWithMicrosoft(verifyData); + + expect(verification).toEqual({ + type: 'error', + message: 'flash.ms.profile.err', + variables: { + msUsername + } + }); + }); + + test("handles failure to reach Microsoft's achievements api", async () => { + const fetchProfile = createFetchMock({ body: { userId } }); + const fetchAchievements = createFetchMock({ ok: false }); + vi.spyOn(globalThis, 'fetch') + .mockImplementationOnce(fetchProfile) + .mockImplementationOnce(fetchAchievements); + + const verification = await verifyTrophyWithMicrosoft(verifyData); + + expect(verification).toEqual({ + type: 'error', + message: 'flash.ms.trophy.err-3' + }); + }); + + test('handles the case where the user has no achievements', async () => { + const fetchProfile = createFetchMock({ body: { userId } }); + const fetchAchievements = createFetchMock({ body: { achievements: [] } }); + vi.spyOn(globalThis, 'fetch') + .mockImplementationOnce(fetchProfile) + .mockImplementationOnce(fetchAchievements); + + const verification = await verifyTrophyWithMicrosoft(verifyData); + + expect(verification).toEqual({ + type: 'error', + message: 'flash.ms.trophy.err-6' + }); + }); + + test("handles failure to find the trophy in the user's achievements", async () => { + const fetchProfile = createFetchMock({ body: { userId } }); + const fetchAchievements = createFetchMock({ + body: { achievements: [{ typeId: 'fake-id' }] } + }); + vi.spyOn(globalThis, 'fetch') + .mockImplementationOnce(fetchProfile) + .mockImplementationOnce(fetchAchievements); + + const verification = await verifyTrophyWithMicrosoft(verifyData); + + expect(verification).toEqual({ + type: 'error', + message: 'flash.ms.trophy.err-4', + variables: { + msUsername + } + }); + }); + + test('returns msUserAchievementsApiUrl on success', async () => { + const fetchProfile = createFetchMock({ body: { userId } }); + const fetchAchievements = createFetchMock({ + body: { achievements: [{ typeId: msTrophyId }] } + }); + vi.spyOn(globalThis, 'fetch') + .mockImplementationOnce(fetchProfile) + .mockImplementationOnce(fetchAchievements); + + const verification = await verifyTrophyWithMicrosoft(verifyData); + + expect(verification).toEqual({ + type: 'success', + msUserAchievementsApiUrl: achievementsUrl + }); + }); + }); + + describe('decodeFiles', () => { + test('decodes base64 encoded file contents', () => { + const encodedFiles = [ + { + contents: btoa('console.log("Hello, world!");') + }, + { + contents: btoa('

Hello, world!

') + } + ]; + + const decodedFiles = decodeFiles(encodedFiles); + + expect(decodedFiles).toEqual([ + { + contents: 'console.log("Hello, world!");' + }, + { + contents: '

Hello, world!

' + } + ]); + }); + + test('leaves all other file properties unchanged', () => { + const encodedFiles = [ + { + contents: btoa('console.log("Hello, world!");'), + ext: '.js', + history: [], + key: 'file1', + name: 'hello.js' + } + ]; + + const decodedFiles = decodeFiles(encodedFiles); + + expect(decodedFiles).toEqual([ + { + contents: 'console.log("Hello, world!");', + ext: '.js', + history: [], + key: 'file1', + name: 'hello.js' + } + ]); + }); + + test('can handle unicode characters', () => { + const encodedFiles = [ + { + contents: encodeBase64('console.log("Hello, ✅🚀!");') + } + ]; + + const decodedFiles = decodeFiles(encodedFiles); + + expect(decodedFiles).toEqual([ + { + contents: 'console.log("Hello, ✅🚀!");' + } + ]); + }); + }); + + describe('decodeBase64', () => { + test('decodes a base64 encoded string', () => { + const encoded = encodeBase64('Hello, world!'); + const decoded = decodeBase64(encoded); + expect(decoded).toBe('Hello, world!'); + }); + + test('can handle unicode characters', () => { + const original = 'Hello, ✅🚀!'; + const encoded = encodeBase64(original); + const decoded = decodeBase64(encoded); + expect(decoded).toBe(original); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.ts new file mode 100644 index 0000000000000000000000000000000000000000..b71e81ddd8f1e93fc6ae38a5fb8adf7e42c1f662 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/challenge-helpers.ts @@ -0,0 +1,175 @@ +/** + * Confirm that a user can submit a CodeRoad project. + * + * @param id The id of the project. + * @param param The challenges the user has completed. + * @param param.partiallyCompletedChallenges The partially completed challenges. + * @param param.completedChallenges The completed challenges. + * @returns A boolean indicating if the user can submit the project. + */ +export const canSubmitCodeRoadCertProject = ( + id: string | undefined, + { + partiallyCompletedChallenges, + completedChallenges + }: { + partiallyCompletedChallenges: { id: string }[]; + completedChallenges: { id: string }[]; + } +) => { + if (partiallyCompletedChallenges.some(c => c.id === id)) return true; + if (completedChallenges.some(c => c.id === id)) return true; + return false; +}; + +type MSProfileError = { + type: 'error'; + message: 'flash.ms.profile.err'; + variables: { msUsername: string }; +}; + +type MSProfileSuccess = { + type: 'success'; + userId: string; +}; + +async function getMSProfile(msUsername: string) { + const error: MSProfileError = { + type: 'error', + message: 'flash.ms.profile.err', + variables: { + msUsername + } + }; + + const msProfileApi = `https://learn.microsoft.com/api/profiles/${msUsername}`; + const msProfileApiRes = await fetch(msProfileApi); + + if (!msProfileApiRes.ok) return error; + + const { userId } = (await msProfileApiRes.json()) as { + userId: string; + }; + + const success: MSProfileSuccess = { + type: 'success', + userId + }; + + return userId ? success : error; +} + +type AchievementsError = { + type: 'error'; + message: 'flash.ms.trophy.err-3'; +}; + +type NoAchievementsError = { + type: 'error'; + message: 'flash.ms.trophy.err-6'; +}; + +type NoTrophyError = { + type: 'error'; + message: 'flash.ms.trophy.err-4'; + variables: { msUsername: string }; +}; + +type Validated = { + type: 'success'; + msUserAchievementsApiUrl: string; +}; + +/** + * Handles all communication with the Microsoft Learn APIs. + * + * @param requestData The data needed by the Microsoft Learn APIs. + * @param requestData.msUsername The Microsoft username used to get the profile. + * @param requestData.msTrophyId The Microsoft trophy ID to verify. + * @returns An object with 'type' of success|error and information about the success or failure. + */ +export async function verifyTrophyWithMicrosoft({ + msUsername, + msTrophyId +}: { + msUsername: string; + msTrophyId: string; +}) { + const msProfile = await getMSProfile(msUsername); + + if (msProfile.type === 'error') return msProfile; + + const msUserAchievementsApiUrl = `https://learn.microsoft.com/api/achievements/user/${msProfile.userId}`; + const msUserAchievementsApiRes = await fetch(msUserAchievementsApiUrl); + + if (!msUserAchievementsApiRes.ok) { + return { + type: 'error', + message: 'flash.ms.trophy.err-3' + } as AchievementsError; + } + + const { achievements } = (await msUserAchievementsApiRes.json()) as { + achievements?: { typeId: string }[]; + }; + + if (!achievements?.length) + return { + type: 'error', + message: 'flash.ms.trophy.err-6' + } as NoAchievementsError; + + // TODO: handle the case where there are achievements, but the `typeId` is not + // a property of the achievements. This suggests that Microsoft has changed + // their API and, to aid debugging, we should report a different error + // message. + const earnedTrophy = achievements?.some(a => a.typeId === msTrophyId); + + if (earnedTrophy) { + return { + type: 'success', + msUserAchievementsApiUrl + } as Validated; + } else { + return { + type: 'error', + message: 'flash.ms.trophy.err-4', + variables: { + msUsername + } + } as NoTrophyError; + } +} + +/** + * Generic helper to decode an array of base64 encoded file objects. + * + * @param files Array of file-like objects each having a base64 encoded `contents` string. + * @returns The same array shape with `contents` decoded. + */ +export function decodeFiles(files: T[]): T[] { + return files.map(file => ({ + ...file, + contents: decodeBase64(file.contents) + })); +} + +/** + * Decodes a base64 encoded string into a UTF-8 string. + * + * @param str The base64 encoded string to decode. + * @returns The decoded UTF-8 string. + */ +export function decodeBase64(str: string): string { + return Buffer.from(str, 'base64').toString('utf-8'); +} + +/** + * Encodes a UTF-8 string into a base64 encoded string. + * + * @param str The UTF-8 string to encode. + * @returns The base64 encoded string. + */ +export function encodeBase64(str: string): string { + return Buffer.from(str, 'utf8').toString('base64'); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/is-restricted.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/is-restricted.ts new file mode 100644 index 0000000000000000000000000000000000000000..e74c1f0f2b5b9783800e4528d4fd0453334f1a6b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/is-restricted.ts @@ -0,0 +1,12 @@ +import { isProfane } from 'no-profanity'; + +import { blocklistedUsernames } from '@freecodecamp/shared/config/constants'; + +/** + * Checks if a username is restricted (i.e. It's profane or reserved). + * @param username - The username to check. + * @returns True if the username is restricted, false otherwise. + */ +export const isRestricted = (username: string): boolean => { + return isProfane(username) || blocklistedUsernames.includes(username); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/user-utils.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/user-utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c39aca8df1893d3c668db71282354f38d1bdfee --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/helpers/user-utils.ts @@ -0,0 +1,61 @@ +import { pick, omit } from 'lodash-es'; + +// user flags that the api-server returns as false if they're missing in the +// user document. Since Prisma returns null for missing fields, we need to +// normalize them to false. +// TODO(Post-MVP): remove this when the database is normalized. +const nullableFlags = [ + 'is2018DataVisCert', + 'is2018FullStackCert', + 'isA2EnglishCert', + 'isApisMicroservicesCert', + 'isBackEndCert', + 'isCheater', + 'isCollegeAlgebraPyCertV8', + 'isDataAnalysisPyCertV7', + 'isDataVisCert', + // isDonating doesn't need fixing because it's not nullable + 'isFoundationalCSharpCertV8', + 'isFrontEndCert', + 'isFullStackCert', + 'isFrontEndLibsCert', + 'isJavascriptCertV9', + 'isClassroomAccount', + 'isHonest', + 'isInfosecCertV7', + 'isInfosecQaCert', + 'isJsAlgoDataStructCert', + 'isJsAlgoDataStructCertV8', + 'isMachineLearningPyCertV7', + 'isPythonCertV9', + 'isQaCertV7', + 'isRelationalDatabaseCertV8', + 'isRelationalDatabaseCertV9', + 'isRespWebDesignCert', + 'isRespWebDesignCertV9', + 'isSciCompPyCertV7', + 'isFrontEndLibsCertV9', + 'isBackEndDevApisCertV9', + 'isFullStackDeveloperCertV9', + 'isB1EnglishCert', + 'isA2SpanishCert', + 'isA2ChineseCert', + 'isA1ChineseCert', + // isUpcomingPythonCertV8 exists in the db, but is not returned by the api-server + // TODO(Post-MVP): delete it from the db? + 'keyboardShortcuts' +] as const; + +type NullableFlags = (typeof nullableFlags)[number]; + +/** + * Splits a user object into two objects: one with nullable flags and one without. + * + * @param user - The user object to split. + * @returns A tuple where the first element is an object with nullable flags and the second element is an object with the remaining properties. + */ +export function splitUser>( + user: U +): [Pick, Omit] { + return [pick(user, nullableFlags), omit(user, nullableFlags)]; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f2d5ef720738adb244f658d6c96309772b17e8a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.test.ts @@ -0,0 +1,598 @@ +import { + describe, + test, + expect, + beforeAll, + afterEach, + beforeEach, + vi +} from 'vitest'; + +import { Certification } from '@freecodecamp/shared/config/certification-settings'; +import { + defaultUserEmail, + defaultUserId, + devLogin, + resetDefaultUser, + setupServer, + superRequest +} from '../../../vitest.utils.js'; +import { getChallenges } from '../../utils/get-challenges.js'; +import { createCertLookup } from './certificate.js'; + +describe('certificate routes', () => { + setupServer(); + describe('Authenticated user', () => { + let setCookies: string[]; + + // Authenticate user + beforeAll(async () => { + setCookies = await devLogin(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('PUT /certificate/verify', () => { + beforeEach(async () => { + await resetDefaultUser(); + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + name: 'fcc', + username: 'fcc', + completedChallenges: [] + } + }); + }); + + test('should return 400 if no certSlug', async () => { + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({}); + + expect(response.body).toMatchObject({ + response: { + message: 'flash.wrong-name', + variables: { name: '' } + } + }); + expect(response.status).toBe(400); + }); + + test('should return 400 if certSlug is invalid', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: 'non-existant' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toMatchObject({ + response: { + message: 'flash.wrong-name', + variables: { name: 'non-existant' } + } + }); + expect(response.status).toBe(400); + expect(count).toHaveBeenCalledWith('certificate.claim_blocked', 1, { + attributes: { reason: 'unknown_slug' } + }); + }); + + // TODO: Revisit this test after deciding if we need/want to fetch the + // entire user during authorization or just the user id. + test('should return 500 and capture an exception if user not found in db', async () => { + const findUniqueForAuth = + fastifyTestInstance.prisma.user.findUnique.bind( + fastifyTestInstance.prisma.user + ); + + vi.spyOn(fastifyTestInstance.prisma.user, 'findUnique') + .mockImplementationOnce(findUniqueForAuth) + .mockResolvedValueOnce(null); + + const captureException = vi.fn(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toStrictEqual({ + message: 'flash.went-wrong', + type: 'danger' + }); + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('certificate.claim_user_missing', 1); + }); + + test('should return 400 if user has not set a `name`', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + name: null + } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toMatchObject({ + response: { + type: 'info', + message: 'flash.name-needed' + }, + isCertMap: { + is2018DataVisCert: false, + isA2EnglishCert: false, + isB1EnglishCert: false, + isApisMicroservicesCert: false, + isBackEndCert: false, + isBackEndDevApisCertV9: false, + isCollegeAlgebraPyCertV8: false, + isDataAnalysisPyCertV7: false, + isDataVisCert: false, + isFoundationalCSharpCertV8: false, + isFrontEndCert: false, + isFrontEndLibsCert: false, + isFrontEndLibsCertV9: false, + isFullStackCert: false, + isInfosecCertV7: false, + isInfosecQaCert: false, + isJsAlgoDataStructCert: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isQaCertV7: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isRespWebDesignCert: false, + isSciCompPyCertV7: false, + isJavascriptCertV9: false, + isRespWebDesignCertV9: false + }, + completedChallenges: [] + }); + expect(response.status).toBe(400); + expect(count).toHaveBeenCalledWith('certificate.claim_blocked', 1, { + attributes: { + certSlug: Certification.RespWebDesign, + reason: 'name_missing' + } + }); + }); + + test('should return 200 if user already claimed cert', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + isRespWebDesignCert: true + } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + expect(response.body.response).toStrictEqual({ + type: 'info', + message: 'flash.already-claimed', + variables: { + name: 'Legacy Responsive Web Design V8' + } + }); + + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith('certificate.claim_blocked', 1, { + attributes: { + certSlug: Certification.RespWebDesign, + reason: 'already_claimed' + } + }); + }); + + test('should return 400 if not all requirements have been met to claim', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + completedChallenges: [ + { id: '587d78af367417b2b2512b03', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b04', completedDate: 123456789 }, + { id: '587d78b0367417b2b2512b05', completedDate: 123456789 }, + { id: 'bd7158d8c242eddfaeb5bd13', completedDate: 123456789 } + ], + isRespWebDesignCert: false + } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + expect(response.body.response).toStrictEqual({ + message: 'flash.incomplete-steps', + type: 'info', + variables: { name: 'Legacy Responsive Web Design V8' } + }); + expect(response.status).toBe(400); + expect(count).toHaveBeenCalledWith('certificate.claim_blocked', 1, { + attributes: { + certSlug: Certification.RespWebDesign, + reason: 'incomplete_steps' + } + }); + }); + + // Note: Email does not actually send (work) in development, but status should still be 200. + test('should send the certified email when full stack developer v9 is claimed', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + completedChallenges: [ + { id: 'bd7158d8c442eddfaeb5bd18', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b03', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b04', completedDate: 123456789 }, + { id: '587d78b0367417b2b2512b05', completedDate: 123456789 }, + { id: 'bd7158d8c242eddfaeb5bd13', completedDate: 123456789 } + ], + isFullStackDeveloperCertV9: true + } + }); + + const spy = vi.spyOn(fastifyTestInstance, 'sendEmail'); + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + expect(spy).toHaveBeenCalled(); + expect(response.status).toBe(200); + }); + + test('should capture an exception if the congratulations email fails to send', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + completedChallenges: [ + { id: 'bd7158d8c442eddfaeb5bd18', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b03', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b04', completedDate: 123456789 }, + { id: '587d78b0367417b2b2512b05', completedDate: 123456789 }, + { id: 'bd7158d8c242eddfaeb5bd13', completedDate: 123456789 } + ], + isFullStackDeveloperCertV9: true + } + }); + + vi.spyOn(fastifyTestInstance, 'sendEmail').mockRejectedValueOnce( + new Error('send failed') + ); + const captureException = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(captureException).toHaveBeenCalledOnce(); + expect(response.status).toBe(200); + }); + + test('should return 200 if all went well', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + completedChallenges: [ + { id: 'bd7158d8c442eddfaeb5bd18', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b03', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b04', completedDate: 123456789 }, + { id: '587d78b0367417b2b2512b05', completedDate: 123456789 }, + { id: 'bd7158d8c242eddfaeb5bd13', completedDate: 123456789 } + ], + isRespWebDesignCert: false + } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + fastifyTestInstance.Sentry = originalSentry; + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: defaultUserEmail } + }); + + expect(user).toMatchObject({ isRespWebDesignCert: true }); + expect(response.body).toStrictEqual({ + response: { + message: 'flash.cert-claim-success', + type: 'success', + variables: { + name: 'Legacy Responsive Web Design V8', + username: 'fcc' + } + }, + isCertMap: { + is2018DataVisCert: false, + isA1ChineseCert: false, + isA2ChineseCert: false, + isA2EnglishCert: false, + isA2SpanishCert: false, + isApisMicroservicesCert: false, + isB1EnglishCert: false, + isBackEndCert: false, + isBackEndDevApisCertV9: false, + isCollegeAlgebraPyCertV8: false, + isDataAnalysisPyCertV7: false, + isDataVisCert: false, + isFoundationalCSharpCertV8: false, + isFrontEndCert: false, + isFrontEndLibsCert: false, + isFrontEndLibsCertV9: false, + isFullStackCert: false, + isFullStackDeveloperCertV9: false, + isInfosecCertV7: false, + isInfosecQaCert: false, + isJavascriptCertV9: false, + isJsAlgoDataStructCert: false, + isJsAlgoDataStructCertV8: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isQaCertV7: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isRespWebDesignCert: true, + isRespWebDesignCertV9: false, + isSciCompPyCertV7: false + }, + completedChallenges: [ + { + completedDate: 123456789, + files: [], + id: 'bd7158d8c442eddfaeb5bd18' + }, + { + completedDate: 123456789, + files: [], + id: '587d78af367417b2b2512b03' + }, + { + completedDate: 123456789, + files: [], + id: '587d78af367417b2b2512b04' + }, + { + completedDate: 123456789, + files: [], + id: '587d78b0367417b2b2512b05' + }, + { + completedDate: 123456789, + files: [], + id: 'bd7158d8c242eddfaeb5bd13' + }, + { + challengeType: 7, + // TODO: use matcher for date near now + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + completedDate: expect.any(Number), + files: [], + id: '561add10cb82ac38a17513bc' + } + ] + }); + expect(count).toHaveBeenCalledWith('certificate.claimed', 1, { + attributes: { certSlug: Certification.RespWebDesign } + }); + expect(response.status).toBe(200); + }); + + // Tests for all certifications as to what may currently be claimed, and what may no longer be claimed + test('should return 400 if certSlug is not allowed', async () => { + const claimableCerts = [ + Certification.RespWebDesign, + // TODO: Enable, once these are no longer "upcoming". + // Certification.RespWebDesignV9, + // Certification.JsV9, + Certification.JsAlgoDataStruct, + Certification.FrontEndDevLibs, + Certification.DataVis, + Certification.RelationalDb, + Certification.BackEndDevApis, + Certification.QualityAssurance, + Certification.SciCompPy, + Certification.DataAnalysisPy, + Certification.InfoSec, + Certification.MachineLearningPy, + Certification.CollegeAlgebraPy, + Certification.FoundationalCSharp, + Certification.LegacyFrontEnd, + Certification.LegacyBackEnd, + Certification.LegacyDataVis, + Certification.LegacyInfoSecQa, + Certification.LegacyFullStack + ]; + const unclaimableCerts = ['fake-slug']; + + for (const certSlug of claimableCerts) { + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug + }); + + // `flash.incomplete-steps` comes after the check for whether a certification may be claimed or not. + expect(response.body).toMatchObject({ + response: { message: 'flash.incomplete-steps' } + }); + expect(response.status).toBe(400); + } + + for (const certSlug of unclaimableCerts) { + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug + }); + + expect(response.body).toMatchObject({ + response: { + variables: { name: certSlug }, + message: 'flash.wrong-name' + } + }); + expect(response.status).toBe(400); + } + }); + + // This has to be the last test since vi.mockRestore replaces the original + // function with undefined when restoring a prisma function (for some + // reason) + test('should return 500 if db update fails', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + completedChallenges: [ + { id: 'bd7158d8c442eddfaeb5bd18', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b03', completedDate: 123456789 }, + { id: '587d78af367417b2b2512b04', completedDate: 123456789 }, + { id: '587d78b0367417b2b2512b05', completedDate: 123456789 }, + { id: 'bd7158d8c242eddfaeb5bd13', completedDate: 123456789 } + ] + } + }); + + vi.spyOn(fastifyTestInstance.prisma, 'user', 'get').mockReturnValue({ + ...fastifyTestInstance.prisma.user, + update: vi.fn().mockRejectedValueOnce(new Error('test')) + }); + + const response = await superRequest('/certificate/verify', { + method: 'PUT', + setCookies + }).send({ + certSlug: Certification.RespWebDesign + }); + + expect(response.body).toStrictEqual({ + message: 'flash.generic-error', + type: 'danger' + }); + expect(response.status).toBe(500); + }); + }); + }); +}); + +describe('createCertLookup', () => { + let challenges: ReturnType; + + beforeAll(() => { + // TODO: create a mock challenges array specific to these tests. + challenges = getChallenges(); + }); + + test('should create a lookup for all certifications', () => { + const certLookup = createCertLookup(challenges); + + for (const cert of Object.values(Certification)) { + const certData = certLookup[cert]; + expect(certData).toHaveProperty('id'); + expect(certData).toHaveProperty('tests'); + expect(certData).toHaveProperty('challengeType'); + } + }); + + test('each certification should have a unique challenge id', () => { + const certLookup = createCertLookup(challenges); + const ids = Object.values(certLookup) + .map(({ id }) => id) + .sort(); + const uniqueIds = Array.from(new Set(ids)).sort(); + expect(uniqueIds).toEqual(ids); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.ts new file mode 100644 index 0000000000000000000000000000000000000000..e68fea85580d6d18b76a3074dbb0059933c3ee06 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/certificate.ts @@ -0,0 +1,442 @@ +import type { CompletedChallenge } from '@prisma/client'; +import validator from 'validator'; +import type { FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import { challenges, getChallenges } from '../../utils/get-challenges.js'; +import { + Certification, + type CertificationFlags, + certSlugTypeMap, + certToIdMap, + certToTitleMap, + currentCertifications, + legacyCertifications, + legacyFullStackCertification, + upcomingCertifications +} from '@freecodecamp/shared/config/certification-settings'; + +import * as schemas from '../../schemas.js'; +import { normalizeChallenges, removeNulls } from '../../utils/normalize.js'; + +import { SHOW_UPCOMING_CHANGES } from '../../utils/env.js'; +import { isKnownCertSlug } from '../helpers/certificate-utils.js'; + +function isCertAllowed(certSlug: string): boolean { + if ( + currentCertifications.includes(certSlug) || + legacyCertifications.includes(certSlug) || + legacyFullStackCertification.includes(certSlug) + ) { + return true; + } + if (SHOW_UPCOMING_CHANGES && upcomingCertifications.includes(certSlug)) { + return true; + } + return false; +} + +function renderCertifiedEmail({ + username, + name +}: { + username: string; + name: string; +}) { + const certifiedEmailTemplate = `Hi ${name || username}, + +Congratulations on completing the Certified Full-Stack Developer Curriculum! + +All of your certifications are now live at: https://www.freecodecamp.org/${username} + +Please tell me a bit more about you and your near-term goals. + +Also, check out https://contribute.freecodecamp.org/ for some fun and convenient ways you can contribute to the community. + +Happy coding, + +- Quincy Larson, teacher at freeCodeCamp +`; + return certifiedEmailTemplate; +} + +function hasCompletedTests( + tests: { id: string }[], + completedChallenges: CompletedChallenge[] +) { + return tests.every(({ id }) => + completedChallenges.some(({ id: completedId }) => completedId === id) + ); +} + +function assertTestsExist( + tests: ReturnType[number]['tests'] +): asserts tests is { id: string }[] { + if (!Array.isArray(tests)) { + throw new Error('Tests is not an array'); + } + if (!tests.every(test => typeof test === 'object' && test !== null)) { + throw new Error('Tests contains non-object values'); + } + if (!tests.every(test => typeof test.id === 'string')) { + throw new Error('Tests contain non-string ids'); + } +} + +function getCertBySlug( + cert: Certification, + challenges: ReturnType +): { id: string; tests: { id: string }[]; challengeType: number } { + const challengeId = certToIdMap[cert]; + const challengeById = challenges.filter(({ id }) => id === challengeId)[0]; + if (!challengeById) { + throw new Error(`Challenge with id '${challengeId}' not found`); + } + const { id, tests, challengeType } = challengeById; + assertTestsExist(tests); + return { id, tests, challengeType }; +} + +type CertLookup = Record< + Certification, + { id: string; tests: { id: string }[]; challengeType: number } +>; + +/** + * Create a lookup from Certification enum values to their corresponding + * challenge metadata (id, tests and challengeType) using the provided + * challenges array. + * + * @param challenges - The array returned by getChallenges(). + * @returns A record mapping each Certification to an object with id, tests and challengeType. + */ +export function createCertLookup( + challenges: ReturnType +): CertLookup { + const certLookup = {} as CertLookup; + + for (const cert of Object.values(Certification)) { + certLookup[cert] = getCertBySlug(cert, challenges); + } + return certLookup; +} + +function getUserIsCertMap(user: Partial) { + const { + is2018DataVisCert = false, + isA1ChineseCert = false, + isA2ChineseCert = false, + isA2EnglishCert = false, + isA2SpanishCert = false, + isApisMicroservicesCert = false, + isB1EnglishCert = false, + isBackEndCert = false, + isBackEndDevApisCertV9 = false, + isCollegeAlgebraPyCertV8 = false, + isDataAnalysisPyCertV7 = false, + isDataVisCert = false, + isFoundationalCSharpCertV8 = false, + isFrontEndCert = false, + isFrontEndLibsCert = false, + isFrontEndLibsCertV9 = false, + isFullStackCert = false, + isFullStackDeveloperCertV9 = false, + isInfosecCertV7 = false, + isInfosecQaCert = false, + isJavascriptCertV9 = false, + isJsAlgoDataStructCert = false, + isJsAlgoDataStructCertV8 = false, + isMachineLearningPyCertV7 = false, + isPythonCertV9 = false, + isQaCertV7 = false, + isRelationalDatabaseCertV8 = false, + isRelationalDatabaseCertV9 = false, + isRespWebDesignCert = false, + isRespWebDesignCertV9 = false, + isSciCompPyCertV7 = false + } = user; + + return { + is2018DataVisCert, + isA1ChineseCert, + isA2ChineseCert, + isA2EnglishCert, + isA2SpanishCert, + isApisMicroservicesCert, + isB1EnglishCert, + isBackEndCert, + isBackEndDevApisCertV9, + isCollegeAlgebraPyCertV8, + isDataAnalysisPyCertV7, + isDataVisCert, + isFoundationalCSharpCertV8, + isFrontEndCert, + isFrontEndLibsCert, + isFrontEndLibsCertV9, + isFullStackCert, + isFullStackDeveloperCertV9, + isInfosecCertV7, + isInfosecQaCert, + isJavascriptCertV9, + isJsAlgoDataStructCert, + isJsAlgoDataStructCertV8, + isMachineLearningPyCertV7, + isPythonCertV9, + isQaCertV7, + isRelationalDatabaseCertV8, + isRelationalDatabaseCertV9, + isRespWebDesignCert, + isRespWebDesignCertV9, + isSciCompPyCertV7 + }; +} + +/** + * Plugin for the protected certificate endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const protectedCertificateRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + const certLookup = createCertLookup(challenges); + + // TODO(POST_MVP): Response should not include updated user. If a client wants the updated user, it should make a separate request + // OR: Always respond with current user - full user object - not random pieces. + fastify.put( + '/certificate/verify', + { + schema: schemas.certificateVerify, + errorHandler(error, request, reply) { + if (error.validation) { + void reply.code(400).send({ + response: { + type: 'danger', + message: 'flash.wrong-name', + variables: { name: '' } + } + }); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + const { certSlug } = req.body; + + if (!isKnownCertSlug(certSlug) || !isCertAllowed(certSlug)) { + req.log.warn({ certSlug }, 'Unknown certificate slug'); + fastify.Sentry?.metrics?.count('certificate.claim_blocked', 1, { + attributes: { reason: 'unknown_slug' } + }); + void reply.code(400); + return { + response: { + type: 'danger', + // message: 'Certificate type not found' + message: 'flash.wrong-name', + variables: { name: certSlug } + } + } as const; + } + + const certType = certSlugTypeMap[certSlug]; + const certName = certToTitleMap[certSlug]; + + const user = await fastify.prisma.user.findUnique({ + where: { id: req.user?.id } + }); + + if (!user) { + void reply.code(500); + fastify.Sentry?.captureException( + new Error('User not found when claiming certificate') + ); + fastify.Sentry?.metrics?.count('certificate.claim_user_missing', 1); + req.log.error('User not found'); + return { + type: 'danger', + // message: 'User not found' + message: 'flash.went-wrong' + } as const; + } + const { completedChallenges } = user; + const isCertMap = getUserIsCertMap(removeNulls(user)); + + // TODO: Discuss if this is a requirement still + if (!user.name) { + req.log.warn('User does not have a name property'); + fastify.Sentry?.metrics?.count('certificate.claim_blocked', 1, { + attributes: { certSlug, reason: 'name_missing' } + }); + void reply.code(400); + return { + response: { + type: 'info', + message: 'flash.name-needed' + }, + isCertMap, + completedChallenges: normalizeChallenges(completedChallenges) + } as const; + } + + if (user[certType]) { + req.log.debug({ certName }, 'User has already claimed certificate'); + fastify.Sentry?.metrics?.count('certificate.claim_blocked', 1, { + attributes: { certSlug, reason: 'already_claimed' } + }); + void reply.code(200); + return { + response: { + type: 'info', + message: 'flash.already-claimed', + variables: { + name: certName + } + }, + isCertMap, + completedChallenges: normalizeChallenges(completedChallenges) + } as const; + } + + const { id, tests, challengeType } = certLookup[certSlug]; + const hasCompletedTestRequirements = hasCompletedTests( + tests, + user.completedChallenges + ); + + if (!hasCompletedTestRequirements) { + req.log.warn( + { certName }, + 'User has not completed the tests for certificate' + ); + fastify.Sentry?.metrics?.count('certificate.claim_blocked', 1, { + attributes: { certSlug, reason: 'incomplete_steps' } + }); + void reply.code(400); + return { + response: { + type: 'info', + message: 'flash.incomplete-steps', + variables: { + name: certName + } + }, + isCertMap, + completedChallenges: normalizeChallenges(completedChallenges) + } as const; + } + + const updatedUser = await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + [certType]: true, + completedChallenges: { + push: { + id, + completedDate: Date.now(), + challengeType + } + } + }, + select: { + completedChallenges: true, + email: true, + name: true, + username: true, + is2018DataVisCert: true, + is2018FullStackCert: true, + isA1ChineseCert: true, + isA2ChineseCert: true, + isA2EnglishCert: true, + isA2SpanishCert: true, + isApisMicroservicesCert: true, + isB1EnglishCert: true, + isBackEndCert: true, + isBackEndDevApisCertV9: true, + isCollegeAlgebraPyCertV8: true, + isDataAnalysisPyCertV7: true, + isDataVisCert: true, + isFoundationalCSharpCertV8: true, + isFrontEndCert: true, + isFrontEndLibsCert: true, + isFrontEndLibsCertV9: true, + isFullStackCert: true, + isFullStackDeveloperCertV9: true, + isInfosecCertV7: true, + isInfosecQaCert: true, + isJavascriptCertV9: true, + isJsAlgoDataStructCert: true, + isJsAlgoDataStructCertV8: true, + isMachineLearningPyCertV7: true, + isPythonCertV9: true, + isQaCertV7: true, + isRelationalDatabaseCertV8: true, + isRelationalDatabaseCertV9: true, + isRespWebDesignCert: true, + isRespWebDesignCertV9: true, + isSciCompPyCertV7: true + } + }); + + const email = updatedUser.email; + const updatedUserSansNull = removeNulls(updatedUser); + const updatedIsCertMap = getUserIsCertMap(updatedUserSansNull); + + // TODO(POST-MVP): Consider sending email based on `user.isEmailVerified` as well + const fullStackV9Claimed = updatedIsCertMap.isFullStackDeveloperCertV9; + + const shouldSendCertifiedEmailToCamper = + email && validator.default.isEmail(email) && fullStackV9Claimed; + + if (shouldSendCertifiedEmailToCamper) { + const notifyUser = { + to: email, + from: 'quincy@freecodecamp.org', + subject: + 'Congratulations on completing the Certified Full-Stack Developer Curriculum!', + text: renderCertifiedEmail({ + username: updatedUser.username, + // Safety: `user.name` is required to exist earlier. TODO: Assert + name: updatedUser.name as string + }) + }; + + // Failed email should not prevent successful response. + try { + req.log.debug('Sending congratulations email'); + // TODO(POST-MVP): Ensure Camper knows they **have** claimed the cert, but the email failed to send. + await fastify.sendEmail(notifyUser); + } catch (e) { + req.log.error(e, 'Failed to send congratulations email'); + fastify.Sentry?.captureException(e); + } + } + + req.log.info({ certName, audit: true }, 'User has claimed certificate'); + fastify.Sentry?.metrics?.count('certificate.claimed', 1, { + attributes: { certSlug } + }); + void reply.code(200); + return { + response: { + type: 'success', + message: 'flash.cert-claim-success', + variables: { + username: updatedUser.username, + name: certName + } + }, + isCertMap: updatedIsCertMap, + completedChallenges: normalizeChallenges( + updatedUserSansNull.completedChallenges + ) + } as const; + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2bc871729652d457a0d917e0e2c46eebe1a254f6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.test.ts @@ -0,0 +1,3052 @@ +import { + describe, + test, + expect, + beforeAll, + afterEach, + beforeEach, + afterAll, + vi +} from 'vitest'; + +vi.mock('../helpers/challenge-helpers', async () => { + const originalModule = await vi.importActual< + typeof import('../helpers/challenge-helpers.js') + >('../helpers/challenge-helpers'); + + return { + __esModule: true, + ...originalModule, + verifyTrophyWithMicrosoft: vi.fn() + }; +}); + +vi.mock('../../utils/exam.js', async () => { + const originalModule = await vi.importActual< + typeof import('../../utils/exam.js') + >('../../utils/exam.js'); + + return { + __esModule: true, + ...originalModule, + generateRandomExam: vi.fn(originalModule.generateRandomExam) + }; +}); + +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import { omit } from 'lodash-es'; +import { Static } from '@fastify/type-provider-typebox'; +import { DailyCodingChallengeLanguage } from '@prisma/client'; +import request from 'supertest'; + +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; +import { + defaultUserId, + devLogin, + setupServer, + superRequest, + seedExam, + defaultUserEmail, + createSuperRequest, + defaultUsername +} from '../../../vitest.utils.js'; +import { + completedExamChallengeOneCorrect, + completedExamChallengeTwoCorrect, + completedExamChallengeAllCorrect, + completedTrophyChallenges, + examChallengeId, + examJson, + mockResultsZeroCorrect, + mockResultsTwoCorrect, + mockResultsAllCorrect, + examWithZeroCorrect, + examWithOneCorrect, + examWithTwoCorrect, + examWithAllCorrect, + type ExamSubmission +} from '../../../__fixtures__/exam.js'; +import { Answer } from '../../utils/exam-types.js'; +import type { getSessionUser } from '../../schemas/user/get-session-user.js'; +import { verifyTrophyWithMicrosoft } from '../helpers/challenge-helpers.js'; +import { encodeUserToken } from '../../utils/tokens.js'; +import { generateRandomExam } from '../../utils/exam.js'; + +const mockVerifyTrophyWithMicrosoft = vi.mocked(verifyTrophyWithMicrosoft); +const mockGenerateRandomExam = vi.mocked(generateRandomExam); + +const EXISTING_COMPLETED_DATE = new Date('2024-11-08').getTime(); +const DATE_NOW = Date.now(); + +vi.mock('../helpers/challenge-helpers.js', async () => { + const originalModule = await vi.importActual< + typeof import('../helpers/challenge-helpers.js') + >('../helpers/challenge-helpers'); + + return { + __esModule: true, + ...originalModule, + verifyTrophyWithMicrosoft: vi.fn() + }; +}); + +const isValidChallengeCompletionErrorMsg = { + type: 'error', + message: 'That does not appear to be a valid challenge submission.' +}; + +// /project-completed +const id1 = 'bd7123c8c441eddfaeb5bdef'; +const id2 = 'bd7123c8c441eddfaeb5bdec'; + +const codeallyProject = { + id: id1, + challengeType: challengeTypes.codeAllyCert, + solution: 'https://any.valid/url' +}; +const backendProject = { + id: id2, + challengeType: challengeTypes.backEndProject, + solution: 'https://any.valid/url', + githubLink: 'https://github.com/anything/valid/' +}; +const partialCompletion = { id: id1, completedDate: 1 }; + +// /backend-challenge-completed +const backendChallengeId1 = '587d7fb1367417b2b2512bf4'; +const backendChallengeId2 = '587d7fb2367417b2b2512bf8'; + +const backendChallengeBody1 = { + id: backendChallengeId1 +}; +const backendChallengeBody2 = { + id: backendChallengeId2 +}; + +// /modern-challenge-completed +const HtmlChallengeId = '5dc174fcf86c76b9248c6eb2'; +const JsProjectId = '56533eb9ac21ba0edf2244e2'; +const multiFileCertProjectId = 'bd7158d8c242eddfaeb5bd13'; + +const HtmlChallengeBody = { + challengeType: challengeTypes.html, + id: HtmlChallengeId +}; + +const baseJsProjectBody = { + challengeType: challengeTypes.jsProject, + id: JsProjectId +}; + +const jsFiles = [ + { + contents: 'console.log("Hello There!")', + key: 'scriptjs', + ext: 'js', + name: 'script', + history: ['script.js'] + } +]; + +const encodedJsFiles = [ + { + contents: btoa('console.log("Hello There!")'), + key: 'scriptjs', + ext: 'js', + name: 'script', + history: ['script.js'] + } +]; + +const baseMultiFileCertProjectBody = { + challengeType: challengeTypes.multifileCertProject, + id: multiFileCertProjectId +}; + +const multiFiles = [ + { + contents: '

Multi File Project v1

', + key: 'indexhtml', + ext: 'html', + name: 'index', + history: ['index.html'] + }, + { + contents: '.hello-there { general: kenobi; }', + key: 'stylescss', + ext: 'css', + name: 'styles', + history: ['styles.css'] + } +]; + +const updatedMultiFiles = [ + { + contents: '

Multi File Project v2

', + key: 'indexhtml', + ext: 'html', + name: 'index', + history: ['index.html'] + }, + { + contents: '.wibbly-wobbly { timey: wimey; }', + key: 'stylescss', + ext: 'css', + name: 'styles', + history: ['styles.css'] + } +]; + +const encodedMultiFiles = [ + { + contents: btoa('

Multi File Project v1

'), + key: 'indexhtml', + ext: 'html', + name: 'index', + history: ['index.html'] + }, + { + contents: btoa('.hello-there { general: kenobi; }'), + key: 'stylescss', + ext: 'css', + name: 'styles', + history: ['styles.css'] + } +]; + +const encodedUpdatedMultiFiles = [ + { + contents: btoa('

Multi File Project v2

'), + key: 'indexhtml', + ext: 'html', + name: 'index', + history: ['index.html'] + }, + { + contents: btoa('.wibbly-wobbly { timey: wimey; }'), + key: 'stylescss', + ext: 'css', + name: 'styles', + history: ['styles.css'] + } +]; + +const dailyCodingChallengeId = '5900f36e1000cf542c50fe80'; +const dailyCodingChallengeBody = { + id: dailyCodingChallengeId, + language: DailyCodingChallengeLanguage.javascript +}; + +const examId = '6721db5d9f0c116e6a0fe25a'; + +describe('challengeRoutes', () => { + setupServer(); + describe('Authenticated user', () => { + let setCookies: string[]; + let superPost: ReturnType; + let superGet: ReturnType; + + // Authenticate user + beforeAll(async () => { + setCookies = await devLogin(); + superPost = createSuperRequest({ method: 'POST', setCookies }); + superGet = createSuperRequest({ method: 'GET', setCookies }); + await seedExam(); + }); + + describe('POST /coderoad-challenge-completed', () => { + test('should return 400 if no tutorialId', async () => { + const response = await superPost('/coderoad-challenge-completed'); + expect(response.body).toEqual({ + msg: `'tutorialId' not found in request body`, + type: 'error' + }); + expect(response.status).toBe(400); + }); + + test('should return 400 if no user token', async () => { + const response = await superPost('/coderoad-challenge-completed').send({ + tutorialId: 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + expect(response.body).toEqual({ + msg: `'Coderoad-User-Token' not found in request headers`, + type: 'error' + }); + expect(response.status).toBe(400); + }); + + test('should return 401 if the token is valid, but has no userToken property', async () => { + // @ts-expect-error TS is trying to protect us, but we need to test this + // edge case. + const emptyToken = encodeUserToken(undefined); + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', emptyToken) + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + + expect(response.body).toEqual({ + msg: 'invalid user token', + type: 'error' + }); + expect(response.status).toBe(401); + }); + + test('should return 401 for invalid user tokens', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', 'invalid') + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + expect(response.body).toEqual({ + msg: 'invalid user token', + type: 'error' + }); + expect(response.status).toBe(401); + expect(count).toHaveBeenCalledWith('coderoad.request_rejected', 1, { + attributes: { reason: 'invalid_token' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 401 for nonsensical user tokens', async () => { + // @ts-expect-error TS is trying to protect us, but we need to test this + // edge case. + const weirdToken = encodeUserToken({}); + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', weirdToken) + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + expect(response.body).toEqual({ + msg: 'invalid user token', + type: 'error' + }); + expect(response.status).toBe(401); + }); + + test('should return 400 if invalid tutorialId', async () => { + const tokenResponse = await superPost('/user/user-token'); + expect(tokenResponse.body).toHaveProperty('userToken'); + expect(tokenResponse.status).toBe(200); + + const token = (tokenResponse.body as { userToken: string }).userToken; + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', token) + .send({ tutorialId: 'invalid' }); + + expect(response.body).toEqual({ + msg: 'Tutorial not hosted on freeCodeCamp GitHub account', + type: 'error' + }); + expect(response.status).toBe(400); + expect(count).toHaveBeenCalledWith('coderoad.request_rejected', 1, { + attributes: { reason: 'untrusted_org' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 404 if invalid tutorialId but is hosted on freeCodeCamp', async () => { + const tokenResponse = await superPost('/user/user-token'); + expect(tokenResponse.body).toHaveProperty('userToken'); + expect(tokenResponse.status).toBe(200); + + const token = (tokenResponse.body as { userToken: string }).userToken; + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', token) + .send({ tutorialId: 'freeCodeCamp/invalid:V1.0.0' }); + + expect(response.body).toEqual({ + msg: 'Tutorial name is not valid', + type: 'error' + }); + expect(response.status).toBe(404); + expect(count).toHaveBeenCalledWith('coderoad.request_rejected', 1, { + attributes: { reason: 'invalid_tutorial' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 401 if user token not found', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const nonexistentToken = encodeUserToken('5fa5c1c3b1c9d40000000000'); + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', nonexistentToken) + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + + expect(response.body).toEqual({ + msg: 'User token not found', + type: 'error' + }); + expect(response.status).toBe(401); + expect(count).toHaveBeenCalledWith('coderoad.request_rejected', 1, { + attributes: { reason: 'token_not_found' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 401 if the token user no longer exists', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const orphanTokenId = 'aaaaaaaaaaaaaaaaaaaaaaaa'; + await fastifyTestInstance.prisma.userToken.create({ + data: { + id: orphanTokenId, + created: new Date(), + ttl: 1000, + userId: '5fa5c1c3b1c9d40000000000' + } + }); + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', encodeUserToken(orphanTokenId)) + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { id: orphanTokenId } + }); + + expect(response.body).toEqual({ + type: 'error', + msg: 'User for user token not found' + }); + expect(response.status).toBe(401); + expect(count).toHaveBeenCalledWith('coderoad.request_rejected', 1, { + attributes: { reason: 'user_not_found' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('Should complete challenge with code 200', async () => { + const tokenResponse = await superPost('/user/user-token'); + expect(tokenResponse.body).toHaveProperty('userToken'); + expect(tokenResponse.status).toBe(200); + + const token = (tokenResponse.body as { userToken: string }).userToken; + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + // This route is special since it does not have CSRF protection OR authN + // protection. As such, we use a normal `request` to send the bare + // minimum (no extra headers or cookies). + const response = await request(fastifyTestInstance.server) + .post('/coderoad-challenge-completed') + .set('coderoad-user-token', token) + .send({ + tutorialId: + 'freeCodeCamp/learn-bash-by-building-a-boilerplate:v1.0.0' + }); + + expect(response.body).toEqual({ + msg: 'Successfully submitted challenge', + type: 'success' + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + const challengeCompleted = user?.completedChallenges.some(challenge => { + return challenge.id === '5ea8adfab628f68d805bfc5e'; + }); + + expect(challengeCompleted).toBe(true); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith('coderoad.challenge_completed', 1, { + attributes: { result: 'completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('Should complete project with code 200', async () => { + const tokenResponse = await superPost('/user/user-token'); + expect(tokenResponse.body).toHaveProperty('userToken'); + expect(tokenResponse.status).toBe(200); + + const token = (tokenResponse.body as { userToken: string }).userToken; + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', token) + .send({ + tutorialId: 'freeCodeCamp/learn-celestial-bodies-database:v1.0.0' + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + const projectCompleted = user?.partiallyCompletedChallenges.some( + project => { + return project.id === '5f1a4ef5d5d6b5ab580fc6ae'; + } + ); + expect(response.body).toEqual({ + msg: 'Successfully submitted challenge', + type: 'success' + }); + expect(projectCompleted).toBe(true); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith('coderoad.challenge_completed', 1, { + attributes: { result: 'partial' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + // This has to be the last test since vi.mockRestore replaces the original + // function with undefined when restoring a prisma function (for some + // reason) + test('Should return an error response if something goes wrong', async () => { + const originalUserToken = fastifyTestInstance.prisma.userToken; + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + vi.spyOn( + fastifyTestInstance.prisma, + 'userToken', + 'get' + ).mockReturnValue({ + ...originalUserToken, + findUnique: vi.fn().mockImplementationOnce(() => { + throw new Error('Database error'); + }) + }); + const tokenResponse = await superPost('/user/user-token'); + const token = (tokenResponse.body as { userToken: string }).userToken; + + const response = await superPost('/coderoad-challenge-completed') + .set('coderoad-user-token', token) + .send({ + tutorialId: 'freeCodeCamp/learn-celestial-bodies-database:v1.0.0' + }); + + expect(response.body).toEqual({ + msg: 'An error occurred trying to submit the challenge', + type: 'error' + }); + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + afterAll(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + progressTimestamps: [] + } + }); + }); + }); + describe('/project-completed', () => { + describe('validation', () => { + test('should reject exam submissions', async () => { + const response = await superPost('/project-completed').send({ + id: examId, + challengeType: challengeTypes.backEndProject, + solution: 'http://localhost:3000', + githubLink: 'http://localhost:3000' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests without ids', async () => { + const response = await superPost('/project-completed').send({}); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectIDs', async () => { + const response = await superPost( + '/project-completed' + // This is a departure from api-server, which does not require a + // solution to give this error. However, the validator will reject + // based on the missing solution before it gets to the invalid id. + ).send({ id: 'not-a-valid-id', solution: '' }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests with invalid challengeTypes', async () => { + const response = await superPost('/project-completed').send({ + id: id1, + challengeType: 'not-a-valid-challenge-type', + // TODO(Post-MVP): drop these comments, since the api-server will not + // exist. + + // a solution is required, because otherwise the request will be + // rejected before it gets to the challengeType validation. NOTE: this + // is a departure from the api-server, but only in the message sent. + solution: '' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without solutions', async () => { + const response = await superPost('/project-completed').send({ + id: id1, + challengeType: 3 + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: + 'You have not provided the valid links for us to inspect your work.' + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests with solutions that are not urls', async () => { + const response = await superPost('/project-completed').send({ + id: id1, + challengeType: 3, + solution: 'not-a-valid-solution' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects backendProject requests without URL githubLinks', async () => { + const response = await superPost('/project-completed').send({ + id: id1, + challengeType: challengeTypes.backEndProject, + // Solution is allowed to be localhost for backEndProject + solution: 'http://localhost:3000' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(403); + + const response_2 = await superPost('/project-completed').send({ + id: id1, + challengeType: challengeTypes.backEndProject, + solution: 'http://localhost:3000', + githubLink: 'not-a-valid-url' + }); + + expect(response_2.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response_2.statusCode).toBe(403); + }); + + test('POST does not log the raw solution or githubLink on backEndProject validation failure', async () => { + const spy = vi.spyOn(fastifyTestInstance.log, 'warn'); + spy.mockClear(); + + const leakySolution = + 'https://example.com/solution?api_key=super-secret'; + const leakyGithubLink = 'not-a-valid-url-with-token-abc123'; + + const response = await superPost('/project-completed').send({ + id: id1, + challengeType: challengeTypes.backEndProject, + solution: leakySolution, + githubLink: leakyGithubLink + }); + + expect(response.statusCode).toBe(403); + + const call = spy.mock.calls.find( + ([, msg]) => msg === 'Invalid backEndProject submission' + ); + expect(call).toBeDefined(); + const [logObject] = call!; + expect(JSON.stringify(logObject)).not.toContain(leakySolution); + expect(JSON.stringify(logObject)).not.toContain(leakyGithubLink); + expect(JSON.stringify(logObject)).not.toContain('super-secret'); + expect(JSON.stringify(logObject)).not.toContain('token-abc123'); + expect(logObject).toEqual({ + hasSolution: true, + solutionLength: leakySolution.length, + hasGithubLink: true, + githubLinkLength: leakyGithubLink.length + }); + }); + + test('POST rejects CodeRoad/CodeAlly projects when the user has not completed the required challenges', async () => { + const response = await superPost('/project-completed').send({ + id: id1, // not a codeally challenge id, but does not matter + challengeType: 13, // this does matter, however, since there's special logic for that challenge type + solution: 'https://any.valid/url' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: + 'You have to complete the project before you can submit a URL.' + }); + // It's not really a bad request, since the client is sending a valid + // body. It's just that the user is not allowed to do this - hence 403. + expect(response.statusCode).toBe(403); + }); + }); + + describe('handling', () => { + beforeEach(async () => { + // setup: complete the challenges that codeally projects require + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + partiallyCompletedChallenges: [{ id: id1, completedDate: 1 }], + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + partiallyCompletedChallenges: [], + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + + test('POST accepts CodeRoad/CodeAlly projects when the user has completed the required challenges', async () => { + const now = Date.now(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = + await superPost('/project-completed').send(codeallyProject); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + partiallyCompletedChallenges: [], + completedChallenges: [ + { + ...codeallyProject, + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user?.completedChallenges[0]?.completedDate; + + // TODO: use a custom matcher for this + expect(completedDate).toBeGreaterThan(now); + expect(completedDate).toBeLessThan(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate + }); + + expect(response.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('challenge.completed', 1, { + attributes: { result: 'completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST accepts backend projects', async () => { + const now = Date.now(); + + const response = + await superPost('/project-completed').send(backendProject); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + partiallyCompletedChallenges: [partialCompletion], + completedChallenges: [ + { + ...backendProject, + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user?.completedChallenges[0]?.completedDate; + + // TODO: use a custom matcher for this + expect(completedDate).toBeGreaterThan(now); + expect(completedDate).toBeLessThan(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate + }); + + expect(response.statusCode).toBe(200); + }); + + test('POST correctly handles multiple requests', async () => { + const resOriginal = + await superPost('/project-completed').send(codeallyProject); + + const resBackend = + await superPost('/project-completed').send(backendProject); + + // sending backendProject again should update its solution, but not + // progressTimestamps or its completedDate + + const resUpdate = await superPost('/project-completed').send({ + ...codeallyProject, + solution: 'https://any.other/url' + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + const expectedProgressTimestamps = user?.completedChallenges.map( + challenge => challenge.completedDate + ); + + expect(user).toMatchObject({ + completedChallenges: [ + { + ...codeallyProject, + solution: 'https://any.other/url', + completedDate: resOriginal.body.completedDate + }, + { + ...backendProject, + completedDate: resBackend.body.completedDate + } + ], + progressTimestamps: expectedProgressTimestamps + }); + + expect(resUpdate.body).toStrictEqual({ + alreadyCompleted: true, + points: 2, + completedDate: expect.any(Number) + }); + + // If a challenge has already been completed, it should return the + // original completedDate + expect(resUpdate.body.completedDate).toBe( + resOriginal.body.completedDate + ); + expect(resUpdate.statusCode).toBe(200); + }); + }); + }); + + describe('/backend-challenge-completed', () => { + describe('validation', () => { + test('should reject exam submissions', async () => { + const response = await superPost('/backend-challenge-completed').send( + { + id: examId, + challengeType: challengeTypes.backEndProject, + solution: 'http://localhost:3000', + githubLink: 'http://localhost:3000' + } + ); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests without ids', async () => { + const response = await superPost('/backend-challenge-completed'); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectIDs', async () => { + const response = await superPost('/backend-challenge-completed').send( + { id: 'not-a-valid-id', solution: '' } + ); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + progressTimestamps: [] + } + }); + }); + + test('POST accepts backend challenges', async () => { + const now = Date.now(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/backend-challenge-completed').send( + backendChallengeBody1 + ); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + completedChallenges: [ + { + ...backendChallengeBody1, + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user?.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate + }); + expect(response.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('challenge.completed', 1, { + attributes: { result: 'completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST correctly handles multiple requests', async () => { + const resOriginal = await superPost( + '/backend-challenge-completed' + ).send(backendChallengeBody1); + + await superPost('/backend-challenge-completed').send( + backendChallengeBody2 + ); + + const resUpdated = await superPost( + '/backend-challenge-completed' + ).send({ + ...backendChallengeBody1 + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + const expectedProgressTimestamps = user?.completedChallenges.map( + challenge => challenge.completedDate + ); + + expect(user).toMatchObject({ + completedChallenges: [ + { + ...backendChallengeBody1, + completedDate: expect.any(Number) + }, + { + ...backendChallengeBody2, + completedDate: expect.any(Number) + } + ], + progressTimestamps: expectedProgressTimestamps + }); + + expect(resUpdated.body.completedDate).not.toBe( + resOriginal.body.completedDate + ); + expect(resUpdated.body).toStrictEqual({ + alreadyCompleted: true, + points: 2, + completedDate: expect.any(Number) + }); + expect(resUpdated.statusCode).toBe(200); + }); + }); + }); + + describe('/modern-challenge-completed', () => { + describe('validation', () => { + test('should reject exam submissions', async () => { + const response = await superPost('/modern-challenge-completed').send({ + id: examId, + challengeType: challengeTypes.backEndProject, + solution: 'http://localhost:3000', + githubLink: 'http://localhost:3000' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests without ids', async () => { + const response = await superPost('/modern-challenge-completed'); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectIDs', async () => { + const response = await superPost('/modern-challenge-completed').send({ + id: 'not-a-valid-id' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + + // HTML(0), JS(1), Modern(6), Video(11), The Odin Project(15) + test('POST accepts challenges without files present', async () => { + const now = Date.now(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/modern-challenge-completed').send( + HtmlChallengeBody + ); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + completedChallenges: [ + { + id: HtmlChallengeId, + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + savedChallenges: [] + }); + expect(count).toHaveBeenCalledWith('challenge.completed', 1, { + attributes: { result: 'completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + // JS Project(5), Multi-file Cert Project(14) + test('POST accepts challenges with files present', async () => { + const now = Date.now(); + + const response = await superPost('/modern-challenge-completed').send({ + ...baseJsProjectBody, + files: jsFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const file = omit(jsFiles[0], 'history'); + + expect(user).toMatchObject({ + completedChallenges: [ + { + id: JsProjectId, + challengeType: baseJsProjectBody.challengeType, + files: [file], + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + savedChallenges: [ + { + files: jsFiles, + id: JsProjectId, + lastSavedDate: expect.any(Number) + } + ] + }); + expect(response.statusCode).toBe(200); + }); + + test('POST accepts challenges with saved solutions', async () => { + const now = Date.now(); + + const response = await superPost('/modern-challenge-completed').send({ + ...baseMultiFileCertProjectBody, + files: multiFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const testFiles = multiFiles.map( + ({ history: _history, ...rest }) => rest + ); + + expect(user).toMatchObject({ + needsModeration: true, + completedChallenges: [ + { + id: multiFileCertProjectId, + challengeType: baseMultiFileCertProjectBody.challengeType, + files: testFiles, + completedDate: expect.any(Number), + isManuallyApproved: false + } + ], + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: multiFiles + } + ] + }); + + const completedDate = user.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: completedDate, + files: multiFiles + } + ] + }); + expect(response.statusCode).toBe(200); + }); + + test('POST correctly handles multiple requests', async () => { + const resOriginal = await superPost( + '/modern-challenge-completed' + ).send({ ...baseMultiFileCertProjectBody, files: multiFiles }); + + await superPost('/modern-challenge-completed').send( + HtmlChallengeBody + ); + + const resUpdate = await superPost('/modern-challenge-completed').send( + { ...baseMultiFileCertProjectBody, files: updatedMultiFiles } + ); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const expectedProgressTimestamps = user.completedChallenges.map( + challenge => challenge.completedDate + ); + + const testFiles = updatedMultiFiles.map(file => + omit(file, 'history') + ); + + expect(user).toMatchObject({ + needsModeration: true, + completedChallenges: [ + { + id: multiFileCertProjectId, + challengeType: baseMultiFileCertProjectBody.challengeType, + files: testFiles, + completedDate: expect.any(Number), + isManuallyApproved: false + }, + { + id: HtmlChallengeId, + completedDate: expect.any(Number) + } + ], + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: updatedMultiFiles + } + ], + progressTimestamps: expectedProgressTimestamps + }); + + expect( + resUpdate.body.savedChallenges[0].lastSavedDate + ).toBeGreaterThan( + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + resOriginal.body.savedChallenges[0].lastSavedDate + ); + + expect(resUpdate.body).toStrictEqual({ + alreadyCompleted: true, + points: 2, + completedDate: expect.any(Number), + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: updatedMultiFiles + } + ] + }); + expect(resUpdate.statusCode).toBe(200); + }); + }); + }); + + describe('/encoded/modern-challenge-completed', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + savedChallenges: [], + progressTimestamps: [] + } + }); + }); + test('should reject exam submissions', async () => { + const response = await superPost( + '/encoded/modern-challenge-completed' + ).send({ + id: examId, + challengeType: challengeTypes.backEndProject, + solution: 'http://localhost:3000', + githubLink: 'http://localhost:3000' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + // JS Project(5), Multi-file Cert Project(14) + test('POST accepts challenges with files present', async () => { + const now = Date.now(); + + const response = await superPost( + '/encoded/modern-challenge-completed' + ).send({ ...baseJsProjectBody, files: encodedJsFiles }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const file = omit(jsFiles[0], 'history'); + + expect(user).toMatchObject({ + completedChallenges: [ + { + id: JsProjectId, + challengeType: baseJsProjectBody.challengeType, + files: [file], + completedDate: expect.any(Number) + } + ] + }); + + const completedDate = user.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + savedChallenges: [ + { + files: jsFiles, + id: JsProjectId, + lastSavedDate: expect.any(Number) + } + ] + }); + expect(response.statusCode).toBe(200); + }); + + test('POST accepts challenges with saved solutions', async () => { + const now = Date.now(); + + const response = await superPost( + '/encoded/modern-challenge-completed' + ).send({ + ...baseMultiFileCertProjectBody, + files: encodedUpdatedMultiFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const testFiles = updatedMultiFiles.map( + ({ history: _history, ...rest }) => rest + ); + + expect(user).toMatchObject({ + needsModeration: true, + completedChallenges: [ + { + id: multiFileCertProjectId, + challengeType: baseMultiFileCertProjectBody.challengeType, + files: testFiles, + completedDate: expect.any(Number), + isManuallyApproved: false + } + ], + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: updatedMultiFiles + } + ] + }); + + const completedDate = user.completedChallenges[0]?.completedDate; + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(response.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: completedDate, + files: updatedMultiFiles + } + ] + }); + expect(response.statusCode).toBe(200); + }); + + test('POST correctly handles multiple requests', async () => { + const resOriginal = await superPost( + '/encoded/modern-challenge-completed' + ).send({ + ...baseMultiFileCertProjectBody, + files: encodedMultiFiles + }); + + await superPost('/encoded/modern-challenge-completed').send( + HtmlChallengeBody + ); + + const resUpdate = await superPost( + '/encoded/modern-challenge-completed' + ).send({ + ...baseMultiFileCertProjectBody, + files: encodedUpdatedMultiFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const expectedProgressTimestamps = user.completedChallenges.map( + challenge => challenge.completedDate + ); + + const testFiles = updatedMultiFiles.map(file => omit(file, 'history')); + + expect(user).toMatchObject({ + needsModeration: true, + completedChallenges: [ + { + id: multiFileCertProjectId, + challengeType: baseMultiFileCertProjectBody.challengeType, + files: testFiles, + completedDate: expect.any(Number), + isManuallyApproved: false + }, + { + id: HtmlChallengeId, + completedDate: expect.any(Number) + } + ], + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: updatedMultiFiles + } + ], + progressTimestamps: expectedProgressTimestamps + }); + + expect(resUpdate.body.savedChallenges[0].lastSavedDate).toBeGreaterThan( + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + resOriginal.body.savedChallenges[0].lastSavedDate + ); + + expect(resUpdate.body).toStrictEqual({ + alreadyCompleted: true, + points: 2, + completedDate: expect.any(Number), + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: expect.any(Number), + files: updatedMultiFiles + } + ] + }); + expect(resUpdate.statusCode).toBe(200); + }); + }); + + describe('/daily-coding-challenge-completed', () => { + describe('validation', () => { + test('should reject exam submissions', async () => { + const response = await superPost( + '/daily-coding-challenge-completed' + ).send({ + id: examId, + language: 'javascript' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests without an id', async () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { id, ...noIdReqBody } = dailyCodingChallengeBody; + const response = await superPost( + '/daily-coding-challenge-completed' + ).send(noIdReqBody); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without a language', async () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { language, ...noLanguageReqBody } = dailyCodingChallengeBody; + const response = await superPost( + '/daily-coding-challenge-completed' + ).send(noLanguageReqBody); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectIDs', async () => { + const response = await superPost( + '/daily-coding-challenge-completed' + ).send({ + ...dailyCodingChallengeBody, + id: 'not-a-valid-id' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid coding language', async () => { + const response = await superPost( + '/daily-coding-challenge-completed' + ).send({ + ...dailyCodingChallengeBody, + language: 'not-a-valid-language' + }); + + expect(response.body).toStrictEqual( + isValidChallengeCompletionErrorMsg + ); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedDailyCodingChallenges: [], + progressTimestamps: [] + } + }); + }); + + test('POST correctly handles multiple requests', async () => { + const now = Date.now(); + + const res1 = await superPost( + '/daily-coding-challenge-completed' + ).send(dailyCodingChallengeBody); + + const user1 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const completedDate = + user1.completedDailyCodingChallenges[0]?.completedDate; + + // should have correct completedDate + expect(completedDate).toBeGreaterThanOrEqual(now); + expect(completedDate).toBeLessThanOrEqual(now + 1000); + + expect(user1).toMatchObject({ + // should add completedDailyCodingChallenge to database with correct info + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [DailyCodingChallengeLanguage.javascript] + } + ], + // should add to progressTimestamps + progressTimestamps: [completedDate] + }); + + // should have correct response + expect(res1.statusCode).toBe(200); + expect(res1.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate, + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [DailyCodingChallengeLanguage.javascript] + } + ] + }); + + const res2 = await superPost( + '/daily-coding-challenge-completed' + ).send(dailyCodingChallengeBody); + + const user2 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + // should not add 'javascript' again, should not update completedDate + expect(user2).toMatchObject({ + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [DailyCodingChallengeLanguage.javascript] + } + ], + // should not add to progressTimestamps + progressTimestamps: [completedDate] + }); + + // should have correct response + expect(res2.statusCode).toBe(200); + expect(res2.body).toStrictEqual({ + alreadyCompleted: true, + points: 1, + completedDate, + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [DailyCodingChallengeLanguage.javascript] + } + ] + }); + + const res3 = await superPost( + '/daily-coding-challenge-completed' + ).send({ + ...dailyCodingChallengeBody, + language: 'python' + }); + + const user3 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + // should add 'python' to languages + should not update completedDate + expect(user3).toMatchObject({ + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [ + DailyCodingChallengeLanguage.javascript, + DailyCodingChallengeLanguage.python + ] + } + ], + // should not add to progressTimestamps + progressTimestamps: [completedDate] + }); + + // should have correct response + expect(res3.statusCode).toBe(200); + expect(res3.body).toStrictEqual({ + alreadyCompleted: true, + points: 1, + completedDate, + completedDailyCodingChallenges: [ + { + id: dailyCodingChallengeId, + completedDate, + languages: [ + DailyCodingChallengeLanguage.javascript, + DailyCodingChallengeLanguage.python + ] + } + ] + }); + }); + }); + }); + + describe('POST /save-challenge', () => { + describe('validation', () => { + test('returns 400 status for unsavable challenges', async () => { + const response = await superPost('/save-challenge').send({ + savedChallenges: { + // valid mongo id, but not a saveable one + id: 'aaaaaaaaaaaaaaaaaaaaaaa', + files: multiFiles + } + }); + + expect(response.body).toEqual({ + message: 'That does not appear to be a valid challenge submission.', + type: 'error' + }); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + savedChallenges: [] + } + }); + }); + + test('rejects requests for challenges that cannot be saved', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/save-challenge').send({ + id: '66ebd4ae2812430bb883c786', + files: multiFiles + }); + + const { savedChallenges } = + await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + expect(response.statusCode).toBe(400); + expect(response.body).toStrictEqual({ + type: 'error', + message: 'That challenge type is not saveable.' + }); + expect(savedChallenges).toHaveLength(0); + expect(count).toHaveBeenCalledWith('challenge.saved', 1, { + attributes: { result: 'not_saveable' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('update the user savedchallenges and return them', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/save-challenge').send({ + id: multiFileCertProjectId, + files: updatedMultiFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const savedDate = user.savedChallenges[0]?.lastSavedDate; + + expect(user).toMatchObject({ + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: savedDate, + files: updatedMultiFiles + } + ] + }); + expect(response.body).toEqual({ + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: savedDate, + files: updatedMultiFiles + } + ] + }); + expect(response.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('challenge.saved', 1, { + attributes: { result: 'saved' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + }); + + describe('POST /encoded/save-challenge', () => { + test('rejects requests for challenges that cannot be saved', async () => { + const response = await superPost('/encoded/save-challenge').send({ + id: '66ebd4ae2812430bb883c786', + files: encodedUpdatedMultiFiles + }); + + const { savedChallenges } = + await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + expect(response.statusCode).toBe(400); + expect(response.body).toStrictEqual({ + type: 'error', + message: 'That challenge type is not saveable.' + }); + expect(savedChallenges).toHaveLength(0); + }); + + test('update the user savedchallenges and return them', async () => { + const response = await superPost('/encoded/save-challenge').send({ + id: multiFileCertProjectId, + files: encodedUpdatedMultiFiles + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + const savedDate = user.savedChallenges[0]?.lastSavedDate; + + expect(user).toMatchObject({ + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: savedDate, + files: updatedMultiFiles + } + ] + }); + expect(response.body).toEqual({ + savedChallenges: [ + { + id: multiFileCertProjectId, + lastSavedDate: savedDate, + files: updatedMultiFiles + } + ] + }); + expect(response.statusCode).toBe(200); + }); + }); + + describe('GET /exam/:id', () => { + beforeAll(async () => { + await seedExam(); + }); + + describe('validation', () => { + test('GET rejects requests without id param', async () => { + const response = await superGet('/exam/'); + + expect(response.body).toStrictEqual({ + error: `Valid 'id' not found in request parameters.` + }); + expect(response.statusCode).toBe(400); + }); + + test('GET rejects requests when id param is not a 24-character string', async () => { + const response = await superGet('/exam/fake-id'); + + expect(response.body).toStrictEqual({ + error: `Valid 'id' not found in request parameters.` + }); + expect(response.statusCode).toBe(400); + }); + + test('GET rejects requests with non-existent id param', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const response = await superGet('/exam/123412341234123412341234'); + + expect(response.body).toStrictEqual({ + error: 'An error occurred trying to get the exam from the database.' + }); + expect(response.statusCode).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('GET rejects requests where camper has not completed prerequisites', async () => { + const response = await superGet('/exam/647e22d18acb466c97ccbef8'); + + expect(response.body).toStrictEqual({ + error: `You have not completed the required challenges to start the 'Exam Certification'.` + }); + expect(response.statusCode).toBe(403); + }); + }); + + describe('handling', () => { + test('GET returns a generatedExam array with the correct objects', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { completedChallenges: completedTrophyChallenges } + }); + + const response = await superGet('/exam/647e22d18acb466c97ccbef8'); + + expect(response.body).toHaveProperty('generatedExam'); + + const { generatedExam } = response.body; + + expect(Array.isArray(generatedExam)).toBe(true); + expect(generatedExam).toHaveLength(3); + + expect(generatedExam[0]).toHaveProperty('question'); + expect(typeof generatedExam[0].question).toBe('string'); + + expect(generatedExam[0]).toHaveProperty('id'); + expect(typeof generatedExam[0].id).toBe('string'); + + expect(generatedExam[0]).toHaveProperty('answers'); + expect(Array.isArray(generatedExam[0].answers)).toBe(true); + expect(generatedExam[0].answers).toHaveLength(5); + + const answers = generatedExam[0].answers as Answer[]; + + answers.forEach(a => { + expect(a).toHaveProperty('answer'); + expect(typeof a.answer).toBe('string'); + expect(a).toHaveProperty('id'); + expect(typeof a.id).toBe('string'); + }); + + expect(response.statusCode).toBe(200); + }); + + test('GET captures unexpected errors when the generated exam fails validation', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + mockGenerateRandomExam.mockReturnValueOnce( + Array.from({ length: 3 }, (_, i) => ({ + id: 'abcdefghij', + question: `Malformed question ${i}`, + answers: [{ id: 'abcdefghij', answer: 'Only one answer' }] + })) + ); + + const response = await superGet('/exam/647e22d18acb466c97ccbef8'); + + expect(response.body).toStrictEqual({ + error: 'An error occurred trying to randomize the exam.' + }); + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + describe('/ms-trophy-challenge-completed', () => { + const msUserId = 'abc123'; + // Add Logic to C# Console Applications's id: + const trophyChallengeId = '647f882207d29547b3bee1c0'; + // Create and Run Simple C# Console Applications's id: + const trophyChallengeId2 = '647f87dc07d29547b3bee1bf'; + const nonTrophyChallengeId = 'bd7123c8c441eddfaeb5bdef'; + const solutionUrl = `https://learn.microsoft.com/api/achievements/user/${msUserId}`; + + const idIsMissingOrInvalid = { + type: 'error', + message: 'flash.ms.trophy.err-2' + } as const; + const userHasNotLinkedTheirAccount = { + type: 'error', + message: 'flash.ms.trophy.err-1' + } as const; + const unexpectedError = { + type: 'error', + message: 'flash.ms.trophy.err-5' + } as const; + + describe('validation', () => { + test('POST rejects requests without valid ids', async () => { + const resNoId = await superPost('/ms-trophy-challenge-completed'); + + expect(resNoId.body).toStrictEqual(idIsMissingOrInvalid); + expect(resNoId.statusCode).toBe(400); + + const resBadId = await superPost( + '/ms-trophy-challenge-completed' + ).send({ id: nonTrophyChallengeId }); + + expect(resBadId.body).toStrictEqual(idIsMissingOrInvalid); + expect(resBadId.statusCode).toBe(400); + }); + + // TODO(Post-MVP): give a more specific error message + test('POST rejects requests without valid ObjectIDs', async () => { + const response = await superPost( + '/ms-trophy-challenge-completed' + ).send({ id: 'not-a-valid-id' }); + + expect(response.body).toStrictEqual(idIsMissingOrInvalid); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + async function createMSUsernameRecord(msUsername: string) { + await fastifyTestInstance.prisma.msUsername.create({ + data: { + msUsername, + ttl: 123, + userId: defaultUserId + } + }); + } + afterEach(async () => { + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { userId: defaultUserId } + }); + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: defaultUserId }, + data: { + completedChallenges: [], + progressTimestamps: [] + } + }); + }); + + test('POST rejects requests if the user does not have a Microsoft username', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superPost('/ms-trophy-challenge-completed').send({ + id: trophyChallengeId + }); + + expect(res.body).toStrictEqual(userHasNotLinkedTheirAccount); + expect(res.statusCode).toBe(403); + expect(count).toHaveBeenCalledWith( + 'ms_trophy.verify_completed', + 1, + { + attributes: { result: 'no_ms_username' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test("POST rejects requests if Microsoft's api responds with an error", async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const msUsername = 'ANRandom'; + await createMSUsernameRecord(msUsername); + // This can be any error that the route can serialize. Other than + // that, the details do not matter, since whatever + // verifyTrophyWithMicrosoft returns will be returned by the route. + const verifyError = { + type: 'error' as const, + message: 'flash.ms.profile.err' as const, + variables: { + msUsername + } + }; + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => + Promise.resolve(verifyError) + ); + + const res = await superPost('/ms-trophy-challenge-completed').send({ + id: trophyChallengeId + }); + + expect(res.body).toStrictEqual(verifyError); + expect(res.statusCode).toBe(403); + expect(count).toHaveBeenCalledWith( + 'ms_trophy.verify_completed', + 1, + { + attributes: { result: 'verify_failed' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST handles unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const distribution = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, distribution } + }; + + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => { + throw new Error('Network error'); + }); + const msUsername = 'ANRandom'; + await createMSUsernameRecord(msUsername); + + const res = await superPost('/ms-trophy-challenge-completed').send({ + id: trophyChallengeId + }); + + expect(res.body).toStrictEqual(unexpectedError); + expect(res.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(distribution).toHaveBeenCalledWith( + 'ms_trophy.verify_latency_ms', + expect.any(Number), + { unit: 'millisecond', attributes: { result: 'failure' } } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST updates the user record with a new completed challenge', async () => { + const count = vi.fn(); + const distribution = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count, distribution } + }; + + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => + Promise.resolve({ + type: 'success', + msUserAchievementsApiUrl: solutionUrl + }) + ); + const msUsername = 'ANRandom'; + await createMSUsernameRecord(msUsername); + const now = Date.now(); + + const res = await superPost('/ms-trophy-challenge-completed').send({ + id: trophyChallengeId + }); + + const user = + await fastifyTestInstance.prisma.user.findUniqueOrThrow({ + where: { id: defaultUserId } + }); + const completedDate = user.completedChallenges[0]?.completedDate; + + expect(res.body).toStrictEqual({ + alreadyCompleted: false, + points: 1, + completedDate + }); + + expect(completedDate).toBeGreaterThan(now); + expect(completedDate).toBeLessThan(now + 1000); + expect(res.statusCode).toBe(200); + + expect(user).toMatchObject({ + completedChallenges: [ + { + id: trophyChallengeId, + solution: solutionUrl, + completedDate: expect.any(Number) + } + ] + }); + expect(count).toHaveBeenCalledWith( + 'ms_trophy.verify_completed', + 1, + { + attributes: { result: 'verified' } + } + ); + expect(distribution).toHaveBeenCalledWith( + 'ms_trophy.verify_latency_ms', + expect.any(Number), + { unit: 'millisecond', attributes: { result: 'success' } } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST correctly handles multiple requests', async () => { + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => + Promise.resolve({ + type: 'success', + msUserAchievementsApiUrl: solutionUrl + }) + ); + const msUsername = 'ANRandom'; + await createMSUsernameRecord(msUsername); + + const resOne = await superPost( + '/ms-trophy-challenge-completed' + ).send({ id: trophyChallengeId }); + + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => + Promise.resolve({ + type: 'success', + msUserAchievementsApiUrl: solutionUrl + }) + ); + const resTwo = await superPost( + '/ms-trophy-challenge-completed' + ).send({ id: trophyChallengeId2 }); + + // sending the second trophy challenge again should not change + // anything + mockVerifyTrophyWithMicrosoft.mockImplementationOnce(() => + Promise.resolve({ + type: 'success', + msUserAchievementsApiUrl: solutionUrl + }) + ); + const resUpdate = await superPost( + '/ms-trophy-challenge-completed' + ).send({ id: trophyChallengeId2 }); + + const { completedChallenges, progressTimestamps } = + await fastifyTestInstance.prisma.user.findUniqueOrThrow({ + where: { id: defaultUserId } + }); + + expect(completedChallenges).toHaveLength(2); + expect(completedChallenges).toStrictEqual( + expect.arrayContaining([ + expect.objectContaining({ + id: trophyChallengeId, + solution: solutionUrl, + completedDate: resOne.body.completedDate + }), + expect.objectContaining({ + id: trophyChallengeId2, + solution: solutionUrl, + completedDate: resTwo.body.completedDate + }) + ]) + ); + + const expectedProgressTimestamps = completedChallenges.map( + challenge => challenge.completedDate + ); + expect(progressTimestamps).toStrictEqual( + expectedProgressTimestamps + ); + + expect(resUpdate.body).toStrictEqual({ + alreadyCompleted: true, + points: 2, + completedDate: expect.any(Number) + }); + + // If a challenge has already been completed, it should return the + // original completedDate + expect(resUpdate.body.completedDate).toBe( + resTwo.body.completedDate + ); + expect(resUpdate.statusCode).toBe(200); + }); + }); + }); + }); + + describe('/exam-challenge-completed', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: defaultUserId }, + data: { + completedChallenges: [], + completedExams: [], + progressTimestamps: [] + } + }); + }); + + describe('validation', () => { + test('should reject exam submissions', async () => { + const response = await superPost('/exam-challenge-completed').send({ + id: examId, + challengeType: 17, + userCompletedExam: { + examTimeInSeconds: 111, + userExamQuestions: [ + { + id: 'q-id', + question: '?', + answer: { + id: 'a-id', + answer: 'a' + } + } + ] + } + }); + + expect(response.body).toStrictEqual({ + error: 'Exam submissions are not allowed on this endpoint.' + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests with no body', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }); + + expect(response.body).toStrictEqual({ + error: `Valid request body not found in attempt to submit exam.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectID', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ id: 'not-a-valid-id' }); + + expect(response.body).toStrictEqual({ + error: `Valid request body not found in attempt to submit exam.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests with valid, but non existing ID', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: '647e22d18acb466c97ccbef0', + challengeType: 17, + userCompletedExam: { + examTimeInSeconds: 111, + userExamQuestions: [ + { + id: 'q-id', + question: '?', + answer: { + id: 'a-id', + answer: 'a' + } + } + ] + } + }); + + expect(response.body).toStrictEqual({ + error: `An error occurred trying to get the exam from the database.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid userCompletedExam schema', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: '' + }); + + expect(response.body).toStrictEqual({ + error: `Valid request body not found in attempt to submit exam.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid examTimeInSeconds schema', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: { examTimeInSeconds: 'a' } + }); + + expect(response.body).toStrictEqual({ + error: `Valid request body not found in attempt to submit exam.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid userExamQuestions schema', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: { examTimeInSeconds: 11, userExamQuestions: [] } + }); + + expect(response.body).toStrictEqual({ + error: `Valid request body not found in attempt to submit exam.` + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests with prerequisites not completed', async () => { + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: { + examTimeInSeconds: 111, + userExamQuestions: [ + { + id: 'q-id', + question: '?', + answer: { + id: 'a-id', + answer: 'a' + } + } + ] + } + }); + + expect(response.body).toStrictEqual({ + error: `You have not completed the required challenges to start the 'Exam Certification'.` + }); + expect(response.statusCode).toBe(403); + }); + + test('POST rejects requests with invalid userCompletedExam values', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: completedTrophyChallenges + } + }); + + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: { + examTimeInSeconds: 111, + userExamQuestions: [ + { + id: 'q-id', + question: '?', + answer: { + id: 'a-id', + answer: 'a' + } + } + ] + } + }); + + expect(response.body).toStrictEqual({ + error: `An error occurred trying to submit your exam.` + }); + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST captures an exception when the exam from the database fails schema validation', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const examSpy = vi + .spyOn(fastifyTestInstance.prisma.exam, 'findUnique') + .mockResolvedValueOnce({ + ...examJson, + numberOfQuestionsInExam: 999 + } as never); + + const response = await superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: { + examTimeInSeconds: 111, + userExamQuestions: [ + { + id: 'q-id', + question: '?', + answer: { + id: 'a-id', + answer: 'a' + } + } + ] + } + }); + + examSpy.mockRestore(); + + expect(response.body).toStrictEqual({ + error: + 'An error occurred validating the exam information from the database.' + }); + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('handling', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: defaultUserId }, + data: { + completedChallenges: completedTrophyChallenges + } + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: defaultUserId }, + data: { + completedChallenges: [], + completedExams: [], + progressTimestamps: [] + } + }); + }); + + const submitExam = async (exam: ExamSubmission) => { + return superRequest('/exam-challenge-completed', { + method: 'POST', + setCookies + }).send({ + id: examChallengeId, + challengeType: 17, + userCompletedExam: exam + }); + }; + + test('POST handles submitting a failing exam', async () => { + const now = Date.now(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + // Submit exam with 0 correct answers + const response = await submitExam(examWithZeroCorrect); + + type GetSessionUserResponseBody = Static< + (typeof getSessionUser)['response']['200'] + >['user']; + + const res = (await superGet('/user/session-user')).body as { + user: GetSessionUserResponseBody; + }; + + const { completedChallenges, completedExams, calendar } = + res.user[defaultUsername]!; + + // should have the 1 prerequisite challenge + expect(completedChallenges).toHaveLength(1); + expect(completedExams).toHaveLength(1); + expect(calendar).toStrictEqual({}); + expect(completedChallenges).toEqual(completedTrophyChallenges); + expect(completedExams[0]).toEqual({ + id: '647e22d18acb466c97ccbef8', + challengeType: 17, + completedDate: expect.any(Number), + examResults: mockResultsZeroCorrect + }); + + expect(completedExams[0]?.completedDate).toBeGreaterThan(now); + expect(response.body).toMatchObject({ + points: 0, + alreadyCompleted: false, + examResults: mockResultsZeroCorrect + }); + expect(response.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('curriculum_exam.completed', 1, { + attributes: { result: 'failed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test("POST always adds to the user's completedExams", async () => { + let now = Date.now(); + // The first exam should be stored in the user's completedExams + await submitExam(examWithAllCorrect); + + let { completedExams } = + await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { id: defaultUserId } + }); + + expect(completedExams).toHaveLength(1); + expect(completedExams[0]).toEqual(completedExamChallengeAllCorrect); + expect(completedExams[0]?.completedDate).toBeGreaterThan(now); + expect(completedExams[0]?.completedDate).toBeLessThan(Date.now()); + + now = Date.now(); + // the second exam should be added to the exams, not replace the first + await submitExam(examWithOneCorrect); + + completedExams = ( + await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { id: defaultUserId } + }) + ).completedExams; + + expect(completedExams).toHaveLength(2); + expect(completedExams).toEqual( + expect.arrayContaining([ + completedExamChallengeAllCorrect, + completedExamChallengeOneCorrect + ]) + ); + expect(completedExams[1]?.completedDate).toBeGreaterThan(now); + expect(completedExams[1]?.completedDate).toBeLessThan(Date.now()); + }); + + test('POST updates user progress if they have not completed the exam before', async () => { + // Submit exam with 2/3 correct answers + const now = Date.now(); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await submitExam(examWithTwoCorrect); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { id: defaultUserId } + }); + + // should add to completedChallenges + expect(user.completedChallenges).toHaveLength(2); + expect(user.completedChallenges).toMatchObject([ + ...completedTrophyChallenges, + completedExamChallengeTwoCorrect + ]); + expect(user.completedChallenges[1]?.completedDate).toBeGreaterThan( + now + ); + + // should add to progressTimestamps + expect(user.progressTimestamps).toHaveLength(1); + + expect(res.body).toMatchObject({ + points: 1, + alreadyCompleted: false, + examResults: mockResultsTwoCorrect + }); + expect(res.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('curriculum_exam.completed', 1, { + attributes: { result: 'completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST does not update user progress if new exam is not an improvement', async () => { + // Submit exam with 2/3 correct answers + await submitExam(examWithTwoCorrect); + + const user1 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { id: defaultUserId } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + // Submit exam with 2/3 correct answers (no improvement) + const res2 = await submitExam(examWithTwoCorrect); + + const user2 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { id: defaultUserId } + }); + + // should not update user progress + expect(user2.completedChallenges).toEqual(user1.completedChallenges); + expect(user2.progressTimestamps).toEqual(user1.progressTimestamps); + + expect(res2.body).toMatchObject({ + points: 1, + alreadyCompleted: true, + examResults: mockResultsTwoCorrect + }); + expect(res2.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('curriculum_exam.completed', 1, { + attributes: { result: 'already_completed' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST updates user progress if exam is an improvement', async () => { + // Submit exam with 2/3 correct answers + await submitExam(examWithTwoCorrect); + const user1 = await fastifyTestInstance.prisma.user.findUniqueOrThrow( + { + where: { id: defaultUserId } + } + ); + + // Submit improved exam + const res = await submitExam(examWithAllCorrect); + + const user2 = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + // should update existing completedChallenge + expect(user2.completedChallenges).toHaveLength(2); + expect(user2.completedChallenges).toMatchObject([ + ...completedTrophyChallenges, + completedExamChallengeAllCorrect + ]); + expect(user2.completedChallenges[1]?.completedDate).toEqual( + user1.completedChallenges[1]?.completedDate + ); + + // they have not completed anything new, so progressTimestamps should + // remain the same + expect(user2.progressTimestamps).toEqual(user1.progressTimestamps); + + expect(res.body).toMatchObject({ + points: 1, + alreadyCompleted: true, + examResults: mockResultsAllCorrect + }); + expect(res.statusCode).toBe(200); + }); + }); + }); + + describe('/submit-quiz-attempt', () => { + describe('validation', () => { + test('POST rejects requests without challengeId', async () => { + const response = await superPost('/submit-quiz-attempt').send({ + quizId: 'id' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: + 'That does not appear to be a valid quiz attempt submission.' + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without quizId', async () => { + const response = await superPost('/submit-quiz-attempt').send({ + challengeId: '66df3b712c41c499e9d31e5b' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: + 'That does not appear to be a valid quiz attempt submission.' + }); + expect(response.statusCode).toBe(400); + }); + + test('POST rejects requests without valid ObjectID', async () => { + const response = await superPost('/submit-quiz-attempt').send({ + challengeId: 'not-a-valid-id' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: + 'That does not appear to be a valid quiz attempt submission.' + }); + expect(response.statusCode).toBe(400); + }); + }); + + describe('handling', () => { + beforeAll(() => { + vi.useFakeTimers({ + // toFake: ['Date'] + }); + vi.setSystemTime(DATE_NOW); + }); + + afterAll(() => { + vi.useRealTimers(); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: 'foo@bar.com' }, + data: { + completedChallenges: [], + quizAttempts: [] + } + }); + }); + + test('POST adds new attempt to quizAttempts', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/submit-quiz-attempt').send({ + challengeId: '66df3b712c41c499e9d31e5b', + quizId: '0' + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + quizAttempts: [ + { + challengeId: '66df3b712c41c499e9d31e5b', + quizId: '0', + timestamp: DATE_NOW + } + ] + }); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({}); + expect(count).toHaveBeenCalledWith('quiz.attempt_submitted', 1, { + attributes: { result: 'created' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST updates the timestamp of the existing attempt', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { id: defaultUserId }, + data: { + quizAttempts: [ + { + challengeId: '66df3b712c41c499e9d31e5b', // quiz-basic-html + quizId: '0', + timestamp: EXISTING_COMPLETED_DATE + }, + { + challengeId: '66ed903cf45ce3ece4053ebe', // quiz-semantic-html + quizId: '1', + timestamp: EXISTING_COMPLETED_DATE + } + ] + } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/submit-quiz-attempt').send({ + challengeId: '66df3b712c41c499e9d31e5b', + quizId: '1' + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: 'foo@bar.com' } + }); + + expect(user).toMatchObject({ + quizAttempts: [ + { + challengeId: '66df3b712c41c499e9d31e5b', + quizId: '1', + timestamp: DATE_NOW + }, + { + challengeId: '66ed903cf45ce3ece4053ebe', + quizId: '1', + timestamp: EXISTING_COMPLETED_DATE + } + ] + }); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({}); + expect(count).toHaveBeenCalledWith('quiz.attempt_submitted', 1, { + attributes: { result: 'updated' } + }); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + }); + }); + + describe('Unauthenticated user', () => { + let setCookies: string[]; + + // Get the CSRF cookies from an unprotected route + beforeAll(async () => { + const res = await superRequest('/status/ping', { method: 'GET' }); + setCookies = res.get('Set-Cookie'); + }); + + const endpoints: { path: string; method: 'POST' | 'GET' }[] = [ + // { path: '/coderoad-challenge-completed', method: 'POST' }, + { path: '/project-completed', method: 'POST' }, + { path: '/backend-challenge-completed', method: 'POST' }, + { path: '/modern-challenge-completed', method: 'POST' }, + { path: '/daily-coding-challenge-completed', method: 'POST' }, + { path: '/save-challenge', method: 'POST' }, + { path: '/exam/647e22d18acb466c97ccbef8', method: 'GET' }, + { path: '/ms-trophy-challenge-completed', method: 'POST' }, + { path: '/exam-challenge-completed', method: 'POST' } + ]; + + endpoints.forEach(({ path, method }) => { + test(`${method} ${path} returns 401 status code with error message`, async () => { + const response = await superRequest(path, { + method, + setCookies + }); + expect(response.statusCode).toBe(401); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.ts new file mode 100644 index 0000000000000000000000000000000000000000..b11d363ec1480ceb6c8ed6ff71654d952ac3f24f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/challenge.ts @@ -0,0 +1,1387 @@ +import { performance } from 'node:perf_hooks'; + +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import jwt from 'jsonwebtoken'; +import { CompletedExam, ExamResults, SavedChallengeFile } from '@prisma/client'; +import type { FastifyBaseLogger, FastifyInstance, FastifyReply } from 'fastify'; +import { uniqBy, matches } from 'lodash-es'; + +import validator from 'validator'; + +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; +import * as schemas from '../../schemas.js'; +import { + jsCertProjectIds, + multifileCertProjectIds, + multifilePythonCertProjectIds, + updateUserChallengeData, + type CompletedChallenge, + saveUserChallengeData, + msTrophyChallenges +} from '../../utils/common-challenge-functions.js'; +import { JWT_SECRET } from '../../utils/env.js'; +import { + formatCoderoadChallengeCompletedValidation, + formatProjectCompletedValidation +} from '../../utils/error-formatting.js'; +import { + challenges, + savableChallenges, + isExamId +} from '../../utils/get-challenges.js'; +import { ProgressTimestamp, getPoints } from '../../utils/progress.js'; +import { + validateExamFromDbSchema, + validateGeneratedExamSchema, + validateUserCompletedExamSchema, + validateExamResultsSchema +} from '../../utils/exam-schemas.js'; +import { generateRandomExam, createExamResults } from '../../utils/exam.js'; +import { + canSubmitCodeRoadCertProject, + decodeFiles, + verifyTrophyWithMicrosoft +} from '../helpers/challenge-helpers.js'; +import { UpdateReplyType, UpdateReqType } from '../../utils/index.js'; +import { + normalizeChallengeType, + normalizeDate +} from '../../utils/normalize.js'; + +interface JwtPayload { + userToken: string; +} + +// TODO(Post-MVP): This could be narrowed down to only the fields needed by +// specific endpoints, but that means complicating the update helper. +const userChallengeSelect = { + id: true, + completedChallenges: true, + partiallyCompletedChallenges: true, + progressTimestamps: true, + needsModeration: true, + savedChallenges: true +}; + +/** + * Plugin for the challenge submission endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const challengeRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.post( + '/project-completed', + { + schema: schemas.projectCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Project submission validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.info('User submitted a project'); + // TODO: considering validation is determined by `challengeType`, it should not come from the client + // Determine `challengeType` by `id` + const { id: projectId, challengeType, solution, githubLink } = req.body; + const userId = req.user?.id; + + if (isExamId(req.body.id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + } + + // If `backEndProject`: + // - `solution` needs to exist, but does not have to be valid URL + // - `githubLink` needs to exist and be valid URL + if (challengeType === challengeTypes.backEndProject) { + if (!solution || !validator.default.isURL(githubLink + '')) { + req.log.warn( + { + hasSolution: !!solution, + solutionLength: solution.length, + hasGithubLink: !!githubLink, + githubLinkLength: githubLink?.length + }, + 'Invalid backEndProject submission' + ); + return void reply.code(403).send({ + type: 'error', + message: 'That does not appear to be a valid challenge submission.' + }); + } + } else if (solution && !validator.default.isURL(solution + '')) { + req.log.warn( + { hasSolution: !!solution, solutionLength: solution.length }, + 'Invalid solution URL' + ); + return void reply.code(403).send({ + type: 'error', + message: 'That does not appear to be a valid challenge submission.' + }); + } + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: userId }, + select: userChallengeSelect + }); + + if ( + (challengeType === challengeTypes.codeAllyCert || + challengeType === challengeTypes.freeCodeCampOsCert) && + !canSubmitCodeRoadCertProject(projectId, user) + ) { + req.log.warn( + { projectId }, + 'User tried to submit a codeRoad cert project before completing the required challenges' + ); + void reply.code(403); + return reply.send({ + type: 'error', + message: + 'You have to complete the project before you can submit a URL.' + }); + } + const challenge = { + challengeType, + solution, + githubLink, + id: projectId, + completedDate: Date.now() + }; + const progressTimestamps = user.progressTimestamps as ProgressTimestamp[]; + const points = getPoints(progressTimestamps); + + const { alreadyCompleted, completedDate } = await updateUserChallengeData( + fastify, + user, + projectId, + challenge + ); + + fastify.Sentry?.metrics?.count('challenge.completed', 1, { + attributes: { + result: alreadyCompleted ? 'already_completed' : 'completed' + } + }); + + reply.send({ + alreadyCompleted, + // TODO(Post-MVP): audit the client and remove this if the client does + // not use it. + completedDate: normalizeDate(completedDate), + points: alreadyCompleted ? points : points + 1 + }); + } + ); + + fastify.post( + '/backend-challenge-completed', + { + schema: schemas.backendChallengeCompleted, + errorHandler(error, request, reply) { + if (error.validation) { + request.log.warn( + { validationError: error.validation }, + 'Backend challenge submission validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + req.log.info('User submitted a backend challenge'); + + if (isExamId(req.body.id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + } + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + + select: userChallengeSelect + }); + const progressTimestamps = user.progressTimestamps as + | ProgressTimestamp[] + | null; + const points = getPoints(progressTimestamps); + + const completedChallenge = { + completedDate: Date.now(), + ...req.body + }; + + const { alreadyCompleted } = await updateUserChallengeData( + fastify, + user, + req.body.id, + completedChallenge + ); + + fastify.Sentry?.metrics?.count('challenge.completed', 1, { + attributes: { + result: alreadyCompleted ? 'already_completed' : 'completed' + } + }); + + return { + alreadyCompleted, + points: alreadyCompleted ? points : points + 1, + completedDate: completedChallenge.completedDate + }; + } + ); + + fastify.post( + '/modern-challenge-completed', + { + schema: schemas.modernChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + // This is another highly used route, so debug log level is used to + // avoid excessive logging + req.log.debug( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + // This is another highly used route, so debug log level is used to + // avoid excessive logging + req.log.debug('User submitted a modern challenge'); + + const { id, files, challengeType } = req.body; + + if (isExamId(id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + } + + return await postModernChallengeCompleted(fastify, { + id, + files, + challengeType, + userId: req.user!.id + }); + } + ); + + fastify.post( + '/encoded/modern-challenge-completed', + { + schema: schemas.modernChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + // This is another highly used route, so debug log level is used to + // avoid excessive logging + req.log.debug( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + // This is another highly used route, so debug log level is used to + // avoid excessive logging + req.log.debug('User submitted a modern challenge'); + + const { id, files: encodedFiles, challengeType } = req.body; + + if (isExamId(id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + } + + const files = encodedFiles ? decodeFiles(encodedFiles) : undefined; + return await postModernChallengeCompleted(fastify, { + id, + files, + challengeType, + userId: req.user!.id + }); + } + ); + + fastify.post( + '/daily-coding-challenge-completed', + { + schema: schemas.dailyCodingChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + void reply.send({ + type: 'error', + message: 'That does not appear to be a valid challenge submission.' + }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + postDailyCodingChallengeCompleted + ); + + fastify.post( + '/save-challenge', + { + schema: schemas.saveChallenge, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.debug('User saved a challenge'); + + const { files, id: challengeId } = req.body; + await postSaveChallenge( + fastify, + { challengeId, files, userId: req.user!.id }, + req.log, + reply + ); + } + ); + + fastify.post( + '/encoded/save-challenge', + { + schema: schemas.saveChallenge, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return formatProjectCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.debug('User saved a challenge'); + + const { files: encodedFiles, id: challengeId } = req.body; + const files = decodeFiles(encodedFiles); + await postSaveChallenge( + fastify, + { challengeId, files, userId: req.user!.id }, + req.log, + reply + ); + } + ); + + fastify.get( + '/exam/:id', + { + schema: schemas.exam, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return { error: `Valid 'id' not found in request parameters.` }; + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.info({ examId: req.params.id }, 'User requested an exam'); + + const { id } = req.params; + + const { completedChallenges } = + await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + select: { completedChallenges: true } + }); + + const examFromDb = await fastify.prisma.exam.findUnique({ + where: { id } + }); + + if (!examFromDb) { + req.log.warn( + { examId: id }, + 'User requested an exam that does not exist' + ); + void reply.code(500); + return { + error: 'An error occurred trying to get the exam from the database.' + }; + } + + const validExamFromDbSchema = validateExamFromDbSchema(examFromDb); + + if ('error' in validExamFromDbSchema) { + req.log.error( + { examId: id, validationError: validExamFromDbSchema.error }, + 'Error validating exam from database' + ); + fastify.Sentry?.captureException( + new Error(`Exam ${id} failed database schema validation`) + ); + void reply.code(500); + return { + error: + 'An error occurred validating the exam information from the database.' + }; + } + + const { prerequisites, numberOfQuestionsInExam, title } = examFromDb; + + // Validate User has completed prerequisite challenges + const prerequisiteIds = prerequisites.map(p => p.id); + const completedPrerequisites = completedChallenges.filter(c => + prerequisiteIds.includes(c.id) + ); + + if (completedPrerequisites.length !== prerequisiteIds.length) { + req.log.warn( + { examId: id, prerequisites, completedPrerequisites }, + 'User has not completed all prerequisites for exam' + ); + void reply.code(403); + return { + error: `You have not completed the required challenges to start the '${title}'.` + }; + } + + const randomizedExam = generateRandomExam(examFromDb); + const validGeneratedExamSchema = validateGeneratedExamSchema( + randomizedExam, + numberOfQuestionsInExam + ); + + if (validGeneratedExamSchema.error) { + req.log.error( + validGeneratedExamSchema.error, + 'Error validating generated exam' + ); + fastify.Sentry?.captureException(validGeneratedExamSchema.error); + void reply.code(500); + return { error: 'An error occurred trying to randomize the exam.' }; + } + + return { + generatedExam: randomizedExam + }; + } + ); + + fastify.post( + '/ms-trophy-challenge-completed', + { + schema: schemas.msTrophyChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + void reply.send({ type: 'error', message: 'flash.ms.trophy.err-2' }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.info('User submitted a Microsoft trophy challenge'); + try { + const challengeId = req.body.id; + const challenge = msTrophyChallenges.find( + challenge => challenge.id === challengeId + ); + + if (!challenge) { + req.log.warn( + { challengeId }, + 'User tried to submit a Microsoft trophy challenge that does not exist' + ); + return reply + .code(400) + .send({ type: 'error', message: 'flash.ms.trophy.err-2' }); + } + + const msUser = await fastify.prisma.msUsername.findFirst({ + where: { userId: req.user?.id } + }); + + if (!msUser || !msUser.msUsername) { + req.log.warn( + { hasMsUser: !!msUser }, + 'User tried to submit a Microsoft trophy challenge without a Microsoft username' + ); + fastify.Sentry?.metrics?.count('ms_trophy.verify_completed', 1, { + attributes: { result: 'no_ms_username' } + }); + return reply + .code(403) + .send({ type: 'error', message: 'flash.ms.trophy.err-1' }); + } + + const { msUsername } = msUser; + + // TODO: log error if msTrophyId not found? + const msTrophyId = challenge.msTrophyId ?? ''; + + const verifyTrophyStart = performance.now(); + let msTrophyStatus; + try { + msTrophyStatus = await verifyTrophyWithMicrosoft({ + msUsername, + msTrophyId + }); + fastify.Sentry?.metrics?.distribution( + 'ms_trophy.verify_latency_ms', + performance.now() - verifyTrophyStart, + { unit: 'millisecond', attributes: { result: 'success' } } + ); + } catch (verifyError) { + fastify.Sentry?.metrics?.distribution( + 'ms_trophy.verify_latency_ms', + performance.now() - verifyTrophyStart, + { unit: 'millisecond', attributes: { result: 'failure' } } + ); + throw verifyError; + } + + if (msTrophyStatus.type === 'error') { + req.log.warn('Error verifying trophy with Microsoft'); + fastify.Sentry?.metrics?.count('ms_trophy.verify_completed', 1, { + attributes: { result: 'verify_failed' } + }); + return reply.code(403).send(msTrophyStatus); + } + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + select: userChallengeSelect + }); + + const progressTimestamps = + user.progressTimestamps as ProgressTimestamp[]; + + const completedChallenge = { + id: challengeId, + solution: msTrophyStatus.msUserAchievementsApiUrl, + completedDate: Date.now() + }; + + const { alreadyCompleted, completedDate } = + await updateUserChallengeData( + fastify, + user, + challengeId, + completedChallenge + ); + + fastify.Sentry?.metrics?.count('ms_trophy.verify_completed', 1, { + attributes: { + result: alreadyCompleted ? 'already_claimed' : 'verified' + } + }); + + reply.send({ + alreadyCompleted, + points: getPoints(progressTimestamps) + (alreadyCompleted ? 0 : 1), + completedDate: normalizeDate(completedDate) + }); + } catch (error) { + fastify.Sentry?.captureException(error); + req.log.error(error, 'Error submitting Microsoft trophy challenge'); + void reply.code(500); + return { + type: 'error', + message: 'flash.ms.trophy.err-5' + } as const; + } + } + ); + + fastify.post( + '/exam-challenge-completed', + { + schema: schemas.examChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + void reply.send({ + error: 'Valid request body not found in attempt to submit exam.' + }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.info('User submitted an exam challenge'); + + try { + const userId = req.user?.id; + const { userCompletedExam, id, challengeType } = req.body; + + if (isExamId(id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + error: 'Exam submissions are not allowed on this endpoint.' + }); + } + + const { completedChallenges, completedExams, progressTimestamps } = + await fastify.prisma.user.findUniqueOrThrow({ + where: { id: userId }, + select: { + completedChallenges: true, + completedExams: true, + progressTimestamps: true + } + }); + + const examFromDb = await fastify.prisma.exam.findUnique({ + where: { id } + }); + + if (!examFromDb) { + req.log.warn( + { examId: id }, + 'User tried to submit an exam that does not exist' + ); + void reply.code(400); + return { + error: 'An error occurred trying to get the exam from the database.' + }; + } + + const validExamFromDbSchema = validateExamFromDbSchema(examFromDb); + if ('error' in validExamFromDbSchema) { + req.log.error( + { examId: id, validationError: validExamFromDbSchema.error }, + 'Error validating exam from database' + ); + fastify.Sentry?.captureException( + new Error(`Exam ${id} failed database schema validation`) + ); + void reply.code(500); + return { + error: + 'An error occurred validating the exam information from the database.' + }; + } + + const { prerequisites, numberOfQuestionsInExam, title } = examFromDb; + + const prerequisiteIds = prerequisites.map(p => p.id); + const completedPrerequisites = completedChallenges.filter(c => + prerequisiteIds.includes(c.id) + ); + + if (completedPrerequisites.length !== prerequisiteIds.length) { + req.log.warn( + { examId: id, prerequisites, completedPrerequisites }, + 'User has not completed all prerequisites for exam' + ); + void reply.code(403); + return { + error: `You have not completed the required challenges to start the '${title}'.` + }; + } + + const validUserCompletedExam = validateUserCompletedExamSchema( + userCompletedExam, + numberOfQuestionsInExam + ); + if ('error' in validUserCompletedExam) { + req.log.warn( + { validationError: validUserCompletedExam.error }, + 'Error validating submitted exam' + ); + void reply.code(400); + return { + error: 'An error occurred validating the submitted exam.' + }; + } + + const examResults = createExamResults(userCompletedExam, examFromDb); + + const validExamResults = validateExamResultsSchema(examResults); + if ('error' in validExamResults) { + req.log.error( + validExamResults.error, + 'Error validating generated exam results' + ); + fastify.Sentry?.captureException(validExamResults.error); + void reply.code(500); + return { + error: 'An error occurred validating the submitted exam.' + }; + } + + const newCompletedChallenges: CompletedChallenge[] = + completedChallenges.map(c => { + const { completedDate, challengeType, ...rest } = c; + + return { + completedDate: normalizeDate(completedDate), + challengeType: normalizeChallengeType(challengeType), + ...rest + }; + }); + const newCompletedExams: CompletedExam[] = completedExams; + const newProgressTimeStamps = progressTimestamps as ProgressTimestamp[]; + const completedDate = Date.now(); + + const newCompletedChallenge = { + id, + challengeType, + completedDate, + examResults + }; + + // Always push to completedExams[] to keep a record of all exams taken. + newCompletedExams.push(newCompletedChallenge); + + let addPoint = false; + + const alreadyCompletedIndex = completedChallenges.findIndex( + c => c.id === id + ); + + const alreadyCompleted = alreadyCompletedIndex >= 0; + + if (examResults.passed) { + if (alreadyCompleted) { + const { percentCorrect } = examResults; + const oldChallenge = completedChallenges[ + alreadyCompletedIndex + ] as CompletedChallenge; + const oldResults = oldChallenge?.examResults as ExamResults; + + // only update if it's a better result + if (percentCorrect > oldResults.percentCorrect) { + const updatedChallenge = { + id, + challengeType: oldChallenge.challengeType, + completedDate: oldChallenge.completedDate, + examResults + }; + + newCompletedChallenges[alreadyCompletedIndex] = updatedChallenge; + + // TODO(Post-MVP): Try to DRY the updates. + // updateUserChallengeData, for all its faults, handles the + // update/insert logic well. + await fastify.prisma.user.update({ + where: { id: userId }, + data: { + completedExams: newCompletedExams, + completedChallenges: newCompletedChallenges + } + }); + } else { + await fastify.prisma.user.update({ + where: { id: userId }, + data: { + completedExams: newCompletedExams + } + }); + } + + // not already completed, push to completedChallenges + } else { + addPoint = true; + newCompletedChallenges.push(newCompletedChallenge); + + await fastify.prisma.user.update({ + where: { id: userId }, + data: { + completedExams: newCompletedExams, + completedChallenges: newCompletedChallenges, + progressTimestamps: [ + ...newProgressTimeStamps, + newCompletedChallenge.completedDate + ] + } + }); + } + + // exam not passed + } else { + await fastify.prisma.user.update({ + where: { id: userId }, + data: { + completedExams: newCompletedExams + } + }); + } + + const points = getPoints(newProgressTimeStamps); + + fastify.Sentry?.metrics?.count('curriculum_exam.completed', 1, { + attributes: { + result: !examResults.passed + ? 'failed' + : alreadyCompleted + ? 'already_completed' + : 'completed' + } + }); + + return { + alreadyCompleted, + points: addPoint ? points + 1 : points, + completedDate, + examResults + }; + } catch (error) { + fastify.Sentry?.captureException(error); + req.log.error(error, 'Error submitting exam challenge'); + void reply.code(500); + return { + error: 'An error occurred trying to submit your exam.' + }; + } + } + ); + + fastify.post( + '/submit-quiz-attempt', + { + schema: schemas.submitQuizAttempt, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + void reply.send({ + type: 'error', + message: + 'That does not appear to be a valid quiz attempt submission.' + }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async req => { + const { challengeId, quizId } = req.body; + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + select: { + id: true, + quizAttempts: true + } + }); + + const existingAttempt = user.quizAttempts.find(matches({ challengeId })); + + const newAttempt = { + challengeId, + quizId, + timestamp: Date.now() + }; + + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + quizAttempts: existingAttempt + ? { + updateMany: { where: { challengeId }, data: newAttempt } + } + : { push: newAttempt } + } + }); + + fastify.Sentry?.metrics?.count('quiz.attempt_submitted', 1, { + attributes: { result: existingAttempt ? 'updated' : 'created' } + }); + + return {}; + } + ); + + done(); +}; + +/** + * Plugin for challenge submissions behind AuthZ, not AuthN. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const challengeTokenRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.post( + '/coderoad-challenge-completed', + { + schema: schemas.coderoadChallengeCompleted, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + return formatCoderoadChallengeCompletedValidation(error.validation); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + postCoderoadChallengeCompleted + ); + + done(); +}; + +async function postCoderoadChallengeCompleted( + this: FastifyInstance, + req: UpdateReqType, + reply: UpdateReplyType +) { + req.log.info('User submitted a coderoad challenge'); + + const { 'coderoad-user-token': encodedUserToken } = req.headers; + const { tutorialId } = req.body; + + let userToken; + try { + const payload = jwt.verify(encodedUserToken, JWT_SECRET) as JwtPayload; + userToken = payload.userToken; + if (!userToken || typeof userToken !== 'string') throw Error(); + } catch { + req.log.warn('Invalid user token'); + void reply.code(401); + this.Sentry?.metrics?.count('coderoad.request_rejected', 1, { + attributes: { reason: 'invalid_token' } + }); + return reply.send({ type: 'error', msg: `invalid user token` }); + } + + const tutorialRepo = tutorialId.split(':')[0]; + const tutorialOrg = tutorialRepo?.split('/')?.[0]; + + if (tutorialOrg !== 'freeCodeCamp') { + req.log.warn( + { tutorialId }, + 'Tutorial not hosted on freeCodeCamp GitHub account' + ); + void reply.code(400); + this.Sentry?.metrics?.count('coderoad.request_rejected', 1, { + attributes: { reason: 'untrusted_org' } + }); + return reply.send({ + type: 'error', + msg: `Tutorial not hosted on freeCodeCamp GitHub account` + }); + } + + const codeRoadChallenges = challenges.filter( + ({ challengeType }) => + challengeType === challengeTypes.codeAllyPractice || + challengeType === challengeTypes.codeAllyCert || + challengeType === challengeTypes.freeCodeCampOsPractice || + challengeType === challengeTypes.freeCodeCampOsCert + ); + + const challenge = codeRoadChallenges.find(challenge => { + return tutorialRepo && challenge.url?.endsWith(tutorialRepo); + }); + + if (!challenge) { + req.log.warn({ tutorialRepo }, 'Tutorial repo is not valid'); + void reply.code(404); + this.Sentry?.metrics?.count('coderoad.request_rejected', 1, { + attributes: { reason: 'invalid_tutorial' } + }); + return reply.send({ type: 'error', msg: 'Tutorial name is not valid' }); + } + + const { id: challengeId, challengeType } = challenge; + try { + const tokenInfo = await this.prisma.userToken.findUnique({ + where: { id: userToken } + }); + + if (!tokenInfo) { + req.log.warn('User token not found'); + void reply.code(401); + this.Sentry?.metrics?.count('coderoad.request_rejected', 1, { + attributes: { reason: 'token_not_found' } + }); + return reply.send({ type: 'error', msg: 'User token not found' }); + } + + const { userId } = tokenInfo; + + const user = await this.prisma.user.findFirst({ + where: { id: userId } + }); + + if (!user) { + req.log.warn('User not found'); + void reply.code(401); + this.Sentry?.metrics?.count('coderoad.request_rejected', 1, { + attributes: { reason: 'user_not_found' } + }); + return { + type: 'error', + msg: 'User for user token not found' + } as const; + } + + const completedDate = Date.now(); + const { completedChallenges = [], partiallyCompletedChallenges = [] } = + user; + + const isCompleted = completedChallenges.some( + challenge => challenge.id === challengeId + ); + + if ( + (challengeType === challengeTypes.codeAllyCert || + challengeType === challengeTypes.freeCodeCampOsCert) && + !isCompleted + ) { + const finalChallenge = { + id: challengeId, + completedDate + }; + + await this.prisma.user.update({ + where: { id: userId }, + data: { + partiallyCompletedChallenges: uniqBy( + [finalChallenge, ...partiallyCompletedChallenges], + 'id' + ) + } + }); + + this.Sentry?.metrics?.count('coderoad.challenge_completed', 1, { + attributes: { result: 'partial' } + }); + } else { + await updateUserChallengeData(this, user, challengeId, { + id: challengeId, + completedDate + }); + + this.Sentry?.metrics?.count('coderoad.challenge_completed', 1, { + attributes: { result: 'completed' } + }); + } + } catch (error) { + this.Sentry?.captureException(error); + req.log.error(error, 'Error submitting coderoad challenge'); + void reply.code(500); + return reply.send({ + type: 'error', + msg: 'An error occurred trying to submit the challenge' + }); + } + reply.send({ + type: 'success', + msg: 'Successfully submitted challenge' + }); +} + +async function postDailyCodingChallengeCompleted( + this: FastifyInstance, + req: UpdateReqType, + reply: UpdateReplyType +) { + req.log.info('User submitted a daily coding challenge'); + + const { id, language } = req.body; + + if (isExamId(id)) { + req.log.warn('User attempted to submit an exam'); + void reply.code(403); + return reply.send({ + type: 'error', + message: 'Exam submissions are not allowed on this endpoint.' + }); + } + + const user = await this.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + select: { + completedDailyCodingChallenges: true, + progressTimestamps: true + } + }); + + const { completedDailyCodingChallenges, progressTimestamps = [] } = user; + + const points = getPoints(progressTimestamps as ProgressTimestamp[]); + const oldCompletedChallenge = completedDailyCodingChallenges.find( + c => c.id === id + ); + + const alreadyCompleted = !!oldCompletedChallenge; + const languageAlreadyCompleted = + oldCompletedChallenge?.languages.includes(language); + + if (alreadyCompleted) { + const { completedDate, languages } = oldCompletedChallenge; + + if (languageAlreadyCompleted) { + // alreadyCompleted && languageAlreadyCompleted, no need to change anything in the database + return reply.send({ + alreadyCompleted, + points, + completedDate, + completedDailyCodingChallenges + }); + } else { + // alreadyCompleted && !languageAlreadyCompleted, add the language to the record + const { completedDailyCodingChallenges } = await this.prisma.user.update({ + where: { id: req.user?.id }, + select: { + completedDailyCodingChallenges: true + }, + data: { + completedDailyCodingChallenges: { + updateMany: { + where: { id }, + data: { + languages: [...new Set([...languages, language])] + } + } + } + } + }); + return reply.send({ + alreadyCompleted, + points, + completedDate, + completedDailyCodingChallenges + }); + } + } else { + // !alreadyCompleted, add new record for completed challenge + const newCompletedDate = Date.now(); + + const newCompletedChallenge = { + id, + completedDate: newCompletedDate, + languages: [language] + }; + + const newCompletedChallenges = [ + ...completedDailyCodingChallenges, + newCompletedChallenge + ]; + + const newProgressTimestamps = Array.isArray(progressTimestamps) + ? [...progressTimestamps, newCompletedDate] + : [newCompletedDate]; + + await this.prisma.user.update({ + where: { id: req.user?.id }, + data: { + completedDailyCodingChallenges: newCompletedChallenges, + progressTimestamps: newProgressTimestamps + } + }); + return reply.send({ + alreadyCompleted, + points: points + 1, + completedDate: newCompletedDate, + completedDailyCodingChallenges: newCompletedChallenges + }); + } +} + +async function postSaveChallenge( + fastify: FastifyInstance, + { + challengeId, + userId, + files + }: { + challengeId: string; + userId: string; + files: SavedChallengeFile[]; + }, + logger: FastifyBaseLogger, + reply: FastifyReply +) { + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: userId } + }); + const challenge = { + id: challengeId, + files + }; + + if (!savableChallenges.has(challengeId)) { + logger.warn( + { + challengeId + }, + 'User tried to save a challenge that is not saveable' + ); + fastify.Sentry?.metrics?.count('challenge.saved', 1, { + attributes: { result: 'not_saveable' } + }); + return void reply.code(400).send({ + type: 'error', + message: 'That challenge type is not saveable.' + }); + } + + const userSavedChallenges = saveUserChallengeData( + challengeId, + user.savedChallenges, + challenge + ); + + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + savedChallenges: userSavedChallenges + } + }); + + fastify.Sentry?.metrics?.count('challenge.saved', 1, { + attributes: { result: 'saved' } + }); + + void reply.send({ savedChallenges: userSavedChallenges }); +} + +async function postModernChallengeCompleted( + fastify: FastifyInstance, + { + id, + userId, + challengeType, + files + }: { + id: string; + userId: string; + challengeType: number; + files: CompletedChallenge['files']; + } +) { + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: userId }, + select: userChallengeSelect + }); + const RawProgressTimestamp = user.progressTimestamps as + | ProgressTimestamp[] + | null; + const points = getPoints(RawProgressTimestamp); + + const completedChallenge: CompletedChallenge = { + id, + files, + completedDate: Date.now() + }; + + if (challengeType === challengeTypes.multifileCertProject) { + completedChallenge.isManuallyApproved = false; + user.needsModeration = true; + } + + if ( + jsCertProjectIds.includes(id) || + multifileCertProjectIds.includes(id) || + multifilePythonCertProjectIds.includes(id) + ) { + completedChallenge.challengeType = challengeType; + } + + const { alreadyCompleted, userSavedChallenges: savedChallenges } = + await updateUserChallengeData(fastify, user, id, completedChallenge); + + fastify.Sentry?.metrics?.count('challenge.completed', 1, { + attributes: { + result: alreadyCompleted ? 'already_completed' : 'completed' + } + }); + + return { + alreadyCompleted, + points: alreadyCompleted ? points : points + 1, + completedDate: completedChallenge.completedDate, + savedChallenges + }; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..b19155f0adb06a49eb2e11188ec17f7d8f851b2f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.test.ts @@ -0,0 +1,679 @@ +import { describe, test, expect, beforeEach, vi } from 'vitest'; +import Stripe from 'stripe'; +import { + createSuperRequest, + devLogin, + setupServer, + defaultUserEmail, + defaultUserId +} from '../../../vitest.utils.js'; +import { createUserInput } from '../../utils/create-user.js'; + +const testEWalletEmail = 'baz@bar.com'; +const testSubscriptionId = 'sub_test_id'; +const testCustomerId = 'cust_test_id'; +const userWithoutProgress = createUserInput(defaultUserEmail); +const userWithProgress = { + ...createUserInput(defaultUserEmail), + completedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + solution: null, + challengeType: 5 + }, + { + id: '33b0bb188d873cb2c8729433', + completedDate: 4420002973122, + solution: null, + challengeType: 5 + }, + { + id: 'a5229172f011153519423690', + completedDate: 1520440323273, + solution: null, + challengeType: 5 + }, + { + id: 'a5229172f011153519423692', + completedDate: 1520440323274, + githubLink: '', + challengeType: 5 + } + ] +}; +const donationMock = { + endDate: null, + startDate: { + date: '2024-07-17T10:20:56.076Z', + when: '2024-07-17T10:20:56.076+00:00' + }, + id: '66979a414748aa2f3ba36d41', + amount: 500, + customerId: 'cust_test_id', + duration: 'month', + email: 'foo@bar.com', + provider: 'stripe', + subscriptionId: 'sub_test_id', + userId: defaultUserId +}; +const sharedDonationReqBody = { + amount: 500, + duration: 'month' +}; +const chargeStripeReqBody = { + email: testEWalletEmail, + subscriptionId: 'sub_test_id', + ...sharedDonationReqBody +}; +const chargeStripeCardReqBody = { + paymentMethodId: 'UID', + ...sharedDonationReqBody +}; +const createStripePaymentIntentReqBody = { + email: testEWalletEmail, + name: 'Baz Bar', + token: { id: 'tok_123' }, + ...sharedDonationReqBody +}; +const mockSubCreate = vi.fn(); +const mockAttachPaymentMethod = vi.fn(() => + Promise.resolve({ + id: 'pm_1MqLiJLkdIwHu7ixUEgbFdYF', + object: 'payment_method' + }) +); +const mockCustomerCreate = vi.fn(() => + Promise.resolve({ + id: testCustomerId, + name: 'Jest_User', + currency: 'sgd', + description: 'Jest User Account created' + }) +); +const mockSubRetrieveObj = { + id: testSubscriptionId, + items: { + data: [ + { + plan: { + product: 'prod_GD1GGbJsqQaupl' + } + } + ] + }, + // 1 Jan 2040 + current_period_start: Math.floor(Date.now() / 1000), + customer: testCustomerId, + status: 'active' +}; +const mockSubRetrieve = vi.fn(() => Promise.resolve(mockSubRetrieveObj)); +const mockCheckoutSessionCreate = vi.fn(() => + Promise.resolve({ id: 'checkout_session_id' }) +); +const mockCustomerUpdate = vi.fn(); +const generateMockSubCreate = (status: string) => () => + Promise.resolve({ + id: testSubscriptionId, + latest_invoice: { + payment_intent: { + client_secret: 'superSecret', + status + } + } + }); +const defaultError = () => + Promise.reject(new Error('Stripe encountered an error')); + +const { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError +} = vi.hoisted(() => { + class StripeError extends Error {} + class StripeCardError extends StripeError {} + class StripeInvalidRequestError extends StripeError {} + class StripeAuthenticationError extends StripeError {} + return { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError + }; +}); + +vi.mock('stripe', () => ({ + default: class { + static errors = { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError + }; + + constructor() {} + + customers = { + create: mockCustomerCreate, + update: mockCustomerUpdate + }; + + paymentMethods = { + attach: mockAttachPaymentMethod + }; + + subscriptions = { + create: mockSubCreate, + retrieve: mockSubRetrieve + }; + + checkout = { + sessions: { + create: mockCheckoutSessionCreate + } + }; + } +})); + +describe('Donate', () => { + let setCookies: string[]; + setupServer(); + describe('Authenticated User', () => { + let superPost: ReturnType; + let superPut: ReturnType; + const verifyUpdatedUserAndNewDonation = async (email: string) => { + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email } + }); + const donations = await fastifyTestInstance.prisma.donation.findMany({ + where: { userId: user?.id } + }); + const donation = donations[0]; + expect(donations.length).toBe(1); + expect(donation?.amount).toBe(sharedDonationReqBody.amount); + expect(donation?.duration).toBe(sharedDonationReqBody.duration); + expect(typeof donation?.subscriptionId).toBe('string'); + expect(donation?.customerId).toBe(testCustomerId); + expect(donation?.provider).toBe('stripe'); + }; + const verifyNoUpdatedUserAndNoNewDonation = async (email: string) => { + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email } + }); + const donations = await fastifyTestInstance.prisma.donation.findMany({}); + expect(user?.isDonating).toBe(false); + expect(donations.length).toBe(0); + }; + const verifyNoNewUserAndNoNewDonation = async () => { + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testEWalletEmail } + }); + const donations = await fastifyTestInstance.prisma.donation.findMany({}); + expect(user).toBe(null); + expect(donations.length).toBe(0); + }; + + beforeEach(async () => { + setCookies = await devLogin(); + superPost = createSuperRequest({ method: 'POST', setCookies }); + superPut = createSuperRequest({ method: 'PUT', setCookies }); + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: userWithProgress.email }, + data: userWithProgress + }); + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: testEWalletEmail } + }); + await fastifyTestInstance.prisma.donation.deleteMany({}); + }); + + describe('POST /donate/charge-stripe-card', () => { + test('should return 200 and update the user', async () => { + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('we only care about specific error cases') + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + await verifyUpdatedUserAndNewDonation(userWithProgress.email); + expect(response.body).toEqual({ isDonating: true, type: 'success' }); + expect(response.status).toBe(200); + }); + + test('should return 402 with client_secret if subscription status requires source action', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('requires_source_action') + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + await verifyNoUpdatedUserAndNoNewDonation(userWithProgress.email); + expect(response.body).toEqual({ + error: { + type: 'UserActionRequired', + message: 'Payment requires user action', + client_secret: 'superSecret' + } + }); + expect(response.status).toBe(402); + expect(count).toHaveBeenCalledWith('donation.action_required', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 402 if subscription status requires source', async () => { + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('requires_source') + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + await verifyNoUpdatedUserAndNoNewDonation(userWithProgress.email); + expect(response.body).toEqual({ + error: { + type: 'PaymentMethodRequired', + message: 'Card has been declined' + } + }); + expect(response.status).toBe(402); + }); + + test('should return 409 if the user is already donating', async () => { + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('still does not matter') + ); + const successResponse = await superPost( + '/donate/charge-stripe-card' + ).send(chargeStripeCardReqBody); + const failResponse = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + + //Verify that only the first call changed the DB + await verifyUpdatedUserAndNewDonation(userWithProgress.email); + expect(successResponse.status).toBe(200); + expect(failResponse.body).toEqual({ + error: { + type: 'AlreadyDonatingError', + message: 'User is already donating.' + } + }); + expect(failResponse.status).toBe(409); + }); + + test('should return 400 if the user has no email', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: userWithProgress.email }, + data: { email: null } + }); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + expect(response.body).toEqual({ + error: { + type: 'EmailRequiredError', + message: 'User has not provided an email address' + } + }); + expect(response.status).toBe(400); + }); + + test('should return 500 if Stripe encountes an error', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + mockSubCreate.mockImplementationOnce(defaultError); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + await verifyNoUpdatedUserAndNoNewDonation(userWithProgress.email); + expect(response.status).toBe(500); + expect(response.body).toEqual({ + error: 'Donation failed due to a server error.' + }); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should not capture Stripe card decline errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const CardError = Stripe.errors.StripeCardError as unknown as new ( + m?: string + ) => Error; + mockSubCreate.mockImplementationOnce(() => + Promise.reject(new CardError('card_declined')) + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + + expect(response.status).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should not capture Stripe invalid request errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const InvalidRequestError = Stripe.errors + .StripeInvalidRequestError as unknown as new (m?: string) => Error; + mockSubCreate.mockImplementationOnce(() => + Promise.reject(new InvalidRequestError('invalid_request')) + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + + expect(response.status).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should capture Stripe infra errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const AuthError = Stripe.errors + .StripeAuthenticationError as unknown as new (m?: string) => Error; + mockSubCreate.mockImplementationOnce(() => + Promise.reject(new AuthError('invalid api key')) + ); + const response = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return 400 if user has not completed challenges', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: userWithProgress.email }, + data: userWithoutProgress + }); + const failResponse = await superPost('/donate/charge-stripe-card').send( + chargeStripeCardReqBody + ); + await verifyNoUpdatedUserAndNoNewDonation(userWithProgress.email); + expect(failResponse.body).toEqual({ + error: { + type: 'MethodRestrictionError', + message: `Donate using another method` + } + }); + expect(failResponse.status).toBe(400); + }); + }); + + describe('POST /donate/add-donation', () => { + test('should return 200 and update the user', async () => { + const response = await superPost('/donate/add-donation').send({ + anything: true, + itIs: 'ignored' + }); + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: userWithProgress.email } + }); + expect(user?.isDonating).toBe(true); + expect(response.body).toEqual({ + isDonating: true + }); + expect(response.status).toBe(200); + }); + + test('should return 409 if the user is already donating', async () => { + const successResponse = await superPost('/donate/add-donation').send( + {} + ); + expect(successResponse.status).toBe(200); + const failResponse = await superPost('/donate/add-donation').send({}); + expect(failResponse.status).toBe(409); + }); + + test('should capture unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + const updateSpy = vi + .spyOn(fastifyTestInstance.prisma.user, 'update') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superPost('/donate/add-donation').send({}); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + updateSpy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('PUT /donate/update-stripe-card', () => { + test('should return 200 and return session id', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.donation.create({ + data: donationMock + }); + const response = await superPut('/donate/update-stripe-card').send({}); + expect(mockCheckoutSessionCreate).toHaveBeenCalledWith({ + cancel_url: 'http://localhost:8000/update-stripe-card', + customer: 'cust_test_id', + mode: 'setup', + payment_method_types: ['card'], + setup_intent_data: { + metadata: { + customer_id: 'cust_test_id', + subscription_id: 'sub_test_id' + } + }, + success_url: + 'http://localhost:8000/update-stripe-card?session_id={CHECKOUT_SESSION_ID}' + }); + expect(response.body).toEqual({ sessionId: 'checkout_session_id' }); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith( + 'donation.card_update_requested', + 1, + { + attributes: { result: 'success' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + test('should return 404 if there is no donation record', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/donate/update-stripe-card').send({}); + expect(response.body).toEqual({ + message: 'flash.generic-error', + type: 'danger' + }); + expect(response.status).toBe(404); + expect(count).toHaveBeenCalledWith( + 'donation.card_update_requested', + 1, + { + attributes: { result: 'not_found' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('POST /donate/create-stripe-payment-intent', () => { + test('should return 200 and call stripe api properly', async () => { + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('no-errors') + ); + const response = await superPost( + '/donate/create-stripe-payment-intent' + ).send(createStripePaymentIntentReqBody); + expect(mockCustomerCreate).toHaveBeenCalledWith({ + email: testEWalletEmail, + name: 'Baz Bar' + }); + expect(response.status).toBe(200); + }); + + test('should return 400 when email format is wrong', async () => { + const response = await superPost( + '/donate/create-stripe-payment-intent' + ).send({ + ...createStripePaymentIntentReqBody, + email: '12raqdcev' + }); + expect(response.body).toEqual({ + error: 'The donation form had invalid values for this submission.' + }); + expect(response.status).toBe(400); + }); + + test('should return 400 if amount is incorrect', async () => { + const response = await superPost( + '/donate/create-stripe-payment-intent' + ).send({ + ...createStripePaymentIntentReqBody, + amount: '350' + }); + expect(response.body).toEqual({ + error: 'The donation form had invalid values for this submission.' + }); + expect(response.status).toBe(400); + }); + + test('should return 500 if Stripe encounters an error', async () => { + mockSubCreate.mockImplementationOnce(defaultError); + const response = await superPost( + '/donate/create-stripe-payment-intent' + ).send(createStripePaymentIntentReqBody); + expect(response.body).toEqual({ + error: 'Donation failed due to a server error.' + }); + expect(response.status).toBe(500); + }); + }); + + describe('POST /donate/charge-stripe', () => { + test('should return 200 and call stripe api properly', async () => { + mockSubCreate.mockImplementationOnce( + generateMockSubCreate('no-errors') + ); + const response = await superPost('/donate/charge-stripe').send( + chargeStripeReqBody + ); + await verifyUpdatedUserAndNewDonation(testEWalletEmail); + expect(mockSubRetrieve).toHaveBeenCalledWith('sub_test_id'); + expect(response.status).toBe(200); + }); + + test('should return 500 when if product id is wrong', async () => { + mockSubRetrieve.mockImplementationOnce(() => + Promise.resolve({ + ...mockSubRetrieveObj, + items: { + ...mockSubRetrieveObj.items, + data: [ + { + ...mockSubRetrieveObj.items.data[0], + plan: { + product: 'wrong_product_id' + } + } + ] + } + }) + ); + const response = await superPost('/donate/charge-stripe').send( + chargeStripeReqBody + ); + await verifyNoNewUserAndNoNewDonation(); + expect(response.body).toEqual({ + error: 'Donation failed due to a server error.' + }); + expect(response.status).toBe(500); + }); + + test('should return 500 if subsciption is not active', async () => { + mockSubRetrieve.mockImplementationOnce(() => + Promise.resolve({ + ...mockSubRetrieveObj, + status: 'canceled' + }) + ); + const response = await superPost('/donate/charge-stripe').send( + chargeStripeReqBody + ); + await verifyNoNewUserAndNoNewDonation(); + expect(response.body).toEqual({ + error: 'Donation failed due to a server error.' + }); + expect(response.status).toBe(500); + }); + + test('should return 500 if timestamp is old', async () => { + mockSubRetrieve.mockImplementationOnce(() => + Promise.resolve({ + ...mockSubRetrieveObj, + current_period_start: Math.floor(Date.now() / 1000) - 500 + }) + ); + const response = await superPost('/donate/charge-stripe').send( + chargeStripeReqBody + ); + await verifyNoNewUserAndNoNewDonation(); + expect(response.body).toEqual({ + error: 'Donation failed due to a server error.' + }); + expect(response.status).toBe(500); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.ts new file mode 100644 index 0000000000000000000000000000000000000000..5da9457ac53d40626a1f879b2651377eb240457c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/donate.ts @@ -0,0 +1,292 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import Stripe from 'stripe'; + +import * as schemas from '../../schemas.js'; +import { donationSubscriptionConfig } from '@freecodecamp/shared/config/donation-settings'; +import { STRIPE_SECRET_KEY, HOME_LOCATION } from '../../utils/env.js'; +import { clientNetInfo } from '../../utils/logger.js'; + +/** + * Plugin for the donation endpoints requiring auth. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const donateRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + // Stripe plugin + const stripe = new Stripe(STRIPE_SECRET_KEY, { + apiVersion: '2024-06-20', + typescript: true + }); + + fastify.put( + '/donate/update-stripe-card', + { + schema: schemas.updateStripeCard + }, + async (req, reply) => { + const donation = await fastify.prisma.donation.findFirst({ + where: { userId: req.user?.id, provider: 'stripe' } + }); + if (!donation) { + req.log.warn( + { userId: req.user?.id }, + 'Stripe donation record not found' + ); + fastify.Sentry?.metrics?.count('donation.card_update_requested', 1, { + attributes: { result: 'not_found' } + }); + void reply.code(404); + return { message: 'flash.generic-error', type: 'danger' } as const; + } + const { customerId, subscriptionId } = donation; + const session = await stripe.checkout.sessions.create({ + payment_method_types: ['card'], + mode: 'setup', + customer: customerId, + setup_intent_data: { + metadata: { + customer_id: customerId, + subscription_id: subscriptionId + } + }, + success_url: `${HOME_LOCATION}/update-stripe-card?session_id={CHECKOUT_SESSION_ID}`, + cancel_url: `${HOME_LOCATION}/update-stripe-card` + }); + req.log.info('Stripe session created'); + fastify.Sentry?.metrics?.count('donation.card_update_requested', 1, { + attributes: { result: 'success' } + }); + return { sessionId: session.id } as const; + } + ); + + fastify.post( + '/donate/add-donation', + { + schema: schemas.addDonation + }, + async (req, reply) => { + try { + const user = await fastify.prisma.user.findUnique({ + where: { id: req.user?.id } + }); + + if (user?.isDonating) { + req.log.warn('User is already donating'); + void reply.code(409); + return { + type: 'info', + message: 'User is already donating.' + } as const; + } + + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + isDonating: true + } + }); + + req.log.info({ audit: true }, 'User is now donating'); + + return { + isDonating: true + } as const; + } catch (error) { + fastify.Sentry?.captureException(error); + req.log.error( + { err: error, userId: req.user?.id, ...clientNetInfo(req) }, + 'User failed to donate' + ); + void reply.code(500); + return { + type: 'danger', + message: 'Something went wrong.' + } as const; + } + } + ); + + fastify.post( + '/donate/charge-stripe-card', + { + schema: schemas.chargeStripeCard + }, + async (req, reply) => { + try { + const { paymentMethodId, amount, duration } = req.body; + const id = req.user!.id; + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id } + }); + + const { email, name } = user; + + if (!email) { + req.log.warn('User has no email'); + void reply.code(400); + return reply.send({ + error: { + type: 'EmailRequiredError', + message: 'User has not provided an email address' + } + }); + } + const threeChallengesCompleted = user.completedChallenges.length >= 3; + + if (!threeChallengesCompleted) { + req.log.warn( + 'User has tried to donate before completing 3 challenges' + ); + void reply.code(400); + return { + error: { + type: 'MethodRestrictionError', + message: `Donate using another method` + } + } as const; + } + + if (user.isDonating) { + req.log.warn('User is already donating'); + void reply.code(409); + return reply.send({ + error: { + type: 'AlreadyDonatingError', + message: 'User is already donating.' + } + }); + } + + // Create Stripe Customer + const { id: customerId } = await stripe.customers.create({ + email, + payment_method: paymentMethodId, + invoice_settings: { default_payment_method: paymentMethodId }, + ...(name && { name }) + }); + + // //Create Stripe Subscription + const plan = `${donationSubscriptionConfig.duration[ + duration + ].toLowerCase()}-donation-${amount}`; + + const { + id: subscriptionId, + latest_invoice: { + // For older api versions, @ts-ignore is recommended by Stripe. More info: https://github.com/stripe/stripe-node/blob/fe81d1f28064c9b468c7b380ab09f7a93054ba63/README.md?plain=1#L91 + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore stripe-version-2019-10-17 + payment_intent: { client_secret, status } + } + } = await stripe.subscriptions.create({ + customer: customerId, + payment_behavior: 'allow_incomplete', + items: [{ plan }], + expand: ['latest_invoice.payment_intent'] + }); + if (status === 'requires_source_action') { + req.log.info('User payment requires user action'); + fastify.Sentry?.metrics?.count('donation.action_required', 1); + void reply.code(402); + return reply.send({ + error: { + type: 'UserActionRequired', + message: 'Payment requires user action', + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + client_secret + } + }); + } else if (status === 'requires_source') { + req.log.warn('User payment declined'); + fastify.Sentry?.metrics?.count('donation.declined', 1, { + attributes: { flow: 'charge-stripe-card' } + }); + void reply.code(402); + return reply.send({ + error: { + type: 'PaymentMethodRequired', + message: 'Card has been declined' + } + }); + } + + // update record in database + const donation = { + userId: id, + email, + amount, + duration, + provider: 'stripe', + subscriptionId, + customerId: customerId, + // TODO(Post-MVP) migrate to startDate: new Date() + startDate: { + date: new Date().toISOString(), + when: new Date().toISOString().replace(/.$/, '+00:00') + } + }; + + await fastify.prisma.donation.create({ + data: donation + }); + + await fastify.prisma.user.update({ + where: { id }, + data: { + isDonating: true + } + }); + + req.log.info( + { + audit: true, + userId: id, + email, + amount, + duration, + subscriptionId, + ...clientNetInfo(req) + }, + 'User has successfully donated' + ); + fastify.Sentry?.metrics?.count('donation.created', 1, { + attributes: { flow: 'charge-stripe-card' } + }); + + return reply.send({ + type: 'success', + isDonating: true + }); + } catch (error) { + const ctx = { + err: error, + userId: req.user?.id, + ...clientNetInfo(req) + }; + if ( + error instanceof Stripe.errors.StripeCardError || + error instanceof Stripe.errors.StripeInvalidRequestError + ) { + req.log.warn(ctx, 'Stripe upstream error charging card'); + } else { + fastify.Sentry?.captureException(error); + req.log.error(ctx, 'User failed to donate'); + } + void reply.code(500); + return reply.send({ + error: 'Donation failed due to a server error.' + }); + } + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..17bcaa705fd2f50c62154f6b11901a79995a41c9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/index.ts @@ -0,0 +1,6 @@ +export * from './certificate.js'; +export * from './challenge.js'; +export * from './donate.js'; +export * from './settings.js'; +export * from './user.js'; +export * from './socrates.js'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6e3bf29bf5edf62b76e3d1b8c3525f568ab7bd9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.test.ts @@ -0,0 +1,2024 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +import { + describe, + test, + expect, + beforeAll, + afterEach, + beforeEach, + vi, + MockInstance +} from 'vitest'; +import { + devLogin, + setupServer, + superRequest, + createSuperRequest, + defaultUserId, + defaultUserEmail +} from '../../../vitest.utils.js'; +import { formatMessage } from '../../plugins/redirect-with-message.js'; +import { createUserInput } from '../../utils/create-user.js'; +import { API_LOCATION, HOME_LOCATION } from '../../utils/env.js'; +import { + isPictureWithProtocol, + getWaitMessage, + validateSocialUrl +} from './settings.js'; +import { findOrCreateUser } from '../helpers/auth-helpers.js'; + +const baseProfileUI = { + isLocked: false, + showAbout: false, + showCerts: false, + showDonation: false, + showExperience: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false +}; + +const profileUI = { + ...baseProfileUI, + isLocked: true, + showAbout: true, + showDonation: true, + showLocation: true, + showName: true, + showPortfolio: true +}; + +const developerUserEmail = 'foo@bar.com'; +const otherDeveloperUserEmail = 'bar@bar.com'; +const unusedEmailOne = 'nobody@would.com'; +const unusedEmailTwo = 'would@they.com'; + +const updateErrorResponse = { + type: 'danger', + message: 'flash.wrong-updating' +}; + +describe('settingRoutes', () => { + setupServer(); + + describe('Authenticated user', () => { + let superPut: ReturnType; + let superGet: ReturnType; + + // Authenticate user + beforeAll(async () => { + const setCookies = await devLogin(); + superPut = createSuperRequest({ method: 'PUT', setCookies }); + superGet = createSuperRequest({ method: 'GET', setCookies }); + // This is not strictly necessary, since the defaultUser has this + // profileUI, but we're interested in how the profileUI is updated. As + // such, setting this explicitly isolates these tests. + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: developerUserEmail }, + data: { profileUI: baseProfileUI } + }); + + const otherUser = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: otherDeveloperUserEmail } + }); + + if (!otherUser) { + await fastifyTestInstance.prisma.user.create({ + data: createUserInput(otherDeveloperUserEmail) + }); + } + }); + + describe('/confirm-email', () => { + const defaultErrorMessage = { + type: 'danger', + content: + 'Oops! Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.' + } as const; + + const successMessage = { + type: 'success', + content: 'flash.email-valid' + } as const; + + const validToken = + '4kZFEVHChxzY7kX1XSzB4uhh8fcUwcqAGWV9hv25hsI6nviVlwzXCv2YE9lENYGy'; + // This is a valid id for a token, but it doesn't exist in the database + const validButMissingToken = + '4kZFEVHChxzY7kX1XSzB4uhh8fcUwcqAGWV9hv25hsI6nviVlwzXCv2YE9lENYGY'; + const tokenWithMissingUser = + '4kZFEVHChxzY7kX1XSzB4uhh8fcUwcqAGWV9hv25hsI6nviVlwzXCv2YE9lENYGH'; + const tokenWithDifferentUser = + '4kZFEVHChxzY7kX1XSzB4uhh8fcUwcqAGWV9hv25hsI6nviVlwzXCv2YE9lENYGI'; + const expiredToken = + '4kZFEVHChxzY7kX1XSzB4uhh8fcUwcqAGWV9hv25hsI6nviVlwzXCv2YE9lENYGE'; + + const tokens = [ + validToken, + tokenWithMissingUser, + expiredToken, + tokenWithDifferentUser + ]; + const newEmail = 'anything@goes.com'; + const otherUserEmail = 'another@user.com'; + const encodedEmail = Buffer.from(newEmail).toString('base64'); + const notEmail = Buffer.from('foobar.com').toString('base64'); + + beforeEach(async () => { + const otherUser = await findOrCreateUser( + fastifyTestInstance, + otherUserEmail + ); + + await fastifyTestInstance.prisma.authToken.create({ + data: { + created: new Date(), + id: validToken, + ttl: 1000, + userId: defaultUserId + } + }); + + await fastifyTestInstance.prisma.authToken.create({ + data: { + created: new Date(), + id: tokenWithMissingUser, + ttl: 1000, + // Random ObjectId + userId: '6650ac23ccc46c0349a86dee' + } + }); + + await fastifyTestInstance.prisma.authToken.create({ + data: { + created: new Date(), + id: tokenWithDifferentUser, + ttl: 1000, + userId: otherUser.id + } + }); + + await fastifyTestInstance.prisma.authToken.create({ + data: { + created: new Date(Date.now() - 1000), + id: expiredToken, + ttl: 1000, + userId: defaultUserId + } + }); + + // We expect these properties to be changed by the endpoint, so they + // need to be set so that change can be confirmed. + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + newEmail, + emailVerified: false, + emailVerifyTTL: new Date(), + emailAuthLinkTTL: new Date() + } + }); + + // Simulate another user changing their email. This user is signed out. + await fastifyTestInstance.prisma.user.update({ + where: { id: otherUser.id }, + data: { + newEmail, + emailVerified: false, + emailVerifyTTL: new Date(), + emailAuthLinkTTL: new Date() + } + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.authToken.deleteMany({ + where: { id: { in: tokens } } + }); + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { newEmail: null, email: defaultUserEmail, emailVerified: true } + }); + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: otherUserEmail } + }); + }); + + test('should reject requests without params', async () => { + const resNoParams = await superGet('/confirm-email'); + + expect(resNoParams.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(resNoParams.status).toBe(302); + }); + + test('should reject requests which have an invalid token param', async () => { + const res = await superGet( + // token should be 64 characters long + `/confirm-email?email=${encodedEmail}&token=tooshort` + ); + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + }); + + test('should reject requests which have an invalid email param', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${notEmail}&token=${validToken}` + ); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + expect(count).toHaveBeenCalledWith( + 'settings.email_confirm_rejected', + 1, + { attributes: { reason: 'invalid_email' } } + ); + }); + + test('should reject requests when the auth token is not in the database', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${validButMissingToken}` + ); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + expect(count).toHaveBeenCalledWith( + 'settings.email_confirm_rejected', + 1, + { attributes: { reason: 'no_token' } } + ); + }); + + test('should reject requests when the auth token exists, but the user does not', async () => { + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${validButMissingToken}` + ); + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + }); + + test('should reject requests when the target user does not match the signed in user', async () => { + // The signed in user is the default (foo@bar.com), but the token is for + // a different user (another@user.com). + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${tokenWithDifferentUser}` + ); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + expect(count).toHaveBeenCalledWith( + 'settings.email_confirm_rejected', + 1, + { attributes: { reason: 'user_mismatch' } } + ); + }); + + // TODO(Post-MVP): there's no need to keep the auth token around if, + // somehow, the user is missing + test.todo( + 'should delete the auth token if there is no user associated with it' + ); + + test('should reject requests when the email param is different from user.newEmail', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { newEmail: 'an@oth.er' } + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${validToken}` + ); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(defaultErrorMessage) + ); + expect(res.status).toBe(302); + expect(count).toHaveBeenCalledWith( + 'settings.email_confirm_rejected', + 1, + { attributes: { reason: 'email_mismatch' } } + ); + }); + + test('should reject requests if the auth token has expired', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${expiredToken}` + ); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + + formatMessage({ + content: + 'The link to confirm your new email address has expired. Please try again.', + type: 'info' + }) + ); + expect(res.status).toBe(302); + expect(count).toHaveBeenCalledWith( + 'settings.email_confirm_rejected', + 1, + { attributes: { reason: 'expired' } } + ); + }); + + test('should update the user email', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet( + `/confirm-email?email=${encodedEmail}&token=${validToken}` + ); + const user = await fastifyTestInstance.prisma.user.findUniqueOrThrow({ + where: { id: defaultUserId } + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(res.headers.location).toBe( + `${HOME_LOCATION}?` + formatMessage(successMessage) + ); + expect(user.email).toBe(newEmail); + expect(count).toHaveBeenCalledWith('settings.email_confirmed', 1); + }); + + test('should clean up the user record', async () => { + await superGet( + `/confirm-email?email=${encodedEmail}&token=${validToken}` + ); + + const user = await fastifyTestInstance.prisma.user.findUniqueOrThrow({ + where: { id: defaultUserId } + }); + + expect(user.newEmail).toBeNull(); + expect(user.emailVerified).toBe(true); + expect(user.emailVerifyTTL).toBeNull(); + expect(user.emailAuthLinkTTL).toBeNull(); + }); + + test('should remove the auth token on success', async () => { + await superGet( + `/confirm-email?email=${encodedEmail}&token=${validToken}` + ); + + const authToken = await fastifyTestInstance.prisma.authToken.findUnique( + { + where: { id: validToken } + } + ); + + expect(authToken).toBeNull(); + }); + }); + + describe('/update-my-profileui', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-profileui').send({ + profileUI + }); + + fastifyTestInstance.Sentry = originalSentry; + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail } + }); + + expect(response.body).toEqual({ + message: 'flash.privacy-updated', + type: 'success' + }); + expect(user?.profileUI).toEqual(profileUI); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'profile_ui' } + }); + }); + + test('PUT ignores invalid keys', async () => { + const response = await superPut('/update-my-profileui').send({ + profileUI: { + ...profileUI, + invalidKey: 'invalidValue' + } + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail } + }); + + expect(user?.profileUI).toEqual(profileUI); + expect(response.statusCode).toEqual(200); + }); + + test('PUT returns 400 status code with missing keys', async () => { + const response = await superPut('/update-my-profileui').send({ + profileUI: { + isLocked: true, + showName: true, + showPoints: false, + showPortfolio: true, + showTimeLine: false + } + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-email', () => { + let sendEmailSpy: MockInstance; + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: developerUserEmail }, + data: { + newEmail: null, + emailVerified: true, + emailVerifyTTL: null, + emailAuthLinkTTL: null + } + }); + + sendEmailSpy = vi + .spyOn(fastifyTestInstance, 'sendEmail') + .mockImplementationOnce(vi.fn()); + }); + + afterEach(async () => { + vi.clearAllMocks(); + await fastifyTestInstance.prisma.authToken.deleteMany({ + where: { userId: defaultUserId } + }); + }); + test('PUT returns 200 status code with "info" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-email').send({ + email: 'foo@foo.com' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: + 'Check your email and click the link we sent you to confirm your new email address.', + type: 'info' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith( + 'settings.email_change_requested', + 1 + ); + }); + + test("PUT updates the user's record in preparation for receiving auth email", async () => { + const timeBefore = Date.now(); + const response = await superPut('/update-my-email').send({ + email: unusedEmailOne + }); + + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: developerUserEmail }, + select: { + emailAuthLinkTTL: true, + emailVerifyTTL: true, + emailVerified: true, + newEmail: true + } + }); + + // expect the emailVerifyTTL and emailAuthLinkTTL to be set to the current time + expect(user.emailVerifyTTL!.getTime()).toBeGreaterThan(timeBefore); + expect(user.emailVerifyTTL!.getTime()).toBeLessThan(Date.now()); + expect(user.emailAuthLinkTTL!.getTime()).toBeGreaterThan(timeBefore); + expect(user.emailAuthLinkTTL!.getTime()).toBeLessThan(Date.now()); + + expect(user.emailVerified).toEqual(false); + expect(user.newEmail).toEqual(unusedEmailOne); + expect(response.statusCode).toEqual(200); + }); + + test('PUT rejects invalid email addresses', async () => { + const response = await superPut('/update-my-email').send({ + email: 'invalid' + }); + + // We cannot use fastify's default validation failure response here + // because the client consumes the response and displays it to the user. + expect(response.body).toEqual({ + type: 'danger', + message: 'Email format is invalid' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT accepts requests to update to the current email address (ignoring case) if it is not verified', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: developerUserEmail }, + data: { emailVerified: false } + }); + const response = await superPut('/update-my-email').send({ + email: developerUserEmail.toUpperCase() + }); + + expect(response.statusCode).toEqual(200); + expect(response.body).toEqual({ + message: + 'Check your email and click the link we sent you to confirm your new email address.', + type: 'info' + }); + }); + + test('PUT rejects a request to update to the existing email (ignoring case) address', async () => { + const response = await superPut('/update-my-email').send({ + email: developerUserEmail.toUpperCase() + }); + + expect(response.body).toEqual({ + type: 'info', + message: `${developerUserEmail} is already associated with this account. +You can update a new email address instead.` + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT rejects a request to update to the same email (ignoring case) twice', async () => { + const successResponse = await superPut('/update-my-email').send({ + email: unusedEmailOne + }); + + expect(successResponse.statusCode).toEqual(200); + + const failResponse = await superPut('/update-my-email').send({ + email: unusedEmailOne.toUpperCase() + }); + + expect(failResponse?.body).toEqual({ + type: 'info', + message: `We have already sent an email confirmation request to ${unusedEmailOne}. +Please wait 5 minutes to resend an authentication link.` + }); + expect(failResponse?.statusCode).toEqual(429); + }); + + test('PUT rejects a request if the new email is already in use', async () => { + const response = await superPut('/update-my-email').send({ + email: otherDeveloperUserEmail + }); + + expect(response.body).toEqual({ + type: 'info', + message: `${otherDeveloperUserEmail} is already associated with another account.` + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT rejects the second request if is immediately after the first', async () => { + const successResponse = await superPut('/update-my-email').send({ + email: unusedEmailOne + }); + + expect(successResponse.statusCode).toEqual(200); + + const failResponse = await superPut('/update-my-email').send({ + email: unusedEmailTwo + }); + + expect(failResponse?.statusCode).toEqual(429); + + expect(failResponse?.body).toEqual({ + type: 'info', + message: `Please wait 5 minutes to resend an authentication link.` + }); + + // The rate-limited request must not overwrite the pending email, + // otherwise the confirmation link sent to the first address stops + // working. + const user = await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: developerUserEmail }, + select: { newEmail: true } + }); + expect(user.newEmail).toEqual(unusedEmailOne); + }); + + test('PUT creates an auth token record for the requesting user', async () => { + // Reset user state to avoid rate limiting from previous tests + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + emailAuthLinkTTL: null, + newEmail: null + } + }); + + const noToken = await fastifyTestInstance.prisma.authToken.findFirst({ + where: { userId: defaultUserId } + }); + expect(noToken).toBeNull(); + + await superPut('/update-my-email').send({ + email: unusedEmailTwo + }); + + const token = await fastifyTestInstance.prisma.authToken.findFirst({ + where: { userId: defaultUserId } + }); + + expect(token).toEqual({ + ttl: 15 * 60 * 1000, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + created: expect.any(Date), + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + id: expect.any(String), + userId: defaultUserId + }); + }); + + // This has to be the last test since vi.mockRestore replaces the original + // function with undefined when restoring a prisma function (for some + // reason) + test('PUT sends an email to the new email address', async () => { + const originalAuthToken = fastifyTestInstance.prisma.authToken; + vi.spyOn( + fastifyTestInstance.prisma, + 'authToken', + 'get' + ).mockReturnValue({ + ...originalAuthToken, + create: vi.fn().mockResolvedValue({ + id: '123' + }) + }); + await superPut('/update-my-email').send({ + email: unusedEmailOne + }); + + const expectedLink = `${API_LOCATION}/confirm-email?email=${Buffer.from(unusedEmailOne).toString('base64')}&token=123&emailChange=true`; + expect(sendEmailSpy).toHaveBeenCalledWith({ + from: 'team@freecodecamp.org', + to: unusedEmailOne, + subject: + 'Please confirm your updated email address for freeCodeCamp.org', + text: `Please confirm this email address for freeCodeCamp.org: + +${expectedLink} + +Happy coding! + +- The freeCodeCamp.org Team +` + }); + }); + }); + + describe('/update-my-theme', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-theme').send({ + theme: 'night' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.updated-themes', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'theme' } + }); + }); + + test('PUT returns 400 status code with invalid theme', async () => { + const response = await superPut('/update-my-theme').send({ + theme: 'invalid' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('PUT captures a Sentry Issue and returns 500 when the update fails', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { ...originalSentry, captureException }; + + const original = fastifyTestInstance.prisma.user.update; + fastifyTestInstance.prisma.user.update = vi + .fn() + .mockRejectedValue(new Error('db down')) as typeof original; + + const response = await superPut('/update-my-theme').send({ + theme: 'night' + }); + + fastifyTestInstance.prisma.user.update = original; + fastifyTestInstance.Sentry = originalSentry; + + expect(response.statusCode).toEqual(500); + expect(response.body).toEqual(updateErrorResponse); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'db down' }) + ); + }); + }); + + describe('/update-my-username', () => { + test('PUT returns an error when the username uses special characters', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-username').send({ + username: 'twaha@' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'Username twaha@ contains invalid characters', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + expect(count).toHaveBeenCalledWith( + 'settings.username_change_rejected', + 1, + { attributes: { reason: 'invalid' } } + ); + }); + + test('PUT returns an error when the username is an endpoint', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-username').send({ + username: 'german' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.username-restricted', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + expect(count).toHaveBeenCalledWith( + 'settings.username_change_rejected', + 1, + { attributes: { reason: 'username_restricted' } } + ); + }); + + test('PUT returns an error when the username is a bad word', async () => { + const response = await superPut('/update-my-username').send({ + username: 'ass' + }); + + expect(response.body).toEqual({ + message: 'flash.username-restricted', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns an error when the username is a https status code', async () => { + const response = await superPut('/update-my-username').send({ + username: '404' + }); + + expect(response.body).toEqual({ + message: 'Username 404 is a reserved error code', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns an error when the username is shorter than 3 characters', async () => { + const response = await superPut('/update-my-username').send({ + username: 'fo' + }); + + expect(response.body).toEqual({ + message: 'body/username must NOT have fewer than 3 characters', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-username').send({ + username: 'TwaHa1' + }); + + fastifyTestInstance.Sentry = originalSentry; + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user?.username).toEqual('twaha1'); + expect(response.body).toStrictEqual({ + message: 'flash.username-updated', + type: 'success', + variables: { username: 'TwaHa1' } + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'username' } + }); + }); + + test('PUT returns an error when the username is already used', async () => { + await fastifyTestInstance.prisma.user.create({ + data: { + email: 'an@ran.dom', + username: 'sembauke', + about: 'about', + acceptedPrivacyTerms: true, + emailVerified: true, + externalId: 'externalId', + isDonating: true, + picture: 'picture', + sendQuincyEmail: true, + unsubscribeId: 'unsubscribeId' + } + }); + await superPut('/update-my-username').send({ username: 'twaha2' }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const secondUpdate = await superPut('/update-my-username').send({ + username: 'twaha2' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(secondUpdate.body).toEqual({ + message: 'flash.username-used', + type: 'info' + }); + expect(secondUpdate.statusCode).toEqual(400); + expect(count).toHaveBeenCalledWith( + 'settings.username_change_rejected', + 1, + { attributes: { reason: 'unchanged' } } + ); + + // Not allowed because, while the usernameDisplay is different, the + // username is not + const takenCount = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count: takenCount } + }; + const existingUser = await superPut('/update-my-username').send({ + username: 'SemBauke' + }); + fastifyTestInstance.Sentry = originalSentry; + + expect(existingUser.body).toEqual({ + message: 'flash.username-taken', + type: 'info' + }); + expect(existingUser.statusCode).toEqual(400); + expect(takenCount).toHaveBeenCalledWith( + 'settings.username_change_rejected', + 1, + { attributes: { reason: 'username_taken' } } + ); + }); + + test('PUT /update-my-username returns 400 status code when username is too long', async () => { + const username = 'a'.repeat(1001); + const response = await superPut('/update-my-username').send({ + username + }); + + expect(response.body).toEqual({ + message: 'body/username must NOT have more than 1000 characters', + type: 'info' + }); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-keyboard-shortcuts', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-keyboard-shortcuts').send({ + keyboardShortcuts: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.keyboard-shortcut-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'keyboard_shortcuts' } + }); + }); + + test('PUT returns 400 status code with invalid shortcuts setting', async () => { + const response = await superPut('/update-my-keyboard-shortcuts').send({ + keyboardShortcuts: 'invalid' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-socials', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-socials').send({ + website: 'https://www.freecodecamp.org/', + twitter: 'https://twitter.com/ossia', + bluesky: 'https://bsky.app/profile/quincy.bsky.social', + linkedin: 'https://www.linkedin.com/in/quincylarson', + githubProfile: 'https://github.com/QuincyLarson' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.updated-socials', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'socials' } + }); + }); + + test('PUT accepts empty strings for socials', async () => { + const response = await superPut('/update-my-socials').send({ + website: 'https://www.freecodecamp.org/', + twitter: '', + bluesky: '', + linkedin: '', + githubProfile: '' + }); + + expect(response.body).toEqual({ + message: 'flash.updated-socials', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + }); + + test('PUT rejects non-url values', async () => { + const response = await superPut('/update-my-socials').send({ + website: 'invalid', + twitter: '', + bluesky: '', + linkedin: '', + githubProfile: '' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('PUT only accepts urls to certain domains', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-socials').send({ + website: '', + twitter: '', + bluesky: '', + linkedin: '', + githubProfile: 'https://x.com/should-be-github' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + expect(count).toHaveBeenCalledWith('settings.social_url_rejected', 1, { + attributes: { provider: 'githubProfile' } + }); + }); + + test('PUT does not log raw social URLs on validation failure', async () => { + const spy = vi.spyOn(fastifyTestInstance.log, 'warn'); + const leakyUrl = 'https://x.com/should-be-github?api_key=super-secret'; + + const response = await superPut('/update-my-socials').send({ + website: '', + twitter: '', + bluesky: '', + linkedin: '', + githubProfile: leakyUrl + }); + + expect(response.statusCode).toEqual(400); + const call = spy.mock.calls.find( + ([, msg]) => msg === 'Invalid social URL' + ); + expect(call).toBeDefined(); + const [logObject] = call!; + expect(JSON.stringify(logObject)).not.toContain(leakyUrl); + expect(JSON.stringify(logObject)).not.toContain('super-secret'); + expect(logObject).toEqual({ invalidSocials: ['githubProfile'] }); + }); + }); + + describe('/update-my-quincy-email', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-quincy-email').send({ + sendQuincyEmail: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.subscribe-to-quincy-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'quincy_email' } + }); + }); + + test('PUT returns 400 status code with invalid sendQuincyEmail', async () => { + const response = await superPut('/update-my-quincy-email').send({ + sendQuincyEmail: 'invalid' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-socrates', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-socrates').send({ + socrates: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.socrates-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'socrates' } + }); + }); + }); + + describe('/update-my-about', () => { + test('PUT updates the values in about settings', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: + 'https://cdn.freecodecamp.org/platform/english/images/quincy-larson-signature.svg' + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + + const user = await fastifyTestInstance?.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user?.about).toEqual('Teacher at freeCodeCamp'); + expect(user?.name).toEqual('Quincy Larson'); + expect(user?.location).toEqual('USA'); + expect(user?.picture).toEqual( + 'https://cdn.freecodecamp.org/platform/english/images/quincy-larson-signature.svg' + ); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'about' } + }); + }); + + test('PUT returns 400 if the URL is invalid', async () => { + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: 'invalid' + }); + + expect(response.body).toEqual({ + message: 'flash.wrong-updating', + type: 'danger' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns 400 if the URL has no image extension', async () => { + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: 'https://example.com/avatar' + }); + + expect(response.body).toEqual({ + message: 'flash.wrong-updating', + type: 'danger' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns 400 if the URL has a non-image extension', async () => { + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: 'https://example.com/file.txt' + }); + + expect(response.body).toEqual({ + message: 'flash.wrong-updating', + type: 'danger' + }); + expect(response.statusCode).toEqual(400); + }); + + test('PUT does not log the raw picture URL on validation failure', async () => { + const spy = vi.spyOn(fastifyTestInstance.log, 'warn'); + spy.mockClear(); + const leakyUrl = 'https://example.com/file.txt?api_key=super-secret'; + + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: leakyUrl + }); + + expect(response.statusCode).toEqual(400); + const call = spy.mock.calls.find( + ([, msg]) => msg === 'Invalid picture URL' + ); + expect(call).toBeDefined(); + const [logObject] = call!; + expect(JSON.stringify(logObject)).not.toContain(leakyUrl); + expect(JSON.stringify(logObject)).not.toContain('super-secret'); + expect(logObject).toEqual({ + hasPicture: true, + pictureLength: leakyUrl.length + }); + }); + + test('PUT accepts an image URL with query string', async () => { + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: 'https://example.com/photo.png?size=200&cache=bust' + }); + + expect(response.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + }); + + test('PUT accepts an image URL with a different valid extension (.webp)', async () => { + const response = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: 'https://example.com/avatar.webp' + }); + + expect(response.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + }); + + test('PUT with empty strings clears the values in about settings', async () => { + const initialResponse = await superPut('/update-my-about').send({ + about: 'Teacher at freeCodeCamp', + name: 'Quincy Larson', + location: 'USA', + picture: + 'https://cdn.freecodecamp.org/platform/english/images/quincy-larson-signature.svg' + }); + + expect(initialResponse.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + expect(initialResponse.statusCode).toEqual(200); + + const response = await superPut('/update-my-about').send({ + about: '', + name: '', + location: '', + picture: '' + }); + + expect(response.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + + const user = await fastifyTestInstance?.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + expect(user?.about).toEqual(''); + expect(user?.name).toEqual(''); + expect(user?.location).toEqual(''); + expect(user?.picture).toEqual(''); + }); + + test('PUT returns 400 status code with invalid about settings', async () => { + const response = await superPut('/update-my-about').send({ + about: { no: 'objects' } + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('PUT allows updating location/about when picture is unchanged (even without extension)', async () => { + // Simulate a user who already has a GitHub avatar URL saved (e.g., from before strict validation) + const githubAvatarUrl = + 'https://avatars0.githubusercontent.com/u/34585031?v=4'; + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + picture: githubAvatarUrl, + about: 'Initial about', + name: 'Test User', + location: 'Initial Location' + } + }); + + // Now update only location and about, keeping the same picture (no extension) + const updateResponse = await superPut('/update-my-about').send({ + about: 'Updated about text', + name: 'Test User', + location: 'New Location', + picture: githubAvatarUrl // Same URL, no extension - should skip validation + }); + + expect(updateResponse.body).toEqual({ + message: 'flash.updated-about-me', + type: 'success' + }); + expect(updateResponse.statusCode).toEqual(200); + + const user = await fastifyTestInstance?.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user?.about).toEqual('Updated about text'); + expect(user?.location).toEqual('New Location'); + expect(user?.picture).toEqual(githubAvatarUrl); + }); + + test('PUT still validates picture when it is actually changed', async () => { + // Set initial valid picture + const validPictureUrl = 'https://example.com/avatar.png'; + await superPut('/update-my-about').send({ + about: 'Initial', + name: 'Test', + location: 'Location', + picture: validPictureUrl + }); + + // Try to change picture to invalid URL (no extension) + const updateResponse = await superPut('/update-my-about').send({ + about: 'Initial', + name: 'Test', + location: 'Location', + picture: 'https://example.com/new-avatar' // Changed but invalid + }); + + expect(updateResponse.statusCode).toEqual(400); + expect(updateResponse.body).toEqual({ + message: 'flash.wrong-updating', + type: 'danger' + }); + + // Verify picture wasn't updated + const user = await fastifyTestInstance?.prisma.user.findFirst({ + where: { email: 'foo@bar.com' } + }); + + expect(user?.picture).toEqual(validPictureUrl); + }); + }); + + describe('/update-my-honesty', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-honesty').send({ + isHonest: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'buttons.accepted-honesty', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'honesty' } + }); + }); + + test('PUT returns 400 status code with invalid honesty', async () => { + const response = await superPut('/update-my-honesty').send({ + isHonest: false + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-privacy-terms', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-privacy-terms').send({ + quincyEmails: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.privacy-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'privacy_terms' } + }); + }); + + test('PUT returns 400 status code with non-boolean data', async () => { + const response = await superPut('/update-privacy-terms').send({ + quincyEmails: '123' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-portfolio', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-portfolio').send({ + portfolio: [{}] + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.portfolio-item-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'portfolio' } + }); + }); + + test('PUT returns 400 status code when the portfolio property is missing', async () => { + const response = await superPut('/update-my-portfolio').send({}); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns 400 status code when any data is the wrong type', async () => { + const response = await superPut('/update-my-portfolio').send({ + portfolio: [ + { id: '', title: '', description: '', url: '', image: '' }, + { id: '', title: {}, description: '', url: '', image: '' } + ] + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-experience', () => { + test('PUT returns 200 status code with "success" message and saves experience', async () => { + const payload = { + experience: [ + { + id: '1', + title: 'Software Engineer', + company: 'Tech Corp', + location: 'Remote', + startDate: '2020-01', + endDate: '2022-06', + description: 'Worked on various projects' + } + ] + }; + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-experience').send(payload); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.experience-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'experience' } + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + + expect(user?.experience).toEqual(payload.experience); + }); + + test('rejects extraneous keys on entries', async () => { + const res = await superPut('/update-my-experience').send({ + experience: [ + { + id: 'x', + title: 'Dev', + company: 'Co', + startDate: '', + description: '', + foo: 'bar' + } + ] + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + + expect(user?.experience).toEqual([ + { + id: 'x', + title: 'Dev', + company: 'Co', + location: null, + startDate: '', + endDate: null, + description: '' + } + ]); + expect(res.statusCode).toBe(200); + }); + + test('returns 400 when experience is not an array', async () => { + const response = await superPut('/update-my-experience').send({ + experience: { not: 'an array' } as unknown as [] + }); + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('supports current position (omitted endDate becomes null)', async () => { + const response = await superPut('/update-my-experience').send({ + experience: [ + { + id: 'cur', + title: 'Engineer', + company: 'Now Co', + startDate: '2023-01', + description: '' + // endDate omitted + } + ] + }); + + expect(response.statusCode).toEqual(200); + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + expect(user?.experience?.[0]).toEqual({ + id: 'cur', + title: 'Engineer', + company: 'Now Co', + location: null, + startDate: '2023-01', + endDate: null, + description: '' + }); + }); + + test('accepts long descriptions', async () => { + const long = 'x'.repeat(1000); + const response = await superPut('/update-my-experience').send({ + experience: [ + { + id: '', + title: 'Writer', + company: 'Docs Inc', + startDate: '2020-01', + endDate: '2020-12', + description: long + } + ] + }); + + expect(response.statusCode).toEqual(200); + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + expect(user?.experience?.[0]?.description).toEqual(long); + }); + test('PUT accepts empty array and clears experience', async () => { + // seed with one item first + await superPut('/update-my-experience').send({ + experience: [ + { + id: 'seed', + title: 'Seed Title', + company: 'Seed Co', + location: 'Seed City', + startDate: '2019-01', + endDate: '2019-12', + description: 'Seed desc' + } + ] + }); + + const response = await superPut('/update-my-experience').send({ + experience: [] + }); + + expect(response.body).toEqual({ + message: 'flash.experience-updated', + type: 'success' + }); + expect(response.statusCode).toEqual(200); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + expect(user?.experience).toEqual([]); + }); + + test('PUT saves multiple experiences and preserves order', async () => { + const payload = { + experience: [ + { + id: '1', + title: 'Junior Dev', + company: 'A Inc', + location: 'NY', + startDate: '2018-01', + endDate: '2019-01', + description: 'Did stuff' + }, + { + id: '2', + title: 'Senior Dev', + company: 'B LLC', + location: 'SF', + startDate: '2019-02', + endDate: '2021-03', + description: 'Did more stuff' + } + ] + }; + + const response = await superPut('/update-my-experience').send(payload); + + expect(response.statusCode).toEqual(200); + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: developerUserEmail }, + select: { experience: true } + }); + expect(user?.experience).toEqual(payload.experience); + }); + + test('PUT returns 400 status code when the experience property is missing', async () => { + const response = await superPut('/update-my-experience').send({}); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('PUT returns 400 status code when any data is the wrong type', async () => { + const response = await superPut('/update-my-experience').send({ + experience: [ + { + id: '', + title: '', + company: '', + location: '', + startDate: '', + endDate: '', + description: '' + }, + { + id: '', + title: {}, + company: '', + location: '', + startDate: '', + endDate: '', + description: '' + } + ] + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + }); + + describe('/update-my-classroom-mode', () => { + test('PUT returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPut('/update-my-classroom-mode').send({ + isClassroomAccount: true + }); + + fastifyTestInstance.Sentry = originalSentry; + + expect(response.body).toEqual({ + message: 'flash.classroom-mode-updated', + type: 'success' + }); + + expect(response.statusCode).toEqual(200); + expect(count).toHaveBeenCalledWith( + 'settings.classroom_mode_toggled', + 1, + { + attributes: { enabled: true } + } + ); + expect(count).toHaveBeenCalledWith('settings.updated', 1, { + attributes: { field: 'classroom_mode' } + }); + }); + + test('PUT returns 400 status code with invalid classroom mode', async () => { + const response = await superPut('/update-my-classroom-mode').send({ + isClassroomAccount: 'invalid' + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + // See updateMyClassroomMode schema for one-way constraint details. + test('PUT returns 400 when attempting to disable classroom mode', async () => { + const response = await superPut('/update-my-classroom-mode').send({ + isClassroomAccount: false + }); + + expect(response.body).toEqual(updateErrorResponse); + expect(response.statusCode).toEqual(400); + }); + + test('After updating the classroom mode, the user should have this property set', async () => { + await superPut('/update-my-classroom-mode').send({ + isClassroomAccount: true + }); + + const user = await fastifyTestInstance?.prisma.user.findFirst({ + where: { + email: developerUserEmail + } + }); + + expect(user?.isClassroomAccount).toEqual(true); + }); + }); + }); + + describe('Unauthenticated User', () => { + let setCookies: string[]; + + // Get the CSRF cookies from an unprotected route + beforeAll(async () => { + const res = await superRequest('/status/ping', { method: 'GET' }); + setCookies = res.get('Set-Cookie'); + }); + + describe('/confirm-email', () => { + test('redirects to the HOME_LOCATION with flash message', async () => { + const res = await superRequest('/confirm-email', { + method: 'GET' + }).set('Referer', 'https://who.knows/'); + + expect(res.status).toBe(302); + expect(res.headers).toMatchObject({ + location: `http://localhost:8000?${formatMessage({ type: 'info', content: 'Only authenticated users can access this route. Please sign in and try again.' })}` + }); + }); + }); + + const endpoints: { path: string; method: 'PUT' }[] = [ + { path: '/update-my-profileui', method: 'PUT' }, + { path: '/update-my-theme', method: 'PUT' }, + { path: '/update-my-username', method: 'PUT' }, + { path: '/update-my-keyboard-shortcuts', method: 'PUT' }, + { path: '/update-my-socials', method: 'PUT' }, + { path: '/update-my-quincy-email', method: 'PUT' }, + { path: '/update-my-about', method: 'PUT' }, + { path: '/update-my-honesty', method: 'PUT' }, + { path: '/update-privacy-terms', method: 'PUT' }, + { path: '/update-my-portfolio', method: 'PUT' }, + { path: '/update-my-experience', method: 'PUT' } + ]; + + endpoints.forEach(({ path, method }) => { + test(`${method} ${path} returns 401 status code with error message`, async () => { + const response = await superRequest(path, { + method, + setCookies + }); + expect(response.statusCode).toBe(401); + }); + }); + }); + + describe('isPictureWithProtocol', () => { + test('Valid protocol', () => { + expect(isPictureWithProtocol('https://www.example.com/')).toEqual(true); + expect(isPictureWithProtocol('http://www.example.com/')).toEqual(true); + }); + + test('Invalid protocol', () => { + expect(isPictureWithProtocol('htps://www.example.com/')).toEqual(false); + expect(isPictureWithProtocol('tp://www.example.com/')).toEqual(false); + expect(isPictureWithProtocol('www.example.com/')).toEqual(false); + }); + }); +}); + +describe('getWaitMessage', () => { + const sec = 1000; + const min = 60 * 1000; + test.each([ + { + sentAt: new Date(0), + now: new Date(0), + expected: 'Please wait 5 minutes to resend an authentication link.' + }, + { + sentAt: new Date(0), + now: new Date(59 * sec), + expected: 'Please wait 5 minutes to resend an authentication link.' + }, + { + sentAt: new Date(0), + now: new Date(4 * min), + expected: 'Please wait 1 minute to resend an authentication link.' + }, + { + sentAt: new Date(0), + now: new Date(4 * min + 59 * sec), + expected: 'Please wait 1 minute to resend an authentication link.' + }, + { + sentAt: new Date(0), + now: new Date(5 * min), + expected: null + } + ])( + `returns "$expected" when sentAt is $sentAt and now is $now`, + ({ sentAt, now, expected }) => { + expect(getWaitMessage({ sentAt, now })).toEqual(expected); + } + ); + + test('returns null when sentAt is null', () => { + expect(getWaitMessage({ sentAt: null, now: new Date(0) })).toBeNull(); + }); + test('uses the current time when now is not provided', () => { + expect(getWaitMessage({ sentAt: new Date() })).toEqual( + 'Please wait 5 minutes to resend an authentication link.' + ); + }); +}); + +describe('validateSocialUrl', () => { + test.each(['githubProfile', 'linkedin', 'twitter', 'bluesky'] as const)( + 'accepts empty strings for %s', + social => { + expect(validateSocialUrl('', social)).toBe(true); + } + ); + + test.each([ + ['githubProfile', 'https://something.com/user'], + ['linkedin', 'https://www.x.com/in/username'], + ['twitter', 'https://www.toomanyexes.com/username'], + ['bluesky', 'https://www.twitter.com/username'] + ] as const)('rejects invalid urls for %s', (social, url) => { + expect(validateSocialUrl(url, social)).toBe(false); + }); + + test.each([ + ['githubProfile', 'https://something.github.com/user'], + ['linkedin', 'https://www.linkedin.com/in/username'], + ['twitter', 'https://twitter.com/username'], + ['twitter', 'https://x.com/username'], + ['bluesky', 'https://bsky.app/profile/username.bsky.social'] + ] as const)('accepts valid urls for %s', (social, url) => { + expect(validateSocialUrl(url, social)).toBe(true); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.ts new file mode 100644 index 0000000000000000000000000000000000000000..629ad9638009323e1db6d277a7af800487d6f1cf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/settings.ts @@ -0,0 +1,1038 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import type { FastifyError, FastifyInstance } from 'fastify'; +import { differenceInMinutes } from 'date-fns'; +import validator from 'validator'; + +import { isValidUsername } from '@freecodecamp/shared/utils/validate'; +import * as schemas from '../../schemas.js'; +import { createAuthToken, isExpired } from '../../utils/tokens.js'; +import { API_LOCATION } from '../../utils/env.js'; +import { getRedirectParams } from '../../utils/redirection.js'; +import { isRestricted } from '../helpers/is-restricted.js'; + +type WaitMesssageArgs = { + sentAt: Date | null; + now?: Date; +}; + +/** + * Get a message to display to the user about how long they need to wait before + * they can request an authentication link. + * + * @param param The parameters. + * @param param.sentAt The date the last email was sent at. + * @param param.now The current date. + * @returns The message to display to the user. + */ +export function getWaitMessage({ sentAt, now = new Date() }: WaitMesssageArgs) { + const minutesLeft = getWaitPeriod({ sentAt, now }); + if (minutesLeft <= 0) return null; + + const timeToWait = `${minutesLeft} minute${minutesLeft > 1 ? 's' : ''}`; + return `Please wait ${timeToWait} to resend an authentication link.`; +} + +function getWaitPeriod({ sentAt, now }: Required) { + if (sentAt == null) return 0; + return 5 - differenceInMinutes(now, sentAt); +} + +/** + * Validate an image url. + * + * @param picture The url to check. + * @returns Whether the url is a picture with a valid protocol. + */ +export const isPictureWithProtocol = (picture?: string): boolean => { + if (!picture) return false; + try { + const url = new URL(picture); + return url.protocol == 'http:' || url.protocol == 'https:'; + } catch { + return false; + } +}; + +const commonImageExtensions = [ + 'apng', + 'avif', + 'gif', + 'jpg', + 'jpeg', + 'jfif', + 'pjpeg', + 'pjp', + 'png', + 'svg', + 'webp' +]; + +/** + * Validate that a picture URL has a common image extension. + * + * @param picture The URL to check. + * @returns Whether the URL has a common image extension. + */ + +const validateImageExtension = (picture?: string): boolean => { + if (!picture) return true; + return commonImageExtensions.some(ext => picture.includes(`.${ext}`)); +}; + +/** + * Validate that a picture URL is valid. A valid picture URL either: + * - is empty/undefined (no update), or + * - has a valid http/https protocol AND has a common image extension. + * + * @param picture The URL to validate. + * @returns Whether the picture URL is considered valid. + */ +const isValidPictureUrl = (picture?: string): boolean => { + if (!picture) return true; + return isPictureWithProtocol(picture) && validateImageExtension(picture); +}; + +const ALLOWED_DOMAINS_MAP = { + githubProfile: ['github.com'], + linkedin: ['linkedin.com'], + twitter: ['twitter.com', 'x.com'], + bluesky: ['bsky.app'] +}; + +/** + * Validate a social URL. + * + * @param socialUrl The URL to check. + * @param key The key of the allowed socials and domains. + * @returns Whether the URL is valid. + */ +export const validateSocialUrl = ( + socialUrl: string, + key: keyof typeof ALLOWED_DOMAINS_MAP +): boolean => { + if (!socialUrl) return true; + + try { + const url = new URL(socialUrl); + const domains = ALLOWED_DOMAINS_MAP[key]; + const domainAndTld = url.hostname.split('.').slice(-2).join('.'); + return domains.includes(domainAndTld); + } catch { + return false; + } +}; + +/** + * Plugin for all endpoints related to user settings. + * + * @param fastify The Fastify instance. + * @param _options Fastify options I guess? + * @param done Callback to signal that the logic has completed. + */ +export const settingRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.setErrorHandler((error: FastifyError, request, reply) => { + if (error.validation) { + request.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400); + void reply.send({ message: 'flash.wrong-updating', type: 'danger' }); + } else { + throw error; + } + }); + + fastify.put( + '/update-my-profileui', + { + schema: schemas.updateMyProfileUI + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + profileUI: { + isLocked: req.body.profileUI.isLocked, + showAbout: req.body.profileUI.showAbout, + showCerts: req.body.profileUI.showCerts, + showDonation: req.body.profileUI.showDonation, + showHeatMap: req.body.profileUI.showHeatMap, + showLocation: req.body.profileUI.showLocation, + showName: req.body.profileUI.showName, + showPoints: req.body.profileUI.showPoints, + showPortfolio: req.body.profileUI.showPortfolio, + showExperience: req.body.profileUI.showExperience, + showTimeLine: req.body.profileUI.showTimeLine + } + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'profile_ui' } + }); + + return { + message: 'flash.privacy-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating profileUI'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + function createUpdateEmailText({ email, id }: { email: string; id: string }) { + const encodedEmail = Buffer.from(email).toString('base64'); + return `Please confirm this email address for freeCodeCamp.org: + +${API_LOCATION}/confirm-email?email=${encodedEmail}&token=${id}&emailChange=true + +Happy coding! + +- The freeCodeCamp.org Team +`; + } + + fastify.put( + '/update-my-email', + { + schema: schemas.updateMyEmail, + // We need to customize the responses to validation failures: + attachValidation: true + }, + async (req, reply) => { + if (req.validationError) { + req.log.warn('Invalid email format'); + void reply.code(400); + return { message: 'Email format is invalid', type: 'danger' } as const; + } + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id }, + select: { + id: true, + email: true, + emailVerifyTTL: true, + newEmail: true, + emailVerified: true, + emailAuthLinkTTL: true + } + }); + const newEmail = req.body.email.toLowerCase(); + const currentEmailFormatted = user.email ? user.email.toLowerCase() : ''; + const isVerifiedEmail = user.emailVerified; + const isOwnEmail = newEmail === currentEmailFormatted; + if (isOwnEmail && isVerifiedEmail) { + req.log.warn( + 'New email address is already associated with this account' + ); + void reply.code(400); + return reply.send({ + type: 'info', + message: `${newEmail} is already associated with this account. +You can update a new email address instead.` + }); + } + + const isResendUpdateToSameEmail = + newEmail === user.newEmail?.toLowerCase(); + const isLinkSentWithinLimitTTL = getWaitMessage({ + sentAt: user.emailVerifyTTL + }); + + if (isResendUpdateToSameEmail && isLinkSentWithinLimitTTL) { + req.log.warn( + 'Email confirmation link has been sent within the last 5 minutes' + ); + void reply.code(429); + return reply.send({ + type: 'info', + message: `We have already sent an email confirmation request to ${newEmail}. +${isLinkSentWithinLimitTTL}` + }); + } + + const isEmailAlreadyTaken = + (await fastify.prisma.user.count({ where: { email: newEmail } })) > 0; + + if (isEmailAlreadyTaken && !isOwnEmail) { + req.log.warn( + 'New email address is already associated with another account' + ); + void reply.code(400); + return reply.send({ + type: 'info', + message: `${newEmail} is already associated with another account.` + }); + } + + // ToDo(MVP): email the new email and wait user to confirm it, before we update the user schema. + try { + // TODO: combine emailVerifyTTL and emailAuthLinkTTL? I'm not sure why + // we need emailVeriftyTTL given that the main thing we want is to + // restrict the rate of attempts and the emailAuthLinkTTL already does + // that. + // This check has to happen before the user is updated, otherwise a + // rate-limited request would still overwrite the pending email and + // invalidate the confirmation link sent for it. + const tooManyRequestsMessage = getWaitMessage({ + sentAt: user.emailAuthLinkTTL + }); + + if (tooManyRequestsMessage) { + req.log.warn( + 'Email confirmation link has been sent within the last 5 minutes' + ); + void reply.code(429); + return reply.send({ + type: 'info', + message: tooManyRequestsMessage + }); + } + + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + newEmail, + emailVerified: false, + emailVerifyTTL: new Date() + } + }); + + // Update the emailAuthLinkTTL to ensure we don't send too many emails. + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + emailAuthLinkTTL: new Date() + } + }); + + // The auth token is used to confirm that the user owns the email. If + // the user provides the correct id (by following the link we send + // them), then we can update the email. + const { id } = await fastify.prisma.authToken.create({ + data: createAuthToken(user.id), + select: { id: true } + }); + + await fastify.sendEmail({ + from: 'team@freecodecamp.org', + to: newEmail, + subject: + 'Please confirm your updated email address for freeCodeCamp.org', + text: createUpdateEmailText({ email: newEmail, id }) + }); + + fastify.Sentry?.metrics?.count('settings.email_change_requested', 1); + + await reply.send({ + message: + 'Check your email and click the link we sent you to confirm your new email address.', + type: 'info' + }); + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating email address'); + void reply.code(500); + await reply.send({ message: 'flash.wrong-updating', type: 'danger' }); + } + } + ); + + fastify.put( + '/update-my-theme', + { + schema: schemas.updateMyTheme + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + theme: req.body.theme + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'theme' } + }); + + return { + message: 'flash.updated-themes', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating theme'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-socials', + { + schema: schemas.updateMySocials + }, + async (req, reply) => { + const socials = { + twitter: req.body.twitter, + bluesky: req.body.bluesky, + githubProfile: req.body.githubProfile, + linkedin: req.body.linkedin, + website: req.body.website + }; + + const valid = ( + ['twitter', 'bluesky', 'githubProfile', 'linkedin'] as const + ).every(key => validateSocialUrl(socials[key], key)); + + if (!valid) { + req.log.warn( + { + invalidSocials: ( + ['twitter', 'bluesky', 'githubProfile', 'linkedin'] as const + ).filter(key => !validateSocialUrl(socials[key], key)) + }, + 'Invalid social URL' + ); + (['twitter', 'bluesky', 'githubProfile', 'linkedin'] as const) + .filter(key => !validateSocialUrl(socials[key], key)) + .forEach(provider => { + fastify.Sentry?.metrics?.count('settings.social_url_rejected', 1, { + attributes: { provider } + }); + }); + void reply.code(400); + return reply.send({ + message: 'flash.wrong-updating', + type: 'danger' + }); + } + + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + website: socials.website, + twitter: socials.twitter, + bluesky: socials.bluesky, + githubProfile: socials.githubProfile, + linkedin: socials.linkedin + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'socials' } + }); + + return { + message: 'flash.updated-socials', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating socials'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-username', + { + schema: schemas.updateMyUsername, + attachValidation: true + }, + async (req, reply) => { + try { + const user = await fastify.prisma.user.findFirstOrThrow({ + where: { id: req.user?.id } + }); + + const newUsernameDisplay = req.body.username.trim(); + const oldUsernameDisplay = user.usernameDisplay?.trim(); + + const newUsername = newUsernameDisplay.toLowerCase(); + const oldUsername = user.username.toLowerCase(); + + const usernameUnchanged = + newUsername === oldUsername && + newUsernameDisplay === oldUsernameDisplay; + + if (usernameUnchanged) { + req.log.warn('Username is unchanged'); + fastify.Sentry?.metrics?.count( + 'settings.username_change_rejected', + 1, + { + attributes: { reason: 'unchanged' } + } + ); + void reply.code(400); + return { + message: 'flash.username-used', + type: 'info' + } as const; + } + + if (req.validationError) { + req.log.warn( + { username: req.body.username }, + 'Bad request. Invalid username supplied' + ); + void reply.code(400); + return { + message: req.validationError.message, + type: 'info' + } as const; + } + + const validation = isValidUsername(newUsername); + + if (!validation.valid) { + req.log.warn( + { username: newUsername, validationError: validation.error }, + 'Invalid username' + ); + fastify.Sentry?.metrics?.count( + 'settings.username_change_rejected', + 1, + { + attributes: { reason: 'invalid' } + } + ); + void reply.code(400); + return reply.send({ + // TODO(Post-MVP): custom validation errors. + message: `Username ${newUsername} ${validation.error}`, + type: 'info' + }); + } + + const usernameTaken = + newUsername === oldUsername + ? false + : await fastify.prisma.user.count({ + where: { username: newUsername } + }); + + if (usernameTaken || isRestricted(newUsername)) { + const reason = usernameTaken + ? 'username_taken' + : 'username_restricted'; + req.log.warn( + { username: newUsername, reason }, + 'Username is taken or restricted' + ); + fastify.Sentry?.metrics?.count( + 'settings.username_change_rejected', + 1, + { + attributes: { reason } + } + ); + void reply.code(400); + return reply.send({ + message: usernameTaken + ? 'flash.username-taken' + : 'flash.username-restricted', + type: 'info' + }); + } + + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + username: newUsername, + usernameDisplay: newUsernameDisplay + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'username' } + }); + + return reply.send({ + message: 'flash.username-updated', + type: 'success', + variables: { username: newUsernameDisplay } + }); + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating username'); + void reply.code(500); + await reply.send({ message: 'flash.wrong-updating', type: 'danger' }); + } + } + ); + + fastify.put( + '/update-my-about', + { + schema: schemas.updateMyAbout + }, + async (req, reply) => { + // No need to validate if picture is being deleted. + if (req.body.picture) { + if (req.body.picture !== req.user!.picture) { + if (!isValidPictureUrl(req.body.picture)) { + req.log.warn( + { + hasPicture: !!req.body.picture, + pictureLength: req.body.picture?.length + }, + 'Invalid picture URL' + ); + void reply.code(400); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + } + + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + about: req.body.about, + name: req.body.name, + location: req.body.location, + picture: req.body.picture + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'about' } + }); + + return { + message: 'flash.updated-about-me', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating about'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-keyboard-shortcuts', + { + schema: schemas.updateMyKeyboardShortcuts + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + keyboardShortcuts: req.body.keyboardShortcuts + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'keyboard_shortcuts' } + }); + + return { + message: 'flash.keyboard-shortcut-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating keyboard shortcuts'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-quincy-email', + { + schema: schemas.updateMyQuincyEmail + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + sendQuincyEmail: req.body.sendQuincyEmail + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'quincy_email' } + }); + + return { + message: 'flash.subscribe-to-quincy-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating Quincy email preference'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-socrates', + { + schema: schemas.updateSocrates + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + socrates: req.body.socrates + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'socrates' } + }); + + return { + message: 'flash.socrates-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating Socrates preference'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-honesty', + { + schema: schemas.updateMyHonesty + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + isHonest: req.body.isHonest + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'honesty' } + }); + + return { + message: 'buttons.accepted-honesty', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating honesty'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-privacy-terms', + { + schema: schemas.updateMyPrivacyTerms + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + acceptedPrivacyTerms: true, + sendQuincyEmail: req.body.quincyEmails + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'privacy_terms' } + }); + + return { + message: 'flash.privacy-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating privacy terms'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-portfolio', + { + schema: schemas.updateMyPortfolio + }, + async (req, reply) => { + try { + // TODO(Post-MVP): make all properties required in the schema and use + // req.body.portfolio directly. + const portfolio = req.body.portfolio.map( + ({ id, title, url, description, image }) => ({ + id: id ? id : '', + title: title ? title : '', + url: url ? url : '', + description: description ? description : '', + image: image ? image : '' + }) + ); + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + portfolio + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'portfolio' } + }); + + return { + message: 'flash.portfolio-item-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating portfolio'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + fastify.put( + '/update-my-experience', + { + schema: schemas.updateMyExperience + }, + async (req, reply) => { + try { + const { experience } = req.body; + + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + experience + } + }); + + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'experience' } + }); + + return { + message: 'flash.experience-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating experience'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + // See updateMyClassroomMode schema for one-way constraint details. + fastify.put( + '/update-my-classroom-mode', + { + schema: schemas.updateMyClassroomMode + }, + async (req, reply) => { + try { + await fastify.prisma.user.update({ + where: { id: req.user?.id }, + data: { + isClassroomAccount: req.body.isClassroomAccount + } + }); + + fastify.Sentry?.metrics?.count('settings.classroom_mode_toggled', 1, { + attributes: { enabled: req.body.isClassroomAccount } + }); + fastify.Sentry?.metrics?.count('settings.updated', 1, { + attributes: { field: 'classroom_mode' } + }); + + return { + message: 'flash.classroom-mode-updated', + type: 'success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error updating classroom mode'); + void reply.code(500); + return { message: 'flash.wrong-updating', type: 'danger' } as const; + } + } + ); + + done(); +}; + +/** + * Plugin for endpoints that redirect if the user is not authenticated. + * + * @param fastify The Fastify instance. + * @param _options Options for the plugin. + * @param done Callback to signal that the logic has completed. + */ +export const settingRedirectRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + const redirectMessage = { + type: 'danger', + content: + 'Oops! Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.' + } as const; + + const expirationMessage = { + type: 'info', + content: + 'The link to confirm your new email address has expired. Please try again.' + } as const; + + const successMessage = { + type: 'success', + content: 'flash.email-valid' + } as const; + + async function updateEmail( + fastify: FastifyInstance, + { id, email }: { id: string; email: string } + ) { + await fastify.prisma.user.update({ + where: { id }, + data: { + email, + emailAuthLinkTTL: null, + emailVerified: true, + emailVerifyTTL: null, + newEmail: null + } + }); + } + + async function deleteAuthToken( + fastify: FastifyInstance, + { id }: { id: string } + ) { + await fastify.prisma.authToken.delete({ + where: { id } + }); + } + + fastify.get( + '/confirm-email', + { + schema: schemas.confirmEmail, + errorHandler(error, request, reply) { + if (error.validation) { + request.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + const { origin } = getRedirectParams(request); + void reply.redirectWithMessage(origin, redirectMessage); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + const email = Buffer.from(req.query.email, 'base64').toString(); + + const { origin } = getRedirectParams(req); + if (!validator.default.isEmail(email)) { + req.log.warn({ userId: req.user?.id }, 'Invalid email format'); + fastify.Sentry?.metrics?.count('settings.email_confirm_rejected', 1, { + attributes: { reason: 'invalid_email' } + }); + return reply.redirectWithMessage(origin, redirectMessage); + } + + const authToken = await fastify.prisma.authToken.findUnique({ + where: { id: req.query.token } + }); + + if (!authToken) { + req.log.warn('No token found'); + fastify.Sentry?.metrics?.count('settings.email_confirm_rejected', 1, { + attributes: { reason: 'no_token' } + }); + return reply.redirectWithMessage(origin, redirectMessage); + } + + // TODO(Post-MVP): clean up expired auth tokens. + if (isExpired(authToken)) { + req.log.warn('Token expired'); + fastify.Sentry?.metrics?.count('settings.email_confirm_rejected', 1, { + attributes: { reason: 'expired' } + }); + return reply.redirectWithMessage(origin, expirationMessage); + } + + const targetUser = await fastify.prisma.user.findUnique({ + where: { id: authToken.userId } + }); + + if (targetUser?.id !== req.user?.id) { + req.log.warn('Target user does not match signed in user'); + fastify.Sentry?.metrics?.count('settings.email_confirm_rejected', 1, { + attributes: { reason: 'user_mismatch' } + }); + return reply.redirectWithMessage(origin, redirectMessage); + } + + if (targetUser?.newEmail !== email) { + fastify.Sentry?.metrics?.count('settings.email_confirm_rejected', 1, { + attributes: { reason: 'email_mismatch' } + }); + return reply.redirectWithMessage(origin, redirectMessage); + } + + // TODO(Post-MVP): clean up any other auth tokens for this user once + // the email is confirmed. + await Promise.all([ + updateEmail(fastify, { id: targetUser.id, email }), + deleteAuthToken(fastify, { id: authToken.id }) + ]); + + fastify.Sentry?.metrics?.count('settings.email_confirmed', 1); + + return reply.redirectWithMessage(origin, successMessage); + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..83e00dacdeecdd403cce11f508608d144ccda127 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.test.ts @@ -0,0 +1,772 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +import { + describe, + test, + expect, + beforeAll, + beforeEach, + afterEach, + vi +} from 'vitest'; +import { + devLogin, + setupServer, + createSuperRequest, + defaultUserId +} from '../../../vitest.utils.js'; + +const mockedFetch = vi.fn(); +vi.stubGlobal('fetch', mockedFetch); + +const validPayload = { + description: 'Make the text say hello', + userInput: 'Hello world', + seed: '

Hello

', + hints: [{ text: 'Check your spelling', failed: true }] +}; + +describe('socratesRoutes', () => { + setupServer(); + + describe('Authenticated user', () => { + let superPut: ReturnType; + + beforeAll(async () => { + const setCookies = await devLogin(); + superPut = createSuperRequest({ method: 'PUT', setCookies }); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.restoreAllMocks(); + }); + + describe('PUT /socrates/get-hint', () => { + test('should return 403 when user has socrates explicitly disabled', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { socrates: false } + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(403); + expect(response.body).toStrictEqual({ + error: 'socrates-no-access', + type: 'danger', + attempts: 0, + limit: 0 + }); + expect(mockedFetch).not.toHaveBeenCalled(); + }); + + test('should allow access when socrates is null (default)', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { socrates: null } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => + Promise.resolve( + JSON.stringify({ hint: 'Try adding a closing tag.' }) + ) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('hint'); + }); + + describe('with socrates enabled', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { socrates: true } + }); + await fastifyTestInstance.prisma.socratesUsage.deleteMany({ + where: { userId: defaultUserId } + }); + }); + + test('should return hint on successful Socrates API response', async () => { + const { Sentry } = fastifyTestInstance; + const count = vi.fn(); + const distribution = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + metrics: { ...Sentry.metrics, count, distribution } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => + Promise.resolve( + JSON.stringify({ hint: 'Try adding a closing tag.' }) + ) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body).toStrictEqual({ + hint: 'Try adding a closing tag.', + attempts: 1, + limit: 3 + }); + expect(count).toHaveBeenCalledWith('socrates.hint_granted', 1, { + attributes: { donorStatus: 'non-donor' } + }); + expect(distribution).toHaveBeenCalledWith( + 'socrates.upstream_latency_ms', + expect.any(Number), + { unit: 'millisecond', attributes: { result: 'success' } } + ); + }); + + test('should pass session userId, not client-supplied userId', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + await superPut('/socrates/get-hint').send({ + ...validPayload + }); + + const fetchCall = mockedFetch.mock.calls[0]!; + const body = JSON.parse(fetchCall[1].body as string) as { + userId: string; + }; + expect(body.userId).toBe(defaultUserId); + }); + + test('should use session userId even when userId is sent in body', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + await superPut('/socrates/get-hint').send({ + ...validPayload, + userId: 'attacker-id' + }); + + const fetchCall = mockedFetch.mock.calls[0]!; + const body = JSON.parse(fetchCall[1].body as string) as { + userId: string; + }; + expect(body.userId).toBe(defaultUserId); + expect(body.userId).not.toBe('attacker-id'); + }); + + test('should drop unknown keys before the upstream call (locks removeAdditional: all)', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + await superPut('/socrates/get-hint').send({ + ...validPayload, + challengeType: 'rust', + hints: [{ text: 'Check your spelling', failed: true, id: 7 }] + }); + + const fetchCall = mockedFetch.mock.calls[0]!; + const body = JSON.parse(fetchCall[1].body as string) as Record< + string, + unknown + >; + expect(Object.keys(body).sort()).toStrictEqual([ + 'description', + 'hints', + 'seed', + 'userId', + 'userInput' + ]); + expect(body.hints).toStrictEqual([ + { text: 'Check your spelling', failed: true } + ]); + }); + + test('should return 429 when Socrates API rate limits', async () => { + const { Sentry } = fastifyTestInstance; + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: false, + status: 429, + text: () => Promise.resolve('') + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(429); + expect(response.body).toStrictEqual({ + error: 'socrates-rate-limit', + type: 'info', + attempts: 0, + limit: 3 + }); + expect(count).toHaveBeenCalledWith('socrates.rate_limit_hit', 1, { + attributes: { source: 'upstream', donorStatus: 'non-donor' } + }); + }); + + test.each([ + [ + 'a Socrates JSON body', + JSON.stringify({ + message: 'Prompt too long: 43531 characters (max 32000)', + status: 400 + }) + ], + ['an empty body', ''], + ['an HTML body', 'Blocked'] + ])( + 'should send the generic client error on 400 with %s', + async (_label, upstreamBody) => { + const { Sentry } = fastifyTestInstance; + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: false, + status: 400, + text: () => Promise.resolve(upstreamBody) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(400); + expect(response.body).toStrictEqual({ + error: 'socrates-unable-to-generate', + type: 'info', + attempts: 0, + limit: 3 + }); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'bad_status' } } + ); + } + ); + + test('should return 500 and capture on other Socrates API errors', async () => { + const { Sentry } = fastifyTestInstance; + const captureException = vi.fn(); + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + captureException, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: false, + status: 503, + text: () => Promise.resolve('Service Unavailable') + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(response.body).toStrictEqual({ + error: 'socrates-unavailable', + type: 'danger', + attempts: 0, + limit: 3 + }); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: 'Socrates API returned status 503' + }) + ); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'bad_status' } } + ); + }); + + test('should return 500 and capture when Socrates API returns invalid JSON', async () => { + const { Sentry } = fastifyTestInstance; + const captureException = vi.fn(); + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + captureException, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve('not json') + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(response.body.type).toBe('danger'); + expect(response.body.attempts).toBe(0); + expect(response.body.limit).toBe(3); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.any(Error) + ); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'invalid_response' } } + ); + }); + + test('should return 500 and capture when Socrates API returns no hint', async () => { + const { Sentry } = fastifyTestInstance; + const captureException = vi.fn(); + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + captureException, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ foo: 'bar' })) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(response.body.type).toBe('danger'); + expect(response.body.attempts).toBe(0); + expect(response.body.limit).toBe(3); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + message: 'Socrates API did not return a hint' + }) + ); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'missing_hint' } } + ); + }); + + test('should return 500 when fetch throws', async () => { + mockedFetch.mockRejectedValueOnce(new Error('Network error')); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(response.body).toStrictEqual({ + error: 'socrates-unavailable', + type: 'danger', + attempts: 0, + limit: 3 + }); + }); + + test('should not capture a fetch network failure', async () => { + const { Sentry } = fastifyTestInstance; + const captureException = vi.fn(); + const count = vi.fn(); + const distribution = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + captureException, + metrics: { ...Sentry.metrics, count, distribution } + }); + + const networkError = Object.assign(new TypeError('fetch failed'), { + cause: Object.assign(new Error('connect ECONNREFUSED'), { + code: 'ECONNREFUSED' + }) + }); + mockedFetch.mockRejectedValueOnce(networkError); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'network' } } + ); + expect(distribution).toHaveBeenCalledWith( + 'socrates.upstream_latency_ms', + expect.any(Number), + { unit: 'millisecond', attributes: { result: 'failure' } } + ); + }); + + test('should capture a genuine TypeError bug from the handler', async () => { + const { Sentry } = fastifyTestInstance; + const captureException = vi.fn(); + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + captureException, + metrics: { ...Sentry.metrics, count } + }); + + const bugError = new TypeError( + "Cannot read properties of undefined (reading 'foo')" + ); + mockedFetch.mockRejectedValueOnce(bugError); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledExactlyOnceWith(bugError); + expect(count).toHaveBeenCalledWith( + 'socrates.upstream_call_failed', + 1, + { attributes: { reason: 'exception' } } + ); + }); + }); + + describe('daily usage entitlements', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { socrates: true, isDonating: false } + }); + await fastifyTestInstance.prisma.socratesUsage.deleteMany({ + where: { userId: defaultUserId } + }); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + test('should return attempts=1 and limit=3 on first hint for non-donor', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body.attempts).toBe(1); + expect(response.body.limit).toBe(3); + }); + + test('should increment attempts on each request', async () => { + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + await superPut('/socrates/get-hint').send(validPayload); + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body.attempts).toBe(2); + }); + + test('should return 429 when non-donor exceeds 3 hints/day', async () => { + const { Sentry } = fastifyTestInstance; + const count = vi.fn(); + vi.spyOn(fastifyTestInstance, 'Sentry', 'get').mockReturnValue({ + ...Sentry, + metrics: { ...Sentry.metrics, count } + }); + + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + for (let i = 0; i < 3; i++) { + await superPut('/socrates/get-hint').send(validPayload); + } + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(429); + expect(response.body.attempts).toBe(3); + expect(response.body.limit).toBe(3); + expect(response.body.error).toBe('socrates-daily-limit'); + expect(mockedFetch).toHaveBeenCalledTimes(3); + expect(count).toHaveBeenCalledWith('socrates.rate_limit_hit', 1, { + attributes: { source: 'local', donorStatus: 'non-donor' } + }); + }); + + test('should not inflate count beyond limit on repeated 429s', async () => { + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + // Exhaust the non-donor limit + for (let i = 0; i < 3; i++) { + await superPut('/socrates/get-hint').send(validPayload); + } + + // Make extra requests that should all be 429 + for (let i = 0; i < 5; i++) { + const res = await superPut('/socrates/get-hint').send(validPayload); + expect(res.status).toBe(429); + } + + // Upgrade to donor (limit: 10) and verify access is restored + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isDonating: true } + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body.attempts).toBe(4); + expect(response.body.limit).toBe(10); + }); + + test('should enforce the non-donor limit for concurrent requests', async () => { + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + const results = await Promise.allSettled( + Array.from({ length: 20 }, () => + superPut('/socrates/get-hint').send(validPayload) + ) + ); + const rejected = results.filter( + result => result.status === 'rejected' + ); + expect(rejected).toEqual([]); + const responses = results + .filter(result => result.status === 'fulfilled') + .map(result => result.value); + + expect(responses.filter(({ status }) => status === 200)).toHaveLength( + 3 + ); + expect(responses.filter(({ status }) => status === 429)).toHaveLength( + 17 + ); + expect(mockedFetch).toHaveBeenCalledTimes(3); + + const now = new Date(); + const usage = + await fastifyTestInstance.prisma.socratesUsage.findUniqueOrThrow({ + where: { + userId_date: { + userId: defaultUserId, + date: new Date( + Date.UTC( + now.getUTCFullYear(), + now.getUTCMonth(), + now.getUTCDate() + ) + ) + } + } + }); + expect(usage.count).toBe(3); + }); + + test('should allow 10 hints/day for donors', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isDonating: true } + }); + + mockedFetch.mockResolvedValue({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + let response = + await superPut('/socrates/get-hint').send(validPayload); + expect(response.status).toBe(200); + + for (let i = 1; i < 10; i++) { + response = await superPut('/socrates/get-hint').send(validPayload); + expect(response.status).toBe(200); + } + + expect(response.body.attempts).toBe(10); + expect(response.body.limit).toBe(10); + + response = await superPut('/socrates/get-hint').send(validPayload); + expect(response.status).toBe(429); + }); + + test('should not consume an attempt on upstream API error', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: false, + status: 500, + text: () => Promise.resolve('Server Error') + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(500); + expect(response.body.attempts).toBe(0); + expect(response.body.limit).toBe(3); + }); + + test('should not count yesterday usage against today limit', async () => { + const yesterday = new Date(); + yesterday.setUTCDate(yesterday.getUTCDate() - 1); + const yesterdayUTC = new Date( + Date.UTC( + yesterday.getUTCFullYear(), + yesterday.getUTCMonth(), + yesterday.getUTCDate() + ) + ); + + await fastifyTestInstance.prisma.socratesUsage.create({ + data: { userId: defaultUserId, date: yesterdayUTC, count: 3 } + }); + + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => Promise.resolve(JSON.stringify({ hint: 'A hint.' })) + }); + + const response = + await superPut('/socrates/get-hint').send(validPayload); + + expect(response.status).toBe(200); + expect(response.body.attempts).toBe(1); + }); + }); + + describe('validation', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { socrates: true } + }); + }); + + test('should return 400 when userInput is empty string', async () => { + const response = await superPut('/socrates/get-hint').send({ + ...validPayload, + userInput: '' + }); + + expect(response.status).toBe(400); + expect(response.body).toStrictEqual({ + error: 'socrates-invalid-request', + type: 'info', + attempts: 0, + limit: 0 + }); + expect(mockedFetch).not.toHaveBeenCalled(); + }); + + test('should accept request without userInput', async () => { + mockedFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + text: () => + Promise.resolve( + JSON.stringify({ hint: 'Try adding a closing tag.' }) + ) + }); + + const { userInput: _unused, ...payloadWithoutUserInput } = + validPayload; + const response = await superPut('/socrates/get-hint').send( + payloadWithoutUserInput + ); + + expect(response.status).toBe(200); + expect(response.body).toHaveProperty('hint'); + expect(mockedFetch).toHaveBeenCalledTimes(1); + }); + + test('should return 400 when seed is empty', async () => { + const response = await superPut('/socrates/get-hint').send({ + ...validPayload, + seed: '' + }); + + expect(response.status).toBe(400); + expect(mockedFetch).not.toHaveBeenCalled(); + }); + + test('should return 400 when description is empty', async () => { + const response = await superPut('/socrates/get-hint').send({ + ...validPayload, + description: '' + }); + + expect(response.status).toBe(400); + expect(mockedFetch).not.toHaveBeenCalled(); + }); + + test('should return 400 when required fields are missing', async () => { + const response = await superPut('/socrates/get-hint').send({}); + + expect(response.status).toBe(400); + expect(mockedFetch).not.toHaveBeenCalled(); + }); + }); + }); + }); + + describe('Unauthenticated user', () => { + test('should not return a hint for unauthenticated requests', async () => { + const response = await createSuperRequest({ method: 'PUT' })( + '/socrates/get-hint' + ).send(validPayload); + + // Unauthenticated requests fail before reaching the route handler + expect(response.status).not.toBe(200); + expect(response.body).not.toHaveProperty('hint'); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e9d56a8d67d48ef25b674e7d38490de9ada096f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/socrates.ts @@ -0,0 +1,296 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import * as schemas from '../../schemas.js'; +import { SOCRATES_API_KEY, SOCRATES_ENDPOINT } from '../../utils/env.js'; +import { mapErr } from '../../utils/index.js'; +import { Prisma } from '@prisma/client'; + +const DAILY_LIMITS = { donor: 10, nonDonor: 3 } as const; + +function getDailyLimit(isDonating: boolean): number { + return isDonating ? DAILY_LIMITS.donor : DAILY_LIMITS.nonDonor; +} + +const NETWORK_ERROR_CODES = new Set([ + 'ENOTFOUND', + 'ECONNREFUSED', + 'ECONNRESET', + 'ETIMEDOUT', + 'EAI_AGAIN' +]); + +function isFetchNetworkError(error: unknown): boolean { + if (!(error instanceof TypeError)) { + return false; + } + const cause = (error as { cause?: unknown }).cause; + const code = + cause && typeof cause === 'object' && 'code' in cause + ? (cause as { code?: unknown }).code + : undefined; + if (typeof code === 'string') { + return code.startsWith('UND_ERR_') || NETWORK_ERROR_CODES.has(code); + } + return error.message === 'fetch failed'; +} + +/** + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const socratesRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + // Socrates plugin + fastify.put( + '/socrates/get-hint', + { + schema: schemas.askSocrates, + errorHandler(error, req, reply) { + if (error.validation) { + void reply.status(400).send({ + error: 'socrates-invalid-request', + type: 'info', + attempts: 0, + limit: 0 + }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + if (!req.user || req.user.socrates === false) { + return reply.status(403).send({ + error: 'socrates-no-access', + type: 'danger', + attempts: 0, + limit: 0 + }); + } + + const limit = getDailyLimit(req.user.isDonating); + const donorStatus = req.user.isDonating ? 'donor' : 'non-donor'; + const now = new Date(); + const todayUTC = new Date( + Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) + ); + const userId = req.user.id; + + const res = await mapErr( + fastify.prisma.$runCommandRaw({ + findAndModify: 'SocratesUsage', + query: { + userId: { $oid: userId }, + date: { $date: todayUTC.toISOString() }, + count: { $lt: limit } + }, + update: { $inc: { count: 1 } }, + upsert: true, + new: true + }) + ); + + if (res.hasError) { + const error = res.error; + // Doc exists but is at the limit. + // - query does not match + // - upsert tries insert + // - unique index rejects + if ( + error instanceof Prisma.PrismaClientKnownRequestError && + error.code === 'P2010' && + /11000|DuplicateKey/.test(error.message) + ) { + fastify.Sentry?.metrics?.count('socrates.rate_limit_hit', 1, { + attributes: { source: 'local', donorStatus } + }); + return reply.status(429).send({ + error: 'socrates-daily-limit', + type: 'info', + attempts: limit, + limit + }); + } + + // Bad error running query. + throw error; + } + + type FindAndModifyResult = { value: { count: number } }; + const data = res.data as FindAndModifyResult; + + const attempts = data.value.count; + + const rollbackUsage = async () => { + await fastify.prisma.socratesUsage.update({ + where: { + userId_date: { userId: req.user!.id, date: todayUTC } + }, + data: { count: { decrement: 1 } } + }); + }; + + const upstreamFetchStart = performance.now(); + + try { + const response = await fetch(`${SOCRATES_ENDPOINT}/hint`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': SOCRATES_API_KEY + }, + body: JSON.stringify({ + description: req.body.description, + userInput: req.body.userInput, + seed: req.body.seed, + hints: req.body.hints, + userId: req.user.id + }) + }); + + fastify.Sentry?.metrics?.distribution( + 'socrates.upstream_latency_ms', + performance.now() - upstreamFetchStart, + { unit: 'millisecond', attributes: { result: 'success' } } + ); + + const responseText = await response.text(); + + if (!response.ok) { + req.log.error( + { + status: response.status, + upstreamBody: responseText.slice(0, 500) + }, + 'Socrates API returned an error response.' + ); + + await rollbackUsage(); + + if (response.status === 429) { + fastify.Sentry?.metrics?.count('socrates.rate_limit_hit', 1, { + attributes: { source: 'upstream', donorStatus } + }); + return reply.status(429).send({ + error: 'socrates-rate-limit', + type: 'info', + attempts: attempts - 1, + limit + }); + } + + if (response.status === 400) { + fastify.Sentry?.metrics?.count('socrates.upstream_call_failed', 1, { + attributes: { reason: 'bad_status' } + }); + return reply.status(400).send({ + error: 'socrates-unable-to-generate', + type: 'info', + attempts: attempts - 1, + limit + }); + } + + fastify.Sentry?.captureException( + new Error(`Socrates API returned status ${response.status}`) + ); + fastify.Sentry?.metrics?.count('socrates.upstream_call_failed', 1, { + attributes: { reason: 'bad_status' } + }); + return reply.status(500).send({ + error: 'socrates-unavailable', + type: 'danger', + attempts: attempts - 1, + limit + }); + } + + let payload: unknown; + try { + payload = responseText ? JSON.parse(responseText) : null; + } catch (error) { + fastify.Sentry?.captureException(error); + fastify.Sentry?.metrics?.count('socrates.upstream_call_failed', 1, { + attributes: { reason: 'invalid_response' } + }); + req.log.error( + { err: error }, + 'Failed to parse Socrates API response.' + ); + await rollbackUsage(); + return reply.status(500).send({ + error: 'socrates-unavailable', + type: 'danger', + attempts: attempts - 1, + limit + }); + } + + if ( + !payload || + typeof payload !== 'object' || + typeof (payload as { hint?: unknown }).hint !== 'string' + ) { + fastify.Sentry?.captureException( + new Error('Socrates API did not return a hint') + ); + fastify.Sentry?.metrics?.count('socrates.upstream_call_failed', 1, { + attributes: { reason: 'missing_hint' } + }); + req.log.error( + { + payloadType: payload === null ? 'null' : typeof payload, + hintType: typeof (payload as { hint?: unknown } | null)?.hint + }, + 'Socrates API did not return a hint.' + ); + await rollbackUsage(); + return reply.status(500).send({ + error: 'socrates-unavailable', + type: 'danger', + attempts: attempts - 1, + limit + }); + } + + const { hint } = payload as { hint: string }; + + fastify.Sentry?.metrics?.count('socrates.hint_granted', 1, { + attributes: { donorStatus } + }); + return { hint, attempts, limit } as const; + } catch (error) { + fastify.Sentry?.metrics?.distribution( + 'socrates.upstream_latency_ms', + performance.now() - upstreamFetchStart, + { unit: 'millisecond', attributes: { result: 'failure' } } + ); + if (!isFetchNetworkError(error)) { + fastify.Sentry?.captureException(error); + } + fastify.Sentry?.metrics?.count('socrates.upstream_call_failed', 1, { + attributes: { + reason: isFetchNetworkError(error) ? 'network' : 'exception' + } + }); + req.log.error( + { err: error }, + 'Failed to fetch hint from Socrates API.' + ); + await rollbackUsage(); + return reply.status(500).send({ + error: 'socrates-unavailable', + type: 'danger', + attempts: attempts - 1, + limit + }); + } + } + ); + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..414b2923601765dd1250ac45710ca11198d84a4c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.test.ts @@ -0,0 +1,2489 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-unsafe-argument */ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import { + describe, + test, + expect, + beforeEach, + afterEach, + beforeAll, + afterAll, + vi, + MockInstance +} from 'vitest'; +import jwt, { JwtPayload } from 'jsonwebtoken'; +import { DailyCodingChallengeLanguage, type Prisma } from '@prisma/client'; +import { ObjectId } from 'bson'; +import { omit } from 'lodash-es'; + +import { createUserInput } from '../../utils/create-user.js'; +import { + defaultUserId, + defaultUserEmail, + devLogin, + setupServer, + superRequest, + createSuperRequest, + defaultUsername, + resetDefaultUser +} from '../../../vitest.utils.js'; +import { JWT_SECRET } from '../../utils/env.js'; +import { + clearEnvExam, + seedEnvExam, + seedEnvExamAttempt, + seedExamEnvExamAuthToken +} from '../../../__fixtures__/exam-environment-exam.js'; +import * as getChallengesModule from '../../utils/get-challenges.js'; +import { getMsTranscriptApiUrl } from './user.js'; + +const mockedFetch = vi.fn(); +vi.spyOn(globalThis, 'fetch').mockImplementation(mockedFetch); + +let mockDeploymentEnv = 'staging'; +vi.mock('../../utils/env', async () => { + const actualEnv = + await vi.importActual( + '../../utils/env' + ); + return { + ...actualEnv, + get DEPLOYMENT_ENV() { + return mockDeploymentEnv; + }, + JWT_SECRET: actualEnv.JWT_SECRET + }; +}); + +// This is used to build a test user. +const testUserData: Prisma.userCreateInput = { + ...createUserInput(defaultUserEmail), + username: 'foobar', + usernameDisplay: 'Foo Bar', + progressTimestamps: [1520002973119, 1520440323273], + completedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + solution: null, + challengeType: 5, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2' + } + ] + }, + { + id: 'a5229172f011153519423690', + completedDate: 1520440323273, + solution: null, + challengeType: 5, + files: [] + }, + { + id: 'a5229172f011153519423692', + completedDate: 1520440323274, + githubLink: '', + challengeType: 5, + examResults: { + numberOfCorrectAnswers: 0, + numberOfQuestionsInExam: 0, + percentCorrect: 0, + passingPercent: 0, + passed: false, + examTimeInSeconds: 0 + } + } + ], + completedDailyCodingChallenges: [ + { + id: '5900f36e1000cf542c50fe80', + completedDate: 1742941672524, + languages: [ + DailyCodingChallengeLanguage.python, + DailyCodingChallengeLanguage.javascript + ] + } + ], + partiallyCompletedChallenges: [{ id: '123', completedDate: 123 }], + completedExams: [], + quizAttempts: [ + { + challengeId: '66df3b712c41c499e9d31e5b', + quizId: '0', + timestamp: 1731924665902 + } + ], + githubProfile: 'github.com/foobar', + website: 'https://www.freecodecamp.org', + donationEmails: ['an@add.ress'], + portfolio: [ + { + description: 'A portfolio', + id: 'a6b0bb188d873cb2c8729495', + image: 'https://www.freecodecamp.org/cat.png', + title: 'A portfolio', + url: 'https://www.freecodecamp.org' + } + ], + savedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + lastSavedDate: 123, + files: [ + { + contents: 'test-contents', + ext: 'js', + history: ['indexjs'], + key: 'indexjs', + name: 'test-name' + } + ] + } + ], + yearsTopContributor: ['2018'], + twitter: '@foobar', + bluesky: '@foobar', + linkedin: 'linkedin.com/foobar', + sendQuincyEmail: false +}; + +const minimalUserData: Prisma.userCreateInput = { + about: 'I am a test user', + acceptedPrivacyTerms: true, + email: testUserData.email, + emailVerified: true, + externalId: '1234567890', + isDonating: false, + picture: 'https://www.freecodecamp.org/cat.png', + sendQuincyEmail: true, + username: 'testuser', + usernameDisplay: 'testuser', + unsubscribeId: '1234567890' +}; + +const lockedProfileUI = { + isLocked: true, + showAbout: false, + showCerts: false, + showDonation: false, + showExperience: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false +}; + +// These are not part of the schema, but are added to the user object by +// session-user's handler +const computedProperties = { + calendar: {}, + completedChallengeCount: 0, + isEmailVerified: minimalUserData.emailVerified, + points: 1, + // This is the default value if profileUI is missing. If individual properties + // are missing from the db, they will be omitted from the response. + profileUI: lockedProfileUI +}; + +// The following appears in session-user responses, but not +// get-public-profile +const sessionOnlyData = { + currentChallengeId: testUserData.currentChallengeId, + email: testUserData.email, + emailVerified: testUserData.emailVerified, + isEmailVerified: testUserData.emailVerified, + sendQuincyEmail: testUserData.sendQuincyEmail, + theme: testUserData.theme, + keyboardShortcuts: testUserData.keyboardShortcuts, + completedChallengeCount: 3, + acceptedPrivacyTerms: testUserData.acceptedPrivacyTerms, + isClassroomAccount: testUserData.isClassroomAccount ?? false +}; + +const publicUserData = { + about: testUserData.about, + calendar: { 1520002973: 1, 1520440323: 1 }, + // testUserData.completedChallenges, with nulls removed + completedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + challengeType: 5, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2' + } + ] + }, + { + id: 'a5229172f011153519423690', + completedDate: 1520440323273, + challengeType: 5, + files: [] + }, + { + id: 'a5229172f011153519423692', + completedDate: 1520440323274, + githubLink: '', + challengeType: 5, + files: [], + examResults: { + numberOfCorrectAnswers: 0, + numberOfQuestionsInExam: 0, + percentCorrect: 0, + passingPercent: 0, + passed: false, + examTimeInSeconds: 0 + } + } + ], + completedDailyCodingChallenges: [ + { + id: '5900f36e1000cf542c50fe80', + completedDate: 1742941672524, + languages: [ + DailyCodingChallengeLanguage.python, + DailyCodingChallengeLanguage.javascript + ] + } + ], + completedExams: testUserData.completedExams, + completedSurveys: [], // TODO: add surveys + quizAttempts: testUserData.quizAttempts, + experience: [], + githubProfile: testUserData.githubProfile, + is2018DataVisCert: testUserData.is2018DataVisCert, + is2018FullStackCert: testUserData.is2018FullStackCert, // TODO: should this be returned? The client doesn't use it at the moment. + isA2EnglishCert: testUserData.isA2EnglishCert, + isApisMicroservicesCert: testUserData.isApisMicroservicesCert, + isBackEndCert: testUserData.isBackEndCert, + isCheater: testUserData.isCheater, + isCollegeAlgebraPyCertV8: testUserData.isCollegeAlgebraPyCertV8, + isDataAnalysisPyCertV7: testUserData.isDataAnalysisPyCertV7, + isDataVisCert: testUserData.isDataVisCert, + isDonating: testUserData.isDonating, + isFoundationalCSharpCertV8: testUserData.isFoundationalCSharpCertV8, + isFrontEndCert: testUserData.isFrontEndCert, + isFrontEndLibsCert: testUserData.isFrontEndLibsCert, + isFullStackCert: testUserData.isFullStackCert, + isHonest: testUserData.isHonest, + isInfosecCertV7: testUserData.isInfosecCertV7, + isInfosecQaCert: testUserData.isInfosecQaCert, + isJavascriptCertV9: testUserData.isJavascriptCertV9, + isJsAlgoDataStructCert: testUserData.isJsAlgoDataStructCert, + isJsAlgoDataStructCertV8: testUserData.isJsAlgoDataStructCertV8, + isMachineLearningPyCertV7: testUserData.isMachineLearningPyCertV7, + isPythonCertV9: testUserData.isPythonCertV9, + isQaCertV7: testUserData.isQaCertV7, + isRelationalDatabaseCertV8: testUserData.isRelationalDatabaseCertV8, + isRelationalDatabaseCertV9: testUserData.isRelationalDatabaseCertV9, + isRespWebDesignCert: testUserData.isRespWebDesignCert, + isRespWebDesignCertV9: testUserData.isRespWebDesignCertV9, + isSciCompPyCertV7: testUserData.isSciCompPyCertV7, + isFrontEndLibsCertV9: testUserData.isFrontEndLibsCertV9, + isBackEndDevApisCertV9: testUserData.isBackEndDevApisCertV9, + isFullStackDeveloperCertV9: testUserData.isFullStackDeveloperCertV9, + isB1EnglishCert: testUserData.isB1EnglishCert, + isA2SpanishCert: testUserData.isA2SpanishCert, + isA2ChineseCert: testUserData.isA2ChineseCert, + isA1ChineseCert: testUserData.isA1ChineseCert, + linkedin: testUserData.linkedin, + location: testUserData.location, + name: testUserData.name, + partiallyCompletedChallenges: [{ id: '123', completedDate: 123 }], + picture: testUserData.picture, + points: 2, + portfolio: testUserData.portfolio, + profileUI: testUserData.profileUI, + savedChallenges: testUserData.savedChallenges, + socrates: true, + twitter: 'https://x.com/foobar', + bluesky: 'https://bsky.app/profile/foobar', + sendQuincyEmail: testUserData.sendQuincyEmail, + username: testUserData.username, + usernameDisplay: testUserData.usernameDisplay, + website: testUserData.website, + yearsTopContributor: testUserData.yearsTopContributor +}; + +// This is (most of) what we expect to get back from the API. The remaining +// properties are 'id' and 'joinDate', which are generated by the database. +// We're currently filtering properties with null values, since the old api just +// would not return those. +const sessionUserData = { + ...sessionOnlyData, + ...publicUserData +}; + +const baseProgressData = { + currentChallengeId: '', + isA2EnglishCert: false, + isB1EnglishCert: false, + isRespWebDesignCert: false, + is2018DataVisCert: false, + isFrontEndLibsCert: false, + isFrontEndLibsCertV9: false, + isJsAlgoDataStructCert: false, + isApisMicroservicesCert: false, + isInfosecQaCert: false, + isQaCertV7: false, + isInfosecCertV7: false, + is2018FullStackCert: false, + isFrontEndCert: false, + isBackEndCert: false, + isBackEndDevApisCertV9: false, + isDataVisCert: false, + isFullStackCert: false, + isJavascriptCertV9: false, + isSciCompPyCertV7: false, + isDataAnalysisPyCertV7: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isRespWebDesignCertV9: false, + isCollegeAlgebraPyCertV8: false, + completedChallenges: [], + completedDailyCodingChallenges: [], + completedExams: [], + savedChallenges: [], + partiallyCompletedChallenges: [], + needsModeration: false +}; + +const modifiedProgressData = { + ...baseProgressData, + currentChallengeId: 'hello there', + isRespWebDesignCert: true, + isJsAlgoDataStructCert: true, + isRelationalDatabaseCertV8: true, + needsModeration: true +}; + +const userTokenId = 'dummy-id'; +const otherUserId = 'aaaaaaaaaaaaaaaaaaaaaaaa'; + +const msUsernameData = [ + { msUsername: 'foobar', userId: defaultUserId, ttl: 123 }, + { msUsername: 'foobar2', userId: defaultUserId, ttl: 123 }, + { msUsername: 'foobar3', userId: otherUserId, ttl: 123 } +]; + +const tokenData = [ + { created: new Date(), id: '123', ttl: 1000, userId: defaultUserId }, + { created: new Date(), id: '456', ttl: 1000, userId: defaultUserId }, + { created: new Date(), id: '789', ttl: 1000, userId: otherUserId } +]; + +const mockSurveyResults = { + title: 'Foundational C# with Microsoft Survey', + responses: [ + { + question: 'Please describe your role:', + response: 'Beginner developer (less than 2 years experience)' + }, + { + question: + 'Prior to this course, how experienced were you with .NET and C#?', + response: 'Novice (no prior experience)' + } + ] +}; + +describe('userRoutes', () => { + setupServer(); + + describe('Authenticated user', () => { + let superGet: ReturnType; + let superPost: ReturnType; + let superDelete: ReturnType; + + beforeEach(async () => { + const setCookies = await devLogin(); + superGet = createSuperRequest({ method: 'GET', setCookies }); + superPost = createSuperRequest({ method: 'POST', setCookies }); + superDelete = createSuperRequest({ method: 'DELETE', setCookies }); + }); + + describe('/account/delete', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + await clearEnvExam(); + }); + + test('POST returns 200 status code with empty object', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const initialCount = await fastifyTestInstance.prisma.user.count(); + const response = await superPost('/account/delete'); + const finalCount = await fastifyTestInstance.prisma.user.count(); + const deletedUser = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(response.body).toStrictEqual({}); + expect(response.status).toBe(200); + expect(finalCount).toBe(initialCount - 1); + expect(deletedUser).toBeNull(); + expect(count).toHaveBeenCalledWith('account.deleted', 1, { + attributes: { endpoint: '/account/delete' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST emits account.deleted_while_donating when a donating user is deleted', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { isDonating: true } + }); + + const response = await superPost('/account/delete'); + + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith( + 'account.deleted_while_donating', + 1, + { attributes: { endpoint: '/account/delete' } } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST deletes Microsoft usernames associated with the user', async () => { + await fastifyTestInstance.prisma.msUsername.createMany({ + data: msUsernameData + }); + + await superPost('/account/delete'); + expect(await fastifyTestInstance.prisma.msUsername.count()).toBe(1); + }); + + test('POST deletes userTokens associated with the user', async () => { + await fastifyTestInstance.prisma.userToken.createMany({ + data: tokenData + }); + + await superPost('/account/delete'); + + const userTokens = + await fastifyTestInstance.prisma.userToken.findMany(); + expect(userTokens).toHaveLength(1); + expect(userTokens[0]?.userId).toBe(otherUserId); + }); + + test("POST deletes all the user's cookies", async () => { + const res = await superPost('/account/delete'); + + const setCookie = res.headers['set-cookie'] as string[]; + expect(setCookie).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^_csrf=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^csrf_token=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^jwt_access_token=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ) + ]) + ); + expect(setCookie).toHaveLength(3); + }); + + test("POST deletes all the user's exam attempts", async () => { + await seedEnvExam(); + await seedEnvExamAttempt(); + const countBefore = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.count(); + expect(countBefore).toBe(1); + + const res = await superPost('/account/delete'); + + const countAfter = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.count(); + expect(countAfter).toBe(0); + expect(res.status).toBe(200); + }); + + test("POST deletes all the user's exam tokens", async () => { + await seedExamEnvExamAuthToken(); + const countBefore = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.count(); + expect(countBefore).toBe(1); + + const res = await superPost('/account/delete'); + + const countAfter = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.count(); + expect(countAfter).toBe(0); + expect(res.status).toBe(200); + }); + + test('handles concurrent requests to delete the same user', async () => { + const deletePromises = Array.from({ length: 2 }, () => + superPost('/account/delete') + ); + + const responses = await Promise.all(deletePromises); + + const userCount = await fastifyTestInstance.prisma.user.count({ + where: { email: testUserData.email } + }); + // Both requests race: one deletes the user and returns 200. The other + // may get a 401 if the auth middleware queries the DB after the user has + // already been deleted by the first request. + responses.forEach(response => { + expect([200, 401]).toContain(response.status); + }); + expect(userCount).toBe(0); + }); + + test("only deletes the logged in user's data", async () => { + const initialCount = await fastifyTestInstance.prisma.user.count(); + const otherEmail = 'an.random@user'; + const otherUser = await fastifyTestInstance.prisma.user.create({ + data: { + ...testUserData, + email: otherEmail + } + }); + expect(otherUser.email).toBe(otherEmail); + const afterAdd = await fastifyTestInstance.prisma.user.count(); + expect(afterAdd).toBe(initialCount + 1); + + await superPost('/account/delete'); + + const finalCount = await fastifyTestInstance.prisma.user.count(); + expect(finalCount).toBe(initialCount); + const remaining = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: otherEmail } + }); + expect(remaining).not.toBeNull(); + }); + + test('logs if it is asked to delete a non-existent user', async () => { + const spy = vi.spyOn(fastifyTestInstance.log, 'warn'); + + // Note: this could be flaky since the log is generated if the two + // requests are concurrent. If they're sequential the second request + // will be not be authed and hence not log anything. + const deletePromises = Array.from({ length: 2 }, () => + superPost('/account/delete') + ); + await Promise.all(deletePromises); + // userId is auto-bound onto req.log by the auth plugin, not passed explicitly. + const found = spy.mock.calls.some( + ([firstArg]) => firstArg === 'User not found for deletion' + ); + expect(found).toBe(true); + }); + }); + + describe('/users/:userId', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + await clearEnvExam(); + }); + + test('DELETE returns 204 status code with empty object', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superDelete(`/users/${defaultUserId}`); + const userCount = await fastifyTestInstance.prisma.user.count({ + where: { email: testUserData.email } + }); + + expect(response.body).toStrictEqual({}); + expect(response.status).toBe(204); + expect(userCount).toBe(0); + expect(count).toHaveBeenCalledWith('account.deleted', 1, { + attributes: { endpoint: '/users/:userId' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('DELETE emits account.deleted_while_donating when a donating user is deleted', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { isDonating: true } + }); + + const response = await superDelete(`/users/${defaultUserId}`); + + expect(response.status).toBe(204); + expect(count).toHaveBeenCalledWith( + 'account.deleted_while_donating', + 1, + { attributes: { endpoint: '/users/:userId' } } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('DELETE deletes Microsoft usernames associated with the user', async () => { + await fastifyTestInstance.prisma.msUsername.createMany({ + data: msUsernameData + }); + + await superDelete(`/users/${defaultUserId}`); + expect(await fastifyTestInstance.prisma.msUsername.count()).toBe(1); + }); + + test('DELETE deletes userTokens associated with the user', async () => { + await fastifyTestInstance.prisma.userToken.createMany({ + data: tokenData + }); + + await superDelete(`/users/${defaultUserId}`); + + const userTokens = + await fastifyTestInstance.prisma.userToken.findMany(); + expect(userTokens).toHaveLength(1); + expect(userTokens[0]?.userId).toBe(otherUserId); + }); + + test("DELETE deletes all the user's cookies", async () => { + const res = await superDelete(`/users/${defaultUserId}`); + + const setCookie = res.headers['set-cookie'] as string[]; + expect(setCookie).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^_csrf=; Max-Age=0; Path=\/:?; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^csrf_token=; Max-Age=0; Path=\/:?; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^jwt_access_token=; Max-Age=0; Path=\/:?; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ) + ]) + ); + expect(setCookie).toHaveLength(3); + }); + + test("DELETE deletes all the user's exam attempts", async () => { + await seedEnvExam(); + await seedEnvExamAttempt(); + const countBefore = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.count(); + expect(countBefore).toBe(1); + + const res = await superDelete(`/users/${defaultUserId}`); + + const countAfter = + await fastifyTestInstance.prisma.examEnvironmentExamAttempt.count(); + expect(countAfter).toBe(0); + expect(res.status).toBe(204); + }); + + test("DELETE deletes all the user's exam tokens", async () => { + await seedExamEnvExamAuthToken(); + const countBefore = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.count(); + expect(countBefore).toBe(1); + + const res = await superDelete(`/users/${defaultUserId}`); + + const countAfter = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.count(); + expect(countAfter).toBe(0); + expect(res.status).toBe(204); + }); + + test("only deletes the logged in user's data", async () => { + const initialCount = await fastifyTestInstance.prisma.user.count(); + const otherEmail = 'an.random@user'; + await fastifyTestInstance.prisma.user.create({ + data: { + ...testUserData, + email: otherEmail + } + }); + expect(await fastifyTestInstance.prisma.user.count()).toBe( + initialCount + 1 + ); + + await superDelete(`/users/${defaultUserId}`); + + const userCount = await fastifyTestInstance.prisma.user.count(); + expect(userCount).toBe(initialCount); + const remaining = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: otherEmail } + }); + expect(remaining).not.toBeNull(); + }); + + test('handles concurrent requests to delete the same user', async () => { + const deletePromises = Array.from({ length: 2 }, () => + superDelete(`/users/${defaultUserId}`) + ); + + const responses = await Promise.all(deletePromises); + + const userCount = await fastifyTestInstance.prisma.user.count({ + where: { email: testUserData.email } + }); + // Both requests race: one deletes the user and returns 204. The other + // gets a 401 if the auth middleware queries the DB after the delete, or + // a 404 if it clears auth but finds no user left to delete. + responses.forEach(response => { + expect([204, 401, 404]).toContain(response.status); + }); + expect(userCount).toBe(0); + }); + + test('logs if it is asked to delete a non-existent user', async () => { + const spy = vi.spyOn(fastifyTestInstance.log, 'warn'); + + const deletePromises = Array.from({ length: 2 }, () => + superDelete(`/users/${defaultUserId}`) + ); + + await Promise.all(deletePromises); + + // userId is auto-bound onto req.log by the auth plugin, not passed explicitly. + const found = spy.mock.calls.some( + ([firstArg]) => firstArg === 'User not found for deletion' + ); + expect(found).toBe(true); + }); + + // Pins the P2025 check itself: without it the handler would report every + // database failure as a 404, silently leaving the account in place. + test('rethrows if the delete fails for any other reason', async () => { + const errorLog = vi.spyOn(fastifyTestInstance.log, 'error'); + const spy = vi + .spyOn(fastifyTestInstance.prisma.user, 'delete') + .mockRejectedValueOnce(new Error('connection reset')); + + try { + const res = await superDelete(`/users/${defaultUserId}`); + + expect(res.status).toBe(500); + expect(res.body).not.toStrictEqual({ + type: 'error', + message: 'not found' + }); + expect(errorLog).toHaveBeenCalled(); + // The account must survive a failure the handler does not understand. + const stillThere = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + expect(stillThere).not.toBeNull(); + } finally { + spy.mockRestore(); + errorLog.mockRestore(); + } + }); + + test('returns 403 if attempting to delete a different user', async () => { + const res = await superDelete(`/users/${otherUserId}`); + expect(res.status).toBe(403); + }); + }); + + describe('/account/reset-progress', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { OR: [{ userId: defaultUserId }, { userId: otherUserId }] } + }); + }); + test('POST returns 200 status code with empty object', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: modifiedProgressData + }); + + const response = await superPost('/account/reset-progress'); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(response.body).toStrictEqual({}); + expect(response.status).toBe(200); + + expect(user?.progressTimestamps).toHaveLength(1); + expect(user).toMatchObject(baseProgressData); + }); + + test('POST emits account.progress_reset metric', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await superPost('/account/reset-progress'); + + expect(count).toHaveBeenCalledWith('account.progress_reset', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST deletes Microsoft usernames associated with the user', async () => { + await fastifyTestInstance.prisma.msUsername.createMany({ + data: msUsernameData + }); + + await superPost('/account/reset-progress'); + + expect(await fastifyTestInstance.prisma.msUsername.count()).toBe(1); + }); + + test('POST deletes userTokens associated with the user', async () => { + await fastifyTestInstance.prisma.userToken.createMany({ + data: tokenData + }); + + await superPost('/account/reset-progress'); + + const userTokens = + await fastifyTestInstance.prisma.userToken.findMany(); + expect(userTokens).toHaveLength(1); + expect(userTokens[0]?.userId).toBe(otherUserId); + }); + + test.todo('POST resets the user to the default state'); + }); + + describe('/account/reset-module', () => { + const testChallengesBlockOne = [ + { + id: 'block-one-challenge-1', + completedDate: 1520002973119, + solution: null, + challengeType: 5, + files: [] + }, + { + id: 'block-one-challenge-2', + completedDate: 1520002973120, + solution: null, + challengeType: 5, + files: [] + } + ]; + + const testChallengesBlockTwo = [ + { + id: 'block-two-challenge-1', + completedDate: 1520002973121, + solution: null, + challengeType: 5, + files: [] + }, + { + id: 'block-two-challenge-2', + completedDate: 1520002973122, + solution: null, + challengeType: 5, + files: [] + } + ]; + + const savedChallengesBlockOne = [ + { + id: 'block-one-challenge-1', + lastSavedDate: 123, + files: [ + { + contents: 'test-contents', + ext: 'js', + history: ['indexjs'], + key: 'indexjs', + name: 'test-name' + } + ] + } + ]; + + const partiallyCompletedChallengesBlockOne = [ + { + id: 'block-one-challenge-1', + completedDate: 1520002973119 + }, + { + id: 'block-one-challenge-2', + completedDate: 1520002973120 + } + ]; + + let getChallengeIdsByBlockSpy: MockInstance; + + beforeEach(async () => { + // Mock getChallengeIdsByBlock to return test challenge IDs + getChallengeIdsByBlockSpy = vi + .spyOn(getChallengesModule, 'getChallengeIdsByBlock') + .mockImplementation((blockId: string) => { + if (blockId === 'block-one') { + return ['block-one-challenge-1', 'block-one-challenge-2']; + } + if (blockId === 'block-two') { + return ['block-two-challenge-1', 'block-two-challenge-2']; + } + return []; + }); + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { + completedChallenges: [ + ...testChallengesBlockOne, + ...testChallengesBlockTwo + ], + savedChallenges: savedChallengesBlockOne, + partiallyCompletedChallenges: partiallyCompletedChallengesBlockOne, + isRespWebDesignCert: true + } + }); + }); + + afterEach(() => { + getChallengeIdsByBlockSpy.mockRestore(); + }); + + test('DELETE returns 400 for missing blockIds', async () => { + const response = await superDelete('/account/reset-module').send({}); + + expect(response.status).toBe(400); + }); + + test('DELETE returns 400 for empty blockIds array', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: [] + }); + + expect(response.status).toBe(400); + }); + + test('DELETE returns 400 for blockIds containing an empty string', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: [''] + }); + + expect(response.status).toBe(400); + }); + + test('DELETE returns 400 when blockIds exceeds maxItems', async () => { + const tooMany = Array.from({ length: 501 }, (_, i) => `block-${i}`); + const response = await superDelete('/account/reset-module').send({ + blockIds: tooMany + }); + + expect(response.status).toBe(400); + }); + + test('DELETE returns 200 with removedChallengeIds', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + expect(response.status).toBe(200); + expect(response.body).toStrictEqual({ + removedChallengeIds: expect.arrayContaining([ + 'block-one-challenge-1', + 'block-one-challenge-2' + ]) + }); + }); + + test('DELETE removes only challenges from the specified block', async () => { + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.completedChallenges).toHaveLength(2); + const challengeIds = ( + user?.completedChallenges as { id: string }[] + ).map(c => c.id); + expect(challengeIds).toContain('block-two-challenge-1'); + expect(challengeIds).toContain('block-two-challenge-2'); + expect(challengeIds).not.toContain('block-one-challenge-1'); + expect(challengeIds).not.toContain('block-one-challenge-2'); + }); + + test('DELETE removes saved challenges from the specified block', async () => { + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.savedChallenges).toHaveLength(0); + }); + + test('DELETE removes partially completed challenges from the specified block', async () => { + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.partiallyCompletedChallenges).toHaveLength(0); + }); + + test('DELETE keeps certifications intact', async () => { + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.isRespWebDesignCert).toBe(true); + }); + + test('DELETE keeps progress timestamps intact', async () => { + const userBefore = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const userAfter = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(userAfter?.progressTimestamps).toEqual( + userBefore?.progressTimestamps + ); + }); + + test('DELETE does not delete userTokens', async () => { + await fastifyTestInstance.prisma.userToken.create({ + data: { + created: new Date(), + id: '123', + ttl: 1000, + userId: defaultUserId + } + }); + + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + expect(await fastifyTestInstance.prisma.userToken.count()).toBe(1); + + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { userId: defaultUserId } + }); + }); + + test('DELETE does not delete surveys', async () => { + await fastifyTestInstance.prisma.survey.create({ + data: { + userId: defaultUserId, + title: 'Test Survey', + responses: [] + } + }); + + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + expect(await fastifyTestInstance.prisma.survey.count()).toBe(1); + + await fastifyTestInstance.prisma.survey.deleteMany({ + where: { userId: defaultUserId } + }); + }); + + test('DELETE handles multiple blocks in a single call', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: ['block-one', 'block-two'] + }); + + expect(response.status).toBe(200); + expect(response.body.removedChallengeIds).toEqual( + expect.arrayContaining([ + 'block-one-challenge-1', + 'block-one-challenge-2', + 'block-two-challenge-1', + 'block-two-challenge-2' + ]) + ); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.completedChallenges).toHaveLength(0); + }); + + test('DELETE dedupes overlapping blockIds', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: ['block-one', 'block-one'] + }); + + expect(response.status).toBe(200); + expect(response.body.removedChallengeIds).toHaveLength(2); + }); + + test('DELETE proceeds when only some blockIds are valid', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: ['block-one', 'non-existent-block'] + }); + + expect(response.status).toBe(200); + expect(response.body.removedChallengeIds).toEqual( + expect.arrayContaining([ + 'block-one-challenge-1', + 'block-one-challenge-2' + ]) + ); + }); + + test('DELETE only affects the authenticated user', async () => { + await fastifyTestInstance.prisma.user.create({ + data: { + ...testUserData, + email: 'another@user.com', + completedChallenges: testChallengesBlockOne + } + }); + + await superDelete('/account/reset-module').send({ + blockIds: ['block-one'] + }); + + const otherUser = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: 'another@user.com' } + }); + + expect(otherUser?.completedChallenges).toHaveLength(2); + + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: 'another@user.com' } + }); + }); + + test('DELETE returns 400 for non-existent blockId', async () => { + const response = await superDelete('/account/reset-module').send({ + blockIds: ['non-existent-block'] + }); + + expect(response.status).toBe(400); + + const user = await fastifyTestInstance.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + + expect(user?.completedChallenges).toHaveLength(4); + }); + }); + + describe('/user/user-token', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.userToken.create({ + data: { + created: new Date(), + id: '123', + ttl: 1000, + userId: defaultUserId + } + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { + userId: defaultUserId + } + }); + }); + + // TODO(Post-MVP): consider using PUT and updating the logic to upsert + test('POST success response includes a JWT encoded string', async () => { + const response = await superPost('/user/user-token'); + + const userToken = response.body.userToken; + const decodedToken = jwt.decode(userToken); + + expect(response.body).toStrictEqual({ userToken: expect.any(String) }); + expect(decodedToken).toStrictEqual({ + userToken: expect.stringMatching(/^[a-zA-Z0-9]{64}$/), + iat: expect.any(Number) + }); + + expect(() => jwt.verify(userToken, 'wrong-secret')).toThrow(); + expect(() => jwt.verify(userToken, JWT_SECRET)).not.toThrow(); + + // TODO(Post-MVP): consider using 201 for new tokens. + expect(response.status).toBe(200); + }); + + test('POST responds with an encoded UserToken id', async () => { + const response = await superPost('/user/user-token'); + + const decodedToken = jwt.decode(response.body.userToken); + const userTokenId = (decodedToken as JwtPayload).userToken; + + // Verify that the token has been created. + await fastifyTestInstance.prisma.userToken.findUniqueOrThrow({ + where: { id: userTokenId } + }); + + // TODO(Post-MVP): consider using 201 for new tokens. + expect(response.status).toBe(200); + }); + + test('POST deletes old tokens when creating a new one', async () => { + const response = await superPost('/user/user-token'); + + const decodedToken = jwt.decode(response.body.userToken); + const userTokenId = (decodedToken as JwtPayload).userToken; + + // Verify that the token has been created. + await fastifyTestInstance.prisma.userToken.findUniqueOrThrow({ + where: { id: userTokenId } + }); + + await superPost('/user/user-token'); + + // Verify that the old token has been deleted. + expect( + await fastifyTestInstance.prisma.userToken.findUnique({ + where: { id: userTokenId } + }) + ).toBeNull(); + expect(await fastifyTestInstance.prisma.userToken.count()).toBe(1); + }); + + test('DELETE returns 200 status with null userToken', async () => { + const response = await superDelete('/user/user-token'); + + expect(response.body).toStrictEqual({ userToken: null }); + expect(response.status).toBe(200); + expect(await fastifyTestInstance.prisma.userToken.count()).toBe(0); + }); + + test('DELETEing a missing userToken returns 404 status with an error message', async () => { + await superDelete('/user/user-token'); + + const response = await superDelete('/user/user-token'); + + expect(response.body).toStrictEqual({ + type: 'info', + message: 'userToken not found' + }); + expect(response.status).toBe(404); + }); + }); + + describe('/user/get-user-session', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: testUserData + }); + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.userToken.deleteMany({ + where: { id: userTokenId } + }); + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.deleteMany( + { + where: { userId: defaultUserId } + } + ); + }); + + test('GET rejects with 500 status code if the username is missing', async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { username: '' } + }); + + const response = await superGet('/user/session-user'); + + expect(response.body).toStrictEqual({ user: {}, result: '' }); + expect(response.statusCode).toBe(500); + }); + + test('GET captures an exception if the username is missing', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { username: '' } + }); + + const response = await superGet('/user/session-user'); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('GET captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.survey, 'findMany') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superGet('/user/session-user'); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + + // This should help debugging, since this the route returns this if + // anything throws in the handler. + test('GET does not return the error response if the request is valid', async () => { + const response = await superGet('/user/session-user'); + + expect(response.body).not.toEqual({ user: {}, result: '' }); + }); + + test('GET returns username as the result property', async () => { + const response = await superGet('/user/session-user'); + + expect(response.body).toMatchObject({ + result: testUserData.username + }); + expect(response.statusCode).toBe(200); + }); + + test('GET returns the public user object', async () => { + // TODO: This gets the user from the database so that we can verify the + // joinDate. It feels like there should be a better way to do this. + const testUser = await fastifyTestInstance?.prisma.user.findFirst({ + where: { email: testUserData.email } + }); + const publicUser = { + ...sessionUserData, + id: testUser?.id, + joinDate: new ObjectId(testUser?.id).getTimestamp().toISOString() + }; + + const response = await superGet('/user/session-user'); + const { + user: { foobar } + } = response.body as unknown as { + user: { foobar: typeof publicUser }; + }; + + expect(testUser).not.toBeNull(); + expect(testUser?.id).not.toBeNull(); + expect(foobar).toEqual(publicUser); + }); + + test('GET returns the userToken if it exists', async () => { + const tokenData = { + userId: defaultUserId, + ttl: 123, + id: userTokenId, + created: new Date() + }; + + await fastifyTestInstance.prisma.userToken.create({ + data: tokenData + }); + + const tokens = await fastifyTestInstance.prisma.userToken.count(); + expect(tokens).toBe(1); + + const response = await superGet('/user/session-user'); + + const { userToken } = jwt.decode( + response.body.user.foobar.userToken + ) as { userToken: string }; + + expect(tokenData.id).toBe(userToken); + }); + + test('GET returns the msUsername if it exists', async () => { + await fastifyTestInstance.prisma.msUsername.create({ + data: msUsernameData[0] as (typeof msUsernameData)[0] + }); + + const msUsernames = await fastifyTestInstance.prisma.msUsername.count(); + expect(msUsernames).toBe(1); + + const response = await superGet('/user/session-user'); + + const { msUsername } = response.body.user.foobar; + + expect(msUsername).toBe(msUsernameData[0]?.msUsername); + }); + + test('GET returns a minimal user when all optional properties are missing', async () => { + // To get a minimal test user we first delete the existing one... + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + email: minimalUserData.email + } + }); + // ...then recreate it using only the properties that the schema + // requires. The alternative is to update, but that would require + // a lot of unsets (this is neater) + const testUser = await fastifyTestInstance.prisma.user.create({ + data: minimalUserData + }); + + // devLogin must not be used here since it overrides the user + const res = await superRequest('/signin', { method: 'GET' }); + const setCookies = res.get('Set-Cookie'); + + const publicUser = { + ...omit(minimalUserData, ['externalId', 'unsubscribeId']), + ...computedProperties, + id: testUser.id, + joinDate: new ObjectId(testUser.id).getTimestamp().toISOString(), + // the following properties are defaults provided if the field is + // missing in the user document. + currentChallengeId: '', + completedChallenges: [], + completedDailyCodingChallenges: [], + completedExams: [], + completedSurveys: [], + experience: [], + partiallyCompletedChallenges: [], + portfolio: [], + savedChallenges: [], + quizAttempts: [], + yearsTopContributor: [], + is2018DataVisCert: false, + is2018FullStackCert: false, + isA2EnglishCert: false, + isApisMicroservicesCert: false, + isBackEndCert: false, + isCheater: false, + isClassroomAccount: false, + isCollegeAlgebraPyCertV8: false, + isDataAnalysisPyCertV7: false, + isDataVisCert: false, + isFoundationalCSharpCertV8: false, + isFrontEndCert: false, + isFrontEndLibsCert: false, + isFullStackCert: false, + isJavascriptCertV9: false, + isHonest: false, + isInfosecCertV7: false, + isInfosecQaCert: false, + isJsAlgoDataStructCert: false, + isJsAlgoDataStructCertV8: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isQaCertV7: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isRespWebDesignCert: false, + isRespWebDesignCertV9: false, + isSciCompPyCertV7: false, + isFrontEndLibsCertV9: false, + isBackEndDevApisCertV9: false, + isFullStackDeveloperCertV9: false, + isB1EnglishCert: false, + isA2SpanishCert: false, + isA2ChineseCert: false, + isA1ChineseCert: false, + keyboardShortcuts: false, + location: '', + name: '', + socrates: true, + theme: 'default' + }; + + const response = await superRequest('/user/session-user', { + method: 'GET', + setCookies + }); + + const { + user: { testuser } + } = response.body as unknown as { + user: { testuser: typeof publicUser }; + }; + + expect(testuser).toStrictEqual(publicUser); + }); + }); + + describe('/user/report-user', () => { + let sendEmailSpy: MockInstance; + beforeEach(() => { + sendEmailSpy = vi + .spyOn(fastifyTestInstance, 'sendEmail') + .mockImplementation(vi.fn()); + }); + + afterEach(async () => { + await resetDefaultUser(); + vi.clearAllMocks(); + }); + + test('POST returns 400 for empty username', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/user/report-user').send({ + username: '', + reportDescription: 'Test Report' + }); + + expect(response.statusCode).toBe(404); + expect(response.body).toStrictEqual({ + type: 'danger', + message: 'flash.report-error' + }); + expect(count).toHaveBeenCalledWith('user.report_submitted', 1, { + attributes: { result: 'not_found' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST returns 400 for empty report', async () => { + const response = await superPost('/user/report-user').send({ + username: testUserData.username, + reportDescription: '' + }); + + expect(response.statusCode).toBe(400); + }); + + test('POST captures unexpected errors when looking up the reported user', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.user, 'findMany') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superPost('/user/report-user').send({ + username: testUserData.username, + reportDescription: 'Test Report' + }); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('user.report_submitted', 1, { + attributes: { result: 'lookup_error' } + }); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST returns 400 for users with no email', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: testUserData.email }, + data: { email: null } + }); + + const response = await superPost('/user/report-user').send({ + username: testUserData.username, + reportDescription: 'Test Report' + }); + + expect(response.statusCode).toBe(400); + expect(response.body).toStrictEqual({ + type: 'danger', + message: 'flash.report-error' + }); + expect(count).toHaveBeenCalledWith('user.report_submitted', 1, { + attributes: { result: 'no_email' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST sanitises report description', async () => { + await superPost('/user/report-user').send({ + username: defaultUsername, + reportDescription: + 'Luke, I am your father' + }); + + expect(sendEmailSpy).toHaveBeenCalledTimes(1); + expect(sendEmailSpy).toHaveBeenCalledWith( + expect.objectContaining({ + text: expect.stringContaining( + 'Report Details:\n\nLuke, I am your father' + ) + }) + ); + }); + + test('POST returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const testUser = await fastifyTestInstance.prisma.user.findFirstOrThrow( + { + where: { email: testUserData.email } + } + ); + const response = await superPost('/user/report-user').send({ + username: testUser.username, + reportDescription: 'Luke, I am your father' + }); + + expect(sendEmailSpy).toHaveBeenCalledTimes(1); + expect(sendEmailSpy).toHaveBeenCalledWith({ + from: 'team@freecodecamp.org', + to: 'support@freecodecamp.org', + cc: 'foo@bar.com', + subject: `Abuse Report : Reporting ${testUser.username}'s profile.`, + text: ` +Hello Team, + +This is to report the profile of ${testUser.username}. ID: ${defaultUserId}. + +Report Details: + +Luke, I am your father + + +Reported by: +ID: ${testUser.id} +Username: ${testUser.username} +Name: +Email: foo@bar.com + +Thanks and regards, +` + }); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({ + type: 'info', + message: 'flash.report-sent', + variables: { email: 'foo@bar.com' } + }); + expect(count).toHaveBeenCalledWith('user.report_submitted', 1, { + attributes: { result: 'success' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('/user/ms-username', () => { + describe('DELETE', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { userId: otherUserId } + }); + }); + + test('deletes all Microsoft usernames associated with the user', async () => { + await fastifyTestInstance.prisma.msUsername.createMany({ + data: [ + { msUsername: 'foobar', userId: defaultUserId, ttl: 123 }, + { msUsername: 'foobar2', userId: defaultUserId, ttl: 123 } + ] + }); + + const response = await superDelete('/user/ms-username'); + + const msUsernames = + await fastifyTestInstance.prisma.msUsername.count(); + + expect(msUsernames).toBe(0); + expect(response.body).toStrictEqual({ msUsername: null }); + expect(response.statusCode).toBe(200); + }); + + test('does not delete Microsoft usernames associated with other users', async () => { + await fastifyTestInstance.prisma.msUsername.createMany({ + data: [ + { msUsername: 'foobar', userId: otherUserId, ttl: 123 }, + { msUsername: 'foobar2', userId: defaultUserId, ttl: 123 } + ] + }); + + await superDelete('/user/ms-username'); + + const msUsernames = + await fastifyTestInstance.prisma.msUsername.count(); + + expect(msUsernames).toBe(1); + }); + + test('captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.msUsername, 'deleteMany') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superDelete('/user/ms-username'); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('POST', () => { + beforeEach(() => { + mockedFetch.mockClear(); + }); + afterEach(async () => { + await fastifyTestInstance.prisma.msUsername.deleteMany({ + where: { + OR: [ + { userId: defaultUserId }, + { userId: 'aaaaaaaaaaaaaaaaaaaaaaaa' } + ] + } + }); + }); + + test('handles missing transcript urls', async () => { + const response = await superPost('/user/ms-username'); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.ms.transcript.link-err-1' + }); + expect(response.statusCode).toBe(400); + }); + + test('handles invalid transcript urls', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: 'https://www.example.com' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.ms.transcript.link-err-1' + }); + expect(response.statusCode).toBe(400); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'invalid_url' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('emits ms_username.link_completed with result fetch_failed when the Microsoft API request fails', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: false, + status: 404 + }) + ); + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.ms.transcript.link-err-2' + }); + expect(response.statusCode).toBe(404); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'fetch_failed' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('emits ms_username.transcript_fetch_latency_ms distribution when the Microsoft API request throws', async () => { + const distribution = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, distribution } + }; + mockedFetch.mockImplementationOnce(() => + Promise.reject(new Error('network error')) + ); + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo' + }); + + expect(response.statusCode).toBe(500); + expect(distribution).toHaveBeenCalledWith( + 'ms_username.transcript_fetch_latency_ms', + expect.any(Number), + { unit: 'millisecond' } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('handles the case that MS does not return a username', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => Promise.resolve({}) + }) + ); + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/not/transcript/8u6ert43q1p' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.ms.transcript.link-err-3' + }); + expect(response.statusCode).toBe(500); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'missing_username' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('handles duplicate Microsoft usernames', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + userName: 'foobar' + }) + }) + ); + + await fastifyTestInstance.prisma.msUsername.create({ + data: { + msUsername: 'foobar', + userId: defaultUserId, + ttl: 77760000000 + } + }); + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8wert4' + }); + + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.ms.transcript.link-err-4' + }); + + expect(response.statusCode).toBe(409); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'username_taken' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('returns the username on success', async () => { + const count = vi.fn(); + const distribution = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count, distribution } + }; + const msUsername = 'ms-user'; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + userName: msUsername + }) + }) + ); + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8ert43q' + }); + + expect(response.body).toStrictEqual({ + msUsername + }); + expect(response.statusCode).toBe(200); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'success' } + }); + expect(distribution).toHaveBeenCalledWith( + 'ms_username.transcript_fetch_latency_ms', + expect.any(Number), + { unit: 'millisecond' } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('creates a record of the linked account', async () => { + const msUsername = 'super-user'; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + userName: msUsername + }) + }) + ); + + await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/12345' + }); + + const linkedAccount = + await fastifyTestInstance.prisma.msUsername.findFirstOrThrow({ + where: { msUsername } + }); + + expect(linkedAccount).toStrictEqual({ + id: expect.stringMatching(/^[a-f\d]{24}$/), + userId: defaultUserId, + ttl: 77760000000, + msUsername + }); + }); + + test('removes any other accounts linked to the same user', async () => { + const msUsernameOne = 'super-user'; + const msUsernameTwo = 'super-user-2'; + mockedFetch + .mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + userName: msUsernameOne + }) + }) + ) + .mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => + Promise.resolve({ + userName: msUsernameTwo + }) + }) + ); + + await fastifyTestInstance.prisma.msUsername.create({ + data: { + msUsername: 'dummy', + userId: 'aaaaaaaaaaaaaaaaaaaaaaaa', + ttl: 77760000000 + } + }); + + await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo' + }); + await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo' + }); + + const linkedAccounts = + await fastifyTestInstance.prisma.msUsername.findMany({}); + + expect(linkedAccounts).toHaveLength(2); + expect(linkedAccounts[1]?.msUsername).toBe(msUsernameTwo); + }); + + test('calls the Microsoft API with the correct url', async () => { + const msTranscriptUrl = + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo'; + + const msTranscriptApiUrl = + 'https://learn.microsoft.com/api/profiles/transcript/share/8u6awert43q1plo'; + + await superPost('/user/ms-username').send({ + msTranscriptUrl + }); + + expect(mockedFetch).toHaveBeenCalledWith(msTranscriptApiUrl); + }); + + test('captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + mockedFetch.mockImplementationOnce(() => + Promise.resolve({ + ok: true, + json: () => Promise.resolve({ userName: 'super-user' }) + }) + ); + const spy = vi + .spyOn(fastifyTestInstance.prisma.msUsername, 'create') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superPost('/user/ms-username').send({ + msTranscriptUrl: + 'https://learn.microsoft.com/en-us/users/mot01/transcript/12345' + }); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('ms_username.link_completed', 1, { + attributes: { result: 'error' } + }); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + }); + + describe('/user/submit-survey', () => { + afterEach(async () => { + await fastifyTestInstance.prisma.survey.deleteMany({ + where: { userId: defaultUserId } + }); + }); + + test('POST returns 400 for invalid survey title', async () => { + const response = await superPost('/user/submit-survey').send({ + surveyResults: { ...mockSurveyResults, title: 'Invalid Survey' } + }); + + expect(response.statusCode).toBe(400); + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.survey.err-1' + }); + }); + + test('POST returns 409 if user already submitted survey', async () => { + // Submit survey for first time + await superPost('/user/submit-survey').send({ + surveyResults: mockSurveyResults + }); + + // Submit same survey again to get failed response + const response = await superPost('/user/submit-survey').send({ + surveyResults: mockSurveyResults + }); + + expect(response.statusCode).toBe(409); + expect(response.body).toStrictEqual({ + type: 'error', + message: 'flash.survey.err-2' + }); + }); + + test('POST returns 200 status code with "success" message', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superPost('/user/submit-survey').send({ + surveyResults: mockSurveyResults + }); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({ + type: 'success', + message: 'flash.survey.success' + }); + expect(count).toHaveBeenCalledWith('survey.submitted', 1, { + attributes: { surveyTitle: mockSurveyResults.title } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.survey, 'create') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superPost('/user/submit-survey').send({ + surveyResults: mockSurveyResults + }); + + expect(response.statusCode).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + }); + + describe('/user/exam-environment/token', () => { + beforeEach(() => { + mockDeploymentEnv = 'staging'; + }); + + afterAll(() => { + mockDeploymentEnv = 'production'; + }); + + afterEach(async () => { + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.deleteMany( + { + where: { userId: defaultUserId } + } + ); + }); + + test('POST generates a new token if one does not exist', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + mockDeploymentEnv = 'production'; + const response = await superPost('/user/exam-environment/token'); + const { examEnvironmentAuthorizationToken } = response.body; + + const decodedToken = jwt.decode(examEnvironmentAuthorizationToken); + + expect(decodedToken).toStrictEqual({ + examEnvironmentAuthorizationToken: + expect.stringMatching(/^[a-z0-9]{24}$/), + iat: expect.any(Number) + }); + + expect(() => + jwt.verify(examEnvironmentAuthorizationToken, 'wrong-secret') + ).toThrow(); + expect(() => + jwt.verify(examEnvironmentAuthorizationToken, JWT_SECRET) + ).not.toThrow(); + + expect(response.status).toBe(201); + expect(count).toHaveBeenCalledWith('exam.token_minted', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('POST only allows for one token per user id', async () => { + mockDeploymentEnv = 'production'; + const token = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.create( + { + data: { + userId: defaultUserId, + expireAt: new Date() + } + } + ); + + const response = await superPost('/user/exam-environment/token'); + + const { examEnvironmentAuthorizationToken } = response.body; + + const decodedToken = jwt.decode(examEnvironmentAuthorizationToken); + + expect(decodedToken).not.toHaveProperty( + 'examEnvironmentAuthorizationToken', + token.id + ); + + expect(response.status).toBe(201); + + const tokens = + await fastifyTestInstance.prisma.examEnvironmentAuthorizationToken.findMany( + { + where: { userId: defaultUserId } + } + ); + expect(tokens).toHaveLength(1); + }); + + test('POST does not generate a new token in non-production environments for non-staff', async () => { + // Override deployment environment for this test + mockDeploymentEnv = 'staging'; + const response = await superPost('/user/exam-environment/token'); + expect(response.status).toBe(403); + }); + + test('POST does generate a new token in non-production environments for staff', async () => { + // Override deployment environment for this test + mockDeploymentEnv = 'staging'; + await fastifyTestInstance.prisma.user.update({ + where: { + id: defaultUserId + }, + data: { email: 'camperbot@freecodecamp.org' } + }); + + const response = await superPost('/user/exam-environment/token'); + const { examEnvironmentAuthorizationToken } = response.body; + + const decodedToken = jwt.decode(examEnvironmentAuthorizationToken); + + expect(decodedToken).toStrictEqual({ + examEnvironmentAuthorizationToken: + expect.stringMatching(/^[a-z0-9]{24}$/), + iat: expect.any(Number) + }); + + expect(() => + jwt.verify(examEnvironmentAuthorizationToken, 'wrong-secret') + ).toThrow(); + expect(() => + jwt.verify(examEnvironmentAuthorizationToken, JWT_SECRET) + ).not.toThrow(); + + expect(response.status).toBe(201); + }); + }); + }); + + describe('Unauthenticated user', () => { + let setCookies: string[]; + // Get the CSRF cookies from an unprotected route + beforeAll(async () => { + const res = await superRequest('/status/ping', { method: 'GET' }); + setCookies = res.get('Set-Cookie'); + }); + + const endpoints: { path: string; method: 'GET' | 'POST' | 'DELETE' }[] = [ + { path: `/users/${otherUserId}`, method: 'DELETE' }, + { path: '/account/delete', method: 'POST' }, + { path: '/account/reset-progress', method: 'POST' }, + { path: '/account/reset-module', method: 'DELETE' }, + { path: '/user/user-token', method: 'DELETE' }, + { path: '/user/user-token', method: 'POST' }, + { path: '/user/ms-username', method: 'DELETE' }, + { path: '/user/report-user', method: 'POST' }, + { path: '/user/ms-username', method: 'POST' }, + { path: '/user/submit-survey', method: 'POST' } + ]; + + endpoints.forEach(({ path, method }) => { + test(`${method} ${path} returns 401 status code with error message`, async () => { + const response = await superRequest(path, { + method, + setCookies + }); + expect(response.statusCode).toBe(401); + }); + }); + + describe('/user/session-user', () => { + test('GET returns 200 with empty user object for unauthenticated users', async () => { + const response = await superRequest('/user/session-user', { + method: 'GET', + setCookies + }); + + expect(response.statusCode).toBe(200); + expect(response.body).toStrictEqual({ user: {}, result: '' }); + }); + }); + }); +}); + +describe('Microsoft helpers', () => { + describe('getMsTranscriptApiUrl', () => { + const expectedUrl = + 'https://learn.microsoft.com/api/profiles/transcript/share/8u6awert43q1plo'; + + const urlWithoutSlash = + 'https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo'; + const urlWithSlash = `${urlWithoutSlash}/`; + const urlWithQueryParams = `${urlWithoutSlash}?foo=bar`; + const urlWithQueryParamsAndSlash = `${urlWithSlash}?foo=bar`; + + test('should extract the transcript id from the url', () => { + expect(getMsTranscriptApiUrl(urlWithoutSlash)).toEqual({ + error: null, + data: expectedUrl + }); + }); + + test('should handle trailing slashes', () => { + expect(getMsTranscriptApiUrl(urlWithSlash)).toEqual({ + error: null, + data: expectedUrl + }); + }); + + test('should ignore query params', () => { + expect(getMsTranscriptApiUrl(urlWithQueryParams)).toEqual({ + error: null, + data: expectedUrl + }); + expect(getMsTranscriptApiUrl(urlWithQueryParamsAndSlash)).toEqual({ + error: null, + data: expectedUrl + }); + }); + + test('should return an error for invalid URLs', () => { + const validBadUrl = 'https://www.example.com/invalid-url'; + expect(getMsTranscriptApiUrl(validBadUrl)).toEqual({ + error: expect.any(String), + data: null + }); + const invalidUrl = ' '; + expect(getMsTranscriptApiUrl(invalidUrl)).toEqual({ + error: expect.any(String), + data: null + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.ts new file mode 100644 index 0000000000000000000000000000000000000000..84c64d1b458e5e1a7b8d7c4f4b72084c9882eff8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/protected/user.ts @@ -0,0 +1,1019 @@ +import { performance } from 'node:perf_hooks'; +import type { FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { ObjectId } from 'bson'; +import { FastifyInstance, FastifyReply } from 'fastify'; +import jwt from 'jsonwebtoken'; +import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library.js'; + +import * as schemas from '../../schemas.js'; +import * as examEnvironmentSchemas from '../../exam-environment/schemas/index.js'; +import { createResetProperties } from '../../utils/create-user.js'; +import { customNanoid } from '../../utils/ids.js'; +import { encodeUserToken } from '../../utils/tokens.js'; +import { trimTags } from '../../utils/validation.js'; +import { generateReportEmail } from '../../utils/email-templates.js'; +import { splitUser } from '../helpers/user-utils.js'; +import { + normalizeChallenges, + normalizeFlags, + normalizeProfileUI, + normalizeSurveys, + normalizeTwitter, + normalizeBluesky, + removeNulls +} from '../../utils/normalize.js'; +import { + mapErr, + type UpdateReqType, + type UpdateReplyType +} from '../../utils/index.js'; +import { + getCalendar, + getPoints, + ProgressTimestamp +} from '../../utils/progress.js'; +import { DEPLOYMENT_ENV, JWT_SECRET } from '../../utils/env.js'; +import { + getExamAttemptHandler, + getExamAttemptsByExamIdHandler, + getExamAttemptsHandler, + getExams +} from '../../exam-environment/routes/exam-environment.js'; +import { ERRORS } from '../../exam-environment/utils/errors.js'; +import { getChallengeIdsByBlock } from '../../utils/get-challenges.js'; + +/** + * Helper function to get the api url from the shared transcript link. + * Example msTranscriptUrl: https://learn.microsoft.com/en-us/users/mot01/transcript/8u6awert43q1plo. + * + * @param msTranscript Shared transcript link. + * @returns Microsoft transcript api url. + */ +export function getMsTranscriptApiUrl(msTranscript: string) { + try { + const url = new URL(msTranscript); + const transcriptUrlRegex = /\/transcript\/([^/]+)\/?/; + const id = transcriptUrlRegex.exec(url.pathname)?.[1]; + if (!id) { + return { error: `Invalid transcript URL: ${msTranscript}`, data: null }; + } + return { + error: null, + data: `https://learn.microsoft.com/api/profiles/transcript/share/${id}` + }; + } catch (e) { + return { + error: `Invalid transcript URL: ${msTranscript}\n${JSON.stringify(e)}`, + data: null + }; + } +} + +/** + * Wrapper for endpoints related to user account management, + * such as account deletion. + * + * @param fastify The Fastify instance. + * @param _options Fastify options I guess? + * @param done Callback to signal that the logic has completed. + */ +export const userRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.post( + '/account/delete', + { + schema: schemas.deleteMyAccount + }, + async (req, reply) => { + req.log.info({ audit: true }, 'User requested account deletion'); + await fastify.prisma.userToken.deleteMany({ + where: { userId: req.user!.id } + }); + await fastify.prisma.msUsername.deleteMany({ + where: { userId: req.user!.id } + }); + await fastify.prisma.survey.deleteMany({ + where: { userId: req.user!.id } + }); + try { + const userBeforeDelete = await fastify.prisma.user.findUnique({ + where: { id: req.user!.id }, + select: { isDonating: true } + }); + if (userBeforeDelete?.isDonating) { + fastify.Sentry?.metrics?.count('account.deleted_while_donating', 1, { + attributes: { endpoint: '/account/delete' } + }); + } + await fastify.prisma.user.delete({ + where: { id: req.user!.id } + }); + fastify.Sentry?.metrics?.count('account.deleted', 1, { + attributes: { endpoint: '/account/delete' } + }); + } catch (err) { + if ( + err instanceof PrismaClientKnownRequestError && + err.code === 'P2025' + ) { + req.log.warn('User not found for deletion'); + } else { + req.log.error(err, 'Error deleting user account'); + throw err; + } + } + reply.clearOurCookies(); + + return {}; + } + ); + + fastify.delete( + '/users/:userId', + { + schema: schemas.deleteUser + }, + async (req, reply) => { + const { userId } = req.params; + + if (userId !== req.user?.id) { + req.log.warn( + { requestedUserId: userId }, + 'User attempted to delete an account they do not have authorization to.' + ); + void reply.code(403); + return { type: 'error', message: 'forbidden' } as const; + } + + req.log.info({ audit: true }, 'User requested account deletion'); + try { + await fastify.prisma.userToken.deleteMany({ + where: { userId: req.user.id } + }); + await fastify.prisma.msUsername.deleteMany({ + where: { userId: req.user.id } + }); + await fastify.prisma.survey.deleteMany({ + where: { userId: req.user.id } + }); + const userBeforeDelete = await fastify.prisma.user.findUnique({ + where: { id: req.user.id }, + select: { isDonating: true } + }); + if (userBeforeDelete?.isDonating) { + fastify.Sentry?.metrics?.count('account.deleted_while_donating', 1, { + attributes: { endpoint: '/users/:userId' } + }); + } + await fastify.prisma.user.delete({ + where: { id: req.user.id } + }); + fastify.Sentry?.metrics?.count('account.deleted', 1, { + attributes: { endpoint: '/users/:userId' } + }); + } catch (err) { + // Whilst this is behind auth, this should never happen + if ( + err instanceof PrismaClientKnownRequestError && + err.code === 'P2025' + ) { + req.log.warn('User not found for deletion'); + return reply.code(404).send({ type: 'error', message: 'not found' }); + } else { + req.log.error(err, 'Error deleting user account'); + throw err; + } + } + reply.clearOurCookies(); + + return reply.code(204).send(null); + } + ); + + fastify.post( + '/account/reset-progress', + { + schema: schemas.resetMyProgress + }, + async (req, _reply) => { + req.log.info({ audit: true }, 'User requested progress reset'); + await fastify.prisma.userToken.deleteMany({ + where: { userId: req.user!.id } + }); + await fastify.prisma.msUsername.deleteMany({ + where: { userId: req.user!.id } + }); + await fastify.prisma.survey.deleteMany({ + where: { userId: req.user!.id } + }); + await fastify.prisma.user.update({ + where: { id: req.user!.id }, + data: createResetProperties() + }); + + fastify.Sentry?.metrics?.count('account.progress_reset', 1); + + return {}; + } + ); + + fastify.delete( + '/account/reset-module', + { + schema: schemas.resetModule + }, + deleteResetModule + ); + // TODO(Post-MVP): POST -> PUT + fastify.post('/user/user-token', async (req, _reply) => { + req.log.info({ audit: true }, 'User requested a new user token'); + + await fastify.prisma.userToken.deleteMany({ + where: { userId: req.user?.id } + }); + + const token = await fastify.prisma.userToken.create({ + data: { + created: new Date(), + id: customNanoid(), + userId: req.user!.id, + // TODO(Post-MVP): expire after ttl has passed. + ttl: 77760000000 // 900 * 24 * 60 * 60 * 1000 + } + }); + + return { + userToken: encodeUserToken(token.id) + }; + }); + + fastify.delete( + '/user/user-token', + { + schema: schemas.deleteUserToken + }, + async (req, reply) => { + req.log.info({ audit: true }, 'User requested token deletion'); + + const { count } = await fastify.prisma.userToken.deleteMany({ + where: { userId: req.user?.id } + }); + + if (count === 0) { + req.log.warn('No userToken found for deletion'); + void reply.code(404); + return { + message: 'userToken not found', + type: 'info' + } as const; + } + return { userToken: null }; + } + ); + + fastify.post( + '/user/report-user', + { + schema: schemas.reportUser, + preHandler: (req, _reply, done) => { + req.body.reportDescription = trimTags(req.body.reportDescription); + done(); + } + }, + async (req, reply) => { + req.log.info( + { reportedUsername: req.body.username }, + 'User reported another user' + ); + + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id } + }); + + if (!user.email) { + req.log.warn('User has no email'); + void reply.code(400); + fastify.Sentry?.metrics?.count('user.report_submitted', 1, { + attributes: { result: 'no_email' } + }); + return reply.send({ + type: 'danger', + message: 'flash.report-error' + }); + } + + const { username, reportDescription: report } = req.body; + + // TODO: `findUnique` once db migration forces unique usernames + const maybeReportedUsers = await mapErr( + fastify.prisma.user.findMany({ + where: { username } + }) + ); + + if (maybeReportedUsers.hasError) { + req.log.error( + { err: maybeReportedUsers.error, username }, + 'Error finding reported user.' + ); + fastify.Sentry?.captureException(maybeReportedUsers.error); + void reply.code(500); + fastify.Sentry?.metrics?.count('user.report_submitted', 1, { + attributes: { result: 'lookup_error' } + }); + return { + type: 'danger', + message: 'flash.generic-error' + } as const; + } + + const reportedUsers = maybeReportedUsers.data; + + if (reportedUsers.length !== 1) { + req.log.warn({ username }, 'Reported user not found'); + void reply.code(404); + fastify.Sentry?.metrics?.count('user.report_submitted', 1, { + attributes: { result: 'not_found' } + }); + return { + type: 'danger', + message: 'flash.report-error' + } as const; + } + + const reportedUser = reportedUsers[0]!; + + await fastify.sendEmail({ + from: 'team@freecodecamp.org', + to: 'support@freecodecamp.org', + cc: user.email, + subject: `Abuse Report : Reporting ${reportedUser.username}'s profile.`, + text: generateReportEmail(user, reportedUser, report) + }); + + fastify.Sentry?.metrics?.count('user.report_submitted', 1, { + attributes: { result: 'success' } + }); + + reply.send({ + type: 'info', + message: 'flash.report-sent', + variables: { email: user.email } + }); + } + ); + + fastify.delete( + '/user/ms-username', + { + schema: schemas.deleteMsUsername + }, + async (req, reply) => { + req.log.info({ audit: true }, 'User requested unlinking of msUsername'); + + try { + await fastify.prisma.msUsername.deleteMany({ + where: { userId: req.user?.id } + }); + + // TODO(Post-MVP): return a generic success message. + return { msUsername: null }; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error unlinking msUsername'); + void reply.code(500); + void reply.send({ + message: 'flash.ms.transcript.unlink-err', + type: 'error' + }); + } + } + ); + + fastify.post( + '/user/ms-username', + { + schema: schemas.postMsUsername, + errorHandler(error, req, reply) { + if (error.validation) { + req.log.warn( + { validationError: error.validation }, + 'Request validation failed' + ); + void reply.code(400).send({ + message: 'flash.ms.transcript.link-err-1', + type: 'error' + }); + } else { + fastify.errorHandler(error, req, reply); + } + } + }, + async (req, reply) => { + req.log.info({ audit: true }, 'User requested linking of msUsername'); + + try { + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id } + }); + + const maybeTranscriptUrl = getMsTranscriptApiUrl( + req.body.msTranscriptUrl + ); + + if (maybeTranscriptUrl.error !== null) { + req.log.warn('Unable to parse Microsoft transcript URL'); + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'invalid_url' } + }); + return reply + .status(400) + .send({ type: 'error', message: 'flash.ms.transcript.link-err-1' }); + } + + const transcriptUrl = maybeTranscriptUrl.data; + + const startTime = performance.now(); + const msApiRes = await fetch(transcriptUrl).catch(err => { + fastify.Sentry?.metrics?.distribution( + 'ms_username.transcript_fetch_latency_ms', + performance.now() - startTime, + { unit: 'millisecond' } + ); + throw err; + }); + fastify.Sentry?.metrics?.distribution( + 'ms_username.transcript_fetch_latency_ms', + performance.now() - startTime, + { unit: 'millisecond' } + ); + + if (!msApiRes.ok) { + req.log.warn( + { status: msApiRes.status }, + "Unable to fetch user's Microsoft transcript" + ); + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'fetch_failed' } + }); + return reply + .status(404) + .send({ type: 'error', message: 'flash.ms.transcript.link-err-2' }); + } + + const { userName } = (await msApiRes.json()) as { userName: string }; + + if (!userName) { + fastify.Sentry?.captureException( + new Error('No userName found in Microsoft transcript response') + ); + req.log.error('No userName found in Microsoft transcript response'); + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'missing_username' } + }); + return reply.status(500).send({ + type: 'error', + message: 'flash.ms.transcript.link-err-3' + }); + } + + // TODO(Post-MVP): make msUsername unique, then we can simply try to + // create the record and catch the error. + const usernameUsed = !!(await fastify.prisma.msUsername.findFirst({ + where: { + msUsername: userName + } + })); + + if (usernameUsed) { + req.log.warn('msUsername already in use'); + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'username_taken' } + }); + return reply.status(409).send({ + type: 'error', + message: 'flash.ms.transcript.link-err-4' + }); + } + + // TODO(Post-MVP): do we need to store tll in the database? We aren't + // storing the creation date, so we can't expire it. + + // 900 days in ms + const ttl = 900 * 24 * 60 * 60 * 1000; + + // TODO(Post-MVP): make userId unique and then we can upsert. + + await fastify.prisma.msUsername.deleteMany({ + where: { userId: user.id } + }); + + await fastify.prisma.msUsername.create({ + data: { + msUsername: userName, + ttl, + userId: user.id + } + }); + + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'success' } + }); + + return { msUsername: userName }; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error linking msUsername'); + fastify.Sentry?.metrics?.count('ms_username.link_completed', 1, { + attributes: { result: 'error' } + }); + return reply.code(500).send({ + type: 'error', + message: 'flash.ms.transcript.link-err-6' + }); + } + } + ); + + fastify.post( + '/user/submit-survey', + { + schema: schemas.submitSurvey, + errorHandler(error, request, reply) { + if (error.validation) { + void reply.code(400).send({ + type: 'error', + message: 'flash.survey.err-1' + }); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + req.log.info('User submitted a survey'); + try { + const user = await fastify.prisma.user.findUniqueOrThrow({ + where: { id: req.user?.id } + }); + const { surveyResults } = req.body; + const { title } = surveyResults; + + const completedSurveys = await fastify.prisma.survey.findMany({ + where: { userId: user.id } + }); + + const surveyAlreadyTaken = completedSurveys.some( + s => s.title === title + ); + if (surveyAlreadyTaken) { + req.log.warn('Survey already taken'); + return reply.code(409).send({ + type: 'error', + message: 'flash.survey.err-2' + }); + } + + const newSurvey = { + ...surveyResults, + userId: user.id + }; + + await fastify.prisma.survey.create({ + data: newSurvey + }); + + fastify.Sentry?.metrics?.count('survey.submitted', 1, { + attributes: { surveyTitle: title } + }); + + return { + type: 'success', + message: 'flash.survey.success' + } as const; + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error submitting survey'); + void reply.code(500); + return { + type: 'error', + message: 'flash.survey.err-3' + } as const; + } + } + ); + + fastify.post( + '/user/exam-environment/token', + { + schema: schemas.userExamEnvironmentToken + }, + examEnvironmentTokenHandler + ); + + fastify.get( + '/user/exam-environment/token', + { + schema: schemas.getUserExamEnvironmentToken + }, + getExamEnvironmentToken + ); + + fastify.get( + '/user/exam-environment/exam/attempts', + { + schema: examEnvironmentSchemas.examEnvironmentGetExamAttempts + }, + getExamAttemptsHandler + ); + fastify.get( + '/user/exam-environment/exam/attempt/:attemptId', + { + schema: examEnvironmentSchemas.examEnvironmentGetExamAttempt + }, + getExamAttemptHandler + ); + fastify.get( + '/user/exam-environment/exams/:examId/attempts', + { + schema: examEnvironmentSchemas.examEnvironmentGetExamAttemptsByExamId + }, + getExamAttemptsByExamIdHandler + ); + fastify.get( + '/user/exam-environment/exams', + { + schema: examEnvironmentSchemas.examEnvironmentExams + }, + getExams + ); + + done(); +}; + +async function deleteResetModule( + this: FastifyInstance, + req: UpdateReqType, + reply: UpdateReplyType +) { + const { blockIds } = req.body; + req.log.info( + { audit: true, blockIds }, + 'User requested module reset for blocks' + ); + + const resetSet = new Set(blockIds.flatMap(getChallengeIdsByBlock)); + + if (resetSet.size === 0) { + void reply.code(400); + return { message: 'No matching blocks found', type: 'error' }; + } + + const user = await this.prisma.user.findUniqueOrThrow({ + where: { id: req.user!.id }, + select: { + completedChallenges: true, + savedChallenges: true, + partiallyCompletedChallenges: true + } + }); + + const filteredCompletedChallenges = normalizeChallenges( + user.completedChallenges + ).filter(c => !resetSet.has(c.id)); + + const filteredSavedChallenges = user.savedChallenges.filter( + c => !resetSet.has(c.id) + ); + + const filteredPartiallyCompletedChallenges = + user.partiallyCompletedChallenges.filter(c => !resetSet.has(c.id)); + + await this.prisma.user.update({ + where: { id: req.user!.id }, + data: { + completedChallenges: filteredCompletedChallenges, + savedChallenges: filteredSavedChallenges, + partiallyCompletedChallenges: filteredPartiallyCompletedChallenges + }, + select: { + id: true + } + }); + + return { removedChallengeIds: Array.from(resetSet) }; +} + +/** + * Generate a new authorization token for the given user, and invalidates any existing tokens. + * + * Requires the user to be authenticated. + */ +async function examEnvironmentTokenHandler( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + req.log.info({ audit: true }, 'User requested a new exam environment token'); + const userId = req.user?.id; + if (!userId) { + throw new Error('Unreachable. User should be authenticated.'); + } + + // In non-production environments, only staff are allowed to generate a token + if ( + DEPLOYMENT_ENV !== 'production' && + (!req.user?.email?.endsWith('@freecodecamp.org') || + !req.user?.emailVerified) + ) { + req.log.warn( + { deploymentEnv: DEPLOYMENT_ENV }, + 'User not allowed to generate authorization token' + ); + void reply.code(403); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT( + `User not allowed to generate authorization token in ${DEPLOYMENT_ENV} environment.` + ) + ); + } + + // Delete (invalidate) any existing tokens for the user. + await this.prisma.examEnvironmentAuthorizationToken.deleteMany({ + where: { + userId + } + }); + + const ONE_YEAR_IN_MS = 365 * 24 * 60 * 60 * 1000; + + const token = await this.prisma.examEnvironmentAuthorizationToken.create({ + data: { + expireAt: new Date(Date.now() + ONE_YEAR_IN_MS), + userId + } + }); + + this.Sentry?.metrics?.count('exam.token_minted', 1); + + const examEnvironmentAuthorizationToken = jwt.sign( + { examEnvironmentAuthorizationToken: token.id }, + JWT_SECRET + ); + + void reply.code(201); + void reply.send({ + examEnvironmentAuthorizationToken + }); +} + +/** + * Plugin containing GET routes for user account management. They are kept + * separate because they do not require CSRF protection. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +export const userGetRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + const getSessionUserHandler = async ( + req: UpdateReqType, + res: FastifyReply + ) => { + // This is one of the most requested routes. To avoid spamming the logs + // with this route, we'll log requests at the debug level. + req.log.debug('User requested session'); + + // Handle unauthenticated users - this is not an error, it's how the client + // determines if they are signed in or not + if (!req.user?.id) { + req.log.debug('Unauthenticated user requested session'); + return { user: {}, result: '' }; + } + + try { + const userTokenP = fastify.prisma.userToken.findFirst({ + where: { userId: req.user.id } + }); + + const userP = fastify.prisma.user.findUnique({ + where: { id: req.user.id }, + select: { + about: true, + acceptedPrivacyTerms: true, + completedChallenges: true, + completedDailyCodingChallenges: true, + completedExams: true, + currentChallengeId: true, + quizAttempts: true, + email: true, + emailVerified: true, + githubProfile: true, + id: true, + is2018DataVisCert: true, + is2018FullStackCert: true, + isA2EnglishCert: true, + isApisMicroservicesCert: true, + isBackEndCert: true, + isCheater: true, + isCollegeAlgebraPyCertV8: true, + isDataAnalysisPyCertV7: true, + isDataVisCert: true, + isDonating: true, + isFoundationalCSharpCertV8: true, + isFrontEndCert: true, + isFrontEndLibsCert: true, + isFullStackCert: true, + isClassroomAccount: true, + isHonest: true, + isInfosecCertV7: true, + isInfosecQaCert: true, + isJavascriptCertV9: true, + isJsAlgoDataStructCert: true, + isJsAlgoDataStructCertV8: true, + isMachineLearningPyCertV7: true, + isPythonCertV9: true, + isQaCertV7: true, + isRelationalDatabaseCertV8: true, + isRelationalDatabaseCertV9: true, + isRespWebDesignCert: true, + isRespWebDesignCertV9: true, + isSciCompPyCertV7: true, + isFrontEndLibsCertV9: true, + isBackEndDevApisCertV9: true, + isFullStackDeveloperCertV9: true, + isB1EnglishCert: true, + isA2SpanishCert: true, + isA2ChineseCert: true, + isA1ChineseCert: true, + keyboardShortcuts: true, + linkedin: true, + location: true, + name: true, + partiallyCompletedChallenges: true, + picture: true, + portfolio: true, + experience: true, + profileUI: true, + progressTimestamps: true, + savedChallenges: true, + sendQuincyEmail: true, + socrates: true, + theme: true, + twitter: true, + bluesky: true, + username: true, + usernameDisplay: true, + website: true, + yearsTopContributor: true + } + }); + + const completedSurveysP = fastify.prisma.survey.findMany({ + where: { userId: req.user.id } + }); + + const msUsernameP = fastify.prisma.msUsername.findFirst({ + where: { userId: req.user.id } + }); + + const [userToken, user, completedSurveys, msUsername] = await Promise.all( + [userTokenP, userP, completedSurveysP, msUsernameP] + ); + + if (!user?.username) { + fastify.Sentry?.captureException(new Error('User has no username')); + req.log.error('User has no username'); + void res.code(500); + return { user: {}, result: '' }; + } + // TODO: DRY this (the creation of the response body) and + // get-public-profile's response body creation. + + const encodedToken = userToken + ? encodeUserToken(userToken.id) + : undefined; + + const [flags, rest] = splitUser(user); + + const { + email, + emailVerified, + username, + usernameDisplay, + completedChallenges, + completedDailyCodingChallenges, + progressTimestamps, + twitter, + bluesky, + profileUI, + currentChallengeId, + location, + name, + theme, + experience, + socrates, + ...publicUser + } = rest; + + await res.send({ + user: { + [username]: { + ...removeNulls(publicUser), + sendQuincyEmail: publicUser.sendQuincyEmail, + ...normalizeFlags(flags), + picture: publicUser.picture ?? '', + email: email ?? '', + currentChallengeId: currentChallengeId ?? '', + completedChallenges: normalizeChallenges(completedChallenges), + completedChallengeCount: completedChallenges.length, + completedDailyCodingChallenges, + // This assertion is necessary until the database is normalized. + calendar: getCalendar( + progressTimestamps as ProgressTimestamp[] | null + ), + emailVerified: !!emailVerified, + // This assertion is necessary until the database is normalized. + points: getPoints(progressTimestamps as ProgressTimestamp[] | null), + profileUI: normalizeProfileUI(profileUI), + // TODO(Post-MVP) remove this and just use emailVerified + isEmailVerified: !!emailVerified, + joinDate: new ObjectId(user.id).getTimestamp().toISOString(), + location: location ?? '', + name: name ?? '', + theme: theme ?? 'default', + twitter: normalizeTwitter(twitter), + bluesky: normalizeBluesky(bluesky), + username, + usernameDisplay: usernameDisplay || username, + userToken: encodedToken, + completedSurveys: normalizeSurveys(completedSurveys), + experience: experience.map(removeNulls), + msUsername: msUsername?.msUsername, + socrates: socrates ?? true + } + }, + result: user.username + }); + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Error fetching session user'); + void res.code(500); + return { user: {}, result: '' }; + } + }; + + fastify.get( + '/user/session-user', + { + schema: schemas.getSessionUser + }, + getSessionUserHandler + ); + + done(); +}; + +async function getExamEnvironmentToken( + this: FastifyInstance, + req: UpdateReqType, + reply: FastifyReply +) { + req.log.info('User requested their exam environment token'); + const userId = req.user?.id; + if (!userId) { + throw new Error('Unreachable. User should be authenticated.'); + } + + const token = await this.prisma.examEnvironmentAuthorizationToken.findUnique({ + where: { + userId, + expireAt: { + gt: new Date() + } + } + }); + + if (!token) { + void reply.code(404); + return reply.send( + ERRORS.FCC_ERR_EXAM_ENVIRONMENT('No valid token found for user.') + ); + } + + const examEnvironmentAuthorizationToken = jwt.sign( + { examEnvironmentAuthorizationToken: token.id }, + JWT_SECRET + ); + + return reply.send({ + examEnvironmentAuthorizationToken + }); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth-dev.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth-dev.ts new file mode 100644 index 0000000000000000000000000000000000000000..81780992edc438c08fd8f3e42050f8329f900c0f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth-dev.ts @@ -0,0 +1,21 @@ +import type { FastifyPluginCallback } from 'fastify'; + +import { devAuth } from '../../plugins/auth-dev.js'; + +/** + * Route handler for development login. + * + * @deprecated + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param done Callback to signal that the logic has completed. + */ +export const devAuthRoutes: FastifyPluginCallback = ( + fastify, + _options, + done +) => { + void fastify.register(devAuth); + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..29de93f913e9a589a7cc2aa351a7200859636a0b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.test.ts @@ -0,0 +1,215 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest'; +import { + setupServer, + superRequest, + createSuperRequest +} from '../../../vitest.utils.js'; +import { AUTH0_DOMAIN } from '../../utils/env.js'; + +const mockedFetch = vi.fn(); +vi.spyOn(globalThis, 'fetch').mockImplementation(mockedFetch); + +const newUserEmail = 'a.n.random@user.com'; + +const mockAuth0NotOk = () => ({ + ok: false, + status: 503 +}); + +const mockAuth0Unauthorized = () => ({ + ok: false, + status: 401 +}); + +const mockAuth0InvalidEmail = () => ({ + ok: true, + json: () => ({ email: 'invalid-email' }) +}); + +const mockAuth0ValidEmail = () => ({ + ok: true, + json: () => ({ email: newUserEmail }) +}); + +vi.mock('../../utils/env', async () => { + const actual = + await vi.importActual( + '../../utils/env' + ); + return { + ...actual, + FCC_ENABLE_DEV_LOGIN_MODE: false + }; +}); + +describe('auth0 routes', () => { + setupServer(); + describe('GET /signin', () => { + it('should redirect to the auth0 login page', async () => { + const res = await superRequest('/signin', { method: 'GET' }); + + expect(res.status).toBe(302); + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const redirectUrl = new URL(res.headers.location); + expect(redirectUrl.host).toMatch(AUTH0_DOMAIN); + expect(redirectUrl.pathname).toBe('/authorize'); + }); + }); + + describe('GET /mobile-login', () => { + let superGet: ReturnType; + + beforeAll(() => { + superGet = createSuperRequest({ method: 'GET' }); + }); + beforeEach(async () => { + await fastifyTestInstance.prisma.user.deleteMany({ + where: { email: newUserEmail } + }); + }); + + it('should capture and return 401 when Auth0 userinfo is down (5xx)', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0NotOk()); + const count = vi.fn(); + const captureException = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer invalid-token' + ); + + expect(res.body).toStrictEqual({ + type: 'danger', + message: 'We could not log you in, please try again in a moment.' + }); + expect(res.status).toBe(401); + expect(count).toHaveBeenCalledWith('auth.mobile_login_attempted', 1, { + attributes: { result: 'failure', reason: 'no_email' } + }); + expect(captureException).toHaveBeenCalledWith( + new Error('Auth0 userinfo request failed'), + { extra: { status: 503 } } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should not capture to Sentry for an expected Auth0 4xx (invalid or expired token)', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0Unauthorized()); + const count = vi.fn(); + const captureException = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer invalid-token' + ); + + expect(res.status).toBe(401); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should return 400 if the email is not valid', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0InvalidEmail()); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer valid-token' + ); + + expect(res.body).toStrictEqual({ + type: 'danger', + message: 'The email is incorrectly formatted' + }); + expect(res.status).toBe(400); + expect(count).toHaveBeenCalledWith('auth.mobile_login_attempted', 1, { + attributes: { result: 'failure', reason: 'invalid_format' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should set the jwt_access_token cookie if the authorization header is valid', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0ValidEmail()); + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const res = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer valid-token' + ); + + expect(res.status).toBe(200); + expect(res.get('Set-Cookie')).toEqual( + expect.arrayContaining([expect.stringMatching(/jwt_access_token=/)]) + ); + expect(count).toHaveBeenCalledWith('auth.mobile_login_attempted', 1, { + attributes: { result: 'success' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + it('should create a user if they do not exist', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0ValidEmail()); + const existingUserCount = await fastifyTestInstance.prisma.user.count(); + + const res = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer valid-token' + ); + + const newUserCount = await fastifyTestInstance.prisma.user.count(); + + expect(existingUserCount).toBe(0); + expect(newUserCount).toBe(1); + expect(res.status).toBe(200); + }); + + it('should redirect to returnTo if already logged in', async () => { + mockedFetch.mockResolvedValueOnce(mockAuth0ValidEmail()); + const firstRes = await superGet('/mobile-login').set( + 'Authorization', + 'Bearer valid-token' + ); + + expect(firstRes.status).toBe(200); + + const res = await superRequest('/mobile-login', { + method: 'GET', + setCookies: firstRes.get('Set-Cookie') + }) + .set('Authorization', 'Bearer does-not-matter') + .set('Referer', 'https://www.freecodecamp.org/back-home'); + + expect(res.status).toBe(302); + expect(res.headers.location).toBe( + 'https://www.freecodecamp.org/back-home' + ); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.ts new file mode 100644 index 0000000000000000000000000000000000000000..c08b29a547cb684818cdc9ae3213261ac6d5f4fb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/auth.ts @@ -0,0 +1,114 @@ +import type { FastifyPluginCallback, FastifyRequest } from 'fastify'; +import validator from 'validator'; + +import { AUTH0_DOMAIN } from '../../utils/env.js'; +import { auth0Client } from '../../plugins/auth0.js'; +import { createAccessToken } from '../../utils/tokens.js'; +import { findOrCreateUser } from '../helpers/auth-helpers.js'; +import { clientNetInfo } from '../../utils/logger.js'; + +const getEmailFromAuth0 = async ( + req: FastifyRequest +): Promise => { + const auth0Res = await fetch(`https://${AUTH0_DOMAIN}/userinfo`, { + headers: { + Authorization: req.headers.authorization ?? '' + } + }); + + if (!auth0Res.ok) { + req.log.warn({ status: auth0Res.status }, 'Auth0 userinfo request failed'); + if (auth0Res.status >= 500) { + req.server.Sentry?.captureException( + new Error('Auth0 userinfo request failed'), + { extra: { status: auth0Res.status } } + ); + } + return null; + } + + // For now, we assume the response is a JSON object. If not, we can't proceed + // and the only safe thing to do is to throw. + const { email } = (await auth0Res.json()) as { email?: string }; + return typeof email === 'string' ? email : null; +}; + +/** + * Route handler for Mobile authentication. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + * + */ +export const mobileAuth0Routes: FastifyPluginCallback = ( + fastify, + _options, + done +) => { + // TODO(Post-MVP): move this into the app, so that we add this hook once for + // all auth routes. + fastify.addHook('onRequest', fastify.redirectIfSignedIn); + + fastify.get('/mobile-login', async (req, reply) => { + const email = await getEmailFromAuth0(req); + + req.log.debug('Mobile app login attempt'); + + if (!email) { + req.log.error( + clientNetInfo(req), + 'Could not get email from Auth0 to log in' + ); + + fastify.Sentry?.metrics?.count('auth.mobile_login_attempted', 1, { + attributes: { result: 'failure', reason: 'no_email' } + }); + + return reply.status(401).send({ + message: 'We could not log you in, please try again in a moment.', + type: 'danger' + }); + } + if (!validator.default.isEmail(email)) { + req.log.warn( + clientNetInfo(req), + 'Email is incorrectly formatted for login' + ); + + fastify.Sentry?.metrics?.count('auth.mobile_login_attempted', 1, { + attributes: { result: 'failure', reason: 'invalid_format' } + }); + + return reply.status(400).send({ + message: 'The email is incorrectly formatted', + type: 'danger' + }); + } + + const { id } = await findOrCreateUser(fastify, email); + + fastify.Sentry?.metrics?.count('auth.mobile_login_attempted', 1, { + attributes: { result: 'success' } + }); + + reply.setAccessTokenCookie(createAccessToken(id)); + }); + + done(); +}; + +/** + * Route handler for authentication routes. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +export const authRoutes: FastifyPluginCallback = (fastify, _options, done) => { + // All routes are registered by the auth0 plugin, but we need an extra plugin + // (this one) to encapsulate the auth0 decorators. Otherwise auth0OAuth will + // be available globally. + void fastify.register(auth0Client); + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1580fa3a954c033aa633c4fc2615c0757ab85ee --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.test.ts @@ -0,0 +1,421 @@ +import { + describe, + it, + test, + expect, + beforeAll, + beforeEach, + afterAll, + vi +} from 'vitest'; +import { + defaultUserEmail, + defaultUserId, + resetDefaultUser, + setupServer, + superRequest +} from '../../../vitest.utils.js'; +import { getFallbackFullStackDate } from '../helpers/certificate-utils.js'; + +const DATE_NOW = Date.now(); + +describe('certificate routes', () => { + setupServer(); + + describe('Unauthenticated user', () => { + beforeAll(async () => { + await resetDefaultUser(); + + vi.useFakeTimers(); + vi.setSystemTime(DATE_NOW); + }); + + afterAll(() => { + vi.useRealTimers(); + }); + + describe('GET /certificate/showCert/:username/:certSlug', () => { + beforeEach(async () => { + await fastifyTestInstance.prisma.user.updateMany({ + where: { email: defaultUserEmail }, + data: { + username: 'foobar', + name: 'foobar', + isHonest: true, + isBanned: false, + isCheater: false, + profileUI: { isLocked: false, showCerts: true, showTimeLine: true } + } + }); + }); + test('should return user not found if the user cannot be found', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest( + '/certificate/showCert/not-a-valid-user-name/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.username-not-found', + variables: { username: 'not-a-valid-user-name' } + } + ] + }); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith( + 'certificate.public_view_blocked', + 1, + { + attributes: { reason: 'user_not_found' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + test('should ask user to add name if there is no name', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { name: null } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.add-name' + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return not eligible if user is banned', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isBanned: true } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.not-eligible' + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return not eligible if user is cheater', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isCheater: true } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.not-eligible' + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return not honest if user is not honest', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { isHonest: false } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.not-honest', + variables: { username: 'foobar' } + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return profile private if profile is private', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + // All properties need to be defined, as this op SETs `profileUI` + profileUI: { isLocked: true, showTimeLine: true, showCerts: true } + } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.profile-private', + variables: { username: 'foobar' } + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return certs private if certs are private', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + profileUI: { showCerts: false, showTimeLine: true, isLocked: false } + } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.certs-private', + variables: { username: 'foobar' } + } + ] + }); + expect(response.status).toBe(200); + }); + test('should return timeline private if timeline is private', async () => { + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + profileUI: { showTimeLine: false, showCerts: true, isLocked: false } + } + }); + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.timeline-private', + variables: { username: 'foobar' } + } + ] + }); + expect(response.status).toBe(200); + }); + + test('should not return user full name if `showName` is `false`', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + profileUI: { + showTimeLine: true, + showCerts: true, + isLocked: false, + showName: false + }, + isJsAlgoDataStructCert: true, + completedChallenges: [ + { + id: '561abd10cb81ac38a17513bc', // Cert ID + completedDate: DATE_NOW + } + ] + } + }); + + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + + // TODO: delete this assertion once there's only one status 200 response + expect(response.body).toHaveProperty('username', 'foobar'); + expect(response.body).not.toHaveProperty('name'); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith('certificate.public_viewed', 1, { + attributes: { + certSlug: 'javascript-algorithms-and-data-structures', + nameVisibility: 'hidden' + } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return user full name if `showName` is `true`', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await fastifyTestInstance.prisma.user.update({ + where: { id: defaultUserId }, + data: { + profileUI: { + showTimeLine: true, + showCerts: true, + isLocked: false, + showName: true + }, + isJsAlgoDataStructCert: true, + completedChallenges: [ + { + id: '561abd10cb81ac38a17513bc', // Cert ID + completedDate: DATE_NOW + } + ] + } + }); + + const response = await superRequest( + '/certificate/showCert/foobar/javascript-algorithms-and-data-structures', + { + method: 'GET' + } + ); + + expect(response.body).toHaveProperty('name', 'foobar'); + expect(response.status).toBe(200); + expect(count).toHaveBeenCalledWith('certificate.public_viewed', 1, { + attributes: { + certSlug: 'javascript-algorithms-and-data-structures', + nameVisibility: 'shown' + } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('should return cert-not-found if there is no cert with that slug', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest( + '/certificate/showCert/foobar/not-a-valid-cert-slug', + { + method: 'GET' + } + ); + expect(response.body).toEqual({ + messages: [ + { + type: 'info', + message: 'flash.cert-not-found', + variables: { certSlug: 'not-a-valid-cert-slug' } + } + ] + }); + expect(response.status).toBe(404); + expect(count).toHaveBeenCalledWith( + 'certificate.public_view_blocked', + 1, + { + attributes: { reason: 'unknown_cert_slug' } + } + ); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + }); +}); + +const fullStackChallenges = [ + { + completedDate: 1585210952511, + id: '5a553ca864b52e1d8bceea14' + }, + { + completedDate: 1585210952511, + id: '561add10cb82ac38a17513bc' + }, + { + completedDate: 1588665778679, + id: '561acd10cb82ac38a17513bc' + }, + { + completedDate: 1685210952511, + id: '561abd10cb81ac38a17513bc' + }, + { + completedDate: 1585210952511, + id: '561add10cb82ac38a17523bc' + }, + { + completedDate: 1588665778679, + id: '561add10cb82ac38a17213bc' + } +]; + +describe('helper functions', () => { + describe('getFallbackFullStackDate', () => { + it('should return the date of the latest completed challenge', () => { + expect(getFallbackFullStackDate(fullStackChallenges, 123)).toBe( + 1685210952511 + ); + }); + + it('should fall back to completedDate if no certifications are provided', () => { + expect(getFallbackFullStackDate([], 123)).toBe(123); + }); + + it('should fall back to completedDate if none of the certifications have been completed', () => { + expect( + getFallbackFullStackDate([{ completedDate: 567, id: 'abc' }], 123) + ).toBe(123); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.ts new file mode 100644 index 0000000000000000000000000000000000000000..80dee746e5ad50dd986762835bc4b6176e919ec9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/certificate.ts @@ -0,0 +1,294 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import { find } from 'lodash-es'; +import * as schemas from '../../schemas.js'; +import { + certSlugTypeMap, + certToTitleMap, + certToIdMap, + completionHours, + oldDataVizId +} from '@freecodecamp/shared/config/certification-settings'; +import { + getFallbackFullStackDate, + isKnownCertSlug +} from '../helpers/certificate-utils.js'; +import { normalizeDate } from '../../utils/normalize.js'; + +/** + * Plugin for the unprotected certificate endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const unprotectedCertificateRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get( + '/certificate/showCert/:username/:certSlug', + { + schema: schemas.certSlug + }, + async (req, reply) => { + const username = req.params.username.toLowerCase(); + const certSlug = req.params.certSlug; + + if (!isKnownCertSlug(certSlug)) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'unknown_cert_slug' } + }); + req.log.warn({ certSlug }, 'Unknown certSlug'); + void reply.code(404); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.cert-not-found', + variables: { certSlug } + } + ] + }); + } + + const certType = certSlugTypeMap[certSlug]; + const certId = certToIdMap[certSlug]; + const certTitle = certToTitleMap[certSlug]; + const completionTime = completionHours[certSlug] || 300; + const user = await fastify.prisma.user.findFirst({ + where: { username }, + select: { + isBanned: true, + isCheater: true, + isA2EnglishCert: true, + isFrontEndCert: true, + isBackEndCert: true, + isFullStackCert: true, + isRespWebDesignCert: true, + isRespWebDesignCertV9: true, + isFrontEndLibsCert: true, + isJavascriptCertV9: true, + isJsAlgoDataStructCert: true, + isJsAlgoDataStructCertV8: true, + isDataVisCert: true, + is2018DataVisCert: true, + isApisMicroservicesCert: true, + isInfosecQaCert: true, + isPythonCertV9: true, + isQaCertV7: true, + isInfosecCertV7: true, + isSciCompPyCertV7: true, + isDataAnalysisPyCertV7: true, + isMachineLearningPyCertV7: true, + isRelationalDatabaseCertV8: true, + isRelationalDatabaseCertV9: true, + isCollegeAlgebraPyCertV8: true, + isFoundationalCSharpCertV8: true, + isFrontEndLibsCertV9: true, + isBackEndDevApisCertV9: true, + isFullStackDeveloperCertV9: true, + isB1EnglishCert: true, + isA2SpanishCert: true, + isA2ChineseCert: true, + isA1ChineseCert: true, + isHonest: true, + username: true, + name: true, + completedChallenges: true, + profileUI: true + } + }); + + if (user === null) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'user_not_found' } + }); + req.log.debug({ username }, 'User not found'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.username-not-found', + variables: { username } + } + ] + }); + } + + if (user.isCheater || user.isBanned) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'user_ineligible' } + }); + req.log.debug({ username }, 'User is banned or a cheater'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.not-eligible' + } + ] + }); + } + + if (!user.isHonest) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'not_honest' } + }); + req.log.debug({ username }, 'User has not accepted honesty policy'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.not-honest', + variables: { username } + } + ] + }); + } + + if (user.profileUI?.isLocked) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'profile_locked' } + }); + req.log.debug({ username }, 'User has a locked profile'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.profile-private', + variables: { username } + } + ] + }); + } + + if (!user.name) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'missing_name' } + }); + req.log.debug({ username }, 'User has not added a name'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.add-name' + } + ] + }); + } + + if (!user.profileUI?.showCerts) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'certs_private' } + }); + req.log.debug({ username }, 'User has private certs'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.certs-private', + variables: { username } + } + ] + }); + } + + if (!user.profileUI?.showTimeLine) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'timeline_private' } + }); + req.log.debug({ username }, 'User has private timeline'); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.timeline-private', + variables: { username } + } + ] + }); + } + + if (!user[certType]) { + fastify.Sentry?.metrics?.count('certificate.public_view_blocked', 1, { + attributes: { reason: 'cert_not_completed' } + }); + req.log.debug( + { username, certTitle }, + 'User has not completed the certification' + ); + return reply.send({ + messages: [ + { + type: 'info', + message: 'flash.user-not-certified', + variables: { username, cert: certTitle } + } + ] + }); + } + + const { completedChallenges } = user; + const certChallenge = find( + completedChallenges, + ({ id }) => certId === id + ); + + let { completedDate = Date.now() } = certChallenge || {}; + + // the challenge id has been rotated for isDataVisCert + if (certType === 'isDataVisCert' && !certChallenge) { + const oldDataVisIdChall = find( + completedChallenges, + ({ id }) => oldDataVizId === id + ); + + if (oldDataVisIdChall) { + completedDate = oldDataVisIdChall.completedDate || completedDate; + } + } + + // if fullcert is not found, return the latest completedDate + if (certType === 'isFullStackCert' && !certChallenge) { + completedDate = getFallbackFullStackDate( + completedChallenges, + completedDate + ); + } + + const { name } = user; + + if (!user.profileUI.showName) { + req.log.debug({ username }, 'User has private name'); + fastify.Sentry?.metrics?.count('certificate.public_viewed', 1, { + attributes: { certSlug, nameVisibility: 'hidden' } + }); + void reply.code(200); + return reply.send({ + certSlug, + certTitle, + username, + date: normalizeDate(completedDate), + completionTime + }); + } + + fastify.Sentry?.metrics?.count('certificate.public_viewed', 1, { + attributes: { certSlug, nameVisibility: 'shown' } + }); + void reply.code(200); + return reply.send({ + certSlug, + certTitle, + username, + name, + date: normalizeDate(completedDate), + completionTime + }); + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..caf1aab263525f86ae53e73981d667e5f03aef42 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.test.ts @@ -0,0 +1,25 @@ +import request from 'supertest'; +import { describe, test, expect } from 'vitest'; + +import { setupServer } from '../../../vitest.utils.js'; +import { endpoints } from './deprecated-endpoints.js'; + +describe('Deprecated endpoints', () => { + setupServer(); + + endpoints.forEach(([endpoint, method]) => { + test(`${method} ${endpoint} returns 410 status code with "info" message`, async () => { + const response = await request(fastifyTestInstance.server)[ + method.toLowerCase() as 'get' | 'post' + ](endpoint); + + expect(response.body).toStrictEqual({ + message: { + type: 'info', + message: 'Please reload the app, this feature is no longer available.' + } + }); + expect(response.status).toBe(410); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.ts new file mode 100644 index 0000000000000000000000000000000000000000..ba40a9ae8df597cb0cca3ff0f1b39bace6819c05 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-endpoints.ts @@ -0,0 +1,50 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import * as schemas from '../../schemas.js'; + +type Endpoints = [string, 'GET' | 'POST'][]; + +export const endpoints: Endpoints = [ + ['/refetch-user-completed-challenges', 'POST'], + ['/certificate/verify-can-claim-cert', 'GET'], + ['/api/github', 'GET'], + ['/account', 'GET'] +]; + +/** + * Plugin for the deprecated endpoints. Instantiates a Fastify route for each + * endpoint, returning a 410 status code and a message indicating that the user + * should reload the app. + * + * These endpoints remain active until we can confirm that no requests are being + * made to them. + * + * @param fastify The Fastify instance. + * @param _options Fastify options I guess? + * @param done Callback to signal that the logic has completed. + */ +export const deprecatedEndpoints: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + endpoints.forEach(([endpoint, method]) => { + fastify.route({ + method, + url: endpoint, + schema: schemas.deprecatedEndpoints, + handler: async (_req, reply) => { + void reply.status(410); + return { + message: { + type: 'info', + message: + 'Please reload the app, this feature is no longer available.' + } + } as const; + } + }); + }); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e5e0464b6d62f095e2c6db0228c465c01b61bae1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.test.ts @@ -0,0 +1,26 @@ +import { describe, test, expect } from 'vitest'; +import { setupServer, superRequest } from '../../../vitest.utils.js'; + +import { unsubscribeEndpoints } from './deprecated-unsubscribe.js'; + +const urlEncodedMessage = + '?messages=info%5B0%5D%3DWe%2520are%2520no%2520longer%2520able%2520to%2520process%2520this%2520unsubscription%2520request.%2520Please%2520go%2520to%2520your%2520settings%2520to%2520update%2520your%2520email%2520preferences'; + +describe('Deprecated unsubscribeEndpoints', () => { + setupServer(); + + unsubscribeEndpoints.forEach(([endpoint, method]) => { + test(`${method} ${endpoint} redirects to origin with "info" message`, async () => { + const response = await superRequest(endpoint, { method }).set( + 'Referer', + 'https://www.freecodecamp.org/settings' + ); + + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + expect(response.headers.location).toStrictEqual( + 'https://www.freecodecamp.org' + urlEncodedMessage + ); + expect(response.status).toBe(302); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.ts new file mode 100644 index 0000000000000000000000000000000000000000..92cd9315ee3c572cfb7127656781f5e6990997aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/deprecated-unsubscribe.ts @@ -0,0 +1,43 @@ +import { FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import { getRedirectParams } from '../../utils/redirection.js'; + +type Endpoint = [string, 'GET' | 'POST']; + +export const unsubscribeEndpoints: Endpoint[] = [ + ['/u/:email', 'GET'], + ['/unsubscribe/:email', 'GET'] +]; + +/** + * Plugin for the deprecated unsubscribe endpoints. Each route returns a 302 + * redirect to the referer with a message explaining how to unsubscribe. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const unsubscribeDeprecated: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + unsubscribeEndpoints.forEach(([endpoint, method]) => { + fastify.route({ + method, + url: endpoint, + handler: async (req, reply) => { + const { origin } = getRedirectParams(req); + void reply.redirectWithMessage(origin, { + type: 'info', + content: + 'We are no longer able to process this unsubscription request. ' + + 'Please go to your settings to update your email preferences' + }); + } + }); + }); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..51914b274ebe03443c7adef91f27dc8919643772 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.test.ts @@ -0,0 +1,351 @@ +import { describe, test, expect, beforeAll, vi } from 'vitest'; +import Stripe from 'stripe'; +import { setupServer, superRequest } from '../../../vitest.utils.js'; + +const testEWalletEmail = 'baz@bar.com'; +const testSubscriptionId = 'sub_test_id'; +const testCustomerId = 'cust_test_id'; + +const sharedDonationReqBody = { + amount: 500, + duration: 'month' +}; +const chargeStripeReqBody = { + email: testEWalletEmail, + subscriptionId: 'sub_test_id', + ...sharedDonationReqBody +}; +const createStripePaymentIntentReqBody = { + email: testEWalletEmail, + name: 'Baz Bar', + token: { id: 'tok_123' }, + ...sharedDonationReqBody +}; +const mockSubCreate = vi.fn(); +const mockAttachPaymentMethod = vi.fn(() => + Promise.resolve({ + id: 'pm_1MqLiJLkdIwHu7ixUEgbFdYF', + object: 'payment_method' + }) +); +const mockCustomerCreate = vi.fn(() => + Promise.resolve({ + id: testCustomerId, + name: 'Jest_User', + currency: 'sgd', + description: 'Jest User Account created' + }) +); +const mockSubRetrieveObj = { + id: testSubscriptionId, + items: { + data: [ + { + plan: { + product: 'prod_GD1GGbJsqQaupl' + } + } + ] + }, + // 1 Jan 2040 + current_period_start: Math.floor(Date.now() / 1000), + customer: testCustomerId, + status: 'active' +}; +const mockSubRetrieve = vi.fn(() => Promise.resolve(mockSubRetrieveObj)); +const mockCheckoutSessionCreate = vi.fn(() => + Promise.resolve({ id: 'checkout_session_id' }) +); +const mockCustomerUpdate = vi.fn(); +const generateMockSubCreate = (status: string) => () => + Promise.resolve({ + id: testSubscriptionId, + latest_invoice: { + payment_intent: { + client_secret: 'superSecret', + status + } + } + }); +const { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError +} = vi.hoisted(() => { + class StripeError extends Error {} + class StripeCardError extends StripeError {} + class StripeInvalidRequestError extends StripeError {} + class StripeAuthenticationError extends StripeError {} + return { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError + }; +}); + +vi.mock('stripe', () => ({ + default: class { + static errors = { + StripeError, + StripeCardError, + StripeInvalidRequestError, + StripeAuthenticationError + }; + constructor() {} + customers = { + create: mockCustomerCreate, + update: mockCustomerUpdate + }; + paymentMethods = { + attach: mockAttachPaymentMethod + }; + subscriptions = { + create: mockSubCreate, + retrieve: mockSubRetrieve + }; + checkout = { + sessions: { + create: mockCheckoutSessionCreate + } + }; + } +})); +describe('Donate', () => { + let setCookies: string[]; + setupServer(); + + describe('Unauthenticated User', () => { + // Get the CSRF cookies from an unprotected route + beforeAll(async () => { + const res = await superRequest('/status/ping', { method: 'GET' }); + setCookies = res.get('Set-Cookie'); + }); + + const endpoints: { path: string; method: 'POST' | 'PUT' }[] = [ + { path: '/donate/add-donation', method: 'POST' }, + { path: '/donate/charge-stripe-card', method: 'POST' }, + { path: '/donate/update-stripe-card', method: 'PUT' } + ]; + + endpoints.forEach(({ path, method }) => { + test(`${method} ${path} returns 401 status code with error message`, async () => { + const response = await superRequest(path, { + method, + setCookies + }); + expect(response.statusCode).toBe(401); + }); + }); + + test('POST /donate/create-stripe-payment-intent should return 200', async () => { + mockSubCreate.mockImplementationOnce(generateMockSubCreate('no-errors')); + const response = await superRequest( + '/donate/create-stripe-payment-intent', + { + method: 'POST', + setCookies + } + ).send(createStripePaymentIntentReqBody); + expect(response.status).toBe(200); + }); + + test('POST /donate/charge-stripe should return 200', async () => { + mockSubCreate.mockImplementationOnce(generateMockSubCreate('no-errors')); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + expect(response.status).toBe(200); + }); + + describe('Sentry Issue reporting', () => { + test('create-stripe-payment-intent captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + mockCustomerCreate.mockImplementationOnce(() => + Promise.reject(new Error('Stripe unavailable')) + ); + const response = await superRequest( + '/donate/create-stripe-payment-intent', + { + method: 'POST', + setCookies + } + ).send(createStripePaymentIntentReqBody); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('create-stripe-payment-intent rejects invalid amount for duration', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest( + '/donate/create-stripe-payment-intent', + { + method: 'POST', + setCookies + } + ).send({ ...createStripePaymentIntentReqBody, amount: 999 }); + + expect(response.status).toBe(400); + expect(count).toHaveBeenCalledWith('donation.intent_rejected', 1, { + attributes: { reason: 'invalid_amount' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('charge-stripe captures each subscription-validation failure', async () => { + const invalidSubscriptions: unknown[] = [ + { ...mockSubRetrieveObj, status: 'incomplete' }, + { + ...mockSubRetrieveObj, + items: { data: [{ plan: { product: 'not_a_real_product' } }] } + }, + { ...mockSubRetrieveObj, current_period_start: 0 }, + { ...mockSubRetrieveObj, customer: 12345 } + ]; + + for (const sub of invalidSubscriptions) { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + mockSubRetrieve.mockImplementationOnce(() => + Promise.resolve(sub as typeof mockSubRetrieveObj) + ); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledExactlyOnceWith( + expect.any(Error), + { + extra: { subscriptionId: 'sub_test_id' } + } + ); + const capturedError = captureException.mock + .calls[0]?.[0] as unknown as Error; + expect(capturedError.message).not.toContain('sub_test_id'); + + fastifyTestInstance.Sentry = originalSentry; + } + }); + + test('charge-stripe captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + mockSubRetrieve.mockImplementationOnce(() => + Promise.reject(new Error('Stripe unavailable')) + ); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('charge-stripe does not capture Stripe card decline errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const CardError = Stripe.errors.StripeCardError as unknown as new ( + m?: string + ) => Error; + mockSubRetrieve.mockImplementationOnce(() => + Promise.reject(new CardError('card_declined')) + ); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + + expect(response.status).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('charge-stripe does not capture Stripe invalid request errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const InvalidRequestError = Stripe.errors + .StripeInvalidRequestError as unknown as new (m?: string) => Error; + mockSubRetrieve.mockImplementationOnce(() => + Promise.reject(new InvalidRequestError('invalid_request')) + ); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + + expect(response.status).toBe(500); + expect(captureException).not.toHaveBeenCalled(); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test('charge-stripe captures Stripe infra errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException + }; + + const AuthError = Stripe.errors + .StripeAuthenticationError as unknown as new (m?: string) => Error; + mockSubRetrieve.mockImplementationOnce(() => + Promise.reject(new AuthError('invalid api key')) + ); + const response = await superRequest('/donate/charge-stripe', { + method: 'POST', + setCookies + }).send(chargeStripeReqBody); + + expect(response.status).toBe(500); + expect(captureException).toHaveBeenCalledOnce(); + + fastifyTestInstance.Sentry = originalSentry; + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.ts new file mode 100644 index 0000000000000000000000000000000000000000..36359753eac189bb7bd527ba6c957049902d3926 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/donate.ts @@ -0,0 +1,267 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import Stripe from 'stripe'; + +import { STRIPE_SECRET_KEY } from '../../utils/env.js'; +import { + donationSubscriptionConfig, + allStripeProductIdsArray +} from '@freecodecamp/shared/config/donation-settings'; +import * as schemas from '../../schemas.js'; +import { inLastFiveMinutes } from '../../utils/validate-donation.js'; +import { findOrCreateUser } from '../helpers/auth-helpers.js'; +import { clientNetInfo } from '../../utils/logger.js'; + +/** + * Plugin for public donation endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const chargeStripeRoute: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + // Stripe plugin + const stripe = new Stripe(STRIPE_SECRET_KEY, { + apiVersion: '2024-06-20', + typescript: true + }); + + fastify.post( + '/donate/create-stripe-payment-intent', + { + schema: schemas.createStripePaymentIntent + }, + async (req, reply) => { + const { email, name, amount, duration } = req.body; + fastify.Sentry?.setUser({ email }); + req.log.debug({ amount, duration }, 'Creating Stripe payment intent'); + + if (!donationSubscriptionConfig.plans[duration].includes(amount)) { + fastify.Sentry?.metrics?.count('donation.intent_rejected', 1, { + attributes: { reason: 'invalid_amount' } + }); + void reply.code(400); + return { + error: 'The donation form had invalid values for this submission.' + } as const; + } + + try { + const stripeCustomer = await stripe.customers.create({ + email, + name + }); + + const stripeSubscription = await stripe.subscriptions.create({ + customer: stripeCustomer.id, + items: [ + { + plan: `${donationSubscriptionConfig.duration[duration]}-donation-${amount}` + } + ], + payment_behavior: 'default_incomplete', + payment_settings: { save_default_payment_method: 'on_subscription' }, + expand: ['latest_invoice.payment_intent'] + }); + + if ( + stripeSubscription.latest_invoice && + typeof stripeSubscription.latest_invoice !== 'string' && + stripeSubscription.latest_invoice.payment_intent && + typeof stripeSubscription.latest_invoice.payment_intent !== + 'string' && + stripeSubscription.latest_invoice.payment_intent.client_secret !== + null + ) { + const clientSecret = + stripeSubscription.latest_invoice.payment_intent.client_secret; + req.log.debug('Successfully created payment intent'); + return reply.send({ + subscriptionId: stripeSubscription.id, + clientSecret + }); + } else { + throw new Error('Stripe payment intent client secret is missing'); + } + } catch (err) { + const ctx = { + audit: true, + err, + email: req.body.email, + amount, + duration, + ...clientNetInfo(req) + }; + if ( + err instanceof Stripe.errors.StripeCardError || + err instanceof Stripe.errors.StripeInvalidRequestError + ) { + req.log.warn(ctx, 'Stripe upstream error creating payment intent'); + } else { + fastify.Sentry?.captureException(err); + req.log.error(ctx, 'Failed to create payment intent'); + } + void reply.code(500); + return reply.send({ + error: 'Donation failed due to a server error.' + }); + } + } + ); + + fastify.post( + '/donate/charge-stripe', + { + schema: schemas.chargeStripe + }, + async (req, reply) => { + try { + const { email, amount, duration, subscriptionId } = req.body; + fastify.Sentry?.setUser({ email }); + req.log.debug( + { amount, duration, subscriptionId }, + 'Processing Stripe charge' + ); + + const subscription = + await stripe.subscriptions.retrieve(subscriptionId); + const isSubscriptionActive = subscription.status === 'active'; + // eslint-disable-next-line @typescript-eslint/no-base-to-string + const productId = subscription.items.data[0]?.plan.product?.toString(); + const isStartedRecently = inLastFiveMinutes( + subscription.current_period_start + ); + const isProductIdValid = + productId && allStripeProductIdsArray.includes(productId); + const isValidCustomer = typeof subscription.customer === 'string'; + + if (!isSubscriptionActive) { + req.log.warn( + { status: subscription.status }, + 'Invalid subscription status' + ); + fastify.Sentry?.captureException( + new Error('Stripe subscription information is invalid'), + { extra: { subscriptionId } } + ); + void reply.code(500); + return { + error: 'Donation failed due to a server error.' + } as const; + } + if (!isProductIdValid) { + req.log.warn({ productId }, 'Invalid product ID'); + fastify.Sentry?.captureException(new Error('Product ID is invalid'), { + extra: { subscriptionId } + }); + void reply.code(500); + return { + error: 'Donation failed due to a server error.' + } as const; + } + if (!isStartedRecently) { + req.log.warn( + { startTime: subscription.current_period_start }, + 'Subscription not recent' + ); + fastify.Sentry?.captureException( + new Error('Subscription is not recent'), + { extra: { subscriptionId } } + ); + void reply.code(500); + return { + error: 'Donation failed due to a server error.' + } as const; + } + if (!isValidCustomer) { + req.log.warn( + { customerId: subscription.customer }, + 'Invalid customer ID' + ); + fastify.Sentry?.captureException( + new Error('Customer ID is invalid'), + { extra: { subscriptionId } } + ); + void reply.code(500); + return { + error: 'Donation failed due to a server error.' + } as const; + } + + const user = await findOrCreateUser(fastify, email); + req.log.debug({ userId: user.id }, 'Found or created user'); + + const donation = { + userId: user.id, + email, + amount, + duration, + provider: 'stripe', + subscriptionId, + customerId: subscription.customer as string, + // TODO(Post-MVP) migrate to startDate: new Date() + startDate: { + date: new Date().toISOString(), + when: new Date().toISOString().replace(/.$/, '+00:00') + } + }; + + await fastify.prisma.donation.create({ + data: donation + }); + + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + isDonating: true + } + }); + req.log.info( + { + audit: true, + userId: user.id, + email, + amount, + duration, + subscriptionId, + ...clientNetInfo(req) + }, + 'Successfully processed donation' + ); + fastify.Sentry?.metrics?.count('donation.created', 1, { + attributes: { flow: 'charge-stripe' } + }); + + return reply.send({ + isDonating: true + }); + } catch (err) { + const ctx = { + audit: true, + err, + email: req.body.email, + subscriptionId: req.body.subscriptionId, + ...clientNetInfo(req) + }; + if ( + err instanceof Stripe.errors.StripeCardError || + err instanceof Stripe.errors.StripeInvalidRequestError + ) { + req.log.warn(ctx, 'Stripe upstream error processing charge'); + } else { + fastify.Sentry?.captureException(err); + req.log.error(ctx, 'Failed to process Stripe charge'); + } + void reply.code(500); + return { + error: 'Donation failed due to a server error.' + } as const; + } + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc096062c3c554b12c6937ca833afa19c4448211 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.test.ts @@ -0,0 +1,421 @@ +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +import type { Prisma } from '@prisma/client'; +import { describe, test, expect, vi } from 'vitest'; +import { setupServer, superRequest } from '../../../vitest.utils.js'; +import { HOME_LOCATION } from '../../utils/env.js'; +import { createUserInput } from '../../utils/create-user.js'; + +const urlEncodedInfoMessage1 = + '?messages=info%5B0%5D%3DWe%2520could%2520not%2520find%2520an%2520account%2520to%2520unsubscribe.'; +const urlEncodedInfoMessage2 = + '?messages=info%5B0%5D%3DWe%2520were%2520unable%2520to%2520process%2520this%2520request%252C%2520please%2520check%2520and%2520try%2520again.'; +const urlEncodedInfoMessage3 = + '?messages=info%5B0%5D%3DWe%2520could%2520not%2520find%2520an%2520account%2520to%2520resubscribe.'; +const urlEncodedSuccessMessage1 = + '?messages=success%5B0%5D%3DWe%2527ve%2520successfully%2520updated%2520your%2520email%2520preferences.'; +const urlEncodedSuccessMessage2 = + '?messages=success%5B0%5D%3DWe%2527ve%2520successfully%2520updated%2520your%2520email%2520preferences.%2520Thank%2520you%2520for%2520resubscribing.'; + +const unsubscribeId1 = 'abcde'; +const unsubscribeId2 = 'abcdef'; +const unsubscribeId3 = 'abcdefg'; + +const testUserData1: Prisma.userCreateInput[] = [ + { + ...createUserInput('user1@freecodecamp.org'), + unsubscribeId: unsubscribeId1, + sendQuincyEmail: true + }, + { + ...createUserInput('user1@freecodecamp.org'), + unsubscribeId: unsubscribeId2, + sendQuincyEmail: true + }, + { + ...createUserInput('user2@freecodecamp.org'), + unsubscribeId: unsubscribeId2, + sendQuincyEmail: true + }, + { + ...createUserInput('user3@freecodecamp.org'), + unsubscribeId: unsubscribeId3, + sendQuincyEmail: true + } +]; + +const testUserData2: Prisma.userCreateInput[] = [ + { + ...createUserInput('user1@freecodecamp.org'), + unsubscribeId: unsubscribeId1, + sendQuincyEmail: false + }, + { + ...createUserInput('user2@freecodecamp.org'), + unsubscribeId: unsubscribeId2, + sendQuincyEmail: false + }, + { + ...createUserInput('user3@freecodecamp.org'), + unsubscribeId: unsubscribeId2, + sendQuincyEmail: false + } +]; + +describe('Email Subscription endpoints', () => { + setupServer(); + + describe('GET /ue/:unsubscribeId', () => { + test('should 302 redirect with info message if no ID', async () => { + const response = await superRequest('/ue/', { method: 'GET' }); + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedInfoMessage1}` + ); + expect(response.status).toBe(302); + }); + + test('should 302 redirect with info message if bad ID', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/ue/54321edcba', { method: 'GET' }); + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedInfoMessage1}` + ); + expect(response.status).toBe(302); + expect(count).toHaveBeenCalledWith('email_subscription.unsubscribed', 1, { + attributes: { result: 'not_found' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test("1: should set 'sendQuincyEmail' to 'false' for users with matching email and 302 redirect with success message", async () => { + await fastifyTestInstance.prisma.user.createMany({ + data: testUserData1 + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest(`/ue/${unsubscribeId1}`, { + method: 'GET' + }); + + const users = await fastifyTestInstance.prisma.user.findMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 }, + { unsubscribeId: unsubscribeId3 } + ] + } + }); + + expect(users).toHaveLength(4); + const unsubscribedUsers = users.filter( + user => user.email === 'user1@freecodecamp.org' + ); + const remainingUsers = users.filter( + user => user.email !== 'user1@freecodecamp.org' + ); + + expect(unsubscribedUsers).toHaveLength(2); + expect( + unsubscribedUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([false, false]); + + expect(remainingUsers).toHaveLength(2); + expect( + remainingUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([true, true]); + + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}/unsubscribed/${unsubscribeId1}${urlEncodedSuccessMessage1}` + ); + + expect(response.status).toBe(302); + expect(count).toHaveBeenCalledWith('email_subscription.unsubscribed', 1, { + attributes: { result: 'success' } + }); + fastifyTestInstance.Sentry = originalSentry; + // TODO: If any assertions fail before this call, other tests will fail for no actual reason. + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 }, + { unsubscribeId: unsubscribeId3 } + ] + } + }); + }); + + test("2: should set 'sendQuincyEmail' to 'false' for all users with matching email and 302 redirect with success message", async () => { + await fastifyTestInstance.prisma.user.createMany({ + data: testUserData1 + }); + + const response = await superRequest(`/ue/${unsubscribeId2}`, { + method: 'GET' + }); + + const users = await fastifyTestInstance.prisma.user.findMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 }, + { unsubscribeId: unsubscribeId3 } + ] + } + }); + + expect(users).toHaveLength(4); + const unsubscribedUsers = users.filter(user => + ['user1@freecodecamp.org', 'user2@freecodecamp.org'].includes( + user.email! + ) + ); + const remainingUsers = users.filter( + user => + !['user1@freecodecamp.org', 'user2@freecodecamp.org'].includes( + user.email! + ) + ); + + expect(unsubscribedUsers).toHaveLength(3); + expect( + unsubscribedUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([false, false, false]); + + expect(remainingUsers).toHaveLength(1); + expect( + remainingUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([true]); + + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}/unsubscribed/${unsubscribeId2}${urlEncodedSuccessMessage1}` + ); + + expect(response.status).toBe(302); + // TODO: If any assertions fail before this call, other tests will fail for no actual reason. + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 }, + { unsubscribeId: unsubscribeId3 } + ] + } + }); + }); + }); + + describe('GET /resubscribe/:unsubscribeId', () => { + test('should 302 redirect with info message if no ID', async () => { + const response = await superRequest('/resubscribe/', { method: 'GET' }); + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedInfoMessage2}` + ); + expect(response.status).toBe(302); + }); + + test('should 302 redirect with info message if bad ID', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest('/resubscribe/54321edcba', { + method: 'GET' + }); + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedInfoMessage3}` + ); + expect(response.status).toBe(302); + expect(count).toHaveBeenCalledWith('email_subscription.resubscribed', 1, { + attributes: { result: 'not_found' } + }); + + fastifyTestInstance.Sentry = originalSentry; + }); + + test("should set 'sendQuincyEmail' to 'true' for user with matching ID and 302 redirect with success message", async () => { + await fastifyTestInstance.prisma.user.createMany({ + data: testUserData2 + }); + + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + const response = await superRequest(`/resubscribe/${unsubscribeId1}`, { + method: 'GET' + }); + + const users = await fastifyTestInstance.prisma.user.findMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 } + ] + } + }); + + expect(users).toHaveLength(3); + const resubscribedUsers = users.filter( + user => user.unsubscribeId === unsubscribeId1 + ); + const remainingUsers = users.filter( + user => user.unsubscribeId !== unsubscribeId1 + ); + + expect(resubscribedUsers).toHaveLength(1); + expect( + resubscribedUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([true]); + + expect(remainingUsers).toHaveLength(2); + expect( + remainingUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([false, false]); + + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedSuccessMessage2}` + ); + + expect(response.status).toBe(302); + expect(count).toHaveBeenCalledWith('email_subscription.resubscribed', 1, { + attributes: { result: 'success' } + }); + fastifyTestInstance.Sentry = originalSentry; + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 } + ] + } + }); + }); + + test("should set 'sendQuincyEmail' to 'true' for first user with matching ID and 302 redirect with success message", async () => { + await fastifyTestInstance.prisma.user.createMany({ + data: testUserData2 + }); + + const response = await superRequest(`/resubscribe/${unsubscribeId2}`, { + method: 'GET' + }); + + const users = await fastifyTestInstance.prisma.user.findMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 } + ] + } + }); + + expect(users).toHaveLength(3); + const resubscribedUsers = users.filter( + user => user.email === 'user2@freecodecamp.org' + ); + const remainingUsers = users.filter( + user => user.email !== 'user2@freecodecamp.org' + ); + + expect(resubscribedUsers).toHaveLength(1); + expect( + resubscribedUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([true]); + + expect(remainingUsers).toHaveLength(2); + expect( + remainingUsers.map(({ sendQuincyEmail }) => sendQuincyEmail) + ).toStrictEqual([false, false]); + + expect(response.headers.location).toStrictEqual( + `${HOME_LOCATION}${urlEncodedSuccessMessage2}` + ); + + expect(response.status).toBe(302); + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + OR: [ + { unsubscribeId: unsubscribeId1 }, + { unsubscribeId: unsubscribeId2 } + ] + } + }); + }); + }); + + describe('Sentry Issue reporting', () => { + test('unsubscribe captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.user, 'findMany') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superRequest(`/ue/${unsubscribeId1}`, { + method: 'GET' + }); + + expect(response.status).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('email_subscription.unsubscribed', 1, { + attributes: { result: 'error' } + }); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + + test('resubscribe captures unexpected errors', async () => { + const originalSentry = fastifyTestInstance.Sentry; + const captureException = vi.fn(); + const count = vi.fn(); + fastifyTestInstance.Sentry = { + ...originalSentry, + captureException, + metrics: { ...originalSentry.metrics, count } + }; + const spy = vi + .spyOn(fastifyTestInstance.prisma.user, 'findFirst') + .mockRejectedValueOnce(new Error('DB error')); + + const response = await superRequest(`/resubscribe/${unsubscribeId1}`, { + method: 'GET' + }); + + expect(response.status).toBe(302); + expect(captureException).toHaveBeenCalledOnce(); + expect(count).toHaveBeenCalledWith('email_subscription.resubscribed', 1, { + attributes: { result: 'error' } + }); + + spy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.ts new file mode 100644 index 0000000000000000000000000000000000000000..900c6eef67d94522c8fb14fb433dfa63f4230a9d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/email-subscription.ts @@ -0,0 +1,170 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import * as schemas from '../../schemas.js'; +import { getRedirectParams } from '../../utils/redirection.js'; + +/** + * Endpoints to set 'sendQuincyEmail' to true or false using 'unsubscribeId'. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const emailSubscribtionRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get( + '/ue/:unsubscribeId', + { + schema: schemas.unsubscribe, + errorHandler(error, request, reply) { + if (error.validation) { + const { origin } = getRedirectParams(request); + void reply.code(302); + void reply.redirectWithMessage(origin, { + type: 'info', + content: 'We could not find an account to unsubscribe.' + }); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + const { origin } = getRedirectParams(req); + const { unsubscribeId } = req.params; + + try { + const unsubUsers = await fastify.prisma.user.findMany({ + where: { unsubscribeId } + }); + + if (!unsubUsers.length) { + req.log.warn('No users found for unsubscribe request'); + fastify.Sentry?.metrics?.count('email_subscription.unsubscribed', 1, { + attributes: { result: 'not_found' } + }); + void reply.code(302); + return reply.redirectWithMessage(origin, { + type: 'info', + content: 'We could not find an account to unsubscribe.' + }); + } + + const userUpdatePromises = unsubUsers.map(user => + fastify.prisma.user.updateMany({ + where: { email: user.email }, + data: { + sendQuincyEmail: false + } + }) + ); + + await Promise.all(userUpdatePromises); + req.log.info( + { matchedUsers: unsubUsers.length, audit: true }, + 'Successfully unsubscribed users from email' + ); + fastify.Sentry?.metrics?.count('email_subscription.unsubscribed', 1, { + attributes: { result: 'success' } + }); + + return reply.redirectWithMessage( + `${origin}/unsubscribed/${unsubscribeId}`, + { + type: 'success', + content: "We've successfully updated your email preferences." + } + ); + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Failed to unsubscribe user from email'); + fastify.Sentry?.metrics?.count('email_subscription.unsubscribed', 1, { + attributes: { result: 'error' } + }); + void reply.code(302); + return reply.redirectWithMessage(origin, { + type: 'danger', + content: `Failed to unsubscribe user, please contact support at support@freecodecamp.org` + }); + } + } + ); + + fastify.get( + '/resubscribe/:unsubscribeId', + { + schema: schemas.resubscribe, + errorHandler(error, request, reply) { + if (error.validation) { + const { origin } = getRedirectParams(request); + void reply.code(302); + void reply.redirectWithMessage(origin, { + type: 'info', + content: + 'We were unable to process this request, please check and try again.' + }); + } else { + fastify.errorHandler(error, request, reply); + } + } + }, + async (req, reply) => { + const { origin } = getRedirectParams(req); + const { unsubscribeId } = req.params; + + try { + const user = await fastify.prisma.user.findFirst({ + where: { unsubscribeId } + }); + + if (!user) { + req.log.warn('No user found for resubscribe request'); + fastify.Sentry?.metrics?.count('email_subscription.resubscribed', 1, { + attributes: { result: 'not_found' } + }); + void reply.code(302); + return reply.redirectWithMessage(origin, { + type: 'info', + content: 'We could not find an account to resubscribe.' + }); + } + + req.log.debug({ userId: user.id }, 'Found user to resubscribe'); + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + sendQuincyEmail: true + } + }); + req.log.info( + { userId: user.id, audit: true }, + 'Successfully resubscribed user' + ); + fastify.Sentry?.metrics?.count('email_subscription.resubscribed', 1, { + attributes: { result: 'success' } + }); + + return reply.redirectWithMessage(origin, { + type: 'success', + content: + "We've successfully updated your email preferences. Thank you for resubscribing." + }); + } catch (err) { + fastify.Sentry?.captureException(err); + req.log.error(err, 'Failed to resubscribe user to email'); + fastify.Sentry?.metrics?.count('email_subscription.resubscribed', 1, { + attributes: { result: 'error' } + }); + void reply.code(302); + return reply.redirectWithMessage(origin, { + type: 'danger', + content: 'Something went wrong.' + }); + } + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..39bdea8d91448324aa5f15d66ea6e0b85a4a0c22 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/index.ts @@ -0,0 +1,11 @@ +export * from './auth-dev.js'; +export * from './auth.js'; +export * from './certificate.js'; +export * from './deprecated-endpoints.js'; +export * from './deprecated-unsubscribe.js'; +export * from './donate.js'; +export * from './email-subscription.js'; +export * from './signout.js'; +export * from './status.js'; +export * from './user.js'; +export * from './sentry.js'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/sentry.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/sentry.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4cfca6bd4a313d7cf5c3ebd310deb074c4ab0cc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/sentry.ts @@ -0,0 +1,37 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { type FastifyInstance, type FastifyReply } from 'fastify'; + +import { UpdateReqType } from '../../utils/index.js'; +import * as schemas from '../../schemas.js'; + +/** + * Plugin for Sentry-related endpoints. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const sentryRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.post( + '/sentry/event', + { + schema: schemas.sentryPostEvent + }, + postSentryEventHandler + ); + + done(); +}; + +function postSentryEventHandler( + this: FastifyInstance, + req: UpdateReqType, + _reply: FastifyReply +) { + throw new Error(`Sentry Test: ${req.body.text}`); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..278729ce2f00209065e26be609001e9cf2c84bd8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.test.ts @@ -0,0 +1,51 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { devLogin, setupServer, superRequest } from '../../../vitest.utils.js'; + +describe('GET /signout', () => { + setupServer(); + + beforeEach(async () => { + await devLogin(); + }); + it('should clear all the cookies', async () => { + const res = await superRequest('/signout', { method: 'GET' }); + + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access + const setCookie = res.headers['set-cookie']; + expect(setCookie).toEqual( + expect.arrayContaining([ + expect.stringMatching( + /^jwt_access_token=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^csrf_token=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ), + expect.stringMatching( + /^_csrf=; Max-Age=0; Path=\/; Expires=Thu, 01 Jan 1970 00:00:00 GMT/ + ) + ]) + ); + expect(setCookie).toHaveLength(3); + }); + + it('should respond with an empty object', async () => { + const res = await superRequest('/signout', { method: 'GET' }); + expect(res.body).toEqual({}); + expect(res.status).toBe(200); + }); + + it('counts an auth.signed_out metric', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + + await superRequest('/signout', { method: 'GET' }); + + expect(count).toHaveBeenCalledWith('auth.signed_out', 1); + + fastifyTestInstance.Sentry = originalSentry; + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.ts new file mode 100644 index 0000000000000000000000000000000000000000..29c310389048ef6b75cddcc4f5d6e5239f1773b8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/signout.ts @@ -0,0 +1,32 @@ +import type { FastifyPluginCallback } from 'fastify'; + +import { signout } from '../../schemas.js'; + +/** + * Route handler for signing out. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param done Callback to signal that the logic has completed. + */ +export const signoutRoute: FastifyPluginCallback = ( + fastify, + _options, + done +) => { + fastify.get( + '/signout', + { + schema: signout + }, + async (req, reply) => { + void reply.clearOurCookies(); + fastify.Sentry?.metrics?.count('auth.signed_out', 1); + req.log.info({ audit: true }, 'User signed out'); + + await reply.send({}); + } + ); + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a8b1d6d407b4098c8093dca469a3f38ca901b94 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.test.ts @@ -0,0 +1,64 @@ +import { describe, test, expect, vi } from 'vitest'; +import { setupServer, superRequest } from '../../../vitest.utils.js'; +import { DEPLOYMENT_VERSION } from '../../utils/env.js'; + +describe('/status', () => { + setupServer(); + + test('GET returns 200 status code with pong', async () => { + const response = await superRequest('/status/ping', { + method: 'GET' + }); + + expect(response.body).toStrictEqual({ msg: 'pong' }); + expect(response.status).toBe(200); + }); + + test('GET returns 200 status code with version', async () => { + const response = await superRequest('/status/version', { + method: 'GET' + }); + + expect(response.body).toStrictEqual({ version: DEPLOYMENT_VERSION }); + expect(response.status).toBe(200); + }); + + test('GET /status/ready returns 200 when the database is reachable', async () => { + const response = await superRequest('/status/ready', { method: 'GET' }); + + expect(response.body).toStrictEqual({ status: 'ready' }); + expect(response.status).toBe(200); + }); + + test('GET /status/ready returns 503 when the database is unreachable', async () => { + const spy = vi + .spyOn(fastifyTestInstance.prisma, '$runCommandRaw') + .mockRejectedValueOnce(new Error('db down')); + + const response = await superRequest('/status/ready', { method: 'GET' }); + + expect(response.body).toStrictEqual({ status: 'unavailable' }); + expect(response.status).toBe(503); + + spy.mockRestore(); + }); + + test('counts a readiness.check_failed metric when the database is unreachable', async () => { + const count = vi.fn(); + const originalSentry = fastifyTestInstance.Sentry; + fastifyTestInstance.Sentry = { + ...originalSentry, + metrics: { ...originalSentry.metrics, count } + }; + const dbSpy = vi + .spyOn(fastifyTestInstance.prisma, '$runCommandRaw') + .mockRejectedValueOnce(new Error('db down')); + + await superRequest('/status/ready', { method: 'GET' }); + + expect(count).toHaveBeenCalledWith('readiness.check_failed', 1); + + dbSpy.mockRestore(); + fastifyTestInstance.Sentry = originalSentry; + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.ts new file mode 100644 index 0000000000000000000000000000000000000000..1a472bb4d4da4b633ba721e65800d1c3b0974284 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/status.ts @@ -0,0 +1,40 @@ +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; + +import { DEPLOYMENT_VERSION } from '../../utils/env.js'; + +/** + * Plugin for the health check endpoint. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, + * options)`. + * @param done The callback to signal that the plugin is ready. + */ +export const statusRoute: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get('/status/ping', async (req, _res) => { + req.log.debug({ what: 'pong' }, 'Replying to ping'); + return { msg: 'pong' }; + }); + + fastify.get('/status/version', async (req, _res) => { + req.log.debug('Sending version'); + return { version: DEPLOYMENT_VERSION }; + }); + + fastify.get('/status/ready', async (req, reply) => { + try { + await fastify.prisma.$runCommandRaw({ ping: 1 }); + return { status: 'ready' }; + } catch (err) { + fastify.Sentry?.metrics?.count('readiness.check_failed', 1); + req.log.error(err, 'Readiness check failed: database unreachable'); + return reply.code(503).send({ status: 'unavailable' }); + } + }); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ff4a1b0af744b62a3cb02384b24a2fc498ba21b3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.test.ts @@ -0,0 +1,649 @@ +import type { Prisma } from '@prisma/client'; +import { ObjectId } from 'bson'; +import { omit } from 'lodash-es'; +import { + describe, + it, + test, + expect, + beforeAll, + beforeEach, + afterAll, + vi +} from 'vitest'; + +import { createUserInput } from '../../utils/create-user.js'; +import { + defaultUserEmail, + setupServer, + createSuperRequest +} from '../../../vitest.utils.js'; +import { replacePrivateData } from './user.js'; + +const mockedFetch = vi.fn(); +vi.spyOn(globalThis, 'fetch').mockImplementation(mockedFetch); + +// This is used to build a test user. +const testUserData: Prisma.userCreateInput = { + ...createUserInput(defaultUserEmail), + sendQuincyEmail: true, + username: 'foobar', + usernameDisplay: 'Foo Bar', + progressTimestamps: [1520002973119, 1520440323273], + completedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + solution: null, + challengeType: 5, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2' + } + ] + }, + { + id: 'a5229172f011153519423690', + completedDate: 1520440323273, + solution: null, + challengeType: 5, + files: [] + }, + { + id: 'a5229172f011153519423692', + completedDate: 1520440323274, + githubLink: '', + challengeType: 5, + examResults: { + numberOfCorrectAnswers: 0, + numberOfQuestionsInExam: 0, + percentCorrect: 0, + passingPercent: 0, + passed: false, + examTimeInSeconds: 0 + } + } + ], + experience: [ + { + id: 'exp1', + title: 'Software Engineer', + company: 'Company A', + startDate: '2020-01-01', + endDate: '2021-01-01', + description: 'Worked on various projects.' + } + ], + partiallyCompletedChallenges: [{ id: '123', completedDate: 123 }], + completedExams: [], + githubProfile: 'github.com/foobar', + website: 'https://www.freecodecamp.org', + donationEmails: ['an@add.ress'], + portfolio: [ + { + description: 'A portfolio', + id: 'a6b0bb188d873cb2c8729495', + image: 'https://www.freecodecamp.org/cat.png', + title: 'A portfolio', + url: 'https://www.freecodecamp.org' + } + ], + savedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + lastSavedDate: 123, + files: [ + { + contents: 'test-contents', + ext: 'js', + history: ['indexjs'], + key: 'indexjs', + name: 'test-name' + } + ] + } + ], + yearsTopContributor: ['2018'], + twitter: '@foobar', + bluesky: '@foobar', + linkedin: 'linkedin.com/foobar' +}; + +const minimalUserData: Prisma.userCreateInput = { + about: 'I am a test user', + acceptedPrivacyTerms: true, + email: testUserData.email, + emailVerified: true, + externalId: '1234567890', + isDonating: false, + picture: 'https://www.freecodecamp.org/cat.png', + sendQuincyEmail: true, + username: 'testuser', + unsubscribeId: '1234567890' +}; + +const lockedProfileUI = { + isLocked: true, + showAbout: false, + showCerts: false, + showDonation: false, + showExperience: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false +}; + +const publicUserData = { + about: testUserData.about, + calendar: { 1520002973: 1, 1520440323: 1 }, + // testUserData.completedChallenges, with nulls removed + completedChallenges: [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + challengeType: 5, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2' + } + ] + }, + { + id: 'a5229172f011153519423690', + completedDate: 1520440323273, + challengeType: 5, + files: [] + }, + { + id: 'a5229172f011153519423692', + completedDate: 1520440323274, + githubLink: '', + challengeType: 5, + files: [], + examResults: { + numberOfCorrectAnswers: 0, + numberOfQuestionsInExam: 0, + percentCorrect: 0, + passingPercent: 0, + passed: false, + examTimeInSeconds: 0 + } + } + ], + completedExams: testUserData.completedExams, + completedSurveys: [], // TODO: add surveys + experience: testUserData.experience, + githubProfile: testUserData.githubProfile, + is2018DataVisCert: testUserData.is2018DataVisCert, + is2018FullStackCert: testUserData.is2018FullStackCert, // TODO: should this be returned? The client doesn't use it at the moment. + isA2EnglishCert: testUserData.isA2EnglishCert, + isB1EnglishCert: testUserData.isB1EnglishCert, + isApisMicroservicesCert: testUserData.isApisMicroservicesCert, + isBackEndCert: testUserData.isBackEndCert, + isBackEndDevApisCertV9: testUserData.isBackEndDevApisCertV9, + isCheater: testUserData.isCheater, + isCollegeAlgebraPyCertV8: testUserData.isCollegeAlgebraPyCertV8, + isDataAnalysisPyCertV7: testUserData.isDataAnalysisPyCertV7, + isDataVisCert: testUserData.isDataVisCert, + isDonating: testUserData.isDonating, + isFoundationalCSharpCertV8: testUserData.isFoundationalCSharpCertV8, + isFrontEndCert: testUserData.isFrontEndCert, + isFrontEndLibsCert: testUserData.isFrontEndLibsCert, + isFrontEndLibsCertV9: testUserData.isFrontEndLibsCertV9, + isFullStackCert: testUserData.isFullStackCert, + isJavascriptCertV9: testUserData.isJavascriptCertV9, + isHonest: testUserData.isHonest, + isInfosecCertV7: testUserData.isInfosecCertV7, + isInfosecQaCert: testUserData.isInfosecQaCert, + isJsAlgoDataStructCert: testUserData.isJsAlgoDataStructCert, + isJsAlgoDataStructCertV8: testUserData.isJsAlgoDataStructCertV8, + isMachineLearningPyCertV7: testUserData.isMachineLearningPyCertV7, + isPythonCertV9: testUserData.isPythonCertV9, + isQaCertV7: testUserData.isQaCertV7, + isRelationalDatabaseCertV8: testUserData.isRelationalDatabaseCertV8, + isRelationalDatabaseCertV9: testUserData.isRelationalDatabaseCertV9, + isRespWebDesignCert: testUserData.isRespWebDesignCert, + isRespWebDesignCertV9: testUserData.isRespWebDesignCertV9, + isSciCompPyCertV7: testUserData.isSciCompPyCertV7, + linkedin: testUserData.linkedin, + location: testUserData.location, + name: testUserData.name, + picture: testUserData.picture, + points: 2, + portfolio: testUserData.portfolio, + profileUI: testUserData.profileUI, + twitter: 'https://x.com/foobar', + bluesky: 'https://bsky.app/profile/foobar', + username: testUserData.username, + usernameDisplay: testUserData.usernameDisplay, + website: testUserData.website, + yearsTopContributor: testUserData.yearsTopContributor +}; + +describe('userRoutes', () => { + setupServer(); + + describe('Public', () => { + let superGet: ReturnType; + + beforeEach(() => { + superGet = createSuperRequest({ method: 'GET' }); + }); + + describe('/users/get-public-profile', () => { + const profilelessUsername = 'profileless-user'; + const lockedUsername = 'locked-user'; + const publicUsername = 'public-user'; + const lockedUserProfileUI = { + isLocked: true, + showAbout: true, + showCerts: true, + showDonation: true, + showExperience: true, + showHeatMap: true, + showLocation: true, + showName: true, + showPoints: true, + showPortfolio: true, + showTimeLine: true + }; + const unlockedUserProfileUI = { + isLocked: false, + showAbout: true, + showCerts: true, + showDonation: true, + showExperience: true, + showHeatMap: true, + showLocation: true, + showName: true, + showPoints: true, + showPortfolio: true, + showTimeLine: true + }; + const users = [profilelessUsername, lockedUsername, publicUsername]; + beforeAll(async () => { + await fastifyTestInstance.prisma.user.create({ + data: { + ...minimalUserData, + email: profilelessUsername, + username: profilelessUsername + } + }); + await fastifyTestInstance.prisma.user.create({ + data: { + ...minimalUserData, + email: lockedUsername, + username: lockedUsername, + profileUI: lockedUserProfileUI + } + }); + await fastifyTestInstance.prisma.user.create({ + data: { + ...testUserData, + email: publicUsername, + username: publicUsername, + profileUI: unlockedUserProfileUI + } + }); + }); + + afterAll(async () => { + await fastifyTestInstance.prisma.user.deleteMany({ + where: { + OR: users.map(username => ({ username })) + } + }); + }); + + describe('GET', () => { + test('returns 400 status code if the user agent is blocked', async () => { + const response = await superGet( + '/users/get-public-profile?username=public-user' + ).set('User-Agent', 'curl'); + + expect(response.text).toBe( + 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' + ); + expect(response.statusCode).toBe(400); + }); + + test('returns 400 status code if the username param is missing', async () => { + const res = await superGet('/users/get-public-profile'); + // TODO(Post-MVP): return something more informative + expect(res.body).toStrictEqual({}); + expect(res.statusCode).toBe(400); + }); + + test('returns 400 status code if the username param is empty', async () => { + const res = await superGet('/users/get-public-profile?username='); + // TODO(Post-MVP): return something more informative + expect(res.body).toStrictEqual({}); + expect(res.statusCode).toBe(400); + }); + + test('returns 404 status code for non-existent user', async () => { + const response = await superGet( + '/users/get-public-profile?username=non-existent' + ); + // TODO(Post-MVP): return something more informative + expect(response.body).toStrictEqual({}); + expect(response.statusCode).toBe(404); + }); + + test('returns 200 status code with a locked profile if the profile is private', async () => { + const response = await superGet( + `/users/get-public-profile?username=${lockedUsername}` + ); + + expect(response.body).toStrictEqual({ + entities: { + user: { + [lockedUsername]: { + isLocked: true, + profileUI: lockedUserProfileUI, + username: lockedUsername + } + } + }, + result: lockedUsername + }); + expect(response.statusCode).toBe(200); + }); + + test('returns 200 status code locked profile if the profile is missing', async () => { + const response = await superGet( + `/users/get-public-profile?username=${profilelessUsername}` + ); + + expect(response.body).toStrictEqual({ + entities: { + user: { + [profilelessUsername]: { + isLocked: true, + profileUI: lockedProfileUI, + username: profilelessUsername + } + } + }, + result: profilelessUsername + }); + expect(response.statusCode).toBe(200); + }); + // TODO: create a list of public properties like the api-server and use that + // to restrict the output of this and session-user. + test('returns 200 status code with public user object', async () => { + const testUser = + await fastifyTestInstance.prisma.user.findFirstOrThrow({ + where: { email: publicUsername } + }); + const response = await superGet( + `/users/get-public-profile?username=${publicUsername}` + ); + + // TODO: create a fixture for this without 'completedSurveys', ideally + // it should contain the entire body. + const publicUser = { + // TODO(Post-MVP, maybe): return completedSurveys? + ...omit(publicUserData, 'completedSurveys'), + username: publicUsername, + joinDate: new ObjectId(testUser.id).getTimestamp().toISOString(), + profileUI: unlockedUserProfileUI + }; + + expect(response.body).toStrictEqual({ + entities: { + user: { + [publicUsername]: publicUser + } + }, + result: publicUsername + }); + expect(response.statusCode).toBe(200); + }); + }); + }); + describe('GET /users/exists', () => { + beforeAll(async () => { + await fastifyTestInstance.prisma.user.create({ + data: minimalUserData + }); + }); + + it('should reject with a 400 status code if the username param is missing or empty', async () => { + const res = await superGet('/users/exists'); + + expect(res.body).toStrictEqual({ + type: 'danger', + message: 'username parameter is required' + }); + expect(res.statusCode).toBe(400); + + const res2 = await superGet('/users/exists?username='); + + expect(res2.body).toStrictEqual({ + type: 'danger', + message: 'username parameter is required' + }); + expect(res2.statusCode).toBe(400); + }); + + it('should return { exists: true } if the username exists', async () => { + const res = await superGet('/users/exists?username=testuser'); + + expect(res.body).toStrictEqual({ exists: true }); + expect(res.statusCode).toBe(200); + }); + + it('should ignore case when checking for username existence', async () => { + const res = await superGet('/users/exists?username=TeStUsEr'); + + expect(res.body).toStrictEqual({ exists: true }); + expect(res.statusCode).toBe(200); + }); + + it('should return { exists: false } if the username does not exist', async () => { + const res = await superGet('/users/exists?username=nonexistent'); + + expect(res.body).toStrictEqual({ exists: false }); + expect(res.statusCode).toBe(200); + }); + + it('should return { exists: true } if the username is restricted (ignoring case)', async () => { + const res = await superGet('/users/exists?username=pRofIle'); + + expect(res.body).toStrictEqual({ exists: true }); + + const res2 = await superGet('/users/exists?username=flAnge'); + + expect(res2.body).toStrictEqual({ exists: true }); + }); + }); + }); +}); + +describe('get-public-profile helpers', () => { + describe('replacePrivateData', () => { + const user = { + about: 'about', + calendar: { 1: 1, 2: 1 } as const, + completedChallenges: [ + { id: '123', completedDate: 123, files: [] }, + { id: '456', completedDate: 456, challengeType: 7, files: [] } + ], + id: '5f5b1b3b1c9d440000d9e3b4', + isDonating: false, + location: 'location', + joinDate: 'joinDate', + name: 'name', + points: 2, + portfolio: [ + { + id: '789', + title: 'portfolio', + url: 'url', + image: 'image', + description: 'description' + } + ], + experience: [ + { + id: 'exp1', + title: 'Developer', + company: 'Company', + location: 'Location', + startDate: '01/2020', + endDate: '12/2022', + description: 'Description' + } + ], + profileUI: { + isLocked: false, + showAbout: true, + showCerts: true, + showDonation: true, + showHeatMap: true, + showLocation: true, + showName: true, + showPoints: true, + showPortfolio: true, + showTimeLine: true, + showExperience: true + } + }; + + test(`returns "" for 'about' if showAbout is not true`, () => { + const userWithoutAbout = { + ...user, + profileUI: { ...user.profileUI, showAbout: false } + }; + expect(replacePrivateData(userWithoutAbout)).toMatchObject({ + about: '' + }); + }); + + test('returns {} for calendar if showHeatMap is not true', () => { + const userWithoutHeatMap = { + ...user, + profileUI: { ...user.profileUI, showHeatMap: false } + }; + expect(replacePrivateData(userWithoutHeatMap).calendar).toEqual({}); + }); + + test(`returns [] for completeChallenges if showTimeLine is not true`, () => { + const userWithoutTimeLine = { + ...user, + profileUI: { ...user.profileUI, showTimeLine: false } + }; + expect(replacePrivateData(userWithoutTimeLine)).toMatchObject({ + completedChallenges: [] + }); + }); + + test('omits certifications from completedChallenges if showCerts is not true', () => { + const userWithoutCerts = { + ...user, + profileUI: { ...user.profileUI, showCerts: false } + }; + expect(replacePrivateData(userWithoutCerts)).toMatchObject({ + completedChallenges: [{ id: '123', completedDate: 123, files: [] }] + }); + }); + + test('returns null for isDonating if showDonation is not true', () => { + const userWithoutDonation = { + ...user, + profileUI: { ...user.profileUI, showDonation: false } + }; + expect(replacePrivateData(userWithoutDonation)).toMatchObject({ + isDonating: null + }); + }); + + test('returns "" for joinDate if showAbout is not true', () => { + const userWithoutAbout = { + ...user, + profileUI: { ...user.profileUI, showAbout: false } + }; + expect(replacePrivateData(userWithoutAbout)).toMatchObject({ + joinDate: '' + }); + }); + + test(`returns "" for 'location' if showLocation is not true`, () => { + const userWithoutLocation = { + ...user, + profileUI: { ...user.profileUI, showLocation: false } + }; + expect(replacePrivateData(userWithoutLocation)).toMatchObject({ + location: '' + }); + }); + + test(`returns "" for 'name' if showName is not true`, () => { + const userWithoutName = { + ...user, + profileUI: { ...user.profileUI, showName: false } + }; + expect(replacePrivateData(userWithoutName)).toMatchObject({ + name: '' + }); + }); + + test('returns null for points if showPoints is not true', () => { + const userWithoutPoints = { + ...user, + profileUI: { ...user.profileUI, showPoints: false } + }; + expect(replacePrivateData(userWithoutPoints)).toMatchObject({ + points: null + }); + }); + + test('returns [] for portfolio if showPortfolio is not true', () => { + const userWithoutPortfolio = { + ...user, + profileUI: { ...user.profileUI, showPortfolio: false } + }; + expect(replacePrivateData(userWithoutPortfolio)).toMatchObject({ + portfolio: [] + }); + }); + + test('returns [] for experience if showExperience is not true', () => { + const userWithoutExperience = { + ...user, + profileUI: { ...user.profileUI, showExperience: false } + }; + expect(replacePrivateData(userWithoutExperience)).toMatchObject({ + experience: [] + }); + }); + + test('returns the expected public user object if all showX flags are true', () => { + expect(replacePrivateData(user)).toEqual(omit(user, ['id', 'profileUI'])); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.ts new file mode 100644 index 0000000000000000000000000000000000000000..d09626c6baa03d570108ae483565c889b1978996 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/routes/public/user.ts @@ -0,0 +1,265 @@ +import { Experience, Portfolio } from '@prisma/client'; +import { type FastifyPluginCallbackTypebox } from '@fastify/type-provider-typebox'; +import { ObjectId } from 'bson'; +import { omit } from 'lodash-es'; + +import { isRestricted } from '../helpers/is-restricted.js'; +import * as schemas from '../../schemas.js'; +import { splitUser } from '../helpers/user-utils.js'; +import { + normalizeChallenges, + type NormalizedChallenge, + normalizeFlags, + normalizeProfileUI, + normalizeTwitter, + normalizeBluesky, + removeNulls, + type NoNullProperties +} from '../../utils/normalize.js'; +import { + Calendar, + getCalendar, + getPoints, + ProgressTimestamp +} from '../../utils/progress.js'; +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; + +type ProfileUI = Partial<{ + isLocked: boolean; + showAbout: boolean; + showCerts: boolean; + showDonation: boolean; + showHeatMap: boolean; + showLocation: boolean; + showName: boolean; + showPoints: boolean; + showPortfolio: boolean; + showExperience: boolean; + showTimeLine: boolean; +}>; + +type RawUser = { + about: string; + completedChallenges: NormalizedChallenge[]; + calendar: Calendar; + id: string; + isDonating: boolean; + joinDate: string; + location: string; + name: string; + points: number; + portfolio: Portfolio[]; + experience: NoNullProperties[]; + profileUI: ProfileUI; +}; + +/** + * Creates an object with the properties that are shared with the public. + * @param user The raw user object. + * @returns The shared user object. + */ +export const replacePrivateData = (user: RawUser) => { + const { + showAbout, + showHeatMap, + showCerts, + showDonation, + showLocation, + showName, + showPoints, + showPortfolio, + showExperience, + showTimeLine + } = user.profileUI; + + return { + about: showAbout ? user.about : '', + calendar: showHeatMap ? user.calendar : {}, + completedChallenges: showTimeLine + ? showCerts + ? user.completedChallenges + : user.completedChallenges.filter( + c => c.challengeType !== challengeTypes.step + ) + : [], + isDonating: showDonation ? user.isDonating : null, + joinDate: showAbout ? user.joinDate : '', + location: showLocation ? user.location : '', + name: showName ? user.name : '', + points: showPoints ? user.points : null, + portfolio: showPortfolio ? user.portfolio : [], + experience: showExperience ? user.experience : [] + }; +}; + +const blockedUserAgentParts = ['python', 'google-apps-script', 'curl']; +/** + * Plugin containing public GET routes for user account management. They are kept + * separate because they do not require CSRF protection or authorization. + * + * @param fastify The Fastify instance. + * @param _options Options passed to the plugin via `fastify.register(plugin, options)`. + * @param done Callback to signal that the logic has completed. + */ +export const userPublicGetRoutes: FastifyPluginCallbackTypebox = ( + fastify, + _options, + done +) => { + fastify.get( + '/users/get-public-profile', + { + schema: schemas.getPublicProfile, + onRequest: (req, reply, done) => { + const userAgent = req.headers['user-agent']; + + if ( + userAgent && + blockedUserAgentParts.some(ua => userAgent.toLowerCase().includes(ua)) + ) { + void reply.code(400); + void reply.send( + 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' + ); + } + done(); + } + }, + async (req, reply) => { + req.log.debug( + { username: req.query.username }, + 'Fetching public profile' + ); + // TODO(Post-MVP): look for duplicates unless we can make username unique in the db. + const user = await fastify.prisma.user.findFirst({ + where: { username: req.query.username } + // TODO: only select desired fields, then stop 'omit'ing the undesired + // ones. + }); + + if (!user) { + req.log.warn('User not found'); + void reply.code(404); + return reply.send({}); + } + + const [flags, rest] = splitUser(user); + + const publicUser = omit(rest, [ + 'currentChallengeId', + 'email', + 'emailVerified', + 'sendQuincyEmail', + 'theme', + // keyboardShortcuts is included in flags. + // 'keyboardShortcuts', + 'acceptedPrivacyTerms', + 'progressTimestamps', + 'unsubscribeId', + 'donationEmails', + 'externalId', + 'isBanned' + ]); + + const normalizedProfileUI = normalizeProfileUI(user.profileUI); + + void reply.code(200); + if (normalizedProfileUI.isLocked) { + // TODO(Post-MVP): just return isLocked: true and either a null user + // or no user at all. (see other TODO in the else branch below) + return reply.send({ + entities: { + user: { + [user.username]: { + isLocked: true, + profileUI: normalizedProfileUI, + username: user.username, + usernameDisplay: user.usernameDisplay || user.username + } + } + }, + result: user.username + }); + } else { + const progressTimestamps = user.progressTimestamps as + | ProgressTimestamp[] + | null; + const sharedUser = replacePrivateData({ + ...user, + calendar: getCalendar(progressTimestamps), + completedChallenges: normalizeChallenges(user.completedChallenges), + location: user.location ?? '', + joinDate: new ObjectId(user.id).getTimestamp().toISOString(), + name: user.name ?? '', + points: getPoints(progressTimestamps), + profileUI: normalizedProfileUI, + experience: user.experience.map(removeNulls) ?? [] + }); + + const returnedUser = { + ...removeNulls(publicUser), + ...normalizeFlags(flags), + ...sharedUser, + picture: user.picture ?? '', + profileUI: normalizedProfileUI, + // TODO: should this always be returned? Shouldn't some privacy + // setting control it? Same applies to website, githubProfile, + // and linkedin. + twitter: normalizeTwitter(user.twitter), + bluesky: normalizeBluesky(user.bluesky), + yearsTopContributor: user.yearsTopContributor, + usernameDisplay: user.usernameDisplay || user.username + }; + return reply.send({ + // TODO(Post-MVP): just return a user object (i.e. returnedUser) and + // isLocked: false. The there should be no need for Type.Union in the + // schema. Alternatively, have the user object be nullable and don't + // bother with isLocked. + entities: { + user: { [user.username]: returnedUser } + }, + result: user.username + }); + } + } + ); + + fastify.get( + '/users/exists', + { + schema: schemas.userExists, + attachValidation: true + }, + async (req, reply) => { + if (req.validationError) { + void reply.code(400); + req.log.warn('Validation error: No username provided'); + return await reply.send({ + type: 'danger', + message: 'username parameter is required' + }); + } + + const username = req.query.username.toLowerCase(); + + if (isRestricted(username)) { + req.log.debug({ username }, 'Restricted username'); + return await reply.send({ exists: true }); + } + + const exists = + (await fastify.prisma.user.count({ + where: { username } + })) > 0; + + if (exists) { + req.log.debug({ username }, 'User exists for username'); + } else { + req.log.debug({ username }, 'User does not exist for username'); + } + await reply.send({ exists }); + } + ); + + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schema.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schema.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..eef31d327fca3015e773e2fa8ca0c7b47d6c1d55 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schema.test.ts @@ -0,0 +1,58 @@ +import { describe, test, expect } from 'vitest'; +import secureSchema from 'ajv/lib/refs/json-schema-secure.json' with { type: 'json' }; +import { Ajv } from 'ajv'; + +import * as schemas from './schemas.js'; + +// it's not strict, but that's okay - we're not using it to validate data +const ajv = new Ajv({ strictTypes: false }); +const isSchemaSecure = ajv.compile(secureSchema); + +// These schemas will fail the tests, so can only be checked by hand. +const ignoredSchemas = ['getSessionUser', 'getPublicProfile']; + +describe('Schemas do not use obviously dangerous validation', () => { + Object.entries(schemas) + .filter(([schema]) => !ignoredSchemas.includes(schema)) + .forEach(([name, schema]) => { + describe(`schema ${name}`, () => { + if ('body' in schema) { + test('body is secure', () => { + expect(isSchemaSecure(schema.body)).toBeTruthy(); + }); + } + + if ('querystring' in schema) { + test('querystring is secure', () => { + expect(isSchemaSecure(schema.querystring)).toBeTruthy(); + }); + } + + test('should use querystring instead of query', () => { + // if query is used then req.query is unknown, but if querystring is + // used then req.query has the expected type + expect('query' in schema).toBeFalsy(); + }); + + if ('params' in schema) { + test('params is secure', () => { + expect(isSchemaSecure(schema.params)).toBeTruthy(); + }); + } + + if ('headers' in schema) { + test('headers is secure', () => { + expect(isSchemaSecure(schema.headers)).toBeTruthy(); + }); + } + + if ('response' in schema) { + Object.entries(schema.response).forEach(([code, codeSchema]) => { + test(`response ${code} is secure`, () => { + expect(isSchemaSecure(codeSchema)).toBeTruthy(); + }); + }); + } + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab66c3f3f045e25f9ae90e580019b656f7cf2f69 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas.ts @@ -0,0 +1,60 @@ +export { getPublicProfile } from './schemas/users/get-public-profile.js'; +export { userExists } from './schemas/users/exists.js'; +export { certSlug } from './schemas/certificate/cert-slug.js'; +export { certificateVerify } from './schemas/certificate/certificate-verify.js'; +export { backendChallengeCompleted } from './schemas/challenge/backend-challenge-completed.js'; +export { coderoadChallengeCompleted } from './schemas/challenge/coderoad-challenge-completed.js'; +export { exam } from './schemas/challenge/exam.js'; +export { examChallengeCompleted } from './schemas/challenge/exam-challenge-completed.js'; +export { dailyCodingChallengeCompleted } from './schemas/challenge/daily-coding-challenge-completed.js'; +export { modernChallengeCompleted } from './schemas/challenge/modern-challenge-completed.js'; +export { msTrophyChallengeCompleted } from './schemas/challenge/ms-trophy-challenge-completed.js'; +export { projectCompleted } from './schemas/challenge/project-completed.js'; +export { saveChallenge } from './schemas/challenge/save-challenge.js'; +export { submitQuizAttempt } from './schemas/challenge/submit-quiz-attempt.js'; +export { deprecatedEndpoints } from './schemas/deprecated/index.js'; +export { addDonation } from './schemas/donate/add-donation.js'; +export { chargeStripeCard } from './schemas/donate/charge-stripe-card.js'; +export { chargeStripe } from './schemas/donate/charge-stripe.js'; +export { createStripePaymentIntent } from './schemas/donate/create-stripe-payment-intent.js'; +export { updateStripeCard } from './schemas/donate/update-stripe-card.js'; +export { resubscribe } from './schemas/email-subscription/resubscribe.js'; +export { unsubscribe } from './schemas/email-subscription/unsubscribe.js'; +export { updateMyAbout } from './schemas/settings/update-my-about.js'; +export { confirmEmail } from './schemas/settings/confirm-email.js'; +export { updateMyClassroomMode } from './schemas/settings/update-my-classroom-mode.js'; +export { updateMyEmail } from './schemas/settings/update-my-email.js'; +export { updateMyExperience } from './schemas/settings/update-my-experience.js'; +export { updateMyHonesty } from './schemas/settings/update-my-honesty.js'; +export { updateMyKeyboardShortcuts } from './schemas/settings/update-my-keyboard-shortcuts.js'; +export { updateMyPortfolio } from './schemas/settings/update-my-portfolio.js'; +export { updateMyPrivacyTerms } from './schemas/settings/update-my-privacy-terms.js'; +export { updateMyProfileUI } from './schemas/settings/update-my-profile-ui.js'; +export { updateMyQuincyEmail } from './schemas/settings/update-my-quincy-email.js'; +export { updateSocrates } from './schemas/settings/update-socrates.js'; +export { updateMySocials } from './schemas/settings/update-my-socials.js'; +export { updateMyTheme } from './schemas/settings/update-my-theme.js'; +export { updateMyUsername } from './schemas/settings/update-my-username.js'; +export { deleteMsUsername } from './schemas/user/delete-ms-username.js'; +export { + deleteMyAccount, + deleteUser +} from './schemas/user/delete-my-account.js'; +export { askSocrates } from './schemas/socrates/ask-socrates.js'; +export { deleteUserToken } from './schemas/user/delete-user-token.js'; +export { getSessionUser } from './schemas/user/get-session-user.js'; +export { postMsUsername } from './schemas/user/post-ms-username.js'; +export { reportUser } from './schemas/user/report-user.js'; +export { resetMyProgress } from './schemas/user/reset-my-progress.js'; +export { resetModule } from './schemas/user/reset-module.js'; +export { submitSurvey } from './schemas/user/submit-survey.js'; +export { + userExamEnvironmentToken, + getUserExamEnvironmentToken +} from './schemas/user/exam-environment-token.js'; +export { sentryPostEvent } from './schemas/sentry/event.js'; +export { signout } from './schemas/signout/signout.js'; +export { + classroomGetUserIdSchema, + classroomGetUserDataSchema +} from './schemas/classroom/classroom.js'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/cert-slug.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/cert-slug.ts new file mode 100644 index 0000000000000000000000000000000000000000..d942bcf8119309900ae037e51ce78c78417c5a10 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/cert-slug.ts @@ -0,0 +1,118 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { Certification } from '@freecodecamp/shared/config/certification-settings'; +import { genericError } from '../types.js'; + +export const certSlug = { + params: Type.Object({ + certSlug: Type.String(), + username: Type.String() + }), + response: { + // TODO(POST_MVP): Most of these should not be 200s + 200: Type.Union([ + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.username-not-found'), + variables: Type.Object({ + username: Type.String() + }) + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.not-eligible') + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.not-honest'), + variables: Type.Object({ + username: Type.String() + }) + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.profile-private'), + variables: Type.Object({ + username: Type.String() + }) + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.add-name') + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.certs-private'), + variables: Type.Object({ + username: Type.String() + }) + }) + ) + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.timeline-private'), + variables: Type.Object({ + username: Type.String() + }) + }) + ) + }), + Type.Object({ + certSlug: Type.Enum(Certification), + certTitle: Type.String(), + username: Type.String(), + name: Type.Optional(Type.String()), + date: Type.Number(), + completionTime: Type.Number() + }), + Type.Object({ + messages: Type.Array( + Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.user-not-certified'), + variables: Type.Object({ + username: Type.String(), + cert: Type.String() + }) + }) + ) + }) + ]), + 404: Type.Object({ + messages: Type.Array( + Type.Object({ + message: Type.Literal('flash.cert-not-found'), + type: Type.Literal('info'), + variables: Type.Object({ + certSlug: Type.String() + }) + }) + ) + }), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/certificate-verify.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/certificate-verify.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc1d686225d001461653d3183dbe816d7666dd26 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/certificate/certificate-verify.ts @@ -0,0 +1,133 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError, isCertMap } from '../types.js'; + +export const certificateVerify = { + // TODO(POST_MVP): Remove partial validation from route for schema validation + body: Type.Object({ + certSlug: Type.String({ maxLength: 1024 }) + }), + response: { + 200: Type.Object({ + response: Type.Union([ + Type.Object({ + type: Type.Literal('info'), + message: Type.Union([Type.Literal('flash.already-claimed')]), + variables: Type.Object({ + name: Type.String() + }) + }), + Type.Object({ + type: Type.Literal('success'), + message: Type.Literal('flash.cert-claim-success'), + variables: Type.Object({ + username: Type.String(), + name: Type.String() + }) + }) + ]), + isCertMap, + completedChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + solution: Type.Optional(Type.String()), + githubLink: Type.Optional(Type.String()), + challengeType: Type.Optional(Type.Number()), + // Technically, files is optional, but the db default was [] and + // the client treats null, undefined and [] equivalently. + // TODO(Post-MVP): make this optional. + files: Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + path: Type.Optional(Type.String()) + }) + ), + isManuallyApproved: Type.Optional(Type.Boolean()) + }) + ) + }), + 400: Type.Union([ + Type.Object({ + response: Type.Object({ + type: Type.Literal('info'), + message: Type.Union([Type.Literal('flash.incomplete-steps')]), + variables: Type.Object({ + name: Type.String() + }) + }), + isCertMap, + completedChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + solution: Type.Optional(Type.String()), + githubLink: Type.Optional(Type.String()), + challengeType: Type.Optional(Type.Number()), + // Technically, files is optional, but the db default was [] and + // the client treats null, undefined and [] equivalently. + // TODO(Post-MVP): make this optional. + files: Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + path: Type.Optional(Type.String()) + }) + ), + isManuallyApproved: Type.Optional(Type.Boolean()) + }) + ) + }), + Type.Object({ + response: Type.Object({ + type: Type.Literal('danger'), + message: Type.Union([Type.Literal('flash.wrong-name')]), + variables: Type.Object({ + name: Type.String() + }) + }) + }), + Type.Object({ + response: Type.Object({ + type: Type.Literal('info'), + message: Type.Union([Type.Literal('flash.name-needed')]) + }), + isCertMap, + completedChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + solution: Type.Optional(Type.String()), + githubLink: Type.Optional(Type.String()), + challengeType: Type.Optional(Type.Number()), + // Technically, files is optional, but the db default was [] and + // the client treats null, undefined and [] equivalently. + // TODO(Post-MVP): make this optional. + files: Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + path: Type.Optional(Type.String()) + }) + ), + isManuallyApproved: Type.Optional(Type.Boolean()) + }) + ) + }) + ]), + 500: Type.Union([ + Type.Object({ + type: Type.Literal('danger'), + message: Type.Literal('flash.went-wrong') + }), + genericError + ]), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/backend-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/backend-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..de3b422928061d8665109cb3e494896fe0f70389 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/backend-challenge-completed.ts @@ -0,0 +1,31 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const backendChallengeCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }) + }), + response: { + 200: Type.Object({ + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean() + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'That does not appear to be a valid challenge submission.' + ) + }), + 403: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'Exam submissions are not allowed on this endpoint.' + ) + }), + genericError + ]), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/coderoad-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/coderoad-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e29b2f5fcfa15740d21be274c7a0bd7040dbc7b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/coderoad-challenge-completed.ts @@ -0,0 +1,22 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const coderoadChallengeCompleted = { + body: Type.Object({ + tutorialId: Type.String() + }), + headers: Type.Object({ 'coderoad-user-token': Type.String() }), + response: { + 200: Type.Object({ + type: Type.Literal('success'), + msg: Type.String() + }), + 400: Type.Object({ + type: Type.Literal('error'), + msg: Type.String() + }), + default: Type.Object({ + type: Type.Literal('error'), + msg: Type.String() + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/daily-coding-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/daily-coding-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec896b432ca7f5eac2f6d509dae8aeefeefc5b20 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/daily-coding-challenge-completed.ts @@ -0,0 +1,45 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +// This has to be declared as a tuple, because Type.Union expects a +// tuple of types, not an array of unions of said types. +const languages: [Type.TLiteral<'javascript'>, Type.TLiteral<'python'>] = [ + Type.Literal('javascript'), + Type.Literal('python') +]; + +export const dailyCodingChallengeCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + language: Type.Union(languages) + }), + response: { + 200: Type.Object({ + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean(), + completedDailyCodingChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + languages: Type.Array(Type.Union(languages)) + }) + ) + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'That does not appear to be a valid challenge submission.' + ) + }), + 403: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'Exam submissions are not allowed on this endpoint.' + ) + }), + genericError + ]) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3f0df500b976fed342878b69974d2e37dc54d79 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam-challenge-completed.ts @@ -0,0 +1,43 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { examResults, genericError } from '../types.js'; + +export const examChallengeCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + challengeType: Type.Number(), + userCompletedExam: Type.Object({ + examTimeInSeconds: Type.Number(), + userExamQuestions: Type.Array( + Type.Object({ + id: Type.String(), + question: Type.String(), + answer: Type.Object({ + id: Type.String(), + answer: Type.String() + }) + }), + { minItems: 1 } + ) + }) + }), + response: { + 200: Type.Object({ + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean(), + examResults + }), + 400: Type.Object({ + error: Type.String() + }), + 403: Type.Union([ + Type.Object({ + error: Type.String() + }), + genericError + ]), + 500: Type.Object({ + error: Type.String() + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam.ts new file mode 100644 index 0000000000000000000000000000000000000000..d47bec19944beca1b4ae15bd610200eb7ca877fd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/exam.ts @@ -0,0 +1,41 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const exam = { + params: Type.Object({ + id: Type.String({ + format: 'objectid', + maxLength: 24, + minLength: 24 + }) + }), + response: { + 200: Type.Object({ + generatedExam: Type.Array( + Type.Object({ + id: Type.String(), + question: Type.String(), + answers: Type.Array( + Type.Object({ + id: Type.String(), + answer: Type.String() + }) + ) + }) + ) + }), + // TODO: Standardize error responses - e.g. { type, message } + 400: Type.Object({ + error: Type.String() + }), + 403: Type.Union([ + Type.Object({ + error: Type.String() + }), + genericError + ]), + 500: Type.Object({ + error: Type.String() + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/modern-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/modern-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc8651f8e4d3d3ceb2ca913570c280efa5a0bf72 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/modern-challenge-completed.ts @@ -0,0 +1,44 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError, savedChallenge } from '../types.js'; + +export const modernChallengeCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + challengeType: Type.Number(), + files: Type.Optional( + Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + history: Type.Array(Type.String()) + }) + ) + ) + }), + response: { + 200: Type.Object({ + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean(), + savedChallenges: Type.Array(savedChallenge) + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'That does not appear to be a valid challenge submission.' + ) + }), + 403: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'Exam submissions are not allowed on this endpoint.' + ) + }), + genericError + ]), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/ms-trophy-challenge-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/ms-trophy-challenge-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..38c509994cda70bb61de151029c45e90ae16badc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/ms-trophy-challenge-completed.ts @@ -0,0 +1,52 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const msTrophyChallengeCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }) + }), + response: { + 200: Type.Object({ + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean() + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-2') + }), + 403: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-1') + }), + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-3') + }), + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-4'), + variables: Type.Object({ + msUsername: Type.String() + }) + }), + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-6') + }), + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.profile.err'), + variables: Type.Object({ + msUsername: Type.String() + }) + }), + genericError + ]), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.trophy.err-5') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/project-completed.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/project-completed.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5cecff0b37b95f467b18c5bfda28373a267b80c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/project-completed.ts @@ -0,0 +1,48 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const projectCompleted = { + body: Type.Object({ + id: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + challengeType: Type.Optional(Type.Number()), + // The solution must be a valid URL only if it is a `backEndProject`. + solution: Type.String({ maxLength: 1024 }), + githubLink: Type.Optional(Type.String()) + }), + response: { + 200: Type.Object({ + // TODO(Post-MVP): delete completedDate and alreadyCompleted? As far as + // I can tell, they are not used anywhere + completedDate: Type.Number(), + points: Type.Number(), + alreadyCompleted: Type.Boolean() + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Union([ + Type.Literal( + 'That does not appear to be a valid challenge submission.' + ), + Type.Literal( + 'You have not provided the valid links for us to inspect your work.' + ) + ]) + }), + 403: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Union([ + Type.Literal( + 'You have to complete the project before you can submit a URL.' + ), + Type.Literal( + 'That does not appear to be a valid challenge submission.' + ), + Type.Literal('Exam submissions are not allowed on this endpoint.') + ]) + }), + genericError + ]), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/save-challenge.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/save-challenge.ts new file mode 100644 index 0000000000000000000000000000000000000000..64a31c9e60c210c95a57bdca79d6a7c7d698ae47 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/save-challenge.ts @@ -0,0 +1,31 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { file, genericError, savedChallenge } from '../types.js'; + +export const saveChallenge = { + body: Type.Object({ + id: Type.String({ + format: 'objectid', + maxLength: 24, + minLength: 24 + }), + files: Type.Array(file) + }), + response: { + 200: Type.Object({ + savedChallenges: Type.Array(savedChallenge) + }), + 400: Type.Union([ + Type.Object({ + message: Type.Literal( + 'That does not appear to be a valid challenge submission.' + ), + type: Type.Literal('error') + }), + Type.Object({ + message: Type.Literal('That challenge type is not saveable.'), + type: Type.Literal('error') + }) + ]), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/submit-quiz-attempt.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/submit-quiz-attempt.ts new file mode 100644 index 0000000000000000000000000000000000000000..6790b51f946f70548df16ef3bedace4a40a2724c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/challenge/submit-quiz-attempt.ts @@ -0,0 +1,23 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const submitQuizAttempt = { + body: Type.Object({ + challengeId: Type.String({ + format: 'objectid', + maxLength: 24, + minLength: 24 + }), + quizId: Type.String() + }), + response: { + 200: Type.Object({}), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal( + 'That does not appear to be a valid quiz attempt submission.' + ) + }), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/classroom/classroom.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/classroom/classroom.ts new file mode 100644 index 0000000000000000000000000000000000000000..3484531f28c98feb3aeaa1880df6599fd1352a3d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/classroom/classroom.ts @@ -0,0 +1,37 @@ +import { Type } from '@fastify/type-provider-typebox'; +export const classroomGetUserIdSchema = { + body: Type.Object({ + email: Type.String({ format: 'email', maxLength: 1024 }) + }), + response: { + 200: Type.Object({ userId: Type.String() }), + 400: Type.Object({ error: Type.String() }), + 401: Type.Object({ error: Type.String() }), + 500: Type.Object({ error: Type.String() }) + } +}; +export const classroomGetUserDataSchema = { + body: Type.Object({ + userIds: Type.Array( + Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }), + { maxItems: 50 } + ) + }), + response: { + 200: Type.Object({ + data: Type.Record( + Type.String({ maxLength: 24 }), + Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number() + }) + ), + { propertyNames: { maxLength: 24 } } + ) + }), + 400: Type.Object({ error: Type.String() }), + 401: Type.Object({ error: Type.String() }), + 500: Type.Object({ error: Type.String() }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/deprecated/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/deprecated/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..e278f05b2634283b0e184529a84dbf66a17c4485 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/deprecated/index.ts @@ -0,0 +1,14 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const deprecatedEndpoints = { + response: { + 410: Type.Object({ + message: Type.Object({ + type: Type.Literal('info'), + message: Type.Literal( + 'Please reload the app, this feature is no longer available.' + ) + }) + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/add-donation.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/add-donation.ts new file mode 100644 index 0000000000000000000000000000000000000000..e574d7f5afeed8bec286bcb56b8b03d408168c88 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/add-donation.ts @@ -0,0 +1,20 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const addDonation = { + body: Type.Object({}), + response: { + 200: Type.Object({ + isDonating: Type.Boolean() + }), + 403: genericError, + 409: Type.Object({ + message: Type.Literal('User is already donating.'), + type: Type.Literal('info') + }), + 500: Type.Object({ + message: Type.Literal('Something went wrong.'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe-card.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe-card.ts new file mode 100644 index 0000000000000000000000000000000000000000..206ff590daeb683331cde46c3b32bca0803614b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe-card.ts @@ -0,0 +1,45 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const chargeStripeCard = { + body: Type.Object({ + paymentMethodId: Type.String(), + amount: Type.Number(), + duration: Type.Literal('month') + }), + response: { + 200: Type.Object({ + isDonating: Type.Boolean(), + type: Type.Literal('success') + }), + 400: Type.Object({ + error: Type.Object({ + message: Type.String(), + type: Type.Union([ + Type.Literal('MethodRestrictionError'), + Type.Literal('EmailRequiredError') + ]) + }) + }), + 402: Type.Object({ + error: Type.Object({ + message: Type.String(), + type: Type.Union([ + Type.Literal('UserActionRequired'), + Type.Literal('PaymentMethodRequired') + ]), + client_secret: Type.Optional(Type.String()) + }) + }), + 403: genericError, + 409: Type.Object({ + error: Type.Object({ + message: Type.String(), + type: Type.Literal('AlreadyDonatingError') + }) + }), + 500: Type.Object({ + error: Type.Literal('Donation failed due to a server error.') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1ebe96a789a9c12b52284c78873889d8d1ac106 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/charge-stripe.ts @@ -0,0 +1,18 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const chargeStripe = { + body: Type.Object({ + amount: Type.Number(), + duration: Type.Literal('month'), + email: Type.String({ format: 'email', maxLength: 1024 }), + subscriptionId: Type.String() + }), + response: { + 200: Type.Object({ + isDonating: Type.Boolean() + }), + default: Type.Object({ + error: Type.Literal('Donation failed due to a server error.') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/create-stripe-payment-intent.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/create-stripe-payment-intent.ts new file mode 100644 index 0000000000000000000000000000000000000000..f28827443e529d8fa750a454b1ec7a68c0120613 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/create-stripe-payment-intent.ts @@ -0,0 +1,24 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const createStripePaymentIntent = { + body: Type.Object({ + amount: Type.Number(), + duration: Type.Literal('month'), + email: Type.String({ format: 'email', maxLength: 1024 }), + name: Type.String() + }), + response: { + 200: Type.Object({ + subscriptionId: Type.String(), + clientSecret: Type.String() + }), + 400: Type.Object({ + error: Type.Literal( + 'The donation form had invalid values for this submission.' + ) + }), + default: Type.Object({ + error: Type.Literal('Donation failed due to a server error.') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/update-stripe-card.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/update-stripe-card.ts new file mode 100644 index 0000000000000000000000000000000000000000..fffdfcc5d69f889a24ab8277e511db6b36c70198 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/donate/update-stripe-card.ts @@ -0,0 +1,12 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const updateStripeCard = { + body: Type.Object({}), + response: { + 200: Type.Object({ + sessionId: Type.String() + }), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/resubscribe.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/resubscribe.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ef22254102c492a4a9b65df66b2d253ec226225 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/resubscribe.ts @@ -0,0 +1,9 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const resubscribe = { + params: Type.Object({ + unsubscribeId: Type.String({ + minLength: 1 + }) + }) +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/unsubscribe.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/unsubscribe.ts new file mode 100644 index 0000000000000000000000000000000000000000..3cf124780b08f19ff91fabd76dcec5e0d94f5096 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/email-subscription/unsubscribe.ts @@ -0,0 +1,9 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const unsubscribe = { + params: Type.Object({ + unsubscribeId: Type.String({ + minLength: 1 + }) + }) +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/sentry/event.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/sentry/event.ts new file mode 100644 index 0000000000000000000000000000000000000000..fc5150ccd2560484b1a93b308dd4094e80c1b3e8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/sentry/event.ts @@ -0,0 +1,13 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const sentryPostEvent = { + body: Type.Object({ + text: Type.String() + }), + response: { + 500: Type.Object({ + message: Type.Literal('flash.generic-error'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/confirm-email.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/confirm-email.ts new file mode 100644 index 0000000000000000000000000000000000000000..a80742a5a9a8d95cc67a561270e38a46a1d0bd07 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/confirm-email.ts @@ -0,0 +1,8 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const confirmEmail = { + querystring: Type.Object({ + email: Type.String({ maxLength: 1000 }), + token: Type.String({ minLength: 64, maxLength: 64 }) + }) +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-about.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-about.ts new file mode 100644 index 0000000000000000000000000000000000000000..72a412078c9bd11b1398a3801a9702916cc992cb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-about.ts @@ -0,0 +1,25 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyAbout = { + body: Type.Object({ + // TODO(Post-MVP): make these required + about: Type.Optional(Type.String()), + name: Type.Optional(Type.String()), + picture: Type.Optional(Type.String()), + location: Type.Optional(Type.String()) + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.updated-about-me'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-classroom-mode.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-classroom-mode.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee7d980e4cae30ab29f40ce698d00780cd0133ca --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-classroom-mode.ts @@ -0,0 +1,28 @@ +import { Type } from '@fastify/type-provider-typebox'; + +/** + * Classroom mode is one-way: can only be enabled, not disabled. + * Consent revocation is not currently supported but may be added later. + * + * Type.Literal(true) enforces this. To allow revocation, change to Type.Boolean(). + * Body payload is kept so the API contract won't change when revocation is added. + */ +export const updateMyClassroomMode = { + body: Type.Object({ + isClassroomAccount: Type.Literal(true) + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.classroom-mode-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-email.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-email.ts new file mode 100644 index 0000000000000000000000000000000000000000..76a4f2522f9b48e720efed99ce01ba8a4b4a5599 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-email.ts @@ -0,0 +1,27 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyEmail = { + body: Type.Object({ + email: Type.String({ format: 'email', maxLength: 1024 }) + }), + response: { + 200: Type.Object({ + message: Type.Literal( + 'Check your email and click the link we sent you to confirm your new email address.' + ), + type: Type.Literal('info') + }), + 400: Type.Object({ + message: Type.String(), + type: Type.Union([Type.Literal('danger'), Type.Literal('info')]) + }), + 429: Type.Object({ + message: Type.String(), + type: Type.Literal('info') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-experience.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-experience.ts new file mode 100644 index 0000000000000000000000000000000000000000..cd6727560cfbfc8262457fb49d5f1f6b321ff26a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-experience.ts @@ -0,0 +1,34 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyExperience = { + body: Type.Object({ + experience: Type.Array( + Type.Object( + { + id: Type.String(), + title: Type.String(), + company: Type.String(), + location: Type.Optional(Type.String()), + startDate: Type.String(), + endDate: Type.Optional(Type.String()), + description: Type.String() + }, + { additionalProperties: false } + ) + ) + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.experience-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-honesty.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-honesty.ts new file mode 100644 index 0000000000000000000000000000000000000000..365749498ab81eb0b8baeaf3e91b568d5a743f0f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-honesty.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyHonesty = { + body: Type.Object({ + isHonest: Type.Literal(true) + }), + response: { + 200: Type.Object({ + message: Type.Literal('buttons.accepted-honesty'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-keyboard-shortcuts.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-keyboard-shortcuts.ts new file mode 100644 index 0000000000000000000000000000000000000000..ccf372fb171c660735439b73fa915a6374bc6240 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-keyboard-shortcuts.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyKeyboardShortcuts = { + body: Type.Object({ + keyboardShortcuts: Type.Boolean() + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.keyboard-shortcut-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-portfolio.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-portfolio.ts new file mode 100644 index 0000000000000000000000000000000000000000..d79d607b5961e09506700fd16aabf8ba09fed0c4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-portfolio.ts @@ -0,0 +1,32 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyPortfolio = { + body: Type.Object({ + portfolio: Type.Array( + Type.Object({ + description: Type.Optional(Type.String()), + id: Type.Optional(Type.String()), + image: Type.Optional(Type.String()), + title: Type.Optional(Type.String()), + url: Type.Optional(Type.String()) + }) + ) + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.portfolio-item-updated'), + type: Type.Literal('success') + }), + // TODO(Post-MVP): give more detailed response (i.e. which item is + // missing) + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + // TODO(Post-MVP): differentiate with more than just the status + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-privacy-terms.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-privacy-terms.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf6b1a63468c2de2cbbae7013bdbdc6c309e3952 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-privacy-terms.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyPrivacyTerms = { + body: Type.Object({ + quincyEmails: Type.Boolean() + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.privacy-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-profile-ui.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-profile-ui.ts new file mode 100644 index 0000000000000000000000000000000000000000..9c6f0116348ccfa7c27ab090f2cbf0be0ef7797c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-profile-ui.ts @@ -0,0 +1,23 @@ +import { Type } from '@fastify/type-provider-typebox'; + +import { profileUI } from '../types.js'; + +export const updateMyProfileUI = { + body: Type.Object({ + profileUI + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.privacy-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-quincy-email.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-quincy-email.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b3d2cf863a78114f8238abe574a257e6457f38b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-quincy-email.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyQuincyEmail = { + body: Type.Object({ + sendQuincyEmail: Type.Boolean() + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.subscribe-to-quincy-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-socials.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-socials.ts new file mode 100644 index 0000000000000000000000000000000000000000..026ca1780bbec5ed0321fdea766e3c0322b5cd25 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-socials.ts @@ -0,0 +1,30 @@ +import { Type } from '@fastify/type-provider-typebox'; + +const urlOrEmptyString = Type.Union([ + Type.Literal(''), + Type.String({ format: 'uri', maxLength: 1024 }) +]); + +export const updateMySocials = { + body: Type.Object({ + website: urlOrEmptyString, + twitter: urlOrEmptyString, + bluesky: urlOrEmptyString, + githubProfile: urlOrEmptyString, + linkedin: urlOrEmptyString + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.updated-socials'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-theme.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-theme.ts new file mode 100644 index 0000000000000000000000000000000000000000..4f553b001dbd04db0c3b0532044c8dea1a3171bc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-theme.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyTheme = { + body: Type.Object({ + theme: Type.Union([Type.Literal('default'), Type.Literal('night')]) + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.updated-themes'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-username.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-username.ts new file mode 100644 index 0000000000000000000000000000000000000000..46df9b368ae20033b59591913e9f6affc7091b0b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-my-username.ts @@ -0,0 +1,22 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateMyUsername = { + body: Type.Object({ + username: Type.String({ minLength: 3, maxLength: 1000 }) + }), + response: { + 200: Type.Object({ + message: Type.String(), + type: Type.Literal('success'), + variables: Type.Object({ username: Type.String() }) + }), + 400: Type.Object({ + message: Type.Optional(Type.String()), + type: Type.Literal('info') + }), + 500: Type.Object({ + message: Type.String(), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-socrates.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-socrates.ts new file mode 100644 index 0000000000000000000000000000000000000000..96a4acbe01c4ef5af1f63fb1d16738de79455fac --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/settings/update-socrates.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const updateSocrates = { + body: Type.Object({ + socrates: Type.Boolean() + }), + response: { + 200: Type.Object({ + message: Type.Literal('flash.socrates-updated'), + type: Type.Literal('success') + }), + 400: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }), + 500: Type.Object({ + message: Type.Literal('flash.wrong-updating'), + type: Type.Literal('danger') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/signout/signout.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/signout/signout.ts new file mode 100644 index 0000000000000000000000000000000000000000..a112dcd4c38d9c8d9b78830d52e12d5f2e7c76de --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/signout/signout.ts @@ -0,0 +1,9 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const signout = { + response: { + 200: Type.Object({}), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/socrates/ask-socrates.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/socrates/ask-socrates.ts new file mode 100644 index 0000000000000000000000000000000000000000..10a75c39c6a369a5b0b521797b552efafc2de5b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/socrates/ask-socrates.ts @@ -0,0 +1,49 @@ +import { Type } from '@fastify/type-provider-typebox'; + +const socratesHint = Type.Object({ + text: Type.String(), + failed: Type.Optional(Type.Boolean()) +}); + +const usageFields = { + attempts: Type.Integer(), + limit: Type.Integer() +}; + +export const askSocrates = { + body: Type.Object( + { + description: Type.String({ minLength: 1, maxLength: 10000 }), + userInput: Type.Optional(Type.String({ minLength: 1, maxLength: 50000 })), + seed: Type.String({ minLength: 1, maxLength: 50000 }), + hints: Type.Array(socratesHint, { maxItems: 200 }) + }, + { additionalProperties: false } + ), + response: { + 200: Type.Object({ + hint: Type.String(), + ...usageFields + }), + 400: Type.Object({ + error: Type.String(), + type: Type.Literal('info'), + ...usageFields + }), + 403: Type.Object({ + error: Type.String(), + type: Type.Literal('danger'), + ...usageFields + }), + 429: Type.Object({ + error: Type.String(), + type: Type.Literal('info'), + ...usageFields + }), + 500: Type.Object({ + error: Type.String(), + type: Type.Literal('danger'), + ...usageFields + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/types.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..8b03922c51b29f680dc520d707fb50651a458d65 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/types.ts @@ -0,0 +1,94 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const genericError = Type.Object({ + message: Type.Literal('flash.generic-error'), + type: Type.Literal('danger') +}); + +export const isCertMap = Type.Object({ + isA2EnglishCert: Type.Boolean(), + isRespWebDesignCert: Type.Boolean(), + isRespWebDesignCertV9: Type.Boolean(), + isJavascriptCertV9: Type.Boolean(), + isJsAlgoDataStructCert: Type.Boolean(), + isFrontEndLibsCert: Type.Boolean(), + is2018DataVisCert: Type.Boolean(), + isApisMicroservicesCert: Type.Boolean(), + isInfosecQaCert: Type.Boolean(), + isPythonCertV9: Type.Boolean(), + isQaCertV7: Type.Boolean(), + isInfosecCertV7: Type.Boolean(), + isFrontEndCert: Type.Boolean(), + isBackEndCert: Type.Boolean(), + isDataVisCert: Type.Boolean(), + isFullStackCert: Type.Boolean(), + isSciCompPyCertV7: Type.Boolean(), + isDataAnalysisPyCertV7: Type.Boolean(), + isMachineLearningPyCertV7: Type.Boolean(), + isRelationalDatabaseCertV8: Type.Boolean(), + isRelationalDatabaseCertV9: Type.Boolean(), + isCollegeAlgebraPyCertV8: Type.Boolean(), + isFoundationalCSharpCertV8: Type.Boolean(), + isJsAlgoDataStructCertV8: Type.Boolean(), + isA1ChineseCert: Type.Boolean(), + isA2ChineseCert: Type.Boolean(), + isA2SpanishCert: Type.Boolean(), + isB1EnglishCert: Type.Boolean(), + isBackEndDevApisCertV9: Type.Boolean(), + isFullStackDeveloperCertV9: Type.Boolean(), + isFrontEndLibsCertV9: Type.Boolean() +}); + +export const file = Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + history: Type.Array(Type.String()) +}); + +// This is only used for serialization, so should not use format. Reason being, +// the serializer's job is simply to create JSON strings, not to validate the +// data. +export const savedChallenge = Type.Object({ + id: Type.String(), + files: Type.Array(file), + lastSavedDate: Type.Number() +}); + +export const examResults = Type.Object({ + numberOfCorrectAnswers: Type.Number(), + numberOfQuestionsInExam: Type.Number(), + percentCorrect: Type.Number(), + passingPercent: Type.Number(), + passed: Type.Boolean(), + examTimeInSeconds: Type.Number() +}); + +export const surveyTitles = Type.Union([ + Type.Literal('Foundational C# with Microsoft Survey') +]); + +export const profileUI = Type.Object({ + isLocked: Type.Boolean(), + showAbout: Type.Boolean(), + showCerts: Type.Boolean(), + showDonation: Type.Boolean(), + showHeatMap: Type.Boolean(), + showLocation: Type.Boolean(), + showName: Type.Boolean(), + showPoints: Type.Boolean(), + showPortfolio: Type.Boolean(), + showTimeLine: Type.Boolean(), + showExperience: Type.Boolean() +}); + +export const experience = Type.Object({ + id: Type.String(), + title: Type.String(), + company: Type.String(), + location: Type.Optional(Type.String()), + startDate: Type.String(), + endDate: Type.Optional(Type.String()), + description: Type.String() +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-ms-username.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-ms-username.ts new file mode 100644 index 0000000000000000000000000000000000000000..544904004d8206fb078037e8c3ce3e23e89ca0bd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-ms-username.ts @@ -0,0 +1,11 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const deleteMsUsername = { + response: { + 200: Type.Object({ msUsername: Type.Null() }), + 500: Type.Object({ + message: Type.Literal('flash.ms.transcript.unlink-err'), + type: Type.Literal('error') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-my-account.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-my-account.ts new file mode 100644 index 0000000000000000000000000000000000000000..0e11760c1175c6647f903a54ce00fed69ca4fe50 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-my-account.ts @@ -0,0 +1,22 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const deleteMyAccount = { + response: { + 200: Type.Object({}), + default: genericError + } +}; + +export const deleteUser = { + params: Type.Object({ + userId: Type.String({ format: 'objectid', maxLength: 24, minLength: 24 }) + }), + response: { + 204: Type.Null(), + default: Type.Object({ + type: Type.String(), + message: Type.String() + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-user-token.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-user-token.ts new file mode 100644 index 0000000000000000000000000000000000000000..e66c355624903ce5196ccff86f54d1f355e7e130 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/delete-user-token.ts @@ -0,0 +1,15 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const deleteUserToken = { + response: { + 200: Type.Object({ + userToken: Type.Null() + }), + 404: Type.Object({ + message: Type.Literal('userToken not found'), + type: Type.Literal('info') + }), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/exam-environment-token.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/exam-environment-token.ts new file mode 100644 index 0000000000000000000000000000000000000000..8070c8e930c0720747a378da11ac96105018e7dc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/exam-environment-token.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { STANDARD_ERROR } from '../../exam-environment/utils/errors.js'; + +export const userExamEnvironmentToken = { + response: { + 201: Type.Object({ + examEnvironmentAuthorizationToken: Type.String() + }), + 403: STANDARD_ERROR + // default: STANDARD_ERROR + } +}; + +export const getUserExamEnvironmentToken = { + response: { + 200: Type.Object({ + examEnvironmentAuthorizationToken: Type.String() + }), + 404: STANDARD_ERROR + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/get-session-user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/get-session-user.ts new file mode 100644 index 0000000000000000000000000000000000000000..2843b5a9ca48593dac9131d7417f3b54055af956 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/get-session-user.ts @@ -0,0 +1,163 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { + examResults, + profileUI, + savedChallenge, + experience +} from '../types.js'; + +const languages = Type.Array( + Type.Union([Type.Literal('javascript'), Type.Literal('python')]) +); + +export const getSessionUser = { + response: { + 200: Type.Object({ + user: Type.Record( + Type.String(), + Type.Object({ + about: Type.String(), + acceptedPrivacyTerms: Type.Boolean(), + calendar: Type.Record(Type.Number(), Type.Literal(1)), + completedChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + solution: Type.Optional(Type.String()), + githubLink: Type.Optional(Type.String()), + challengeType: Type.Optional(Type.Number()), + // Technically, files is optional, but the db default was [] and + // the client treats null, undefined and [] equivalently. + // TODO(Post-MVP): make this optional. + files: Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + path: Type.Optional(Type.String()) + }) + ), + isManuallyApproved: Type.Optional(Type.Boolean()), + examResults: Type.Optional(examResults) + }) + ), + completedExams: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + challengeType: Type.Optional(Type.Number()), + examResults + }) + ), + quizAttempts: Type.Array( + Type.Object({ + challengeId: Type.String(), + quizId: Type.String(), + timestamp: Type.Number() + }) + ), + completedChallengeCount: Type.Number(), + completedDailyCodingChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + languages + }) + ), + currentChallengeId: Type.String(), + email: Type.String(), + emailVerified: Type.Boolean(), + githubProfile: Type.Optional(Type.String()), + id: Type.String(), + is2018DataVisCert: Type.Boolean(), + is2018FullStackCert: Type.Boolean(), + isA2EnglishCert: Type.Boolean(), + isApisMicroservicesCert: Type.Boolean(), + isBackEndCert: Type.Boolean(), + isCheater: Type.Boolean(), + isCollegeAlgebraPyCertV8: Type.Boolean(), + isDataAnalysisPyCertV7: Type.Boolean(), + isDataVisCert: Type.Boolean(), + isDonating: Type.Boolean(), + isFoundationalCSharpCertV8: Type.Boolean(), + isFrontEndCert: Type.Boolean(), + isFrontEndLibsCert: Type.Boolean(), + isFullStackCert: Type.Boolean(), + isJavascriptCertV9: Type.Boolean(), + isClassroomAccount: Type.Boolean(), + isHonest: Type.Boolean(), + isInfosecCertV7: Type.Boolean(), + isInfosecQaCert: Type.Boolean(), + isJsAlgoDataStructCert: Type.Boolean(), + isJsAlgoDataStructCertV8: Type.Boolean(), + isMachineLearningPyCertV7: Type.Boolean(), + isPythonCertV9: Type.Boolean(), + isQaCertV7: Type.Boolean(), + isRelationalDatabaseCertV8: Type.Boolean(), + isRelationalDatabaseCertV9: Type.Boolean(), + isRespWebDesignCert: Type.Boolean(), + isRespWebDesignCertV9: Type.Boolean(), + isSciCompPyCertV7: Type.Boolean(), + isFrontEndLibsCertV9: Type.Boolean(), + isBackEndDevApisCertV9: Type.Boolean(), + isFullStackDeveloperCertV9: Type.Boolean(), + isB1EnglishCert: Type.Boolean(), + isA2SpanishCert: Type.Boolean(), + isA2ChineseCert: Type.Boolean(), + isA1ChineseCert: Type.Boolean(), + keyboardShortcuts: Type.Boolean(), + linkedin: Type.Optional(Type.String()), + location: Type.String(), + name: Type.String(), + partiallyCompletedChallenges: Type.Array( + Type.Object({ id: Type.String(), completedDate: Type.Number() }) + ), + picture: Type.String(), + points: Type.Number(), + portfolio: Type.Array( + Type.Object({ + description: Type.String(), + id: Type.String(), + image: Type.String(), + title: Type.String(), + url: Type.String() + }) + ), + experience: Type.Optional(Type.Array(experience)), + profileUI, + sendQuincyEmail: Type.Union([Type.Null(), Type.Boolean()]), // // Tri-state: null (likely new user), true (subscribed), false (unsubscribed) + socrates: Type.Optional(Type.Boolean()), + theme: Type.String(), + twitter: Type.Optional(Type.String()), + bluesky: Type.Optional(Type.String()), + website: Type.Optional(Type.String()), + yearsTopContributor: Type.Array(Type.String()), // TODO(Post-MVP): convert to number? + isEmailVerified: Type.Boolean(), + joinDate: Type.String(), + savedChallenges: Type.Optional(Type.Array(savedChallenge)), + username: Type.String(), + usernameDisplay: Type.String(), + userToken: Type.Optional(Type.String()), + completedSurveys: Type.Array( + Type.Object({ + title: Type.String(), + responses: Type.Array( + Type.Object({ + question: Type.String(), + response: Type.String() + }) + ) + }) + ), + msUsername: Type.Optional(Type.String()) + }) + ), + result: Type.String() + }), + 500: Type.Object({ + user: Type.Object({}), + result: Type.Literal('') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/post-ms-username.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/post-ms-username.ts new file mode 100644 index 0000000000000000000000000000000000000000..80473c3946585f73b493f1f2d7c0747d123ecff1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/post-ms-username.ts @@ -0,0 +1,36 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const postMsUsername = { + body: Type.Object({ + msTranscriptUrl: Type.String({ maxLength: 1000 }) + }), + response: { + 200: Type.Object({ + msUsername: Type.String() + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.transcript.link-err-1') + }), + 404: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.transcript.link-err-2') + }), + 403: genericError, + 409: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.transcript.link-err-4') + }), + 500: Type.Union([ + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.transcript.link-err-6') + }), + Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.ms.transcript.link-err-3') + }) + ]) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/report-user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/report-user.ts new file mode 100644 index 0000000000000000000000000000000000000000..7de47bd9e2a80f23463c0f0f9ccc371a4c6d1e1e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/report-user.ts @@ -0,0 +1,28 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const reportUser = { + body: Type.Object({ + username: Type.String(), + reportDescription: Type.String({ minLength: 1 }) + }), + response: { + 200: Type.Object({ + type: Type.Literal('info'), + message: Type.Literal('flash.report-sent'), + variables: Type.Object({ + email: Type.String() + }) + }), + 400: Type.Object({ + type: Type.Literal('danger'), + message: Type.Literal('flash.report-error') + }), + 404: Type.Object({ + type: Type.Literal('danger'), + message: Type.Literal('flash.report-error') + }), + 403: genericError, + 500: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-module.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..73b234c8d3d0a1546abea49734c3da68c65d023a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-module.ts @@ -0,0 +1,21 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const resetModule = { + body: Type.Object({ + blockIds: Type.Array(Type.String({ minLength: 1 }), { + minItems: 1, + maxItems: 500 + }) + }), + response: { + 200: Type.Object({ + removedChallengeIds: Type.Array(Type.String()) + }), + 400: Type.Object({ + message: Type.String(), + type: Type.String() + }), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-my-progress.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-my-progress.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9661b293d7bf1bb71cc2008a906a0c5d154493c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/reset-my-progress.ts @@ -0,0 +1,9 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError } from '../types.js'; + +export const resetMyProgress = { + response: { + 200: Type.Object({}), + default: genericError + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/submit-survey.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/submit-survey.ts new file mode 100644 index 0000000000000000000000000000000000000000..5bd61c19960275ac5fa7009a8748d3b5d9fa3a3b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/user/submit-survey.ts @@ -0,0 +1,35 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { genericError, surveyTitles } from '../types.js'; + +export const submitSurvey = { + body: Type.Object({ + surveyResults: Type.Object({ + title: surveyTitles, + responses: Type.Array( + Type.Object({ + question: Type.String(), + response: Type.String() + }) + ) + }) + }), + response: { + 200: Type.Object({ + type: Type.Literal('success'), + message: Type.Literal('flash.survey.success') + }), + 400: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.survey.err-1') + }), + 403: genericError, + 409: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.survey.err-2') + }), + 500: Type.Object({ + type: Type.Literal('error'), + message: Type.Literal('flash.survey.err-3') + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/exists.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/exists.ts new file mode 100644 index 0000000000000000000000000000000000000000..8655c824ee5a3e4a28da7c1515eac70e11978c12 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/exists.ts @@ -0,0 +1,17 @@ +import { Type } from '@fastify/type-provider-typebox'; + +export const userExists = { + querystring: Type.Object({ + username: Type.String({ minLength: 1 }) + }), + response: { + 200: Type.Object({ + exists: Type.Boolean() + }), + 400: Type.Object({ + type: Type.Literal('danger'), + message: Type.Literal('username parameter is required') + // message: Type.Literal("'username' parameter is required") + }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/get-public-profile.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/get-public-profile.ts new file mode 100644 index 0000000000000000000000000000000000000000..86ce2a99ec7a237395e116183d202ddbeed84634 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/schemas/users/get-public-profile.ts @@ -0,0 +1,127 @@ +import { Type } from '@fastify/type-provider-typebox'; +import { profileUI, examResults, experience } from '../types.js'; + +export const getPublicProfile = { + querystring: Type.Object({ + username: Type.String({ minLength: 1 }) + }), + response: { + 200: Type.Object({ + entities: Type.Object({ + user: Type.Record( + Type.String(), + Type.Union([ + Type.Object({ + isLocked: Type.Boolean(), + profileUI, + username: Type.String() + }), + Type.Object({ + about: Type.String(), + calendar: Type.Record(Type.Number(), Type.Literal(1)), + completedChallenges: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + solution: Type.Optional(Type.String()), + githubLink: Type.Optional(Type.String()), + challengeType: Type.Optional(Type.Number()), + files: Type.Array( + Type.Object({ + contents: Type.String(), + key: Type.String(), + ext: Type.String(), + name: Type.String(), + path: Type.Optional(Type.String()) + }) + ), + isManuallyApproved: Type.Optional(Type.Boolean()), + examResults: Type.Optional(examResults) + }) + ), + completedExams: Type.Array( + Type.Object({ + id: Type.String(), + completedDate: Type.Number(), + challengeType: Type.Optional(Type.Number()), + examResults + }) + ), + experience: Type.Array(experience), + // TODO(Post-MVP): return completedSurveys? Presumably not, since why + // would this need to be public. + githubProfile: Type.Optional(Type.String()), + is2018DataVisCert: Type.Boolean(), + is2018FullStackCert: Type.Boolean(), + isA2EnglishCert: Type.Boolean(), + isB1EnglishCert: Type.Boolean(), + isApisMicroservicesCert: Type.Boolean(), + isBackEndCert: Type.Boolean(), + isBackEndDevApisCertV9: Type.Boolean(), + isCheater: Type.Boolean(), + isCollegeAlgebraPyCertV8: Type.Boolean(), + isDataAnalysisPyCertV7: Type.Boolean(), + isDataVisCert: Type.Boolean(), + // TODO(Post-MVP): isDonating should be boolean. + isDonating: Type.Union([Type.Boolean(), Type.Null()]), + isFoundationalCSharpCertV8: Type.Boolean(), + isFrontEndCert: Type.Boolean(), + isFrontEndLibsCert: Type.Boolean(), + isFrontEndLibsCertV9: Type.Boolean(), + isFullStackCert: Type.Boolean(), + isJavascriptCertV9: Type.Boolean(), + isHonest: Type.Boolean(), + isInfosecCertV7: Type.Boolean(), + isInfosecQaCert: Type.Boolean(), + isJsAlgoDataStructCert: Type.Boolean(), + isJsAlgoDataStructCertV8: Type.Boolean(), + isMachineLearningPyCertV7: Type.Boolean(), + isPythonCertV9: Type.Boolean(), + isQaCertV7: Type.Boolean(), + isRelationalDatabaseCertV8: Type.Boolean(), + isRelationalDatabaseCertV9: Type.Boolean(), + isRespWebDesignCert: Type.Boolean(), + isRespWebDesignCertV9: Type.Boolean(), + isSciCompPyCertV7: Type.Boolean(), + linkedin: Type.Optional(Type.String()), + location: Type.String(), + name: Type.String(), + picture: Type.String(), + // TODO(Post-MVP): points should be a number + points: Type.Union([Type.Number(), Type.Null()]), + portfolio: Type.Array( + Type.Object({ + description: Type.String(), + id: Type.String(), + image: Type.String(), + title: Type.String(), + url: Type.String() + }) + ), + profileUI, + twitter: Type.Optional(Type.String()), + bluesky: Type.Optional(Type.String()), + website: Type.Optional(Type.String()), + yearsTopContributor: Type.Array(Type.String()), // TODO(Post-MVP): convert to number? + joinDate: Type.String(), + username: Type.String(), + usernameDisplay: Type.String(), + msUsername: Type.Optional(Type.String()) + }) + ]) + ) + }), + result: Type.String() + }), + // We can't simply have Type.Object({}), even though that's correct, because + // TypeScript will then accept all responses (since every object can be + // assigned to {}) + 400: Type.Union([ + Type.Object({ entities: Type.Optional(Type.Never()) }), + Type.Literal( + 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' + ) + ]), + 404: Type.Object({ entities: Type.Optional(Type.Never()) }) + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/server.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/server.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cc6e0761c56258c577ef927e95b3845d840e5433 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/server.test.ts @@ -0,0 +1,86 @@ +import { describe, test, expect, vi } from 'vitest'; +import { setupServer, superRequest } from '../vitest.utils.js'; +import { HOME_LOCATION } from './utils/env.js'; + +vi.mock('./utils/env', async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + COOKIE_DOMAIN: 'freecodecamp.org' + }; +}); + +describe('server', () => { + setupServer(); + + describe('GET /', () => { + test('should have OWASP recommended headers', async () => { + const res = await superRequest('/', { method: 'GET' }); + expect(res.headers).toMatchObject({ + 'cache-control': 'no-store', + 'content-security-policy': "frame-ancestors 'none'", + 'content-type': 'application/json; charset=utf-8', + 'x-content-type-options': 'nosniff', + 'x-frame-options': 'DENY' + // In production we also set strict-transport-security, but in order to + // test this we would need to mock FREECODECAMP_NODE_ENV to production. + // This is possible, but has side effects (like using the normal + // database instead of the test ones). On balance it's not worth it. + }); + }); + + test.each([ + 'https://www.freecodecamp.org', + 'https://www.freecodecamp.dev', + 'https://beta.freecodecamp.org', + 'https://beta.freecodecamp.dev', + 'https://chinese.freecodecamp.org', + 'https://chinese.freecodecamp.dev' + ])( + 'should have Access-Control-Allow-Origin header for %s', + async origin => { + const res = await superRequest('/', { method: 'GET' }).set( + 'origin', + origin + ); + expect(res.headers).toMatchObject({ + 'access-control-allow-origin': origin + }); + } + ); + + test('should have HOME_LOCATION Access-Control-Allow-Origin header for other origins', async () => { + const res = await superRequest('/', { method: 'GET' }).set( + 'origin', + 'https://www.google.com' + ); + expect(res.headers).toMatchObject({ + 'access-control-allow-origin': HOME_LOCATION + }); + }); + + test('should have CORS headers', async () => { + const res = await superRequest('/', { method: 'GET' }); + expect(res.headers).toMatchObject({ + 'access-control-allow-headers': + 'Origin, X-Requested-With, Content-Type, Accept, Csrf-Token, Coderoad-User-Token, Exam-Environment-Authorization-Token', + 'access-control-allow-credentials': 'true', + 'access-control-allow-methods': 'GET, PUT, POST, DELETE' + }); + }); + }); + + describe('GET /documentation', () => { + test('should have OWASP recommended headers, except content-type', async () => { + const res = await superRequest('/documentation/static/index.html', { + method: 'GET' + }); + expect(res.headers).toMatchObject({ + 'cache-control': 'no-store', + 'content-security-policy': "frame-ancestors 'none'", + 'x-content-type-options': 'nosniff', + 'x-frame-options': 'DENY' + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/server.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/server.ts new file mode 100644 index 0000000000000000000000000000000000000000..868a96770131420a2c4712c722fddefa94024a3f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/server.ts @@ -0,0 +1,77 @@ +import './instrument.js'; + +import os from 'node:os'; + +import * as Sentry from '@sentry/node'; +import { build, buildOptions } from './app.js'; +import { + DEPLOYMENT_VERSION, + HOST, + PORT, + SENTRY_SERVER_NAME, + FCC_DRAIN_TIMEOUT_MS +} from './utils/env.js'; + +const start = async () => { + let fastify: Awaited> | undefined; + + try { + fastify = await build(buildOptions); + + const stop = async (signal: NodeJS.Signals) => { + fastify!.log.info({ signal }, 'Received signal, shutting down'); + + // Safety net: if in-flight requests do not finish in time, hard-close + // whatever is left so Swarm's SIGKILL never fires mid-write. + const forceClose = setTimeout(() => { + fastify!.log.warn( + { signal, timeoutMs: FCC_DRAIN_TIMEOUT_MS }, + 'Drain timeout exceeded, force-closing connections' + ); + fastify!.server.closeAllConnections(); + }, FCC_DRAIN_TIMEOUT_MS); + forceClose.unref(); + + await fastify!.close(); + clearTimeout(forceClose); + Sentry.metrics.count('server.shutdown_completed', 1, { + attributes: { signal } + }); + await fastify!.Sentry.close(2000); + // No process.exit(): once close() resolves, the loop drains and the + // process exits 0 on its own. Hard-exiting here is what used to race + // pino's exit-time flush (see #66135). + }; + + process.on('SIGINT', signal => void stop(signal)); + process.on('SIGTERM', signal => void stop(signal)); + + const address = await fastify.listen({ port: Number(PORT), host: HOST }); + fastify.log.info( + { + audit: true, + version: DEPLOYMENT_VERSION, + instanceId: SENTRY_SERVER_NAME ?? os.hostname(), + address + }, + 'API server started' + ); + Sentry.metrics.count('server.boot', 1, { + attributes: { result: 'success' } + }); + } catch (err) { + if (fastify) { + fastify.log.error(err, 'Failed to start server'); + } else { + console.error('Failed to start server', err); + } + Sentry.metrics.count('server.boot', 1, { + attributes: { result: 'failure' } + }); + Sentry.captureException(err); + await (fastify?.Sentry ?? Sentry).close(2000); + process.exit(1); + } +}; + +void start(); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/allowed-origins.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/allowed-origins.ts new file mode 100644 index 0000000000000000000000000000000000000000..897489d447a2bf57ddb7f0c27e59bc6ff344368a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/allowed-origins.ts @@ -0,0 +1,17 @@ +import { HOME_LOCATION, FREECODECAMP_NODE_ENV } from './env.js'; + +const ALLOWED_ORIGINS = [ + 'https://www.freecodecamp.dev', + 'https://www.freecodecamp.org', + 'https://exam.freecodecamp.org', + // pretty sure the rest of these can go? + 'https://beta.freecodecamp.dev', + 'https://beta.freecodecamp.org', + 'https://chinese.freecodecamp.dev', + 'https://chinese.freecodecamp.org' +]; + +export const allowedOrigins = + FREECODECAMP_NODE_ENV === 'development' + ? [...ALLOWED_ORIGINS, HOME_LOCATION] + : ALLOWED_ORIGINS; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/common-challenge-functions.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/common-challenge-functions.ts new file mode 100644 index 0000000000000000000000000000000000000000..7847080e975ca03b7492b291593340f0e7a1c107 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/common-challenge-functions.ts @@ -0,0 +1,240 @@ +import type { ExamResults, user, Prisma } from '@prisma/client'; +import { FastifyInstance } from 'fastify'; +import { omit, pick } from 'lodash-es'; +import { challengeTypes } from '@freecodecamp/shared/config/challenge-types'; +import { challenges, savableChallenges } from './get-challenges.js'; +import { normalizeDate } from './normalize.js'; + +export const jsCertProjectIds = [ + 'aaa48de84e1ecc7c742e1124', + 'a7f4d8f2483413a6ce226cac', + '56533eb9ac21ba0edf2244e2', + 'aff0395860f5d3034dc0bfc9', + 'aa2e6f85cab2ab736c9a9b24' +]; + +export const multifileCertProjectIds = challenges + .filter(c => c.challengeType === challengeTypes.multifileCertProject) + .map(c => c.id); + +export const multifilePythonCertProjectIds = challenges + .filter(c => c.challengeType === challengeTypes.multifilePythonCertProject) + .map(c => c.id); + +export const msTrophyChallenges = challenges + .filter(challenge => challenge.challengeType === challengeTypes.msTrophy) + .map(({ id, msTrophyId }) => ({ id, msTrophyId })); + +type SavedChallengeFile = { + key: string; + ext: string; // NOTE: This is Ext type in client + name: string; + history: string[]; + contents: string; +}; + +type SavedChallenge = { + id: string; + lastSavedDate: number; + files: SavedChallengeFile[]; +}; + +// TODO: Confirm this type - read comments below +type CompletedChallengeFile = { + key: string; + ext: string; // NOTE: This is Ext type in client + name: string; + contents: string; + + // These values are present in prop-types and ajax.ts builds with it + // editableRegionBoundaries?: number[]; + // usesMultifileEditor?: boolean; + // error: null | string | unknown; + // head: string; + // tail: string; + // seed: string; + // id: string; + // history: string[]; + + // This value is present in prisma schema + path?: string | null; +}; + +// TODO: Should probably prefer `import{CompletedChallenge}from'@prisma/client'` instead of defining it here +export type CompletedChallenge = { + id: string; + solution?: string | null; + githubLink?: string | null; + challengeType?: number | null; + completedDate: number; + isManuallyApproved?: boolean | null; + files?: CompletedChallengeFile[]; + examResults?: ExamResults | null; +}; + +/** + * Helper function to save a user's challenge data. Used in challenge + * submission endpoints. + * + * @param challengeId The id of the submitted challenge. + * @param savedChallenges The user's saved challenges array. + * @param challenge The saveble challenge. + * @returns Update or push the saved challenges. + */ +export function saveUserChallengeData( + challengeId: string, + savedChallenges: SavedChallenge[], + challenge: Omit +) { + const challengeToSave: SavedChallenge = { + id: challengeId, + lastSavedDate: Date.now(), + files: challenge.files?.map(file => + pick(file, ['contents', 'key', 'name', 'ext', 'history']) + ) + }; + + const savedIndex = savedChallenges.findIndex(({ id }) => challengeId === id); + + if (savedIndex >= 0) { + savedChallenges[savedIndex] = challengeToSave; + } else { + savedChallenges.push(challengeToSave); + } + + return savedChallenges; +} + +/** + * Helper function to update a user's challenge data. Used in challenge + * submission endpoints. + * TODO: Keep refactoring. This function does too much. + * @param fastify The Fastify instance. + * @param user The existing user record. + * @param challengeId The id of the submitted challenge. + * @param _completedChallenge The challenge submission. + * @returns Information about the update. + */ +export async function updateUserChallengeData( + fastify: FastifyInstance, + user: Pick< + user, + | 'id' + | 'completedChallenges' + | 'needsModeration' + | 'savedChallenges' + | 'progressTimestamps' + | 'partiallyCompletedChallenges' + >, + challengeId: string, + _completedChallenge: CompletedChallenge +) { + const { files, completedDate: newProgressTimeStamp = Date.now() } = + _completedChallenge; + let completedChallenge: CompletedChallenge; + + if (savableChallenges.has(challengeId)) { + completedChallenge = { + ..._completedChallenge, + files: files?.map( + file => + pick(file, [ + 'contents', + 'key', + 'index', + 'name', + 'path', + 'ext' + ]) as CompletedChallengeFile + ), + completedDate: normalizeDate(_completedChallenge.completedDate) + }; + } else { + completedChallenge = omit(_completedChallenge, ['files']); + } + + const { + completedChallenges = [], + needsModeration = false, + savedChallenges = [], + progressTimestamps = [], + partiallyCompletedChallenges = [] + } = user; + + let savedChallengesUpdate: Prisma.userUpdateInput['savedChallenges']; + + const oldChallenge = completedChallenges.find(({ id }) => challengeId === id); + const alreadyCompleted = !!oldChallenge; + + const finalChallenge = alreadyCompleted + ? { + ...completedChallenge, + completedDate: normalizeDate(oldChallenge.completedDate) + } + : completedChallenge; + + // TODO(Post-MVP): prevent concurrent completions of the same challenge by + // using optimistic concurrency control. i.e. the update should simultaneously + // check and update some property of the user record such that the same update + // can't be applied twice. + const userCompletedChallenges = alreadyCompleted + ? completedChallenges.map(x => + x.id === challengeId + ? finalChallenge + : { ...x, completedDate: normalizeDate(x.completedDate) } + ) + : { push: finalChallenge }; + + // We can't use push, because progressTimestamps is a JSON blob and, until + // we convert it to an array, push is not available. Since this could result + // in the completedChallenges and progressTimestamps arrays being out of sync, + // we should prioritize normalizing the data structure. + const userProgressTimestamps = + !alreadyCompleted && progressTimestamps && Array.isArray(progressTimestamps) + ? [...progressTimestamps, newProgressTimeStamp] + : progressTimestamps; + + if (savableChallenges.has(challengeId)) { + const challengeToSave: SavedChallenge = { + id: challengeId, + lastSavedDate: newProgressTimeStamp, + files: files?.map(file => + pick(file, ['contents', 'key', 'name', 'ext', 'history']) + ) as SavedChallengeFile[] + }; + + const isSaved = savedChallenges.some(({ id }) => challengeId === id); + + savedChallengesUpdate = isSaved + ? savedChallenges.map(x => (x.id === challengeId ? challengeToSave : x)) + : { push: challengeToSave }; + } + + // remove from partiallyCompleted on submit + const userPartiallyCompletedChallenges = partiallyCompletedChallenges.filter( + challenge => challenge.id !== challengeId + ); + + const { savedChallenges: userSavedChallenges } = + await fastify.prisma.user.update({ + where: { id: user.id }, + data: { + completedChallenges: userCompletedChallenges, + // TODO: `needsModeration` should be handled closer to source, because it exists in 3 states: true, false, undefined/null + // `undefined` in Prisma is a no-op + needsModeration: needsModeration || undefined, + savedChallenges: savedChallengesUpdate, + progressTimestamps: userProgressTimestamps, + partiallyCompletedChallenges: userPartiallyCompletedChallenges + }, + select: { + savedChallenges: true + } + }); + + return { + alreadyCompleted, + completedDate: finalChallenge.completedDate, + userSavedChallenges + }; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/create-user.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/create-user.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f714f2661bf17fba235bfb4c063fa4f01fb6490 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/create-user.ts @@ -0,0 +1,106 @@ +import crypto from 'node:crypto'; + +import { customAlphabet } from 'nanoid'; + +export const nanoidCharSet = + '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; +const nanoid = customAlphabet(nanoidCharSet, 21); + +/** + * Creates the necessary data to reset a user's properties. + * @returns Default data for resetting a user's properties. + */ +export const createResetProperties = () => ({ + completedChallenges: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + completedExams: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + currentChallengeId: '', + experience: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + is2018DataVisCert: false, + is2018FullStackCert: false, + isA2EnglishCert: false, + isApisMicroservicesCert: false, + isBackEndCert: false, + isCollegeAlgebraPyCertV8: false, + isDataAnalysisPyCertV7: false, + isDataVisCert: false, + isFoundationalCSharpCertV8: false, + isFrontEndCert: false, + isFrontEndLibsCert: false, + isFullStackCert: false, + isInfosecCertV7: false, + isInfosecQaCert: false, + isJavascriptCertV9: false, + isJsAlgoDataStructCert: false, + isJsAlgoDataStructCertV8: false, + isMachineLearningPyCertV7: false, + isPythonCertV9: false, + isQaCertV7: false, + isRelationalDatabaseCertV8: false, + isRelationalDatabaseCertV9: false, + isRespWebDesignCert: false, + isRespWebDesignCertV9: false, + isSciCompPyCertV7: false, + isFrontEndLibsCertV9: false, + isBackEndDevApisCertV9: false, + isFullStackDeveloperCertV9: false, + isB1EnglishCert: false, + isA2SpanishCert: false, + isA2ChineseCert: false, + isA1ChineseCert: false, + needsModeration: false, + partiallyCompletedChallenges: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + progressTimestamps: [Date.now()], // TODO(Post-MVP): This may need normalising before we can omit it. Also, does it need to start with a timestamp? + savedChallenges: [] // TODO(Post-MVP): Omit this from the document? (prisma will always return []) +}); + +/** + * Creates the necessary data to create a new user. + * @param email The email address of the new user. + * @returns Default data for a new user. + */ +export function createUserInput(email: string) { + const username = 'fcc-' + crypto.randomUUID(); + const externalId = crypto.randomUUID(); + // This explicitly includes all array fields. This is not strictly necessary - + // Prisma will return an empty array even if the property is missing, but it's + // probably best to add them to the document, at least until we normalise the + // data. + return { + about: '', + acceptedPrivacyTerms: false, + donationEmails: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + email, + emailVerified: true, // this should be true until a user changes their email address + // TODO(Post-MVP): remove externalId? + externalId, + isBanned: false, + isCheater: false, + isDonating: false, + isHonest: false, + keyboardShortcuts: false, + location: '', + name: '', + unsubscribeId: nanoid(), + picture: '', + portfolio: [], // TODO(Post-MVP): Omit this from the document? (prisma will always return []) + profileUI: { + isLocked: false, + showAbout: false, + showCerts: false, + showDonation: false, + showExperience: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false + }, + sendQuincyEmail: null, + theme: 'default', + username, + usernameDisplay: username, + yearsTopContributor: [], // TODO: Omit this from the document? (prisma will always return []), + ...createResetProperties() + }; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2058e31c6ccd982cdd33112947fd4f65e3d4bb72 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect } from 'vitest'; +import { assignVariantBucket } from './drip-campaign.js'; + +describe('assignVariantBucket', () => { + it('should return either A or B', () => { + const variant = assignVariantBucket('test-user-id'); + expect(['A', 'B']).toContain(variant); + }); + + it('should return consistent results for the same userId', () => { + const userId = '6863cb33ad61b38a74d2ba40'; + const variant1 = assignVariantBucket(userId); + const variant2 = assignVariantBucket(userId); + const variant3 = assignVariantBucket(userId); + + expect(variant1).toBe(variant2); + expect(variant2).toBe(variant3); + }); + + it('should distribute users across both buckets', () => { + const variants = new Set(); + + // Test with multiple user IDs to ensure both buckets are possible + for (let i = 0; i < 100; i++) { + const variant = assignVariantBucket(`user-${i}`); + variants.add(variant); + } + + // Both A and B should be present + expect(variants.has('A')).toBe(true); + expect(variants.has('B')).toBe(true); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c676e513eb02815bd3d9ff998c633b26a9436a1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/drip-campaign.ts @@ -0,0 +1,19 @@ +import crypto from 'node:crypto'; + +/** + * Assigns a user to variant bucket A or B based on a hash of their userId. + * This ensures consistent variant assignment for the same userId. + * + * @param userId - The user's unique identifier. + * @returns 'A' or 'B' based on the hash. + */ +export function assignVariantBucket(userId: string): 'A' | 'B' { + // Create a hash of the userId + const hash = crypto.createHash('sha256').update(userId).digest('hex'); + + // Convert first character of hash to a number (0-15 in hex) + // Use modulo 2 to determine bucket A or B + const numericValue = parseInt(hash.charAt(0), 16); + + return numericValue % 2 === 0 ? 'A' : 'B'; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/email-templates.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/email-templates.ts new file mode 100644 index 0000000000000000000000000000000000000000..20f502b75c1d596addaa3c6e68bd49d5a0235a62 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/email-templates.ts @@ -0,0 +1,33 @@ +import { user } from '@prisma/client'; + +/** + * Generates an email template for reporting a user profile. + * @param reporter - The user who is reporting the profile. + * @param abuser - The username of the user being reported. + * @param reportDesc - The description of the report. + * @returns - The generated email template. + */ +export const generateReportEmail = ( + reporter: user, + abuser: user, + reportDesc: string +) => { + return ` +Hello Team, + +This is to report the profile of ${abuser.username}. ID: ${abuser.id}. + +Report Details: + +${reportDesc} + + +Reported by: +ID: ${reporter.id} +Username: ${reporter.username} +Name:${reporter.name ? ' ' + reporter.name : ''} +Email: ${reporter.email} + +Thanks and regards, +${reporter.name ?? reporter.username}`; +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/env.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/env.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f6dee31818a34c394e624ad368f59085b9be015 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/env.ts @@ -0,0 +1,301 @@ +import assert from 'node:assert'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { config } from 'dotenv'; +import { LogLevel } from 'fastify'; +import { parseBool, parseInt } from './validation.js'; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const envPath = path.resolve(__dirname, '../../../.env'); +const { error } = config({ path: envPath }); + +if ( + error && + process.env.FREECODECAMP_NODE_ENV == 'production' && + process.env.NODE_ENV !== 'test' +) { + console.warn(` + ---------------------------------------------------- + Warning: .env file not found. + ---------------------------------------------------- + Please copy sample.env to .env + + You can ignore this warning if using a different way + to setup this environment. + ---------------------------------------------------- + `); +} + +function isAllowedEnv(env: string): env is 'development' | 'production' { + return ['development', 'production'].includes(env); +} + +const _EMAIL_PROVIDER = process.env.EMAIL_PROVIDER || 'ses'; +const _FREECODECAMP_NODE_ENV = + process.env.FREECODECAMP_NODE_ENV || 'production'; + +function isAllowedProvider(provider: string): provider is 'ses' | 'nodemailer' { + return ['ses', 'nodemailer'].includes(provider); +} + +function createTestConnectionURL(url: string, dbId?: string) { + assert.notEqual( + _FREECODECAMP_NODE_ENV, + 'production', + "The database URL can't be modified in production." + ); + assert.ok( + dbId, + `dbId is required for test connection URL. Is this running in a test environment? +If so, ensure that the environment variable VITEST_WORKER_ID is set.` + ); + return url.replace(/(.*)(\?.*)/, `$1${dbId}$2`); +} + +assert.ok(process.env.HOME_LOCATION); +assert.ok(isAllowedEnv(_FREECODECAMP_NODE_ENV)); +assert.ok(process.env.DEPLOYMENT_ENV); +assert.ok(isAllowedProvider(_EMAIL_PROVIDER)); +assert.ok(process.env.AUTH0_CLIENT_ID); +assert.ok(process.env.AUTH0_CLIENT_SECRET); +assert.ok(process.env.AUTH0_DOMAIN); +assert.ok(process.env.API_LOCATION); +assert.ok(process.env.JWT_SECRET); +assert.ok(process.env.STRIPE_SECRET_KEY); +assert.ok(process.env.MONGOHQ_URL); +assert.ok(process.env.COOKIE_SECRET); +assert.ok(process.env.SOCRATES_API_KEY); +assert.ok(process.env.SOCRATES_ENDPOINT); + +const LOG_LEVELS: LogLevel[] = [ + 'fatal', + 'error', + 'warn', + 'info', + 'debug', + 'trace', + 'silent' +] as const; + +function isLogLevel(level: string): level is LogLevel { + return LOG_LEVELS.includes(level); +} + +const _FCC_API_LOG_LEVEL = process.env.FCC_API_LOG_LEVEL || 'info'; +const _FCC_API_LOG_TRANSPORT = process.env.FCC_API_LOG_TRANSPORT || 'default'; + +assert.ok( + isLogLevel(_FCC_API_LOG_LEVEL), + `FCC_API_LOG_LEVEL must be one of ${LOG_LEVELS.join(', ')}. Found ${_FCC_API_LOG_LEVEL}` +); + +assert.ok( + _FCC_API_LOG_TRANSPORT === 'pretty' || _FCC_API_LOG_TRANSPORT === 'default', + `FCC_API_LOG_TRANSPORT must be one of 'pretty' or 'default'. Found ${_FCC_API_LOG_TRANSPORT}` +); + +if (process.env.FREECODECAMP_NODE_ENV !== 'development') { + assert.ok( + process.env.SES_SMTP_USERNAME, + 'SES_SMTP_USERNAME is required in production.' + ); + assert.ok( + process.env.SES_SMTP_PASSWORD, + 'SES_SMTP_PASSWORD is required in production.' + ); + assert.notEqual( + process.env.SES_SMTP_PASSWORD, + 'ses_smtp_password_from_aws', + 'The SES SMTP password should be changed from the default value.' + ); + assert.ok(process.env.COOKIE_DOMAIN); + assert.notEqual(process.env.COOKIE_SECRET, 'a_cookie_secret'); + assert.ok(process.env.SENTRY_DSN); + assert.ok(process.env.SENTRY_ENVIRONMENT); + assert.ok(process.env.DEPLOYMENT_VERSION); + // The following values can exist in development, but production-like + // environments need to override the defaults. + assert.notEqual( + process.env.SENTRY_DSN, + 'dsn_from_sentry_dashboard', + `The DSN from Sentry's dashboard should be used.` + ); + assert.notEqual( + process.env.SENTRY_ENVIRONMENT, + 'development', + `The Sentry environment should be changed from the default.` + ); + assert.notEqual( + process.env.JWT_SECRET, + 'a_jwt_secret', + 'The JWT secret should be changed from the default value.' + ); + assert.ok( + process.env.FCC_ENABLE_DEV_LOGIN_MODE !== 'true', + 'Dev login mode MUST be disabled in production.' + ); + assert.ok( + process.env.EMAIL_PROVIDER === 'ses', + 'SES MUST be used in production.' + ); + assert.notEqual( + process.env.STRIPE_SECRET_KEY, + 'sk_from_stripe_dashboard', + 'The Stripe secret should be changed from the default value.' + ); + assert.notEqual(process.env.NODE_ENV, 'test'); + assert.notEqual( + process.env.AUTH0_CLIENT_SECRET, + 'client_secret_from_auth0_dashboard', + 'The Auth0 client secret should be changed from the default value.' + ); + assert.ok( + process.env.GROWTHBOOK_FASTIFY_API_HOST, + 'GROWTHBOOK_FASTIFY_API_HOST should be set.' + ); + assert.notEqual( + process.env.GROWTHBOOK_FASTIFY_API_HOST, + 'fastify_api_sdk_api_host_from_growthbook_dashboard', + 'The GROWTHBOOK_FASTIFY_API_HOST env should be changed from the default value.' + ); + assert.ok( + process.env.GROWTHBOOK_FASTIFY_CLIENT_KEY, + 'GROWTHBOOK_FASTIFY_CLIENT_KEY should be set.' + ); + assert.notEqual( + process.env.GROWTHBOOK_FASTIFY_CLIENT_KEY, + 'fastify_api_sdk_client_key_from_growthbook_dashboard', + 'The GROWTHBOOK_FASTIFY_CLIENT_KEY env should be changed from the default value.' + ); + if (process.env.FCC_ENABLE_CLASSROOM === 'true') { + assert.ok( + process.env.TPA_API_BEARER_TOKEN, + 'TPA_API_BEARER_TOKEN should be set.' + ); + assert.notEqual( + process.env.TPA_API_BEARER_TOKEN, + 'tpa_api_bearer_token_from_dashboard', + 'The TPA_API_BEARER_TOKEN env should be changed from the default value.' + ); + } +} + +export const HOME_LOCATION = process.env.HOME_LOCATION; +// Mailpit is used in development and test environments, hence the localhost +// default. +export const MAILPIT_HOST = process.env.MAILPIT_HOST ?? 'localhost'; +export const MONGOHQ_URL = + process.env.NODE_ENV === 'test' + ? createTestConnectionURL( + process.env.MONGOHQ_URL, + process.env.VITEST_WORKER_ID + ) + : process.env.MONGOHQ_URL; + +export const AUTH0_CLIENT_ID = process.env.AUTH0_CLIENT_ID; +export const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN; +export const AUTH0_CLIENT_SECRET = process.env.AUTH0_CLIENT_SECRET; +export const EMAIL_PROVIDER = _EMAIL_PROVIDER; +export const PORT = process.env.PORT || '3000'; +// HOST defaults to 0.0.0.0 because the server is intended to be used in a +// container. +export const HOST = process.env.HOST || '0.0.0.0'; +export const API_LOCATION = process.env.API_LOCATION; +export const FCC_ENABLE_SWAGGER_UI = parseWith( + 'FCC_ENABLE_SWAGGER_UI', + undefined, + parseBool +); +export const FCC_ENABLE_DEV_LOGIN_MODE = + process.env.FCC_ENABLE_DEV_LOGIN_MODE === 'true'; +export const FCC_API_LOG_LEVEL = _FCC_API_LOG_LEVEL; +export const FCC_API_LOG_TRANSPORT = _FCC_API_LOG_TRANSPORT; +export const FCC_ENABLE_SENTRY_ROUTES = parseWith( + 'FCC_ENABLE_SENTRY_ROUTES', + undefined, + parseBool +); +export const FCC_ENABLE_CLASSROOM = parseWith( + 'FCC_ENABLE_CLASSROOM', + undefined, + parseBool +); +export const FREECODECAMP_NODE_ENV = _FREECODECAMP_NODE_ENV; +export const DEPLOYMENT_ENV = process.env.DEPLOYMENT_ENV; +export const SENTRY_DSN = + process.env.SENTRY_DSN === 'dsn_from_sentry_dashboard' + ? '' + : process.env.SENTRY_DSN; +export const SENTRY_ENVIRONMENT = + process.env.SENTRY_ENVIRONMENT === 'development' + ? '' + : process.env.SENTRY_ENVIRONMENT; +export const SENTRY_SERVER_NAME = process.env.SENTRY_SERVER_NAME; +function parseUnitRate(name: string, fallback: number): number { + const raw = process.env[name]; + if (raw == null || raw.trim() === '') return fallback; + const value = Number(raw); + assert.ok( + Number.isFinite(value) && value >= 0 && value <= 1, + `${name} must be a number between 0 and 1. Found ${raw}` + ); + return value; +} +export const SENTRY_TRACES_SAMPLE_RATE = parseUnitRate( + 'SENTRY_TRACES_SAMPLE_RATE', + 0.1 +); +export const SENTRY_PROFILE_SESSION_SAMPLE_RATE = parseUnitRate( + 'SENTRY_PROFILE_SESSION_SAMPLE_RATE', + 0.1 +); +export const SENTRY_LOGS_DEBUG_SAMPLE_RATE = parseUnitRate( + 'SENTRY_LOGS_DEBUG_SAMPLE_RATE', + 0.05 +); +export const SENTRY_LOGS_INFO_SAMPLE_RATE = parseUnitRate( + 'SENTRY_LOGS_INFO_SAMPLE_RATE', + 1.0 +); +export const COOKIE_DOMAIN = process.env.COOKIE_DOMAIN; +export const COOKIE_SECRET = process.env.COOKIE_SECRET; +export const JWT_SECRET = process.env.JWT_SECRET; +export const SES_SMTP_USERNAME = process.env.SES_SMTP_USERNAME; +export const SES_SMTP_PASSWORD = process.env.SES_SMTP_PASSWORD; +export const SES_SMTP_HOST = + process.env.SES_SMTP_HOST || 'email-smtp.us-east-1.amazonaws.com'; +export const SHOW_UPCOMING_CHANGES = + process.env.SHOW_UPCOMING_CHANGES === 'true'; +export const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY; +export const GROWTHBOOK_FASTIFY_API_HOST = + process.env.GROWTHBOOK_FASTIFY_API_HOST; +export const GROWTHBOOK_FASTIFY_CLIENT_KEY = + process.env.GROWTHBOOK_FASTIFY_CLIENT_KEY; +export const SOCRATES_API_KEY = process.env.SOCRATES_API_KEY; +export const SOCRATES_ENDPOINT = process.env.SOCRATES_ENDPOINT; +export const TPA_API_BEARER_TOKEN = process.env.TPA_API_BEARER_TOKEN; +/** Server grace timeout before force closing in-flight requests. */ +export const FCC_DRAIN_TIMEOUT_MS = parseWith( + 'FCC_DRAIN_TIMEOUT_MS', + 20_000, + parseInt +); + +export const DEPLOYMENT_VERSION = process.env.DEPLOYMENT_VERSION || 'unknown'; + +function parseWith( + name: string, + fallback: T, + parserFunction: (str: string) => T +): T { + const str = process.env[name]; + if (str === undefined || str === null || str?.trim() === '') return fallback; + try { + return parserFunction(str); + } catch (e) { + if (e instanceof Error) { + throw new Error(`Failed to parse ${name}: ${e}`); + } + throw new Error(`Unhandled error parsing '${name}'`); + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/error-formatting.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/error-formatting.ts new file mode 100644 index 0000000000000000000000000000000000000000..3c671d0f926c47ff61a6d8e1ae062086fd6cc4e2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/error-formatting.ts @@ -0,0 +1,79 @@ +import { ErrorObject } from 'ajv'; + +type FormattedError = { + type: 'error'; + message: string; +}; + +// TODO(Post-MVP): Normalize error responses (either msg or message, not both) +type CodeRoadError = { + type: 'error'; + msg: string; +}; + +const getError = (errors: ErrorObject[]): ErrorObject => { + // This is a guard against accidentally enabling allErrors in ajv and making + // the server more vulnerable to DOS. + const error = errors[0]; + if (!error || errors.length !== 1) { + throw new Error( + 'Bad Argument: the array of errors must have exactly one element.' + ); + } + return error; +}; + +/** + * Format validation errors for /project-completed. + * + * @param errors An array of validation errors. + * @returns Formatted errors that can be used in the response. + */ +export const formatProjectCompletedValidation = ( + errors: ErrorObject[] +): FormattedError => { + const error = getError(errors); + + // TODO: split this into two functions. There's no need for it to handle both + // /project-completed and /save-challenge + return error.instancePath === '' && + error.params.missingProperty === 'solution' + ? { + type: 'error', + message: + 'You have not provided the valid links for us to inspect your work.' + } + : { + type: 'error', + message: 'That does not appear to be a valid challenge submission.' + }; +}; + +/** + * Format validation errors for /coderoad-challenge-completed. + * + * @param errors An array of validation errors. + * @returns Formatted errors that can be used in the response. + */ +export const formatCoderoadChallengeCompletedValidation = ( + errors: ErrorObject[] +): CodeRoadError => { + const error = getError(errors); + + // TODO(Post-MVP): Return error saying that the body is not an object. + if (error.instancePath === '' && error.message === 'must be object') + return { type: 'error', msg: `'tutorialId' not found in request body` }; + + if ( + error.instancePath === '' && + error.params.missingProperty === 'coderoad-user-token' + ) { + return { + type: 'error', + msg: `'Coderoad-User-Token' not found in request headers` + }; + } else { + // by process of elimination: + return { type: 'error', msg: `'tutorialId' not found in request body` }; + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-schemas.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-schemas.ts new file mode 100644 index 0000000000000000000000000000000000000000..b4861ce54b110d8d4a5a61f3f0766990f1b1fb14 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-schemas.ts @@ -0,0 +1,192 @@ +import { Answer, Exam, Question, ExamResults } from '@prisma/client'; +import Joi from 'joi'; +import { GeneratedExam, UserExam } from './exam-types.js'; + +const nanoIdRE = new RegExp('[a-z0-9]{10}'); +const objectIdRE = new RegExp('^[0-9a-fA-F]{24}$'); + +// Exam from database schema +const DbPrerequisitesJoi = Joi.object().keys({ + id: Joi.string().regex(objectIdRE).required(), + title: Joi.string() +}); + +const DbAnswerJoi = Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + deprecated: Joi.bool().allow(null), + answer: Joi.string().required() +}); + +const DbQuestionJoi = Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + question: Joi.string().required(), + deprecated: Joi.bool().allow(null), + wrongAnswers: Joi.array() + .items(DbAnswerJoi) + .required() + .custom((value: Answer[], helpers) => { + const nonDeprecatedCount = value.reduce( + (count: number, answer: Answer) => + answer.deprecated ? count : count + 1, + 0 + ); + const minimumAnswers = 4; + + if (nonDeprecatedCount < minimumAnswers) { + return helpers.message({ + en: `'wrongAnswers' must have at least ${minimumAnswers} non-deprecated answers.` + }); + } + + return value; + }), + correctAnswers: Joi.array() + .items(DbAnswerJoi) + .required() + .custom((value: Answer[], helpers) => { + const nonDeprecatedCount = value.reduce( + (count: number, answer: Answer) => + answer.deprecated ? count : count + 1, + 0 + ); + const minimumAnswers = 1; + + if (nonDeprecatedCount < minimumAnswers) { + return helpers.message({ + en: `'correctAnswers' must have at least ${minimumAnswers} non-deprecated answer.` + }); + } + + return value; + }) +}); + +const examFromDbSchema = Joi.object().keys({ + // TODO: make sure _id and title match what's in the challenge markdown file + id: Joi.string().regex(objectIdRE).required(), + title: Joi.string().required(), + numberOfQuestionsInExam: Joi.number() + .min(1) + .max( + Joi.ref('questions', { + adjust: (questions: Question[]) => { + const nonDeprecatedCount = questions.reduce( + (count: number, question: Question) => + question.deprecated ? count : count + 1, + 0 + ); + return nonDeprecatedCount; + } + }) + ) + .required(), + passingPercent: Joi.number().min(0).max(100).required(), + prerequisites: Joi.array().items(DbPrerequisitesJoi), + questions: Joi.array().items(DbQuestionJoi).min(1).required() +}); + +/** + * Function to validate the exam data from the database. + * + * @param examFromDb The exam object from the database. + * @returns JOI Validation object. + */ +export const validateExamFromDbSchema = (examFromDb: Exam) => { + return examFromDbSchema.validate(examFromDb); +}; + +// Generated Exam Schema +const GeneratedAnswerJoi = Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + answer: Joi.string().required() +}); + +const GeneratedQuestionJoi = Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + question: Joi.string().required(), + answers: Joi.array().items(GeneratedAnswerJoi).min(5).required() +}); + +const generatedExamSchema = Joi.array() + .items(GeneratedQuestionJoi) + .min(1) + .required(); + +/** + * Function to validate a generated exam. + * + * @param exam The exam that was generated. + * @param numberOfQuestionsInExam The number of questions in the exam. + * @returns JOI Validation object. + */ +export const validateGeneratedExamSchema = ( + exam: GeneratedExam, + numberOfQuestionsInExam: number +) => { + if (exam.length !== numberOfQuestionsInExam) { + throw new Error( + 'The number of exam questions generated does not match the number of questions required.' + ); + } + + return generatedExamSchema.validate(exam); +}; + +// User Completed Exam Schema +const UserCompletedQuestionJoi = Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + question: Joi.string().required(), + answer: Joi.object().keys({ + id: Joi.string().regex(nanoIdRE).required(), + answer: Joi.string().required() + }) +}); + +const userCompletedExamSchema = Joi.object().keys({ + userExamQuestions: Joi.array() + .items(UserCompletedQuestionJoi) + .min(1) + .required(), + examTimeInSeconds: Joi.number().min(0) +}); + +/** + * Function to validate a user completed exam. + * + * @param exam The exam the camper completed. + * @param numberOfQuestionsInExam The number of questions in the exam. + * @returns JOI Validation object. + */ +export const validateUserCompletedExamSchema = ( + exam: UserExam, + numberOfQuestionsInExam: number +) => { + // TODO: Validate that the properties exist + if (exam.userExamQuestions.length !== numberOfQuestionsInExam) { + throw new Error( + 'The number of exam questions answered does not match the number of questions required.' + ); + } + + return userCompletedExamSchema.validate(exam); +}; + +// Exam Results Schema +const examResultsSchema = Joi.object().keys({ + numberOfCorrectAnswers: Joi.number().min(0), + numberOfQuestionsInExam: Joi.number().min(0), + percentCorrect: Joi.number().min(0), + passingPercent: Joi.number().min(0).max(100), + passed: Joi.bool(), + examTimeInSeconds: Joi.number().min(0) +}); + +/** + * Function to validate generated exam results after a camper submits their exam. + * + * @param examResults The exam results that were generated. + * @returns JOI Validation object. + */ +export const validateExamResultsSchema = (examResults: ExamResults) => { + return examResultsSchema.validate(examResults); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-types.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-types.ts new file mode 100644 index 0000000000000000000000000000000000000000..0ef0d4a54393dacbb96ed4ccfbae14389e96cb1b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam-types.ts @@ -0,0 +1,25 @@ +export interface Answer { + id: string; + answer: string; +} + +// types for a generated exam +interface GeneratedQuestion { + id: string; + question: string; + answers: Answer[]; +} + +export type GeneratedExam = GeneratedQuestion[]; + +// types for a user completed exam (from client) +interface UserQuestion { + id: string; + question: string; + answer: Answer; +} + +export interface UserExam { + userExamQuestions: UserQuestion[]; + examTimeInSeconds: number; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5999699de9adf395a6848e878e51080a5466ebe6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect } from 'vitest'; +import { Exam, Question } from '@prisma/client'; +import { + examJson, + examWithZeroCorrect, + examWithOneCorrect, + examWithTwoCorrect, + examWithAllCorrect, + mockResultsZeroCorrect, + mockResultsOneCorrect, + mockResultsTwoCorrect, + mockResultsAllCorrect +} from '../../__fixtures__/exam.js'; +import { generateRandomExam, createExamResults } from './exam.js'; +import { GeneratedExam } from './exam-types.js'; + +describe('Exam helpers', () => { + describe('generateRandomExam()', () => { + const randomizedExam: GeneratedExam = generateRandomExam(examJson as Exam); + + it('should have three questions', () => { + expect(randomizedExam.length).toBe(3); + }); + + it('should have five answers per question', () => { + randomizedExam.forEach(question => { + expect(question.answers.length).toBe(5); + }); + }); + + it('should have exactly one correct answer per question', () => { + randomizedExam.forEach(question => { + const originalQuestion = examJson.questions.find( + q => q.id === question.id + ) as Question; + const originalCorrectAnswer = originalQuestion.correctAnswers; + const correctIds = originalCorrectAnswer.map(a => a.id); + + const numberOfCorrectAnswers = question.answers.filter(a => + correctIds.includes(a.id) + ); + + expect(numberOfCorrectAnswers).toHaveLength(1); + }); + }); + }); + + describe('createExamResults()', () => { + const examResults1 = createExamResults( + examWithZeroCorrect, + examJson as Exam + ); + const examResults2 = createExamResults( + examWithOneCorrect, + examJson as Exam + ); + const examResults3 = createExamResults( + examWithTwoCorrect, + examJson as Exam + ); + const examResults4 = createExamResults( + examWithAllCorrect, + examJson as Exam + ); + + it('failing exam should return correct results', () => { + expect(examResults1).toEqual(mockResultsZeroCorrect); + }); + + it('passing exam should return correct results', () => { + expect(examResults2).toEqual(mockResultsOneCorrect); + expect(examResults3).toEqual(mockResultsTwoCorrect); + expect(examResults4).toEqual(mockResultsAllCorrect); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.ts new file mode 100644 index 0000000000000000000000000000000000000000..7c57e3a92a6d8bb043b58af73323ad69dfb27b68 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/exam.ts @@ -0,0 +1,103 @@ +import { Exam, Question } from '@prisma/client'; +import { shuffleArray } from '@freecodecamp/shared/utils/shuffle-array'; +import { UserExam, GeneratedExam } from './exam-types.js'; + +/** + * Remove objects from array with deprecated: true. + * + * @param arr An array. + * @returns The array without objects that have deprecated: true. + */ +function filterDeprecated( + arr: T[] +): T[] { + return arr.filter(i => !i.deprecated); +} + +function getRandomElement(arr: T[]): T { + const id: number = Math.floor(Math.random() * arr.length); + return arr[id] as T; +} + +/** + * Generates a random exam. + * + * @param examJson Exam from the database converted to JSON. + * @returns An array of randomized questions for the exam. + */ +export function generateRandomExam(examJson: Exam): GeneratedExam { + const { numberOfQuestionsInExam, questions } = examJson; + const numberOfAnswersPerQuestion = 5; + + const availableQuestions = shuffleArray(filterDeprecated(questions)); + const examQuestions = availableQuestions.slice(0, numberOfQuestionsInExam); + + const randomizedExam: GeneratedExam = examQuestions.map( + (question: Question) => { + const availableCorrectAnswers = filterDeprecated(question.correctAnswers); + const availableWrongAnswers = shuffleArray( + filterDeprecated(question.wrongAnswers) + ); + const correctAnswer = getRandomElement(availableCorrectAnswers); + const answers = shuffleArray([ + correctAnswer, + ...availableWrongAnswers.slice(0, numberOfAnswersPerQuestion - 1) + ]).map(({ id, answer }) => ({ id, answer })); + return { + id: question.id, + question: question.question, + answers + }; + } + ); + + return randomizedExam; +} + +/** + * Evaluates a user completed exam. + * + * @param userExam User completed exam. + * @param originalExam Exam from the database converted to JSON. + * @returns An object of the exam results. + */ +export function createExamResults(userExam: UserExam, originalExam: Exam) { + const { userExamQuestions, examTimeInSeconds } = userExam; + const { + questions: originalQuestions, + numberOfQuestionsInExam, + passingPercent + } = originalExam; + + const numberOfCorrectAnswers = userExamQuestions.reduce( + (count, userQuestion) => { + const originalQuestion = originalQuestions.find( + examQuestion => examQuestion.id === userQuestion.id + ); + + if (!originalQuestion) { + throw new Error('An error occurred. Could not find exam question.'); + } + + const isCorrect = originalQuestion.correctAnswers.find( + examAnswer => examAnswer.id === userQuestion.answer.id + ); + return isCorrect ? count + 1 : count; + }, + 0 + ); + + // Percent rounded to one decimal place + const percent = (numberOfCorrectAnswers / numberOfQuestionsInExam) * 100; + const percentCorrect = Math.round(percent * 10) / 10; + const passed = percentCorrect >= passingPercent; + + return { + numberOfCorrectAnswers, + numberOfQuestionsInExam, + percentCorrect, + passingPercent, + passed, + examTimeInSeconds + }; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..030cde3e25ebd953f9d992bc7845596ecb197a8b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.test.ts @@ -0,0 +1,52 @@ +import { describe, test, expect } from 'vitest'; +import { challenges, getChallengeIdsByBlock } from './get-challenges.js'; +import { isObjectID } from './validation.js'; + +describe('challenges as a proxy for getChallenges', () => { + // challenges is assigned the result of getChallenges() so we can save time by using the pre-computed version + test('returns an array of challenges', () => { + expect(Array.isArray(challenges)).toBe(true); + expect(challenges.length).toBeGreaterThan(0); + }); + + test( + 'challenge objects should contain challengeType and id', + { + timeout: 10000 + }, + () => { + for (const challenge of challenges) { + expect(challenge).toHaveProperty('challengeType'); + expect(typeof challenge?.challengeType).toBe('number'); + + expect(challenge).toHaveProperty('id'); + expect(isObjectID(challenge?.id)).toBe(true); + } + } + ); +}); + +describe('getChallengeIdsByBlock', () => { + test('returns challenge IDs for a valid block', () => { + const ids = getChallengeIdsByBlock('responsive-web-design-principles'); + expect(ids).toContain('587d78b0367417b2b2512b08'); + }); + + test('returns a non-empty array of strings', () => { + const ids = getChallengeIdsByBlock('responsive-web-design-principles'); + expect(ids.length).toBeGreaterThan(0); + for (const id of ids) { + expect(typeof id).toBe('string'); + } + }); + + test('returns empty array for non-existent block', () => { + const ids = getChallengeIdsByBlock('non-existent-block'); + expect(ids).toEqual([]); + }); + + test('returns empty array for empty string', () => { + const ids = getChallengeIdsByBlock(''); + expect(ids).toEqual([]); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.ts new file mode 100644 index 0000000000000000000000000000000000000000..420e2353bfbfbc224cd7f16eb8cbbbf06e35abce --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/get-challenges.ts @@ -0,0 +1,101 @@ +// TODO: keeping curriculum in memory is handy if we want to field requests that +// need to 'query' the curriculum, but if we force the client to handle +// redirectToCurrentChallenge and, instead, only report the current challenge id +// via the user object, then we should *not* store this so it can be garbage +// collected. +import { readFileSync } from 'fs'; +import { fileURLToPath } from 'node:url'; +import { join, dirname } from 'path'; + +const CURRICULUM_PATH = '../../../curriculum/generated/curriculum.json'; +const __dirname = dirname(fileURLToPath(import.meta.url)); +// Curriculum is read using fs, because it is too large for VSCode's LSP to handle type inference which causes annoying behavior. +const curriculum = JSON.parse( + readFileSync(join(__dirname, CURRICULUM_PATH), 'utf-8') +) as Curriculum; + +interface Challenge { + id: string; + tests?: { id?: string }[]; + challengeType: number; + url?: string; + msTrophyId?: string; + saveSubmissionToDB?: boolean; + isExam?: boolean; +} + +interface Block { + challenges: Challenge[]; +} + +type SuperBlock = { + blocks: Record; +}; + +type Curriculum = Record; + +/** + * Get all challenges including all certifications as "challenges" (ids and tests). + * @returns The whole curricula reduced to an array. + */ +export function getChallenges(): Challenge[] { + const curricula = Object.values(curriculum); + + return curricula + .map(v => v.blocks) + .reduce((acc: Challenge[], superBlock) => { + const blockKeys = Object.keys(superBlock); + const challengesForBlock = blockKeys.map(k => { + const block = superBlock[k]; + if (!block) { + return []; + } + return block.challenges; + }); + return [...acc, ...challengesForBlock.flat()]; + }, []); +} + +export const challenges = getChallenges(); + +export const savableChallenges = challenges.reduce((acc, curr) => { + if (curr.saveSubmissionToDB) { + acc.add(curr.id); + } + + return acc; +}, new Set()); + +const examChallenges = challenges.reduce((acc, curr) => { + if (curr.isExam) { + acc.add(curr.id); + } + + return acc; +}, new Set()); + +/** + * Checks if a challenge id is an exam challenge. + * + * @param id The challenge id to check. + * @returns A boolean indicating if the challenge id is an exam challenge. + */ +export const isExamId = (id: string): boolean => examChallenges.has(id); + +/** + * Get all challenge IDs for a specific block. + * @param blockId The dashedName of the block. + * @returns An array of challenge IDs for the block, or empty array if block not found. + */ +export function getChallengeIdsByBlock(blockId: string): string[] { + const curricula = Object.values(curriculum); + + for (const superBlock of curricula) { + const block = superBlock.blocks[blockId]; + if (block) { + return block.challenges.map(challenge => challenge.id); + } + } + + return []; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb7cf69bf148be7e2a19aee2cdd2f827c878687a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.test.ts @@ -0,0 +1,88 @@ +import type { FastifyReply, FastifyRequest } from 'fastify'; +import { describe, expect, it, vi } from 'vitest'; + +import { recordHttpMetrics } from './http-metrics.js'; + +const invoke = ({ + method = 'GET', + url = '/users/:id', + matched = true, + statusCode = 200, + elapsedTime = 12.5, + withMetrics = true +} = {}) => { + const count = vi.fn(); + const distribution = vi.fn(); + const done = vi.fn(); + const req = { + method, + routeOptions: matched ? { url } : {}, + server: { + Sentry: withMetrics ? { metrics: { count, distribution } } : {} + } + } as unknown as FastifyRequest; + const reply = { statusCode, elapsedTime } as unknown as FastifyReply; + + recordHttpMetrics(req, reply, done); + + return { count, distribution, done }; +}; + +describe('recordHttpMetrics', () => { + it('counts the response by route pattern, method and status class', () => { + const { count } = invoke({ + method: 'POST', + url: '/users/:id', + statusCode: 201 + }); + + expect(count).toHaveBeenCalledWith('http.response', 1, { + attributes: { route: '/users/:id', method: 'POST', statusClass: '2xx' } + }); + }); + + it('records request duration in milliseconds with the same attributes', () => { + const { distribution } = invoke({ statusCode: 200, elapsedTime: 42 }); + + expect(distribution).toHaveBeenCalledWith('http.request_duration_ms', 42, { + unit: 'millisecond', + attributes: { route: '/users/:id', method: 'GET', statusClass: '2xx' } + }); + }); + + it('derives a 4xx status class from the numeric status code', () => { + expect(invoke({ statusCode: 404 }).count).toHaveBeenCalledWith( + 'http.response', + 1, + { attributes: { route: '/users/:id', method: 'GET', statusClass: '4xx' } } + ); + }); + + it('derives a 5xx status class from the numeric status code', () => { + expect(invoke({ statusCode: 503 }).count).toHaveBeenCalledWith( + 'http.response', + 1, + { attributes: { route: '/users/:id', method: 'GET', statusClass: '5xx' } } + ); + }); + + it('labels an unmatched route rather than emitting an interpolated path', () => { + expect( + invoke({ matched: false, statusCode: 404 }).count + ).toHaveBeenCalledWith('http.response', 1, { + attributes: { route: 'unmatched', method: 'GET', statusClass: '4xx' } + }); + }); + + it('always completes the hook', () => { + expect(invoke().done).toHaveBeenCalledOnce(); + }); + + it('does not throw and still completes when metrics are unavailable', () => { + const { count, distribution, done } = invoke({ withMetrics: false }); + + expect(count).not.toHaveBeenCalled(); + expect(distribution).not.toHaveBeenCalled(); + expect(done).toHaveBeenCalledOnce(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.ts new file mode 100644 index 0000000000000000000000000000000000000000..075f0740fa0e1dcc6b7e3f448140fe2fce136b0a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/http-metrics.ts @@ -0,0 +1,27 @@ +import type { + FastifyReply, + FastifyRequest, + HookHandlerDoneFunction +} from 'fastify'; + +// eslint-disable-next-line jsdoc/require-jsdoc +export const recordHttpMetrics = ( + req: FastifyRequest, + reply: FastifyReply, + done: HookHandlerDoneFunction +): void => { + const metrics = req.server.Sentry?.metrics; + if (metrics) { + const attributes = { + route: req.routeOptions?.url ?? 'unmatched', + method: req.method, + statusClass: `${Math.floor(reply.statusCode / 100)}xx` + }; + metrics.count('http.response', 1, { attributes }); + metrics.distribution('http.request_duration_ms', reply.elapsedTime, { + unit: 'millisecond', + attributes + }); + } + done(); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/ids.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/ids.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e63a2a3a9d91a1d7cb312113c90f05f8044cfd0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/ids.ts @@ -0,0 +1,7 @@ +import { customAlphabet } from 'nanoid'; + +// uppercase, lowercase letters and numbers +export const customNanoid = customAlphabet( + '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + 64 +); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4eb946a4e436c5f0d0b02fbfd96147a20ff4c209 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.test.ts @@ -0,0 +1,16 @@ +import { describe, test, expect } from 'vitest'; +import { base64URLEncode, challenge, verifier } from './index.js'; + +describe('utils', () => { + test('base64URLEncode', () => { + expect(base64URLEncode(Buffer.from('test'))).toEqual('dGVzdA'); + }); + + test('verifier', () => { + expect(verifier).toHaveLength(43); + }); + + test('challenge', () => { + expect(challenge).toHaveLength(43); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..f7a9008494bdbc7c3e7de9aebbe51775cbb50314 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/index.ts @@ -0,0 +1,128 @@ +import { randomBytes, createHash } from 'crypto'; +import { type TypeBoxTypeProvider } from '@fastify/type-provider-typebox'; +import { + ContextConfigDefault, + FastifyReply, + RawReplyDefaultExpression, + type FastifyRequest, + type FastifySchema, + type RawRequestDefaultExpression, + type RawServerDefault, + type RouteGenericInterface +} from 'fastify'; + +/** + * Utility to encode a buffer to a base64 URI. + * + * @param buf The buffer to encode. + * @returns The encoded string. + */ +export function base64URLEncode(buf: Buffer): string { + return buf + .toString('base64') + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=/g, ''); +} +export const verifier = base64URLEncode(randomBytes(32)); + +function sha256(buf: Buffer) { + return createHash('sha256').update(buf).digest(); +} +export const challenge = base64URLEncode(sha256(Buffer.from(verifier))); + +export type UpdateReqType = FastifyRequest< + RouteGenericInterface, + RawServerDefault, + RawRequestDefaultExpression, + Schema, + TypeBoxTypeProvider +>; + +export type UpdateReplyType = FastifyReply< + RouteGenericInterface, + RawServerDefault, + RawRequestDefaultExpression, + RawReplyDefaultExpression, + ContextConfigDefault, + Schema, + TypeBoxTypeProvider +>; + +/* eslint-disable jsdoc/require-description-complete-sentence */ +/** + * Wrapper around a promise to catch errors and return them as part of the promise. + * + * This is most useful to prevent callback / try...catch hell. + * + * ## Example: + * + * ```ts + * const maybeExam = await mapErr( + * this.prisma.examEnvironmentExam.findUnique({ where: { id: examId } }) + * ); + * + * if (maybeExam.hasError) { + * if (maybeExam.error instanceof PrismaClientValidationError) { + * void reply.code(400); + * return reply.send(ERRORS.FCC_EINVAL_EXAM_ID(maybeExam.error.message)); + * } + * + * this.Sentry?.captureException(maybeExam.error); + * void reply.code(500); + * return reply.send( + * ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeExam.error)) + * ); + * } + * + * const exam = maybeExam.data; + * ``` + * + * @param promise - any promise to be tried. + * @returns a promise with either the data or the caught error + */ +export async function mapErr(promise: Promise): Promise> { + try { + return { hasError: false, data: await promise }; + } catch (error) { + return { hasError: true, error }; + } +} + +/** + * Wrapper around a synchronise function to catch throws and return them as part of the value. + * + * This is most useful to prevent try...catch hell. + * + * ## Example: + * + * ```ts + * const maybeUserExam = syncMapErr(() => + * constructUserExam(generatedExam, exam) + * ); + * + * if (maybeUserExam.hasError) { + * this.Sentry?.captureException(maybeUserExam.error); + * void reply.code(500); + * return reply.send( + * ERRORS.FCC_ERR_EXAM_ENVIRONMENT(JSON.stringify(maybeUserExam.error)) + * ); + * } + * + * const userExam = maybeUserExam.data; + * ``` + * + * @param fn - any function to be tried. + * @returns the data or the caught error + */ +export function syncMapErr(fn: () => T): Result { + try { + return { hasError: false, data: fn() }; + } catch (error) { + return { hasError: true, error }; + } +} + +export type Result = + | { hasError: false; data: T } + | { hasError: true; error: unknown }; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ab91877ee397f1ab813f2b1344becda6216c98ab --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.test.ts @@ -0,0 +1,312 @@ +import { Writable } from 'stream'; +import { pino, type Logger } from 'pino'; +import { describe, it, expect } from 'vitest'; +import Fastify, { type FastifyReply, type FastifyRequest } from 'fastify'; + +import { + bindRouteToLogger, + genReqId, + getLoggerOptions, + serializers +} from './logger.js'; + +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +const fakeRequest = (overrides: { + headers?: Record; + query?: unknown; + id?: string; + ip?: string; + url?: string; + routeUrl?: string; +}): FastifyRequest => + ({ + id: overrides.id ?? 'req-1', + method: 'GET', + url: overrides.url ?? '/status/ping', + ip: overrides.ip ?? '127.0.0.1', + headers: overrides.headers ?? {}, + query: overrides.query ?? {}, + routeOptions: { url: overrides.routeUrl } + }) as unknown as FastifyRequest; + +describe('serializers.req', () => { + it('emits lowercase camelCase keys', () => { + const result = serializers.req( + fakeRequest({ + headers: { + 'user-agent': 'vitest', + 'cf-ipcountry': 'NL' + }, + query: { page: '2' } + }) + ); + + expect(result).toEqual({ + method: 'GET', + url: '/status/ping', + ip: '127.0.0.1', + userAgent: 'vitest', + country: 'NL', + query: { page: '2' } + }); + }); + + it('prefers cf-connecting-ip over other ip sources', () => { + const result = serializers.req( + fakeRequest({ + headers: { + 'cf-connecting-ip': '1.1.1.1', + 'x-forwarded-for': '2.2.2.2', + 'x-real-ip': '3.3.3.3' + } + }) + ); + expect(result.ip).toBe('1.1.1.1'); + }); + + it('uses the first x-forwarded-for value when it is an array', () => { + const result = serializers.req( + fakeRequest({ + headers: { 'x-forwarded-for': ['2.2.2.2', '9.9.9.9'] } + }) + ); + expect(result.ip).toBe('2.2.2.2'); + }); + + it('uses the first hop of a comma-separated x-forwarded-for chain', () => { + const result = serializers.req( + fakeRequest({ + headers: { 'x-forwarded-for': '2.2.2.2, 10.0.0.1, 172.16.0.1' } + }) + ); + expect(result.ip).toBe('2.2.2.2'); + }); + + it('falls back to req.ip when no proxy headers are present', () => { + const result = serializers.req(fakeRequest({ ip: '10.0.0.5' })); + expect(result.ip).toBe('10.0.0.5'); + }); + + it('omits the query property when the query is empty', () => { + const result = serializers.req(fakeRequest({ query: {} })); + expect(result).not.toHaveProperty('query'); + }); + + it('strips the query string from the logged url', () => { + const result = serializers.req( + fakeRequest({ url: '/status/ping?token=supersecret&page=1' }) + ); + expect(result.url).toBe('/status/ping'); + expect(JSON.stringify(result)).not.toContain('supersecret'); + }); + + it('includes the templated route pattern when resolved', () => { + const result = serializers.req( + fakeRequest({ url: '/users/abc123', routeUrl: '/users/:id' }) + ); + expect(result.route).toBe('/users/:id'); + }); + + it('omits the route property when no route matched', () => { + const result = serializers.req(fakeRequest({})); + expect(result).not.toHaveProperty('route'); + }); +}); + +describe('serializers.res', () => { + it('emits only statusCode', () => { + const result = serializers.res({ + statusCode: 200, + elapsedTime: 12.5 + } as unknown as FastifyReply); + + expect(result).toEqual({ statusCode: 200 }); + }); +}); + +describe('serializers.err', () => { + it('whitelists safe fields and drops secret/payment payloads', () => { + const stripeErr = Object.assign(new Error('Your card was declined.'), { + code: 'card_declined', + statusCode: 402, + requestId: 'req_123', + raw: { payment_intent: { client_secret: 'pi_secret_LEAK' } }, + headers: { authorization: 'Bearer sk_live_LEAK' }, + payment_method: { card: { number: '4242424242424242' } } + }); + + const result = serializers.err(stripeErr); + + expect(result).toMatchObject({ + type: 'Error', + message: 'Your card was declined.', + code: 'card_declined', + statusCode: 402, + requestId: 'req_123' + }); + expect(result).not.toHaveProperty('raw'); + expect(result).not.toHaveProperty('headers'); + expect(result).not.toHaveProperty('payment_method'); + const serialized = JSON.stringify(result); + expect(serialized).not.toContain('pi_secret_LEAK'); + expect(serialized).not.toContain('sk_live_LEAK'); + expect(serialized).not.toContain('4242424242424242'); + }); + + it('recursively whitelists the cause chain', () => { + const cause = Object.assign(new Error('inner'), { + raw: { client_secret: 'cause_LEAK' } + }); + const err = Object.assign(new Error('outer'), { cause }); + + const result = serializers.err(err); + + expect(JSON.stringify(result)).not.toContain('cause_LEAK'); + expect((result.cause as { message: string }).message).toBe('inner'); + }); + + it('handles non-object errors', () => { + expect(serializers.err('boom')).toEqual({ message: 'boom' }); + }); +}); + +describe('bindRouteToLogger', () => { + it('binds the matched route onto request logs', async () => { + const lines: string[] = []; + const sink = new Writable({ + write(chunk: Buffer, _enc, cb) { + lines.push(chunk.toString()); + cb(); + } + }); + const app = Fastify({ + loggerInstance: pino(getLoggerOptions('info'), sink) + }); + app.addHook('onRequest', bindRouteToLogger); + app.get('/widgets/:id', () => ({ ok: true })); + + await app.inject({ method: 'GET', url: '/widgets/42' }); + await app.close(); + + const completed = lines + .map(line => JSON.parse(line) as Record) + .find(entry => entry.msg === 'request completed'); + expect(completed?.route).toBe('/widgets/:id'); + }); +}); + +describe('genReqId', () => { + it('passes through a valid cf-ray header', () => { + expect(genReqId({ headers: { 'cf-ray': 'abc-123_DEF' } })).toBe( + 'abc-123_DEF' + ); + }); + + it('uses the first value of an array header', () => { + expect(genReqId({ headers: { 'cf-ray': ['first', 'second'] } })).toBe( + 'first' + ); + }); + + it('ignores a client-supplied x-request-id', () => { + expect(genReqId({ headers: { 'x-request-id': 'client-spoofed' } })).toMatch( + UUID_PATTERN + ); + }); + + it('generates a uuid when the header is missing', () => { + expect(genReqId({ headers: {} })).toMatch(UUID_PATTERN); + }); + + it('rejects headers longer than 64 characters', () => { + expect(genReqId({ headers: { 'cf-ray': 'a'.repeat(65) } })).toMatch( + UUID_PATTERN + ); + }); + + it('rejects headers with characters outside [A-Za-z0-9_-]', () => { + for (const dirty of ['abc def', 'abc\ndef', 'abc"def', 'abc{def']) { + expect(genReqId({ headers: { 'cf-ray': dirty } })).toMatch(UUID_PATTERN); + } + }); +}); + +describe('getLoggerOptions', () => { + const captureLog = (write: (logger: Logger) => void): string => { + const lines: string[] = []; + const sink = new Writable({ + write(chunk: Buffer, _enc, cb) { + lines.push(chunk.toString()); + cb(); + } + }); + const logger = pino(getLoggerOptions('info'), sink); + write(logger); + return lines.join(''); + }; + + it('sets the requested level', () => { + expect(getLoggerOptions('warn').level).toBe('warn'); + }); + + it('redacts sensitive query parameters in serialized requests', () => { + const output = captureLog(logger => + logger.info( + { + req: fakeRequest({ + query: { token: 'super-secret', page: '1' } + }) + }, + 'incoming request' + ) + ); + + const parsed = JSON.parse(output) as { + req: { query: { token: string; page: string } }; + }; + expect(parsed.req.query.token).toBe('[REDACTED]'); + expect(parsed.req.query.page).toBe('1'); + }); + + it('redacts oauth state and id_token query parameters', () => { + const output = captureLog(logger => + logger.info( + { + req: fakeRequest({ + query: { state: 'csrf-state', id_token: 'jwt-secret', page: '1' } + }) + }, + 'incoming request' + ) + ); + + const parsed = JSON.parse(output) as { + req: { query: { state: string; id_token: string; page: string } }; + }; + expect(parsed.req.query.state).toBe('[REDACTED]'); + expect(parsed.req.query.id_token).toBe('[REDACTED]'); + expect(parsed.req.query.page).toBe('1'); + }); + + it('exposes a mixin that is safe to call without an active Sentry span', () => { + const { mixin } = getLoggerOptions('info'); + expect(mixin).toBeTypeOf('function'); + expect(mixin!({}, 30, pino({ level: 'info' }))).toEqual({}); + }); + + it('serializes req with the standard lowercase shape in log output', () => { + const output = captureLog(logger => + logger.info( + { req: fakeRequest({ headers: { 'user-agent': 'vitest' } }) }, + 'incoming request' + ) + ); + + const parsed = JSON.parse(output) as { req: Record }; + expect(parsed.req.method).toBe('GET'); + expect(parsed.req.url).toBe('/status/ping'); + expect(parsed.req).not.toHaveProperty('REQ_METHOD'); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3c6f3293e84a144056387fee4b3c95fecfb7364 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/logger.ts @@ -0,0 +1,174 @@ +import { randomUUID } from 'crypto'; +import * as Sentry from '@sentry/node'; +import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify'; +import { isEmpty } from 'lodash-es'; +import type { Logger, LoggerOptions } from 'pino'; +import { pino } from 'pino'; + +import { FCC_API_LOG_LEVEL, FCC_API_LOG_TRANSPORT } from './env.js'; + +const firstValue = ( + value: string | string[] | undefined +): string | undefined => (Array.isArray(value) ? value[0] : value); + +const firstHop = (value: string | string[] | undefined): string | undefined => + firstValue(value)?.split(',')[0]?.trim(); + +const clientIp = (req: FastifyRequest): string | undefined => + firstValue(req.headers['cf-connecting-ip']) ?? + firstHop(req.headers['x-forwarded-for']) ?? + firstValue(req.headers['x-real-ip']) ?? + req.ip; + +/** + * Extract the client IP and country from proxy headers for fraud triage. + * + * @param req The incoming request. + * @returns The client IP and ISO country code, when present. + */ +export const clientNetInfo = ( + req: FastifyRequest +): { ip: string | undefined; country: string | undefined } => ({ + ip: clientIp(req), + country: firstValue(req.headers['cf-ipcountry']) +}); + +type SerializedRequest = { + method: string; + url: string; + route?: string; + ip: string | undefined; + userAgent: string | undefined; + country: string | undefined; + query?: unknown; +}; + +const errSerializer = (err: unknown, depth = 0): Record => { + if (typeof err !== 'object' || err === null) return { message: String(err) }; + const e = err as Record; + const safe: Record = { + type: (e.constructor as { name?: string } | undefined)?.name ?? e.name, + message: e.message, + stack: e.stack + }; + for (const key of ['code', 'statusCode', 'requestId'] as const) { + if (e[key] !== undefined) safe[key] = e[key]; + } + if (depth < 3 && e.cause != null) + safe.cause = errSerializer(e.cause, depth + 1); + return safe; +}; + +export const serializers = { + req: (req: FastifyRequest): SerializedRequest => ({ + method: req.method, + url: req.url.split('?')[0] ?? req.url, + ...(req.routeOptions?.url ? { route: req.routeOptions.url } : {}), + ip: clientIp(req), + userAgent: firstValue(req.headers['user-agent']), + country: firstValue(req.headers['cf-ipcountry']), + ...(isEmpty(req.query) ? {} : { query: req.query }) + }), + res: (reply: FastifyReply): { statusCode: number } => ({ + statusCode: reply.statusCode + }), + err: errSerializer +}; + +const REQUEST_ID_PATTERN = /^[\w-]{1,64}$/; + +/** + * Generate a request id, preferring the Cloudflare edge ray id. A + * client-supplied x-request-id is not trusted (spoofable / collidable). + * + * @param req The incoming request. + * @returns The edge-set ray id when valid, otherwise a random UUID. + */ +export const genReqId = (req: { + headers: Record; +}): string => { + const edgeId = firstValue(req.headers['cf-ray']); + return edgeId && REQUEST_ID_PATTERN.test(edgeId) ? edgeId : randomUUID(); +}; + +const SENSITIVE_QUERY_PARAMS = [ + 'token', + 'email', + 'code', + 'key', + 'state', + 'id_token', + 'access_token', + 'refresh_token', + 'password', + 'secret', + 'authorization' +]; + +/** + * Build the pino options shared by all logger instances. + * + * @param level The minimum log level. + * @returns The pino logger options. + */ +export const getLoggerOptions = (level: string): LoggerOptions => ({ + level, + serializers, + mixin: () => { + const spanContext = Sentry.getActiveSpan()?.spanContext(); + if (!spanContext) return {}; + return { + traceId: spanContext.traceId, + traceSampled: (spanContext.traceFlags & 0x1) === 1 + }; + }, + redact: { + paths: SENSITIVE_QUERY_PARAMS.map(param => `req.query.${param}`), + censor: '[REDACTED]' + } +}); + +/** + * Bind the matched route onto the request logger so per-route policies apply. + * + * @param req The incoming request. + * @param reply The reply whose logger is rebound alongside the request logger. + * @param done The hook completion callback. + */ +export const bindRouteToLogger = ( + req: FastifyRequest, + reply: FastifyReply, + done: HookHandlerDoneFunction +): void => { + const route = req.routeOptions?.url; + if (route) { + req.log = reply.log = req.log.child({ route }); + } + done(); +}; + +/** + * Get a logger instance. + * + * @returns A logger instance. + */ +export const getLogger = (): Logger => { + const options = getLoggerOptions(FCC_API_LOG_LEVEL || 'info'); + + if (FCC_API_LOG_TRANSPORT === 'pretty') { + return pino({ + ...options, + transport: { + target: 'pino-pretty', + options: { + singleLine: true, + translateTime: 'HH:MM:ss Z', + ignore: 'pid,hostname', + colorize: true + } + } + }); + } + + return pino(options); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..d2331003dc992772aabcb27b8bfbdf65efff48dc --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.test.ts @@ -0,0 +1,220 @@ +import { describe, test, expect } from 'vitest'; +import { + normalizeTwitter, + normalizeBluesky, + normalizeProfileUI, + normalizeChallenges, + normalizeFlags, + normalizeDate, + normalizeChallengeType +} from './normalize.js'; + +describe('normalize', () => { + describe('normalizeTwitter', () => { + test('returns the input if it is a url', () => { + const url = 'https://x.com/a_generic_user'; + expect(normalizeTwitter(url)).toEqual(url); + }); + test('adds the handle to x.com if it is not a url', () => { + const handle = '@a_generic_user'; + expect(normalizeTwitter(handle)).toEqual('https://x.com/a_generic_user'); + }); + test('returns undefined if that is the input', () => { + expect(normalizeTwitter('')).toBeUndefined(); + }); + }); + + describe('normalizeBluesky', () => { + test('returns the input if it is a url', () => { + const url = 'https://bsky.app/profile/a_generic_user'; + expect(normalizeBluesky(url)).toEqual(url); + }); + test('adds the handle to bsky.app if it is not a url', () => { + const handle = '@a_generic_user'; + expect(normalizeBluesky(handle)).toEqual( + 'https://bsky.app/profile/a_generic_user' + ); + }); + test('returns undefined if that is the input', () => { + expect(normalizeBluesky('')).toBeUndefined(); + }); + }); + + const profileUIInput = { + isLocked: true, + showAbout: true, + showCerts: true, + showDonation: true, + showHeatMap: true, + showLocation: true, + showName: true, + showPoints: true, + showPortfolio: true, + showTimeLine: true, + showExperience: true + }; + + const defaultProfileUI = { + isLocked: true, + showAbout: false, + showCerts: false, + showDonation: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false, + showExperience: false + }; + + describe('normalizeProfileUI', () => { + test('should return the input if it is not null', () => { + expect(normalizeProfileUI(profileUIInput)).toEqual(profileUIInput); + }); + + test('should return the default profileUI if the input is null', () => { + const input = null; + expect(normalizeProfileUI(input)).toEqual(defaultProfileUI); + }); + + test('should convert all "null" values to "false"', () => { + const input = { + isLocked: null, + showAbout: false, + showCerts: null, + showDonation: null, + showHeatMap: null, + showLocation: null, + showName: null, + showPoints: null, + showPortfolio: null, + showTimeLine: null, + showExperience: null + }; + expect(normalizeProfileUI(input)).toEqual({ + isLocked: false, + showAbout: false, + showCerts: false, + showDonation: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false, + showExperience: false + }); + }); + }); + + describe('normalizeChallenges', () => { + test('should remove null values from the input', () => { + const completedChallenges = [ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + challengeType: 5, + solution: null, + githubLink: null, + isManuallyApproved: null, + examResults: null, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2', + path: null + } + ] + } + ]; + expect(normalizeChallenges(completedChallenges)).toEqual([ + { + id: 'a6b0bb188d873cb2c8729495', + completedDate: 1520002973119, + challengeType: 5, + files: [ + { + contents: 'test', + ext: 'js', + key: 'indexjs', + name: 'test', + path: 'path-test' + }, + { + contents: 'test2', + ext: 'html', + key: 'html-test', + name: 'test2' + } + ] + } + ]); + }); + }); + + describe('normalizeFlags', () => { + test('should replace nulls with false', () => { + const flags = { + isLocked: null, + showAbout: false, + showCerts: true, + showDonation: null + }; + expect(normalizeFlags(flags)).toEqual({ + isLocked: false, + showAbout: false, + showCerts: true, + showDonation: false + }); + }); + }); + + describe('normalizeDate', () => { + test('should return the date as a number', () => { + expect(normalizeDate(1)).toEqual(1); + expect(normalizeDate({ $date: '2023-10-01T00:00:00Z' })).toEqual( + 1696118400000 + ); + }); + + test('should throw an error if the date is not in the expected shape', () => { + expect(() => normalizeDate('2023-10-01T00:00:00Z')).toThrow( + 'Unexpected date value: "2023-10-01T00:00:00Z"' + ); + expect(() => normalizeDate({ date: '123' })).toThrow( + 'Unexpected date value: {"date":"123"}' + ); + }); + + test('should handle string numbers', () => { + expect(normalizeDate('1696118400000')).toEqual(1696118400000); + }); + }); + + describe('normalizeChallengeType', () => { + test('should return the challenge type as a number or null', () => { + expect(normalizeChallengeType(10)).toEqual(10); + expect(normalizeChallengeType('10')).toEqual(10); + expect(normalizeChallengeType(null)).toEqual(null); + }); + + test('should throw an error if the challenge type is not in the expected shape', () => { + expect(() => normalizeChallengeType('invalid')).toThrow( + 'Unexpected challengeType value: "invalid"' + ); + expect(() => normalizeChallengeType({ type: '123' })).toThrow( + 'Unexpected challengeType value: {"type":"123"}' + ); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f9dc14fa36f122b2fe31503e342a9706d06d119 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/normalize.ts @@ -0,0 +1,236 @@ +/* This module's job is to parse the database output and prepare it for +serialization */ +import type { + ProfileUI, + CompletedChallenge, + ExamResults, + Survey, + Prisma +} from '@prisma/client'; +import { pickBy, mapValues } from 'lodash-es'; + +type NullToUndefined = T extends null ? undefined : T; +type NullToFalse = T extends null ? false : T; + +export type NoNullProperties = { + [P in keyof T]: NullToUndefined; +}; + +type DefaultToFalse = { + [P in keyof T]: NullToFalse; +}; + +/** + * Converts a Twitter handle or URL to a URL. + * + * @param handleOrUrl Twitter handle or URL. + * @returns Twitter URL. + */ +export const normalizeTwitter = ( + handleOrUrl: string | null +): string | undefined => { + if (!handleOrUrl) return undefined; + + let url; + try { + new URL(handleOrUrl); + } catch { + url = `https://x.com/${handleOrUrl.replace(/^@/, '')}`; + } + return url ?? handleOrUrl; +}; + +/** + * Converts a Bluesky handle or URL to a URL. + * + * @param handleOrUrl Bluesky handle or URL. + * @returns Bluesky URL. + */ +export const normalizeBluesky = ( + handleOrUrl: string | null +): string | undefined => { + if (!handleOrUrl) return undefined; + + let url; + try { + new URL(handleOrUrl); + } catch { + url = `https://bsky.app/profile/${handleOrUrl.replace(/^@/, '')}`; + } + return url ?? handleOrUrl; +}; + +/** + * Normalizes a date value to a timestamp number. + * + * @param date An object with a $date string or a number. + * @returns The date as a timestamp number. + */ +export const normalizeDate = (date?: Prisma.JsonValue): number => { + if (typeof date === 'number') { + return date; + } else if ( + date && + typeof date === 'object' && + '$date' in date && + typeof date.$date === 'string' + ) { + return new Date(date.$date).getTime(); + } else if (typeof date === 'string') { + const parsed = Number(date); + if (!isNaN(parsed)) { + // Number() handles invalid strings e.g. '2023-10-01T00:00:00Z' + // parseInt() handles floats + return parseInt(String(parsed)); + } + } + + throw Error('Unexpected date value: ' + JSON.stringify(date)); +}; + +/** + * Normalizes a challenge type value to a number. + * + * @param challengeType A JSON value that can be a number, string, or null. + * @returns The challenge type as a number or null. + */ +export const normalizeChallengeType = ( + challengeType?: Prisma.JsonValue +): number | null => { + if (typeof challengeType === 'number') { + return challengeType; + } else if (typeof challengeType === 'string') { + const parsed = parseInt(challengeType, 10); + if (isNaN(parsed)) { + throw Error( + 'Unexpected challengeType value: ' + JSON.stringify(challengeType) + ); + } + return parsed; + } else if (challengeType === null) { + return null; + } else { + throw Error( + 'Unexpected challengeType value: ' + JSON.stringify(challengeType) + ); + } +}; + +/** + * Ensure that the user's profile UI settings are valid. + * + * @param maybeProfileUI A null or the user's profile UI settings. + * @returns The input with nulls removed or a default value if there is no input. + */ +export const normalizeProfileUI = ( + maybeProfileUI: ProfileUI | null +): DefaultToFalse => { + return maybeProfileUI + ? normalizeFlags(maybeProfileUI) + : { + isLocked: true, + showAbout: false, + showCerts: false, + showDonation: false, + showHeatMap: false, + showLocation: false, + showName: false, + showPoints: false, + showPortfolio: false, + showTimeLine: false, + showExperience: false + }; +}; + +/** + * Remove all the null properties from an object. + * + * @param obj Any object. + * @returns The input with nulls removed. + */ +export const removeNulls = >( + obj: T +): NoNullProperties => + pickBy(obj, value => value !== null) as NoNullProperties; + +type NormalizedFile = { + contents: string; + ext: string; + key: string; + name: string; + path?: string; +}; + +export type NormalizedChallenge = { + challengeType?: number; + completedDate: number; + files: NormalizedFile[]; + githubLink?: string; + id: string; + isManuallyApproved?: boolean; + solution?: string; + examResults?: ExamResults; +}; + +/** + * Remove all the null properties from a CompletedChallenge array. + * + * @param completedChallenges The CompletedChallenge array. + * @returns The input with nulls removed. + */ +export const normalizeChallenges = ( + completedChallenges: CompletedChallenge[] +): NormalizedChallenge[] => { + const fixedDateAndType = completedChallenges.map(challenge => { + const { completedDate, challengeType, ...rest } = challenge; + return { + ...rest, + completedDate: normalizeDate(completedDate), + challengeType: normalizeChallengeType(challengeType) + }; + }); + + const noNullProps = fixedDateAndType.map(challenge => removeNulls(challenge)); + // files.path is optional + const noNullPath = noNullProps.map(challenge => { + const { files, ...rest } = challenge; + const noNullFiles = files?.map(file => removeNulls(file)); + + return { ...rest, files: noNullFiles }; + }); + + return noNullPath; +}; + +type NormalizedSurvey = { + title: string; + responses: { + question: string; + response: string; + }[]; +}; + +/** + * Remove the extra properties from the SurveyResults array. + * + * @param surveyResults The SurveyResults array. + * @returns The input without the id and userid. + */ +export const normalizeSurveys = ( + surveyResults: Survey[] +): NormalizedSurvey[] => { + return surveyResults.map(survey => { + const { title, responses } = survey; + return { title, responses }; + }); +}; + +/** + * Replace null flags with false. + * @param flags Object with nullable boolean flags. + * @returns Same object with boolean flags, defaulting to false. + */ +export const normalizeFlags = >( + flags: T +): DefaultToFalse => + mapValues(flags, flag => flag ?? false) as DefaultToFalse; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f3b4cc072e0ddb28f0426954b975bc26db98b84 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.test.ts @@ -0,0 +1,40 @@ +import { describe, test, expect } from 'vitest'; +import { getCalendar, getPoints } from './progress.js'; + +describe('utils/progress', () => { + describe('getCalendar', () => { + test('should return an empty object if no timestamps are passed', () => { + expect(getCalendar([])).toEqual({}); + expect(getCalendar(null)).toEqual({}); + }); + test('should take timestamps and return a calendar object', () => { + const timestamps = [-1111001, 0, 1111000, 1111500, 1113000, 9999999]; + + expect(getCalendar(timestamps)).toEqual({ + '-1112': 1, + 0: 1, + 1111: 1, + 1113: 1, + 9999: 1 + }); + }); + + test('should handle null, { timestamp: number } and float entries', () => { + const timestamps = [null, { timestamp: 1113000 }, 1111000.5]; + + expect(getCalendar(timestamps)).toEqual({ + 1111: 1, + 1113: 1 + }); + }); + }); + + describe('getPoints', () => { + test('should return 1 if there are no progressTimestamps', () => { + expect(getPoints(null)).toEqual(1); + }); + test('should return then number of progressTimestamps if there are any', () => { + expect(getPoints([0, 1, 2])).toEqual(3); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.ts new file mode 100644 index 0000000000000000000000000000000000000000..009415a2a74ae1ce3ceb0b5ce348ee3d33c082fa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/progress.ts @@ -0,0 +1,36 @@ +export type ProgressTimestamp = number | { timestamp: number } | null; +export type Calendar = Record; +/** + * Converts a ProgressTimestamp array to a object with keys based on the timestamps. + * + * @param progressTimestamps The ProgressTimestamp array. + * @returns The object with keys based on the timestamps. + */ +export const getCalendar = ( + progressTimestamps: ProgressTimestamp[] | null +): Calendar => { + const calendar: Calendar = {}; + + progressTimestamps?.forEach(progress => { + if (progress === null) return; + if (typeof progress === 'number') { + calendar[Math.floor(progress / 1000)] = 1; + } else { + calendar[Math.floor(progress.timestamp / 1000)] = 1; + } + }); + + return calendar; +}; + +/** + * Converts a ProgressTimestamp array to an integer number of points. + * + * @param progressTimestamps The ProgressTimestamp array. + * @returns The number of points. + */ +export const getPoints = ( + progressTimestamps: ProgressTimestamp[] | null +): number => { + return progressTimestamps?.length ?? 1; +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1b9380ab690048e1d794d8c4fca4bb7883b8f428 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.test.ts @@ -0,0 +1,263 @@ +import { describe, test, expect, vi } from 'vitest'; +import jwt from 'jsonwebtoken'; + +import { + getReturnTo, + normalizeParams, + getRedirectParams, + getPrefixedLandingPath, + getLoginRedirectParams +} from './redirection.js'; +import { HOME_LOCATION } from './env.js'; + +const validJWTSecret = 'this is a super secret string'; +const invalidJWTSecret = 'This is not correct secret'; +const validReturnTo = 'https://www.freecodecamp.org/settings'; +const invalidReturnTo = 'https://www.freecodecamp.org.fake/settings'; +const defaultReturnTo = 'https://www.freecodecamp.org/learn'; +const defaultOrigin = 'https://www.freecodecamp.org'; +const defaultPrefix = ''; + +const defaultObject = { + returnTo: defaultReturnTo, + origin: defaultOrigin, + pathPrefix: defaultPrefix +}; + +// TODO: tidy this up (the mocking is a bit of a mess) +describe('redirection', () => { + describe('getReturnTo', () => { + test('should extract returnTo from a jwt', () => { + expect.assertions(1); + + const encryptedReturnTo = jwt.sign( + { returnTo: validReturnTo, origin: defaultOrigin }, + validJWTSecret + ); + expect( + getReturnTo(encryptedReturnTo, validJWTSecret, defaultOrigin) + ).toStrictEqual({ + ...defaultObject, + returnTo: validReturnTo + }); + }); + + test('should return a default url if the secrets do not match', () => { + const oldLog = console.log; + expect.assertions(2); + console.log = vi.fn(); + const encryptedReturnTo = jwt.sign( + { returnTo: validReturnTo }, + invalidJWTSecret + ); + expect( + getReturnTo(encryptedReturnTo, validJWTSecret, defaultOrigin) + ).toStrictEqual(defaultObject); + expect(console.log).not.toHaveBeenCalled(); + console.log = oldLog; + }); + + test('should return a default url for unknown origins', () => { + expect.assertions(1); + const encryptedReturnTo = jwt.sign( + { returnTo: invalidReturnTo }, + validJWTSecret + ); + expect( + getReturnTo(encryptedReturnTo, validJWTSecret, defaultOrigin) + ).toStrictEqual(defaultObject); + }); + }); + describe('normalizeParams', () => { + test('should return a {returnTo, origin, pathPrefix} object', () => { + expect.assertions(2); + const keys = Object.keys(normalizeParams({})); + const expectedKeys = ['returnTo', 'origin', 'pathPrefix']; + expect(keys.length).toBe(3); + expect(keys).toEqual(expect.arrayContaining(expectedKeys)); + }); + test('should default to process.env.HOME_LOCATION', () => { + expect.assertions(1); + expect(normalizeParams({}, defaultOrigin)).toEqual(defaultObject); + }); + test('should convert an unknown pathPrefix to ""', () => { + expect.assertions(1); + const brokenPrefix = { + ...defaultObject, + pathPrefix: 'not-really-a-name' + }; + expect(normalizeParams(brokenPrefix, defaultOrigin)).toEqual( + defaultObject + ); + }); + test('should not change a known pathPrefix', () => { + expect.assertions(1); + const spanishPrefix = { + ...defaultObject, + pathPrefix: 'espanol' + }; + expect(normalizeParams(spanishPrefix, defaultOrigin)).toEqual( + spanishPrefix + ); + }); + // we *could*, in principle, grab the path and send them to + // process.env.HOME_LOCATION/path, but if the origin is wrong something unexpected is + // going on. In that case it's probably best to just send them to + // process.env.HOME_LOCATION/learn. + test('should return default parameters if the origin is unknown', () => { + expect.assertions(1); + const exampleOrigin = { + ...defaultObject, + origin: 'http://example.com', + pathPrefix: 'espanol' + }; + expect(normalizeParams(exampleOrigin, defaultOrigin)).toEqual( + defaultObject + ); + }); + test('should return default parameters if the returnTo is unknown', () => { + expect.assertions(1); + const exampleReturnTo = { + ...defaultObject, + returnTo: 'http://example.com/path', + pathPrefix: 'espanol' + }; + expect(normalizeParams(exampleReturnTo, defaultOrigin)).toEqual( + defaultObject + ); + }); + + test('should reject returnTo without trailing slashes', () => { + const exampleReturnTo = { + ...defaultObject, + returnTo: 'https://www.freecodecamp.dev' + }; + expect(normalizeParams(exampleReturnTo, defaultOrigin)).toEqual( + defaultObject + ); + }); + + test('should not modify the returnTo if it is valid', () => { + const exampleReturnTo = { + ...defaultObject, + returnTo: 'https://www.freecodecamp.dev/' + }; + expect(normalizeParams(exampleReturnTo, defaultOrigin)).toEqual( + exampleReturnTo + ); + }); + }); + + describe('getRedirectParams', () => { + test('should return origin, pathPrefix and returnTo given valid headers', () => { + const req = { + headers: { + referer: `https://www.freecodecamp.org/espanol/learn/rosetta-code/` + } + }; + + const expectedReturn = { + origin: 'https://www.freecodecamp.org', + pathPrefix: 'espanol', + returnTo: 'https://www.freecodecamp.org/espanol/learn/rosetta-code/' + }; + + const result = getRedirectParams(req); + expect(result).toEqual(expectedReturn); + }); + + test('should strip off any query parameters from the referer', () => { + const req = { + headers: { + referer: `https://www.freecodecamp.org/espanol/learn/rosetta-code/?query=param` + } + }; + + const expectedReturn = { + origin: 'https://www.freecodecamp.org', + pathPrefix: 'espanol', + returnTo: 'https://www.freecodecamp.org/espanol/learn/rosetta-code/' + }; + + const result = getRedirectParams(req); + expect(result).toEqual(expectedReturn); + }); + + test('should returnTo the origin if the referer is missing', () => { + const req = { + headers: {} + }; + + const expectedReturn = { + returnTo: `${HOME_LOCATION}/`, + origin: HOME_LOCATION, + pathPrefix: '' + }; + + const result = getRedirectParams(req); + expect(result).toEqual(expectedReturn); + }); + + test('should returnTo the origin if the referrer is invalid', () => { + const req = { + headers: { + referer: 'invalid-url' + } + }; + + const expectedReturn = { + returnTo: `${HOME_LOCATION}/`, + origin: HOME_LOCATION, + pathPrefix: '' + }; + + const result = getRedirectParams(req); + expect(result).toEqual(expectedReturn); + }); + }); + + describe('getLoginRedirectParams', () => { + test('should use the login-returnto cookie if present', () => { + const mockReq = { + cookies: { + 'login-returnto': 'https://www.freecodecamp.org/espanol/learn' + }, + unsignCookie: (rawValue: string) => ({ value: rawValue }) + }; + + const expectedReturn = { + origin: 'https://www.freecodecamp.org', + pathPrefix: 'espanol', + returnTo: 'https://www.freecodecamp.org/espanol/learn' + }; + + const result = getLoginRedirectParams(mockReq); + expect(result).toEqual(expectedReturn); + }); + }); + + describe('getPrefixedLandingPath', () => { + test('should return the origin when no pathPrefix is provided', () => { + const result = getPrefixedLandingPath(defaultOrigin); + expect(result).toEqual(defaultOrigin); + }); + + test('should append pathPrefix to origin when pathPrefix is provided', () => { + const expectedPath = `${defaultOrigin}/learn`; + const result = getPrefixedLandingPath(defaultOrigin, 'learn'); + expect(result).toEqual(expectedPath); + }); + + test('should handle empty origin', () => { + const pathPrefix = 'learn'; + const expectedPath = '/learn'; + const result = getPrefixedLandingPath('', pathPrefix); + expect(result).toEqual(expectedPath); + }); + + test('should handle empty pathPrefix', () => { + const result = getPrefixedLandingPath(defaultOrigin, ''); + expect(result).toEqual(defaultOrigin); + }); + }); +});