diff --git a/.gitattributes b/.gitattributes index f3408b4a8a8532909643b18ab392734aff0ff0e5..72139abd49c12f7b1cc6ff8f5505f6322a304eb6 100644 --- a/.gitattributes +++ b/.gitattributes @@ -59,3 +59,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.mp4 filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text code_syntax_dataset_1GB.csv filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Black.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Bold.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Light.woff filter=lfs diff=lfs merge=lfs -text +github_code/freeCodeCamp__freeCodeCamp/client/static/fonts/noto-sans-japanese/NotoSansJP-Regular.woff filter=lfs diff=lfs merge=lfs -text diff --git a/github_code/README.md b/github_code/README.md new file mode 100644 index 0000000000000000000000000000000000000000..56d5ccbcb781e6b8a6f7007b23720c16959397b2 --- /dev/null +++ b/github_code/README.md @@ -0,0 +1,2 @@ +# GitHub Code Import +This PR will contain 500 top-starred GitHub repos extracted from zip. diff --git a/github_code/codecrafters-io__build-your-own-x/.gitattributes b/github_code/codecrafters-io__build-your-own-x/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..a158744534ea2cb560296f647509a63e8028f033 --- /dev/null +++ b/github_code/codecrafters-io__build-your-own-x/.gitattributes @@ -0,0 +1,2 @@ +*.md linguist-detectable=true +*.md linguist-documentation=false diff --git a/github_code/codecrafters-io__build-your-own-x/ISSUE_TEMPLATE.md b/github_code/codecrafters-io__build-your-own-x/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..683f25e83b5c9469745567c42c809315546387db --- /dev/null +++ b/github_code/codecrafters-io__build-your-own-x/ISSUE_TEMPLATE.md @@ -0,0 +1,39 @@ + + +### Main programming language + + +### Tutorial title + + +### Tutorial URL + +### Category +* [ ] 3D Renderer +* [ ] Augmented Reality +* [ ] BitTorrent Client +* [ ] Blockchain / Cryptocurrency +* [ ] Bot +* [ ] Command-Line Tool +* [ ] Database +* [ ] Docker +* [ ] Emulator / Virtual Machine +* [ ] Front-end Framework / Library +* [ ] Game +* [ ] Git +* [ ] Network Stack +* [ ] Neural Network +* [ ] Operating System +* [ ] Physics Engine +* [ ] Programming Language +* [ ] Regex Engine +* [ ] Search Engine +* [ ] Shell +* [ ] Template Engine +* [ ] Visual Recognition System +* [ ] Voxel Engine +* [ ] Web Search Engine +* [ ] Web Server +* [ ] Uncategorized diff --git a/github_code/codecrafters-io__build-your-own-x/README.md b/github_code/codecrafters-io__build-your-own-x/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9a553c729b29bc69296d7092fc1c314c2c811bad --- /dev/null +++ b/github_code/codecrafters-io__build-your-own-x/README.md @@ -0,0 +1,505 @@ +[![Banner](https://codecrafters.io/images/new-ccgithub-banner.png)](https://codecrafters.io/github-banner) + +## Build your own <insert-technology-here> + +This repository is a compilation of well-written, step-by-step guides for re-creating our favorite technologies from scratch. + +> *What I cannot create, I do not understand — Richard Feynman.* + +It's a great way to learn. + +* [3D Renderer](#build-your-own-3d-renderer) +* [AI Model](#build-your-own-ai-model) +* [Augmented Reality](#build-your-own-augmented-reality) +* [BitTorrent Client](#build-your-own-bittorrent-client) +* [Blockchain / Cryptocurrency](#build-your-own-blockchain--cryptocurrency) +* [Bot](#build-your-own-bot) +* [Command-Line Tool](#build-your-own-command-line-tool) +* [Database](#build-your-own-database) +* [Docker](#build-your-own-docker) +* [Emulator / Virtual Machine](#build-your-own-emulator--virtual-machine) +* [Front-end Framework / Library](#build-your-own-front-end-framework--library) +* [Game](#build-your-own-game) +* [Git](#build-your-own-git) +* [Memory Allocator](#build-your-own-memory-allocator) +* [Network Stack](#build-your-own-network-stack) +* [Neural Network](#build-your-own-neural-network) +* [Operating System](#build-your-own-operating-system) +* [Physics Engine](#build-your-own-physics-engine) +* [Processor](#build-your-own-processor) +* [Programming Language](#build-your-own-programming-language) +* [Regex Engine](#build-your-own-regex-engine) +* [Search Engine](#build-your-own-search-engine) +* [Shell](#build-your-own-shell) +* [Template Engine](#build-your-own-template-engine) +* [Text Editor](#build-your-own-text-editor) +* [Visual Recognition System](#build-your-own-visual-recognition-system) +* [Voxel Engine](#build-your-own-voxel-engine) +* [Web Browser](#build-your-own-web-browser) +* [Web Server](#build-your-own-web-server) +* [Uncategorized](#uncategorized) + +## Tutorials + +#### Build your own `Distributed Systems` +* [**Java**: _Building Your Own Kafka-like System From Scratch: A Step-by-Step Guide_](https://github.com/buildthingsuseful/build-your-own-kafka) + +#### Build your own `3D Renderer` + +* [**C++**: _Introduction to Ray Tracing: a Simple Method for Creating 3D Images_](https://www.scratchapixel.com/lessons/3d-basic-rendering/introduction-to-ray-tracing/how-does-it-work) +* [**C++**: _How OpenGL works: software rendering in 500 lines of code_](https://github.com/ssloy/tinyrenderer/wiki) +* [**C++**: _Raycasting engine of Wolfenstein 3D_](http://lodev.org/cgtutor/raycasting.html) +* [**C++**: _Physically Based Rendering:From Theory To Implementation_](http://www.pbr-book.org/) +* [**C++**: _Ray Tracing in One Weekend_](https://raytracing.github.io/books/RayTracingInOneWeekend.html) +* [**C++**: _Rasterization: a Practical Implementation_](https://www.scratchapixel.com/lessons/3d-basic-rendering/rasterization-practical-implementation/overview-rasterization-algorithm) +* [**C# / TypeScript / JavaScript**: _Learning how to write a 3D soft engine from scratch in C#, TypeScript or JavaScript_](https://www.davrous.com/2013/06/13/tutorial-series-learning-how-to-write-a-3d-soft-engine-from-scratch-in-c-typescript-or-javascript/) +* [**Java / JavaScript**: _Build your own 3D renderer_](https://avik-das.github.io/build-your-own-raytracer/) +* [**Java**: _How to create your own simple 3D render engine in pure Java_](http://blog.rogach.org/2015/08/how-to-create-your-own-simple-3d-render.html) +* [**JavaScript / Pseudocode**: _Computer Graphics from scratch_](http://www.gabrielgambetta.com/computer-graphics-from-scratch/introduction.html) +* [**Python**: _A 3D Modeller_](http://aosabook.org/en/500L/a-3d-modeller.html) + +#### Build your own `AI Model` +* [**Python**: _A Large Language Model (LLM)_](https://github.com/rasbt/LLMs-from-scratch) +* [**Python**: _Diffusion Models for Image Generation_](https://huggingface.co/learn/diffusion-course/en/unit1/3) +* [**Python**: _RAG for Document Search_](https://github.com/langchain-ai/rag-from-scratch) + +#### Build your own `Augmented Reality` + +* [**C#**: _How To: Augmented Reality App Tutorial for Beginners with Vuforia and Unity 3D_](https://www.youtube.com/watch?v=uXNjNcqW4kY) [video] +* [**C#**: _How To Unity ARCore_](https://www.youtube.com/playlist?list=PLKIKuXdn4ZMjuUAtdQfK1vwTZPQn_rgSv) [video] +* [**C#**: _AR Portal Tutorial with Unity_](https://www.youtube.com/playlist?list=PLPCqNOwwN794Gz5fzUSi1p4OqLU0HTmvn) [video] +* [**C#**: _How to create a Dragon in Augmented Reality in Unity ARCore_](https://www.youtube.com/watch?v=qTSDPkPyPqs) [video] +* [**C#**: _How to Augmented Reality AR Tutorial: ARKit Portal to the Upside Down_](https://www.youtube.com/watch?v=Z5AmqMuNi08) [video] +* [**Python**: _Augmented Reality with Python and OpenCV_](https://bitesofcode.wordpress.com/2017/09/12/augmented-reality-with-python-and-opencv-part-1/) + +#### Build your own `BitTorrent Client` + +* [**C#**: _Building a BitTorrent client from scratch in C#_](https://www.seanjoflynn.com/research/bittorrent.html) +* [**Go**: _Building a BitTorrent client from the ground up in Go_](https://blog.jse.li/posts/torrent/) +* [**Nim**: _Writing a Bencode Parser_](https://xmonader.github.io/nimdays/day02_bencode.html) +* [**Node.js**: _Write your own bittorrent client_](https://allenkim67.github.io/programming/2016/05/04/how-to-make-your-own-bittorrent-client.html) +* [**Python**: _A BitTorrent client in Python 3.5_](http://markuseliasson.se/article/bittorrent-in-python/) + +#### Build your own `Blockchain / Cryptocurrency` + +* [**ATS**: _Functional Blockchain_](https://beta.observablehq.com/@galletti94/functional-blockchain) +* [**Crystal**: _Write your own blockchain and PoW algorithm using Crystal_](https://medium.com/@bradford_hamilton/write-your-own-blockchain-and-pow-algorithm-using-crystal-d53d5d9d0c52) +* [**Go**: _Building Blockchain in Go_](https://jeiwan.net/posts/building-blockchain-in-go-part-1/) +* [**Go**: _Code your own blockchain in less than 200 lines of Go_](https://medium.com/@mycoralhealth/code-your-own-blockchain-in-less-than-200-lines-of-go-e296282bcffc) +* [**Java**: _Creating Your First Blockchain with Java_](https://medium.com/programmers-blockchain/create-simple-blockchain-java-tutorial-from-scratch-6eeed3cb03fa) +* [**JavaScript**: _A cryptocurrency implementation in less than 1500 lines of code_](https://github.com/conradoqg/naivecoin) +* [**JavaScript**: _Build your own Blockchain in JavaScript_](https://github.com/nambrot/blockchain-in-js) +* [**JavaScript**: _Learn & Build a JavaScript Blockchain_](https://medium.com/digital-alchemy-holdings/learn-build-a-javascript-blockchain-part-1-ca61c285821e) +* [**JavaScript**: _Creating a blockchain with JavaScript_](https://github.com/SavjeeTutorials/SavjeeCoin) +* [**JavaScript**: _How To Launch Your Own Production-Ready Cryptocurrency_](https://hackernoon.com/how-to-launch-your-own-production-ready-cryptocurrency-ab97cb773371) +* [**JavaScript**: _Writing a Blockchain in Node.js_](https://www.smashingmagazine.com/2020/02/cryptocurrency-blockchain-node-js/) +* [**Kotlin**: _Let’s implement a cryptocurrency in Kotlin_](https://medium.com/@vasilyf/lets-implement-a-cryptocurrency-in-kotlin-part-1-blockchain-8704069f8580) +* [**Python**: _Learn Blockchains by Building One_](https://hackernoon.com/learn-blockchains-by-building-one-117428612f46) +* [**Python**: _Build your own blockchain: a Python tutorial_](http://ecomunsing.com/build-your-own-blockchain) +* [**Python**: _A Practical Introduction to Blockchain with Python_](http://adilmoujahid.com/posts/2018/03/intro-blockchain-bitcoin-python/) +* [**Python**: _Let’s Build the Tiniest Blockchain_](https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b) +* [**Ruby**: _Programming Blockchains Step-by-Step (Manuscripts Book Edition)_](https://github.com/yukimotopress/programming-blockchains-step-by-step) +* [**Scala**: _How to build a simple actor-based blockchain_](https://medium.freecodecamp.org/how-to-build-a-simple-actor-based-blockchain-aac1e996c177) +* [**TypeScript**: _Naivecoin: a tutorial for building a cryptocurrency_](https://lhartikk.github.io/) +* [**TypeScript**: _NaivecoinStake: a tutorial for building a cryptocurrency with the Proof of Stake consensus_](https://naivecoinstake.learn.uno/) +* [**Rust**: _Building A Blockchain in Rust & Substrate_](https://hackernoon.com/building-a-blockchain-in-rust-and-substrate-a-step-by-step-guide-for-developers-kc223ybp) + + +#### Build your own `Bot` + +* [**Haskell**: _Roll your own IRC bot_](https://wiki.haskell.org/Roll_your_own_IRC_bot) +* [**Node.js**: _Creating a Simple Facebook Messenger AI Bot with API.ai in Node.js_](https://tutorials.botsfloor.com/creating-a-simple-facebook-messenger-ai-bot-with-api-ai-in-node-js-50ae2fa5c80d) +* [**Node.js**: _How to make a responsive telegram bot_](https://www.sohamkamani.com/blog/2016/09/21/making-a-telegram-bot/) +* [**Node.js**: _Create a Discord bot_](https://discordjs.guide/) +* [**Node.js**: _gifbot - Building a GitHub App_](https://blog.scottlogic.com/2017/05/22/gifbot-github-integration.html) +* [**Node.js**: _Building A Simple AI Chatbot With Web Speech API And Node.js_](https://www.smashingmagazine.com/2017/08/ai-chatbot-web-speech-api-node-js/) +* [**Python**: _How to Build Your First Slack Bot with Python_](https://www.fullstackpython.com/blog/build-first-slack-bot-python.html) +* [**Python**: _How to build a Slack Bot with Python using Slack Events API & Django under 20 minute_](https://medium.com/freehunch/how-to-build-a-slack-bot-with-python-using-slack-events-api-django-under-20-minute-code-included-269c3a9bf64e) +* [**Python**: _Build a Reddit Bot_](https://pythonforengineers.com/blog/build-a-reddit-bot-part-1/) +* [**Python**: _How To Make A Reddit Bot_](https://www.youtube.com/watch?v=krTUf7BpTc0) [video] +* [**Python**: _How To Create a Telegram Bot Using Python_](https://www.freecodecamp.org/news/how-to-create-a-telegram-bot-using-python/) +* [**Python**: _Create a Twitter Bot in Python Using Tweepy_](https://medium.freecodecamp.org/creating-a-twitter-bot-in-python-with-tweepy-ac524157a607) +* [**Python**: _Creating Reddit Bot with Python & PRAW_](https://www.youtube.com/playlist?list=PLIFBTFgFpoJ9vmYYlfxRFV6U_XhG-4fpP) [video] +* [**R**: _Build A Cryptocurrency Trading Bot with R_](https://towardsdatascience.com/build-a-cryptocurrency-trading-bot-with-r-1445c429e1b1) +* [**Rust**: _A bot for Starcraft in Rust, C or any other language_](https://habr.com/en/post/436254/) + +#### Build your own `Command-Line Tool` + +* [**Go**: _Visualize your local git contributions with Go_](https://flaviocopes.com/go-git-contributions/) +* [**Go**: _Build a command line app with Go: lolcat_](https://flaviocopes.com/go-tutorial-lolcat/) +* [**Go**: _Building a cli command with Go: cowsay_](https://flaviocopes.com/go-tutorial-cowsay/) +* [**Go**: _Go CLI tutorial: fortune clone_](https://flaviocopes.com/go-tutorial-fortune/) +* [**Nim**: _Writing a stow alternative to manage dotfiles_](https://xmonader.github.io/nimdays/day06_nistow.html) +* [**Node.js**: _Create a CLI tool in Javascript_](https://citw.dev/tutorial/create-your-own-cli-tool) +* [**Rust**: _Command line apps in Rust_](https://rust-cli.github.io/book/index.html) +* [**Rust**: _Writing a Command Line Tool in Rust_](https://mattgathu.dev/2017/08/29/writing-cli-app-rust.html) +* [**Zig**: _Build Your Own CLI App in Zig from Scratch_](https://rebuild-x.github.io/docs/#/./zig/terminal/cli) + + +#### Build your own `Database` + +* [**C**: _Let's Build a Simple Database_](https://cstack.github.io/db_tutorial/) +* [**C++**: _Build Your Own Redis from Scratch_](https://build-your-own.org/redis) +* [**C#**: _Build Your Own Database_](https://www.codeproject.com/Articles/1029838/Build-Your-Own-Database) +* [**Clojure**: _An Archaeology-Inspired Database_](http://aosabook.org/en/500L/an-archaeology-inspired-database.html) +* [**Crystal**: _Why you should build your own NoSQL Database_](https://medium.com/@marceloboeira/why-you-should-build-your-own-nosql-database-9bbba42039f5) +* [**Go**: _Build Your Own Database from Scratch: From B+Tree To SQL in 3000 Lines_](https://build-your-own.org/database/) +* [**Go**: _Code a database in 45 steps: a series of test-driven small coding puzzles_](https://trialofcode.org/database/) +* [**Go**: _Build Your Own Redis from Scratch_](https://www.build-redis-from-scratch.dev/) +* [**JavaScript**: _Dagoba: an in-memory graph database_](http://aosabook.org/en/500L/dagoba-an-in-memory-graph-database.html) +* [**Python**: _DBDB: Dog Bed Database_](http://aosabook.org/en/500L/dbdb-dog-bed-database.html) +* [**Python**: _Write your own miniature Redis with Python_](http://charlesleifer.com/blog/building-a-simple-redis-server-with-python/) +* [**Ruby**: _Build your own fast, persistent KV store in Ruby_](https://dineshgowda.com/posts/build-your-own-persistent-kv-store/) +* [**Rust**: _Build your own Redis client and server_](https://tokio.rs/tokio/tutorial/setup) + +#### Build your own `Docker` + +* [**C**: _Linux containers in 500 lines of code_](https://blog.lizzie.io/linux-containers-in-500-loc.html) +* [**Go**: _Build Your Own Container Using Less than 100 Lines of Go_](https://www.infoq.com/articles/build-a-container-golang) +* [**Go**: _Building a container from scratch in Go_](https://www.youtube.com/watch?v=8fi7uSYlOdc) [video] +* [**Python**: _A workshop on Linux containers: Rebuild Docker from Scratch_](https://github.com/Fewbytes/rubber-docker) +* [**Python**: _A proof-of-concept imitation of Docker, written in 100% Python_](https://github.com/tonybaloney/mocker) +* [**Shell**: _Docker implemented in around 100 lines of bash_](https://github.com/p8952/bocker) + +#### Build your own `Emulator / Virtual Machine` + +* [**C**: _Home-grown bytecode interpreters_](https://medium.com/bumble-tech/home-grown-bytecode-interpreters-51e12d59b25c) +* [**C**: _Virtual machine in C_](http://web.archive.org/web/20200121100942/https://blog.felixangell.com/virtual-machine-in-c/) +* [**C**: _Write your Own Virtual Machine_](https://justinmeiners.github.io/lc3-vm/) +* [**C**: _Writing a Game Boy emulator, Cinoop_](https://cturt.github.io/cinoop.html) +* [**C++**: _How to write an emulator (CHIP-8 interpreter)_](http://www.multigesture.net/articles/how-to-write-an-emulator-chip-8-interpreter/) +* [**C++**: _Emulation tutorial (CHIP-8 interpreter)_](http://www.codeslinger.co.uk/pages/projects/chip8.html) +* [**C++**: _Emulation tutorial (GameBoy emulator)_](http://www.codeslinger.co.uk/pages/projects/gameboy.html) +* [**C++**: _Emulation tutorial (Master System emulator)_](http://www.codeslinger.co.uk/pages/projects/mastersystem/memory.html) +* [**C++**: _NES Emulator From Scratch_](https://www.youtube.com/playlist?list=PLrOv9FMX8xJHqMvSGB_9G9nZZ_4IgteYf) [video] +* [**Common Lisp**: _CHIP-8 in Common Lisp_](http://stevelosh.com/blog/2016/12/chip8-cpu/) +* [**JavaScript**: _GameBoy Emulation in JavaScript_](http://imrannazar.com/GameBoy-Emulation-in-JavaScript) +* [**Python**: _Emulation Basics: Write your own Chip 8 Emulator/Interpreter_](http://omokute.blogspot.com.br/2012/06/emulation-basics-write-your-own-chip-8.html) +* [**Rust**: _0dmg: Learning Rust by building a partial Game Boy emulator_](https://jeremybanks.github.io/0dmg/) + +#### Build your own `Front-end Framework / Library` + +* [**JavaScript**: _WTF is JSX (Let's Build a JSX Renderer)_](https://jasonformat.com/wtf-is-jsx/) +* [**JavaScript**: _A DIY guide to build your own React_](https://github.com/hexacta/didact) +* [**JavaScript**: _Building React From Scratch_](https://www.youtube.com/watch?v=_MAD4Oly9yg) [video] +* [**JavaScript**: _Gooact: React in 160 lines of JavaScript_](https://medium.com/@sweetpalma/gooact-react-in-160-lines-of-javascript-44e0742ad60f) +* [**JavaScript**: _Learn how React Reconciler package works by building your own lightweight React DOM_](https://hackernoon.com/learn-you-some-custom-react-renderers-aed7164a4199) +* [**JavaScript**: _Build Yourself a Redux_](https://zapier.com/engineering/how-to-build-redux/) +* [**JavaScript**: _Let’s Write Redux!_](https://www.jamasoftware.com/blog/lets-write-redux/) +* [**JavaScript**: _Redux: Implementing Store from Scratch_](https://egghead.io/lessons/react-redux-implementing-store-from-scratch) [video] +* [**JavaScript**: _Build Your own Simplified AngularJS in 200 Lines of JavaScript_](https://blog.mgechev.com/2015/03/09/build-learn-your-own-light-lightweight-angularjs/) +* [**JavaScript**: _Make Your Own AngularJS_](http://teropa.info/blog/2013/11/03/make-your-own-angular-part-1-scopes-and-digest.html) +* [**JavaScript**: _How to write your own Virtual DOM_](https://medium.com/@deathmood/how-to-write-your-own-virtual-dom-ee74acc13060) +* [**JavaScript**: _Building a frontend framework, from scratch, with components (templating, state, VDOM)_](https://mfrachet.github.io/create-frontend-framework/) +* [**JavaScript**: _Build your own React_](https://pomb.us/build-your-own-react/) +* [**JavaScript**: _Building a Custom React Renderer_](https://youtu.be/CGpMlWVcHok) [video] + +#### Build your own `Game` + +* [**C**: _Handmade Hero_](https://handmadehero.org/) +* [**C**: _How to Program an NES game in C_](https://nesdoug.com/) +* [**C**: _Chess Engine In C_](https://www.youtube.com/playlist?list=PLZ1QII7yudbc-Ky058TEaOstZHVbT-2hg) [video] +* [**C**: _Let's Make: Dangerous Dave_](https://www.youtube.com/playlist?list=PLSkJey49cOgTSj465v2KbLZ7LMn10bCF9) [video] +* [**C**: _Learn Video Game Programming in C_](https://www.youtube.com/playlist?list=PLT6WFYYZE6uLMcPGS3qfpYm7T_gViYMMt) + [video] +* [**C**: _Coding A Sudoku Solver in C_](https://www.youtube.com/playlist?list=PLkTXsX7igf8edTYU92nU-f5Ntzuf-RKvW) [video] +* [**C**: _Coding a Rogue/Nethack RPG in C_](https://www.youtube.com/playlist?list=PLkTXsX7igf8erbWGYT4iSAhpnJLJ0Nk5G) [video] +* [**C**: _On Tetris and Reimplementation_](https://brennan.io/2015/06/12/tetris-reimplementation/) +* [**C++**: _Breakout_](https://learnopengl.com/In-Practice/2D-Game/Breakout) +* [**C++**: _Beginning Game Programming v2.0_](http://lazyfoo.net/tutorials/SDL/) +* [**C++**: _Tetris tutorial in C++ platform independent focused in game logic for beginners_](http://javilop.com/gamedev/tetris-tutorial-in-c-platform-independent-focused-in-game-logic-for-beginners/) +* [**C++**: _Remaking Cavestory in C++_](https://www.youtube.com/watch?v=ETvApbD5xRo&list=PLNOBk_id22bw6LXhrGfhVwqQIa-M2MsLa) [video] +* [**C++**: _Reconstructing Cave Story_](https://www.youtube.com/playlist?list=PL006xsVEsbKjSKBmLu1clo85yLrwjY67X) [video] +* [**C++**: _Space Invaders from Scratch_](http://nicktasios.nl/posts/space-invaders-from-scratch-part-1.html) +* [**C#**: _Learn C# by Building a Simple RPG_](http://scottlilly.com/learn-c-by-building-a-simple-rpg-index/) +* [**C#**: _Creating a Roguelike Game in C#_](https://roguesharp.wordpress.com/) +* [**C#**: _Build a C#/WPF RPG_](https://scottlilly.com/build-a-cwpf-rpg/) +* [**Go**: _Games With Go_](https://www.youtube.com/playlist?list=PLDZujg-VgQlZUy1iCqBbe5faZLMkA3g2x) [video] +* [**Java**: _Code a 2D Game Engine using Java - Full Course for Beginners_](https://www.youtube.com/watch?v=025QFeZfeyM) [video] +* [**Java**: _3D Game Development with LWJGL 3_](https://lwjglgamedev.gitbooks.io/3d-game-development-with-lwjgl/content/) +* [**JavaScript**: _2D breakout game using Phaser_](https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_breakout_game_Phaser) +* [**JavaScript**: _How to Make Flappy Bird in HTML5 With Phaser_](http://www.lessmilk.com/tutorial/flappy-bird-phaser-1) +* [**JavaScript**: _Developing Games with React, Redux, and SVG_](https://auth0.com/blog/developing-games-with-react-redux-and-svg-part-1/) +* [**JavaScript**: _Build your own 8-Ball Pool game from scratch_](https://www.youtube.com/watch?v=aXwCrtAo4Wc) [video] +* [**JavaScript**: _How to Make Your First Roguelike_](https://gamedevelopment.tutsplus.com/tutorials/how-to-make-your-first-roguelike--gamedev-13677) +* [**JavaScript**: _Think like a programmer: How to build Snake using only JavaScript, HTML & CSS_](https://medium.freecodecamp.org/think-like-a-programmer-how-to-build-snake-using-only-javascript-html-and-css-7b1479c3339e) +* [**Lua**: _BYTEPATH_](https://github.com/SSYGEN/blog/issues/30) +* [**Python**: _Developing Games With PyGame_](https://pythonprogramming.net/pygame-python-3-part-1-intro/) +* [**Python**: _Making Games with Python & Pygame_](https://inventwithpython.com/makinggames.pdf) [pdf] +* [**Python**: _Roguelike Tutorial Revised_](http://rogueliketutorials.com/) +* [**Ruby**: _Developing Games With Ruby_](https://leanpub.com/developing-games-with-ruby/read) +* [**Ruby**: _Ruby Snake_](https://www.diatomenterprises.com/gamedev-on-ruby-why-not/) +* [**Rust**: _Adventures in Rust: A Basic 2D Game_](https://a5huynh.github.io/posts/2018/adventures-in-rust/) +* [**Rust**: _Roguelike Tutorial in Rust + tcod_](https://tomassedovic.github.io/roguelike-tutorial/) + +#### Build your own `Git` + +* [**Haskell**: _Reimplementing “git clone” in Haskell from the bottom up_](http://stefan.saasen.me/articles/git-clone-in-haskell-from-the-bottom-up/) +* [**JavaScript**: _Gitlet_](http://gitlet.maryrosecook.com/docs/gitlet.html) +* [**JavaScript**: _Build GIT - Learn GIT_](https://kushagra.dev/blog/build-git-learn-git/) +* [**Python**: _Just enough of a Git client to create a repo, commit, and push itself to GitHub_](https://benhoyt.com/writings/pygit/) +* [**Python**: _Write yourself a Git!_](https://wyag.thb.lt/) +* [**Python**: _ugit: Learn Git Internals by Building Git Yourself_](https://www.leshenko.net/p/ugit/) +* [**Ruby**: _Rebuilding Git in Ruby_](https://robots.thoughtbot.com/rebuilding-git-in-ruby) + +#### Build your own `Memory Allocator` + +* [**C**: _Malloc is not magic -- Implementing your own memory allocator_](https://medium.com/p/e0354e914402) + +#### Build your own `Network Stack` + +* [**C**: _Beej's Guide to Network Programming_](http://beej.us/guide/bgnet/) +* [**C**: _Let's code a TCP/IP stack_](http://www.saminiir.com/lets-code-tcp-ip-stack-1-ethernet-arp/) +* [**C / Python**: _Build your own VPN/Virtual Switch_](https://github.com/peiyuanix/build-your-own-zerotier) +* [**Ruby**: _How to build a network stack in Ruby_](https://medium.com/geckoboard-under-the-hood/how-to-build-a-network-stack-in-ruby-f73aeb1b661b) + +#### Build your own `Neural Network` + +* [**C#**: _Neural Network OCR_](https://www.codeproject.com/Articles/11285/Neural-Network-OCR) +* [**F#**: _Building Neural Networks in F#: Part 1_](https://medium.com/data-science/building-neural-networks-in-f-part-1-a2832ae972e6) +* [**F#**: _Building Neural Networks in F#: Part 2_](https://medium.com/data-science/building-neural-networks-in-f-part-2-training-evaluation-5e3a68889da6) +* [**Go**: _Build a multilayer perceptron with Golang_](https://made2591.github.io/posts/neuralnetwork) +* [**Go**: _How to build a simple artificial neural network with Go_](https://sausheong.github.io/posts/how-to-build-a-simple-artificial-neural-network-with-go/) +* [**Go**: _Building a Neural Net from Scratch in Go_](https://datadan.io/blog/neural-net-with-go) +* [**JavaScript / Java**: _Neural Networks - The Nature of Code_](https://www.youtube.com/playlist?list=PLRqwX-V7Uu6aCibgK1PTWWu9by6XFdCfh) [video] +* [**JavaScript**: _Neural networks from scratch for JavaScript linguists (Part1 — The Perceptron)_](https://hackernoon.com/neural-networks-from-scratch-for-javascript-linguists-part1-the-perceptron-632a4d1fbad2) +* [**Python**: _A Neural Network in 11 lines of Python_](https://iamtrask.github.io/2015/07/12/basic-python-network/) +* [**Python**: _Build Deep Learning From Scratch (reimplement PyTorch internals across 34 stages)_](https://github.com/roiamiel1/Build-Deep-Learning-From-Scratch) +* [**Python**: _Implement a Neural Network from Scratch_](https://victorzhou.com/blog/intro-to-neural-networks/) +* [**Python**: _Optical Character Recognition (OCR)_](http://aosabook.org/en/500L/optical-character-recognition-ocr.html) +* [**Python**: _Traffic signs classification with a convolutional network_](https://navoshta.com/traffic-signs-classification/) +* [**Python**: _Generate Music using LSTM Neural Network in Keras_](https://towardsdatascience.com/how-to-generate-music-using-a-lstm-neural-network-in-keras-68786834d4c5) +* [**Python**: _An Introduction to Convolutional Neural Networks_](https://victorzhou.com/blog/intro-to-cnns-part-1/) +* [**Python**: _Neural Networks: Zero to Hero_](https://www.youtube.com/playlist?list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ) +* [**Python**: _SlowTorch: Implementation of PyTorch from the ground up in 100% pure Python_](https://github.com/xames3/slowtorch) + +#### Build your own `Operating System` + +* [**Assembly**: _Writing a Tiny x86 Bootloader_](http://joebergeron.io/posts/post_two.html) +* [**Assembly**: _Baking Pi – Operating Systems Development_](http://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/os/index.html) +* [**C**: _Building a software and hardware stack for a simple computer from scratch_](https://www.youtube.com/watch?v=ZjwvMcP3Nf0&list=PLU94OURih-CiP4WxKSMt3UcwMSDM3aTtX) [video] +* [**C**: _Operating Systems: From 0 to 1_](https://tuhdo.github.io/os01/) +* [**C**: _The little book about OS development_](https://littleosbook.github.io/) +* [**C**: _Roll your own toy UNIX-clone OS_](http://jamesmolloy.co.uk/tutorial_html/) +* [**C**: _Kernel 101 – Let’s write a Kernel_](https://arjunsreedharan.org/post/82710718100/kernel-101-lets-write-a-kernel) +* [**C**: _Kernel 201 – Let’s write a Kernel with keyboard and screen support_](https://arjunsreedharan.org/post/99370248137/kernel-201-lets-write-a-kernel-with-keyboard) +* [**C**: _Build a minimal multi-tasking kernel for ARM from scratch_](https://github.com/jserv/mini-arm-os) +* [**C**: _How to create an OS from scratch_](https://github.com/cfenollosa/os-tutorial) +* [**C**: _Malloc tutorial_](https://danluu.com/malloc-tutorial/) +* [**C**: _Hack the virtual memory_](https://blog.holbertonschool.com/hack-the-virtual-memory-c-strings-proc/) +* [**C**: _Learning operating system development using Linux kernel and Raspberry Pi_](https://github.com/s-matyukevich/raspberry-pi-os) +* [**C**: _Operating systems development for Dummies_](https://medium.com/@lduck11007/operating-systems-development-for-dummies-3d4d786e8ac) +* [**C++**: _Write your own Operating System_](https://www.youtube.com/playlist?list=PLHh55M_Kq4OApWScZyPl5HhgsTJS9MZ6M) [video] +* [**C++**: _Writing a Bootloader_](http://3zanders.co.uk/2017/10/13/writing-a-bootloader/) +* [**Rust**: _Writing an OS in Rust_](https://os.phil-opp.com/) +* [**Rust**: _Add RISC-V Rust Operating System Tutorial_](https://osblog.stephenmarz.com/) +* [**(any)**: _Linux from scratch_](https://linuxfromscratch.org/lfs) + +#### Build your own `Physics Engine` + +* [**C**: _Video Game Physics Tutorial_](https://www.toptal.com/game/video-game-physics-part-i-an-introduction-to-rigid-body-dynamics) +* [**C++**: _Game physics series by Allen Chou_](http://allenchou.net/game-physics-series/) +* [**C++**: _How to Create a Custom Physics Engine_](https://gamedevelopment.tutsplus.com/series/how-to-create-a-custom-physics-engine--gamedev-12715) +* [**C++**: _3D Physics Engine Tutorial_](https://www.youtube.com/playlist?list=PLEETnX-uPtBXm1KEr_2zQ6K_0hoGH6JJ0) [video] +* [**JavaScript**: _How Physics Engines Work_](http://buildnewgames.com/gamephysics/) +* [**JavaScript**: _Broad Phase Collision Detection Using Spatial Partitioning_](http://buildnewgames.com/broad-phase-collision-detection/) +* [**JavaScript**: _Build a simple 2D physics engine for JavaScript games_](https://developer.ibm.com/tutorials/wa-build2dphysicsengine/?mhsrc=ibmsearch_a&mhq=2dphysic) + +#### Build your own `Processor` + +* [**Verilog**: _From Blinker to RISC-V_](https://github.com/BrunoLevy/learn-fpga/tree/master/FemtoRV/TUTORIALS/FROM_BLINKER_TO_RISCV) + +#### Build your own `Programming Language` + +* [**(any)**: _mal - Make a Lisp_](https://github.com/kanaka/mal#mal---make-a-lisp) +* [**Assembly**: _Jonesforth_](https://github.com/nornagon/jonesforth/blob/master/jonesforth.S) +* [**C**: _Baby's First Garbage Collector_](http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/) +* [**C**: _Build Your Own Lisp: Learn C and build your own programming language in 1000 lines of code_](http://www.buildyourownlisp.com/) +* [**C**: _Writing a Simple Garbage Collector in C_](http://maplant.com/gc.html) +* [**C**: _C interpreter that interprets itself._](https://github.com/lotabout/write-a-C-interpreter) +* [**C**: _A C & x86 version of the "Let's Build a Compiler" by Jack Crenshaw_](https://github.com/lotabout/Let-s-build-a-compiler) +* [**C**: _A journey explaining how to build a compiler from scratch_](https://github.com/DoctorWkt/acwj) +* [**C++**: _Writing Your Own Toy Compiler Using Flex_](https://gnuu.org/2009/09/18/writing-your-own-toy-compiler/) +* [**C++**: _How to Create a Compiler_](https://www.youtube.com/watch?v=eF9qWbuQLuw) [video] +* [**C++**: _Kaleidoscope: Implementing a Language with LLVM_](https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/index.html) +* [**F#**: _Understanding Parser Combinators_](https://fsharpforfunandprofit.com/posts/understanding-parser-combinators/) +* [**Elixir**: _Demystifying compilers by writing your own_](https://www.youtube.com/watch?v=zMJYoYwOCd4) [video] +* [**Go**: _The Super Tiny Compiler_](https://github.com/hazbo/the-super-tiny-compiler) +* [**Go**: _Lexical Scanning in Go_](https://www.youtube.com/watch?v=HxaD_trXwRE) [video] +* [**Haskell**: _Let's Build a Compiler_](https://g-ford.github.io/cradle/) +* [**Haskell**: _Write You a Haskell_](http://dev.stephendiehl.com/fun/) +* [**Haskell**: _Write Yourself a Scheme in 48 Hours_](https://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours) +* [**Haskell**: _Write You A Scheme_](https://www.wespiser.com/writings/wyas/home.html) +* [**Java**: _Crafting interpreters: A handbook for making programming languages_](http://www.craftinginterpreters.com/) +* [**Java**: _Creating JVM Language_](http://jakubdziworski.github.io/categories.html#Enkel-ref) +* [**JavaScript**: _The Super Tiny Compiler_](https://github.com/jamiebuilds/the-super-tiny-compiler) +* [**JavaScript**: _The Super Tiny Interpreter_](https://github.com/keyanzhang/the-super-tiny-interpreter) +* [**JavaScript**: _Little Lisp interpreter_](https://maryrosecook.com/blog/post/little-lisp-interpreter) +* [**JavaScript**: _How to implement a programming language in JavaScript_](http://lisperator.net/pltut/) +* [**JavaScript**: _Let’s go write a Lisp_](https://idiocy.org/lets-go-write-a-lisp/part-1.html) +* [**OCaml**: _Writing a C Compiler_](https://norasandler.com/2017/11/29/Write-a-Compiler.html) +* [**OCaml**: _Writing a Lisp, the series_](https://bernsteinbear.com/blog/lisp/) +* [**Pascal**: _Let's Build a Compiler_](https://compilers.iecc.com/crenshaw/) +* [**Python**: _A Python Interpreter Written in Python_](http://aosabook.org/en/500L/a-python-interpreter-written-in-python.html) +* [**Python**: _lisp.py: Make your own Lisp interpreter_](http://khamidou.com/compilers/lisp.py/) +* [**Python**: _How to Write a Lisp Interpreter in Python_](http://norvig.com/lispy.html) +* [**Python**: _Let’s Build A Simple Interpreter_](https://ruslanspivak.com/lsbasi-part1/) +* [**Python**: _Make Your Own Simple Interpreted Programming Language_](https://www.youtube.com/watch?v=dj9CBS3ikGA&list=PLZQftyCk7_SdoVexSmwy_tBgs7P0b97yD&index=1) [video] +* [**Python**: _From Source Code To Machine Code: Build Your Own Compiler From Scratch_](https://build-your-own.org/compiler/) +* [**Racket**: _Beautiful Racket: How to make your own programming languages with Racket_](https://beautifulracket.com/) +* [**Ruby**: _A Compiler From Scratch_](https://www.destroyallsoftware.com/screencasts/catalog/a-compiler-from-scratch) +* [**Ruby**: _Markdown compiler from scratch in Ruby_](https://blog.beezwax.net/2017/07/07/writing-a-markdown-compiler/) +* [**Rust**: _Learning Parser Combinators With Rust_](https://bodil.lol/parser-combinators/) +* [**Swift**: _Building a LISP from scratch with Swift_](https://www.uraimo.com/2017/02/05/building-a-lisp-from-scratch-with-swift/) +* [**TypeScript**: _Build your own WebAssembly Compiler_](https://blog.scottlogic.com/2019/05/17/webassembly-compiler.html) + +#### Build your own `Regex Engine` + +* [**C**: _A Regular Expression Matcher_](https://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html) +* [**C**: _Regular Expression Matching Can Be Simple And Fast_](https://swtch.com/~rsc/regexp/regexp1.html) +* [**Go**: _How to build a regex engine from scratch_](https://rhaeguard.github.io/posts/regex) +* [**JavaScript**: _Build a Regex Engine in Less than 40 Lines of Code_](https://nickdrane.com/build-your-own-regex/) +* [**JavaScript**: _How to implement regular expressions in functional javascript using derivatives_](http://dpk.io/dregs/toydregs) +* [**JavaScript**: _Implementing a Regular Expression Engine_](https://deniskyashif.com/2019/02/17/implementing-a-regular-expression-engine/) +* [**Perl**: _How Regexes Work_](https://perl.plover.com/Regex/article.html) +* [**Python**: _Build Your Own Regular Expression Engines: Backtracking, NFA, DFA_](https://build-your-own.org/b2a/r0_intro) +* [**Scala**: _No Magic: Regular Expressions_](https://rcoh.svbtle.com/no-magic-regular-expressions) + +#### Build your own `Search Engine` + +* [**CSS**: _A search engine in CSS_](https://stories.algolia.com/a-search-engine-in-css-b5ec4e902e97) +* [**Python**: _Building a search engine using Redis and redis-py_](http://www.dr-josiah.com/2010/07/building-search-engine-using-redis-and.html) +* [**Python**: _Building a Vector Space Indexing Engine in Python_](https://boyter.org/2010/08/build-vector-space-search-engine-python/) +* [**Python**: _Building A Python-Based Search Engine_](https://www.youtube.com/watch?v=cY7pE7vX6MU) [video] +* [**Python**: _Making text search learn from feedback_](https://medium.com/filament-ai/making-text-search-learn-from-feedback-4fe210fd87b0) +* [**Python**: _Finding Important Words in Text Using TF-IDF_](https://stevenloria.com/tf-idf/) + +#### Build your own `Shell` + +* [**C**: _Tutorial - Write a Shell in C_](https://brennan.io/2015/01/16/write-a-shell-in-c/) +* [**C**: _Let's build a shell!_](https://github.com/kamalmarhubi/shell-workshop) +* [**C**: _Writing a UNIX Shell_](https://indradhanush.github.io/blog/writing-a-unix-shell-part-1/) +* [**C**: _Build Your Own Shell_](https://github.com/tokenrove/build-your-own-shell) +* [**C**: Write a shell in C](https://danishpraka.sh/posts/write-a-shell/) +* [**Go**: _Writing a simple shell in Go_](https://sj14.gitlab.io/post/2018-07-01-go-unix-shell/) +* [**Rust**: _Build Your Own Shell using Rust_](https://www.joshmcguigan.com/blog/build-your-own-shell-rust/) + +#### Build your own `Template Engine` + +* [**JavaScript**: _JavaScript template engine in just 20 lines_](http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line) +* [**JavaScript**: _Understanding JavaScript Micro-Templating_](https://medium.com/wdstack/understanding-javascript-micro-templating-f37a37b3b40e) +* [**Python**: _Approach: Building a toy template engine in Python_](http://alexmic.net/building-a-template-engine/) +* [**Python**: _A Template Engine_](http://aosabook.org/en/500L/a-template-engine.html) +* [**Ruby**: _How to write a template engine in less than 30 lines of code_](http://bits.citrusbyte.com/how-to-write-a-template-library/) + +#### Build your own `Text Editor` + +* [**C**: _Build Your Own Text Editor_](https://viewsourcecode.org/snaptoken/kilo/) +* [**C++**: _Designing a Simple Text Editor_](http://www.fltk.org/doc-1.1/editor.html) +* [**Python**: _Python Tutorial: Make Your Own Text Editor_](https://www.youtube.com/watch?v=xqDonHEYPgA) [video] +* [**Python**: _Create a Simple Python Text Editor!_](http://www.instructables.com/id/Create-a-Simple-Python-Text-Editor/) +* [**Ruby**: _Build a Collaborative Text Editor Using Rails_](https://blog.aha.io/text-editor/) +* [**Rust**: _Hecto: Build your own text editor in Rust_ ](https://www.flenker.blog/hecto/) + +#### Build your own `Visual Recognition System` + +* [**Python**: _Developing a License Plate Recognition System with Machine Learning in Python_](https://medium.com/devcenter/developing-a-license-plate-recognition-system-with-machine-learning-in-python-787833569ccd) +* [**Python**: _Building a Facial Recognition Pipeline with Deep Learning in Tensorflow_](https://hackernoon.com/building-a-facial-recognition-pipeline-with-deep-learning-in-tensorflow-66e7645015b8) + +#### Build your own `Voxel Engine` + +* [**C++**: _Let's Make a Voxel Engine_](https://sites.google.com/site/letsmakeavoxelengine/home) + +#### Build your own `Web Browser` + +* [**Rust**: _Let's build a browser engine_](https://limpet.net/mbrubeck/2014/08/08/toy-layout-engine-1.html) +* [**Python**: _Browser Engineering_](https://browser.engineering) + +#### Build your own `Web Server` + +* [**C#**: _Writing a Web Server from Scratch_](https://www.codeproject.com/Articles/859108/Writing-a-Web-Server-from-Scratch) +* [**Node.js**: _Build Your Own Web Server From Scratch In JavaScript_](https://build-your-own.org/webserver/) +* [**Node.js**: _Let's code a web server from scratch with NodeJS Streams_](https://www.codementor.io/@ziad-saab/let-s-code-a-web-server-from-scratch-with-nodejs-streams-h4uc9utji) +* [**Node.js**: _lets-build-express_](https://github.com/antoaravinth/lets-build-express) +* [**PHP**: _Writing a webserver in pure PHP_](http://station.clancats.com/writing-a-webserver-in-pure-php/) +* [**Python**: _A Simple Web Server_](http://aosabook.org/en/500L/a-simple-web-server.html) +* [**Python**: _Let’s Build A Web Server._](https://ruslanspivak.com/lsbaws-part1/) +* [**Python**: _Web application from scratch_](https://defn.io/2018/02/25/web-app-from-scratch-01/) +* [**Python**: _Building a basic HTTP Server from scratch in Python_](http://joaoventura.net/blog/2017/python-webserver/) +* [**Python**: _Implementing a RESTful Web API with Python & Flask_](http://blog.luisrei.com/articles/flaskrest.html) +* [**Ruby**: _Building a simple websockets server from scratch in Ruby_](http://blog.honeybadger.io/building-a-simple-websockets-server-from-scratch-in-ruby/) + +#### Uncategorized + +* [**(any)**: _From NAND to Tetris: Building a Modern Computer From First Principles_](http://nand2tetris.org/) +* [**(any)**: build-your-own-x-vibe-coding: BYOX-style tutorials adapted for vibe coding](https://github.com/inFaaa/build-your-own-x-vibe-coding) +* [**Alloy**: _The Same-Origin Policy_](http://aosabook.org/en/500L/the-same-origin-policy.html) +* [**C**: _How to Write a Video Player in Less Than 1000 Lines_](http://dranger.com/ffmpeg/ffmpeg.html) +* [**C**: _Learn how to write a hash table in C_](https://github.com/jamesroutley/write-a-hash-table) +* [**C**: _The very basics of a terminal emulator_](https://www.uninformativ.de/blog/postings/2018-02-24/0/POSTING-en.html) +* [**C**: _Write a System Call_](https://brennan.io/2016/11/14/kernel-dev-ep3/) +* [**C**: _Sol - An MQTT broker from scratch_](https://codepr.github.io/posts/sol-mqtt-broker) +* [**C++**: _Build your own VR headset for $200_](https://github.com/relativty/Relativ) +* [**C++**: _How X Window Managers work and how to write one_](https://seasonofcode.com/posts/how-x-window-managers-work-and-how-to-write-one-part-i.html) +* [**C++**: _Writing a Linux Debugger_](https://blog.tartanllama.xyz/writing-a-linux-debugger-setup/) +* [**C++**: _How a 64k intro is made_](http://www.lofibucket.com/articles/64k_intro.html) +* [**C++**: _Make your own Game Engine_](https://www.youtube.com/playlist?list=PLlrATfBNZ98dC-V-N3m0Go4deliWHPFwT) +* [**C#**: _C# Networking: Create a TCP chater server, TCP games, UDP Pong and more_](https://16bpp.net/tutorials/csharp-networking) +* [**C#**: _Loading and rendering 3D skeletal animations from scratch in C# and GLSL_](https://www.seanjoflynn.com/research/skeletal-animation.html) +* [**Clojure**: _Building a spell-checker_](https://bernhardwenzel.com/articles/clojure-spellchecker/) +* [**Go**: _Build A Simple Terminal Emulator In 100 Lines of Golang_](https://ishuah.com/2021/03/10/build-a-terminal-emulator-in-100-lines-of-go/) +* [**Go**: _Let's Create a Simple Load Balancer_](https://kasvith.me/posts/lets-create-a-simple-lb-go/) +* [**Go**: _Video Encoding from Scratch_](https://github.com/kevmo314/codec-from-scratch) +* [**Java**: _How to Build an Android Reddit App_](https://www.youtube.com/playlist?list=PLgCYzUzKIBE9HUJU-upNvl3TRVAo9W47y) [video] +* [**JavaScript**: _Build Your Own Module Bundler - Minipack_](https://github.com/ronami/minipack) +* [**JavaScript**: _Learn JavaScript Promises by Building a Promise from Scratch_](https://levelup.gitconnected.com/understand-javascript-promises-by-building-a-promise-from-scratch-84c0fd855720) +* [**JavaScript**: _Implementing promises from scratch (TDD way)_](https://www.mauriciopoppe.com/notes/computer-science/computation/promises/) +* [**JavaScript**: _Implement your own — call(), apply() and bind() method in JavaScript_](https://blog.usejournal.com/implement-your-own-call-apply-and-bind-method-in-javascript-42cc85dba1b) +* [**JavaScript**: _JavaScript Algorithms and Data Structures_](https://github.com/trekhleb/javascript-algorithms) +* [**JavaScript**: _Build a ride hailing app with React Native_](https://pusher.com/tutorials/ride-hailing-react-native) +* [**JavaScript**: _Build Your Own AdBlocker in (Literally) 10 Minutes_](https://levelup.gitconnected.com/building-your-own-adblocker-in-literally-10-minutes-1eec093b04cd) +* [**Kotlin**: _Build Your Own Cache_](https://github.com/kezhenxu94/cache-lite) +* [**Lua**: _Building a CDN from Scratch to Learn about CDN_](https://github.com/leandromoreira/cdn-up-and-running) +* [**Nim**: _Writing a Redis Protocol Parser_](https://xmonader.github.io/nimdays/day12_resp.html) +* [**Nim**: _Writing a Build system_](https://xmonader.github.io/nimdays/day11_buildsystem.html) +* [**Nim**: _Writing a MiniTest Framework_](https://xmonader.github.io/nimdays/day08_minitest.html) +* [**Nim**: _Writing a DMIDecode Parser_](https://xmonader.github.io/nimdays/day01_dmidecode.html) +* [**Nim**: _Writing a INI Parser_](https://xmonader.github.io/nimdays/day05_iniparser.html) +* [**Nim**: _Writing a Link Checker_](https://xmonader.github.io/nimdays/day04_asynclinkschecker.html) +* [**Nim**: _Writing a URL Shortening Service_](https://xmonader.github.io/nimdays/day07_shorturl.html) +* [**Node.js**: _Build a static site generator in 40 lines with Node.js_](https://www.webdevdrops.com/en/build-static-site-generator-nodejs-8969ebe34b22/) +* [**Node.js**: _Building A Simple Single Sign On(SSO) Server And Solution From Scratch In Node.js._](https://codeburst.io/building-a-simple-single-sign-on-sso-server-and-solution-from-scratch-in-node-js-ea6ee5fdf340) +* [**Node.js**: _How to create a real-world Node CLI app with Node_](https://medium.freecodecamp.org/how-to-create-a-real-world-node-cli-app-with-node-391b727bbed3) +* [**Node.js**: _Build a DNS Server in Node.js_](https://engineerhead.github.io/dns-server/) +* [**Node.js**: _Build a Synchronization Engine with Node.js and Y.js_](https://greenvitriol.com/posts/sync-engine-for-everyone) +* [**PHP**: _Write your own MVC from scratch in PHP_ ](https://chaitya62.github.io/2018/04/29/Writing-your-own-MVC-from-Scratch-in-PHP.html) +* [**PHP**: _Make your own blog_](https://ilovephp.jondh.me.uk/en/tutorial/make-your-own-blog) +* [**PHP**: _Modern PHP Without a Framework_](https://kevinsmith.io/modern-php-without-a-framework) +* [**PHP**: _Code a Web Search Engine in PHP_](https://boyter.org/2013/01/code-for-a-search-engine-in-php-part-1/) +* [**Python**: _Build a Deep Learning Library_](https://www.youtube.com/watch?v=o64FV-ez6Gw) [video] +* [**Python**: _How to Build a Kick-Ass Mobile Document Scanner in Just 5 Minutes_](https://www.pyimagesearch.com/2014/09/01/build-kick-ass-mobile-document-scanner-just-5-minutes/) +* [**Python**: _Continuous Integration System_](http://aosabook.org/en/500L/a-continuous-integration-system.html) +* [**Python**: _Recommender Systems in Python: Beginner Tutorial_](https://www.datacamp.com/community/tutorials/recommender-systems-python) +* [**Python**: _Write SMS-spam detector with Scikit-learn_](https://medium.com/@kopilov.vlad/detect-sms-spam-in-kaggle-with-scikit-learn-5f6afa7a3ca2) +* [**Python**: _A Simple Content-Based Recommendation Engine in Python_](http://blog.untrod.com/2016/06/simple-similar-products-recommendation-engine-in-python.html) +* [**Python**: _Stock Market Predictions with LSTM in Python_](https://www.datacamp.com/community/tutorials/lstm-python-stock-market) +* [**Python**: _Building a simple Generative Adversarial Network (GAN) using Tensorflow_](https://blog.paperspace.com/implementing-gans-in-tensorflow/) +* [**Python**: _Learn ML Algorithms by coding: Decision Trees_](https://lethalbrains.com/learn-ml-algorithms-by-coding-decision-trees-439ac503c9a4) +* [**Python**: _JSON Decoding Algorithm_](https://github.com/cheery/json-algorithm) +* [**Python**: _Build your own Git plugin with python_](https://joshburns-xyz.vercel.app/posts/build-your-own-git-plugin) +* [**Ruby**: _A Pedometer in the Real World_](http://aosabook.org/en/500L/a-pedometer-in-the-real-world.html) +* [**Ruby**: _Creating a Linux Desktop application with Ruby_](https://iridakos.com/tutorials/2018/01/25/creating-a-gtk-todo-application-with-ruby) +* [**Rust**: _Building a DNS server in Rust_](https://github.com/EmilHernvall/dnsguide/blob/master/README.md) +* [**Rust**: _Writing Scalable Chat Service from Scratch_](https://nbaksalyar.github.io/2015/07/10/writing-chat-in-rust.html) +* [**Rust**: _WebGL + Rust: Basic Water Tutorial_](https://www.chinedufn.com/3d-webgl-basic-water-tutorial/) +* [**TypeScript**: _Tiny Package Manager: Learns how npm or Yarn works_](https://github.com/g-plane/tiny-package-manager) + +## Contribute +* Submissions welcome, just send a PR, or [create an issue](https://github.com/codecrafters-io/build-your-own-x/issues/new) +* Help us review [pending submissions](https://github.com/codecrafters-io/build-your-own-x/issues) by leaving comments and "reactions" + +## Origins & License + +[![CC0](https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg)](https://creativecommons.org/publicdomain/zero/1.0/) + +This repository is the work of [many contributors](https://github.com/codecrafters-io/build-your-own-x/graphs/contributors). It was started by [Daniel Stefanovic](https://github.com/danistefanovic), and is now maintained by [CodeCrafters, Inc.](https://codecrafters.io) To the extent possible under law, [CodeCrafters, Inc.](https://codecrafters.io) has waived all copyright and related or neighboring rights to this work. diff --git a/github_code/codecrafters-io__build-your-own-x/codecrafters-banner.png b/github_code/codecrafters-io__build-your-own-x/codecrafters-banner.png new file mode 100644 index 0000000000000000000000000000000000000000..ca3d318defce0359daf94b217cabec577698e5e9 --- /dev/null +++ b/github_code/codecrafters-io__build-your-own-x/codecrafters-banner.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2ee06b565f53528a7645b921a4fa76822a56b07581fcdc45c2fd4374e7871e4 +size 25061 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); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.ts new file mode 100644 index 0000000000000000000000000000000000000000..d4905269c1143a7ddc09c5986e4f68cd3a8a5d66 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/redirection.ts @@ -0,0 +1,174 @@ +import jwt from 'jsonwebtoken'; + +import { availableLangs } from '@freecodecamp/shared/config/i18n'; +import { allowedOrigins } from './allowed-origins.js'; + +// process.env.HOME_LOCATION is being used as a fallback here. If the one +// provided by the client is invalid we default to this. +import { HOME_LOCATION } from './env.js'; + +/** + * Get the returnTo value. + * + * @param encryptedParams - The encrypted parameters. + * @param secret - The secret key. + * @param _homeLocation - The home location. + * @returns The returnTo value. + */ +export function getReturnTo( + encryptedParams: string, + secret: jwt.Secret, + _homeLocation = process.env.HOME_LOCATION +) { + let params; + try { + params = jwt.verify(encryptedParams, secret); + } catch { + // something went wrong, use default params + params = { + returnTo: `${_homeLocation}/learn`, + origin: _homeLocation, + pathPrefix: '' + }; + } + + // @ts-expect-error - I'm working on it... + return normalizeParams(params, _homeLocation); +} + +type RedirectParams = { + returnTo: string; + origin: string; + pathPrefix: string; +}; + +/** + * Normalize the parameters, making they're valid. + * + * @param arg - The parameters to normalize. + * @param arg.returnTo - The returnTo value. + * @param arg.origin - The origin value. + * @param arg.pathPrefix - The pathPrefix value. + * @param _homeLocation - The home location. + * @returns The normalized parameters. + */ +export function normalizeParams( + { returnTo, origin, pathPrefix }: Partial, + _homeLocation = HOME_LOCATION +): RedirectParams { + // coerce to strings, just in case something weird and nefarious is happening + // TODO: validate, don't coerce + returnTo = '' + returnTo; + origin = '' + origin; + pathPrefix = '' + pathPrefix; + // TODO(Post-MVP): consider adding HOME_LOCATION in allowedOrigins to allow + // redirection to work in development. + // we add the '/' to prevent returns to + // www.freecodecamp.org.somewhere.else.com + if ( + !returnTo || + !allowedOrigins.some(allowed => returnTo?.startsWith(allowed + '/')) + ) { + returnTo = `${_homeLocation}/learn`; + origin = _homeLocation; + pathPrefix = ''; + } + if (!origin || !allowedOrigins.includes(origin)) { + returnTo = `${_homeLocation}/learn`; + origin = _homeLocation; + pathPrefix = ''; + } + pathPrefix = availableLangs.client.includes(pathPrefix) ? pathPrefix : ''; + return { returnTo, origin, pathPrefix }; +} + +/** + * Get the prefixed landing path. + * + * @param origin - The origin value. + * @param pathPrefix - The pathPrefix value. + * @returns The prefixed landing path. + */ +export function getPrefixedLandingPath(origin: string, pathPrefix?: string) { + const redirectPathSegment = pathPrefix ? `/${pathPrefix}` : ''; + return `${origin}${redirectPathSegment}`; +} + +function getParamsFromUrl( + url: string | undefined | null, + normalize: typeof normalizeParams +) { + // since we do not always redirect the user back to the page they were on + // we need client locale and origin to construct the redirect url. + let returnUrl; + try { + returnUrl = new URL(url ? url : HOME_LOCATION); + } catch (_e) { + returnUrl = new URL(HOME_LOCATION); + } + + const origin = returnUrl.origin; + // if this is not one of the client languages, validation will convert + // this to '' before it is used. + const pathPrefix = returnUrl.pathname.split('/')[1] ?? ''; + return normalize({ + // strip off any query parameters + returnTo: returnUrl.origin + returnUrl.pathname, + origin, + pathPrefix + }); +} + +/** + * Get the redirect parameters. + * + * @param req - A fastify Request. + * @param req.headers - The request headers. + * @param req.headers.referer - The referer header. + * @param _normalizeParams - The function to normalize the parameters. + * @returns The redirect parameters. + */ +export function getRedirectParams( + req: { headers: { referer?: string } }, + _normalizeParams = normalizeParams +): RedirectParams { + const url = req.headers['referer']; + return getParamsFromUrl(url, _normalizeParams); +} + +/** + * Get the redirect parameters after sign in flow. + * + * @param req - A fastify Request. + * @param req.cookies - The request cookies. + * @param req.unsignCookie - The function to unsign the cookie. + * @param _normalizeParams - The function to normalize the parameters. + * @returns The redirect parameters. + */ +export function getLoginRedirectParams( + req: { + cookies: Record; + unsignCookie: (rawValue: string) => { value: string | null }; + }, + _normalizeParams = normalizeParams +): RedirectParams { + const signedUrl = req.cookies['login-returnto']; + const url = signedUrl ? req.unsignCookie(signedUrl).value : null; + return getParamsFromUrl(url, _normalizeParams); +} + +/** + * Check if the redirect base and return URL have the same path. + * + * @param redirectBase - The redirect base URL. + * @param returnUrl - The return URL. + * @returns A boolean indicating whether the paths are the same. + */ +export function haveSamePath( + redirectBase: string | URL, + returnUrl: string | URL +) { + const base = new URL(redirectBase); + const url = new URL(returnUrl); + return base.pathname === url.pathname; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..76416fd541f86ab4c862e4aee47be513818a4320 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.test.ts @@ -0,0 +1,843 @@ +import type { ErrorEvent, Event, Log } from '@sentry/node'; +import { describe, expect, it, vi } from 'vitest'; + +import { + makeShouldSendLog, + makeTracesSampler, + scrubRedundantLogAttributes, + scrubRequestPii, + scrubSpanDescriptions +} from './sentry.js'; + +const makeLog = (overrides: Partial = {}): Log => ({ + level: 'info', + message: 'something happened', + attributes: {}, + ...overrides +}); + +describe('shouldSendLog', () => { + const shouldSendLog = makeShouldSendLog(1); + + it('drops the incoming request message regardless of level', () => { + expect(shouldSendLog(makeLog({ message: 'incoming request' }))).toBe(false); + expect( + shouldSendLog(makeLog({ message: 'incoming request', level: 'error' })) + ).toBe(false); + }); + + it('drops the fastify per-interface boot line by message prefix', () => { + expect( + shouldSendLog( + makeLog({ message: 'Server listening at http://127.0.0.1:3000' }) + ) + ).toBe(false); + expect( + shouldSendLog( + makeLog({ message: 'Server listening at http://[::1]:3000' }) + ) + ).toBe(false); + }); + + it('keeps the custom "API server started" boot log', () => { + expect( + shouldSendLog( + makeLog({ message: 'API server started', attributes: { audit: true } }) + ) + ).toBe(true); + }); + + it('drops debug logs from suppressed routes', () => { + expect( + shouldSendLog( + makeLog({ level: 'debug', attributes: { route: '/user/session-user' } }) + ) + ).toBe(false); + }); + + it('keeps debug logs on other routes', () => { + expect( + shouldSendLog( + makeLog({ level: 'debug', attributes: { route: '/some/route' } }) + ) + ).toBe(true); + }); + + it('keeps debug logs without a route', () => { + expect(shouldSendLog(makeLog({ level: 'debug' }))).toBe(true); + }); + + it('drops per-request framework lifecycle chatter regardless of route', () => { + for (const message of ['request completed', 'stream closed prematurely']) { + expect(shouldSendLog(makeLog({ message }))).toBe(false); + expect( + shouldSendLog( + makeLog({ message, attributes: { route: '/some/route' } }) + ) + ).toBe(false); + } + }); + + it('keeps request errored so response failures still reach Sentry', () => { + expect( + shouldSendLog(makeLog({ message: 'request errored', level: 'error' })) + ).toBe(true); + }); + + it('keeps non-info levels', () => { + for (const level of ['warn', 'error', 'fatal'] as const) { + expect(shouldSendLog(makeLog({ level }))).toBe(true); + } + }); + + it('keeps non-info levels even on a suppressed route', () => { + expect( + shouldSendLog( + makeLog({ level: 'error', attributes: { route: '/user/session-user' } }) + ) + ).toBe(true); + }); + + it('drops info logs from suppressed routes', () => { + expect( + shouldSendLog(makeLog({ attributes: { route: '/user/session-user' } })) + ).toBe(false); + }); + + it('keeps info logs on other routes', () => { + expect( + shouldSendLog(makeLog({ attributes: { route: '/some/route' } })) + ).toBe(true); + }); + + it('keeps info logs without a route', () => { + expect(shouldSendLog(makeLog())).toBe(true); + }); +}); + +describe('makeShouldSendLog — debug sampling', () => { + const debugLog = (overrides: Partial = {}): Log => + makeLog({ level: 'debug', ...overrides }); + + it('drops debug from suppressed routes even when the trace is sampled', () => { + expect( + makeShouldSendLog(1)( + debugLog({ + attributes: { route: '/status/ping', traceSampled: true } + }) + ) + ).toBe(false); + }); + + it('keeps debug whose trace is sampled regardless of rate', () => { + expect( + makeShouldSendLog(0)( + debugLog({ attributes: { traceId: 'abc', traceSampled: true } }) + ) + ).toBe(true); + }); + + it('drops ambient (unsampled-trace) debug at rate 0', () => { + expect( + makeShouldSendLog(0)(debugLog({ attributes: { traceId: 'abc' } })) + ).toBe(false); + expect(makeShouldSendLog(0)(debugLog())).toBe(false); + }); + + it('keeps ambient debug at rate 1', () => { + expect( + makeShouldSendLog(1)(debugLog({ attributes: { traceId: 'abc' } })) + ).toBe(true); + }); + + it('samples debug deterministically by traceId', () => { + const log = debugLog({ attributes: { traceId: 'deadbeef' } }); + const first = makeShouldSendLog(0.5)(log); + const second = makeShouldSendLog(0.5)(log); + expect(first).toBe(second); + }); + + it('keeps warn/error/fatal regardless of the debug rate', () => { + for (const level of ['warn', 'error', 'fatal'] as const) { + expect(makeShouldSendLog(0)(makeLog({ level }))).toBe(true); + } + }); +}); + +describe('makeShouldSendLog — info sampling', () => { + it('always keeps audit info logs even at a zero sample rate', () => { + expect( + makeShouldSendLog(1, 0)(makeLog({ attributes: { audit: true } })) + ).toBe(true); + }); + + it('always keeps audit info logs on an otherwise suppressed route', () => { + expect( + makeShouldSendLog( + 1, + 0 + )( + makeLog({ + attributes: { audit: true, route: '/some/route' } + }) + ) + ).toBe(true); + }); + + it('keeps audit info logs on a real suppressed route even at zero sample rates', () => { + expect( + makeShouldSendLog( + 0, + 0 + )( + makeLog({ + message: 'audit', + attributes: { audit: true, route: '/user/session-user' } + }) + ) + ).toBe(true); + }); + + it('keeps audit logs regardless of level, including debug on a suppressed route', () => { + expect( + makeShouldSendLog( + 0, + 0 + )( + makeLog({ + level: 'debug', + message: 'audit', + attributes: { audit: true, route: '/user/session-user' } + }) + ) + ).toBe(true); + }); + + it('drops non-audit info logs at a zero sample rate', () => { + expect( + makeShouldSendLog(1, 0)(makeLog({ attributes: { traceId: 'abc' } })) + ).toBe(false); + }); + + it('keeps non-audit info logs at a sample rate of 1', () => { + expect( + makeShouldSendLog(1, 1)(makeLog({ attributes: { traceId: 'abc' } })) + ).toBe(true); + }); + + it('keeps info whose trace is sampled regardless of the info rate', () => { + expect( + makeShouldSendLog( + 1, + 0 + )(makeLog({ attributes: { traceId: 'abc', traceSampled: true } })) + ).toBe(true); + }); + + it('samples non-audit info deterministically by traceId', () => { + const log = makeLog({ attributes: { traceId: 'deadbeef' } }); + const first = makeShouldSendLog(1, 0.5)(log); + const second = makeShouldSendLog(1, 0.5)(log); + expect(first).toBe(second); + }); + + it('never touches warn/error/fatal regardless of the info rate', () => { + for (const level of ['warn', 'error', 'fatal'] as const) { + expect(makeShouldSendLog(1, 0)(makeLog({ level }))).toBe(true); + } + }); + + it('defaults to a sample rate of 1 when none is given', () => { + expect( + makeShouldSendLog(1)(makeLog({ attributes: { traceId: 'abc' } })) + ).toBe(true); + }); +}); + +describe('scrubRedundantLogAttributes', () => { + it('drops pino bindings duplicated by Sentry-native fields', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + msg: 'hello', + 'pino.logger.level': 30, + message: 'hello', + trace_id: 'abc', + level: 'info', + severity_number: 9, + userId: 'user-42' + } + }) + ); + + expect(result.attributes).toEqual({ + message: 'hello', + trace_id: 'abc', + level: 'info', + severity_number: 9, + userId: 'user-42' + }); + }); + + it('is a no-op when there are no attributes', () => { + expect( + scrubRedundantLogAttributes(makeLog({ attributes: undefined })) + ).toEqual(makeLog({ attributes: undefined })); + }); + + it('redacts secret- and payment-credential-shaped attribute keys', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + audit: true, + userId: 'user-42', + email: 'a@b.com', + client_secret: 'pi_secret_LEAK', + authorization: 'Bearer sk_live_LEAK', + password: 'hunter2', + api_key: 'key_LEAK', + token: 'tok_LEAK', + 'err.raw.client_secret': 'nested_LEAK' + } + }) + ); + + expect(result.attributes).toEqual({ + audit: true, + userId: 'user-42', + email: 'a@b.com', + client_secret: '[REDACTED]', + authorization: '[REDACTED]', + password: '[REDACTED]', + api_key: '[REDACTED]', + token: '[REDACTED]', + 'err.raw.client_secret': '[REDACTED]' + }); + }); + + it('redacts secrets nested inside object attribute values', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + err: { message: 'boom', raw: { client_secret: 'LEAK' } } + } + }) + ); + + expect(JSON.stringify(result.attributes)).not.toContain('LEAK'); + }); + + it('keeps intentional PII (email, ip, country) on an audit log', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + audit: true, + email: 'a@b.com', + ip: '1.2.3.4', + country: 'US' + } + }) + ); + + expect(result.attributes).toEqual({ + audit: true, + email: 'a@b.com', + ip: '1.2.3.4', + country: 'US' + }); + }); + + it('redacts email but keeps ip/country on a non-audit log', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { email: 'a@b.com', ip: '1.2.3.4', country: 'US' } + }) + ); + + expect(result.attributes).toEqual({ + email: '[REDACTED]', + ip: '1.2.3.4', + country: 'US' + }); + }); + + it('redacts secret-token-shaped substrings found inside a string value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { note: 'leaked key sk_live_ABC123 in the log' } + }) + ); + + expect(result.attributes?.note).toBe('leaked key [REDACTED] in the log'); + }); + + it('redacts an email substring in a non-audit log string value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ attributes: { note: 'contact a@b.com for help' } }) + ); + + expect(result.attributes?.note).toBe('contact [REDACTED] for help'); + }); + + it('keeps an email substring in an audit log string value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ attributes: { audit: true, note: 'contact a@b.com for help' } }) + ); + + expect(result.attributes?.note).toBe('contact a@b.com for help'); + }); + + it('redacts a bare email attribute value on a non-audit log', () => { + const result = scrubRedundantLogAttributes( + makeLog({ attributes: { email: 'keep@me.com' } }) + ); + + expect(result.attributes?.email).toBe('[REDACTED]'); + }); + + it('redacts a bare JWT substring in a log string value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + note: 'token eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.dozjgNryP4J3jVmNHl0w5 rest' + } + }) + ); + + expect(result.attributes?.note).toBe('token [REDACTED] rest'); + }); + + it('redacts a lowercase bearer token substring in a log string value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { + note: 'auth bearer abcdefghijklmnopqrstuvwxyz012345 done' + } + }) + ); + + expect(result.attributes?.note).toBe('auth [REDACTED] done'); + }); + + it('fail-safe redacts a Logs attribute value nested past the depth cap', () => { + const buildNested = (depth: number, leaf: unknown): unknown => + depth <= 0 ? leaf : { nested: buildNested(depth - 1, leaf) }; + + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: buildNested(9, 'deep-plain-value') as Record< + string, + unknown + > + }) + ); + + const serialized = JSON.stringify(result.attributes); + expect(serialized).toContain('[REDACTED]'); + expect(serialized).not.toContain('deep-plain-value'); + }); + + it('redacts a secret-shaped substring in the log message', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + message: 'auth bearer abcdefghijklmnopqrstuvwxyz012345 failed' + }) + ); + + expect(result.message).toBe('auth [REDACTED] failed'); + }); + + it('redacts an email in a non-audit log message', () => { + const result = scrubRedundantLogAttributes( + makeLog({ message: 'error for user@example.com occurred' }) + ); + + expect(result.message).toBe('error for [REDACTED] occurred'); + }); + + it('keeps an email in an audit log message', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + message: 'donation outreach to user@example.com queued', + attributes: { audit: true } + }) + ); + + expect(result.message).toBe('donation outreach to user@example.com queued'); + }); + + it('redacts a Stripe webhook secret in an attribute value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ attributes: { note: 'sig whsec_abcdef0123456789 ok' } }) + ); + + expect(result.attributes?.note).toBe('sig [REDACTED] ok'); + }); + + it('redacts a Basic auth credential in an attribute value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { note: 'auth Basic dXNlcjpodW50ZXIyc2VjcmV0 end' } + }) + ); + + expect(result.attributes?.note).toBe('auth [REDACTED] end'); + }); + + it('scrubs a pathological JWT-prefix string without catastrophic backtracking', () => { + const attack = 'eyJ'.repeat(80000); + const result = scrubRedundantLogAttributes( + makeLog({ attributes: { note: attack } }) + ); + + expect(typeof result.attributes?.note).toBe('string'); + }); + + it('redacts a secret in a boxed-String (parameterized) message', () => { + const message = Object.assign( + new String('issued token sk_live_BOXEDLEAK now'), + { + __sentry_template_string__: 'issued token %s now', + __sentry_template_values__: ['sk_live_BOXEDLEAK'] + } + ) as unknown as Log['message']; + + const result = scrubRedundantLogAttributes(makeLog({ message })); + + expect(String(result.message)).toBe('issued token [REDACTED] now'); + }); + + it('redacts secrets nested inside an array attribute value', () => { + const result = scrubRedundantLogAttributes( + makeLog({ + attributes: { items: [{ list: [{ client_secret: 'ARRLEAK' }] }] } + }) + ); + + expect(JSON.stringify(result.attributes)).not.toContain('ARRLEAK'); + }); +}); + +describe('scrubRequestPii', () => { + const eventWithRequest = (request: ErrorEvent['request']): ErrorEvent => ({ + type: undefined, + request + }); + + it('is a no-op when the event has no request', () => { + const event = eventWithRequest(undefined); + expect(scrubRequestPii(event)).toEqual(event); + }); + + it('strips the query string entirely and the query portion of the url', () => { + const result = scrubRequestPii( + eventWithRequest({ + url: 'https://api.freecodecamp.org/donate?code=abc123', + query_string: 'code=abc123' + }) + ); + + expect(result.request?.query_string).toBeUndefined(); + expect(result.request?.url).toBe('https://api.freecodecamp.org/donate'); + }); + + it('redacts an email embedded in the url path', () => { + const result = scrubRequestPii( + eventWithRequest({ url: 'https://api.freecodecamp.org/u/foo@bar.com' }) + ); + + expect(result.request?.url).toBe( + 'https://api.freecodecamp.org/u/[REDACTED]' + ); + }); + + it('redacts PII- and secret-shaped keys from the request body', () => { + const result = scrubRequestPii( + eventWithRequest({ + data: { + paymentMethodId: 'pm_12345', + email: 'a@b.com', + name: 'Camper Bot', + code: 'oauth-code', + state: 'oauth-state', + amount: 500 + } + }) + ); + + expect(result.request?.data).toEqual({ + paymentMethodId: '[REDACTED]', + email: '[REDACTED]', + name: '[REDACTED]', + code: '[REDACTED]', + state: '[REDACTED]', + amount: 500 + }); + }); + + it('redacts sensitive request headers', () => { + const result = scrubRequestPii( + eventWithRequest({ + headers: { authorization: 'Bearer sk_live_LEAK', 'user-agent': 'x' } + }) + ); + + expect(result.request?.headers).toEqual({ + authorization: '[REDACTED]', + 'user-agent': 'x' + }); + }); + + it('redacts email and paymentMethodId when request data is a raw JSON string', () => { + const result = scrubRequestPii( + eventWithRequest({ + data: JSON.stringify({ + email: 'a@b.com', + paymentMethodId: 'pm_123', + amount: 5 + }) + }) + ); + + const data = result.request?.data; + const parsed = typeof data === 'string' ? JSON.parse(data) : data; + + expect(parsed).toEqual({ + email: '[REDACTED]', + paymentMethodId: '[REDACTED]', + amount: 5 + }); + }); + + it('always strips cookies regardless of their content', () => { + const result = scrubRequestPii( + eventWithRequest({ cookies: { jwt_access_token: 'secret' } }) + ); + + expect(result.request?.cookies).toBeUndefined(); + }); + + it('redacts an email found inside a free-text data value', () => { + const result = scrubRequestPii( + eventWithRequest({ data: { about: 'reach me at me@example.com' } }) + ); + + expect(result.request?.data).toEqual({ + about: 'reach me at [REDACTED]' + }); + }); + + it('redacts a secret-shaped value in a header whose key is not sensitive', () => { + const result = scrubRequestPii( + eventWithRequest({ + headers: { 'x-custom': 'Bearer abcdefghijklmnopqrstuvwxyz012345' } + }) + ); + + expect(result.request?.headers).toEqual({ 'x-custom': '[REDACTED]' }); + }); + + it('fail-safe redacts a value nested past the depth cap', () => { + const buildNested = (depth: number, leaf: unknown): unknown => + depth <= 0 ? leaf : { nested: buildNested(depth - 1, leaf) }; + + const result = scrubRequestPii( + eventWithRequest({ data: buildNested(9, 'just-a-plain-value') }) + ); + + const serialized = JSON.stringify(result.request?.data); + expect(serialized).toContain('[REDACTED]'); + expect(serialized).not.toContain('just-a-plain-value'); + }); + + it('redacts an email in the exception message and in extra', () => { + const event: ErrorEvent = { + type: undefined, + exception: { values: [{ value: 'failed for user x@y.com' }] }, + extra: { email: 'z@z.com' } + }; + + const result = scrubRequestPii(event); + + expect(result.exception?.values?.[0]?.value).toBe( + 'failed for user [REDACTED]' + ); + expect(result.extra?.email).toBe('[REDACTED]'); + }); + + it('redacts secret-shaped local variables captured in stack frames', () => { + const event: ErrorEvent = { + type: undefined, + exception: { + values: [ + { + value: 'boom', + stacktrace: { + frames: [ + { + function: 'doThing', + vars: { + jwt_access_token: 'signed-cookie-value', + note: 'holding sk_live_FRAMELEAK here', + userId: 'u1' + } + } + ] + } + } + ] + } + }; + + const result = scrubRequestPii(event); + const vars = result.exception?.values?.[0]?.stacktrace?.frames?.[0]?.vars; + + expect(vars?.jwt_access_token).toBe('[REDACTED]'); + expect(vars?.note).toBe('holding [REDACTED] here'); + expect(vars?.userId).toBe('u1'); + }); + + it('redacts secret-shaped fields on event.user but keeps id and email', () => { + const event: ErrorEvent = { + type: undefined, + user: { id: 'u1', email: 'donor@example.com', apiKey: 'sk_live_USERLEAK' } + }; + + const result = scrubRequestPii(event); + + expect(result.user?.id).toBe('u1'); + expect(result.user?.email).toBe('donor@example.com'); + expect((result.user as Record).apiKey).toBe('[REDACTED]'); + }); + + it('strips request.env entirely', () => { + const result = scrubRequestPii( + eventWithRequest({ + env: { REMOTE_USER: 'a@b.com', SERVER_SECRET: 'sk_live_ENVLEAK' } + }) + ); + + expect(result.request?.env).toBeUndefined(); + }); + + it('redacts secret-shaped data in breadcrumbs', () => { + const event: ErrorEvent = { + type: undefined, + breadcrumbs: [ + { + category: 'http', + data: { + url: 'https://api.stripe.com?key=sk_live_BCLEAK', + token: 'ghp_BCLEAK' + } + } + ] + }; + + const result = scrubRequestPii(event); + const data = result.breadcrumbs?.[0]?.data; + + expect(data?.token).toBe('[REDACTED]'); + expect(data?.url).toBe('https://api.stripe.com?key=[REDACTED]'); + }); + + it('scrubs a 1MB JWT-prefix body within the ReDoS budget', () => { + const result = scrubRequestPii( + eventWithRequest({ data: 'eyJ'.repeat(333333) }) + ); + + expect(typeof result.request?.data).toBe('string'); + }); +}); + +describe('makeTracesSampler', () => { + const context = (name: string) => ({ + name, + inheritOrSampleWith: vi.fn((fallback: number) => fallback) + }); + + it('drops health check transactions', () => { + expect(makeTracesSampler(0.1)(context('GET /status/ping'))).toBe(0); + expect(makeTracesSampler(0.1)(context('GET /status/ready'))).toBe(0); + }); + + it('samples other transactions with the configured rate', () => { + const ctx = context('GET /user/session-user'); + expect(makeTracesSampler(0.1)(ctx)).toBe(0.1); + expect(ctx.inheritOrSampleWith).toHaveBeenCalledWith(0.1); + }); +}); + +describe('scrubSpanDescriptions', () => { + const makeTxn = ( + spans: Array<{ description?: string; data?: Record }> + ): Event => + ({ + type: 'transaction', + spans: spans.map(({ description, data }) => ({ + span_id: 'a', + trace_id: 'b', + start_timestamp: 0, + description, + data: data ?? {} + })) + }) as unknown as Event; + + it('replaces a Mongo ObjectId literal in a span description with a placeholder', () => { + const [span] = + scrubSpanDescriptions( + makeTxn([ + { + description: + 'aggregate [{"$match":{"_id":ObjectId("58dfb02b565f48223c4da7b5")}}]' + } + ]) + ).spans ?? []; + expect(span?.description).toBe( + 'aggregate [{"$match":{"_id":ObjectId("?")}}]' + ); + }); + + it('produces identical descriptions for spans differing only by ObjectId', () => { + const scrub = (id: string): string | undefined => + scrubSpanDescriptions( + makeTxn([{ description: `find ObjectId("${id}")` }]) + ).spans?.[0]?.description; + expect(scrub('58dfb02b565f48223c4da7b5')).toBe( + scrub('58f2a1dc23aadf34519c26ba') + ); + }); + + it('scrubs the db.query.text span attribute', () => { + const [span] = + scrubSpanDescriptions( + makeTxn([ + { + description: 'q', + data: { 'db.query.text': 'ObjectId("58dfb02b565f48223c4da7b5")' } + } + ]) + ).spans ?? []; + expect(span?.data['db.query.text']).toBe('ObjectId("?")'); + }); + + it('replaces an ISODate literal', () => { + const [span] = + scrubSpanDescriptions( + makeTxn([{ description: 'ISODate("2026-07-13T00:00:00.000Z")' }]) + ).spans ?? []; + expect(span?.description).toBe('ISODate("?")'); + }); + + it('leaves a non-Mongo span description untouched', () => { + const [span] = + scrubSpanDescriptions(makeTxn([{ description: 'GET /learn' }])).spans ?? + []; + expect(span?.description).toBe('GET /learn'); + }); + + it('is a no-op when the event has no spans', () => { + const event = { type: 'transaction' } as unknown as Event; + expect(scrubSpanDescriptions(event).spans).toBeUndefined(); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ee772aaae7409a9904b98c9c088ec768d9fda43 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/sentry.ts @@ -0,0 +1,343 @@ +import type { ErrorEvent, Event, Log, RequestEventData } from '@sentry/node'; + +const DROPPED_LOG_MESSAGES = new Set([ + 'incoming request', + 'request completed', + 'stream closed prematurely' +]); + +const DROPPED_LOG_MESSAGE_PREFIXES = ['Server listening at']; + +const isDroppedLogMessage = (message: Log['message']): boolean => + typeof message === 'string' && + (DROPPED_LOG_MESSAGES.has(message) || + DROPPED_LOG_MESSAGE_PREFIXES.some(prefix => message.startsWith(prefix))); + +// Hot / health routes whose routine info+debug chatter is filtered out of +// Sentry entirely (replaces the old per-route sample rates). warn/error/fatal +// on these routes is still forwarded. +const DROPPED_LOG_ROUTES = new Set([ + '/user/session-user', + '/status/ping', + '/status/ready' +]); + +const routeOf = (log: Log): string | undefined => + typeof log.attributes?.route === 'string' ? log.attributes.route : undefined; + +const traceIdOf = (log: Log): string | undefined => + typeof log.attributes?.traceId === 'string' + ? log.attributes.traceId + : undefined; + +const traceIsSampled = (log: Log): boolean => + log.attributes?.traceSampled === true; + +const isAuditLog = (log: Log): boolean => log.attributes?.audit === true; + +const hashUnit = (value: string): number => { + let hash = 2166136261; + for (let i = 0; i < value.length; i++) { + hash ^= value.charCodeAt(i); + hash = Math.imul(hash, 16777619); + } + return (hash >>> 0) / 2 ** 32; +}; + +const shouldSendDebug = (log: Log, debugRate: number): boolean => { + const route = routeOf(log); + if (route !== undefined && DROPPED_LOG_ROUTES.has(route)) return false; + if (traceIsSampled(log)) return true; + const traceId = traceIdOf(log); + const roll = traceId !== undefined ? hashUnit(traceId) : Math.random(); + return roll < debugRate; +}; + +const shouldSendInfo = (log: Log, infoRate: number): boolean => { + if (traceIsSampled(log)) return true; + const traceId = traceIdOf(log); + const roll = traceId !== undefined ? hashUnit(traceId) : Math.random(); + return roll < infoRate; +}; + +/** + * Build the beforeSendLog filter. Warn, error and fatal always pass. Info + * passes unless it is on a hot or health route, and is otherwise sampled at + * the given info rate — unless it carries `audit: true`, which always + * passes. Debug is trace-aware: it is kept in full for a sampled trace, + * otherwise sampled deterministically by trace id at the given debug rate. + * + * @param debugRate The sample rate for debug logs not on a sampled trace. + * @param infoRate The sample rate for non-audit info logs not on a sampled + * trace. Defaults to 1 (send all), matching the pre-sampling behavior. + * @returns A predicate deciding whether a log is forwarded to Sentry. + */ +export const makeShouldSendLog = + (debugRate: number, infoRate = 1) => + (log: Log): boolean => { + if (isDroppedLogMessage(log.message)) return false; + if (isAuditLog(log)) return true; + if (log.level === 'debug') return shouldSendDebug(log, debugRate); + if (log.level !== 'info') return true; + const route = routeOf(log); + if (route !== undefined && DROPPED_LOG_ROUTES.has(route)) return false; + return shouldSendInfo(log, infoRate); + }; + +const REDUNDANT_LOG_ATTRIBUTES = ['msg', 'pino.logger.level'] as const; + +const SECRET_KEY_PATTERN = + /(client_?secret|secret|passwd|password|authorization|cookie|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|\bjwt\b|session[-_]?id|card[-_]?number|\bcvc\b|\bcvv\b|\btoken\b)/i; + +const ISSUE_REQUEST_KEY_PATTERN = + /(client_?secret|secret|passwd|password|authorization|cookie|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|\bjwt\b|session[-_]?id|card[-_]?number|\bcvc\b|\bcvv\b|\btoken\b|email|name|payment_?method_?id|\bcode\b|\bstate\b)/i; + +const VALUE_SECRET_PATTERN = + /\bsk_(?:live|test)_[A-Za-z0-9]+\b|\bwhsec_[A-Za-z0-9]+\b|\bghp_[A-Za-z0-9]+\b|\bgithub_pat_[A-Za-z0-9_]+\b|\bxox[baprs]-[A-Za-z0-9-]+\b|\beyJ[A-Za-z0-9_-]{1,1024}\.[A-Za-z0-9_-]{1,8192}\.[A-Za-z0-9_-]{1,1024}|[Bb](?:earer|asic) [A-Za-z0-9._~+/=-]{16,4096}/g; + +const EMAIL_PATTERN = + /\b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}/g; + +const MAX_SCRUB_LENGTH = 200_000; + +const redactSecretSubstrings = (value: string): string => + value.length > MAX_SCRUB_LENGTH + ? value + : value.replace(VALUE_SECRET_PATTERN, '[REDACTED]'); + +const redactIssueSubstrings = (value: string): string => + value.length > MAX_SCRUB_LENGTH + ? value + : value + .replace(VALUE_SECRET_PATTERN, '[REDACTED]') + .replace(EMAIL_PATTERN, '[REDACTED]'); + +const redactDeep = ( + value: unknown, + keyPattern: RegExp, + scrubValue: (v: string) => string, + depth = 0, + redactOnDepthCap = false +): unknown => { + if (value === null) return value; + if (depth > 6) return redactOnDepthCap ? '[REDACTED]' : value; + if (typeof value === 'string') return scrubValue(value); + if (typeof value !== 'object') return value; + if (Array.isArray(value)) + return value.map(entry => + redactDeep(entry, keyPattern, scrubValue, depth + 1, redactOnDepthCap) + ); + const out: Record = {}; + for (const [key, entry] of Object.entries(value as Record)) { + out[key] = keyPattern.test(key) + ? '[REDACTED]' + : redactDeep(entry, keyPattern, scrubValue, depth + 1, redactOnDepthCap); + } + return out; +}; + +/** + * Remove pino bindings that Sentry already records as native log fields, then + * redact secret- or payment-credential-shaped values. Email addresses are also + * redacted unless the log carries `audit: true`, the marker for the sanctioned + * identifier buckets (donation outreach, duplicate-account) where support needs + * the email to resolve the case. + * + * @param log The log entry from the SDK. + * @returns The same log with redundant attributes removed and secrets redacted. + */ +export const scrubRedundantLogAttributes = (log: Log): Log => { + const scrubValue = + log.attributes?.audit === true + ? redactSecretSubstrings + : redactIssueSubstrings; + if (log.message != null) { + log.message = scrubValue(String(log.message)); + } + if (log.attributes == null) return log; + for (const key of REDUNDANT_LOG_ATTRIBUTES) { + delete log.attributes[key]; + } + log.attributes = redactDeep( + log.attributes, + SECRET_KEY_PATTERN, + scrubValue, + 0, + true + ) as typeof log.attributes; + return log; +}; + +const stripQueryFromUrl = (url: string): string => url.split('?', 1)[0] ?? url; + +const redactHeaders = ( + headers: Record +): Record => { + const out: Record = {}; + for (const [key, value] of Object.entries(headers)) { + out[key] = ISSUE_REQUEST_KEY_PATTERN.test(key) + ? '[REDACTED]' + : redactIssueSubstrings(value); + } + return out; +}; + +const scrubIssueBody = (data: unknown): unknown => { + if (typeof data === 'string') { + try { + const parsed: unknown = JSON.parse(data); + return JSON.stringify( + redactDeep( + parsed, + ISSUE_REQUEST_KEY_PATTERN, + redactIssueSubstrings, + 0, + true + ) + ); + } catch { + return redactIssueSubstrings(data); + } + } + return redactDeep( + data, + ISSUE_REQUEST_KEY_PATTERN, + redactIssueSubstrings, + 0, + true + ); +}; + +// eslint-disable-next-line jsdoc/require-jsdoc +export const scrubRequestPii = (event: ErrorEvent): ErrorEvent => { + const out: ErrorEvent = { ...event }; + const { request } = event; + + if (request != null) { + const scrubbed: RequestEventData = { ...request }; + delete scrubbed.query_string; + delete scrubbed.cookies; + delete scrubbed.env; + if (scrubbed.url != null) { + scrubbed.url = redactIssueSubstrings(stripQueryFromUrl(scrubbed.url)); + } + if (scrubbed.data != null) { + scrubbed.data = scrubIssueBody(scrubbed.data); + } + if (scrubbed.headers != null) { + scrubbed.headers = redactHeaders(scrubbed.headers); + } + out.request = scrubbed; + } + + if (out.exception?.values) { + out.exception = { + ...out.exception, + values: out.exception.values.map(value => { + const next = { ...value }; + if (typeof next.value === 'string') { + next.value = redactIssueSubstrings(next.value); + } + if (next.stacktrace?.frames) { + next.stacktrace = { + ...next.stacktrace, + frames: next.stacktrace.frames.map(frame => + frame.vars == null + ? frame + : { + ...frame, + vars: redactDeep( + frame.vars, + ISSUE_REQUEST_KEY_PATTERN, + redactIssueSubstrings, + 0, + true + ) as typeof frame.vars + } + ) + }; + } + return next; + }) + }; + } + + if (out.extra !== undefined) { + out.extra = redactDeep( + out.extra, + ISSUE_REQUEST_KEY_PATTERN, + redactIssueSubstrings, + 0, + true + ) as ErrorEvent['extra']; + } + + if (out.user != null) { + out.user = redactDeep( + out.user, + SECRET_KEY_PATTERN, + redactSecretSubstrings, + 0, + true + ) as ErrorEvent['user']; + } + + if (out.breadcrumbs) { + out.breadcrumbs = out.breadcrumbs.map(breadcrumb => + breadcrumb.data == null + ? breadcrumb + : { + ...breadcrumb, + data: redactDeep( + breadcrumb.data, + ISSUE_REQUEST_KEY_PATTERN, + redactIssueSubstrings, + 0, + true + ) as typeof breadcrumb.data + } + ); + } + + return out; +}; + +const MONGO_OBJECT_ID_PATTERN = /ObjectId\("[0-9a-f]{24}"\)/g; +const MONGO_ISO_DATE_PATTERN = /ISODate\("[^"]+"\)/g; + +const scrubMongoLiterals = (text: string): string => + text + .replace(MONGO_OBJECT_ID_PATTERN, 'ObjectId("?")') + .replace(MONGO_ISO_DATE_PATTERN, 'ISODate("?")'); + +// workaround: getsentry/sentry#40650 — prismaIntegration sets the DB span description to raw query text, so a literal ObjectId splits the N+1 fingerprint into one issue group per user +// eslint-disable-next-line jsdoc/require-jsdoc +export const scrubSpanDescriptions = (event: E): E => { + for (const span of event.spans ?? []) { + if (typeof span.description === 'string') { + span.description = scrubMongoLiterals(span.description); + } + const dbQueryText = span.data['db.query.text']; + if (typeof dbQueryText === 'string') { + span.data['db.query.text'] = scrubMongoLiterals(dbQueryText); + } + } + return event; +}; + +/** + * Build a traces sampler that drops health check transactions. + * + * @param rate The sample rate for all other transactions. + * @returns The sampler for Sentry.init. + */ +export const makeTracesSampler = + (rate: number) => + (context: { + name: string; + inheritOrSampleWith: (fallbackSampleRate: number) => number; + }): number => + context.name.includes('/status/ping') || + context.name.includes('/status/ready') + ? 0 + : context.inheritOrSampleWith(rate); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..412843f0b8440161bc68247939a046bb25e2657e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.test.ts @@ -0,0 +1,79 @@ +import { describe, test, expect, vi } from 'vitest'; + +vi.useFakeTimers(); +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ +import { createAccessToken, createAuthToken, isExpired } from './tokens.js'; + +describe('createAccessToken', () => { + test('creates an object with id, ttl, created and userId', () => { + const userId = 'abc'; + + const actual = createAccessToken(userId); + + expect(actual).toStrictEqual({ + id: expect.stringMatching(/[a-zA-Z0-9]{64}/), + ttl: 77760000000, + created: expect.stringMatching( + /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/ + ), + userId + }); + }); + + test('sets the ttl, defaulting to 77760000000 ms', () => { + const userId = 'abc'; + const ttl = 123; + const actual = createAccessToken(userId, ttl); + + expect(actual.ttl).toBe(ttl); + expect(createAccessToken(userId).ttl).toBe(77760000000); + }); +}); + +describe('createAuthToken', () => { + test('creates an object with id, ttl, created and userId', () => { + const userId = 'abc'; + + const actual = createAuthToken(userId); + + expect(actual).toStrictEqual({ + id: expect.stringMatching(/[a-zA-Z0-9]{64}/), + ttl: 900000, + created: expect.stringMatching( + /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/ + ), + userId + }); + }); + + test('sets the ttl, defaulting to 900000 ms', () => { + const userId = 'abc'; + const ttl = 123; + const actual = createAuthToken(userId, ttl); + + expect(actual.ttl).toBe(ttl); + expect(createAuthToken(userId).ttl).toBe(900000); + }); +}); + +describe('isExpired', () => { + test('returns true if the token expiry date is in the past', () => { + const token = createAccessToken('abc', 1000); + expect(isExpired(token)).toBe(false); + vi.advanceTimersByTime(500); + expect(isExpired(token)).toBe(false); + vi.advanceTimersByTime(500); + expect(isExpired(token)).toBe(false); + vi.advanceTimersByTime(1); + expect(isExpired(token)).toBe(true); + }); + + test('handles tokens with Date values for created', () => { + const token = { ...createAccessToken('abc', 2000), created: new Date() }; + expect(isExpired(token)).toBe(false); + vi.advanceTimersByTime(2000); + expect(isExpired(token)).toBe(false); + vi.advanceTimersByTime(1); + expect(isExpired(token)).toBe(true); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.ts new file mode 100644 index 0000000000000000000000000000000000000000..fb7f02f0486e9dbda438139a00ae9e9d0d668975 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/tokens.ts @@ -0,0 +1,68 @@ +import jwt from 'jsonwebtoken'; +import { customNanoid } from './ids.js'; + +import { JWT_SECRET } from './env.js'; + +/** + * Encode an id into a JWT (the naming suggests it's a user token, but it's the + * id of the UserToken document). + * @param userToken A token id to encode. + * @returns An encoded object with the userToken property. + */ +export function encodeUserToken(userToken: string): string { + return jwt.sign({ userToken }, JWT_SECRET); +} + +export type Token = { + userId: string; + id: string; + ttl: number; + created: string; +}; + +type DbToken = { + userId: string; + id: string; + ttl: number; + created: Date; +}; + +/** + * Creates an access token. + * @param userId The user ID as a string (yes, it's an ObjectID, but it will be serialized to a string anyway). + * @param ttl The time to live for the token in milliseconds (default: 77760000000). + * @returns The access token. + */ +export const createAccessToken = (userId: string, ttl?: number): Token => { + return { + userId, + id: customNanoid(), + ttl: ttl ?? 77760000000, + created: new Date().toISOString() + }; +}; + +/** + * Creates an auth token. + * @param userId The user ID as a string (yes, it's an ObjectID, but it will be serialized to a string anyway). + * @param ttl The time to live for the token in milliseconds (default: 900000 aka 15 minutes). + * @returns The access token. + */ +export const createAuthToken = (userId: string, ttl?: number): Token => { + return { + userId, + id: customNanoid(), + ttl: ttl ?? 900000, + created: new Date().toISOString() + }; +}; + +/** + * Check if an access token has expired. + * @param token The access token to check. + * @returns True if the token has expired, false otherwise. + */ +export const isExpired = (token: Token | DbToken): boolean => { + const created = new Date(token.created); + return Date.now() > created.getTime() + token.ttl; +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5fe3587a1c22f637d99035d44e5d6267b43073eb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { inLastFiveMinutes } from './validate-donation.js'; + +describe('inLastFiveMinutes', () => { + beforeAll(() => { + vi.useFakeTimers(); + }); + + afterAll(() => { + vi.useRealTimers(); + }); + + it('should return true if the timestamp is within the last five minutes', () => { + const currentTimestamp = Math.floor(Date.now() / 1000); + const recentTimestamp = currentTimestamp - 100; + expect(inLastFiveMinutes(recentTimestamp)).toBe(true); + }); + + it('should return false if the timestamp is more than five minutes ago', () => { + const currentTimestamp = Math.floor(Date.now() / 1000); + const oldTimestamp = currentTimestamp - 400; + expect(inLastFiveMinutes(oldTimestamp)).toBe(false); + }); + + it('should return true if the timestamp is exactly five minutes ago', () => { + const currentTimestamp = Math.floor(Date.now() / 1000); + const exactTimestamp = currentTimestamp - 300; + expect(inLastFiveMinutes(exactTimestamp)).toBe(true); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.ts new file mode 100644 index 0000000000000000000000000000000000000000..d51daaecc0a374596b8b8e4466503c7ba0be7f51 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validate-donation.ts @@ -0,0 +1,10 @@ +/** + * Checks if a timestamp was created within five minutes. + * @param unixTimestamp - A unix timestamp . + * @returns - The generated email template. + */ +export const inLastFiveMinutes = (unixTimestamp: number) => { + const currentTimestamp = Math.floor(Date.now() / 1000); + const timeDifference = currentTimestamp - unixTimestamp; + return timeDifference <= 300; // 300 seconds is 5 minutes +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce0d6832755bdf82b1b346d770e44e2471463952 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.test.ts @@ -0,0 +1,17 @@ +import { describe, it, expect } from 'vitest'; +import { isObjectID } from './validation.js'; + +describe('Validation', () => { + describe('isObjectID', () => { + it('returns true for valid ObjectIDs', () => { + expect(isObjectID('5f1e0f3b5d2c12b0b8f7a6b9')).toBe(true); + }); + + it('returns false for invalid ObjectIDs', () => { + expect(isObjectID('5f1e0f3b5d2c12b0b8f7a6b')).toBe(false); + expect(isObjectID('5f1e0f3b5d2c12b0b8f7a6b99')).toBe(false); + expect(isObjectID('5f1e0f3b5d2c12b0b8f7a6b-')).toBe(false); + expect(isObjectID(undefined)).toBe(false); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.ts b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..6c57ec457f0d342c588cae6a8ff50efe8bd935aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/src/utils/validation.ts @@ -0,0 +1,64 @@ +import { ObjectId } from 'bson'; +import assert from 'node:assert'; + +// This is trivial, but makes it simple to refactor if we swap monogodb for +// bson, say. + +/** + * Checks if a string is a valid MongoDB ObjectID. + * @param id A string to check. + * @returns A boolean indicating if the string is a valid MongoDB ObjectID. + */ +export const isObjectID = (id?: string): boolean => + id ? ObjectId.isValid(id) : false; + +// Refer : http://stackoverflow.com/a/430240/1932901 +/** + * Sanitizes a input by removing HTML tags. + * @deprecated + * @param value A string to sanitize. + * @returns A string with HTML tags removed. + */ +export const trimTags = (value: string): string => { + const tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*'; + const tagOrComment = new RegExp( + '<(?:' + + // Comment body. + '!--(?:(?:-*[^->])*--+|-?)' + + // Special "raw text" elements whose content should be elided. + '|script\\b' + + tagBody + + '>[\\s\\S]*?[\\s\\S]*?', + 'gi' + ); + let rawValue; + do { + rawValue = value; + value = value.replace(tagOrComment, ''); + } while (value !== rawValue); + + return value.replace(/` collections. +import { PrismaClient } from '@prisma/client'; +import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library.js'; +import { MONGOHQ_URL } from '../../../src/utils/env.js'; + +const prisma = new PrismaClient({ + datasources: { + db: { + url: MONGOHQ_URL + } + } +}); + +async function main() { + await prisma.$connect(); + try { + const examEnvironmentExam = await prisma.examEnvironmentExam.findMany(); + const examEnvironmentGeneratedExam = + await prisma.examEnvironmentGeneratedExam.findMany(); + const examEnvironmentExamAttempt = + await prisma.examEnvironmentExamAttempt.findMany(); + + console.log('Number of exams:', examEnvironmentExam.length); + console.log( + 'Number of generated exams:', + examEnvironmentGeneratedExam.length + ); + console.log('Number of exam attempts:', examEnvironmentExamAttempt.length); + // NOTE: This is not strictly true. E.g. If a `Boolean` becomes an `Int`, Prisma converts it instead of throwing. + console.log('\nSUCCESS! The database schema matches the Prisma schema.'); + } catch (error) { + if (error instanceof PrismaClientKnownRequestError) { + console.log(error.message); + console.info('\nCHECK DATABASE SCHEMA!'); + } + } +} + +void main(); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.build.json b/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.build.json new file mode 100644 index 0000000000000000000000000000000000000000..8672fa47aa494fe9ea6b8df83178a910de9cfa0c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "outDir": "dist", + "rootDir": "../", + "noEmit": false, + "sourceMap": true + }, + "include": ["src"], + "exclude": ["**/*.test.*"] +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.json b/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..e3d8b080c36fc422b4fdf4b3175f09affe7061a3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/tsconfig.json @@ -0,0 +1,14 @@ +{ + "include": ["**/*.ts"], + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "allowJs": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "noEmit": true, + "noUncheckedIndexedAccess": true + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/turbo.json b/github_code/freeCodeCamp__freeCodeCamp/api/turbo.json new file mode 100644 index 0000000000000000000000000000000000000000..35afbe569e13855e47776ec0486c8674afbe59cb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/turbo.json @@ -0,0 +1,102 @@ +{ + "$schema": "https://v2-10-0.turborepo.dev/schema.json", + "extends": ["//"], + "tasks": { + "build": { + "env": [ + "API_LOCATION", + "AUTH0_CLIENT_ID", + "AUTH0_CLIENT_SECRET", + "AUTH0_DOMAIN", + "COOKIE_DOMAIN", + "COOKIE_SECRET", + "DEPLOYMENT_ENV", + "DEPLOYMENT_VERSION", + "EMAIL_PROVIDER", + "FCC_API_LOG_LEVEL", + "FCC_API_LOG_TRANSPORT", + "FCC_ENABLE_CLASSROOM", + "FCC_ENABLE_DEV_LOGIN_MODE", + "FCC_ENABLE_SENTRY_ROUTES", + "FCC_ENABLE_SWAGGER_UI", + "FCC_ENABLE_TEST_LOGGING", + "FCC_DRAIN_TIMEOUT_MS", + "FREECODECAMP_NODE_ENV", + "GROWTHBOOK_FASTIFY_API_HOST", + "GROWTHBOOK_FASTIFY_CLIENT_KEY", + "HOME_LOCATION", + "HOST", + "JWT_SECRET", + "MAILPIT_HOST", + "NODE_ENV", + "PORT", + "SENTRY_DSN", + "SENTRY_ENVIRONMENT", + "SENTRY_LOGS_DEBUG_SAMPLE_RATE", + "SENTRY_LOGS_INFO_SAMPLE_RATE", + "SENTRY_PROFILE_SESSION_SAMPLE_RATE", + "SENTRY_SERVER_NAME", + "SENTRY_TRACES_SAMPLE_RATE", + "SES_ID", + "SES_REGION", + "SES_SECRET", + "SES_SMTP_HOST", + "SES_SMTP_PASSWORD", + "SES_SMTP_USERNAME", + "SHOW_UPCOMING_CHANGES", + "SOCRATES_API_KEY", + "SOCRATES_ENDPOINT", + "STRIPE_SECRET_KEY", + "TPA_API_BEARER_TOKEN" + ] + }, + "test": { + "passThroughEnv": ["VITEST_WORKER_ID"], + "env": [ + "API_LOCATION", + "AUTH0_CLIENT_ID", + "AUTH0_CLIENT_SECRET", + "AUTH0_DOMAIN", + "COOKIE_DOMAIN", + "COOKIE_SECRET", + "DEPLOYMENT_ENV", + "DEPLOYMENT_VERSION", + "EMAIL_PROVIDER", + "FCC_API_LOG_LEVEL", + "FCC_API_LOG_TRANSPORT", + "FCC_ENABLE_CLASSROOM", + "FCC_ENABLE_DEV_LOGIN_MODE", + "FCC_ENABLE_SENTRY_ROUTES", + "FCC_ENABLE_SWAGGER_UI", + "FCC_ENABLE_TEST_LOGGING", + "FREECODECAMP_NODE_ENV", + "GROWTHBOOK_FASTIFY_API_HOST", + "GROWTHBOOK_FASTIFY_CLIENT_KEY", + "HOME_LOCATION", + "HOST", + "JWT_SECRET", + "MAILPIT_HOST", + "NODE_ENV", + "PORT", + "SENTRY_DSN", + "SENTRY_ENVIRONMENT", + "SENTRY_LOGS_DEBUG_SAMPLE_RATE", + "SENTRY_LOGS_INFO_SAMPLE_RATE", + "SENTRY_PROFILE_SESSION_SAMPLE_RATE", + "SENTRY_SERVER_NAME", + "SENTRY_TRACES_SAMPLE_RATE", + "SES_ID", + "SES_REGION", + "SES_SECRET", + "SES_SMTP_HOST", + "SES_SMTP_PASSWORD", + "SES_SMTP_USERNAME", + "SHOW_UPCOMING_CHANGES", + "SOCRATES_API_KEY", + "SOCRATES_ENDPOINT", + "STRIPE_SECRET_KEY", + "TPA_API_BEARER_TOKEN" + ] + } + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.test.ts b/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1fad63317d85a2e3f60954189fe749bc6e67c5c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.test.ts @@ -0,0 +1,105 @@ +import { describe, test, expect } from 'vitest'; +import { getCsrfToken, getCookies, serializeDates } from './vitest.utils.js'; + +const fakeCookies = [ + '_csrf=123; Path=/; HttpOnly; SameSite=Strict', + 'csrf_token=abc-123; Path=/', + 'sessionId=CV-abc.123; Path=/; Expires=Wed, 03 May 2023 16:29:53 GMT; HttpOnly' +]; + +describe('getCsrfToken', () => { + test('returns csrf token if there is one', () => { + expect(getCsrfToken(fakeCookies)).toEqual('abc-123'); + }); + + test('returns undefined if there is no csrf token', () => { + expect( + getCsrfToken(['_csrf=123; Path=/; HttpOnly; SameSite=Strict']) + ).toBeUndefined(); + }); +}); + +describe('setCookiesToCookies', () => { + test('returns a string of cookies', () => { + expect(getCookies(fakeCookies)).toEqual( + '_csrf=123; csrf_token=abc-123; sessionId=CV-abc.123' + ); + }); + test('handles bare cookies', () => { + expect(getCookies(['_csrf=123'])).toEqual('_csrf=123'); + }); + + test('throws an error if the cookies are malformed', () => { + expect(() => getCookies(['_csrf'])).toThrow(); + }); +}); + +describe('serializeDates', () => { + function isAsymmetricMatcher(x: unknown): x is typeof expect.any { + return ( + typeof x === 'object' && + x !== null && + typeof (x as { asymmetricMatch?: unknown }).asymmetricMatch === 'function' + ); + } + + test('returns primitives unchanged', () => { + expect(serializeDates(42)).toBe(42); + expect(serializeDates('hello')).toBe('hello'); + expect(serializeDates(true)).toBe(true); + }); + + test('converts Date to ISO string', () => { + const d = new Date('2020-01-01T00:00:00.000Z'); + expect(serializeDates(d)).toBe(d.toISOString()); + }); + + test('recursively converts nested objects with Date', () => { + const input = { + a: new Date('2021-05-05T05:05:05.000Z'), + b: { c: new Date('2022-06-06T06:06:06.000Z') } + }; + const output = serializeDates(input); + expect(output).toEqual({ + a: input.a.toISOString(), + b: { c: input.b.c.toISOString() } + }); + }); + + test('recursively converts arrays with Date and nested structures', () => { + const d1 = new Date('2020-02-02T02:02:02.000Z'); + const d2 = new Date('2023-03-03T03:03:03.000Z'); + const d3 = new Date('2024-04-04T04:04:04.000Z'); + const arr: [Date, { x: Date; y: Date[] }] = [d1, { x: d2, y: [d3] }]; + const out = serializeDates(arr); + expect(out).toEqual([ + d1.toISOString(), + { x: d2.toISOString(), y: [d3.toISOString()] } + ]); + }); + + test('handles null and undefined', () => { + expect(serializeDates(null)).toBeNull(); + expect(serializeDates(undefined)).toBeUndefined(); + }); + + test('preserves asymmetric matchers', () => { + type MatchersShape = { id: unknown; meta: { when: unknown } }; + const withMatchers: MatchersShape = { + id: expect.any(String) as unknown, + meta: { when: expect.stringMatching(/Z$/) as unknown } + }; + const serialized = serializeDates(withMatchers); + expect(isAsymmetricMatcher(serialized.id)).toBe(true); + expect(isAsymmetricMatcher(serialized.meta.when)).toBe(true); + + // Serializing `Date`s yield strings that match the same patterns + const body = { + id: 'abc', + meta: { when: new Date('2025-01-01T00:00:00.000Z') } + }; + const wrapped = serializeDates(body); + expect(typeof wrapped.id).toBe('string'); + expect(wrapped.meta.when).toMatch(/Z$/); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.ts b/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.ts new file mode 100644 index 0000000000000000000000000000000000000000..019a4e7dcb75313bf7e3b8402f8fa2339d3d6718 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/api/vitest.utils.ts @@ -0,0 +1,327 @@ +/* eslint-disable jsdoc/require-jsdoc */ +import { beforeAll, afterAll, expect, vi } from 'vitest'; +import request from 'supertest'; + +import { build, buildOptions } from './src/app.js'; +import { createUserInput } from './src/utils/create-user.js'; +import { examJson } from './__fixtures__/exam.js'; +import { CSRF_COOKIE, CSRF_HEADER } from './src/plugins/csrf.js'; + +type FastifyTestInstance = Awaited>; + +declare global { + var fastifyTestInstance: FastifyTestInstance; +} + +type Options = { + sendCSRFToken?: boolean; +}; + +const requests = { + GET: (resource: string) => request(fastifyTestInstance?.server).get(resource), + POST: (resource: string) => + request(fastifyTestInstance?.server).post(resource), + PUT: (resource: string) => request(fastifyTestInstance?.server).put(resource), + DELETE: (resource: string) => + request(fastifyTestInstance?.server).delete(resource) +}; + +export const getCsrfToken = (setCookies: string[]): string | undefined => { + const csrfSetCookie = setCookies.find(str => str.includes(CSRF_COOKIE)); + const [csrfCookie] = csrfSetCookie?.split(';') ?? []; + const [_key, csrfToken] = csrfCookie?.split('=') ?? []; + + return csrfToken; +}; + +const ORIGIN = 'https://www.freecodecamp.org'; + +export const getCookies = (setCookies: string[]): string => { + for (const cookie of setCookies) { + expect(cookie).toMatch(/.*=.*/); + } + return setCookies.map(cookie => cookie.split(';')[0]).join('; '); +}; + +/** + * A wrapper around supertest that handles common setup for requests. Namely + * setting the Origin header, cookies and CSRF token. + * + * @param resource - The URL of the resource to be requested. + * @param config - The configuration for the request. + * @param config.method - The HTTP method to be used. + * @param config.setCookies - The cookies to be set in the request. + * @param options - Additional options for the request. + * @param options.sendCSRFToken - Whether to send the CSRF token in the request (default: true). + * @returns The request object. + */ +export function superRequest( + resource: string, + config: { + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + setCookies?: string[]; + }, + options?: Options +): request.Test { + const { method, setCookies } = config; + const { sendCSRFToken = true } = options ?? {}; + + const req = requests[method](resource).set('Origin', ORIGIN); + + if (setCookies) { + void req.set('Cookie', getCookies(setCookies)); + } + + const csrfToken = (setCookies && getCsrfToken(setCookies)) ?? ''; + if (sendCSRFToken) { + void req.set(CSRF_HEADER, csrfToken); + } + return req; +} + +/** + * Factory function for 'superRequest' allows for the creation of a concise + * request function with the desired method and setCookies baked in. + * + * @param config + * @param config.method - HTTP method. + * @param config.setCookies - Cookies to be set in the request. + * @returns A superRequest function with the desired method and setCookies. + */ +export function createSuperRequest(config: { + method: 'GET' | 'POST' | 'PUT' | 'DELETE'; + setCookies?: string[]; +}): (resource: string, options?: Options) => request.Test { + return (resource, options) => superRequest(resource, config, options); +} + +type IndexData = { + collection: string; + indexes: { + key: Record; + name: string; + expireAfterSeconds?: number; + unique?: boolean; + }[]; +}; +const indexData: IndexData[] = [ + { + collection: 'AccessToken', + indexes: [ + { + key: { userId: 1 }, + name: 'userId_1' + } + ] + }, + { + collection: 'Donation', + indexes: [ + { key: { email: 1 }, name: 'email_1' }, + { key: { userId: 1 }, name: 'userId_1' } + ] + }, + { + collection: 'MsUsername', + indexes: [{ key: { userId: 1, id: 1 }, name: 'userId_1__id_1' }] + }, + { + collection: 'SocratesUsage', + indexes: [ + { + key: { userId: 1, date: 1 }, + name: 'userId_date_unique', + unique: true + } + ] + }, + { + collection: 'Survey', + indexes: [{ key: { userId: 1 }, name: 'userId_1' }] + }, + { + collection: 'UserToken', + indexes: [{ key: { userId: 1 }, name: 'userId_1' }] + }, + { + collection: 'sessions', + indexes: [ + { + key: { expires: 1 }, + name: 'expires_1', + expireAfterSeconds: 0 + } + ] + }, + { + collection: 'user', + indexes: [ + { + key: { email: 1, sendQuincyEmail: 1 }, + name: 'mailing-list-pull' + }, + { key: { email: 1 }, name: 'email_1' }, + { key: { isDonating: 1 }, name: 'isDonating_1' }, + { key: { username: 1, id: 1 }, name: 'username_1__id_1' } + ] + } +]; + +export async function checkCanConnectToDb( + prisma: FastifyTestInstance['prisma'] +): Promise { + const countP = prisma.user.count(); + const delayedRejection = new Promise((_resolve, reject) => + setTimeout( + () => reject(Error('unable to connect to Mongodb (timeout)')), + 1000 + ) + ); + await Promise.race([countP, delayedRejection]); +} + +export function setupServer(): void { + let fastify: FastifyTestInstance; + beforeAll(async () => { + if (process.env.FCC_ENABLE_TEST_LOGGING !== 'true') { + delete buildOptions.loggerInstance; + } + fastify = await build(buildOptions); + await fastify.ready(); + // Supertest does not handle multiple concurrent requests gracefully + // https://github.com/forwardemail/supertest/issues/709 + // it calls `server.close` and can end up killing live connections. + // By listening to 0, we keep the ephemeral port generation, but the fact + // it is listening means supertest will not attempt to close it. + fastify.server.listen(0); + + await checkCanConnectToDb(fastify.prisma); + + // Prisma does not support TTL indexes in the schema yet, so, to avoid + // conflicts with the TTL index in the sessions collection, we need to + // create it manually (before interacting with the db in any way). Also, + // to save time, we create all other indexes so we don't need to invoke + // `prisma db push` (which is relatively slow). + + await Promise.all( + indexData.map(async ({ collection, indexes }) => { + await fastify.prisma.$runCommandRaw({ + createIndexes: collection, + indexes + }); + }) + ); + + global.fastifyTestInstance = fastify; + // allow a little time to setup the db + }, 10000); + + afterAll(async () => { + if (!global.fastifyTestInstance) + throw Error(`fastifyTestInstance was not created. Typically this means that something went wrong when building the fastify instance. +If you are seeing this error, the root cause is likely an error thrown in the beforeAll hook.`); + await fastifyTestInstance.prisma.$runCommandRaw({ dropDatabase: 1 }); + + await fastifyTestInstance.close(); + }); +} + +// demoUser _id to allow testing with mock data +export const defaultUserId = '5bd30e0f1caf6ac3ddddddb5'; +export const defaultUserEmail = 'foo@bar.com'; +export const defaultUsername = 'fcc-test-user'; + +export const resetDefaultUser = async (): Promise => { + await fastifyTestInstance.prisma.user.deleteMany({ + where: { OR: [{ id: defaultUserId }, { email: defaultUserEmail }] } + }); + + await fastifyTestInstance.prisma.user.create({ + data: { + ...createUserInput(defaultUserEmail), + id: defaultUserId, + username: defaultUsername + } + }); +}; + +export async function devLogin(): Promise { + await resetDefaultUser(); + const res = await superRequest('/signin', { method: 'GET' }); + expect(res.status).toBe(302); + return res.get('Set-Cookie'); +} + +export async function seedExam(): Promise { + const query = { where: { id: examJson.id } }; + const testExamExists = + await fastifyTestInstance.prisma.exam.findUnique(query); + + if (testExamExists) { + await fastifyTestInstance.prisma.exam.deleteMany(query); + } + + await fastifyTestInstance.prisma.exam.create({ + data: { + ...examJson + } + }); +} + +export function createFetchMock({ ok = true, body = {} } = {}) { + return vi.fn().mockResolvedValue( + Promise.resolve({ + ok, + json: () => Promise.resolve(body) + }) + ); +} + +/** + * Utility type to recursively replace `Date` with `string`. + */ +export type ReplaceDates = T extends Date + ? string + : T extends (infer U)[] + ? ReplaceDates[] + : T extends Record + ? { [K in keyof T]: ReplaceDates } + : T; + +/** + * Recursively finds and converts Date objects to ISO strings while preserving shape. + */ +export function serializeDates(data: T): ReplaceDates { + if (data === null || data === undefined) { + return data as ReplaceDates; + } + + // Preserve Vitest/Jest asymmetric matchers (e.g., expect.any(Number)) + if ( + typeof data === 'object' && + data !== null && + typeof (data as { asymmetricMatch?: unknown }).asymmetricMatch === + 'function' + ) { + return data as unknown as ReplaceDates; + } + + if (data instanceof Date) { + return data.toISOString() as ReplaceDates; + } + + if (Array.isArray(data)) { + return (data as unknown[]).map(item => + serializeDates(item) + ) as ReplaceDates; + } + + if (typeof data === 'object') { + const entries = Object.entries(data as Record).map( + ([key, value]) => [key, serializeDates(value)] as const + ); + return Object.fromEntries(entries) as ReplaceDates; + } + + return data as ReplaceDates; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/.babelrc.js b/github_code/freeCodeCamp__freeCodeCamp/client/.babelrc.js new file mode 100644 index 0000000000000000000000000000000000000000..c528a06aa0907ba0deb665cad249ca2ae8099fd6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/.babelrc.js @@ -0,0 +1,71 @@ +/* eslint-disable filenames-simple/naming-convention */ +require('dotenv').config({ path: '../.env' }); +const config = { + presets: [ + [ + '@babel/preset-env', + { + loose: true, + modules: false, + useBuiltIns: 'usage', + corejs: 3, + shippedProposals: true, + targets: { + browsers: ['>0.25%', 'not dead'] + } + } + ], + [ + '@babel/preset-react', + { + useBuiltIns: true, + pragma: 'React.createElement' + } + ], + '@babel/preset-typescript' + ], + plugins: [ + 'preval', + '@babel/plugin-syntax-dynamic-import', + 'babel-plugin-macros', + [ + '@babel/plugin-transform-runtime', + { + helpers: true, + regenerator: true + } + ], + [ + 'prismjs', + { + languages: [ + 'bash', + 'c', + 'clike', + 'cpp', + 'css', + 'csharp', + 'html', + 'javascript', + 'json', + 'jsx', + 'markup', + 'mathml', + 'pug', + 'python', + 'scss', + 'sass', + 'sql', + 'svg', + 'typescript', + 'tsx', + 'xml' + ], + theme: 'default', + css: true, + plugins: ['line-numbers'] + } + ] + ] +}; +module.exports = config; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/.gitignore b/github_code/freeCodeCamp__freeCodeCamp/client/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3b1f6a47d089015a0a5b78f1797974474f86ee5c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/.gitignore @@ -0,0 +1,31 @@ +# Project dependencies +.cache +node_modules +yarn-error.log + +# Build directory +/public +.DS_Store + +/static/js +/static/css +/static/curriculum-data + +# i18n build script copies non-English translations from i18n-curriculum submodule +/i18n/locales/*/translations.json +/i18n/locales/*/intro.json +/i18n/locales/*/meta-tags.json +/i18n/locales/*/motivation.json +# english is a special case and is commited in this repo +!/i18n/locales/english/translations.json +!/i18n/locales/english/intro.json +!/i18n/locales/english/meta-tags.json +!/i18n/locales/english/motivation.json + +# Generated for all locales +i18n/locales/**/trending.json +i18n/locales/**/search-bar.json + +# Config + +config/env.json diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/.lintstagedrc.mjs b/github_code/freeCodeCamp__freeCodeCamp/client/.lintstagedrc.mjs new file mode 100644 index 0000000000000000000000000000000000000000..2cb8879f45f5371b6d5d5f6845e87c02e1564f7e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/.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/client/__mocks__/gatsby.ts b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/gatsby.ts new file mode 100644 index 0000000000000000000000000000000000000000..b279e387259c0ee8b5b87e4db3c92602162b1cc8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/gatsby.ts @@ -0,0 +1,33 @@ +import React from 'react'; +import type { GatsbyLinkProps } from 'gatsby'; +import { vi } from 'vitest'; +import gatsby from 'gatsby'; + +import envData from '../config/env.json'; +const { clientLocale } = envData; + +export const navigate = vi.fn(); +export const graphql = vi.fn(); +export const Link = vi + .fn() + .mockImplementation(({ to, ...rest }: GatsbyLinkProps) => + React.createElement('a', { ...rest, href: to }) + ); +export const withPrefix = vi.fn().mockImplementation((path: string) => { + const pathPrefix = clientLocale === 'english' ? '' : '/' + clientLocale; + return pathPrefix + path; +}); +export const StaticQuery = vi.fn(); +export const useStaticQuery = vi.fn(); + +export default { + // ...existing code... + // spread the actual gatsby module to keep other exports working + ...gatsby, + navigate, + graphql, + Link, + withPrefix, + StaticQuery, + useStaticQuery +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-i18next.js b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-i18next.js new file mode 100644 index 0000000000000000000000000000000000000000..600e23b01368d754279a7d42191eae5f63a8d77e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-i18next.js @@ -0,0 +1,67 @@ +import React from 'react'; + +// modified from https://github.com/i18next/react-i18next/blob/master/example/test-jest/src/__mocks__/react-i18next.js +const hasChildren = node => + node && (node.children || (node.props && node.props.children)); + +const getChildren = node => + node && node.children ? node.children : node.props && node.props.children; + +const renderNodes = reactNodes => { + if (typeof reactNodes === 'string') { + return reactNodes; + } + + return Object.keys(reactNodes).map((key, i) => { + const child = reactNodes[key]; + const isElement = React.isValidElement(child); + + if (typeof child === 'string') { + return child; + } + if (hasChildren(child)) { + const inner = renderNodes(getChildren(child)); + return React.cloneElement(child, { ...child.props, key: i }, inner); + } + if (typeof child === 'object' && !isElement) { + return Object.keys(child).reduce( + (str, childKey) => `${str}${child[childKey]}`, + '' + ); + } + + return child; + }); +}; + +const withTranslation = () => Component => { + const WrappedComponent = props => + React.createElement(Component, { + ...props, + t: props.t ?? (str => str) + }); + + WrappedComponent.WrappedComponent = Component; + WrappedComponent.displayName = `withTranslation(${Component.displayName || Component.name || 'Component'})`; + + return WrappedComponent; +}; + +const useTranslation = () => { + return { + t: str => str, + i18n: { + changeLanguage: () => new Promise(() => {}) + } + }; +}; + +const Trans = ({ children }) => + Array.isArray(children) ? renderNodes(children) : renderNodes([children]); + +// translate isn't being used anywhere, uncomment if needed +/* const translate = () => Component => props => ( + ''} {...props} /> +); */ + +module.exports = { withTranslation, useTranslation, Trans }; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-spinkit.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-spinkit.tsx new file mode 100644 index 0000000000000000000000000000000000000000..982f64b2b5ff785909b8543c3226f36b74b0dd07 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/__mocks__/react-spinkit.tsx @@ -0,0 +1,4 @@ +import React from 'react'; + +// eslint-disable-next-line react/display-name +export default () =>
Spinner
; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/config/analytics-settings.ts b/github_code/freeCodeCamp__freeCodeCamp/client/config/analytics-settings.ts new file mode 100644 index 0000000000000000000000000000000000000000..0547e57a814143eed0ad9bd690eb5047b47efa02 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/config/analytics-settings.ts @@ -0,0 +1,2 @@ +export const prodAnalyticsId = 'GTM-57R6KJM'; +export const devAnalyticsId = 'GTM-WSS47LM'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.test.ts b/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1c1ce8c21360c8f9153e1ce6013258820253b8a7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.test.ts @@ -0,0 +1,77 @@ +import path from 'node:path'; +import fs from 'node:fs'; +import { describe, test, expect } from 'vitest'; + +import { getContentDir } from '@freecodecamp/curriculum/file-handler'; +import { buildCertification } from '@freecodecamp/curriculum/build-certification'; + +import { allCerts } from './cert-and-project-map'; + +describe('certifications', () => { + const certificationsDir = path.resolve( + getContentDir('english'), + 'certifications' + ); + + const certificationFiles = fs.readdirSync(certificationsDir); + + certificationFiles.forEach(filename => { + test(`${filename} should have matching items in cert-and-project-map`, () => { + const filePath = path.join(certificationsDir, filename); + const result = buildCertification(filePath); + + const certData = result.challenges[0]; + const certTests = certData.tests; + + const matchingCert = allCerts.find(cert => cert.id === certData.id); + + expect( + matchingCert, + `Cert ID ${certData.id} not found in allCerts.` + ).toBeDefined(); + expect( + matchingCert, + `Matching cert has no 'projects' property` + ).toHaveProperty('projects'); + + // skip legacy-full-stack as it has no projects + if (filename === 'legacy-full-stack.yml') { + return; + } + + expect( + Array.isArray(matchingCert?.projects), + `Matching cert 'projects' is not an array` + ).toBe(true); + + const certProjects = matchingCert?.projects; + + expect( + certProjects?.length, + `Project count mismatch: allCerts has ${certProjects?.length} projects, YAML has ${certTests.length} tests` + ).toBe(certTests.length); + + certTests.forEach((test, i) => { + expect( + test, + `Test at index ${i} in missing id property` + ).toHaveProperty('id'); + expect( + test, + `Test at index ${i} missing title property` + ).toHaveProperty('title'); + + const matchingProject = certProjects?.[i]; + + expect( + matchingProject, + `No project found at index ${i} for test ${test.id}` + ).toBeDefined(); + expect( + matchingProject?.id, + `Project ID mismatch at index ${i}: allCerts has "${matchingProject?.id}", YAML has "${test.id}"` + ).toBe(test.id); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.ts b/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.ts new file mode 100644 index 0000000000000000000000000000000000000000..95e793e1b664c9099e3be151f0cca582895d7289 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/config/cert-and-project-map.ts @@ -0,0 +1,1031 @@ +import { + Certification, + legacyCertifications, + upcomingCertifications, + currentCertifications +} from '@freecodecamp/shared/config/certification-settings'; + +import config from '../config/env.json'; + +const { showUpcomingChanges } = config; + +const responsiveWebBase = + '/learn/responsive-web-design/responsive-web-design-projects'; +const responsiveWeb22Base = '/learn/2022/responsive-web-design'; +const jsAlgoBase = + '/learn/javascript-algorithms-and-data-structures/' + + 'javascript-algorithms-and-data-structures-projects'; +const jsAlgo22Base = '/learn/javascript-algorithms-and-data-structures-v8'; +const feLibsBase = + '/learn/front-end-development-libraries/front-end-development-libraries-projects'; +const dataVisBase = '/learn/data-visualization/data-visualization-projects'; +const relationalDatabaseBase = '/learn/relational-database'; +const apiMicroBase = + '/learn/back-end-development-and-apis/back-end-development-and-apis-projects'; +const qaBase = '/learn/quality-assurance/quality-assurance-projects'; +const infoSecBase = '/learn/information-security/information-security-projects'; +const sciCompPyBase = '/learn/scientific-computing-with-python'; +const dataAnalysisPyBase = + '/learn/data-analysis-with-python/data-analysis-with-python-projects'; +const machineLearningPyBase = + '/learn/machine-learning-with-python/machine-learning-with-python-projects'; +const collegeAlgebraPyBase = '/learn/college-algebra-with-python'; +const takeHomeBase = '/learn/coding-interview-prep/take-home-projects'; +const foundationalCSharpBase = + '/learn/foundational-c-sharp-with-microsoft/foundational-c-sharp-with-microsoft-certification-exam'; +const respWebV9Base = '/learn/responsive-web-design-v9'; +const jsV9Base = '/learn/javascript-v9'; +const frontEndDevLibsV9Base = '/learn/front-end-development-libraries-v9'; +const pythonV9Base = '/learn/python-v9'; +const relationalDbV9Base = '/learn/relational-databases-v9'; +const backEndDevApisV9Base = '/learn/back-end-development-and-apis-v9'; +const fullStackDeveloperV9Base = '/learn/full-stack-developer-v9'; +const a2EnglishBase = '/learn/a2-english-for-developers'; +const b1EnglishBase = '/learn/b1-english-for-developers'; +const a2SpanishBase = '/learn/a2-professional-spanish'; +const a2ChineseBase = '/learn/a2-professional-chinese'; +const a1ChineseBase = '/learn/a1-professional-chinese'; +const legacyFrontEndBase = feLibsBase; +const legacyFrontEndResponsiveBase = responsiveWebBase; +const legacyFrontEndTakeHomeBase = takeHomeBase; +const legacyBackEndBase = apiMicroBase; +const legacyBackEndTakeHomeBase = takeHomeBase; +const legacyDataVisBase = dataVisBase; +const legacyDataVisFrontEndBase = feLibsBase; +const legacyDataVisTakeHomeBase = takeHomeBase; +const legacyInfosecQaQaBase = qaBase; +const legacyInfosecQaInfosecBase = infoSecBase; + +// TODO: generate this automatically in a separate file +// from the md/meta.json files for each cert and projects +const fullstackCert = { + id: '561add10cb82ac38a17213bd', + title: 'Legacy Full-Stack', + certSlug: Certification.LegacyFullStack, + projects: null + // Requirements are other certs and is + // handled elsewhere +} as const; +const allStandardCerts = [ + { + id: '561add10cb82ac38a17513bc', + title: 'Responsive Web Design', + certSlug: Certification.RespWebDesign, + projects: [ + { + id: '587d78af367417b2b2512b03', + title: 'Build a Survey Form', + link: getResponsiveWebDesignPath('build-a-survey-form'), + certSlug: Certification.RespWebDesign + }, + { + id: 'bd7158d8c442eddfaeb5bd18', + title: 'Build a Tribute Page', + link: getResponsiveWebDesignPath('build-a-tribute-page'), + certSlug: Certification.RespWebDesign + }, + { + id: '587d78b0367417b2b2512b05', + title: 'Build a Technical Documentation Page', + link: getResponsiveWebDesignPath( + 'build-a-technical-documentation-page' + ), + certSlug: Certification.RespWebDesign + }, + { + id: '587d78af367417b2b2512b04', + title: 'Build a Product Landing Page', + link: getResponsiveWebDesignPath('build-a-product-landing-page'), + certSlug: Certification.RespWebDesign + }, + { + id: 'bd7158d8c242eddfaeb5bd13', + title: 'Build a Personal Portfolio Webpage', + link: getResponsiveWebDesignPath('build-a-personal-portfolio-webpage'), + certSlug: Certification.RespWebDesign + } + ] + }, + { + id: '658180220947283cdc0689ce', + title: 'JavaScript Algorithms and Data Structures', + certSlug: Certification.JsAlgoDataStructNew, + projects: [ + { + id: '657bdc55a322aae1eac3838f', + title: 'Build a Palindrome Checker', + link: getJavaScriptAlgoPath('build-a-palindrome-checker'), + certSlug: Certification.JsAlgoDataStructNew + }, + { + id: '657bdc8ba322aae1eac38390', + title: 'Build a Roman Numeral Converter', + link: getJavaScriptAlgoPath('build-a-roman-numeral-converter'), + certSlug: Certification.JsAlgoDataStructNew + }, + { + id: '657bdcb9a322aae1eac38391', + title: 'Build a Telephone Number Validator', + link: getJavaScriptAlgoPath('build-a-telephone-number-validator'), + certSlug: Certification.JsAlgoDataStructNew + }, + { + id: '657bdcc3a322aae1eac38392', + title: 'Build a Cash Register', + link: getJavaScriptAlgoPath('build-a-cash-register'), + certSlug: Certification.JsAlgoDataStructNew + }, + { + id: '6555c1d3e11a1574434cf8b5', + title: 'Build an RPG Creature Search App', + link: getJavaScriptAlgoPath('build-an-rpg-creature-search-app'), + certSlug: Certification.JsAlgoDataStructNew + } + ] + }, + { + id: '561acd10cb82ac38a17513bc', + title: 'Front-End Development Libraries', + certSlug: Certification.FrontEndDevLibs, + projects: [ + { + id: 'bd7158d8c442eddfaeb5bd13', + title: 'Build a Random Quote Machine', + link: `${feLibsBase}/build-a-random-quote-machine`, + certSlug: Certification.FrontEndDevLibs + }, + { + id: 'bd7157d8c242eddfaeb5bd13', + title: 'Build a Markdown Previewer', + link: `${feLibsBase}/build-a-markdown-previewer`, + certSlug: Certification.FrontEndDevLibs + }, + { + id: '587d7dbc367417b2b2512bae', + title: 'Build a Drum Machine', + link: `${feLibsBase}/build-a-drum-machine`, + certSlug: Certification.FrontEndDevLibs + }, + { + id: 'bd7158d8c442eddfaeb5bd17', + title: 'Build a JavaScript Calculator', + link: `${feLibsBase}/build-a-javascript-calculator`, + certSlug: Certification.FrontEndDevLibs + }, + { + id: 'bd7158d8c442eddfaeb5bd0f', + title: 'Build a 25 + 5 Clock', + link: `${feLibsBase}/build-a-25--5-clock`, + certSlug: Certification.FrontEndDevLibs + } + ] + }, + { + id: '5a553ca864b52e1d8bceea14', + title: 'Data Visualization', + certSlug: Certification.DataVis, + projects: [ + { + id: 'bd7168d8c242eddfaeb5bd13', + title: 'Visualize Data with a Bar Chart', + link: `${dataVisBase}/visualize-data-with-a-bar-chart`, + certSlug: Certification.DataVis + }, + { + id: 'bd7178d8c242eddfaeb5bd13', + title: 'Visualize Data with a Scatterplot Graph', + link: `${dataVisBase}/visualize-data-with-a-scatterplot-graph`, + certSlug: Certification.DataVis + }, + { + id: 'bd7188d8c242eddfaeb5bd13', + title: 'Visualize Data with a Heat Map', + link: `${dataVisBase}/visualize-data-with-a-heat-map`, + certSlug: Certification.DataVis + }, + { + id: '587d7fa6367417b2b2512bbf', + title: 'Visualize Data with a Choropleth Map', + link: `${dataVisBase}/visualize-data-with-a-choropleth-map`, + certSlug: Certification.DataVis + }, + { + id: '587d7fa6367417b2b2512bc0', + title: 'Visualize Data with a Treemap Diagram', + link: `${dataVisBase}/visualize-data-with-a-treemap-diagram`, + certSlug: Certification.DataVis + } + ] + }, + { + id: '606243f50267e718b1e755f4', + title: 'Relational Database', + certSlug: Certification.RelationalDb, + projects: [ + { + id: '5f1a4ef5d5d6b5ab580fc6ae', + title: 'Celestial Bodies Database', + link: `${relationalDatabaseBase}/build-a-celestial-bodies-database-project/build-a-celestial-bodies-database`, + certSlug: Certification.RelationalDb + }, + { + id: '5f9771307d4d22b9d2b75a94', + title: 'World Cup Database', + link: `${relationalDatabaseBase}/build-a-world-cup-database-project/build-a-world-cup-database`, + certSlug: Certification.RelationalDb + }, + { + id: '5f87ac112ae598023a42df1a', + title: 'Salon Appointment Scheduler', + link: `${relationalDatabaseBase}/build-a-salon-appointment-scheduler-project/build-a-salon-appointment-scheduler`, + certSlug: Certification.RelationalDb + }, + { + id: '602d9ff222201c65d2a019f2', + title: 'Periodic Table Database', + link: `${relationalDatabaseBase}/build-a-periodic-table-database-project/build-a-periodic-table-database`, + certSlug: Certification.RelationalDb + }, + { + id: '602da04c22201c65d2a019f4', + title: 'Number Guessing Game', + link: `${relationalDatabaseBase}/build-a-number-guessing-game-project/build-a-number-guessing-game`, + certSlug: Certification.RelationalDb + } + ] + }, + { + id: '561add10cb82ac38a17523bc', + title: 'Back-End Development and APIs', + certSlug: Certification.BackEndDevApis, + projects: [ + { + id: 'bd7158d8c443edefaeb5bdef', + title: 'Timestamp Microservice', + link: `${apiMicroBase}/timestamp-microservice`, + certSlug: Certification.BackEndDevApis + }, + { + id: 'bd7158d8c443edefaeb5bdff', + title: 'Request Header Parser Microservice', + link: `${apiMicroBase}/request-header-parser-microservice`, + certSlug: Certification.BackEndDevApis + }, + { + id: 'bd7158d8c443edefaeb5bd0e', + title: 'URL Shortener Microservice', + link: `${apiMicroBase}/url-shortener-microservice`, + certSlug: Certification.BackEndDevApis + }, + { + id: '5a8b073d06fa14fcfde687aa', + title: 'Exercise Tracker', + link: `${apiMicroBase}/exercise-tracker`, + certSlug: Certification.BackEndDevApis + }, + { + id: 'bd7158d8c443edefaeb5bd0f', + title: 'File Metadata Microservice', + link: `${apiMicroBase}/file-metadata-microservice`, + certSlug: Certification.BackEndDevApis + } + ] + }, + { + id: '5e611829481575a52dc59c0e', + title: 'Quality Assurance', + certSlug: Certification.QualityAssurance, + projects: [ + { + id: '587d8249367417b2b2512c41', + title: 'Metric-Imperial Converter', + link: `${qaBase}/metric-imperial-converter`, + certSlug: Certification.QualityAssurance + }, + { + id: '587d8249367417b2b2512c42', + title: 'Issue Tracker', + link: `${qaBase}/issue-tracker`, + certSlug: Certification.QualityAssurance + }, + { + id: '587d824a367417b2b2512c43', + title: 'Personal Library', + link: `${qaBase}/personal-library`, + certSlug: Certification.QualityAssurance + }, + { + id: '5e601bf95ac9d0ecd8b94afd', + title: 'Sudoku Solver', + link: `${qaBase}/sudoku-solver`, + certSlug: Certification.QualityAssurance + }, + { + id: '5e601c0d5ac9d0ecd8b94afe', + title: 'American British Translator', + link: `${qaBase}/american-british-translator`, + certSlug: Certification.QualityAssurance + } + ] + }, + { + id: '5e44431b903586ffb414c951', + title: 'Scientific Computing with Python', + certSlug: Certification.SciCompPy, + projects: [ + { + id: '5e44412c903586ffb414c94c', + title: 'Arithmetic Formatter', + link: `${sciCompPyBase}/build-an-arithmetic-formatter-project/build-an-arithmetic-formatter-project`, + certSlug: Certification.SciCompPy + }, + { + id: '5e444136903586ffb414c94d', + title: 'Time Calculator', + link: `${sciCompPyBase}/build-a-time-calculator-project/build-a-time-calculator-project`, + certSlug: Certification.SciCompPy + }, + { + id: '5e44413e903586ffb414c94e', + title: 'Budget App', + link: `${sciCompPyBase}/build-a-budget-app-project/build-a-budget-app-project`, + certSlug: Certification.SciCompPy + }, + { + id: '5e444147903586ffb414c94f', + title: 'Polygon Area Calculator', + link: `${sciCompPyBase}/build-a-polygon-area-calculator-project/build-a-polygon-area-calculator-project`, + certSlug: Certification.SciCompPy + }, + { + id: '5e44414f903586ffb414c950', + title: 'Probability Calculator', + link: `${sciCompPyBase}/build-a-probability-calculator-project/build-a-probability-calculator-project`, + certSlug: Certification.SciCompPy + } + ] + }, + { + id: '5e46fc95ac417301a38fb934', + title: 'Data Analysis with Python', + certSlug: Certification.DataAnalysisPy, + projects: [ + { + id: '5e46f7e5ac417301a38fb928', + title: 'Mean-Variance-Standard Deviation Calculator', + link: `${dataAnalysisPyBase}/mean-variance-standard-deviation-calculator`, + certSlug: Certification.DataAnalysisPy + }, + { + id: '5e46f7e5ac417301a38fb929', + title: 'Demographic Data Analyzer', + link: `${dataAnalysisPyBase}/demographic-data-analyzer`, + certSlug: Certification.DataAnalysisPy + }, + { + id: '5e46f7f8ac417301a38fb92a', + title: 'Medical Data Visualizer', + link: `${dataAnalysisPyBase}/medical-data-visualizer`, + certSlug: Certification.DataAnalysisPy + }, + { + id: '5e46f802ac417301a38fb92b', + title: 'Page View Time Series Visualizer', + link: `${dataAnalysisPyBase}/page-view-time-series-visualizer`, + certSlug: Certification.DataAnalysisPy + }, + { + id: '5e4f5c4b570f7e3a4949899f', + title: 'Sea Level Predictor', + link: `${dataAnalysisPyBase}/sea-level-predictor`, + certSlug: Certification.DataAnalysisPy + } + ] + }, + + { + id: '5e6021435ac9d0ecd8b94b00', + title: 'Information Security', + certSlug: Certification.InfoSec, + projects: [ + { + id: '587d824a367417b2b2512c44', + title: 'Stock Price Checker', + link: `${infoSecBase}/stock-price-checker`, + certSlug: Certification.InfoSec + }, + { + id: '587d824a367417b2b2512c45', + title: 'Anonymous Message Board', + link: `${infoSecBase}/anonymous-message-board`, + certSlug: Certification.InfoSec + }, + { + id: '5e46f979ac417301a38fb932', + title: 'Port Scanner', + link: `${infoSecBase}/port-scanner`, + certSlug: Certification.InfoSec + }, + { + id: '5e46f983ac417301a38fb933', + title: 'SHA-1 Password Cracker', + link: `${infoSecBase}/sha-1-password-cracker`, + certSlug: Certification.InfoSec + }, + { + id: '5e601c775ac9d0ecd8b94aff', + title: 'Secure Real Time Multiplayer Game', + link: `${infoSecBase}/secure-real-time-multiplayer-game`, + certSlug: Certification.InfoSec + } + ] + }, + { + id: '5e46fc95ac417301a38fb935', + title: 'Machine Learning with Python', + certSlug: Certification.MachineLearningPy, + projects: [ + { + id: '5e46f8d6ac417301a38fb92d', + title: 'Rock Paper Scissors', + link: `${machineLearningPyBase}/rock-paper-scissors`, + certSlug: Certification.MachineLearningPy + }, + { + id: '5e46f8dcac417301a38fb92e', + title: 'Cat and Dog Image Classifier', + link: `${machineLearningPyBase}/cat-and-dog-image-classifier`, + certSlug: Certification.MachineLearningPy + }, + { + id: '5e46f8e3ac417301a38fb92f', + title: 'Book Recommendation Engine using KNN', + link: `${machineLearningPyBase}/book-recommendation-engine-using-knn`, + certSlug: Certification.MachineLearningPy + }, + { + id: '5e46f8edac417301a38fb930', + title: 'Linear Regression Health Costs Calculator', + link: `${machineLearningPyBase}/linear-regression-health-costs-calculator`, + certSlug: Certification.MachineLearningPy + }, + { + id: '5e46f8edac417301a38fb931', + title: 'Neural Network SMS Text Classifier', + link: `${machineLearningPyBase}/neural-network-sms-text-classifier`, + certSlug: Certification.MachineLearningPy + } + ] + }, + { + id: '61531b20cc9dfa2741a5b800', + title: 'College Algebra with Python', + certSlug: Certification.CollegeAlgebraPy, + projects: [ + { + id: '63d83ff239c73468b059cd3f', + title: 'Build a Multi-Function Calculator', + link: getCollegeAlgebraPyPath('build-a-multi-function-calculator'), + certSlug: Certification.CollegeAlgebraPy + }, + { + id: '63d83ffd39c73468b059cd40', + title: 'Build a Graphing Calculator', + link: getCollegeAlgebraPyPath('build-a-graphing-calculator'), + certSlug: Certification.CollegeAlgebraPy + }, + { + id: '63d8401039c73468b059cd41', + title: 'Build Three Math Games', + link: getCollegeAlgebraPyPath('build-three-math-games'), + certSlug: Certification.CollegeAlgebraPy + }, + { + id: '63d8401e39c73468b059cd42', + title: 'Build a Financial Calculator', + link: getCollegeAlgebraPyPath('build-a-financial-calculator'), + certSlug: Certification.CollegeAlgebraPy + }, + { + id: '63d8402e39c73468b059cd43', + title: 'Build a Data Graph Explorer', + link: getCollegeAlgebraPyPath('build-a-data-graph-explorer'), + certSlug: Certification.CollegeAlgebraPy + } + ] + }, + // Legacy certifications + { + id: '561add10cb82ac38a17513be', + title: 'Legacy Front-End', + certSlug: Certification.LegacyFrontEnd, + projects: [ + { + id: 'bd7158d8c242eddfaeb5bd13', + title: 'Build a Personal Portfolio Webpage', + link: `${legacyFrontEndResponsiveBase}/build-a-personal-portfolio-webpage`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd13', + title: 'Build a Random Quote Machine', + link: `${legacyFrontEndBase}/build-a-random-quote-machine`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd0f', + title: 'Build a 25 + 5 Clock', + link: `${legacyFrontEndBase}/build-a-25--5-clock`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd17', + title: 'Build a JavaScript Calculator', + link: `${legacyFrontEndBase}/build-a-javascript-calculator`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd10', + title: 'Show the Local Weather', + link: `${legacyFrontEndTakeHomeBase}/show-the-local-weather`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd1f', + title: 'Use the TwitchTV JSON API', + link: `${legacyFrontEndTakeHomeBase}/use-the-twitch-json-api`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd18', + title: 'Build a Tribute Page', + link: `${legacyFrontEndResponsiveBase}/build-a-tribute-page`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd19', + title: 'Build a Wikipedia Viewer', + link: `${legacyFrontEndTakeHomeBase}/build-a-wikipedia-viewer`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eedfaeb5bd1c', + title: 'Build a Tic Tac Toe Game', + link: `${legacyFrontEndTakeHomeBase}/build-a-tic-tac-toe-game`, + certSlug: Certification.LegacyFrontEnd + }, + { + id: 'bd7158d8c442eddfaeb5bd1c', + title: 'Build a Memory Light Game', + link: `${legacyFrontEndTakeHomeBase}/build-a-memory-light-game`, + certSlug: Certification.LegacyFrontEnd + } + ] + }, + { + id: '561abd10cb81ac38a17513bc', + title: 'Legacy JavaScript Algorithms and Data Structures', + certSlug: Certification.JsAlgoDataStruct, + projects: [ + { + id: 'aaa48de84e1ecc7c742e1124', + title: 'Palindrome Checker', + link: `${jsAlgoBase}/palindrome-checker`, + certSlug: Certification.JsAlgoDataStruct + }, + { + id: 'a7f4d8f2483413a6ce226cac', + title: 'Roman Numeral Converter', + link: `${jsAlgoBase}/roman-numeral-converter`, + certSlug: Certification.JsAlgoDataStruct + }, + { + id: '56533eb9ac21ba0edf2244e2', + title: 'Caesars Cipher', + link: `${jsAlgoBase}/caesars-cipher`, + certSlug: Certification.JsAlgoDataStruct + }, + { + id: 'aff0395860f5d3034dc0bfc9', + title: 'Telephone Number Validator', + link: `${jsAlgoBase}/telephone-number-validator`, + certSlug: Certification.JsAlgoDataStruct + }, + { + id: 'aa2e6f85cab2ab736c9a9b24', + title: 'Cash Register', + link: `${jsAlgoBase}/cash-register`, + certSlug: Certification.JsAlgoDataStruct + } + ] + }, + { + id: '660add10cb82ac38a17513be', + title: 'Legacy Back-End', + certSlug: Certification.LegacyBackEnd, + projects: [ + { + id: 'bd7158d8c443edefaeb5bdef', + title: 'Timestamp Microservice', + link: `${legacyBackEndBase}/timestamp-microservice`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443edefaeb5bdff', + title: 'Request Header Parser Microservice', + link: `${legacyBackEndBase}/request-header-parser-microservice`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443edefaeb5bd0e', + title: 'URL Shortener Microservice', + link: `${legacyBackEndBase}/url-shortener-microservice`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443edefaeb5bdee', + title: 'Image Search Abstraction Layer', + link: `${legacyBackEndTakeHomeBase}/build-an-image-search-abstraction-layer`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443edefaeb5bd0f', + title: 'File Metadata Microservice', + link: `${legacyBackEndBase}/file-metadata-microservice`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443eddfaeb5bdef', + title: 'Build a Voting App', + link: `${legacyBackEndTakeHomeBase}/build-a-voting-app`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443eddfaeb5bdff', + title: 'Build a Nightlife Coordination App', + link: `${legacyBackEndTakeHomeBase}/build-a-nightlife-coordination-app`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443eddfaeb5bd0e', + title: 'Chart the Stock Market', + link: `${legacyBackEndTakeHomeBase}/chart-the-stock-market`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443eddfaeb5bd0f', + title: 'Manage a Book Trading Club', + link: `${legacyBackEndTakeHomeBase}/manage-a-book-trading-club`, + certSlug: Certification.LegacyBackEnd + }, + { + id: 'bd7158d8c443eddfaeb5bdee', + title: 'Build a Pinterest Clone', + link: `${legacyBackEndTakeHomeBase}/build-a-pinterest-clone`, + certSlug: Certification.LegacyBackEnd + } + ] + }, + + { + id: '561add10cb82ac39a17513bc', + title: 'Legacy Data Visualization', + certSlug: Certification.LegacyDataVis, + projects: [ + { + id: 'bd7157d8c242eddfaeb5bd13', + title: 'Build a Markdown Previewer', + link: `${legacyDataVisFrontEndBase}/build-a-markdown-previewer`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7156d8c242eddfaeb5bd13', + title: 'Build a freeCodeCamp Forum Homepage', + link: `${legacyDataVisTakeHomeBase}/build-a-freecodecamp-forum-homepage`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7155d8c242eddfaeb5bd13', + title: 'Build a Recipe Box', + link: `${legacyDataVisTakeHomeBase}/build-a-recipe-box`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7154d8c242eddfaeb5bd13', + title: 'Build the Game of Life', + link: `${legacyDataVisTakeHomeBase}/build-the-game-of-life`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7153d8c242eddfaeb5bd13', + title: 'Build a Roguelike Dungeon Crawler Game', + link: `${legacyDataVisTakeHomeBase}/build-a-roguelike-dungeon-crawler-game`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7168d8c242eddfaeb5bd13', + title: 'Visualize Data with a Bar Chart', + link: `${legacyDataVisBase}/visualize-data-with-a-bar-chart`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7178d8c242eddfaeb5bd13', + title: 'Visualize Data with a Scatterplot Graph', + link: `${legacyDataVisBase}/visualize-data-with-a-scatterplot-graph`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7188d8c242eddfaeb5bd13', + title: 'Visualize Data with a Heat Map', + link: `${legacyDataVisBase}/visualize-data-with-a-heat-map`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7198d8c242eddfaeb5bd13', + title: 'Show National Contiguity with a Force Directed Graph', + link: `${legacyDataVisTakeHomeBase}/show-national-contiguity-with-a-force-directed-graph`, + certSlug: Certification.LegacyDataVis + }, + { + id: 'bd7108d8c242eddfaeb5bd13', + title: 'Map Data Across the Globe', + link: `${legacyDataVisTakeHomeBase}/map-data-across-the-globe`, + certSlug: Certification.LegacyDataVis + } + ] + }, + { + id: '561add10cb82ac38a17213bc', + title: 'Legacy Information Security and Quality Assurance', + // Keep this as information-security-and-quality-assurance + certSlug: Certification.LegacyInfoSecQa, + projects: [ + // Keep this as information-security-and-quality-assurance + { + id: '587d8249367417b2b2512c41', + title: 'Metric-Imperial Converter', + link: `${legacyInfosecQaQaBase}/metric-imperial-converter`, + certSlug: Certification.LegacyInfoSecQa + }, + { + id: '587d8249367417b2b2512c42', + title: 'Issue Tracker', + link: `${legacyInfosecQaQaBase}/issue-tracker`, + certSlug: Certification.LegacyInfoSecQa + }, + { + id: '587d824a367417b2b2512c43', + title: 'Personal Library', + link: `${legacyInfosecQaQaBase}/personal-library`, + certSlug: Certification.LegacyInfoSecQa + }, + { + id: '587d824a367417b2b2512c44', + title: 'Stock Price Checker', + link: `${legacyInfosecQaInfosecBase}/stock-price-checker`, + certSlug: Certification.LegacyInfoSecQa + }, + { + id: '587d824a367417b2b2512c45', + title: 'Anonymous Message Board', + link: `${legacyInfosecQaInfosecBase}/anonymous-message-board`, + certSlug: Certification.LegacyInfoSecQa + } + ] + }, + { + id: '647f7da207d29547b3bee1ba', + title: 'Foundational C# with Microsoft', + certSlug: Certification.FoundationalCSharp, + projects: [ + { + id: '647e22d18acb466c97ccbef8', + title: 'Foundational C# with Microsoft Certification Exam', + link: `${foundationalCSharpBase}/foundational-c-sharp-with-microsoft-certification-exam`, + certSlug: Certification.FoundationalCSharp + } + ] + }, + // Upcoming Certifications + { + id: '68db314d3c11a8bff07c7535', + title: 'Responsive Web Design', + certSlug: Certification.RespWebDesignV9, + projects: [ + { + id: '68db37350b398ecddd1f5dac', + title: 'Responsive Web Design Certification Exam', + link: `${respWebV9Base}/exam-responsive-web-design-certification/exam-responsive-web-design-certification`, + certSlug: Certification.RespWebDesignV9 + } + ] + }, + { + id: '68c4069c1ef859270e17c495', + title: 'JavaScript', + certSlug: Certification.JsV9, + projects: [ + { + id: '68c462d7dc707f3ca82f8e6d', + title: 'JavaScript Certification Exam', + link: `${jsV9Base}/exam-javascript-certification/exam-javascript-certification`, + certSlug: Certification.JsV9 + } + ] + }, + { + id: '68e008aa5f80c6099d47b3a2', + title: 'Front-End Development Libraries', + certSlug: Certification.FrontEndDevLibsV9, + projects: [ + { + id: '68e00b355f80c6099d47b3a3', + title: 'Front-End Development Libraries Certification Exam', + link: `${frontEndDevLibsV9Base}/exam-front-end-development-libraries-certification/exam-front-end-development-libraries-certification`, + certSlug: Certification.FrontEndDevLibsV9 + } + ] + }, + { + id: '68e6bd5020effa1586e79855', + title: 'Python', + certSlug: Certification.PythonV9, + projects: [ + { + id: '68e6bf0320effa1586e79858', + title: 'Python Certification Exam', + link: `${pythonV9Base}/exam-python-certification/exam-python-certification`, + certSlug: Certification.PythonV9 + } + ] + }, + { + id: '68e6bd5120effa1586e79856', + title: 'Relational Databases', + certSlug: Certification.RelationalDbV9, + projects: [ + { + id: '68e6bf3f20effa1586e79859', + title: 'Relational Databases Certification Exam', + link: `${relationalDbV9Base}/exam-relational-databases-certification/exam-relational-databases-certification`, + certSlug: Certification.RelationalDbV9 + } + ] + }, + { + id: '68e6bd5120effa1586e79857', + title: 'Back-End Development and APIs', + certSlug: Certification.BackEndDevApisV9, + projects: [ + { + id: '68e6bfa120effa1586e7985a', + title: 'Back-End Development and APIs Certification Exam', + link: `${backEndDevApisV9Base}/exam-back-end-development-and-apis-certification/exam-back-end-development-and-apis-certification`, + certSlug: Certification.BackEndDevApisV9 + } + ] + }, + { + id: '64514fda6c245de4d11eb7bb', + title: 'Certified Full-Stack Developer', + certSlug: Certification.FullStackDeveloperV9, + projects: [ + { + id: '645147516c245de4d11eb7ba', + title: 'Certified Full-Stack Developer Exam', + link: `${fullStackDeveloperV9Base}/exam-certified-full-stack-developer/exam-certified-full-stack-developer`, + certSlug: Certification.FullStackDeveloperV9 + } + ] + }, + { + id: '651dd7e01d697d0aab7833b7', + title: 'A2 English for Developers', + certSlug: Certification.A2English, + projects: [ + { + id: '6721db5d9f0c116e6a0fe25a', + title: 'A2 English for Developers Certification Exam', + link: `${a2EnglishBase}/en-a2-certification-exam/en-a2-certification-exam`, + certSlug: Certification.A2English + } + ] + }, + { + id: '66607e53317411dd5e8aae21', + title: 'B1 English for Developers', + certSlug: Certification.B1English, + projects: [ + { + id: '694106b87224ea1c1a9d3201', + title: 'B1 English for Developers Certification Exam', + link: `${b1EnglishBase}/en-b1-certification-exam/en-b1-certification-exam`, + certSlug: Certification.B1English + } + ] + }, + { + id: '681a6b22e5a782fe3459984a', + title: 'A2 Professional Spanish', + certSlug: Certification.A2Spanish, + projects: [ + { + id: '681a8796e5a782fe3459984b', + title: 'Dialogue 1: PLACEHOLDER', + link: `${a2SpanishBase}/talk-about-who-you-are-by-using-key-verbs +/text-1`, + certSlug: Certification.A2Spanish + } + ] + }, + { + id: '682c3153086dd7cabe7f48bc', + title: 'A2 Professional Chinese', + certSlug: Certification.A2Chinese, + projects: [ + { + id: '682c2753317b88f1ecdad894', + title: 'Dialogue 1: PLACEHOLDER', + link: `${a2ChineseBase}/talk-about-what-you-do-by-using-key-verbs +/text-1`, + certSlug: Certification.A2Chinese + } + ] + }, + { + id: '68f1268149f045a650d4229e', + title: 'A1 Professional Chinese', + certSlug: Certification.A1Chinese, + projects: [ + { + id: '688f1daf0133dbe2a36b140b', + title: 'Dialogue 1: PLACEHOLDER', + link: `${a1ChineseBase}/learn-essential-courtesies-at-the-office +/text-1`, + certSlug: Certification.A1Chinese + } + ] + } +] as const; + +function getResponsiveWebDesignPath(project: string) { + return `${responsiveWeb22Base}/${project}-project/${project}`; +} + +function getCollegeAlgebraPyPath(project: string) { + return `${collegeAlgebraPyBase}/${project}-project/${project}`; +} + +function getJavaScriptAlgoPath(project: string) { + return `${jsAlgo22Base}/${project}-project/${project}`; +} + +type FilteredCert = T extends { certSlug: U } ? T : never; + +type CurrentCert = FilteredCert< + (typeof allStandardCerts)[number], + (typeof currentCertifications)[number] +>; + +type LegacyCert = FilteredCert< + (typeof allStandardCerts)[number], + (typeof legacyCertifications)[number] +>; + +type UpcomingCert = FilteredCert< + (typeof allStandardCerts)[number], + (typeof upcomingCertifications)[number] +>; + +const currentCerts = allStandardCerts.filter((cert): cert is CurrentCert => + currentCertifications.includes(cert.certSlug) +); +const legacyCerts = allStandardCerts.filter((cert): cert is LegacyCert => + legacyCertifications.includes(cert.certSlug) +); +const upcomingCerts = allStandardCerts.filter((cert): cert is UpcomingCert => + upcomingCertifications.includes(cert.certSlug) +); +const liveCerts = showUpcomingChanges + ? [...currentCerts, ...legacyCerts, fullstackCert, ...upcomingCerts] + : [...currentCerts, ...legacyCerts, fullstackCert]; +const allCerts = [ + ...currentCerts, + ...legacyCerts, + fullstackCert, + ...upcomingCerts +]; + +type CertsToProjects = Record< + (typeof allStandardCerts)[number]['certSlug'], + (typeof allStandardCerts)[number]['projects'] +>; + +const certsToProjects = allStandardCerts.reduce((acc, curr) => { + return { + ...acc, + [curr.certSlug]: curr.projects + }; +}, {} as CertsToProjects); + +export { liveCerts, certsToProjects, allCerts }; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/config/growthbook-features-default.json b/github_code/freeCodeCamp__freeCodeCamp/client/config/growthbook-features-default.json new file mode 100644 index 0000000000000000000000000000000000000000..3a4001d1e28f32a5a7c703ae269278d3996264b8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/config/growthbook-features-default.json @@ -0,0 +1,151 @@ +{ + "aa-test": { + "defaultValue": false + }, + "aa-test-in-component": { + "defaultValue": false + }, + "rdb-codespaces-instructions": { + "defaultValue": true + }, + "rdb-local-instructions": { + "defaultValue": true + }, + "landing-top-skill-focused": { + "defaultValue": false, + "rules": [ + { + "coverage": 1, + "hashAttribute": "id", + "seed": "landing-top-skill-focused", + "hashVersion": 2, + "variations": [ + false, + true + ], + "weights": [ + 0.5, + 0.5 + ], + "key": "landing-top-skill-focused", + "meta": [ + { + "key": "0", + "name": "Control" + }, + { + "key": "1", + "name": "Variation 1" + } + ], + "phase": "0", + "name": "tests the conversion rate of the new design comparing to the old one" + } + ] + }, + "replace-20-with-25": { + "defaultValue": false, + "rules": [ + { + "coverage": 1, + "hashAttribute": "id", + "seed": "replace-20-with-25", + "hashVersion": 2, + "variations": [ + false, + true + ], + "weights": [ + 0.5, + 0.5 + ], + "key": "replace-20-with-25", + "meta": [ + { + "key": "0", + "name": "Control" + }, + { + "key": "1", + "name": "Variation 1" + } + ], + "phase": "0", + "name": "stg replace 20 with 25" + } + ] + }, + "show-modal-randomly": { + "defaultValue": false, + "rules": [ + { + "coverage": 1, + "hashAttribute": "id", + "seed": "show-modal-randomly", + "hashVersion": 2, + "variations": [ + false, + true + ], + "weights": [ + 0.5, + 0.5 + ], + "key": "show-modal-randomly", + "meta": [ + { + "key": "0", + "name": "Control" + }, + { + "key": "1", + "name": "Variation 1" + } + ], + "phase": "0", + "name": "stg show modal randomly" + } + ] + }, + "landing-two-button-cta": { + "defaultValue": false, + "rules": [ + { + "coverage": 1, + "hashAttribute": "id", + "seed": "landing-two-button-cta", + "hashVersion": 2, + "variations": [ + false, + true + ], + "weights": [ + 0.5, + 0.5 + ], + "key": "landing-two-button-cta", + "meta": [ + { + "key": "0", + "name": "Control" + }, + { + "key": "1", + "name": "Variation 1" + } + ], + "phase": "0", + "name": "prod-landing-two-button-cta" + } + ] + }, + "classroom-mode": { + "defaultValue": false + }, + "disabled_blocks": { + "defaultValue": [] + }, + "show-socrates": { + "defaultValue": false + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/config/misc.ts b/github_code/freeCodeCamp__freeCodeCamp/client/config/misc.ts new file mode 100644 index 0000000000000000000000000000000000000000..228e312876909a8bd8d6fe0913dcaf031cb93122 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/config/misc.ts @@ -0,0 +1,4 @@ +export const MAX_MOBILE_WIDTH = 767; +export const EX_SMALL_VIEWPORT_HEIGHT = 300; +export const SEARCH_EXPOSED_WIDTH = 980; +export const GITHUB_LOCATION = 'https://github.com/freeCodeCamp'; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/eslint.config.mjs b/github_code/freeCodeCamp__freeCodeCamp/client/eslint.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ac2bc845a8767da7338af04df9d0e468690b8f8a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/eslint.config.mjs @@ -0,0 +1,78 @@ +import { + config, + configTypeChecked, + configReact, + configTestingLibrary, + jsFiles, + tsFiles +} from '@freecodecamp/eslint-config/base'; +import globals from 'globals'; + +import { defineConfig, globalIgnores } from 'eslint/config'; + +const baseLanguageOptions = { + globals: { + ...globals.browser, + ...globals.mocha, + ...globals.node, + Promise: true, + window: true, + $: true, + ga: true, + jQuery: true, + router: true, + globalThis: true + } +}; + +const baseConfig = { + settings: { + react: { + version: '16.4.2' + }, + + 'import/resolver': { + typescript: true, + node: true + } + }, + + rules: { + 'import/no-cycle': [ + 2, + { + maxDepth: 2 + } + ], + 'react/prop-types': 'off', + 'react/jsx-no-useless-fragment': 'error' + } +}; + +// Order matters here; later configs can override settings in earlier ones. +export default defineConfig( + globalIgnores(['static', '.cache', 'public']), + { + files: jsFiles, + extends: [configReact, configTestingLibrary, config], + ...baseConfig, + languageOptions: { + ...baseLanguageOptions, + + parserOptions: { + babelOptions: { + presets: ['@babel/preset-react'], + configFile: './.babelrc.js' + } + } + } + }, + { + files: tsFiles, + extends: [configReact, configTestingLibrary, configTypeChecked], + ...baseConfig, + languageOptions: { + ...baseLanguageOptions + } + } +); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-browser.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-browser.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2aa5006d0d394a5da1ecd1d3ceef335c43a91377 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-browser.tsx @@ -0,0 +1,50 @@ +import type { GatsbyBrowser } from 'gatsby'; +import { LocationProvider } from '@gatsbyjs/reach-router'; +import cookies from 'browser-cookies'; +import React from 'react'; +import { I18nextProvider } from 'react-i18next'; +import { Provider } from 'react-redux'; +import { Elements } from '@stripe/react-stripe-js'; + +import i18n from './i18n/config'; +import { stripe } from './src/utils/stripe'; +import AppMountNotifier from './src/components/app-mount-notifier'; +import { createStore } from './src/redux/create-store'; +import layoutSelector from './utils/gatsby/layout-selector'; +import GrowthBookProvider from './src/components/growth-book/growth-book-wrapper'; + +const store = createStore(); + +export const wrapRootElement: GatsbyBrowser['wrapRootElement'] = ({ + element +}) => { + return ( + + + + + + {element} + + + + + + ); +}; + +export const wrapPageElement: GatsbyBrowser['wrapPageElement'] = layoutSelector; + +export const disableCorePrefetching: GatsbyBrowser['disableCorePrefetching'] = + () => true; + +export const onRouteUpdate: GatsbyBrowser['onRouteUpdate'] = () => { + store.dispatch({ type: 'app.routeUpdated' }); +}; + +export const onClientEntry: GatsbyBrowser['onClientEntry'] = () => { + // Letting the users' browsers expire the cookie seems to have caused issues + // for some users. Until we have time to investigate further, we should remove + // the cookie on every page load. + cookies.erase('csrf_token'); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-config.ts b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-config.ts new file mode 100644 index 0000000000000000000000000000000000000000..f2e9faa734902048970a834a5de9f5b43161edeb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-config.ts @@ -0,0 +1,70 @@ +import path from 'path'; +import type { GatsbyConfig } from 'gatsby'; + +import envData from './config/env.json'; +import { + buildChallenges, + replaceChallengeNodes, + localeChallengesRootDir +} from './utils/build-challenges'; +import { pathPrefix } from './utils/gatsby/path-prefix'; + +const { homeLocation } = envData; + +const config: GatsbyConfig = { + flags: { + DEV_SSR: false + }, + trailingSlash: 'ignore', + siteMetadata: { + title: 'freeCodeCamp', + siteUrl: homeLocation + }, + pathPrefix: pathPrefix, + plugins: [ + 'gatsby-plugin-pnpm-gatsby-5', + { + resolve: 'gatsby-plugin-webpack-bundle-analyser-v2', + options: { + analyzerMode: 'disabled', + // It doesn't matter if the file is generated or not as far as caching + // is concerned. It doesn't affect any tasks in any way, so we can + // ignore it. + + // eslint-disable-next-line turbo/no-undeclared-env-vars + generateStatsFile: process.env.CI + } + }, + 'gatsby-plugin-react-helmet', + { + resolve: 'gatsby-plugin-postcss', + options: { + postcssOptions: { + config: path.resolve(__dirname, 'postcss.config.js') + } + } + }, + { + resolve: path.resolve( + __dirname, + '../tools/client-plugins/gatsby-source-challenges' + ), + options: { + name: 'challenges', + source: buildChallenges, + onSourceChange: replaceChallengeNodes(), + curriculumPath: localeChallengesRootDir + } + }, + 'gatsby-plugin-remove-serviceworker', + { + resolve: 'gatsby-plugin-schema-snapshot', + options: { + path: 'schema.gql', + update: process.env.GATSBY_UPDATE_SCHEMA_SNAPSHOT === 'true' + } + } + ] +}; + +export default config; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-node.ts b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-node.ts new file mode 100644 index 0000000000000000000000000000000000000000..45ba9bf2f25e667112e79ada72a6c52c5d6c2767 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-node.ts @@ -0,0 +1,137 @@ +/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access */ + +const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin'); + +const env = require('./config/env.json'); +const { createSuperBlockIntroPages } = require('./utils/gatsby'); + +exports.createPages = async function createPages({ + actions, + graphql, + reporter +}: any) { + if (!env.algoliaAPIKey || !env.algoliaAppId) { + if (process.env.FREECODECAMP_NODE_ENV === 'production') { + throw new Error( + 'Algolia App id and API key are required to start the client!' + ); + } else { + reporter.info( + 'Algolia keys missing or invalid. Required for search to yield results.' + ); + } + } + + if (!env.stripePublicKey) { + if (process.env.FREECODECAMP_NODE_ENV === 'production') { + throw new Error('Stripe public key is required to start the client!'); + } else { + reporter.info( + 'Stripe public key is missing or invalid. Required for Stripe integration.' + ); + } + } + + const { createPage } = actions; + + const result = await graphql(` + { + allSuperBlockStructure { + nodes { + superBlock + } + } + } + `); + + if (result.errors) { + reporter.panic('createPages GraphQL query failed', result.errors); + } + + const { + data: { allSuperBlockStructure } + } = result; + + const superBlocks = allSuperBlockStructure.nodes.map( + (node: { superBlock: string }) => node.superBlock + ); + + superBlocks.forEach((superBlock: string) => { + createSuperBlockIntroPages(createPage)({ superBlock }); + }); +}; + +exports.onCreateWebpackConfig = ({ stage, actions, plugins }: any) => { + const newPlugins = [ + // We add the shims of the node globals to the global scope + plugins.provide({ + Buffer: ['buffer', 'Buffer'] + }), + plugins.provide({ + process: 'process/browser' + }) + ]; + + // The monaco editor relies on some browser only globals so should not be + // involved in SSR. Also, if the plugin is used during the 'build-html' or + // 'develop-html' stage it overwrites the minfied files with ordinary ones. + + if (stage !== 'build-html' && stage !== 'develop-html') { + newPlugins.push( + new MonacoWebpackPlugin({ + filename: '[name].worker-[contenthash].js' + }) + ); + } + + actions.setWebpackConfig({ + resolve: { + fallback: { + fs: false, + path: 'path-browserify', + assert: 'assert', + crypto: 'crypto-browserify', + util: 'util/util', + buffer: 'buffer', + stream: 'stream-browserify', + process: 'process/browser', + url: 'url' + } + }, + plugins: newPlugins, + ignoreWarnings: [ + (warning: Error) => { + if (warning instanceof Error) { + if (warning.message.includes('mini-css-extract-plugin')) { + return true; + } + } + return false; + } + ] + }); +}; + +exports.onCreateBabelConfig = ({ actions }: any) => { + actions.setBabelPlugin({ + name: '@babel/plugin-proposal-function-bind' + }); + + actions.setBabelPlugin({ + name: '@babel/plugin-proposal-export-default-from' + }); +}; + +exports.createSchemaCustomization = ({ actions }: any) => { + const { createTypes } = actions; + + // This hook is supported by the test runner, but is not currently used by the + // client, so we have to tell Gatsby that it exists. + const typeDefs = ` + type ChallengeNodeChallengeHooks { + afterEach: String + } + `; + + createTypes(typeDefs); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-ssr.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-ssr.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e95022e8f506a1b3573ee7a0bc9cddf7d76b6b6d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/gatsby-ssr.tsx @@ -0,0 +1,66 @@ +import type { GatsbySSR } from 'gatsby'; +import React from 'react'; +import { I18nextProvider } from 'react-i18next'; +import { Provider } from 'react-redux'; +import { Elements } from '@stripe/react-stripe-js'; + +import i18n from './i18n/config'; +import { stripe } from './src/utils/stripe'; +import { createStore } from './src/redux/create-store'; +import layoutSelector from './utils/gatsby/layout-selector'; +import { webmanifestComponents } from './src/components/webmanifest'; +import { + getheadTagComponents, + getPostBodyComponents, + getPreBodyThemeScript +} from './utils/tags'; +import GrowthBookProvider from './src/components/growth-book/growth-book-wrapper'; + +const store = createStore(); + +export const wrapRootElement: GatsbySSR['wrapRootElement'] = ({ element }) => { + return ( + + + + {element} + + + + ); +}; + +export const wrapPageElement: GatsbySSR['wrapPageElement'] = layoutSelector; + +export const onRenderBody: GatsbySSR['onRenderBody'] = ({ + pathname, + setHeadComponents, + setPreBodyComponents, + setPostBodyComponents +}) => { + setHeadComponents([...getheadTagComponents(), ...webmanifestComponents]); + setPreBodyComponents(getPreBodyThemeScript()); + setPostBodyComponents(getPostBodyComponents(pathname)); +}; + +export const onPreRenderHTML: GatsbySSR['onPreRenderHTML'] = ({ + getHeadComponents, + replaceHeadComponents +}) => { + const isBootstrapScript = (key: React.Key | null) => + key === 'bootstrap-min-preload' || key === 'bootstrap-min'; + + const headComponents = getHeadComponents(); + headComponents.sort((x, y) => { + const xKey = React.isValidElement(x) ? x.key : null; + const yKey = React.isValidElement(y) ? y.key : null; + + if (isBootstrapScript(xKey)) { + return -1; + } else if (isBootstrapScript(yKey)) { + return 1; + } + return 0; + }); + replaceHeadComponents(headComponents); +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config-for-tests.ts b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config-for-tests.ts new file mode 100644 index 0000000000000000000000000000000000000000..65fab3e8410a16685e5a4df878462b2b1258a77e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config-for-tests.ts @@ -0,0 +1,22 @@ +import i18n from 'i18next'; +import { initReactI18next } from 'react-i18next'; + +i18n + .use(initReactI18next) + .init({ + debug: true, + defaultNS: 'translations', + fallbackLng: 'en', + interpolation: { + escapeValue: false + }, + lng: 'en', + ns: ['intro', 'translations'], + resources: { en: { intro: {}, translations: {} } }, + returnNull: false + }) + .catch((error: Error) => { + throw Error(error.message); + }); + +export default i18n; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config.js b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config.js new file mode 100644 index 0000000000000000000000000000000000000000..434c72c7daf52d78cd2dec0152f9f273097a47a6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/config.js @@ -0,0 +1,91 @@ +/* global preval */ + +import i18n from 'i18next'; +import { initReactI18next } from 'react-i18next'; +import { i18nextCodes } from '@freecodecamp/shared/config/i18n'; + +import translations from './locales/english/translations.json'; +import trending from './locales/english/trending.json'; +import intro from './locales/english/intro.json'; +import metaTags from './locales/english/meta-tags.json'; +import links from './locales/english/links.json'; +import searchBar from './locales/english/search-bar.json'; + +import envData from '../config/env.json'; + +const { clientLocale } = envData; + +const i18nextCode = i18nextCodes[clientLocale]; + +// Non-english locale resources are loaded via preval so that webpack only +// bundles the single locale selected by CLIENT_LOCALE and the english fallback. +// For english the preval returns undefined, so webpack will not bundle the +// english resources twice. +i18n.use(initReactI18next).init({ + fallbackLng: 'en', + lng: i18nextCode, + resources: { + [i18nextCode]: { + translations: preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/translations.json'); + } + `, + trending: preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/trending.json'); + } + `, + intro: preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/intro.json'); + } + `, + metaTags: preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/meta-tags.json'); + } + `, + links: preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/links.json'); + } + `, + 'search-bar': preval` + const { clientLocale } = require('../config/env.json'); + if (clientLocale !== 'english') { + module.exports = require('./locales/' + clientLocale + '/search-bar.json'); + } + ` + }, + en: { + translations, + trending, + intro, + metaTags, + links, + 'search-bar': searchBar + } + }, + ns: ['translations', 'trending', 'intro', 'metaTags', 'links', 'search-bar'], + defaultNS: 'translations', + returnObjects: true, + // Uncomment the next line for debug logging + // debug: true, + interpolation: { + escapeValue: false + }, + react: { + useSuspense: true + }, + returnNull: false +}); + +i18n.languages = clientLocale; + +export default i18n; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales.test.ts b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..756401d8df839abb69f9063cd53eb6b90dde5a6e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales.test.ts @@ -0,0 +1,120 @@ +import { dirname } from 'path'; +import { fileURLToPath } from 'url'; + +import { describe, test, expect } from 'vitest'; + +import { + availableLangs, + LangNames, + LangCodes +} from '@freecodecamp/shared/config/i18n'; +import { + SuperBlocks, + superBlockStages, + SuperBlockStage +} from '@freecodecamp/shared/config/curriculum'; +import { getCurriculum } from '../tools/get-curriculum'; +import intro from './locales/english/intro.json'; + +interface Intro { + [key: string]: { + title: string; + summary?: string[]; + intro: string[]; + blocks: { + [block: string]: { + title: string; + intro: string[]; + }; + }; + }; +} + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +describe('Locale tests:', () => { + availableLangs.client.forEach(lang => { + describe(`-- ${lang} --`, () => { + test(`has an entry in the langDisplayNames enum`, () => { + expect( + Object.keys(LangNames) + .map(langCode => langCode.toLowerCase()) + .includes(lang) + ).toBe(true); + }); + + test(`has an entry in the langCodes enum`, () => { + expect( + Object.keys(LangCodes) + .map(langCode => langCode.toLowerCase()) + .includes(lang) + ).toBe(true); + }); + }); + }); +}); + +describe('Intro file structure tests:', () => { + const typedIntro = intro as unknown as Intro; + const superblocks = Object.values(SuperBlocks); + const catalogSuperBlocks = superBlockStages[SuperBlockStage.Catalog]; + for (const superBlock of superblocks) { + test(`superBlock ${superBlock} has required properties`, () => { + expect(typeof typedIntro[superBlock].title).toBe('string'); + + // catalog superblocks should have a summary + expect( + !catalogSuperBlocks.includes(superBlock) || + Array.isArray(typedIntro[superBlock].summary) + ).toBe(true); + + expect(typedIntro[superBlock].intro).toBeInstanceOf(Array); + expect(typedIntro[superBlock].blocks).toBeInstanceOf(Object); + const blocks = Object.keys(typedIntro[superBlock].blocks); + blocks.forEach(block => { + expect(typeof typedIntro[superBlock].blocks[block].title).toBe( + 'string' + ); + expect(typedIntro[superBlock].blocks[block].intro).toBeInstanceOf( + Array + ); + }); + }); + } +}); + +type SuperBlockInfo = { + blocks: Record; +}; + +describe('Curriculum validation', () => { + const curriculum = getCurriculum() as Record; + // certifications are not superblocks, they're just mixed in with them. + const superblocks = Object.entries(curriculum).filter( + ([key]) => key !== 'certifications' + ); + + // It's important that we check that each block in the curriculum has a title + // in the intro, rather than the other way around, because the intro must + // include upcoming changes. The curriculum only does if SHOW_UPCOMING_CHANGES + // is true. + superblocks.forEach(superblock => { + const [name, superBlockInfo] = superblock; + const blockObject = superBlockInfo.blocks; + describe(`${name}`, () => { + test('should have titles for each block in intro.json', () => { + const blocks = Object.keys(blockObject); + + blocks.forEach(block => { + const blockFromIntro = (intro as unknown as Intro)[superblock[0]] + .blocks[block]; + expect( + blockFromIntro.title, + `block ${block} needs a non-empty title` + ).toBeTruthy(); + }); + }); + }); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/arabic/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/arabic/links.json new file mode 100644 index 0000000000000000000000000000000000000000..d6dc081770787d445e4822aeae4f8237bde1346c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/arabic/links.json @@ -0,0 +1,43 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://cdn.freecodecamp.org/non-profit-docs/freeCodeCamp-determination-letter.pdf", + "download-990-url": "https://cdn.freecodecamp.org/non-profit-docs/freeCodeCamp-2019-f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp", + "one-time-external-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#how-can-i-make-a-one-time-donation", + "mail-check-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#can-i-mail-a-physical-check" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "programming/html-css", + "JavaScript": "programming/javascript", + "Python": "programming/python", + "Backend Development": "programming/backend-development", + "C-Sharp": "programming/c-sharp", + "English": "world-languages/english", + "Spanish Curriculum": "world-languages/spanish-curriculum", + "Chinese Curriculum": "world-languages/chinese-curriculum", + "Odin": "programming/the-odin-project", + "Euler": "programming/project-euler", + "Rosetta": "programming/rosetta-code", + "General": "General" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese-traditional/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese-traditional/links.json new file mode 100644 index 0000000000000000000000000000000000000000..f92ff1d80aa45e9e626860da2cb5adf2e4c9fedd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese-traditional/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://chinese.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://chinese.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://chinese.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://chinese.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://chinese.freecodecamp.org/news/how-to-donate-to-free-code-camp/", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/chinese/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://chinese.freecodecamp.org/news/", + "podcast": "open.spotify.com/show/3dIVV6XRRPMs75z2xDtsOg?si=Ugm6rwlcTgiEJ1Udw9WzVQ" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese/links.json new file mode 100644 index 0000000000000000000000000000000000000000..f92ff1d80aa45e9e626860da2cb5adf2e4c9fedd --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/chinese/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://chinese.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://chinese.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://chinese.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://chinese.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://chinese.freecodecamp.org/news/how-to-donate-to-free-code-camp/", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/chinese/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://chinese.freecodecamp.org/news/", + "podcast": "open.spotify.com/show/3dIVV6XRRPMs75z2xDtsOg?si=Ugm6rwlcTgiEJ1Udw9WzVQ" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/intro.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/intro.json new file mode 100644 index 0000000000000000000000000000000000000000..8928d7142d07f65b78ccee8f5d5925f706072584 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/intro.json @@ -0,0 +1,10405 @@ +{ + "responsive-web-design": { + "title": "Legacy Responsive Web Design Challenges", + "intro": [ + "In this Responsive Web Design Certification, you'll learn the languages that developers use to build webpages: HTML (Hypertext Markup Language) for content, and CSS (Cascading Style Sheets) for design.", + "First, you'll build a cat photo app to learn the basics of HTML and CSS. Later, you'll learn modern techniques like CSS variables by building a penguin, and best practices for accessibility by building a web form.", + "Finally, you'll learn how to make webpages that respond to different screen sizes by building a Twitter card with Flexbox, and a complex blog layout with CSS Grid." + ], + "note": "Note: Some browser extensions, such as ad-blockers and dark mode extensions can interfere with the tests. If you face issues, we recommend disabling extensions that modify the content or layout of pages, while taking the course.", + "blocks": { + "basic-html-and-html5": { + "title": "Basic HTML and HTML5", + "intro": [ + "HTML is a markup language that uses a special syntax or notation to describe the structure of a webpage to the browser. HTML elements usually have opening and closing tags that surround and give meaning to content. For example, different elements can describe text as a heading, paragraph, or list item.", + "In this course, you'll build a cat photo app to learn some of the most common HTML elements — the building blocks of any webpage." + ] + }, + "basic-css": { + "title": "Basic CSS", + "intro": [ + "CSS, or Cascading Style Sheets, tell the browser how to display the text and other content that you write in HTML. With CSS, you can control the color, font, size, spacing, and many other aspects of HTML elements.", + "Now that you've described the structure of your cat photo app, give it some style with CSS." + ] + }, + "applied-visual-design": { + "title": "Applied Visual Design", + "intro": [ + "Visual design is a combination of typography, color theory, graphics, animation, page layout, and more to help deliver your unique message.", + "In this course, you'll learn how to apply these different elements of visual design to your webpages." + ] + }, + "applied-accessibility": { + "title": "Applied Accessibility", + "intro": [ + "In web development, accessibility refers to web content and a UI (user interface) that can be understood, navigated, and interacted with by a broad audience. This includes people with visual, auditory, mobility, or cognitive disabilities.", + "In this course, you'll learn best practices for building webpages that are accessible to everyone." + ] + }, + "responsive-web-design-principles": { + "title": "Responsive Web Design Principles", + "intro": [ + "There are many devices that can access the web, and they come in all shapes and sizes. Responsive web design is the practice of designing flexible websites that can respond to different screen sizes, orientations, and resolutions.", + "In this course, you'll learn how to use CSS to make your webpages look good, no matter what device they're viewed on." + ] + }, + "css-flexbox": { + "title": "CSS Flexbox", + "intro": [ + "Flexbox is a powerful, well-supported layout method that was introduced with the latest version of CSS, CSS3. With flexbox, it's easy to center elements on the page and create dynamic user interfaces that shrink and expand automatically.", + "In this course, you'll learn the fundamentals of flexbox and dynamic layouts by building a Twitter card." + ] + }, + "css-grid": { + "title": "CSS Grid", + "intro": [ + "The CSS grid is a newer standard that makes it easy to build complex responsive layouts. It works by turning an HTML element into a grid, and lets you place child elements anywhere within.", + "In this course, you'll learn the fundamentals of CSS grid by building different complex layouts, including a blog." + ] + } + } + }, + "2022/responsive-web-design": { + "title": "Legacy Responsive Web Design V8", + "intro": [ + "In this Responsive Web Design Certification, you'll learn the languages that developers use to build webpages: HTML (Hypertext Markup Language) for content, and CSS (Cascading Style Sheets) for design.", + "First, you'll build a cat photo app to learn the basics of HTML and CSS. Later, you'll learn modern techniques like CSS variables by building a penguin, and best practices for accessibility by building a quiz site.", + "Finally, you'll learn how to make webpages that respond to different screen sizes by building a photo gallery with Flexbox, and a magazine article layout with CSS Grid." + ], + "note": "Note: Some browser extensions, such as ad-blockers and dark mode extensions can interfere with the tests. If you face issues, we recommend disabling extensions that modify the content or layout of pages, while taking the course.", + "blocks": { + "build-a-tribute-page-project": { + "title": "Tribute Page", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a tribute page for a subject of your choosing, fictional or real." + ] + }, + "build-a-personal-portfolio-webpage-project": { + "title": "Personal Portfolio Webpage", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build your own personal portfolio page." + ] + }, + "build-a-product-landing-page-project": { + "title": "Product Landing Page", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a product landing page to market a product of your choice." + ] + }, + "build-a-survey-form-project": { + "title": "Survey Form", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a survey form to collect data from your users." + ] + }, + "build-a-technical-documentation-page-project": { + "title": "Technical Documentation Page", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a technical documentation page to serve as instruction or reference for a topic." + ] + }, + "learn-html-by-building-a-cat-photo-app": { + "title": "Learn HTML by Building a Cat Photo App", + "intro": [ + "HTML tags give a webpage its structure. You can use HTML tags to add photos, buttons, and other elements to your webpage.", + "In this course, you'll learn the most common HTML tags by building your own cat photo app." + ] + }, + "learn-basic-css-by-building-a-cafe-menu": { + "title": "Learn Basic CSS by Building a Cafe Menu", + "intro": [ + "CSS tells the browser how to display your webpage. You can use CSS to set the color, font, size, and other aspects of HTML elements.", + "In this course, you'll learn CSS by designing a menu page for a cafe webpage." + ] + }, + "learn-the-css-box-model-by-building-a-rothko-painting": { + "title": "Learn the CSS Box Model by Building a Rothko Painting", + "intro": [ + "Every HTML element is its own box – with its own spacing and a border. This is called the Box Model.", + "In this course, you'll use CSS and the Box Model to create your own Rothko-style rectangular art pieces." + ] + }, + "learn-css-variables-by-building-a-city-skyline": { + "title": "Learn CSS Variables by Building a City Skyline", + "intro": [ + "CSS variables help you organize your styles and reuse them.", + "In this course, you'll build a city skyline. You'll learn how to configure CSS variables so you can reuse them whenever you want." + ] + }, + "learn-html-forms-by-building-a-registration-form": { + "title": "Learn HTML Forms by Building a Registration Form", + "intro": [ + "You can use HTML forms to collect information from people who visit your webpage.", + "In this course, you'll learn HTML forms by building a signup page. You'll learn how to control what types of data people can type into your form, and some new CSS tools for styling your page." + ] + }, + "learn-accessibility-by-building-a-quiz": { + "title": "Learn Accessibility by Building a Quiz", + "intro": [ + "Accessibility is making your webpage easy for all people to use – even people with disabilities.", + "In this course, you'll build a quiz webpage. You'll learn accessibility tools such as keyboard shortcuts, ARIA attributes, and design best practices." + ] + }, + "learn-intermediate-css-by-building-a-picasso-painting": { + "title": "Learn Intermediate CSS by Building a Picasso Painting", + "intro": [ + "In this course, you'll learn how to use some intermediate CSS techniques by coding your own Picasso painting webpage. You'll learn about SVG icons, CSS positioning, and review other CSS skills you've learned." + ] + }, + "learn-responsive-web-design-by-building-a-piano": { + "title": "Learn Responsive Web Design by Building a Piano", + "intro": [ + "Responsive Design tells your webpage how it should look on different-sized screens.", + "In this course, you'll use CSS and responsive design to code a piano. You'll also learn more about media queries and pseudo selectors." + ] + }, + "learn-css-flexbox-by-building-a-photo-gallery": { + "title": "Learn CSS Flexbox by Building a Photo Gallery", + "intro": [ + "Flexbox helps you design your webpage so that it looks good on any screen size.", + "In this course, you'll use Flexbox to build a responsive photo gallery webpage." + ] + }, + "learn-css-grid-by-building-a-magazine": { + "title": "Learn CSS Grid by Building a Magazine", + "intro": [ + "CSS Grid gives you control over the rows and columns of your webpage design.", + "In this course, you'll build a magazine article. You'll learn how to use CSS Grid, including concepts like grid rows and grid columns." + ] + }, + "learn-typography-by-building-a-nutrition-label": { + "title": "Learn Typography by Building a Nutrition Label", + "intro": [ + "Typography is the art of styling your text to be easily readable and suit its purpose.", + "In this course, you'll use typography to build a nutrition label webpage. You'll learn how to style text, adjust line height, and position your text using CSS." + ] + }, + "learn-css-transforms-by-building-a-penguin": { + "title": "Learn CSS Transforms by Building a Penguin", + "intro": [ + "You can transform HTML elements to create appealing designs that draw your reader's eye. You can use transforms to rotate elements, scale them, and more.", + "In this course, you'll build a penguin. You'll use CSS transforms to position and resize the parts of your penguin, create a background, and animate your work." + ] + }, + "learn-css-animation-by-building-a-ferris-wheel": { + "title": "Learn CSS Animation by Building a Ferris Wheel", + "intro": [ + "You can use CSS animation to draw attention to specific sections of your webpage and make it more engaging.", + "In this course, you'll build a Ferris wheel. You'll learn how to use CSS to animate elements, transform them, and adjust their speed." + ] + }, + "learn-more-about-css-pseudo-selectors-by-building-a-balance-sheet": { + "title": "Learn More About CSS Pseudo Selectors by Building A Balance Sheet", + "intro": [ + "You can use CSS pseudo selectors to change specific HTML elements.", + "In this course, you'll build a balance sheet using pseudo selectors. You'll learn how to change the style of an element when you hover over it with your mouse, and trigger other events on your webpage." + ] + }, + "learn-css-colors-by-building-a-set-of-colored-markers": { + "title": "Learn CSS Colors by Building a Set of Colored Markers", + "intro": [ + "Selecting the correct colors for your webpage can greatly improve the aesthetic appeal to your readers.", + "In this course, you'll build a set of colored markers. You'll learn different ways to set color values and how to pair colors with each other." + ] + }, + "learn-intermediate-css-by-building-a-cat-painting": { + "title": "Learn Intermediate CSS by Building a Cat Painting", + "intro": [ + "Mastering CSS positioning is essential for creating visually appealing and responsive web layouts", + "In this course, you will build a cat painting. You'll learn about how to work with absolute positioning, the z-index property, and the transform property." + ] + } + } + }, + "javascript-algorithms-and-data-structures": { + "title": "Legacy JavaScript Algorithms and Data Structures V7", + "intro": [ + "While HTML and CSS control the content and styling of a page, JavaScript is used to make it interactive. In the JavaScript Algorithm and Data Structures Certification, you'll learn the fundamentals of JavaScript including variables, arrays, objects, loops, and functions.", + "Once you have the fundamentals down, you'll apply that knowledge by creating algorithms to manipulate strings, factorialize numbers, and even calculate the orbit of the International Space Station.", + "Along the way, you'll also learn two important programming styles or paradigms: Object Oriented Programming (OOP) and Functional Programming (FP)." + ], + "note": "Note: Some browser extensions, such as ad-blockers and script-blockers can interfere with the tests. If you face issues, we recommend disabling extensions that modify or block the content of pages while taking the course.", + "blocks": { + "basic-javascript": { + "title": "Basic JavaScript", + "intro": [ + "JavaScript is a scripting language you can use to make web pages interactive. It is one of the core technologies of the web, along with HTML and CSS, and is supported by all modern browsers.", + "In this course, you'll learn fundamental programming concepts in JavaScript. You'll start with basic data structures like numbers and strings. Then you'll learn to work with arrays, objects, functions, loops, if/else statements, and more." + ] + }, + "es6": { + "title": "ES6", + "intro": [ + "ECMAScript, or ES, is a standardized version of JavaScript. Because all major browsers follow this specification, the terms ECMAScript and JavaScript are interchangeable.", + "Most of the JavaScript you've learned up to this point was in ES5 (ECMAScript 5), which was finalized in 2009. While you can still write programs in ES5, JavaScript is constantly evolving, and new features are released every year.", + "ES6, released in 2015, added many powerful new features to the language. In this course, you'll learn these new features, including arrow functions, destructuring, classes, promises, and modules." + ] + }, + "regular-expressions": { + "title": "Regular Expressions", + "intro": [ + "Regular expressions, often shortened to \"regex\" or \"regexp\", are patterns that help programmers match, search, and replace text. Regular expressions are very powerful, but can be hard to read because they use special characters to make more complex, flexible matches.", + "In this course, you'll learn how to use special characters, capture groups, positive and negative lookaheads, and other techniques to match any text you want." + ] + }, + "debugging": { + "title": "Debugging", + "intro": [ + "Debugging is the process of going through your code, finding any issues, and fixing them.", + "Issues in code generally come in three forms: syntax errors that prevent your program from running, runtime errors where your code has unexpected behavior, or logical errors where your code doesn't do what you intended.", + "In this course, you'll learn how to use the JavaScript console to debug programs and prevent common issues before they happen." + ] + }, + "basic-data-structures": { + "title": "Basic Data Structures", + "intro": [ + "Data can be stored and accessed in many ways. You already know some common JavaScript data structures — arrays and objects.", + "In this Basic Data Structures course, you'll learn more about the differences between arrays and objects, and which to use in different situations. You'll also learn how to use helpful JS methods like splice() and Object.keys() to access and manipulate data." + ] + }, + "basic-algorithm-scripting": { + "title": "Basic Algorithm Scripting", + "intro": [ + "An algorithm is a series of step-by-step instructions that describe how to do something.", + "To write an effective algorithm, it helps to break a problem down into smaller parts and think carefully about how to solve each part with code.", + "In this course, you'll learn the fundamentals of algorithmic thinking by writing algorithms that do everything from converting temperatures to handling complex 2D arrays." + ] + }, + "object-oriented-programming": { + "title": "Object Oriented Programming", + "intro": [ + "OOP, or Object Oriented Programming, is one of the major approaches to the software development process. In OOP, objects and classes organize code to describe things and what they can do.", + "In this course, you'll learn the basic principles of OOP in JavaScript, including the this keyword, prototype chains, constructors, and inheritance." + ] + }, + "functional-programming": { + "title": "Functional Programming", + "intro": [ + "Functional Programming is another popular approach to software development. In Functional Programming, code is organized into smaller, basic functions that can be combined to build complex programs.", + "In this course, you'll learn the core concepts of Functional Programming including pure functions, how to avoid mutations, and how to write cleaner code with methods like .map() and .filter()." + ] + }, + "intermediate-algorithm-scripting": { + "title": "Intermediate Algorithm Scripting", + "intro": [ + "Now that you know the basics of algorithmic thinking, along with OOP and Functional Programming, test your skills with the Intermediate Algorithm Scripting challenges." + ] + }, + "javascript-algorithms-and-data-structures-projects": { + "title": "JavaScript Algorithms and Data Structures Projects", + "intro": [ + "This is it — time to put your new JavaScript skills to work. These projects are similar to the algorithm scripting challenges you've done before – just much more difficult.", + "Complete these 5 JavaScript projects to earn the JavaScript Algorithms and Data Structures certification." + ] + } + } + }, + "javascript-algorithms-and-data-structures-v8": { + "title": "Legacy JavaScript Algorithms and Data Structures V8", + "intro": [ + "Developers use HTML and CSS to control the content and styling of a page. And they use JavaScript to make that page interactive.", + "In this JavaScript Algorithm and Data Structures Certification, you'll learn the JavaScript fundamentals like variables, arrays, objects, loops, functions, the DOM and more.", + "You'll also learn about Object Oriented Programming (OOP), Functional Programming, algorithmic thinking, how to work with local storage, and how to fetch data using an API." + ], + "note": "Note: Some browser extensions, such as ad-blockers and script-blockers can interfere with the tests. If you face issues, we recommend disabling extensions that modify or block the content of pages while taking the course.", + "blocks": { + "build-an-rpg-creature-search-app-project": { + "title": "Build an RPG Creature Search App Project", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build an RPG creature search app." + ] + }, + "build-a-cash-register-project": { + "title": "Build a Cash Register Project", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you'll build a cash register web app." + ] + }, + "build-a-palindrome-checker-project": { + "title": "Build a Palindrome Checker Project", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you'll build an application that checks whether a given word is a palindrome." + ] + }, + "build-a-roman-numeral-converter-project": { + "title": "Build a Roman Numeral Converter Project", + "intro": [ + "This is one of the required projects to claim your certification.", + "For this project, you'll build an application that converts integers to Roman numerals." + ] + }, + "build-a-telephone-number-validator-project": { + "title": "Build a Telephone Number Validator Project", + "intro": [ + "This is one of the required projects to claim your certification.", + "For this project, you'll build an application that checks if a number is a valid United States phone number." + ] + }, + "learn-basic-javascript-by-building-a-role-playing-game": { + "title": "Learn Basic JavaScript by Building a Role Playing Game", + "intro": [ + "JavaScript is a powerful scripting language that you can use to make web pages interactive. It's one of the core technologies of the web, along with HTML and CSS. All modern browsers support JavaScript.", + "In this practice project, you'll learn fundamental programming concepts in JavaScript by coding your own Role Playing Game. You'll learn how to work with arrays, strings, objects, functions, loops, if/else statements, and more." + ] + }, + "learn-form-validation-by-building-a-calorie-counter": { + "title": "Learn Form Validation by Building a Calorie Counter", + "intro": [ + "Sometimes when you're coding a web application, you'll need to be able to accept input from a user. In this calorie counter project, you'll learn how to validate user input, perform calculations based on that input, and dynamically update your interface to display the results.", + "In this practice project, you'll learn basic regular expressions, template literals, the addEventListener() method, and more." + ] + }, + "learn-functional-programming-by-building-a-spreadsheet": { + "title": "Learn Functional Programming by Building a Spreadsheet", + "intro": [ + "Functional Programming is a popular approach to software development. In Functional Programming, developers organize code into smaller functions, then combine those functions to build complex programs.", + "In this spreadsheet application project, you'll learn about parsing and evaluating mathematical expressions, implementing spreadsheet functions, handling cell references, and creating interactive web interfaces. You'll learn how to dynamically update the page based on user input.", + "This project will cover concepts like the map(), find(), and includes() methods and the parseInt() function." + ] + }, + "learn-modern-javascript-methods-by-building-football-team-cards": { + "title": "Learn Modern JavaScript Methods by Building Football Team Cards", + "intro": [ + "One common aspect of building web applications: processing datasets, and then outputting information to the screen. In this sports team cards project, you'll learn how to work with DOM manipulation, object destructuring, event handling, and data filtering.", + "This project will cover concepts like, default parameters, Object.freeze(), and reinforce your knowledge of the switch statement and map() method." + ] + }, + "learn-advanced-array-methods-by-building-a-statistics-calculator": { + "title": "Learn Advanced Array Methods by Building a Statistics Calculator", + "intro": [ + "As you expand your JavaScript skills, you'll want to get comfortable with array manipulation methods, such as map(), reduce(), and filter().", + "In this statistics calculator project, you'll gain experience with handling user input, DOM manipulation, and method chaining. You'll get practice by performing statistical calculations like mean, median, mode, variance, and standard deviation." + ] + }, + "learn-basic-oop-by-building-a-shopping-cart": { + "title": "Learn Basic OOP by Building a Shopping Cart", + "intro": [ + "OOP, or Object Oriented Programming, is one of the major approaches to the software development process. In OOP, developers use objects and classes to structure their code.", + "In this shopping cart project, you'll learn how to define classes and use them. You'll create class instances and implement methods for data manipulation.", + "This project will cover concepts like the ternary operator, the spread operator, the this keyword, and more." + ] + }, + "learn-fetch-and-promises-by-building-an-fcc-authors-page": { + "title": "Learn Fetch and Promises by Building an fCC Authors Page", + "intro": [ + "One common aspect of web development is learning how to fetch data from an external API, then work with asynchronous JavaScript.", + "This freeCodeCamp authors page project will show you how to use the fetch method, then dynamically update the DOM to display the fetched data.", + "This project will also teach you how to paginate your data so you can load results in batches." + ] + }, + "learn-regular-expressions-by-building-a-spam-filter": { + "title": "Learn Regular Expressions by Building a Spam Filter", + "intro": [ + "Regular expressions, often shortened to \"regex\" or \"regexp\", are patterns that help programmers match, search, and replace text. Regular expressions are powerful, but can be difficult to understand because they use so many special characters.", + "In this spam filter project, you'll learn about capture groups, positive lookaheads, negative lookaheads, and other techniques to match any text you want." + ] + }, + "learn-basic-algorithmic-thinking-by-building-a-number-sorter": { + "title": "Learn Basic Algorithmic Thinking by Building a Number Sorter", + "intro": [ + "In computer science, there are fundamental sorting algorithms that all developers should learn. In this number sorter project, you'll learn how to implement and visualize different sorting algorithms like bubble sort, selection sort, and insertion sort – all with JavaScript.", + "This project will help you understand the fundamental concepts behind these algorithms, and how you can apply them to sort numerical data in web applications." + ] + }, + "review-algorithmic-thinking-by-building-a-dice-game": { + "title": "Review Algorithmic Thinking by Building a Dice Game", + "intro": [ + "Algorithmic thinking involves the ability to break down complex problems into a sequence of well-defined, step-by-step instructions.", + "In this Dice game project, you’ll learn how to manage game state, implement game logic for rolling dice, keeping score, and applying rules for various combinations.", + "This project covers concepts such as event handling, array manipulation, conditional logic, and updating the user interface dynamically based on game state." + ] + }, + "learn-intermediate-oop-by-building-a-platformer-game": { + "title": "Learn Intermediate OOP by Building a Platformer Game", + "intro": [ + "Coding a game is a great way to grasp fundamental programming principles, while also creating an interactive gaming experience.", + "In this platformer game project, you'll continue to learn about classes, objects, inheritance, and encapsulation. You'll also learn how to design and organize game elements efficiently and gain insights into problem-solving and code reusability." + ] + }, + "learn-localstorage-by-building-a-todo-app": { + "title": "Learn localStorage by Building a Todo App", + "intro": [ + "Local storage is a web browser feature that lets web applications store key-value pairs persistently within a user's browser. This allows web apps to save data during one session, then retrieve it in a later page session.", + "In this TODO application, you'll learn how to handle form inputs, manage local storage, perform CRUD (Create, Read, Update, Delete) operations on tasks, implement event listeners, and toggle UI elements." + ] + }, + "learn-the-date-object-by-building-a-date-formatter": { + "title": "Learn the Date Object by Building a Date Formatter", + "intro": [ + "Working with dates in JavaScript can be challenging. You have to navigate various methods, formats, and time zones. In this project, you'll learn how to work with the JavaScript Date object, including its methods and properties. You'll also learn how to correctly format dates.", + "This project will cover concepts such as the getDate(), getMonth(), and getFullYear() methods." + ] + }, + "learn-asynchronous-programming-by-building-an-fcc-forum-leaderboard": { + "title": "Learn Asynchronous Programming by Building an fCC Forum Leaderboard", + "intro": [ + "JavaScript is an asynchronous programming language. And this project will help you gain proficiency in asynchronous concepts. You'll code your own freeCodeCamp forum leaderboard.", + "This project will cover the Fetch API, promises, Async/Await, and the try..catch statement." + ] + }, + "learn-basic-string-and-array-methods-by-building-a-music-player": { + "title": "Learn Basic String and Array Methods by Building a Music Player", + "intro": [ + "Now let's learn some essential string and array methods like the find(), forEach(), map(), and join(). These methods are crucial for developing dynamic web applications.", + "In this project, you'll code a basic MP3 player using HTML, CSS, and JavaScript. The project covers fundamental concepts such as handling audio playback, managing a playlist, implementing play, pause, next, previous, and shuffle functionalities. You'll even learn how to dynamically update your user interface based on the current song." + ] + }, + "learn-recursion-by-building-a-decimal-to-binary-converter": { + "title": "Learn Recursion by Building a Decimal to Binary Converter", + "intro": [ + "Recursion is a programming concept where a function calls itself. This can reduce a complex problem into simpler sub-problems, until they become straightforward to solve.", + "In this project, you’ll build a decimal-to-binary converter using JavaScript. You’ll learn the fundamental concepts of recursion, explore the call stack, and build out a visual representation of the recursion process through an animation." + ] + }, + "learn-introductory-javascript-by-building-a-pyramid-generator": { + "title": "Learn Introductory JavaScript by Building a Pyramid Generator", + "intro": [ + "JavaScript is a powerful scripting language that you can use to make web pages interactive. It's one of the core technologies of the web, along with HTML and CSS. All modern browsers support JavaScript.", + "In this practice project, you'll learn fundamental programming concepts in JavaScript by coding your own Pyramid Generator. You'll learn how to work with arrays, strings, functions, loops, if/else statements, and more." + ] + }, + "review-js-fundamentals-by-building-a-gradebook-app": { + "title": "Review JavaScript Fundamentals by Building a Gradebook App", + "intro": [ + "In this mini project, you will get to review JavaScript fundamentals like functions, variables, conditionals and more by building a gradebook app.", + "This will give you an opportunity to solve small problems and get a better understanding of the basics." + ] + }, + "learn-basic-debugging-by-building-a-random-background-color-changer": { + "title": "Learn Basic Debugging by Building a Random Background Color Changer", + "intro": [ + "Debugging is the process of going through your code, finding any issues, and fixing them.", + "In this project, you will help CamperBot build a random background color changer and help them find and fix errors." + ] + }, + "review-dom-manipulation-by-building-a-rock-paper-scissors-game": { + "title": "Review DOM Manipulation by Building a Rock, Paper, Scissors Game", + "intro": [ + "In the previous projects you learned how to work with basic DOM manipulation. Now it is time to review what you have learned by building a Rock, Paper, Scissors game.", + "In this mini project, you will review conditionals, functions, getElementById, and more. This project will give you an opportunity to solve small problems and get a better understanding of the basics." + ] + } + } + }, + "front-end-development-libraries": { + "title": "Front-End Development Libraries V8", + "intro": [ + "Now that you're familiar with HTML, CSS, and JavaScript, level up your skills by learning some of the most popular front-end libraries in the industry.", + "In the Front-End Development Libraries Certification, you'll learn how to style your site quickly with Bootstrap. You'll also learn how to add logic to your CSS styles and extend them with Sass.", + "Later, you'll build a shopping cart and other applications to learn how to create powerful Single Page Applications (SPAs) with React and Redux." + ], + "note": "", + "blocks": { + "bootstrap": { + "title": "Bootstrap", + "intro": [ + "Bootstrap is a front-end framework used to design responsive web pages and applications. It takes a mobile-first approach to web development, and includes pre-built CSS styles and classes, plus some JavaScript functionality.", + "In this course, you'll learn how to build responsive websites with Bootstrap, and use its included classes to style buttons, images, forms, navigation, and other common elements." + ] + }, + "jquery": { + "title": "jQuery", + "intro": [ + "jQuery is one of the most widely used JavaScript libraries in the world.", + "In 2006 when it was released, all major browsers handled JavaScript slightly differently. jQuery simplified the process of writing client-side JavaScript, and also ensured that your code worked the same way in all browsers.", + "In this course, you'll learn how to use jQuery to select, remove, clone, and modify different elements on the page." + ] + }, + "sass": { + "title": "SASS", + "intro": [ + "Sass, or \"Syntactically Awesome StyleSheets\", is a language extension of CSS. It adds features that aren't available in basic CSS, which make it easier for you to simplify and maintain the style sheets for your projects.", + "In this Sass course, you'll learn how to store data in variables, nest CSS, create reusable styles with mixins, add logic and loops to your styles, and more." + ] + }, + "react": { + "title": "React", + "intro": [ + "React is a popular JavaScript library for building reusable, component-driven user interfaces for web pages or applications.", + "React combines HTML with JavaScript functionality into its own markup language called JSX. React also makes it easy to manage the flow of data throughout the application.", + "In this course, you'll learn how to create different React components, manage data in the form of state props, use different lifecycle methods like componentDidMount, and much more." + ] + }, + "redux": { + "title": "Redux", + "intro": [ + "As applications grow in size and scope, managing shared data becomes much more difficult. Redux is defined as a \"predictable state container for JavaScript apps\" that helps ensure your apps work predictably, and are easier to test.", + "While you can use Redux with any view library, we introduce Redux here before combining it with React in the next set of courses.", + "In this course, you'll learn the fundamentals of Redux stores, actions, reducers and middleware to manage data throughout your application." + ] + }, + "react-and-redux": { + "title": "React and Redux", + "intro": [ + "React and Redux are often mentioned together, and with good reason. The developer who created Redux was a React developer who wanted to make it easier to share data across different components.", + "Now that you know how to manage the flow of shared data with Redux, it's time to combine that knowledge with React. In the React and Redux courses, you'll build a React component and learn how to manage state locally at the component level, and throughout the entire application with Redux." + ] + }, + "front-end-development-libraries-projects": { + "title": "Front-End Development Libraries Projects", + "intro": [ + "It's time to put your front-end development libraries skills to the test. Use Bootstrap, jQuery, Sass, React, and Redux to build 5 projects that will test everything you've learned up to this point.", + "Complete all 5 projects, and you'll earn the Front-End Development Libraries certification." + ] + } + } + }, + "data-visualization": { + "title": "Data Visualization V8", + "intro": [ + "Data is all around us, but it doesn't mean much without shape or context.", + "In the Data Visualization Certification, you'll build charts, graphs, and maps to present different types of data with the D3.js library.", + "You'll also learn about JSON (JavaScript Object Notation), and how to work with data online using an API (Application Programming Interface)." + ], + "note": "", + "blocks": { + "data-visualization-with-d3": { + "title": "Data Visualization with D3", + "intro": [ + "D3, or D3.js, stands for Data Driven Documents. It's a JavaScript library for creating dynamic and interactive data visualizations in the browser.", + "D3 is built to work with common web standards – namely HTML, CSS, and Scalable Vector Graphics (SVG).", + "D3 supports many different kinds of input data formats. Then, using its powerful built-in methods, you can transform those data into different charts, graphs, and maps.", + "In the Data Visualization with D3 courses, you'll learn how to work with data to create different charts, graphs, hover elements, and other ingredients to create dynamic and attractive data visualizations." + ] + }, + "json-apis-and-ajax": { + "title": "JSON APIs and AJAX", + "intro": [ + "Similar to how UIs help people use programs, APIs (Application Programming Interfaces) help programs interact with other programs. APIs are tools that computers use to communicate with one another, in part to send and receive data.", + "Programmers often use AJAX (Asynchronous JavaScript and XML) when working with APIs. AJAX refers to a group of technologies that make asynchronous requests to a server to transfer data, then load any returned data into the page. And the data transferred between the browser and server is often in a format called JSON (JavaScript Object Notation).", + "This course will teach you the basics about working with APIs and different AJAX technologies in the browser." + ] + }, + "data-visualization-projects": { + "title": "Data Visualization Projects", + "intro": [ + "Now that you learned how to work with D3, APIs, and AJAX technologies, put your skills to the test with these 5 Data Visualization projects.", + "In these projects, you'll need to fetch data and parse a dataset, then use D3 to create different data visualizations. Finish them all to earn your Data Visualization certification." + ] + } + } + }, + "learn-data-visualization-with-d3": { + "title": "Learn Data Visualization with D3", + "summary": [ + "Learn how to use D3 to turn data into interactive bar charts and scatterplots." + ], + "intro": [ + "In this course, you'll learn core data visualization concepts and practice using the D3 library to build charts from datasets." + ], + "note": "", + "chapters": { + "learn-data-visualization-with-d3": "Learn Data Visualization with D3" + }, + "modules": { "introduction-to-d3": "Introduction to D3" }, + "module-intros": { + "introduction-to-d3": { + "note": "Coming Late 2026", + "intro": [ + "In this module, you will learn the basics of working with D3." + ] + } + }, + "blocks": { + "lecture-introduction-to-data-visualization": { + "title": "Introduction to Data Visualization", + "intro": [ + "In these lessons, you will learn about basic data visualization concepts." + ] + }, + "lab-bar-chart": { + "title": "Build a Bar Chart", + "intro": ["In this lab, you will use D3 to build a bar chart."] + }, + "lab-scatterplot-graph": { + "title": "Build a Scatterplot Graph", + "intro": [ + "In this lab, you will create a D3 scatterplot graph using a provided dataset." + ] + } + } + }, + "relational-database": { + "title": "Relational Database V8", + "intro": [ + "For these courses, you will use real developer tools and software including VS Code, PostgreSQL, and the Linux / Unix command line to complete interactive tutorials and build projects.", + "These courses start off with basic Bash commands. Using the terminal, you will learn everything from navigating and manipulating a file system, scripting in Bash, all the way to advanced usage.", + "Next, you will learn how to create and use a relational database with PostgreSQL, a database management system, and SQL, the language of these databases.", + "Finally, you will learn Git, the version control system, an essential tool of every developer." + ], + "blocks": { + "build-a-celestial-bodies-database-project": { + "title": "Celestial Bodies Database", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a database of celestial bodies using PostgreSQL." + ] + }, + "build-a-number-guessing-game-project": { + "title": "Number Guessing Game", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will use Bash scripting, PostgreSQL, and Git to create a number guessing game that runs in the terminal and saves user information." + ] + }, + "build-a-periodic-table-database-project": { + "title": "Periodic Table Database", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will create a Bash script to get information about chemical elements from a periodic table database." + ] + }, + "build-a-salon-appointment-scheduler-project": { + "title": "Salon Appointment Scheduler", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will create an interactive Bash program that uses PostgreSQL to track the customers and appointments for your salon." + ] + }, + "build-a-world-cup-database-project": { + "title": "World Cup Database", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will create a Bash script that enters information from World Cup games into PostgreSQL, then query the database for useful statistics." + ] + }, + "learn-advanced-bash-by-building-a-kitty-ipsum-translator": { + "title": "Learn Advanced Bash by Building a Kitty Ipsum Translator", + "intro": [ + "There's more to Bash commands than you might think.", + "In this 140-lesson course, you will learn some more complex commands, and the details of how commands work." + ] + }, + "learn-bash-and-sql-by-building-a-bike-rental-shop": { + "title": "Learn Bash and SQL by Building a Bike Rental Shop", + "intro": [ + "In this 210-lesson course, you will build an interactive Bash program that stores rental information for your bike rental shop using PostgreSQL." + ] + }, + "learn-bash-by-building-a-boilerplate": { + "title": "Learn Bash by Building a Boilerplate", + "intro": [ + "The terminal allows you to send text commands to your computer that can manipulate the file system, run programs, automate tasks, and much more.", + "In this 170-lesson course, you will learn terminal commands by creating a website boilerplate using only the command line." + ] + }, + "learn-bash-scripting-by-building-five-programs": { + "title": "Learn Bash Scripting by Building Five Programs", + "intro": [ + "Bash scripts combine terminal commands and logic into programs that can execute or automate tasks, and much more.", + "In this 220-lesson course, you will learn more terminal commands and how to use them within Bash scripts by creating five small programs." + ] + }, + "learn-git-by-building-an-sql-reference-object": { + "title": "Learn Git by Building an SQL Reference Object", + "intro": [ + "Git is a version control system that keeps track of all the changes you make to your codebase.", + "In this 240-lesson course, you will learn how Git keeps track of your code by creating an object containing commonly used SQL commands." + ] + }, + "learn-nano-by-building-a-castle": { + "title": "Learn Nano by Building a Castle", + "intro": [ + "Nano is a program that allows you to edit files right in the terminal.", + "In this 40-lesson course, you will learn how to edit files in the terminal with Nano while building a castle." + ] + }, + "learn-relational-databases-by-building-a-database-of-video-game-characters": { + "title": "Learn Relational Databases by Building a Database of Video Game Characters", + "intro": [ + "A relational database organizes data into tables that are linked together through relationships.", + "In this 165-lesson course, you will learn the basics of a relational database by creating a PostgreSQL database filled with video game characters." + ] + }, + "learn-sql-by-building-a-student-database-part-1": { + "title": "Learn SQL by Building a Student Database: Part 1", + "intro": [ + "SQL, or Structured Query Language, is the language for communicating with a relational database.", + "In this 140-lesson course, you will create a Bash script that uses SQL to enter information about your computer science students into PostgreSQL." + ] + }, + "learn-sql-by-building-a-student-database-part-2": { + "title": "Learn SQL by Building a Student Database: Part 2", + "intro": [ + "SQL join commands are used to combine information from multiple tables in a relational database", + "In this 140-lesson course, you will complete your student database while diving deeper into SQL commands." + ] + } + } + }, + "back-end-development-and-apis": { + "title": "Back-End Development and APIs V8", + "intro": [ + "Until this point, you've only used JavaScript on the front-end to add interactivity to a page, solve algorithm challenges, or build an SPA. But JavaScript can also be used on the back-end, or server, to build entire web applications.", + "Today, one of the popular ways to build applications is through microservices, which are small, modular applications that work together to form a larger whole.", + "In the Back-End Development and APIs Certification, you'll learn how to write back-end apps with Node.js and npm. You'll also build web applications with the Express framework, and build a People Finder microservice with MongoDB and the Mongoose library." + ], + "note": "", + "blocks": { + "managing-packages-with-npm": { + "title": "Managing Packages with NPM", + "intro": [ + "npm (Node Package Manager), is a command line tool to install, create, and share packages of JavaScript code written for Node.js. There are many open source packages available on npm, so before starting a project, take some time to explore so you don't end up recreating the wheel for things like working with dates or fetching data from an API.", + "In this course, you'll learn the basics of using npm, including how to work with the package.json and how to manage your installed dependencies." + ] + }, + "basic-node-and-express": { + "title": "Basic Node and Express", + "intro": [ + "Node.js is a JavaScript runtime that allows developers to write back-end (server-side) programs in JavaScript. Node.js comes with a handful of built-in modules — small, independent programs — that help with this. Some of the core modules include HTTP, which acts like a server, and File System, a module to read and modify files.", + "In the last set of courses you learned to install and manage packages from npm, which are collections of smaller modules. These packages can help you build larger, more complex applications.", + "Express is a lightweight web application framework, and is one of the most popular packages on npm. Express makes it much easier to create a server and handle routing for your application, which handles things like directing people to the correct page when they visit a certain endpoint like
/blog
.", + "In this course, you'll learn the basics of Node and Express including how to create a server, serve different files, and handle different requests from the browser." + ] + }, + "mongodb-and-mongoose": { + "title": "MongoDB and Mongoose", + "intro": [ + "MongoDB is a database application that stores JSON documents (or records) that you can use in your application. Unlike SQL, another type of database, MongoDB is a non-relational or \"NoSQL\" database. This means MongoDB stores all associated data within one record, instead of storing it across many preset tables as in a SQL database.", + "Mongoose is a popular npm package for interacting with MongoDB. With Mongoose, you can use plain JavaScript objects instead of JSON, which makes it easier to work with MongoDB. Also, it allows you to create blueprints for your documents called schemas, so you don't accidentally save the wrong type of data and cause bugs later.", + "In the MongoDB and Mongoose courses, you'll learn the fundamentals of working with persistent data including how to set up a model, and save, delete, and find documents in the database." + ] + }, + "back-end-development-and-apis-projects": { + "title": "Back-End Development and APIs Projects", + "intro": [ + "You've worked with APIs before, but now that you know npm, Node, Express, MongoDB, and Mongoose, it's time to build your own. Draw on everything you've learned up to this point to create 5 different microservices, which are smaller applications that are limited in scope.", + "After creating these, you'll have 5 cool microservice APIs you can show off to friends, family, and potential employers. Oh, and you'll have a shiny new Back-End Development and APIs Certification, too." + ] + } + } + }, + "quality-assurance": { + "title": "Quality Assurance", + "intro": [ + "As your programs or web applications become more complex, you'll want to test them to make sure that new changes don't break their original functionality.", + "In the Quality Assurance Certification, you'll learn how to write tests with Chai to ensure your applications work the way you expect them to.", + "Then you'll build a chat application to learn advanced Node and Express concepts. You'll also use Pug as a template engine, Passport for authentication, and Socket.io for real-time communication between the server and connected clients." + ], + "note": "", + "blocks": { + "quality-assurance-and-testing-with-chai": { + "title": "Quality Assurance and Testing with Chai", + "intro": [ + "Chai is a JavaScript testing library that helps you confirm that your program still behaves the way you expect it to after you make changes to your code.", + "Using Chai, you can write tests that describe your program's requirements and see if your program meets them.", + "In this course, you'll learn about assertions, deep equality, truthiness, testing APIs, and other fundamentals for testing JavaScript applications." + ] + }, + "advanced-node-and-express": { + "title": "Advanced Node and Express", + "intro": [ + "Now it's time to take a deep dive into Node.js and Express.js by building a chat application with a sign-in system.", + "To implement the sign-in system safely, you'll need to learn about authentication. This is the act of verifying the identity of a person or process.", + "In this course, you'll learn how to use Passport to manage authentication, Pug to create reusable templates for quickly building the front-end, and web sockets for real-time communication between the clients and server." + ] + }, + "quality-assurance-projects": { + "title": "Quality Assurance Projects", + "intro": [ + "Now that you're well versed in both the front-end and back-end, it's time to apply all the skills and concepts you've learned up to this point. You'll build 5 different web applications, and write tests for each one to make sure they're working and can handle different edge cases.", + "After completing these Quality Assurance projects, you'll have 5 more projects under your belt, and a new certification to show off on your portfolio." + ] + } + } + }, + "scientific-computing-with-python": { + "title": "Scientific Computing with Python", + "intro": [ + "The Scientific Computing with Python curriculum will equip you with the skills to analyze and manipulate data using Python, a powerful and versatile programming language. You'll learn key concepts like data structures, algorithm, Object Oriented Programming, and how to perform complex calculations using a variety of tools.", + "This comprehensive course will guide you through the fundamentals of scientific computing, including data structures, and algorithms." + ], + "note": "", + "blocks": { + "learn-string-manipulation-by-building-a-cipher": { + "title": "Learn String Manipulation by Building a Cipher", + "intro": [ + "Python is a powerful and popular programming language widely used for data science, data visualization, web development, game development, machine learning and more.", + "In this project, you'll learn fundamental programming concepts in Python, such as variables, functions, loops, and conditional statements. You'll use these to code your first programs." + ] + }, + "learn-how-to-work-with-numbers-and-strings-by-implementing-the-luhn-algorithm": { + "title": "Learn How to Work with Numbers and Strings by Implementing the Luhn Algorithm", + "intro": [ + "The Luhn Algorithm is widely used for error-checking in various applications, such as verifying credit card numbers.", + "By building this project, you'll gain experience working with numerical computations and string manipulation." + ] + }, + "learn-list-comprehension-by-building-a-case-converter-program": { + "title": "Learn Python List Comprehension by Building a Case Converter Program", + "intro": [ + "List Comprehension is a way to construct a new Python list from an iterable types: lists, tuples, and strings. All without using a for loop or the .append() list method.", + "In this project, you'll write a program that takes a string formatted in Camel Case or Pascal Case, then converts it into Snake Case.", + "The project has two phases: first you'll use a for loop to implement the program. Then you'll learn how to use List Comprehension instead of a loop to achieve the same results." + ] + }, + "learn-regular-expressions-by-building-a-password-generator": { + "title": "Learn Regular Expressions by Building a Password Generator", + "intro": [ + "A Python module is a file that contains a set of statements and definitions that you can use in your code.", + "In this project, you'll learn how to import modules from the Python standard library. You'll also learn how to use Regular Expressions by building your own password generator program." + ] + }, + "learn-algorithm-design-by-building-a-shortest-path-algorithm": { + "title": "Learn Algorithm Design by Building a Shortest Path Algorithm", + "intro": [ + "Algorithms are step-by-step procedures that developers use to perform calculations and solve computational problems.", + "In this project, you'll learn how to use functions, loops, conditional statements, and dictionary comprehensions to implement a Shortest Path algorithm." + ] + }, + "learn-recursion-by-solving-the-tower-of-hanoi-puzzle": { + "title": "Learn Recursion by Solving the Tower of Hanoi Puzzle", + "intro": [ + "Recursion is a programming approach that allows you to solve complicated computational problems with just a little code.", + "In this project, you'll start with a loop-based approach to solving the tower of Hanoi mathematical puzzle. Then you'll learn how to implement a recursive solution." + ] + }, + "learn-data-structures-by-building-the-merge-sort-algorithm": { + "title": "Learn Data Structures by Building the Merge Sort Algorithm", + "intro": [ + "The Merge Sort Algorithm is a sorting algorithm based on the divide and conquer principle.", + "In this project, you'll learn how to interact with data structures by sorting a list of random numbers using the Merge Sort Algorithm." + ] + }, + "learn-classes-and-objects-by-building-a-sudoku-solver": { + "title": "Learn Classes and Objects by Building a Sudoku Solver", + "intro": [ + "Classes and objects are important programming concepts. These Object-Oriented Programming tools help developers to achieve code modularity, abstraction, and readability. And they promote reusability.", + "In this Sudoku Solver project, you'll learn how to use classes and objects to build a Sudoku grid and to solve a Sudoku puzzle." + ] + }, + "learn-tree-traversal-by-building-a-binary-search-tree": { + "title": "Learn Tree Traversal by Building a Binary Search Tree", + "intro": [ + "A Binary Search Tree (BST) is an common data structure where data is sorted hierarchically.", + "In this project, you'll learn how to construct your own BST and perform an in-order traversal. You'll also learn key operations like insertion, search, and deletion." + ] + }, + "learn-lambda-functions-by-building-an-expense-tracker": { + "title": "Learn Lambda Functions by Building an Expense Tracker", + "intro": [ + "Lambda functions give you a concise way to write small, throwaway functions in your code.", + "In this project, you'll explore the power of Lambda Functions by creating an expense tracker. Your resulting app will demonstrate how you can use Lambda Functions for efficient, streamlined operations." + ] + }, + "build-an-arithmetic-formatter-project": { + "title": "Build an Arithmetic Formatter Project", + "intro": [ + "This is one of the required projects to claim your certification." + ] + }, + "build-a-time-calculator-project": { + "title": "Build a Time Calculator Project", + "intro": [ + "This is one of the required projects to claim your certification." + ] + }, + "build-a-budget-app-project": { + "title": "Build a Budget App Project", + "intro": [ + "This is one of the required projects to claim your certification." + ] + }, + "build-a-polygon-area-calculator-project": { + "title": "Build a Polygon Area Calculator Project", + "intro": [ + "This is one of the required projects to claim your certification." + ] + }, + "build-a-probability-calculator-project": { + "title": "Build a Probability Calculator Project", + "intro": [ + "This is one of the required projects to claim your certification." + ] + }, + "learn-interfaces-by-building-an-equation-solver": { + "title": "Learn Interfaces by Building an Equation Solver", + "intro": [ + "Abstract classes enable you to define formal interfaces - objects acting as blueprints for classes.", + "In this project, you'll discover how to implement an interface in Python while building a simple equation solver program." + ] + }, + "learn-special-methods-by-building-a-vector-space": { + "title": "Learn Special Methods by Building a Vector Space", + "intro": [ + "Python special methods are called in response to specific operations and enable you to customize the behavior of your objects in a detailed and effective way.", + "In this project, you are going to explore some of the most common special methods while learning about vectors by building a vector space." + ] + }, + "learn-encapsulation-by-building-a-projectile-trajectory-calculator": { + "title": "Learn Encapsulation by Building a Projectile Trajectory Calculator", + "intro": [ + "Encapsulation is a core OOP principle based on writing code that limits direct access to data.", + "In this project, you'll discover new concepts related to encapsulation, such as getters, setters, and name mangling, and you'll use them together with what you already learned to create a program that calculates a projectile trajectory." + ] + }, + "learn-the-bisection-method-by-finding-the-square-root-of-a-number": { + "title": "Learn the Bisection Method by Finding the Square Root of a Number", + "intro": [ + "Numerical methods are used to approximate solutions to mathematical problems that are difficult or impossible to solve analytically.", + "In this project, you will explore the numerical method of bisection to find the square root of a number by iteratively narrowing down the possible range of values that contain the square root." + ] + } + } + }, + "data-analysis-with-python": { + "title": "Data Analysis with Python", + "intro": [ + "Data Analysis has been around for a long time. But up until a few years ago, developers practiced it using expensive, closed-source tools like Tableau. But recently, Python, SQL, and other open libraries have changed Data Analysis forever.", + "In the Data Analysis with Python Certification, you'll learn the fundamentals of data analysis with Python. By the end of this certification, you'll know how to read data from sources like CSVs and SQL, and how to use libraries like Numpy, Pandas, Matplotlib, and Seaborn to process and visualize data." + ], + "note": "", + "blocks": { + "data-analysis-with-python-course": { + "title": "Data Analysis with Python", + "intro": [ + "In these comprehensive video courses, created by Santiago Basulto, you will learn the whole process of data analysis. You'll be reading data from multiple sources (CSV, SQL, Excel), process that data using NumPy and Pandas, and visualize it using Matplotlib and Seaborn,", + "Additionally, we've included a thorough Jupyter Notebook course, and a quick Python reference to refresh your programming skills." + ] + }, + "numpy": { + "title": "Numpy", + "intro": [ + "Learn the basics of the NumPy library in the following video course created by Keith Galli.", + "In this course, you'll learn how NumPy works and how it compares to Python's built-in lists. You'll also learn how to write code with NumPy, indexing, reshaping, applied statistics, and much more." + ] + }, + "data-analysis-with-python-projects": { + "title": "Data Analysis with Python Projects", + "intro": [ + "There are many ways to analyze data with Python. By completing these projects, you will demonstrate that you have a good foundational knowledge of data analysis with Python.", + "Finish them all to claim your Data Analysis with Python certification." + ] + } + } + }, + "learn-python-for-beginners": { + "title": "Learn Python for Beginners", + "summary": [ + "Learn the fundamentals of Python programming from the ground up by practicing foundational concepts and building small projects." + ], + "intro": [ + "Python is one of the most popular programming languages today. It's easy to learn, readable, and versatile.", + "In this comprehensive course, you'll learn the fundamentals of Python programming from the ground up. You'll start with basic concepts like variables and data types, progress through control flow and functions, and build projects to practice what you've learned." + ], + "note": "", + "blocks": { + "python-setup-first-steps": { + "title": "Python Setup & First Steps", + "intro": [ + "In these videos, popular programming instructor Mike Dane will introduce you to Python and show you how to setup your local environment." + ] + }, + "core-primitives-in-python": { + "title": "Core Primitives in Python", + "intro": [ + "In these videos, you will learn about variables, data types, strings, numbers, and getting input from the user." + ] + }, + "small-python-projects": { + "title": "Small Python Projects", + "intro": [ + "In these videos, you will practice what you have learned so far by building a basic calculator app and mad libs game." + ] + }, + "lists-and-tuples": { + "title": "Lists and Tuples", + "intro": [ + "In these videos, you will learn about lists, tuples and common operations." + ] + }, + "control-flow-and-functions-in-python": { + "title": "Control Flow and Functions", + "intro": [ + "In these videos, you will learn how to control the flow of your programs with if statements. You will also learn how to write reusable code with functions." + ] + }, + "dictionaries-and-loops": { + "title": "Dictionaries and Loops", + "intro": [ + "In these videos, you will learn how to work with dictionaries and various loops include the while and for loops." + ] + }, + "error-handling-files-and-modules-in-python": { + "title": "Error Handling, Files, and Modules", + "intro": [ + "In these videos, you will learn how to handle errors gracefully, read and write to files, and organize your code with modules and external packages." + ] + }, + "object-oriented-programming-with-python": { + "title": "Object-Oriented Programming with Python", + "intro": [ + "In these videos, you will learn about object-oriented programming by creating classes and objects. You will practice these skills by building a multiple choice quiz application." + ] + } + } + }, + "introduction-to-algorithms-and-data-structures": { + "title": "Introduction to Algorithms and Data Structures", + "summary": [ + "Learn about common algorithms and data structures in this introductory course." + ], + "intro": [ + "Algorithms and Data Structures are the backbone of programming. So it's important to learn how to work with them.", + "In this comprehensive course, you will learn about common sorting and searching algorithms including merge sort, quicksort and binary search.", + "You will also learn how to work with common data structures including arrays and linked lists." + ], + "note": "", + "blocks": { + "searching-algorithms": { + "title": "Searching Algorithms", + "intro": [ + "In these videos, you will learn what an algorithm is and learn how to work with the binary search and linear search algorithms." + ] + }, + "time-complexity": { + "title": "Time Complexity", + "intro": [ + "In these videos, you will learn about time complexity and how it works with measuring efficiency of algorithms." + ] + }, + "algorithms-in-code": { + "title": "Algorithms in Code", + "intro": [ + "In these videos, you will write Python code for the linear and binary search algorithms." + ] + }, + "recursion-and-space-complexity": { + "title": "Recursion and Space Complexity", + "intro": [ + "In these videos, you will learn about recursion and space complexity for algorithms." + ] + }, + "introduction-to-arrays": { + "title": "Introduction to Arrays", + "intro": [ + "In these videos, you will learn how to work with arrays. You will learn about different operations including insert, delete and search." + ] + }, + "introduction-to-linked-lists": { + "title": "Introduction to Linked Lists", + "intro": [ + "In these videos, you will learn about linked lists. You will learn how to add nodes to a list as well as remove and search a list." + ] + }, + "merge-sort-algorithm": { + "title": "Merge Sort Algorithm", + "intro": [ + "In these videos, you will learn about the merge sort algorithm." + ] + }, + "sorting-a-linked-list": { + "title": "Sorting a Linked List", + "intro": [ + "In these videos, you will learn more about how to sort linked lists." + ] + }, + "sorting-algorithms": { + "title": "Sorting Algorithms", + "intro": [ + "In these videos, you will learn about common sorting algorithms including selection sort and quicksort." + ] + }, + "searching-names-using-sorting-and-searching-algorithms": { + "title": "Searching Names using Sorting and Searching Algorithms", + "intro": [ + "In these videos, you will practice searching for names using the binary and linear search algorithms and comparing the runtimes for them." + ] + } + } + }, + "learn-rag-mcp-fundamentals": { + "title": "Learn RAG and MCP Fundamentals", + "summary": [ + "Learn the fundamentals of RAG and MCP in this comprehensive video course." + ], + "intro": [ + "RAG stands for Retrieval-Augmented Generation. MCP stands for Model Context Protocol. These are powerful frameworks for building AI agents that can retrieve information from a knowledge base, generate responses based on that information, and plan their actions accordingly.", + "In this course, you'll learn the fundamentals of RAG and MCP and how to implement them in your own projects. You'll explore the components of RAG and MCP, including retrieval, generation, memory, context, and planning. By the end of this course, you'll have a solid understanding of how RAG and MCP work and how to use them to build intelligent agents." + ], + "note": "", + "blocks": { + "understanding-rag": { + "title": "Understanding RAG", + "intro": [ + "Learn the fundamentals of Retrieval-Augmented Generation (RAG), including what it is, when to use it, and core concepts." + ] + }, + "retrieval-engine-internals": { + "title": "Retrieval Engine Internals", + "intro": [ + "Dive into semantic search, embedding models, vector databases, and chunking to understand how retrieval works under the hood." + ] + }, + "designing-reliable-rag-systems": { + "title": "Designing Reliable RAG Systems", + "intro": [ + "Explore RAG architecture, monitoring, error handling, and how to deploy RAG systems in production." + ] + }, + "mcp-ecosystem-and-tooling": { + "title": "MCP Ecosystem & Tooling", + "intro": [ + "Learn why MCP exists, its architecture, JSON-RPC, and how to build and use MCP servers and clients effectively." + ] + } + } + }, + "introduction-to-precalculus": { + "title": "Introduction to Precalculus", + "summary": [ + "Learn the fundamentals of precalculus, including functions, and trigonometry." + ], + "intro": [ + "Precalculus is a branch of mathematics that prepares you for calculus. It covers a wide range of topics including functions, and trigonometry." + ], + "note": "", + "blocks": { + "function-basics": { + "title": "Function Basics", + "intro": [ + "In these videos, you will learn about functions and how to work with them." + ] + }, + "angles-and-circular-motion": { + "title": "Angles and Circular Motion", + "intro": [ + "In these videos, you will learn about angles and circular motion." + ] + }, + "right-triangle-trigonometry": { + "title": "Right Triangle Trigonometry", + "intro": [ + "In these videos, you will learn about right triangle trigonometry and how to work with it." + ] + }, + "trig-graphs-inverses": { + "title": "Trigonometric Graphs and Inverses", + "intro": [ + "In these videos, you will learn about trigonometric graphs and inverse functions." + ] + }, + "solving-trig-equations": { + "title": "Solving Trigonometric Equations", + "intro": [ + "In these videos, you will learn how to solve trigonometric equations." + ] + }, + "trig-identities-formulas": { + "title": "Trigonometric Identities and Formulas", + "intro": [ + "In these videos, you will learn about trigonometric identities and formulas." + ] + }, + "advanced-trig-conics": { + "title": "Advanced Trigonometry and Conics", + "intro": [ + "In these videos, you will learn about advanced trigonometry and conic sections." + ] + } + } + }, + "introduction-to-bash": { + "title": "Introduction to Bash", + "summary": [ + "Learn how to use the terminal and write Bash scripts to automate tasks and manage files and processes." + ], + "intro": [ + "Bash is a Unix shell and command language that provides a powerful interface for interacting with your computer's operating system. It allows you to execute commands, automate tasks, and manage files and processes efficiently.", + "In this course, you'll learn the basics of Bash scripting, including how to navigate the file system, manipulate files and directories." + ], + "note": "", + "blocks": { + "lecture-understanding-the-command-line-and-working-with-bash": { + "title": "Understanding the Command Line and Working with Bash", + "intro": [ + "Learn about the Command Line and Working with Bash in these lessons." + ] + }, + "workshop-bash-boilerplate": { + "title": "Build a Boilerplate", + "intro": [ + "The terminal allows you to send text commands to your computer that can manipulate the file system, run programs, automate tasks, and much more.", + "In this 170-lesson workshop, you will learn terminal commands by creating a website boilerplate using only the command line." + ] + }, + "review-bash-commands": { + "title": "Bash Commands Review", + "intro": [ + "Review the Bash Commands concepts to prepare for the upcoming quiz." + ] + }, + "quiz-bash-commands": { + "title": "Bash Commands Quiz", + "intro": ["Test what you've learned bash commands with this quiz."] + } + } + }, + "introduction-to-sql-and-postgresql": { + "title": "Introduction to SQL and PostgreSQL", + "summary": [ + "Learn how to use SQL and PostgreSQL to create and manage relational databases." + ], + "intro": [ + "SQL (Structured Query Language) is a programming language used to manage and manipulate relational databases. It allows you to create, read, update, and delete data in a database.", + "PostgreSQL is a powerful, open-source relational database management system that uses SQL as its query language. It provides a robust and scalable platform for storing and managing data." + ], + "note": "", + "blocks": { + "lecture-working-with-relational-databases": { + "title": "Working with Relational Databases", + "intro": [ + "Learn how to work with Relational Databases in these lessons." + ] + }, + "workshop-database-of-video-game-characters": { + "title": "Build a Database of Video Game Characters", + "intro": [ + "A relational database organizes data into tables that are linked together through relationships.", + "In this 165-lesson workshop, you will learn the basics of a relational database by creating a PostgreSQL database filled with video game characters." + ] + }, + "lab-celestial-bodies-database": { + "title": "Build a Celestial Bodies Database", + "intro": [ + "For this project, you will build a database of celestial bodies using PostgreSQL." + ] + }, + "review-sql-and-postgresql": { + "title": "SQL and PostgreSQL Review", + "intro": [ + "Review SQL and PostgreSQL concepts to prepare for the upcoming quiz." + ] + }, + "quiz-sql-and-postgresql": { + "title": "SQL and PostgreSQL Quiz", + "intro": [ + "Test what you've learned about SQL and PostgreSQL with this quiz." + ] + } + } + }, + "learn-bash-scripting": { + "title": "Learn Bash Scripting", + "summary": [ + "Learn how to write Bash scripts to automate tasks and manage files and processes." + ], + "intro": [ + "Bash scripts combine terminal commands and logic into programs that can execute or automate tasks, and much more.", + "In this course, you will learn more terminal commands and how to use them within Bash scripts by creating five small programs." + ], + "note": "", + "blocks": { + "lecture-understanding-bash-scripting": { + "title": "Understanding Bash Scripting", + "intro": ["Learn about Bash Scripting in these lessons."] + }, + "workshop-bash-five-programs": { + "title": "Build Five Programs", + "intro": [ + "Bash scripts combine terminal commands and logic into programs that can execute or automate tasks, and much more.", + "In this 220-lesson workshop, you will learn more terminal commands and how to use them within Bash scripts by creating five small programs." + ] + }, + "review-bash-scripting": { + "title": "Bash Scripting Review", + "intro": [ + "Review the bash scripting concepts you've learned to prepare for the upcoming quiz." + ] + }, + "quiz-bash-scripting": { + "title": "Bash Scripting Quiz", + "intro": ["Test what you've learned on bash scripting in this quiz."] + } + } + }, + "learn-sql-and-bash": { + "title": "Learn SQL and Bash", + "summary": [ + "Learn how to use SQL and Bash together to manage and manipulate relational databases." + ], + "intro": [ + "SQL, or Structured Query Language, is the language for communicating with a relational database. Bash is a Unix shell and command language that provides a powerful interface for interacting with your computer's operating system.", + "In this course, you will create a Bash script that uses SQL to enter information about your computer science students into PostgreSQL." + ], + "note": "", + "blocks": { + "lecture-working-with-sql": { + "title": "Working With SQL", + "intro": [ + "In these lessons, you will learn about SQL injection, normalization, and the N+1 problem." + ] + }, + "workshop-sql-student-database-part-1": { + "title": "Build a Student Database: Part 1", + "intro": [ + "SQL, or Structured Query Language, is the language for communicating with a relational database.", + "In this 140-lesson workshop, you will create a Bash script that uses SQL to enter information about your computer science students into PostgreSQL." + ] + }, + "workshop-sql-student-database-part-2": { + "title": "Build a Student Database: Part 2", + "intro": [ + "SQL join commands are used to combine information from multiple tables in a relational database", + "In this 140-lesson workshop, you will complete your student database while diving deeper into SQL commands." + ] + }, + "workshop-kitty-ipsum-translator": { + "title": "Build a Kitty Ipsum Translator", + "intro": [ + "There's more to Bash commands than you might think.", + "In this 140-lesson workshop, you will learn some more complex commands, and the details of how commands work." + ] + }, + "workshop-bike-rental-shop": { + "title": "Build a Bike Rental Shop", + "intro": [ + "In this 210-lesson workshop, you will build an interactive Bash program that stores rental information for your bike rental shop using PostgreSQL." + ] + }, + "lab-world-cup-database": { + "title": "Build a World Cup Database", + "intro": [ + "For this project, you will create a Bash script that enters information from World Cup games into PostgreSQL, then query the database for useful statistics." + ] + }, + "lab-salon-appointment-scheduler": { + "title": "Build a Salon Appointment Scheduler", + "intro": [ + "For this lab, you will create an interactive Bash program that uses PostgreSQL to track the customers and appointments for your salon." + ] + }, + "review-bash-and-sql": { + "title": "Bash and SQL Review", + "intro": [ + "Review the Bash and SQL concepts to prepare for the upcoming quiz." + ] + }, + "quiz-bash-and-sql": { + "title": "Bash and SQL Quiz", + "intro": ["Test what you've learned in this quiz on Bash and SQL."] + } + } + }, + "introduction-to-nano": { + "title": "Introduction to Nano", + "summary": [ + "Learn how to use the Nano text editor to create and edit files in the terminal." + ], + "intro": [ + "Nano is a simple, user-friendly text editor that runs in the terminal. It allows you to create and edit files without leaving the command line.", + "In this course, you'll learn how to use Nano to create and edit files, navigate through text, and perform basic editing operations." + ], + "note": "", + "blocks": { + "lecture-working-with-nano": { + "title": "Working With Nano", + "intro": ["Learn about Nano in this lesson."] + }, + "workshop-castle": { + "title": "Build a Castle", + "intro": [ + "Nano is a program that allows you to edit files right in the terminal.", + "In this 40-lesson workshop, you will learn how to edit files in the terminal with Nano while building a castle." + ] + } + } + }, + "introduction-to-git-and-github": { + "title": "Introduction to Git and GitHub", + "summary": [ + "Learn how to use Git and GitHub to manage and collaborate on software projects." + ], + "intro": [ + "Git is a version control system that allows developers to track changes in their code and collaborate with others. GitHub is a web-based platform that provides hosting for Git repositories, making it easier for developers to share and collaborate on projects.", + "In this course, you'll learn the basics of Git and GitHub, including how to create repositories, commit changes, and collaborate with others on software projects." + ], + "note": "", + "blocks": { + "lecture-introduction-to-git-and-github": { + "title": "Introduction to Git and GitHub", + "intro": ["Learn how to work with Git and GitHub in these lessons."] + }, + "lecture-working-with-code-reviews-branching-deployment-and-ci-cd": { + "title": "Working With Code Reviews, Branching, Deployment, and CI/CD", + "intro": [ + "Learn about code reviews, branching, deployment, and CI/CD in these lessons." + ] + }, + "workshop-sql-reference-object": { + "title": "Build an SQL Reference Object", + "intro": [ + "Git is a version control system that keeps track of all the changes you make to your codebase.", + "In this 240-lesson workshop, you will learn how Git keeps track of your code by creating an object containing commonly used SQL commands." + ] + }, + "review-git": { + "title": "Git Review", + "intro": ["Review Git concepts to prepare for the upcoming quiz."] + }, + "quiz-git": { + "title": "Git Quiz", + "intro": ["Test what you've learned on Git with this quiz."] + } + } + }, + "learn-oop-with-python": { + "title": "Learn OOP with Python", + "summary": [ + "In this video course, you will learn about object-oriented programming using Python." + ], + "intro": [ + "Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code to manipulate that data. This course introduces the key principles of OOP, including classes, objects, inheritance, and shows how to apply them in practice." + ], + "note": "", + "blocks": { + "oop-basics": { + "title": "OOP Basics", + "intro": [ + "In these videos, learn the basics of OOP including how to create classes and work with constructors." + ] + }, + "methods-and-inheritance": { + "title": "Methods and Inheritance", + "intro": [ + "In these videos, learn about methods and inheritance in OOP." + ] + }, + "advanced-oop-concepts": { + "title": "Advanced OOP Concepts", + "intro": [ + "In these videos, learn about advanced OOP concepts including getters, setters and other important OOP principles." + ] + } + } + }, + "introduction-to-python-basics": { + "title": "Introduction to Python Basics", + "summary": ["Learn the fundamentals of Python programming."], + "intro": [ + "In this interactive course, you will learn the basic syntax, data types, and control structures of Python." + ], + "note": "", + "blocks": { + "lecture-introduction-to-python": { + "title": "Introduction to Python", + "intro": [ + "In these lessons, you will learn what Python is and some common uses in the industry." + ] + }, + "lecture-understanding-variables-and-data-types": { + "title": "Understanding Variables and Data Types", + "intro": [ + "In these lessons, you will learn about variables and data types in Python." + ] + }, + "workshop-report-card-printer": { + "title": "Build a Report Card Printer", + "intro": [ + "In this workshop, you will practice working with primitive data types in Python by creating and printing data for a simple report card." + ] + }, + "lecture-introduction-to-python-strings": { + "title": "Introduction to Strings", + "intro": ["In these lessons, you will learn about strings in Python."] + }, + "workshop-employee-profile-generator": { + "title": "Build an Employee Profile Generator", + "intro": [ + "In this workshop, you will practice the fundamentals of string manipulation in Python by building a tool that generates formatted employee badges and analyzes employee codes." + ] + }, + "lecture-numbers-and-mathematical-operations": { + "title": "Numbers and Mathematical Operations", + "intro": [ + "In these lessons, you will learn about numbers and mathematical operations in Python." + ] + }, + "workshop-bill-splitter": { + "title": "Build a Bill Splitter", + "intro": [ + "In this workshop, you will build a bill splitter to practice working with numbers and mathematical operations in Python." + ] + }, + "lecture-booleans-and-conditionals": { + "title": "Booleans and Conditionals", + "intro": [ + "In these lessons, you will learn about booleans and conditionals in Python." + ] + }, + "workshop-movie-ticket-booking-calculator": { + "title": "Build a Movie Ticket Booking Calculator", + "intro": [ + "In this workshop, you will practice how to use booleans and conditional statements in Python by building a movie ticket booking calculator." + ] + }, + "lab-travel-weather-planner": { + "title": "Build a Travel Weather Planner", + "intro": [ + "In this lab, you will build a travel weather planner using conditionals." + ] + }, + "lecture-understanding-functions-and-scope": { + "title": "Understanding Functions and Scope", + "intro": [ + "In these lessons, you will learn about functions and scope in Python." + ] + }, + "lab-discount-calculator": { + "title": "Build an Apply Discount Function", + "intro": [ + "In this lab, you will practice basic Python by building a calculator to apply a discount to a price." + ] + }, + "workshop-caesar-cipher": { + "title": "Build a Caesar Cipher", + "intro": [ + "In this workshop, you'll build a Caesar cipher using basic Python concepts such as strings, conditionals, functions, and more." + ] + }, + "lab-rpg-character": { + "title": "Build an RPG Character", + "intro": [ + "In this lab you will practice basic Python by building an RPG character." + ] + }, + "review-python-basics": { + "title": "Python Basics Review", + "intro": [ + "Before you're quizzed on Python basics, you should review what you've learned about it.", + "In this review page, you will review working with strings, functions, comparison operators and more." + ] + }, + "quiz-python-basics": { + "title": "Python Basics Quiz", + "intro": [ + "Test what you've learned about Python basics with this quiz." + ] + } + } + }, + "learn-python-loops-and-sequences": { + "title": "Learn Python Loops and Sequences", + "summary": ["Learn how to work with loops and sequences in Python."], + "intro": [ + "In this interactive course, you will learn how to work with loops and sequences in Python." + ], + "note": "", + "blocks": { + "lecture-working-with-loops-and-sequences": { + "title": "Working with Loops and Sequences", + "intro": [ + "Learn about working with loops and sequences in these lessons." + ] + }, + "workshop-pin-extractor": { + "title": "Build a Pin Extractor", + "intro": [ + "In this workshop you will build a function to extract secret pins hidden in poems." + ] + }, + "lab-number-pattern-generator": { + "title": "Build a Number Pattern Generator", + "intro": ["In this lab you will build a number pattern generator."] + }, + "review-loops-and-sequences": { + "title": "Loops and Sequences Review", + "intro": [ + "Before you're quizzed on loops and sequences, you should review what you've learned about them.", + "Open up this page to review concepts around loops, lists, tuples and some of their common methods." + ] + }, + "quiz-loops-and-sequences": { + "title": "Loops and Sequences Quiz", + "intro": [ + "Test what you've learned about loops and sequences in Python with this quiz." + ] + } + } + }, + "learn-python-dictionaries-and-sets": { + "title": "Learn Python Dictionaries and Sets", + "summary": ["Learn how to work with dictionaries and sets in Python."], + "intro": [ + "In this interactive course, you will learn how to work with dictionaries and sets in Python." + ], + "note": "", + "blocks": { + "lecture-working-with-dictionaries-and-sets": { + "title": "Working with Dictionaries and Sets", + "intro": [ + "Learn about working with dictionaries and sets in these lessons." + ] + }, + "lecture-working-with-modules": { + "title": "Working with Modules", + "intro": ["Learn about working with modules in these lessons."] + }, + "workshop-medical-data-validator": { + "title": "Build a Medical Data Validator", + "intro": [ + "In this workshop, you'll practice working with dictionaries and sets while validating a collection of medical data." + ] + }, + "lab-user-configuration-manager": { + "title": "Build a User Configuration Manager", + "intro": [ + "In this lab, you will practice working with dictionaries in Python." + ] + }, + "review-dictionaries-and-sets": { + "title": "Dictionaries and Sets Review", + "intro": [ + "Before you're quizzed on dictionaries and sets, you should review what you've learned about them.", + "Open up this page to review concepts around dictionaries, sets, and how to import modules." + ] + }, + "quiz-dictionaries-and-sets": { + "title": "Dictionaries and Sets Quiz", + "intro": [ + "Test what you've learned about dictionaries and sets in Python with this quiz." + ] + } + } + }, + "learn-error-handling-in-python": { + "title": "Learn Error Handling in Python", + "summary": ["Learn how to handle errors and exceptions in Python."], + "intro": [ + "In this interactive course, you will learn how to handle errors and exceptions in Python." + ], + "note": "", + "blocks": { + "lecture-understanding-error-handling": { + "title": "Understanding Error Handling", + "intro": [ + "In these lessons, you will learn about error handling in Python. You will learn about the different types of errors, some good debugging practices, what exceptions are, and how to handle them." + ] + }, + "lab-isbn-validator": { + "title": "Debug an ISBN Validator", + "intro": [ + "In this lab, you will start with a bugged app, and you will need to debug and fix the bugs until it is working properly." + ] + }, + "review-error-handling": { + "title": "Error Handling Review", + "intro": [ + "Before you're quizzed on error handling, you should review what you've learned about it." + ] + }, + "quiz-error-handling": { + "title": "Error Handling Quiz", + "intro": [ + "Test what you've learned about Error Handling in Python with this quiz." + ] + } + } + }, + "learn-python-classes-and-objects": { + "title": "Learn Python Classes and Objects", + "summary": ["Learn how to work with classes and objects in Python."], + "intro": [ + "In this interactive course, you will learn how to work with classes and objects in Python." + ], + "note": "", + "blocks": { + "lecture-classes-and-objects": { + "title": "Classes and Objects", + "intro": ["Learn about classes and objects in these lessons."] + }, + "workshop-musical-instrument-inventory": { + "title": "Build a Musical Instrument Inventory", + "intro": [ + "In this workshop, you will learn about classes, objects, and methods in Python by building a simple musical instrument inventory." + ] + }, + "lab-planet-class": { + "title": "Build a Planet Class", + "intro": [ + "In this lab you will create a class that represents a planet." + ] + }, + "workshop-email-simulator": { + "title": "Build an Email Simulator", + "intro": [ + "In this workshop you will implement classes and objects by building an email simulator that simulates sending, receiving, and managing emails between different users." + ] + }, + "lab-budget-app": { + "title": "Build a Budget App", + "intro": [ + "In this lab you will build a budget app and practice creating a class and methods for that class." + ] + }, + "review-classes-and-objects": { + "title": "Classes and Objects Review", + "intro": [ + "Before you're quizzed on classes and objects, you should review what you've learned about them.", + "Open up this page to review concepts like how classes work, what are objects, methods, attributes, special methods and more." + ] + }, + "quiz-classes-and-objects": { + "title": "Classes and Objects Quiz", + "intro": [ + "Test what you've learned about classes and objects in Python with this quiz." + ] + } + } + }, + "introduction-to-oop-in-python": { + "title": "Introduction to OOP in Python", + "summary": [ + "Learn the basics of Object-Oriented Programming (OOP) in Python." + ], + "intro": [ + "In this interactive course, you will learn the basics of Object-Oriented Programming (OOP) in Python." + ], + "note": "", + "blocks": { + "lecture-understanding-object-oriented-programming-and-encapsulation": { + "title": "Understanding Object Oriented Programming and Encapsulation", + "intro": [ + "Learn about understanding object oriented programming and encapsulation in these lessons." + ] + }, + "workshop-salary-tracker": { + "title": "Build a Salary Tracker", + "intro": [ + "In this workshop, you'll practice encapsulation, properties, and other OOP concepts by building a salary tracking system for employees." + ] + }, + "lab-game-character-stats": { + "title": "Build a Game Character Stats Tracker", + "intro": [ + "In this lab, you will build a game character with different stats using object-oriented programming." + ] + }, + "lecture-understanding-inheritance-and-polymorphism": { + "title": "Understanding Inheritance and Polymorphism", + "intro": [ + "Learn about understanding inheritance and polymorphism in these lessons." + ] + }, + "workshop-media-catalogue": { + "title": "Build a Media Catalogue", + "intro": [ + "In this workshop, you will create a media catalogue application using object-oriented programming principles." + ] + }, + "lecture-understanding-abstraction": { + "title": "Understanding Abstraction", + "intro": ["Learn about understanding abstraction in these lessons."] + }, + "workshop-discount-calculator": { + "title": "Build a Discount Calculator", + "intro": [ + "In this workshop you will build a flexible discount pricing calculator through abstract base classes, allowing multiple discount algorithms to be applied interchangeably without modifying the core logic." + ] + }, + "lab-player-interface": { + "title": "Build a Player Interface", + "intro": [ + "In this lab, you'll use the abc module to build a player interface." + ] + }, + "lab-polygon-area-calculator": { + "title": "Build a Polygon Area Calculator", + "intro": [ + "In this lab, you will use object-oriented programming to calculate the areas of different polygons like squares and rectangles." + ] + }, + "review-object-oriented-programming": { + "title": "Object Oriented Programming Review", + "intro": [ + "Before you're quizzed on object oriented programming, you should review what you've learned about it." + ] + }, + "quiz-object-oriented-programming": { + "title": "Object Oriented Programming Quiz", + "intro": [ + "Test what you've learned about object oriented programming in Python with this quiz." + ] + } + } + }, + "introduction-to-linear-data-structures-in-python": { + "title": "Introduction to Linear Data Structures in Python", + "summary": ["Learn the basics of linear data structures in Python."], + "intro": [ + "In this interactive course, you will learn the basics of linear data structures in Python." + ], + "note": "", + "blocks": { + "lecture-working-with-common-data-structures": { + "title": "Working with Common Data Structures", + "intro": [ + "Learn about working with common data structures in these lessons." + ] + }, + "workshop-linked-list-class": { + "title": "Build a Linked List", + "intro": [ + "In this workshop, you'll practice working with data structures by building a linked list." + ] + }, + "lab-hash-table": { + "title": "Build a Hash Table", + "intro": [ + "A hash table is a data structure that is used to store key-value pairs and is optimized for quick lookups.", + "In this lab, you will use your knowledge about data structures to build a hash table." + ] + }, + "review-data-structures": { + "title": "Data Structures Review", + "intro": [ + "Before you're quizzed on data structures, you should review what you've learned about them.", + "Open up this page to review concepts like the different data structures, algorithms, time and space complexity, and big O notation." + ] + }, + "quiz-data-structures": { + "title": "Data Structures Quiz", + "intro": [ + "Test what you've learned about data structures in Python with this quiz." + ] + } + } + }, + "learn-algorithms-in-python": { + "title": "Learn Algorithms in Python", + "summary": ["Learn the basics of algorithms in Python."], + "intro": [ + "In this interactive course, you will learn the basics of algorithms in Python." + ], + "note": "", + "blocks": { + "lecture-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms", + "intro": [ + "Learn about fundamental searching and sorting algorithms, including linear search, binary search, and merge sort.", + "These lessons cover algorithm implementations, time and space complexity analysis, and the divide and conquer programming paradigm." + ] + }, + "workshop-binary-search": { + "title": "Implement the Binary Search Algorithm", + "intro": [ + "The binary search algorithm is a searching algorithm used to find a target item in a sorted list.", + "In this workshop, you'll implement the binary search algorithm and return the path it took to find the target or return 'Value not found'." + ] + }, + "lab-bisection-method": { + "title": "Implement the Bisection Method", + "intro": [ + "In this lab, you will implement the bisection method to find the square root of a number." + ] + }, + "workshop-merge-sort": { + "title": "Implement the Merge Sort Algorithm", + "intro": [ + "The merge sort algorithm is a sorting algorithm based on the divide and conquer principle.", + "In this workshop, you'll implement the merge sort algorithm to sort a list of random numbers." + ] + }, + "lab-quicksort": { + "title": "Implement the Quicksort Algorithm", + "intro": [ + "In this lab you will implement the quicksort algorithm to sort a list of integers." + ] + }, + "lab-selection-sort": { + "title": "Implement the Selection Sort Algorithm", + "intro": [ + "In this lab you will implement the selection sort algorithm." + ] + }, + "lab-luhn-algorithm": { + "title": "Implement the Luhn Algorithm", + "intro": [ + "In this lab, you will implement the Luhn algorithm to validate identification numbers such as credit card numbers." + ] + }, + "lab-tower-of-hanoi": { + "title": "Implement the Tower of Hanoi Algorithm", + "intro": [ + "In this lab, you will implement an algorithm to solve the Tower of Hanoi puzzle." + ] + }, + "review-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms Review", + "intro": [ + "Before you're quizzed on searching and sorting algorithms, you should review what you've learned about them." + ] + }, + "quiz-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms Quiz", + "intro": [ + "Test what you've learned about searching and sorting algorithms in Python with this quiz." + ] + } + } + }, + "learn-graphs-and-trees-in-python": { + "title": "Learn Graphs and Trees in Python", + "summary": ["Learn the basics of graphs and trees in Python."], + "intro": [ + "In this interactive course, you will learn the basics of graphs and trees in Python." + ], + "note": "", + "blocks": { + "lecture-understanding-graphs-and-trees": { + "title": "Understanding Graphs and Trees", + "intro": [ + "In this lesson, you will learn about fundamental data structures like graphs, trees, and their practical applications in computer science." + ] + }, + "workshop-shortest-path-algorithm": { + "title": "Implement the Shortest Path Algorithm", + "intro": [ + "In this workshop you will implement an algorithm to find the shortest path between two nodes in a graph." + ] + }, + "lab-adjacency-list-to-matrix-converter": { + "title": "Build an Adjacency List to Matrix Converter", + "intro": [ + "In this lab, you will implement a function that converts an adjacency list representation of a graph into an adjacency matrix representation." + ] + }, + "workshop-breadth-first-search": { + "title": "Implement the Breadth-First Search Algorithm", + "intro": [ + "In this workshop, you will use the breadth-first search algorithm to generate all valid combinations of parentheses." + ] + }, + "lab-depth-first-search": { + "title": "Implement the Depth-First Search Algorithm", + "intro": [ + "In this lab, you will implement the Depth-First Search Algorithm." + ] + }, + "lab-n-queens-problem": { + "title": "Implement the N-Queens Algorithm", + "intro": [ + "In this lab, you will implement a solution for the N-Queens problem." + ] + }, + "review-graphs-and-trees": { + "title": "Graphs and Trees Review", + "intro": [ + "Before you're quizzed on graphs and trees, you should review what you've learned about them." + ] + }, + "quiz-graphs-and-trees": { + "title": "Graphs and Trees Quiz", + "intro": [ + "Test what you've learned about graphs and trees in Python with this quiz." + ] + } + } + }, + "learn-dynamic-programming-in-python": { + "title": "Learn Dynamic Programming in Python", + "summary": ["Learn the basics of dynamic programming in Python."], + "intro": [ + "In this interactive course, you will learn the basics of dynamic programming in Python." + ], + "note": "", + "blocks": { + "lecture-understanding-dynamic-programming": { + "title": "Understanding Dynamic Programming", + "intro": [ + "In this lesson, you will learn about dynamic programming, an algorithmic technique used to solve complex problems efficiently by breaking them down into simpler subproblems." + ] + }, + "lab-nth-fibonacci-number": { + "title": "Build an Nth Fibonacci Number Calculator", + "intro": [ + "In this lab you will implement a Fibonacci sequence calculator using a dynamic programming approach." + ] + }, + "review-dynamic-programming": { + "title": "Dynamic Programming Review", + "intro": [ + "Before you're quizzed on dynamic programming, you should review what you've learned about it." + ] + }, + "quiz-dynamic-programming": { + "title": "Dynamic Programming Quiz", + "intro": [ + "Test what you've learned about dynamic programming in Python with this quiz." + ] + } + } + }, + "introduction-to-variables-and-strings-in-javascript": { + "title": "Introduction to Variables and Strings in JavaScript", + "summary": ["Learn the basics of variables and strings in JavaScript."], + "intro": [ + "In this interactive course, you will learn about variables and strings, which are fundamental concepts in JavaScript programming." + ], + "note": "", + "blocks": { + "lecture-introduction-to-javascript": { + "title": "Introduction to JavaScript", + "intro": [ + "In these lectures, you will learn the fundamentals of JavaScript. Topics covered include, but are not limited to, variables, data types, how JavaScript interacts with HTML and CSS, strings, and much more." + ] + }, + "lecture-introduction-to-strings": { + "title": "Introduction to Strings", + "intro": [ + "In these lessons, you will learn how to work with strings, string concatenation, and console.log()." + ] + }, + "lecture-understanding-code-clarity": { + "title": "Understanding Code Clarity", + "intro": [ + "In these lessons, you will learn about comments in JavaScript and the role of semicolons in programming." + ] + }, + "workshop-greeting-bot": { + "title": "Build a Greeting Bot", + "intro": [ + "In this workshop, you will learn JavaScript fundamentals by building a greeting bot.", + "You will learn about variables, let, const, console.log and basic string usage." + ] + }, + "lab-javascript-trivia-bot": { + "title": "Build a JavaScript Trivia Bot", + "intro": [ + "In this lab, you'll practice working with JavaScript variables and strings by building a trivia bot." + ] + }, + "lab-sentence-maker": { + "title": "Build a Sentence Maker", + "intro": [ + "In this lab, you will continue practicing with strings and concatenation by creating and customizing various stories." + ] + }, + "lecture-working-with-data-types": { + "title": "Working with Data Types", + "intro": [ + "In the following lectures, you will learn how to work with data types in JavaScript. You will also learn how dynamic typing differs from static typing, the typeof operator, and the typeof null bug." + ] + }, + "review-javascript-variables-and-data-types": { + "title": "JavaScript Variables and Data Types Review", + "intro": [ + "Before you are quizzed on JavaScript variables and data types you first need to review the concepts.", + "Open up this page to review variables, data types, logging and commenting." + ] + }, + "quiz-javascript-variables-and-data-types": { + "title": "JavaScript Variables and Data Types Quiz", + "intro": [ + "Test your knowledge of JavaScript variables and data types with this quiz." + ] + }, + "lecture-working-with-strings-in-javascript": { + "title": "Working with Strings in JavaScript", + "intro": [ + "In these lectures, you will learn how to work with strings in JavaScript. You will learn how to access characters from a string, how to use template literals and interpolation, how to create a new line in strings, and much more." + ] + }, + "workshop-teacher-chatbot": { + "title": "Build a Teacher Chatbot", + "intro": [ + "In this workshop, you will continue to learn more about JavaScript strings by building a chatbot.", + "You will learn how to work with template literals, and the indexOf method." + ] + }, + "lecture-working-with-string-character-methods": { + "title": "Working with String Character Methods", + "intro": [ + "In this lecture you will learn about ASCII character encoding and how to use JavaScript's charCodeAt() and fromCharCode() methods to convert between characters and their numerical ASCII values." + ] + }, + "lecture-working-with-string-search-and-slice-methods": { + "title": "Working with String Search and Slice Methods", + "intro": [ + "In this lecture you will learn how to search for substrings using the includes() method and how to extract portions of strings using the slice() method." + ] + }, + "workshop-string-inspector": { + "title": "Build a String Inspector", + "intro": [ + "In this workshop, you will practice working with the includes() and slice() methods by building a string inspector." + ] + }, + "lecture-working-with-string-formatting-methods": { + "title": "Working with String Formatting Methods", + "intro": [ + "In this lecture you will learn how to format strings by changing their case using toUpperCase() and toLowerCase() methods, and how to remove whitespace using trim(), trimStart(), and trimEnd() methods." + ] + }, + "workshop-string-formatter": { + "title": "Build a String Formatter", + "intro": [ + "In this workshop, you will practice working with various string methods including trim(), toUpperCase() and toLowerCase()." + ] + }, + "lecture-working-with-string-modification-methods": { + "title": "Working with String Modification Methods", + "intro": [ + "In this lecture you will learn how to modify strings by replacing parts of them using the replace() method and how to repeat strings multiple times using the repeat() method." + ] + }, + "workshop-string-transformer": { + "title": "Build a String Transformer", + "intro": [ + "In this workshop, you will practice working with the replace(), replaceAll() and repeat() methods." + ] + }, + "review-javascript-strings": { + "title": "JavaScript Strings Review", + "intro": [ + "Before you are quizzed on working with JavaScript strings, you first need to review.", + "Open up this page to review how to work with template literals, the slice method, the includes method, the trim method and more." + ] + }, + "quiz-javascript-strings": { + "title": "JavaScript Strings Quiz", + "intro": ["Test your knowledge of JavaScript strings with this quiz."] + } + } + }, + "introduction-to-booleans-and-numbers-in-javascript": { + "title": "Introduction to Booleans and Numbers in JavaScript", + "summary": ["Learn the basics of booleans and numbers in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with booleans and numbers in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-numbers-and-arithmetic-operators": { + "title": "Working with Numbers and Arithmetic Operators", + "intro": [ + "In these lectures you will learn about the number type, arithmetic operators, and using them with numbers and strings." + ] + }, + "lab-debug-type-coercion-errors": { + "title": "Debug Type Coercion Errors in a Buggy App", + "intro": [ + "In this lab, you will be working with a buggy app that contains several type coercion errors.", + "Your task is to identify and fix these errors to ensure the app functions correctly." + ] + }, + "lecture-working-with-operator-behavior": { + "title": "Working with Operator Behavior", + "intro": [ + "In these lectures you will learn about operator precedence, the increment and decrement operators, and compound assignment operators." + ] + }, + "lab-debug-increment-and-decrement-operator-errors": { + "title": "Debug Increment and Decrement Operator Errors in a Buggy App", + "intro": [ + "In this lab, you'll debug an app that has several errors related to the increment and decrement operators.", + "Your task is to identify and fix the errors so that the app works as intended." + ] + }, + "lecture-working-with-comparison-and-boolean-operators": { + "title": "Working with Comparison and Boolean Operators", + "intro": [ + "In these lectures you will learn about booleans, and equality and inequality operators, and other comparison operators." + ] + }, + "workshop-logic-checker-app": { + "title": "Build a Logic Checker App", + "intro": [ + "In this workshop, you'll practice working with conditional statements and comparison operators by building a logic checker app." + ] + }, + "lecture-working-with-unary-and-bitwise-operators": { + "title": "Working with Unary and Bitwise Operators", + "intro": [ + "In these lectures, you will learn about unary and bitwise operators." + ] + }, + "lecture-working-with-conditional-logic-and-math-methods": { + "title": "Working with Conditional Logic and Math Methods", + "intro": [ + "In these lectures, you will learn about conditional statements, binary logical operators, and the Math object." + ] + }, + "workshop-mathbot": { + "title": "Build a Mathbot", + "intro": [ + "In this workshop, you will review how to work with the different Math object methods by building a Mathbot." + ] + }, + "lab-fortune-teller": { + "title": "Build a Fortune Teller", + "intro": [ + "In this lab, you'll build a fortune teller by randomly selecting a fortune from the available fortunes.", + "You'll practice how to work with the Math.random() method and the Math.floor() method to generate random numbers." + ] + }, + "lecture-working-with-numbers-and-common-number-methods": { + "title": "Working with Numbers and Common Number Methods", + "intro": [ + "In these lectures, you will learn about numbers and common number methods. These include isNaN(), parseInt(), parseFloat(), and toFixed()." + ] + }, + "review-javascript-math": { + "title": "JavaScript Math Review", + "intro": [ + "Before you're quizzed on working with the Math object, you should review what you've learned.", + "Open up this page to review how to work with the Math.random() method, the Math.floor() method and more." + ] + }, + "quiz-javascript-math": { + "title": "JavaScript Math Quiz", + "intro": [ + "Test your knowledge of the JavaScript Math object with this quiz." + ] + }, + "lecture-understanding-comparisons-and-conditionals": { + "title": "Understanding Comparisons and Conditionals", + "intro": [ + "In these lectures, you will learn about comparison operators and conditionals. You will learn how the various conditionals differ from one another, and how comparisons work with null and undefined." + ] + }, + "review-javascript-comparisons-and-conditionals": { + "title": "JavaScript Comparisons and Conditionals Review", + "intro": [ + "Before you're quizzed on working with conditionals, you should review what you've learned about them.", + "Open up this page to review how to work with switch statements, other types of conditionals and more." + ] + }, + "quiz-javascript-comparisons-and-conditionals": { + "title": "JavaScript Comparisons and Conditionals Quiz", + "intro": [ + "Test your knowledge of JavaScript Comparisons and Conditionals with this quiz." + ] + } + } + }, + "introduction-functions-in-javascript": { + "title": "Introduction to Functions in JavaScript", + "summary": ["Learn the basics of functions in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with functions in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-functions": { + "title": "Working with Functions", + "intro": [ + "In these lectures, you will learn how to reuse a block of code with functions. You will learn what the purpose of a function is and how they work, and how scope works in programming. " + ] + }, + "workshop-calculator": { + "title": "Build a Calculator", + "intro": [ + "In this workshop, you will review your knowledge of functions by building a calculator." + ] + }, + "lab-boolean-check": { + "title": "Build a Boolean Check Function", + "intro": [ + "In this lab, you'll implement a function that checks if a value is a boolean." + ] + }, + "lab-email-masker": { + "title": "Build an Email Masker", + "intro": [ + "In this lab, you'll build an email masker that will take an email address and obscure it.", + "You'll practice string slicing, concatenation, and using functions." + ] + }, + "workshop-loan-qualification-checker": { + "title": "Build a Loan Qualification Checker", + "intro": [ + "In this workshop, you will continue to learn how to work with conditionals by building a loan qualification checker app.", + "You will learn more about if statements, and how to use comparison operators and multiple conditions in an if statement." + ] + }, + "lab-celsius-to-fahrenheit-converter": { + "title": "Build a Celsius to Fahrenheit Converter", + "intro": [ + "In this lab you will implement a function that converts the temperature from Celsius to Fahrenheit." + ] + }, + "lab-counting-cards": { + "title": "Build a Card Counting Assistant", + "intro": ["In this lab you will use JavaScript to count dealt cards."] + }, + "lab-leap-year-calculator": { + "title": "Build a Leap Year Calculator ", + "intro": [ + "In this lab you'll use conditional statements and loops to determine if a year is a leap year." + ] + }, + "lab-truncate-string": { + "title": "Implement the Truncate String Algorithm", + "intro": [ + "In this lab, you will practice truncating a string at a certain length." + ] + }, + "lab-string-ending-checker": { + "title": "Build a Confirm the Ending Tool", + "intro": [ + "In this lab, you will implement a function that checks if a given string ends with a specified target string." + ] + }, + "review-javascript-functions": { + "title": "JavaScript Functions Review", + "intro": [ + "Before you're quizzed on JavaScript functions, you should review what you've learned about them.", + "Open up this page to review functions, arrow functions and scope." + ] + }, + "quiz-javascript-functions": { + "title": "JavaScript Functions Quiz", + "intro": ["Test your knowledge of JavaScript functions with this quiz."] + } + } + }, + "introduction-to-arrays-in-javascript": { + "title": "Introduction to Arrays in JavaScript", + "summary": ["Learn the basics of arrays in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with arrays in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-arrays": { + "title": "Working with Arrays", + "intro": [ + "In these lectures, you will learn how to work with JavaScript arrays. You will learn about what makes an array, one-dimensional and two-dimensional arrays, how to access and update the elements in an array, and much more." + ] + }, + "workshop-shopping-list": { + "title": "Build a Shopping List", + "intro": [ + "In this workshop, you will practice how to work with arrays by building a shopping list.", + "You will review how to add and remove elements from an array using methods like push, pop, shift, and unshift." + ] + }, + "lab-lunch-picker-program": { + "title": "Build a Lunch Picker Program", + "intro": [ + "In this lab, you'll review working with arrays and random numbers by building a lunch picker program." + ] + }, + "lab-golf-score-translator": { + "title": "Build a Golf Score Translator", + "intro": [ + "For this lab, you will use array methods to translate golf scores into their nickname." + ] + }, + "lecture-working-with-common-array-methods": { + "title": "Working with Common Array Methods", + "intro": [ + "In these lectures, you will learn about the array methods for performing more advanced operations like getting the position of an item in an array, checking if an array contains a certain element, copying an array, and lots more." + ] + }, + "review-javascript-arrays": { + "title": "JavaScript Arrays Review", + "intro": [ + "Before you're quizzed on JavaScript arrays, you should review what you've learned about them.", + "Open up this page to review concepts like array destructuring, how to add and remove elements from an array, and more." + ] + }, + "quiz-javascript-arrays": { + "title": "JavaScript Arrays Quiz", + "intro": ["Test your knowledge of JavaScript arrays with this quiz."] + } + } + }, + "introduction-to-objects-in-javascript": { + "title": "Introduction to Objects in JavaScript", + "summary": ["Learn the basics of objects in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with objects in JavaScript." + ], + "note": "", + "blocks": { + "lecture-introduction-to-javascript-objects-and-their-properties": { + "title": "Introduction to JavaScript Objects and Their Properties", + "intro": [ + "In these lectures, you will learn the fundamentals of JavaScript objects, including how to create them, access their properties, and understand the difference between primitive and non-primitive data types." + ] + }, + "workshop-wildlife-tracker": { + "title": "Build a Wildlife Tracker", + "intro": [ + "In this workshop, you will build a simple Wildlife Tracker using JavaScript objects.", + "You will practice creating objects, accessing and updating properties, removing properties, checking for property existence, and working with bracket notation." + ] + }, + "lab-cargo-manifest-validator": { + "title": "Build a Cargo Manifest Validator", + "intro": [ + "In this lab, you will use JavaScript to normalize and validate cargo manifests." + ] + }, + "lecture-working-with-json": { + "title": "Working with JSON", + "intro": [ + "In these lectures, you will learn about JavaScript Object Notation (JSON), including how to access JSON data and use the JSON.parse() and JSON.stringify() methods." + ] + }, + "lecture-working-with-optional-chaining-and-object-destructuring": { + "title": "Working with Optional Chaining and Object Destructuring", + "intro": [ + "In these lectures, you will learn about advanced object manipulation techniques in JavaScript, including the optional chaining operator and object destructuring syntax." + ] + }, + "workshop-recipe-tracker": { + "title": "Build a Recipe Tracker", + "intro": [ + "In this workshop, you will review working with JavaScript objects by building a recipe tracker." + ] + }, + "lab-quiz-game": { + "title": "Build a Quiz Game", + "intro": [ + "In this lab, you'll build a quiz game using JavaScript arrays and objects.", + "You'll also practice using functions to randomly select a question and an answer from an array and compare them." + ] + }, + "lab-record-collection": { + "title": "Build a Record Collection", + "intro": [ + "In this lab you will build a function to manage a record collection." + ] + }, + "review-javascript-objects": { + "title": "JavaScript Objects Review", + "intro": [ + "Before you're quizzed on JavaScript objects, you should review what you've learned about them.", + "Open up this page to review concepts including how to access information from objects, object destructuring, working with JSON, and more." + ] + }, + "quiz-javascript-objects": { + "title": "JavaScript Objects Quiz", + "intro": ["Test your knowledge of JavaScript objects with this quiz."] + } + } + }, + "introduction-to-loops-in-javascript": { + "title": "Introduction to Loops in JavaScript", + "summary": ["Learn the basics of loops in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with loops in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-loops": { + "title": "Working with Loops", + "intro": [ + "Loops are an essential part of JavaScript. That's why the following lectures have been prepared for you to learn about the different types of loops and how they work, and also how iteration works." + ] + }, + "workshop-word-counter": { + "title": "Build a Word Counter", + "intro": [ + "In this workshop, you will practice using for...of loops by building a function that counts the occurrences of a string in an array of strings." + ] + }, + "workshop-sentence-analyzer": { + "title": "Build a Sentence Analyzer", + "intro": [ + "In this workshop, you'll review how to work with JavaScript loops by building a sentence analyzer app." + ] + }, + "lab-traffic-light-sequencer": { + "title": "Build a Traffic Light Sequencer", + "intro": [ + "In this lab, you will use JavaScript loops to build a traffic light sequencer." + ] + }, + "workshop-space-mission-roster": { + "title": "Build a Space Mission Roster", + "intro": [ + "In this workshop, you'll leverage JavaScript loops to build a space mission roster." + ] + }, + "workshop-heritage-library-catalog": { + "title": "Build a Heritage Library Catalog", + "intro": [ + "In this workshop, you will digitize historical catalog cards for a heritage library.", + "You will practice using loops, objects, and string methods to parse raw text data, search and group entries, render formatted output, and export to JSON and CSV." + ] + }, + "lab-longest-word-in-a-string": { + "title": "Build a Longest Word Finder App", + "intro": [ + "In this lab, you will use JavaScript loops to find the length of the longest word in the given sentence." + ] + }, + "lab-factorial-calculator": { + "title": "Build a Factorial Calculator ", + "intro": [ + "In this lab, you'll build a factorial calculator.", + "You'll practice using loops and conditionals to calculate the factorial of a number." + ] + }, + "lab-mutations": { + "title": "Implement the Mutations Algorithm", + "intro": [ + "In this lab, you will practice iterating over two different strings to compare their characters." + ] + }, + "lab-chunky-monkey": { + "title": "Implement the Chunky Monkey Algorithm", + "intro": [ + "In this lab, you will practice dividing an array into smaller arrays with the technique of your choice." + ] + }, + "lab-profile-lookup": { + "title": "Build a Profile Lookup", + "intro": [ + "In this lab, you'll create a function that looks up profile information." + ] + }, + "lab-repeat-a-string": { + "title": "Build a String Repeating Function", + "intro": [ + "In this lab, you will implement loops to repeat a string a specified number of times." + ] + }, + "workshop-festival-crowd-flow-simulator": { + "title": "Build a Festival Crowd Flow Simulator", + "intro": [ + "In this workshop, you will use JavaScript to simulate the flow of attendants at a music festival." + ] + }, + "lab-missing-letter-detector": { + "title": "Build a Missing Letter Detector", + "intro": [ + "In this lab, you will build a function that finds the missing letter in a given range of consecutive letters and returns it." + ] + }, + "lab-smart-pantry-restocker": { + "title": "Build a Smart Pantry Restocker", + "intro": [ + "In this lab, you will build a small pantry management program using basic JavaScript concepts like arrays, objects, loops, and conditionals." + ] + }, + "lab-proofreading-tool": { + "title": "Build a Proofreading Tool", + "intro": [ + "In this lab, you will build a proofreading tool that analyzes arrays of words for palindromes and repeated phrases.", + "You will practice for loops and nested loops to check palindromes and find repeated word sequences." + ] + }, + "review-javascript-loops": { + "title": "JavaScript Loops Review", + "intro": [ + "Before you're quizzed on the different JavaScript loops, you should review them.", + "Open up this page to review the for...of loop, while loop, break and continue statements and more." + ] + }, + "quiz-javascript-loops": { + "title": "JavaScript Loops Quiz", + "intro": ["Test your knowledge of JavaScript loops with this quiz."] + } + } + }, + "javascript-fundamentals-review": { + "title": "JavaScript Fundamentals Review", + "summary": ["Review the core concepts of JavaScript."], + "intro": [ + "In this interactive course, you will practice core JavaScript fundamentals including loops, objects, arrays and more." + ], + "note": "", + "blocks": { + "lecture-working-with-types-and-objects": { + "title": "Working with Types and Objects", + "intro": [ + "In these lectures you will learn about string objects, the toString() method, the Number constructor and more." + ] + }, + "lecture-working-with-arrays-variables-and-naming-practices": { + "title": "Working with Arrays, Variables, and Naming Practices", + "intro": [ + "In these lectures you will learn about common practices for naming variables and functions, and how to work with arrays." + ] + }, + "lecture-working-with-code-quality-and-execution-concepts": { + "title": "Working with Code Quality and Execution Concepts", + "intro": [ + "In these lectures you will learn what are linters and formatters, what is memory management, and closures." + ] + }, + "lab-reverse-a-string": { + "title": "Build a String Inverter", + "intro": [ + "In this lab, you create a function that reverses a given string." + ] + }, + "lab-largest-number-finder": { + "title": "Build the Largest Number Finder", + "intro": [ + "In this lab, you will use JavaScript fundamentals to create a function that finds the largest number in each sub-array of a given array." + ] + }, + "lab-first-element-finder": { + "title": "Build a First Element Finder", + "intro": [ + "In this lab, you will create a function that looks through an array and returns the first element in it that passes a \"truth test\"." + ] + }, + "lab-slice-and-splice": { + "title": "Implement the Slice and Splice Algorithm", + "intro": [ + "In this lab, you will practice merging an array with another." + ] + }, + "lab-pyramid-generator": { + "title": "Build a Pyramid Generator", + "intro": [ + "In this lab you'll build a pyramid generator.", + "You'll take a number as input and generate a pyramid with that many levels using a loop." + ] + }, + "lab-gradebook-app": { + "title": "Build a Gradebook App", + "intro": [ + "For this lab, you'll create a gradebook app.", + "You'll practice conditionals to determine the student's grade based on their score." + ] + }, + "lab-story-fragment-restoration": { + "title": "Restore a Coherent Narrative from an Array of Story Fragments", + "intro": [ + "In this lab, you'll restore a coherent narrative from a corrupted array of story fragments.", + "You will practice working with loops by implementing fundamental array algorithms from scratch." + ] + }, + "lecture-the-var-keyword-and-hoisting": { + "title": "The var Keyword and Hoisting", + "intro": [ + "In these lectures, you will learn about the var keyword and why it is not recommended for use anymore. You will also learn about hoisting in JavaScript so you can avoid subtle bugs in your code." + ] + }, + "lab-title-case-converter": { + "title": "Build a Title Case Converter", + "intro": [ + "In this lab, you will build a function that converts a string to title case." + ] + }, + "lab-falsy-remover": { + "title": "Implement a Falsy Remover", + "intro": [ + "In this lab, you will create a function that removes all falsy values from an array." + ] + }, + "lab-inventory-management-program": { + "title": "Build an Inventory Management Program", + "intro": [ + "For this lab, you'll build an inventory management program using JavaScript.", + "You'll use JavaScript array of objects to manage the inventory." + ] + }, + "lecture-understanding-modules-imports-and-exports": { + "title": "Understanding Modules, Imports, and Exports", + "intro": [ + "In this lecture, you will learn about modules, imports, and exports in JavaScript." + ] + }, + "lecture-working-with-the-arguments-object-and-rest-parameters": { + "title": "Working With the Arguments Object and Rest Parameters", + "intro": [ + "In these lessons, you will learn how to work with the arguments object and rest parameter syntax." + ] + }, + "lab-unique-sorted-union": { + "title": "Implement a Unique Sorted Union", + "intro": [ + "In this lab, you will create a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays." + ] + }, + "lab-password-generator": { + "title": "Build a Password Generator App", + "intro": [ + "In this lab, you'll build a password generator app based on the user's input." + ] + }, + "lab-sum-all-numbers-algorithm": { + "title": "Design a Sum All Numbers Algorithm", + "intro": [ + "In this lab, you will design a sum all numbers algorithm. This algorithm takes an array of two numbers and returns the sum of those two numbers plus the sum of all the numbers between them." + ] + }, + "lab-dna-pair-generator": { + "title": "Implement a DNA Pair Generator", + "intro": [ + "In this lab you will implement a DNA base pairing algorithm that converts a single DNA strand into complementary base pairs." + ] + }, + "lab-html-entitiy-converter": { + "title": "Implement an HTML Entity Converter", + "intro": [ + "In this lab, you will convert special characters in a string to their corresponding HTML entities." + ] + }, + "lab-odd-fibonacci-sum-calculator": { + "title": "Build an Odd Fibonacci Sum Calculator", + "intro": [ + "In this lab you will build an odd Fibonacci sum calculator that takes a number and returns the sum of all odd Fibonacci numbers that are less than or equal to that number." + ] + }, + "lab-element-skipper": { + "title": "Implement an Element Skipper", + "intro": [ + "In this lab you will create a function that skips elements in an array based on a specified step value." + ] + }, + "lab-playlist-remix-engine": { + "title": "Build a Playlist Remix Engine", + "intro": [ + "In this lab, you will build a Playlist Remix Engine using JavaScript arrays.", + "You will apply array methods and logic to transform data and generate a final remix schedule." + ] + }, + "review-javascript-fundamentals": { + "title": "JavaScript Fundamentals Review", + "intro": [ + "Before you are quizzed on JavaScript fundamentals, you first need to review the concepts.", + "Open up this page to review concepts like closures, memory management, and more." + ] + }, + "quiz-javascript-fundamentals": { + "title": "JavaScript Fundamentals Quiz", + "intro": [ + "Test your knowledge of JavaScript fundamentals with this quiz." + ] + } + } + }, + "introduction-to-higher-order-functions-and-callbacks-in-javascript": { + "title": "Introduction to Higher-Order Functions and Callbacks in JavaScript", + "summary": [ + "Learn the basics of higher-order functions and callbacks in JavaScript." + ], + "intro": [ + "In this interactive course, you will learn how to work with higher-order functions and callbacks in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-higher-order-functions-and-callbacks": { + "title": "Working with Higher Order Functions and Callbacks", + "intro": [ + "In these lectures, you will learn how to work with higher order functions and callbacks. The higher order functions you will learn include map(), filter(), reduce(), sort(), every(), and some(). You will also learn how to chain these methods together to achieve your desired results." + ] + }, + "workshop-library-manager": { + "title": "Build a Library Manager", + "intro": [ + "In this workshop, you will learn higher order array methods by building a library manager." + ] + }, + "lab-book-organizer": { + "title": "Build a Book Organizer", + "intro": [ + "In this lab, you'll build a book organizer using higher order functions in JavaScript." + ] + }, + "lab-sorted-index-finder": { + "title": "Implement a Sorted Index Finder", + "intro": [ + "In this lab, you will create a function that finds the index at which a given number should be inserted into a sorted array to maintain the array's sorted order." + ] + }, + "lab-symmetric-difference": { + "title": "Build a Symmetric Difference Function", + "intro": [ + "In this lab, you will practice using higher order functions to find the symmetric difference between two arrays." + ] + }, + "lab-value-remover-function": { + "title": "Implement a Value Remover Function", + "intro": [ + "In this lab, you will create a function that removes all instances of a specified value from an array." + ] + }, + "lab-matching-object-filter": { + "title": "Implement a Matching Object Filter", + "intro": [ + "In this lab, you will create a function that looks through an array of objects and returns an array of all objects that have matching property and value pairs." + ] + }, + "lab-range-based-lcm-calculator": { + "title": "Implement a Range-Based LCM Calculator", + "intro": [ + "In this lab, you will create a function that takes an array of two numbers and returns the least common multiple (LCM) of those two numbers and all the numbers between them." + ] + }, + "lab-deep-flattening-tool": { + "title": "Create a Deep Flattening Tool", + "intro": [ + "In this lab you will create a function that can flatten deeply nested arrays, handling any level of nesting without using built-in flat methods." + ] + }, + "lab-all-true-property-validator": { + "title": "Build an All-True Property Validator", + "intro": [ + "In this lab you will build a function that checks if all objects in an array have a truthy value for a specific property." + ] + }, + "review-javascript-higher-order-functions": { + "title": "JavaScript Higher Order Functions Review", + "intro": [ + "Before you're quizzed on JavaScript higher order functions, you should review them.", + "Open up this page to review concepts including how to work with the map(), filter(), and reduce() methods." + ] + }, + "quiz-javascript-higher-order-functions": { + "title": "JavaScript Higher Order Functions Quiz", + "intro": [ + "Test what you've learned about JavaScript higher order functions with this quiz." + ] + } + } + }, + "learn-dom-manipulation-and-events-with-javascript": { + "title": "Learn DOM Manipulation and Events with JavaScript", + "summary": [ + "Learn how to manipulate the DOM and work with events in JavaScript." + ], + "intro": [ + "In this interactive course, you will learn how to manipulate the DOM and work with events in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-the-dom-click-events-and-web-apis": { + "title": "Working with the DOM, Click Events, and Web APIs", + "intro": [ + "In these lectures, you will learn how to work with the Document Object Model (DOM), the addEventListener() method and events, and web APIs." + ] + }, + "workshop-storytelling-app": { + "title": "Build a Storytelling App", + "intro": [ + "In this workshop, you will build a storytelling app that will allow you to list different stories based on genre." + ] + }, + "workshop-emoji-reactor": { + "title": "Build an Emoji Reactor", + "intro": [ + "In this workshop, you will build an emoji reactor to practice querySelector and querySelectorAll." + ] + }, + "lab-favorite-icon-toggler": { + "title": "Build a Favorite Icon Toggler", + "intro": [ + "In this lab, you'll build a favorite icon toggler by utilizing JavaScript click events." + ] + }, + "lecture-understanding-the-event-object-and-event-delegation": { + "title": "Understanding the Event Object and Event Delegation", + "intro": [ + "In these lectures, you will learn about the event object, the change event, event bubbling, and event delegation." + ] + }, + "workshop-music-instrument-filter": { + "title": "Build a Music Instrument Filter", + "intro": [ + "In this workshop, you will build a music instrument filter with JavaScript." + ] + }, + "lab-real-time-counter": { + "title": "Build a Real Time Counter", + "intro": [ + "In this lab, you'll build a real-time character counter", + "You'll practice how to work with the input event when the user types in the input field." + ] + }, + "lab-lightbox-viewer": { + "title": "Build a Lightbox Viewer", + "intro": [ + "In this lab, you'll build a lightbox viewer for viewing images in a focused mode.", + "You'll practice click events and toggling classes." + ] + }, + "workshop-rps-game": { + "title": "Build a Rock, Paper, Scissors Game", + "intro": [ + "In this workshop, you will review DOM manipulation and events by building a Rock, Paper, Scissors Game." + ] + }, + "lab-football-team-cards": { + "title": "Build a Set of Football Team Cards", + "intro": [ + "In this lab, you'll use DOM manipulation, object destructuring, event handling, and data filtering to build a set of football team cards." + ] + }, + "review-dom-manipulation-and-click-events-with-javascript": { + "title": "DOM Manipulation and Click Events with JavaScript Review", + "intro": [ + "Before you're quizzed on the DOM, you should review what you've learned about it.", + "Open up this page to review concepts including how to work with the DOM, Web APIs, the addEventListener() method, change events, event bubbling and more." + ] + }, + "quiz-dom-manipulation-and-click-event-with-javascript": { + "title": "DOM Manipulation and Click Events with JavaScript Quiz", + "intro": [ + "Test your knowledge of DOM manipulation and click events in JavaScript with this quiz." + ] + } + } + }, + "introduction-to-javascript-and-accessibility": { + "title": "Introduction to JavaScript and Accessibility", + "summary": ["Learn how to use JavaScript to enhance web accessibility."], + "intro": [ + "In this interactive course, you will learn how to use JavaScript to enhance web accessibility." + ], + "note": "", + "blocks": { + "lecture-understanding-aria-expanded-aria-live-and-common-aria-states": { + "title": "Understanding aria-expanded, aria-live, and Common ARIA States", + "intro": [ + "In these lectures you will learn more about ARIA attributes like aria-expanded, aria-live, and common ARIA states." + ] + }, + "workshop-planets-tablist": { + "title": "Build a Planets Tablist", + "intro": [ + "In this workshop, you will build a dynamic tabbed interface that showcases facts about the planets in the solar system." + ] + }, + "workshop-note-taking-app": { + "title": "Build a Note Taking App", + "intro": [ + "In this workshop, you are going to build an accessible note taking app.", + "This will provide you with the opportunity to practice working with aria-live attribute." + ] + }, + "lab-theme-switcher": { + "title": "Build a Theme Switcher", + "intro": [ + "In this lab, you will build a theme switcher and practice working with the aria-haspopup, aria-expanded, and aria-controls attributes." + ] + }, + "review-js-a11y": { + "title": "JavaScript and Accessibility Review", + "intro": [ + "Before you're quizzed on JavaScript and accessibility, you should review what you've learned about it.", + "Open up this page to review concepts including how to work with the aria-expanded, aria-live, and aria-controls attributes." + ] + }, + "quiz-js-a11y": { + "title": "JavaScript and Accessibility Quiz", + "intro": [ + "Test your knowledge of JavaScript and accessibility best practices with this quiz." + ] + } + } + }, + "learn-javascript-debugging": { + "title": "Learn JavaScript Debugging", + "summary": ["Learn how to debug JavaScript code effectively."], + "intro": [ + "In this interactive course, you will learn how to debug JavaScript code." + ], + "note": "", + "blocks": { + "lecture-debugging-techniques": { + "title": "Debugging Techniques", + "intro": [ + "In these lectures, you will learn about the common errors in JavaScript and the techniques you can use to fix them – a process called debugging." + ] + }, + "lab-random-background-color-changer": { + "title": "Debug a Random Background Color Changer", + "intro": [ + "In this lab, you'll debug a random background color changer and fix the errors to make it work properly." + ] + }, + "review-debugging-javascript": { + "title": "Debugging JavaScript Review", + "intro": [ + "Before you're quizzed on common debugging techniques, you should review what you've learned.", + "Open up this page to review concepts including how to work with the throw statement, try...catch...finally and more." + ] + }, + "quiz-debugging-javascript": { + "title": "Debugging JavaScript Quiz", + "intro": ["Test your knowledge of JavaScript debugging with this quiz."] + } + } + }, + "learn-basic-regex-with-javascript": { + "title": "Learn Basic Regex with JavaScript", + "summary": ["Learn the basics of regular expressions in JavaScript."], + "intro": [ + "In this interactive course, you will learn the fundamentals of regular expressions and how to use them in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-regular-expressions": { + "title": "Working with Regular Expressions", + "intro": [ + "In these lectures, you will learn about regular expressions in JavaScript. You will learn about the methods for working with regular expressions, modifiers, character classes, lookaheads, lookbehinds, back-references, quantifiers, and more." + ] + }, + "workshop-spam-filter": { + "title": "Build a Spam Filter", + "intro": [ + "Regular expressions, often shortened to \"regex\" or \"regexp\", are patterns that help programmers match, search, and replace text. Regular expressions are powerful, but can be difficult to understand because they use so many special characters.", + "In this workshop, you'll use capture groups, positive lookaheads, negative lookaheads, and other techniques to match any text you want." + ] + }, + "lab-palindrome-checker": { + "title": "Build a Palindrome Checker", + "intro": [ + "For this lab, you'll build an application that checks whether a given word is a palindrome." + ] + }, + "lab-regex-sandbox": { + "title": "Build a RegEx Sandbox", + "intro": ["In this lab you'll build a regex sandbox."] + }, + "lab-spinal-case-converter": { + "title": "Implement a Spinal Case Converter", + "intro": [ + "In this lab, you will create a function that converts a given string to spinal case which is a style of writing where all letters are lowercase and separated by hyphens." + ] + }, + "lab-pig-latin": { + "title": "Implement a Pig Latin Translator", + "intro": [ + "In this lab, you'll implement a Pig Latin translator using JavaScript.", + "You'll practice string manipulation, conditional logic, and regular expressions." + ] + }, + "lab-smart-word-replacement": { + "title": "Build a Smart Word Replacement Function", + "intro": [ + "In this lab, you will use regex to create a function that performs a search and replace operation on a given string." + ] + }, + "lab-markdown-to-html-converter": { + "title": "Build a Markdown to HTML Converter", + "intro": [ + "For this lab, you'll build a Markdown to HTML converter using JavaScript.", + "You'll practice regular expressions, string manipulation, and more." + ] + }, + "review-javascript-regular-expressions": { + "title": "JavaScript Regular Expressions Review", + "intro": [ + "Before you're quizzed on Regular Expressions, you should review what you've learned.", + "Open up this page to review concepts like lookaheads, lookbehinds, common regex modifiers and more." + ] + }, + "quiz-javascript-regular-expressions": { + "title": "JavaScript Regular Expressions Quiz", + "intro": [ + "Test your knowledge of JavaScript Regular Expressions with this quiz." + ] + } + } + }, + "introduction-to-dates-in-javascript": { + "title": "Introduction to Dates in JavaScript", + "summary": ["Learn how to work with dates in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with dates in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-dates": { + "title": "Working with Dates", + "intro": [ + "In these lectures, you will learn about the JavaScript date object. You will learn about the methods for working with dates and how to format dates." + ] + }, + "lab-date-conversion": { + "title": "Build a Date Conversion Program", + "intro": [ + "In this lab, you'll build a program to convert a date from one format to another." + ] + }, + "review-javascript-dates": { + "title": "JavaScript Dates Review", + "intro": [ + "Before you're quizzed on working with dates, you should review what you've learned.", + "Open up this page to review the Date() object and common methods." + ] + }, + "quiz-javascript-dates": { + "title": "JavaScript Dates Quiz", + "intro": [ + "Test what you've learned about JavaScript Dates with this quiz." + ] + } + } + }, + "learn-audio-and-video-events-with-javascript": { + "title": "Learn Audio and Video Events with JavaScript", + "summary": ["Learn how to work with audio and video events in JavaScript."], + "intro": [ + "In this interactive course, you will learn how to work with audio and video events in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-audio-and-video": { + "title": "Working with Audio and Video", + "intro": [ + "In these lectures, you will learn how to work with audio and video files using JavaScript. You will learn about the Audio and Video constructors, their methods and properties, audio and video formats, codecs, the HTMLMediaElement API, and much more." + ] + }, + "workshop-music-player": { + "title": "Build a Music Player", + "intro": [ + "In this workshop, you'll code a basic MP3 player using HTML, CSS, and JavaScript.", + "The project covers fundamental concepts such as handling audio playback, managing a playlist, implementing play, pause, next, and previous functionalities and dynamically update your user interface based on the current song." + ] + }, + "lab-drum-machine": { + "title": "Build a Drum Machine", + "intro": [ + "For this lab you will use the audio element to build a drum machine." + ] + }, + "review-javascript-audio-and-video": { + "title": "JavaScript Audio and Video Review", + "intro": [ + "Before you're quizzed on working with audio and video in JavaScript, you should review what you've learned about them.", + "Open up this page to review concepts including the Audio constructor, the HTMLMediaElement API and more." + ] + }, + "quiz-javascript-audio-and-video": { + "title": "JavaScript Audio and Video Quiz", + "intro": [ + "Test what you've learned about JavaScript audio and video with this quiz." + ] + } + } + }, + "introduction-to-maps-and-sets-in-javascript": { + "title": "Introduction to Maps and Sets in JavaScript", + "summary": ["Learn about the Map and Set objects in JavaScript."], + "intro": [ + "In this interactive course, you will learn about the Map and Set objects in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-maps-and-sets": { + "title": "Working with Maps and Sets", + "intro": [ + "In these lectures, you will learn about JavaScript Map and Set. You will also learn how they both differ from WeakSets and WeakMaps." + ] + }, + "workshop-plant-nursery-catalog": { + "title": "Build a Plant Nursery Catalog", + "intro": [ + "In this workshop, you will practice using Maps and Sets by building a plant nursery catalog." + ] + }, + "lab-voting-system": { + "title": "Build a Voting System", + "intro": [ + "In this lab, you'll build a voting system using Maps and Sets.", + "You'll practice how to use the Map object to store key-value pairs and the Set object to store unique values." + ] + }, + "review-javascript-maps-and-sets": { + "title": "JavaScript Maps and Sets Review", + "intro": [ + "Before you're quizzed on JavaScript Maps and Sets, you should review what you've learned about them.", + "Open up this page to review concepts such as the Map and Set objects, as well as WeakSet and WeakMap." + ] + }, + "quiz-javascript-maps-and-sets": { + "title": "JavaScript Maps and Sets Quiz", + "intro": [ + "Test what you've learned about JavaScript Maps and Sets with this quiz." + ] + } + } + }, + "learn-localstorage-and-crud-operations-with-javascript": { + "title": "Learn localStorage and CRUD Operations with JavaScript", + "summary": [ + "Learn how to use localStorage and perform CRUD operations in JavaScript." + ], + "intro": [ + "In this interactive course, you will learn how to use localStorage and perform CRUD operations in JavaScript." + ], + "note": "", + "blocks": { + "lecture-working-with-client-side-storage-and-crud-operations": { + "title": "Working with Client-Side Storage and CRUD Operations", + "intro": [ + "In these lectures, you will learn about client-side storage and CRUD operations in JavaScript. You will learn about localStorage and sessionStorage alongside their methods and properties, cookies, the Cache API, IndexedDB, and much more." + ] + }, + "workshop-todo-app": { + "title": "Build a Todo App using Local Storage", + "intro": [ + "Local storage is a web browser feature that lets web applications store key-value pairs persistently within a user's browser. This allows web apps to save data during one session, then retrieve it in a later page session.", + "In this workshop, you'll learn how to handle form inputs, manage local storage, perform CRUD (Create, Read, Update, Delete) operations on tasks, implement event listeners, and toggle UI elements." + ] + }, + "lab-bookmark-manager-app": { + "title": "Build a Bookmark Manager App", + "intro": [ + "For this lab, you'll build a bookmark manager app.", + "You'll utilize local storage to store bookmarks, and practice how to add, remove, and display bookmarks." + ] + }, + "review-local-storage-and-crud": { + "title": "Local Storage and CRUD Review", + "intro": [ + "Before you are quizzed on working with localStorage, you first need to review the concepts.", + "Open up this page to review the localStorage property, sessionStorage property and more." + ] + }, + "quiz-local-storage-and-crud": { + "title": "Local Storage and CRUD Quiz", + "intro": [ + "Test what you've learned about local storage and CRUD with this quiz." + ] + } + } + }, + "introduction-to-javascript-classes": { + "title": "Introduction to JavaScript Classes", + "summary": ["Learn about classes in JavaScript and how to use them."], + "intro": [ + "In this interactive course, you will learn about classes in JavaScript and how to use them." + ], + "note": "", + "blocks": { + "lecture-understanding-how-to-work-with-classes-in-javascript": { + "title": "Understanding How to Work with Classes in JavaScript", + "intro": [ + "In these lectures, you will learn about classes in JavaScript. You will learn about inheritance, the this keyword, static properties and methods, and more." + ] + }, + "workshop-shopping-cart": { + "title": "Build a Shopping Cart", + "intro": [ + "In this workshop you'll create a shopping cart using JavaScript classes.", + "You will practice how to use the this keyword, create class instances, implement methods for data manipulation and more." + ] + }, + "lab-project-idea-board": { + "title": "Build a Project Idea Board", + "intro": [ + "In this lab, you'll build a project idea board using OOP in JavaScript.", + "You'll practice how to create classes, add methods to classes, and create instances of classes." + ] + }, + "lab-bank-account-manager": { + "title": "Build a Bank Account Management Program", + "intro": [ + "In this lab, you'll build a simple transaction management system for a bank account." + ] + }, + "review-javascript-classes": { + "title": "JavaScript Classes Review", + "intro": [ + "Before you're quizzed on how to work with classes, you should review what you've learned about them.", + "Open up this page to review concepts including the this keyword, class inheritance and more." + ] + }, + "quiz-javascript-classes": { + "title": "JavaScript Classes Quiz", + "intro": [ + "Test what you've learned about JavaScript classes with this quiz." + ] + } + } + }, + "learn-recursion-with-javascript": { + "title": "Learn Recursion with JavaScript", + "summary": [ + "Understand the concept of recursion and how to implement it in JavaScript." + ], + "intro": [ + "In this interactive course, you'll learn about recursion in JavaScript and how to use it to solve problems." + ], + "note": "", + "blocks": { + "lecture-understanding-recursion-and-the-call-stack": { + "title": "Understanding Recursion and the Call Stack", + "intro": [ + "In this lecture, you will learn about recursion and the call stack." + ] + }, + "workshop-countup": { + "title": "Build a Countup", + "intro": [ + "In this workshop you will build a countup function that returns an array of numbers counting up from 1 to a given number." + ] + }, + "lab-countdown": { + "title": "Build a Countdown", + "intro": [ + "For this lab, you will build a countdown function that returns an array of numbers counting down from given number to 1." + ] + }, + "lab-range-of-numbers": { + "title": "Build a Range of Numbers Generator", + "intro": [ + "In this lab, you'll use recursion to generate an array of numbers within a specified range.", + "You'll practice recursive function calls, base cases, and building arrays through recursion." + ] + }, + "workshop-decimal-to-binary-converter": { + "title": "Build a Decimal to Binary Converter", + "intro": [ + "Recursion is a programming concept where a function calls itself. This can reduce a complex problem into simpler sub-problems, until they become straightforward to solve.", + "In this workshop, you'll build a decimal-to-binary converter using JavaScript. You'll practice the fundamental concepts of recursion, explore the call stack, and build out a visual representation of the recursion process through an animation." + ] + }, + "lab-permutation-generator": { + "title": "Build a Permutation Generator", + "intro": [ + "For this lab, you'll build a permutation generator that produces all possible permutations of a given string." + ] + }, + "review-recursion": { + "title": "Recursion Review", + "intro": [ + "Before you're quizzed on recursion, you should review what you've learned.", + "Open up this page to review what is recursion and what is it used for." + ] + }, + "quiz-recursion": { + "title": "Recursion Quiz", + "intro": ["Test your knowledge of Recursion with this quiz."] + } + } + }, + "introduction-to-functional-programming-with-javascript": { + "title": "Introduction to Functional Programming with JavaScript", + "summary": [ + "Learn the fundamentals of functional programming in JavaScript." + ], + "intro": [ + "In this interactive course, you will learn about functional programming concepts and techniques in JavaScript." + ], + "note": "", + "blocks": { + "lecture-understanding-functional-programming": { + "title": "Understanding Functional Programming", + "intro": [ + "In these lectures, you will learn about functional programming and how to nest functions using a technique called currying." + ] + }, + "workshop-recipe-ingredient-converter": { + "title": "Build a Recipe Ingredient Converter", + "intro": [ + "In the previous lectures, you learned the core concepts behind functional programming and currying.", + "Now you will be able to apply what you have learned about currying and functional programming by building a recipe ingredient converter application." + ] + }, + "lab-optional-arguments-sum-function": { + "title": "Build an Optional Arguments Sum Function", + "intro": [ + "In this lab you will build a function that accepts up to two arguments, and sum them, but if there is only one argument returns a function that waits for the second number to sum." + ] + }, + "lab-sorting-visualizer": { + "title": "Build a Sorting Visualizer", + "intro": [ + "For this lab, you'll use JavaScript to visualize the steps that the Bubble Sort algorithm takes to reorder an array of integers." + ] + }, + "review-javascript-functional-programming": { + "title": "JavaScript Functional Programming Review", + "intro": [ + "Before you're quizzed on functional programming, you should review what you've learned.", + "Open up this page to review concepts on functional programming, currying and more." + ] + }, + "quiz-javascript-functional-programming": { + "title": "JavaScript Functional Programming Quiz", + "intro": [ + "Test what you've learned about JavaScript functional programming with this quiz." + ] + } + } + }, + "introduction-to-asynchronous-javascript": { + "title": "Introduction to Asynchronous JavaScript", + "summary": [ + "Learn the fundamentals of asynchronous programming in JavaScript." + ], + "intro": [ + "In this interactive course, you will learn about asynchronous programming concepts and techniques in JavaScript." + ], + "note": "", + "blocks": { + "lecture-understanding-asynchronous-programming": { + "title": "Understanding Asynchronous Programming", + "intro": [ + "In these lectures, you will learn about asynchronous programming in JavaScript. You will learn about the differences between synchronous and asynchronous programming, how the async keyword works, the Fetch API, promises, async/await, the Geolocation API, and much more." + ] + }, + "workshop-fcc-authors-page": { + "title": "Build an fCC Authors Page", + "intro": [ + "One common aspect of web development is learning how to fetch data from an external API, then work with asynchronous JavaScript.", + "In this workshop you will practice how to use the fetch method, dynamically update the DOM to display the fetched data and paginate your data so you can load results in batches." + ] + }, + "lab-fcc-forum-leaderboard": { + "title": "Build an fCC Forum Leaderboard", + "intro": [ + "For this lab you'll practice asynchronous JavaScript by coding your own freeCodeCamp forum leaderboard." + ] + }, + "lab-weather-app": { + "title": "Build a Weather App", + "intro": [ + "In this lab you'll build a Weather App using an API", + "You'll practice how to fetch data from the API, store and display it on your app." + ] + }, + "review-asynchronous-javascript": { + "title": "Asynchronous JavaScript Review", + "intro": [ + "Review asynchronous JavaScript concepts to prepare for the upcoming quiz." + ] + }, + "quiz-asynchronous-javascript": { + "title": "Asynchronous JavaScript Quiz", + "intro": [ + "Test what you've learned about asynchronous JavaScript with this quiz." + ] + } + } + }, + "information-security": { + "title": "Information Security", + "intro": [ + "With everything we do online, there's a vast amount of sensitive information at risk: email addresses, passwords, phone numbers, and much more.", + "With the Information Security Certification, you'll build a secure web app with HelmetJS to learn the fundamentals of protecting people's information online.", + "You'll also build a TCP client, and an Nmap and port scanner in Python. This will help you learn the basics of penetration testing — an important component of good information security." + ], + "note": "", + "blocks": { + "information-security-with-helmetjs": { + "title": "Information Security with HelmetJS", + "intro": [ + "This programming course focuses on HelmetJS, a type of middleware for Express-based applications that automatically sets HTTP headers. This way it can prevent sensitive information from unintentionally being passed between the server and client.", + "Completing the courses below will help you understand how to protect your website from malicious behavior." + ] + }, + "python-for-penetration-testing": { + "title": "Python for Penetration Testing", + "intro": [ + "These video courses teach you penetration testing with Python. Also known as a pen test, penetration testing is a simulated attack against a system to check for vulnerabilities.", + "In this course, you'll learn about sockets, create a TCP server and client, build an Nmap scanner, and other tools and techniques that pen testers use daily." + ] + }, + "information-security-projects": { + "title": "Information Security Projects", + "intro": [ + "Now it’s time to put your new information security skills to work. These projects will give you a chance to apply the infosec skills, principles, and concepts you've learned.", + "When you are done, you will have plenty of information security projects under your belt, along with a certification that you can show off to friends, family, and employers." + ] + } + } + }, + "machine-learning-with-python": { + "title": "Machine Learning with Python", + "intro": [ + "Machine learning has many practical applications that you can use in your projects or on the job.", + "In the Machine Learning with Python Certification, you'll use the TensorFlow framework to build several neural networks and explore more advanced techniques like natural language processing and reinforcement learning.", + "You'll also dive into neural networks, and learn the principles behind how deep, recurrent, and convolutional neural networks work." + ], + "note": "", + "blocks": { + "tensorflow": { + "title": "TensorFlow", + "intro": [ + "TensorFlow is an open source framework that makes machine learning and neural networking easier to use.", + "The following video course was created by Tim Ruscica, also known as “Tech With Tim”. It will help you to understand TensorFlow and some of its powerful capabilities." + ] + }, + "how-neural-networks-work": { + "title": "How Neural Networks Work", + "intro": [ + "Neural networks are at the core of what we call artificial intelligence today. But historically they've been hard to understand. Especially for beginners in the machine learning field.", + "Even if you are completely new to neural networks, these video courses by Brandon Rohrer will get you comfortable with the concepts and the math behind them." + ] + }, + "machine-learning-with-python-projects": { + "title": "Machine Learning with Python Projects", + "intro": [ + "Machine learning has many practical applications. By completing these free and challenging coding projects, you will demonstrate that you have a good foundational knowledge of machine learning, and qualify for your Machine Learning with Python certification." + ] + } + } + }, + "college-algebra-with-python": { + "title": "College Algebra with Python", + "intro": [ + "This course is designed as a one-semester college course. It consists of instructional videos, with Google Colaboratory notebooks to follow along interactively, assignments, and challenging projects.", + "As you go through each part of this course in sequence, you will gain a full understanding of Algebra and how to write Python code to solve Algebra problems.", + "Throughout this course, you will also build your own Algebra Colab notebook that you will be able to use as your custom calculator. This course (and the code you write here) will give you the foundation for a deeper math and data science understanding." + ], + "note": "", + "blocks": { + "learn-ratios-and-proportions": { + "title": "Learn Ratios and Proportions", + "intro": [ + "Your journey begins here as you learn how to set up a Colab Notebook that can run Python code. Then, use the notebook to follow along with the videos to learn ratios and proportions using Python." + ] + }, + "learn-how-to-solve-for-x": { + "title": "Learn How to Solve for X", + "intro": [ + "This unit will focus on how to solve for an unknown number (often referred to as \"x\") using written Algebra and Python code." + ] + }, + "learn-fractions-and-decimals": { + "title": "Learn Fractions and Decimals", + "intro": [ + "This unit will focus on converting decimals to fractions and percents." + ] + }, + "learn-functions-and-graphing": { + "title": "Learn Functions and Graphing", + "intro": ["This unit will teach you about math functions."] + }, + "learn-linear-functions": { + "title": "Learn Linear Functions", + "intro": [ + "This unit will show you how to develop linear equations from two points." + ] + }, + "learn-common-factors-and-square-roots": { + "title": "Learn Common Factors and Square Roots", + "intro": [ + "In this unit, you will learn how to find common factors and divide them out. This will be useful when simplifying fractions and factoring square roots." + ] + }, + "build-a-multi-function-calculator-project": { + "title": "Multi-Function Calculator", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a multi-function calculator." + ] + }, + "learn-how-to-graph-systems-of-equations": { + "title": "Learn How to Graph Systems of Equations", + "intro": [ + "This unit will focus on graphing two equations on the same coordinate plane, so that you can see where the lines intersect." + ] + }, + "learn-how-to-solve-systems-of-equations": { + "title": "Learn How to Solve Systems of Equations", + "intro": [ + "In this unit, you will learn how to solve a system of two equations (with two variables) without graphing. You will see how you can factor an equation and solve for a certain variable in Python. By the end of this unit, you will be able to solve and graph the system with one block of code." + ] + }, + "learn-applications-of-linear-systems": { + "title": "Learn Applications of Linear Systems", + "intro": [ + "In this unit, you will see how you can use the algebra you learned so far to solve real world problems." + ] + }, + "learn-quadratic-equations": { + "title": "Learn Quadratic Equations", + "intro": [ + "This unit will go beyond linear equations, to work with exponents and graph parabolas. You will learn how to find key points in parabolas and how to solve quadratic equations." + ] + }, + "build-a-graphing-calculator-project": { + "title": "Graphing Calculator", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a graphing calculator." + ] + }, + "learn-parent-graphs-and-polynomials": { + "title": "Learn Parent Graphs and Polynomials", + "intro": [ + "This unit will show you many different types of \"parent\" graphs, the basic patterns that make up more complicated graphs. Polynomials are mathematical expressions with \"multiple things\" - the more complicated equations that are built with basic patterns. You will see what these graphs look like, how to modify them, and how to do this all with Python code." + ] + }, + "build-three-math-games-project": { + "title": "Three Math Games", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build three math games." + ] + }, + "learn-business-applications-of-college-algebra": { + "title": "Learn Business Applications of College Algebra", + "intro": [ + "This unit will show you how to apply your solving and graphing skills to find cost, revenue, and profit. You will write code to develop a demand function from two points. You will see how price affects the profit graph and how all of these equations relate to each other." + ] + }, + "learn-simple-and-compound-interest": { + "title": "Learn Simple and Compound Interest", + "intro": [ + "This unit will show you how to calculate interest, loan payments, and the estimated value of investments. You will see the math formula and turn that into code. Because these formulas tend to get complicated, you will appreciate having the code where you can just modify a few values." + ] + }, + "learn-exponents-and-logarithms": { + "title": "Learn Exponents and Logarithms", + "intro": [ + "This unit will show you how exponents and logarithms are inverse functions, and how you can use these functions in various applications." + ] + }, + "build-a-financial-calculator-project": { + "title": "Financial Calculator", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a financial calculator." + ] + }, + "college-algebra-with-python-conclusion": { + "title": "College Algebra with Python: Conclusion", + "intro": [ + "This will be the last unit in this course. Let's look at how you can connect your Math and Python knowledge with external data." + ] + }, + "build-a-data-graph-explorer-project": { + "title": "Data Graph Explorer", + "intro": [ + "This is one of the required projects to earn your certification.", + "For this project, you will build a data graph explorer." + ] + } + } + }, + "python-for-everybody": { + "title": "Legacy Python for Everybody", + "intro": [ + "Python is one of the most popular, flexible programming languages today. You can use it for everything from basic scripting to machine learning." + ], + "note": "", + "blocks": { + "python-for-everybody": { + "title": "Python for Everybody", + "intro": [ + "Python for everybody is a free video course series that teaches the basics of using Python 3.", + "The courses were created by Dr. Charles Severance (also known as Dr. Chuck). He is a Clinical Professor at the University of Michigan School of Information, where he teaches various technology-oriented courses including programming, database design, and web development." + ] + } + } + }, + "coding-interview-prep": { + "title": "Coding Interview Prep", + "intro": [ + "If you're looking for free coding exercises to prepare for your next job interview, we've got you covered.", + "This section contains dozens of coding challenges that test your knowledge of algorithms, data structures, and mathematics. It also has a number of take-home projects you can use to strengthen your skills, or add to your portfolio.", + "This work incorporates material from Wikipedia, which is licensed under the Creative Commons Attribution-ShareAlike License 4.0. The original content might have been modified and adapted. For the unaltered version and additional details, see the original page on Wikipedia." + ], + "blocks": { + "algorithms": { + "title": "Algorithms", + "intro": [ + "These free programming exercises will teach you about some common algorithms that you will likely encounter in real life. They are a great opportunity to improve your logic and programming skills.", + "These algorithms are frequently used in job interviews to test a candidate's skills. We'll give you clear and concise explanations of how these different algorithms work so you can implement a solution for each one.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "data-structures": { + "title": "Data Structures", + "intro": [ + "These free programming courses are meant to help you deal with large and complex data structures that you may not yet be familiar with.", + "Working through the courses below, you will learn about each type of data structure, and implement algorithms to reinforce your understanding of them.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "take-home-projects": { + "title": "Take Home Projects", + "intro": [ + "Programming interviews have always been stressful. Job applicants are sometimes given a take home project to be completed outside of the interview. These types of interviews usually require a lot of work, but they're a great way for employers to see how you might perform on the job.", + "Build the bonus coding projects below for extra practice. Take your time, make them great, and put them on your resume or portfolio to show potential employers." + ] + } + } + }, + "the-odin-project": { + "title": "The Odin Project - freeCodeCamp Remix", + "intro": [ + "The Odin Project was created in 2013 by a lone developer, Erik Trautman. Over the years, an open source community has sprung up to maintain and expand the project.", + "freeCodeCamp has expanded upon the open source curriculum to make it run interactively in the browser, with tests to evaluate your code and ensure you've understood key concepts.", + "If you want the original experience of configuring all of The Odin Project to run on your local computer, you can check out the original Odin Project on The Odin Project website. A huge thanks to The Odin Project community for continuing to maintain this valuable learning resource for developers all around the world.", + "This course is unofficial, and not endorsed by The Odin Project. Changes to The Odin Project curriculum content have been made, and all instructional material for this course is licensed under CC-BY-SA-NC 4.0", + "© The Odin Project", + "This course includes content from JavaScript.info, which is licensed under CC-BY-NC-SA 4.0." + ], + "blocks": { + "top-learn-html-foundations": { + "title": "Learn HTML Foundations", + "intro": [ + "Get a solid grasp of HTML essentials with this course. From structuring web pages to understanding semantic tags, you'll build a strong foundation for creating well-organized and accessible content on the web." + ] + }, + "top-working-with-text": { + "title": "Working with Text", + "intro": [ + "Explore the intricacies of working with text in web development. Learn about text formatting, manipulation, and presentation to enhance your skills in creating web content." + ] + }, + "top-links-and-images": { + "title": "Links and Images", + "intro": [ + "Learn how to incorporate links and images into your web projects. This course covers the fundamentals of creating links and embedding images to make your websites more interactive and visually appealing." + ] + }, + "top-build-a-recipe-project": { + "title": "Learn HTML Foundations by Building a Recipe Page", + "intro": [ + "Put your HTML skills into practice by building a recipe page. This hands-on project allows you to apply your knowledge and create a functional web page while reinforcing key concepts of HTML development." + ] + }, + "top-learn-css-foundations": { + "title": "Learn CSS Foundations", + "intro": [ + "Dive into the world of Cascading Style Sheets (CSS) and learn how to style your HTML elements. Explore styling properties, selectors, and layouts to bring your web pages to life." + ] + }, + "top-learn-css-foundations-projects": { + "title": "Learn CSS Foundations Projects", + "intro": [ + "Take your CSS skills to the next level by working on practical projects. This course provides hands-on experience in applying CSS to create responsive designs for real-world scenarios." + ] + }, + "top-learn-css-specificity": { + "title": "Learn CSS Specificity", + "intro": [ + "Learn CSS specificity and gain a better understanding of how styles are applied to HTML elements. This course explores the nuances of CSS rules and helps you write efficient and targeted styles for your web pages." + ] + }, + "top-the-box-model": { + "title": "Learn the Box Model", + "intro": [ + "Learn the CSS box model with this course. Understand how elements are rendered on the web, and learn to manipulate spacing, borders, and padding to achieve your desired layout and design." + ] + }, + "top-learn-block-and-inline": { + "title": "Learn the difference between Block and Inline", + "intro": [ + "Explore the distinctions between block and inline elements in HTML and CSS. This course provides insights into how these display types affect layout and behavior, empowering you to make informed design decisions." + ] + }, + "top-introduction-to-flexbox": { + "title": "Introduction to Flexbox", + "intro": [ + "Discover the power of Flexbox, a layout model that simplifies the design of flexible and responsive web layouts. Learn how to create dynamic and adaptive page structures with ease." + ] + }, + "top-learn-variables-and-operators": { + "title": "Learn Variables and Operators", + "intro": [ + "Get started with JavaScript by learning about variables and operators. This course covers the fundamentals of JavaScript programming, including data types, operators, and variable declarations." + ] + }, + "top-learn-data-types-and-conditionals": { + "title": "Learn Data Types and Conditionals", + "intro": ["Learn about data types and conditionals in JavaScript."] + }, + "top-learn-function-basics": { + "title": "Learn Function Basics", + "intro": ["Learn about functions in JavaScript."] + }, + "top-basic-function-projects": { + "title": "Basic Function Projects", + "intro": [ + "Put your JavaScript skills to the test by building basic functions." + ] + }, + "top-learn-arrays-and-loops": { + "title": "Learn Arrays and Loops", + "intro": ["Learn about arrays and loops in JavaScript."] + }, + "top-learn-to-solve-problems-and-understand-errors": { + "title": "Learn to Solve Problems and Understand Errors", + "intro": [ + "Learn how to solve problems and understand errors in JavaScript." + ] + }, + "top-build-a-rock-paper-scissors-game": { + "title": "Build a Rock Paper Scissors Game", + "intro": [ + "Put your JavaScript skills to the test by building a Rock Paper Scissors game." + ] + } + } + }, + "project-euler": { + "title": "Project Euler", + "intro": [ + "Complete the programming challenges below, from the massive Project Euler archives. These will harden your algorithm and mathematics knowledge.", + "These problems range in difficulty and, for many, the experience is inductive chain learning. That is, by solving one problem, it will expose you to a new concept that allows you to undertake a previously inaccessible problem. Can you finish them all?" + ], + "blocks": { + "project-euler-problems-1-to-100": { + "title": "Project Euler Problems 1 to 100", + "intro": [ + "In this first set of challenges, you will use mathematical concepts like the Fibonacci sequence, prime number theory, and combinatorics to write efficient algorithms to solve these problems.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "project-euler-problems-101-to-200": { + "title": "Project Euler Problems 101 to 200", + "intro": [ + "In this set of challenges, you'll build upon the skills you learned in the first part of the course and use more advanced concepts like vector computation, Pascal's pyramid, and the RSA algorithm to solve these problems efficiently.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "project-euler-problems-201-to-300": { + "title": "Project Euler Problems 201 to 300", + "intro": [ + "In this set of challenges, you'll continue to build upon the skills you learned earlier and use concepts like the binomial theorem, Hamming numbers, and the Collatz sequence to further develop your math and problem solving skills.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "project-euler-problems-301-to-400": { + "title": "Project Euler Problems 301 to 400", + "intro": [ + "Here you will continue to flex your mathematical and algorithmic skills as you use concepts such as combinatorial game theory, bitwise operations, and Golomb's self-describing sequence to develop efficient solutions to these problems.", + "NOTE: These challenges support JavaScript only solutions." + ] + }, + "project-euler-problems-401-to-480": { + "title": "Project Euler Problems 401 to 480", + "intro": [ + "In this final set of challenges, you will need draw upon everything you learned up to this point and use advanced concepts like unitary divisors, the Kaprekar routine, and much more to solve these complex problems.", + "NOTE: These challenges support JavaScript only solutions." + ] + } + } + }, + "foundational-c-sharp-with-microsoft": { + "title": "Free Foundational C# with Microsoft Certification", + "intro": [ + "This course offers a comprehensive introduction to C# programming, covering its core concepts, syntax, and practical application in software development.", + "Through hands-on exercises and projects, you will learn the fundamentals of C#, including variables, data types, control structures, and object-oriented programming principles.", + "By the end of this course, you will have gained the practical skills and knowledge needed to confidently leverage C# for building applications." + ], + "note": "Each section below has a trophy associated with it that you must earn on the Microsoft Learn platform. After earning each trophy, you need to verify them on freeCodeCamp. Once you have done those, you can qualify for the certification exam.", + "blocks": { + "write-your-first-code-using-c-sharp": { + "title": "Write Your First Code Using C#", + "intro": [ + "Begin your journey by learning to write your first code using C#. Develop a strong foundation as you explore the fundamentals and syntax of the language, setting the stage for your programming adventures." + ] + }, + "create-and-run-simple-c-sharp-console-applications": { + "title": "Create and Run Simple C# Console Applications", + "intro": [ + "Master the art of creating and running simple C# console applications. Dive into the world of console-based programming, where you will gain hands-on experience executing your code and seeing it in action." + ] + }, + "add-logic-to-c-sharp-console-applications": { + "title": "Add Logic to C# Console Applications", + "intro": [ + "Unlock the power of logic in C# console applications. Learn how to add logic and decision-making capabilities to your code, enabling your applications to make dynamic choices and respond intelligently to different scenarios." + ] + }, + "work-with-variable-data-in-c-sharp-console-applications": { + "title": "Work with Variable Data in C# Console Applications", + "intro": [ + "Discover the versatility of variable data in C# console applications. Harness the ability to store and manipulate different types of data, such as numbers and text, as you delve into the essential concepts of variables and data handling." + ] + }, + "create-methods-in-c-sharp-console-applications": { + "title": "Create Methods in C# Console Applications", + "intro": [ + "Take your C# console applications to the next level by mastering the art of creating methods. Learn how to organize and modularize your code, making it more manageable, reusable, and efficient." + ] + }, + "debug-c-sharp-console-applications": { + "title": "Debug C# Console Applications", + "intro": [ + "Sharpen your troubleshooting skills as you dive into the world of debugging C# console applications. Gain the ability to identify and fix issues in your code, ensuring your applications run smoothly and deliver the desired results." + ] + }, + "foundational-c-sharp-with-microsoft-certification-exam": { + "title": "Foundational C# with Microsoft Certification Exam", + "intro": [ + "Use what you've learned to pass the exam to earn your Foundational C# with Microsoft Certification" + ] + } + } + }, + "a2-english-for-developers": { + "title": "A2 English for Developers Certification (Beta)", + "intro": [ + "In this English for Developers Curriculum, you'll learn the essentials of English communication. This will follow the A2 level of the Common European Framework of Reference (CEFR). And we've focused on vocabulary that is particularly useful for developers.", + "The first half of the curriculum will help you get comfortable with English grammar and usage. It will give you tons of hands-on practice. You'll learn basics like introducing yourself, making small talk, and discussing your work.", + "In the second half, you'll practice vocabulary specific to software development. You'll learn how to describe code, discuss tech trends, and participate in stand-up meetings.", + "This entire A2-level curriculum includes 105 different dialogues. Each is designed to build your vocabulary and boost your confidence when speaking in a professional tech setting." + ], + "note": "This certification is currently in beta.", + "blocks": { + "learn-greetings-in-your-first-day-at-the-office": { + "title": "Learn Greetings in your First Day at the Office", + "intro": [ + "In this first course, you'll learn common expressions for situations you may encounter on your first day at work. You'll learn about introductions, getting to know people, asking for lunch recommendations, and getting an access card from security." + ] + }, + "en-a2-quiz-first-day-conversations-at-work": { + "title": "First Day Conversations at Work Quiz", + "intro": ["", ""] + }, + "learn-introductions-in-an-online-team-meeting": { + "title": "Learn Introductions in an Online Team Meeting", + "intro": [ + "In this course, you'll learn how to give a personal introduction. You'll also learn how to state your profession, and share your goals in group meetings." + ] + }, + "en-a2-quiz-meeting-introductions-at-work": { + "title": "Meeting Introductions at Work Quiz", + "intro": ["", ""] + }, + "learn-conversation-starters-in-the-break-room": { + "title": "Learn Conversation Starters in the Break Room", + "intro": [ + "In this course, you'll learn how to start a conversation in casual settings. You'll also learn how to talk about your hobbies and personality traits. You'll even learn how to ask about places around the town." + ] + }, + "en-a2-quiz-conversation-starters-at-work": { + "title": "Break Room Conversations Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-a-typical-workday-and-tasks": { + "title": "Learn How to Talk About a Typical Workday and Tasks", + "intro": [ + "In this course, you'll learn how to talk about your workday and the tasks that you perform in the workplace and how to share them with others. It mainly focuses on the structures used for describing your activities and task-related vocabulary." + ] + }, + "en-a2-quiz-work-routines-and-tasks": { + "title": "Talking About Your Workday Quiz", + "intro": ["", ""] + }, + "learn-how-to-discuss-your-morning-or-evening-routine": { + "title": "Learn How to Discuss Your Morning or Evening Routine", + "intro": [ + "In this course, you'll learn how to talk about details of your routine and share them with someone else. It mainly focuses on the structures used for declaring routine actions and related vocabulary." + ] + }, + "en-a2-quiz-daily-life-routines": { + "title": "Daily Routines at Work Quiz", + "intro": ["", ""] + }, + "learn-how-to-describe-your-current-project": { + "title": "Learn How to Describe Your Current Project", + "intro": [ + "In this course, you'll learn how to talk about the projects that you are involved in and how to inform others of what you are doing in these projects. It mainly focuses on the structures used for informing it and on the related vocabulary." + ] + }, + "en-a2-quiz-what-are-you-working-on": { + "title": "Describing Your Current Project Quiz", + "intro": ["", ""] + }, + "learn-how-to-ask-and-share-about-educational-and-professional-background": { + "title": "Learn How to Ask and Share About Educational and Professional Background", + "intro": [ + "In this course, you'll learn how to ask about another person's educational and professional backgrounds and you'll learn how to share information about your background as well." + ] + }, + "en-a2-quiz-educational-and-professional-background": { + "title": "Educational and Professional Background Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-hobbies-and-interests": { + "title": "Learn How to Talk About Hobbies and Interests", + "intro": [ + "In this course, you'll learn different ways to talk about hobbies and things that interest you. You'll also learn how to ask about other people's hobbies and how to invite them to join you in these activities." + ] + }, + "en-a2-quiz-hobbies-and-interests": { + "title": "Talking About Hobbies and Interests Quiz", + "intro": ["", ""] + }, + "learn-how-to-discuss-roles-and-responsibilities": { + "title": "Learn How to Discuss Roles and Responsibilities", + "intro": [ + "In this course, you'll discuss people's roles and responsibilities in a company and out of it. You'll discover how to ask about these roles and responsibilities and how to share information about you related to the topic." + ] + }, + "en-a2-quiz-discuss-roles-responsibilities": { + "title": "Roles and Responsibilities Quiz", + "intro": ["", ""] + }, + "learn-how-to-have-a-conversation-about-preferences-and-motivations": { + "title": "Learn How to Have a Conversation About Preferences and Motivations", + "intro": [ + "In this course, you'll learn how to ask about what motivates people in their personal and professional lives, answer questions related to your motivations, and discuss about people's preferences." + ] + }, + "en-a2-quiz-preferences-and-motivations": { + "title": "Preferences and Motivations Quiz", + "intro": ["", ""] + }, + "learn-how-to-discuss-popular-trends-in-technology": { + "title": "Learn How to Discuss Popular Trends in Technology", + "intro": [ + "In this course, you'll learn how to discuss about things that everybody's talking about in technology these days." + ] + }, + "en-a2-quiz-sharing-opinions": { + "title": "Technology Trends Quiz", + "intro": ["", ""] + }, + "learn-how-to-clarify-information-in-different-interactions": { + "title": "Learn How to Clarify Information in Different Interactions", + "intro": [ + "In this course, you'll learn how to check to see if the information you had is correct and how to ask for clarification when something is not clear to you." + ] + }, + "en-a2-quiz-getting-the-details-right": { + "title": "Clarifying Information Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-basic-programming-vocabulary-in-conversations": { + "title": "Learn How to Use Basic Programming Vocabulary in Conversations", + "intro": [ + "This course will present basic vocabulary related to programming. You'll learn how to ask questions related to basic programming concepts." + ] + }, + "en-a2-quiz-basic-programming-vocabulary": { + "title": "Basic Programming Vocabulary Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-code-related-concepts-and-terms": { + "title": "Learn How to Use Code-related Concepts and Terms", + "intro": [ + "In this course, you will be introduced to terms related to coding and learn how to use them in conversation." + ] + }, + "en-a2-quiz-key-programming-terms": { + "title": "Code Concepts and Terms Quiz", + "intro": ["", ""] + }, + "learn-how-to-discuss-tech-trends-and-updates": { + "title": "Learn How to Discuss Tech Trends and Updates", + "intro": [ + "In this course, you will be introduced to some recent trends in the world of technology and learn how to discuss them in English." + ] + }, + "en-a2-quiz-discussing-new-ideas": { + "title": "Tech Updates and Trends Quiz", + "intro": ["", ""] + }, + "learn-how-to-help-a-coworker-troubleshoot-on-github": { + "title": "Learn How to Help a Coworker Troubleshoot on GitHub", + "intro": [ + "In this course, you will learn expression related to how to ask for help from a coworker as well as how to offer them some assistance." + ] + }, + "en-a2-quiz-discussing-problems-and-solutions": { + "title": "Helping a Coworker on GitHub Quiz", + "intro": ["", ""] + }, + "learn-how-to-share-your-progress-in-weekly-stand-up-meetings": { + "title": "Learn How to Share Your Progress in Weekly Stand-up Meetings", + "intro": [ + "This course will show you how to talk about your projects in terms of what you have already done and what you are currently doing in them." + ] + }, + "en-a2-quiz-collaborating-in-meetings": { + "title": "Weekly Meeting Progress Quiz", + "intro": ["", ""] + }, + "learn-how-to-ask-for-clarification-on-code-understanding": { + "title": "Learn How to Ask for Clarification on Code Understanding", + "intro": [ + "In this course, you will see how you can ask questions to clarify things which are not very clear to you in a code." + ] + }, + "en-a2-quiz-understanding-problems": { + "title": "Asking for Code Clarification Quiz", + "intro": ["", ""] + }, + "learn-how-to-document-code-for-a-project": { + "title": "Learn How to Document Code for a Project", + "intro": [ + "This course will show you expressions related to what to do when documenting code." + ] + }, + "en-a2-quiz-document-code-project": { + "title": "Documenting Code Quiz", + "intro": ["", ""] + }, + "learn-how-to-read-and-understand-code-documentation": { + "title": "Learn How to Read and Understand Code Documentation", + "intro": [ + "This course will present more expressions related to code documentation and bring tips on how to understand it." + ] + }, + "en-a2-quiz-read-understand-code-documentation": { + "title": "Understanding Code Documentation Quiz", + "intro": ["", ""] + }, + "learn-how-to-analyze-code-documentation": { + "title": "Learn How to Analyze Code Documentation", + "intro": [ + "In this course, you will see some ideas to help you to approach documentation and analyze it in simple terms." + ] + }, + "en-a2-quiz-analyzing-documentation": { + "title": "Analyzing Code Documentation Quiz", + "intro": ["", ""] + }, + "learn-how-to-share-progress-and-accomplishments": { + "title": "Learn How to Share Progress and Accomplishments", + "intro": [ + "In this course, you will learn how to share your progress with coworkers and tell about what successes you've had in your projects." + ] + }, + "en-a2-quiz-discussing-progress-and-results": { + "title": "Sharing Progress and Achievements Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-updates-and-plans-for-tasks-and-projects": { + "title": "Learn How to Talk about Updates and Plans for Tasks and Projects", + "intro": [ + "This course will show you how to speak about the most recent advancements in your projects and about your plans." + ] + }, + "en-a2-quiz-task-project-updates-plans": { + "title": "Task and Project Updates Quiz", + "intro": ["", ""] + }, + "learn-how-to-express-agreement-or-disagreement": { + "title": "Learn How to Express Agreement or Disagreement", + "intro": [ + "This course will introduce how to say that you agree with what another person says and to tell them politely that you do not agree with them." + ] + }, + "en-a2-quiz-express-agreement-disagreement": { + "title": "Expressing Agreement and Disagreement Quiz", + "intro": ["", ""] + }, + "learn-how-to-offer-technical-support-and-guidance": { + "title": "Learn How to Offer Technical Support and Guidance", + "intro": [ + "In this course, you will see ways of offering some help in terms of technical specifics to another person." + ] + }, + "en-a2-quiz-following-best-practices": { + "title": "Offering Technical Support Quiz", + "intro": ["", ""] + }, + "learn-how-to-request-and-receive-guidance": { + "title": "Learn How to Request and Receive Guidance", + "intro": [ + "This course will show you how to ask for assistance from a coworker when you need it." + ] + }, + "en-a2-quiz-asking-for-help": { + "title": "Requesting and Receiving Guidance Quiz", + "intro": ["", ""] + }, + "learn-how-to-provide-explanations-when-helping-others": { + "title": "Learn How to Provide Explanations When Helping Others", + "intro": [ + "This course will provide you with ways to explain things to other people while assisting them." + ] + }, + "en-a2-quiz-giving-adivice-and-suggestions": { + "title": "Explaining Things to Others Quiz", + "intro": ["", ""] + }, + "en-a2-certification-exam": { + "title": "A2 English for Developers Certification Exam", + "intro": [ + "This exam is required to claim the A2 English for Developers Certification." + ] + } + } + }, + "b1-english-for-developers": { + "title": "B1 English for Developers Certification (Beta)", + "intro": [ + "In this English for Developers Curriculum, you'll learn the essentials of English communication. This will follow the B1 level of the Common European Framework of Reference (CEFR). And we've focused on vocabulary that is particularly useful for developers.", + "It will help you strengthen your foundational skills while introducing more complex grammar and usage. You'll learn how to describe places and things, share past experiences, and confidently use tenses like Present Perfect and Future. Practical communication strategies are included as well, such as managing conversations, expressing opinions, and building agreement or disagreement in discussions.", + "You'll also focus on applying these skills in professional and technical settings. You'll practice vocabulary and phrases essential for developers, such as describing code, participating in stand-up meetings, and discussing tech trends. Advanced topics include conditionals, comparative structures, and conversation management, so you can prepare for real-world interactions in the tech industry.", + "This entire B1-level curriculum includes 73 different dialogues. Each is designed to build your vocabulary and boost your confidence when speaking in a professional tech setting." + ], + "note": "This certification is currently in beta.", + "blocks": { + "learn-how-to-describe-places-and-events": { + "title": "Learn How to Describe Places and Events", + "intro": [ + "This course will show you ways of talking about places and events conversationally." + ] + }, + "en-b1-quiz-describe-places-events": { + "title": "Describing Places and Events Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-past-experiences": { + "title": "Learn How to Talk About Past Experiences", + "intro": [ + "In this course, you will learn how to share experiences that you had in the past." + ] + }, + "en-b1-quiz-past-experiences": { + "title": "Talking About Past Experiences Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-past-activities": { + "title": "Learn How to Talk About Past Activities", + "intro": [ + "In this course, you will learn how talk about things that you did." + ] + }, + "en-b1-quiz-past-activities": { + "title": "Talking About Past Activities Quiz", + "intro": ["", ""] + }, + "learn-present-perfect-while-talking-about-accessibility": { + "title": "Learn Present Perfect while Talking About Accessibility", + "intro": [ + "In this course, you will learn to use the Present Perfect structure and learn a bit more about accessibility." + ] + }, + "en-b1-quiz-present-perfect-accessibility": { + "title": "Present Perfect and Accessibility Quiz", + "intro": ["", ""] + }, + "learn-how-to-plan-future-events": { + "title": "Learn How to Plan Future Events", + "intro": [ + "In this course, you will learn to use the different forms of the future to plan for upcoming events." + ] + }, + "en-b1-quiz-plan-future-events": { + "title": "Planning Future Events Quiz", + "intro": ["", ""] + }, + "learn-future-continuous-while-describing-actions": { + "title": "Learn Future Continuous while Describing Actions", + "intro": [ + "In this course, you will learn to use the Future Continuous tense, and how to describe actions to be performed." + ] + }, + "en-b1-quiz-future-continuous-actions": { + "title": "Future Continuous Actions Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-conditionals": { + "title": "Learn How to Use Conditionals", + "intro": [ + "In this course, you will learn to use the conditional sentences to describe hypothetical outcomes depending on the fact that certain conditions are met." + ] + }, + "en-b1-quiz-conditionals": { + "title": "Using Conditionals Quiz", + "intro": ["", ""] + }, + "learn-how-to-share-feedback": { + "title": "Learn How to Share Feedback", + "intro": [ + "In this course, you will see ways of telling other people how you feel about their work, highlighting both their strengths and points for improvement." + ] + }, + "en-b1-quiz-share-feedback": { + "title": "Sharing Feedback Quiz", + "intro": ["", ""] + }, + "learn-how-to-share-your-opinion": { + "title": "Learn How to Share Your Opinion", + "intro": [ + "This course will show you how to express your ideas and feeling towards topics in a discussion." + ] + }, + "en-b1-quiz-share-opinions": { + "title": "Sharing Opinions Quiz", + "intro": ["", ""] + }, + "learn-how-to-express-agreement": { + "title": "Learn How to Express Agreement", + "intro": [ + "In this course, you will learn to express agreement in different professional settings." + ] + }, + "en-b1-quiz-express-agreement": { + "title": "Expressing Agreement Quiz", + "intro": ["", ""] + }, + "learn-how-to-express-disagreement": { + "title": "Learn How to Express Disagreement", + "intro": [ + "In this course, you will learn to express disagreement in different professional settings." + ] + }, + "en-b1-quiz-express-disagreement": { + "title": "Expressing Disagreement Quiz", + "intro": ["", ""] + }, + "learn-how-to-express-concerns": { + "title": "Learn How to Express Concerns", + "intro": [ + "In this course, you will learn to inform other people that you are worried about things that might happen to your projects and tasks." + ] + }, + "en-b1-quiz-express-concerns": { + "title": "Expressing Concerns Quiz", + "intro": ["", ""] + }, + "learn-how-to-express-decisions-based-on-comparisons": { + "title": "Learn How to Express Decisions Based on Comparisons", + "intro": [ + "In this course, you will learn how to compare things like tools or companies using words like better, faster, and the best. You will also practice having friendly conversations to give opinions and make decisions" + ] + }, + "en-b1-quiz-decisions-comparisons": { + "title": "Making Decisions with Comparisons Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-modal-verbs": { + "title": "Learn How to Use Modal Verbs", + "intro": [ + "In this course, you will learn how to talk about rules, describe things that are necessary, and what could happen if they aren't. You'll also practice asking and answering questions clearly, and adding helpful details to your ideas." + ] + }, + "en-b1-quiz-modal-verbs": { + "title": "Using Modal Verbs Quiz", + "intro": ["", ""] + }, + "learn-how-to-manage-a-conversation": { + "title": "Learn How to Manage a Conversation", + "intro": [ + "In this course, you will learn how to manage conversations at work — like how to continue a talk after a break, change topics politely, or interrupt when needed. You'll also practice using useful expressions to keep the conversation clear, friendly, and organized." + ] + }, + "en-b1-quiz-manage-conversations": { + "title": "Managing Conversations Quiz", + "intro": ["", ""] + }, + "learn-how-to-clarify-misunderstandings": { + "title": "Learn How to Clarify Misunderstandings", + "intro": [ + "In this course, you will learn how to ask for and give explanations when something is not clear, using polite questions and helpful responses. You'll also practice guessing the meaning of new words, describing problems, and clearing up misunderstandings in a friendly and professional way." + ] + }, + "en-b1-quiz-clarify-misunderstandings": { + "title": "Clarifying Misunderstandings Quiz", + "intro": ["", ""] + }, + "learn-about-speculation-and-requests": { + "title": "Learn About Speculation and Requests", + "intro": [ + "In this course, you will learn how to talk about things that should or could have happened in the past, and how to give suggestions or make polite requests. You'll also practice using expressions to guess what might have caused a problem and how to work together to solve it in a clear and respectful way." + ] + }, + "en-b1-quiz-speculation-requests": { + "title": "Speculation and Requests Quiz", + "intro": ["", ""] + }, + "learn-about-adverbial-phrases": { + "title": "Learn About Adverbial Phrases", + "intro": [ + "In this course, you will learn how to use phrases that give more information about when, where, how often, or how much something happens. You'll also practice using these phrases to describe tasks, talk about plans, and explain results more clearly in your daily work." + ] + }, + "en-b1-quiz-adverbial-phrases": { + "title": "Adverbial Phrases Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-adjectives-in-conversations": { + "title": "Learn How to Use Adjectives in Conversations", + "intro": [ + "In this course, you will learn how to use adjectives to describe things clearly, compare options, and highlight important details in professional conversations. You'll also practice how to make your ideas stronger and more persuasive." + ] + }, + "en-b1-quiz-adjectives-conversations": { + "title": "Using Adjectives in Conversations Quiz", + "intro": ["", ""] + }, + "learn-determiners-and-advanced-use-of-articles": { + "title": "Learn Determiners and Advanced Use of Articles", + "intro": [ + "In this course, you will learn how to use determiners to give clear information about quantity, choice, and distribution. You will also practice using articles in more advanced ways, especially in professional conversations about planning, tasks, and resources." + ] + }, + "en-b1-quiz-determiners-articles": { + "title": "Determiners and Articles Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-reported-speech": { + "title": "Learn How to Use Reported Speech", + "intro": [ + "In this course, you will learn how to report what someone else said in a clear and natural way. You will also practice using the correct verb tenses and sentence structures to share feedback, explain situations, and talk about past events in professional conversations." + ] + }, + "en-b1-quiz-reported-speech": { + "title": "Using Reported Speech Quiz", + "intro": ["", ""] + }, + "learn-how-to-use-prepositions-according-to-context": { + "title": "Learn How to Use Prepositions According to Context", + "intro": [ + "In this course, you will learn how to use prepositions to describe time, place, and direction clearly in everyday work situations. You will also practice talking about schedules, giving directions, and explaining where people or things are located using natural and accurate language." + ] + }, + "en-b1-quiz-prepositions-context": { + "title": "Using Prepositions by Context Quiz", + "intro": ["", ""] + }, + "learn-how-to-talk-about-numbers-with-a-coworker": { + "title": "Learn How to Talk About Numbers with a Coworker", + "intro": [ + "In this course, you will learn how to use numbers to talk about tasks, schedules, budgets, and resources in the workplace. You will practice using cardinal and ordinal numbers, percentages, and fractions to organize work, explain progress, and share inventory or financial updates clearly with your team." + ] + }, + "en-b1-quiz-numbers-at-work": { + "title": "Talking About Numbers at Work Quiz", + "intro": ["", ""] + }, + "learn-common-phrasal-verbs-and-idioms": { + "title": "Learn Common Phrasal Verbs and Idioms", + "intro": [ + "In this course, you will learn how to use common phrasal verbs and idioms to sound more natural and confident at work. You will practice using expressions to give opinions, make suggestions, organize meetings, and talk about tasks in everyday professional conversations." + ] + }, + "en-b1-quiz-phrasal-verbs-idioms": { + "title": "Phrasal Verbs and Idioms Quiz", + "intro": ["", ""] + }, + "en-b1-certification-exam": { + "title": "B1 English for Developers Certification Exam", + "intro": [ + "This exam is required to claim the B1 English for Developers Certification." + ] + } + } + }, + "rosetta-code": { + "title": "Rosetta Code", + "intro": [ + "Level up your creative problem solving skills with these free programming tasks from the classic Rosetta Code library.", + "These challenges can prove to be difficult, but they will push your algorithm logic to new heights.", + "Attribute: Rosetta Code" + ], + "blocks": { + "rosetta-code-challenges": { + "title": "Rosetta Code Challenges", + "intro": [ + "These are the challenges for Rosetta Code.", + "NOTE: These challenges support JavaScript only solutions." + ] + } + } + }, + "javascript-v9": { + "title": "JavaScript Certification", + "intro": [ + "This course teaches you core JavaScript programming concepts such as working with variables, functions, objects, arrays, and control flow. You'll also learn how to manipulate the DOM, handle events, and apply techniques like asynchronous programming, functional programming, and accessibility best practices.", + "To earn your JavaScript Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the JavaScript Certification exam." + ], + "chapters": { + "javascript": "JavaScript", + "javascript-certification-exam": "JavaScript Certification Exam" + }, + "modules": { + "javascript-variables-and-strings": "Variables and Strings", + "javascript-booleans-and-numbers": "Booleans and Numbers", + "javascript-functions": "Functions", + "javascript-arrays": "Arrays", + "javascript-objects": "Objects", + "javascript-loops": "Loops", + "review-javascript-fundamentals": "JavaScript Fundamentals Review", + "higher-order-functions-and-callbacks": "Higher Order Functions and Callbacks", + "dom-manipulation-and-events": "DOM Manipulation and Events", + "js-a11y": "JavaScript and Accessibility", + "debugging-javascript": "Debugging", + "basic-regex": "Basic Regex", + "lab-markdown-to-html-converter": "Build a Markdown to HTML Converter", + "form-validation": "Form Validation", + "javascript-dates": "Dates", + "audio-and-video-events": "Audio and Video Events", + "lab-drum-machine": "Build a Drum Machine", + "maps-and-sets": "Maps and Sets", + "lab-voting-system": "Build a Voting System", + "localstorage-and-crud-operations": "localStorage and CRUD Operations", + "classes-and-the-this-keyword": "Classes", + "lab-bank-account-manager": "Build a Bank Account Management Program", + "recursion": "Recursion", + "data-structures": "Data Structures", + "algorithms": "Algorithms", + "graphs-and-trees": "Graphs and Trees", + "dynamic-programming": "Dynamic Programming", + "functional-programming": "Functional Programming", + "asynchronous-javascript": "Asynchronous JavaScript", + "lab-weather-app": "Build a Weather App", + "review-javascript": "JavaScript Review", + "javascript-certification-exam": "JavaScript Certification Exam" + }, + "blocks": { + "lecture-introduction-to-javascript": { + "title": "Introduction to JavaScript", + "intro": [ + "In these lectures, you will learn the fundamentals of JavaScript. Topics covered include, but are not limited to, variables, data types, how JavaScript interacts with HTML and CSS, strings, and much more." + ] + }, + "lecture-introduction-to-strings": { + "title": "Introduction to Strings", + "intro": [ + "In these lessons, you will learn how to work with strings and string concatenation." + ] + }, + "lecture-understanding-code-clarity": { + "title": "Understanding Code Clarity", + "intro": [ + "In these lessons, you will learn about comments in JavaScript and the role of semicolons in programming." + ] + }, + "workshop-greeting-bot": { + "title": "Build a Greeting Bot", + "intro": [ + "In this workshop, you will learn JavaScript fundamentals by building a greeting bot.", + "You will learn about variables, let, const, console.log and basic string usage." + ] + }, + "lab-javascript-trivia-bot": { + "title": "Build a JavaScript Trivia Bot", + "intro": [ + "In this lab, you'll practice working with JavaScript variables and strings by building a trivia bot." + ] + }, + "lab-sentence-maker": { + "title": "Build a Sentence Maker", + "intro": [ + "In this lab, you will continue practicing with strings and concatenation by creating and customizing various stories." + ] + }, + "lecture-working-with-data-types": { + "title": "Working with Data Types", + "intro": [ + "In the following lectures, you will learn how to work with data types in JavaScript. You will also learn how dynamic typing differs from static typing, the typeof operator, and the typeof null bug." + ] + }, + "review-javascript-variables-and-data-types": { + "title": "JavaScript Variables and Data Types Review", + "intro": [ + "Before you are quizzed on JavaScript variables and data types you first need to review the concepts.", + "Open up this page to review variables, data types, logging and commenting." + ] + }, + "quiz-javascript-variables-and-data-types": { + "title": "JavaScript Variables and Data Types Quiz", + "intro": [ + "Test your knowledge of JavaScript variables and data types with this quiz." + ] + }, + "lecture-working-with-strings-in-javascript": { + "title": "Working with Strings in JavaScript", + "intro": [ + "In these lectures, you will learn how to work with strings in JavaScript. You will learn how to access characters from a string, how to use template literals and interpolation, how to create a new line in strings, and much more." + ] + }, + "workshop-teacher-chatbot": { + "title": "Build a Teacher Chatbot", + "intro": [ + "In this workshop, you will continue to learn more about JavaScript strings by building a chatbot.", + "You will learn how to work with template literals, and the indexOf method." + ] + }, + "lecture-working-with-string-character-methods": { + "title": "Working with String Character Methods", + "intro": [ + "In this lecture you will learn about ASCII character encoding and how to use JavaScript's charCodeAt() and fromCharCode() methods to convert between characters and their numerical ASCII values." + ] + }, + "lecture-working-with-string-search-and-slice-methods": { + "title": "Working with String Search and Slice Methods", + "intro": [ + "In this lecture you will learn how to search for substrings using the includes() method and how to extract portions of strings using the slice() method." + ] + }, + "workshop-string-inspector": { + "title": "Build a String Inspector", + "intro": [ + "In this workshop, you will practice working with the includes() and slice() methods by building a string inspector." + ] + }, + "lecture-working-with-string-formatting-methods": { + "title": "Working with String Formatting Methods", + "intro": [ + "In this lecture you will learn how to format strings by changing their case using toUpperCase() and toLowerCase() methods, and how to remove whitespace using trim(), trimStart(), and trimEnd() methods." + ] + }, + "workshop-string-formatter": { + "title": "Build a String Formatter", + "intro": [ + "In this workshop, you will practice working with various string methods including trim(), toUpperCase() and toLowerCase()." + ] + }, + "lecture-working-with-string-modification-methods": { + "title": "Working with String Modification Methods", + "intro": [ + "In this lecture you will learn how to modify strings by replacing parts of them using the replace() method and how to repeat strings multiple times using the repeat() method." + ] + }, + "workshop-string-transformer": { + "title": "Build a String Transformer", + "intro": [ + "In this workshop, you will practice working with the replace(), replaceAll() and repeat() methods." + ] + }, + "review-javascript-strings": { + "title": "JavaScript Strings Review", + "intro": [ + "Before you are quizzed on working with JavaScript strings, you first need to review.", + "Open up this page to review how to work with template literals, the slice method, the includes method, the trim method and more." + ] + }, + "quiz-javascript-strings": { + "title": "JavaScript Strings Quiz", + "intro": ["Test your knowledge of JavaScript strings with this quiz."] + }, + "lecture-working-with-numbers-and-arithmetic-operators": { + "title": "Working with Numbers and Arithmetic Operators", + "intro": [ + "In these lectures you will learn about the number type, arithmetic operators, and using them with numbers and strings." + ] + }, + "lab-debug-type-coercion-errors": { + "title": "Debug Type Coercion Errors in a Buggy App", + "intro": [ + "In this lab, you will be working with a buggy app that contains several type coercion errors.", + "Your task is to identify and fix these errors to ensure the app functions correctly." + ] + }, + "lecture-working-with-operator-behavior": { + "title": "Working with Operator Behavior", + "intro": [ + "In these lectures you will learn about operator precedence, the increment and decrement operators, and compound assignment operators." + ] + }, + "lab-debug-increment-and-decrement-operator-errors": { + "title": "Debug Increment and Decrement Operator Errors in a Buggy App", + "intro": [ + "In this lab, you'll debug an app that has several errors related to the increment and decrement operators.", + "Your task is to identify and fix the errors so that the app works as intended." + ] + }, + "lecture-working-with-comparison-and-boolean-operators": { + "title": "Working with Comparison and Boolean Operators", + "intro": [ + "In these lectures you will learn about booleans, and equality and inequality operators, and other comparison operators." + ] + }, + "workshop-logic-checker-app": { + "title": "Build a Logic Checker App", + "intro": [ + "In this workshop, you'll practice working with conditional statements and comparison operators by building a logic checker app." + ] + }, + "lecture-working-with-unary-and-bitwise-operators": { + "title": "Working with Unary and Bitwise Operators", + "intro": [ + "In these lectures, you will learn about unary and bitwise operators." + ] + }, + "lecture-working-with-conditional-logic-and-math-methods": { + "title": "Working with Conditional Logic and Math Methods", + "intro": [ + "In these lectures, you will learn about conditional statements, binary logical operators, and the Math object." + ] + }, + "workshop-mathbot": { + "title": "Build a Mathbot", + "intro": [ + "In this workshop, you will review how to work with the different Math object methods by building a Mathbot." + ] + }, + "lab-fortune-teller": { + "title": "Build a Fortune Teller", + "intro": [ + "In this lab, you'll build a fortune teller by randomly selecting a fortune from the available fortunes.", + "You'll practice how to work with the Math.random() method and the Math.floor() method to generate random numbers." + ] + }, + "lecture-working-with-numbers-and-common-number-methods": { + "title": "Working with Numbers and Common Number Methods", + "intro": [ + "In these lectures, you will learn about numbers and common number methods. These include isNaN(), parseInt(), parseFloat(), and toFixed()." + ] + }, + "review-javascript-math": { + "title": "JavaScript Math Review", + "intro": [ + "Before you're quizzed on working with the Math object, you should review what you've learned.", + "Open up this page to review how to work with the Math.random() method, the Math.floor() method and more." + ] + }, + "quiz-javascript-math": { + "title": "JavaScript Math Quiz", + "intro": [ + "Test your knowledge of the JavaScript Math object with this quiz." + ] + }, + "lecture-understanding-comparisons-and-conditionals": { + "title": "Understanding Comparisons and Conditionals", + "intro": [ + "In these lectures, you will learn about comparison operators and conditionals. You will learn how the various conditionals differ from one another, and how comparisons work with null and undefined." + ] + }, + "review-javascript-comparisons-and-conditionals": { + "title": "JavaScript Comparisons and Conditionals Review", + "intro": [ + "Before you're quizzed on working with conditionals, you should review what you've learned about them.", + "Open up this page to review how to work with switch statements, other types of conditionals and more." + ] + }, + "quiz-javascript-comparisons-and-conditionals": { + "title": "JavaScript Comparisons and Conditionals Quiz", + "intro": [ + "Test your knowledge of JavaScript Comparisons and Conditionals with this quiz." + ] + }, + "lecture-working-with-functions": { + "title": "Working with Functions", + "intro": [ + "In these lectures, you will learn how to reuse a block of code with functions. You will learn what the purpose of a function is and how they work, and how scope works in programming. " + ] + }, + "workshop-calculator": { + "title": "Build a Calculator", + "intro": [ + "In this workshop, you will review your knowledge of functions by building a calculator." + ] + }, + "lab-boolean-check": { + "title": "Build a Boolean Check Function", + "intro": [ + "In this lab, you'll implement a function that checks if a value is a boolean." + ] + }, + "lab-email-masker": { + "title": "Build an Email Masker", + "intro": [ + "In this lab, you'll build an email masker that will take an email address and obscure it.", + "You'll practice string slicing, concatenation, and using functions." + ] + }, + "workshop-loan-qualification-checker": { + "title": "Build a Loan Qualification Checker", + "intro": [ + "In this workshop, you will continue to learn how to work with conditionals by building a loan qualification checker app.", + "You will learn more about if statements, and how to use comparison operators and multiple conditions in an if statement." + ] + }, + "lab-celsius-to-fahrenheit-converter": { + "title": "Build a Celsius to Fahrenheit Converter", + "intro": [ + "In this lab you will implement a function that converts the temperature from Celsius to Fahrenheit." + ] + }, + "lab-counting-cards": { + "title": "Build a Card Counting Assistant", + "intro": ["In this lab you will use JavaScript to count dealt cards."] + }, + "lab-leap-year-calculator": { + "title": "Build a Leap Year Calculator ", + "intro": [ + "In this lab you'll use conditional statements and loops to determine if a year is a leap year." + ] + }, + "lab-truncate-string": { + "title": "Implement the Truncate String Algorithm", + "intro": [ + "In this lab, you will practice truncating a string at a certain length." + ] + }, + "lab-string-ending-checker": { + "title": "Build a Confirm the Ending Tool", + "intro": [ + "In this lab, you will implement a function that checks if a given string ends with a specified target string." + ] + }, + "review-javascript-functions": { + "title": "JavaScript Functions Review", + "intro": [ + "Before you're quizzed on JavaScript functions, you should review what you've learned about them.", + "Open up this page to review functions, arrow functions and scope." + ] + }, + "quiz-javascript-functions": { + "title": "JavaScript Functions Quiz", + "intro": ["Test your knowledge of JavaScript functions with this quiz."] + }, + "lecture-working-with-arrays": { + "title": "Working with Arrays", + "intro": [ + "In these lectures, you will learn how to work with JavaScript arrays. You will learn about what makes an array, one-dimensional and two-dimensional arrays, how to access and update the elements in an array, and much more." + ] + }, + "workshop-shopping-list": { + "title": "Build a Shopping List", + "intro": [ + "In this workshop, you will practice how to work with arrays by building a shopping list.", + "You will review how to add and remove elements from an array using methods like push, pop, shift, and unshift." + ] + }, + "lab-lunch-picker-program": { + "title": "Build a Lunch Picker Program", + "intro": [ + "In this lab, you'll review working with arrays and random numbers by building a lunch picker program." + ] + }, + "lab-golf-score-translator": { + "title": "Build a Golf Score Translator", + "intro": [ + "For this lab, you will use array methods to translate golf scores into their nickname." + ] + }, + "lecture-working-with-common-array-methods": { + "title": "Working with Common Array Methods", + "intro": [ + "In these lectures, you will learn about the array methods for performing more advanced operations like getting the position of an item in an array, checking if an array contains a certain element, copying an array, and lots more." + ] + }, + "review-javascript-arrays": { + "title": "JavaScript Arrays Review", + "intro": [ + "Before you're quizzed on JavaScript arrays, you should review what you've learned about them.", + "Open up this page to review concepts like array destructuring, how to add and remove elements from an array, and more." + ] + }, + "quiz-javascript-arrays": { + "title": "JavaScript Arrays Quiz", + "intro": ["Test your knowledge of JavaScript arrays with this quiz."] + }, + "lecture-introduction-to-javascript-objects-and-their-properties": { + "title": "Introduction to JavaScript Objects and Their Properties", + "intro": [ + "In these lectures, you will learn the fundamentals of JavaScript objects, including how to create them, access their properties, and understand the difference between primitive and non-primitive data types." + ] + }, + "workshop-wildlife-tracker": { + "title": "Build a Wildlife Tracker", + "intro": [ + "In this workshop, you will build a simple Wildlife Tracker using JavaScript objects.", + "You will practice creating objects, accessing and updating properties, removing properties, checking for property existence, and working with bracket notation." + ] + }, + "lab-cargo-manifest-validator": { + "title": "Build a Cargo Manifest Validator", + "intro": [ + "In this lab, you will use JavaScript to normalize and validate cargo manifests." + ] + }, + "lecture-working-with-json": { + "title": "Working with JSON", + "intro": [ + "In these lectures, you will learn about JavaScript Object Notation (JSON), including how to access JSON data and use the JSON.parse() and JSON.stringify() methods." + ] + }, + "lecture-working-with-optional-chaining-and-object-destructuring": { + "title": "Working with Optional Chaining and Object Destructuring", + "intro": [ + "In these lectures, you will learn about advanced object manipulation techniques in JavaScript, including the optional chaining operator and object destructuring syntax." + ] + }, + "lab-device-loan-ledger": { + "title": "Build a Device Loan Ledger", + "intro": [ + "In this lab, you will build a device loan ledger to manage IT hardware provisioned by your company's Service Desk.", + "You will practice working with nested objects and JSON by implementing functions to check devices in and out, track overdue loans, and convert between JSON strings and JavaScript objects." + ] + }, + "workshop-recipe-tracker": { + "title": "Build a Recipe Tracker", + "intro": [ + "In this workshop, you will review working with JavaScript objects by building a recipe tracker." + ] + }, + "lab-quiz-game": { + "title": "Build a Quiz Game", + "intro": [ + "In this lab, you'll build a quiz game using JavaScript arrays and objects.", + "You'll also practice using functions to randomly select a question and an answer from an array and compare them." + ] + }, + "lab-record-collection": { + "title": "Build a Record Collection", + "intro": [ + "In this lab you will build a function to manage a record collection." + ] + }, + "review-javascript-objects": { + "title": "JavaScript Objects Review", + "intro": [ + "Before you're quizzed on JavaScript objects, you should review what you've learned about them.", + "Open up this page to review concepts including how to access information from objects, object destructuring, working with JSON, and more." + ] + }, + "quiz-javascript-objects": { + "title": "JavaScript Objects Quiz", + "intro": ["Test your knowledge of JavaScript objects with this quiz."] + }, + "lecture-working-with-loops": { + "title": "Working with Loops", + "intro": [ + "Loops are an essential part of JavaScript. That's why the following lectures have been prepared for you to learn about the different types of loops and how they work, and also how iteration works." + ] + }, + "workshop-word-counter": { + "title": "Build a Word Counter", + "intro": [ + "In this workshop, you will practice using for...of loops by building a function that counts the occurrences of a string in an array of strings." + ] + }, + "workshop-sentence-analyzer": { + "title": "Build a Sentence Analyzer", + "intro": [ + "In this workshop, you'll review how to work with JavaScript loops by building a sentence analyzer app." + ] + }, + "lab-traffic-light-sequencer": { + "title": "Build a Traffic Light Sequencer", + "intro": [ + "In this lab, you will use JavaScript loops to build a traffic light sequencer." + ] + }, + "workshop-space-mission-roster": { + "title": "Build a Space Mission Roster", + "intro": [ + "In this workshop, you'll leverage JavaScript loops to build a space mission roster." + ] + }, + "workshop-heritage-library-catalog": { + "title": "Build a Heritage Library Catalog", + "intro": [ + "In this workshop, you will digitize historical catalog cards for a heritage library.", + "You will practice using loops, objects, and string methods to parse raw text data, search and group entries, render formatted output, and export to JSON and CSV." + ] + }, + "lab-longest-word-in-a-string": { + "title": "Build a Longest Word Finder App", + "intro": [ + "In this lab, you will use JavaScript loops to find the length of the longest word in the given sentence." + ] + }, + "lab-factorial-calculator": { + "title": "Build a Factorial Calculator ", + "intro": [ + "In this lab, you'll build a factorial calculator.", + "You'll practice using loops and conditionals to calculate the factorial of a number." + ] + }, + "lab-mutations": { + "title": "Implement the Mutations Algorithm", + "intro": [ + "In this lab, you will practice iterating over two different strings to compare their characters." + ] + }, + "lab-chunky-monkey": { + "title": "Implement the Chunky Monkey Algorithm", + "intro": [ + "In this lab, you will practice dividing an array into smaller arrays with the technique of your choice." + ] + }, + "lab-profile-lookup": { + "title": "Build a Profile Lookup", + "intro": [ + "In this lab, you'll create a function that looks up profile information." + ] + }, + "lab-repeat-a-string": { + "title": "Build a String Repeating Function", + "intro": [ + "In this lab, you will implement loops to repeat a string a specified number of times." + ] + }, + "workshop-festival-crowd-flow-simulator": { + "title": "Build a Festival Crowd Flow Simulator", + "intro": [ + "In this workshop, you will use JavaScript to simulate the flow of attendants at a music festival." + ] + }, + "lab-missing-letter-detector": { + "title": "Build a Missing Letter Detector", + "intro": [ + "In this lab, you will build a function that finds the missing letter in a given range of consecutive letters and returns it." + ] + }, + "lab-smart-pantry-restocker": { + "title": "Build a Smart Pantry Restocker", + "intro": [ + "In this lab, you will build a small pantry management program using basic JavaScript concepts like arrays, objects, loops, and conditionals." + ] + }, + "lab-proofreading-tool": { + "title": "Build a Proofreading Tool", + "intro": [ + "In this lab, you will build a proofreading tool that analyzes arrays of words for palindromes and repeated phrases.", + "You will practice for loops and nested loops to check palindromes and find repeated word sequences." + ] + }, + "review-javascript-loops": { + "title": "JavaScript Loops Review", + "intro": [ + "Before you're quizzed on the different JavaScript loops, you should review them.", + "Open up this page to review the for...of loop, while loop, break and continue statements and more." + ] + }, + "quiz-javascript-loops": { + "title": "JavaScript Loops Quiz", + "intro": ["Test your knowledge of JavaScript loops with this quiz."] + }, + "lecture-working-with-types-and-objects": { + "title": "Working with Types and Objects", + "intro": [ + "In these lectures you will learn about string objects, the toString() method, the Number constructor and more." + ] + }, + "lecture-working-with-arrays-variables-and-naming-practices": { + "title": "Working with Arrays, Variables, and Naming Practices", + "intro": [ + "In these lectures you will learn about common practices for naming variables and functions, and how to work with arrays." + ] + }, + "lecture-working-with-code-quality-and-execution-concepts": { + "title": "Working with Code Quality and Execution Concepts", + "intro": [ + "In these lectures you will learn what are linters and formatters, what is memory management, and closures." + ] + }, + "lab-reverse-a-string": { + "title": "Build a String Inverter", + "intro": [ + "In this lab, you create a function that reverses a given string." + ] + }, + "lab-largest-number-finder": { + "title": "Build the Largest Number Finder", + "intro": [ + "In this lab, you will use JavaScript fundamentals to create a function that finds the largest number in each sub-array of a given array." + ] + }, + "lab-first-element-finder": { + "title": "Build a First Element Finder", + "intro": [ + "In this lab, you will create a function that looks through an array and returns the first element in it that passes a \"truth test\"." + ] + }, + "lab-slice-and-splice": { + "title": "Implement the Slice and Splice Algorithm", + "intro": [ + "In this lab, you will practice merging an array with another." + ] + }, + "lab-pyramid-generator": { + "title": "Build a Pyramid Generator", + "intro": [ + "In this lab you'll build a pyramid generator.", + "You'll take a number as input and generate a pyramid with that many levels using a loop." + ] + }, + "lab-gradebook-app": { + "title": "Build a Gradebook App", + "intro": [ + "For this lab, you'll create a gradebook app.", + "You'll practice conditionals to determine the student's grade based on their score." + ] + }, + "lab-story-fragment-restoration": { + "title": "Restore a Coherent Narrative from an Array of Story Fragments", + "intro": [ + "In this lab, you'll restore a coherent narrative from a corrupted array of story fragments.", + "You will practice working with loops by implementing fundamental array algorithms from scratch." + ] + }, + "lecture-the-var-keyword-and-hoisting": { + "title": "The var Keyword and Hoisting", + "intro": [ + "In these lectures, you will learn about the var keyword and why it is not recommended for use anymore. You will also learn about hoisting in JavaScript so you can avoid subtle bugs in your code." + ] + }, + "lab-title-case-converter": { + "title": "Build a Title Case Converter", + "intro": [ + "In this lab, you will build a function that converts a string to title case." + ] + }, + "lab-falsy-remover": { + "title": "Implement a Falsy Remover", + "intro": [ + "In this lab, you will create a function that removes all falsy values from an array." + ] + }, + "lab-inventory-management-program": { + "title": "Build an Inventory Management Program", + "intro": [ + "For this lab, you'll build an inventory management program using JavaScript.", + "You'll use JavaScript array of objects to manage the inventory." + ] + }, + "lecture-understanding-modules-imports-and-exports": { + "title": "Understanding Modules, Imports, and Exports", + "intro": [ + "In this lecture, you will learn about modules, imports, and exports in JavaScript." + ] + }, + "lecture-working-with-the-arguments-object-and-rest-parameters": { + "title": "Working With the Arguments Object and Rest Parameters", + "intro": [ + "In these lessons, you will learn how to work with the arguments object and rest parameter syntax." + ] + }, + "lab-unique-sorted-union": { + "title": "Implement a Unique Sorted Union", + "intro": [ + "In this lab, you will create a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays." + ] + }, + "lab-password-generator": { + "title": "Build a Password Generator App", + "intro": [ + "In this lab, you'll build a password generator app based on the user's input." + ] + }, + "lab-sum-all-numbers-algorithm": { + "title": "Design a Sum All Numbers Algorithm", + "intro": [ + "In this lab, you will design a sum all numbers algorithm. This algorithm takes an array of two numbers and returns the sum of those two numbers plus the sum of all the numbers between them." + ] + }, + "lab-dna-pair-generator": { + "title": "Implement a DNA Pair Generator", + "intro": [ + "In this lab you will implement a DNA base pairing algorithm that converts a single DNA strand into complementary base pairs." + ] + }, + "lab-html-entitiy-converter": { + "title": "Implement an HTML Entity Converter", + "intro": [ + "In this lab, you will convert special characters in a string to their corresponding HTML entities." + ] + }, + "lab-odd-fibonacci-sum-calculator": { + "title": "Build an Odd Fibonacci Sum Calculator", + "intro": [ + "In this lab you will build an odd Fibonacci sum calculator that takes a number and returns the sum of all odd Fibonacci numbers that are less than or equal to that number." + ] + }, + "lab-element-skipper": { + "title": "Implement an Element Skipper", + "intro": [ + "In this lab you will create a function that skips elements in an array based on a specified step value." + ] + }, + "lab-playlist-remix-engine": { + "title": "Build a Playlist Remix Engine", + "intro": [ + "In this lab, you will build a Playlist Remix Engine using JavaScript arrays.", + "You will apply array methods and logic to transform data and generate a final remix schedule." + ] + }, + "review-javascript-fundamentals": { + "title": "JavaScript Fundamentals Review", + "intro": [ + "Before you are quizzed on JavaScript fundamentals, you first need to review the concepts.", + "Open up this page to review concepts like closures, memory management, and more." + ] + }, + "quiz-javascript-fundamentals": { + "title": "JavaScript Fundamentals Quiz", + "intro": [ + "Test your knowledge of JavaScript fundamentals with this quiz." + ] + }, + "lecture-working-with-higher-order-functions-and-callbacks": { + "title": "Working with Higher Order Functions and Callbacks", + "intro": [ + "In these lectures, you will learn how to work with higher order functions and callbacks. The higher order functions you will learn include map(), filter(), reduce(), sort(), every(), and some(). You will also learn how to chain these methods together to achieve your desired results." + ] + }, + "workshop-library-manager": { + "title": "Build a Library Manager", + "intro": [ + "In this workshop, you will learn higher order array methods by building a library manager." + ] + }, + "lab-book-organizer": { + "title": "Build a Book Organizer", + "intro": [ + "In this lab, you'll build a book organizer using higher order functions in JavaScript." + ] + }, + "lab-sorted-index-finder": { + "title": "Implement a Sorted Index Finder", + "intro": [ + "In this lab, you will create a function that finds the index at which a given number should be inserted into a sorted array to maintain the array's sorted order." + ] + }, + "lab-symmetric-difference": { + "title": "Build a Symmetric Difference Function", + "intro": [ + "In this lab, you will practice using higher order functions to find the symmetric difference between two arrays." + ] + }, + "lab-value-remover-function": { + "title": "Implement a Value Remover Function", + "intro": [ + "In this lab, you will create a function that removes all instances of a specified value from an array." + ] + }, + "lab-matching-object-filter": { + "title": "Implement a Matching Object Filter", + "intro": [ + "In this lab, you will create a function that looks through an array of objects and returns an array of all objects that have matching property and value pairs." + ] + }, + "lab-range-based-lcm-calculator": { + "title": "Implement a Range-Based LCM Calculator", + "intro": [ + "In this lab, you will create a function that takes an array of two numbers and returns the least common multiple (LCM) of those two numbers and all the numbers between them." + ] + }, + "lab-deep-flattening-tool": { + "title": "Create a Deep Flattening Tool", + "intro": [ + "In this lab you will create a function that can flatten deeply nested arrays, handling any level of nesting without using built-in flat methods." + ] + }, + "lab-all-true-property-validator": { + "title": "Build an All-True Property Validator", + "intro": [ + "In this lab you will build a function that checks if all objects in an array have a truthy value for a specific property." + ] + }, + "review-javascript-higher-order-functions": { + "title": "JavaScript Higher Order Functions Review", + "intro": [ + "Before you're quizzed on JavaScript higher order functions, you should review them.", + "Open up this page to review concepts including how to work with the map(), filter(), and reduce() methods." + ] + }, + "quiz-javascript-higher-order-functions": { + "title": "JavaScript Higher Order Functions Quiz", + "intro": [ + "Test what you've learned about JavaScript higher order functions with this quiz." + ] + }, + "lecture-working-with-the-dom-click-events-and-web-apis": { + "title": "Working with the DOM, Click Events, and Web APIs", + "intro": [ + "In these lectures, you will learn how to work with the Document Object Model (DOM), the addEventListener() method and events, and web APIs." + ] + }, + "workshop-storytelling-app": { + "title": "Build a Storytelling App", + "intro": [ + "In this workshop, you will build a storytelling app that will allow you to list different stories based on genre." + ] + }, + "workshop-emoji-reactor": { + "title": "Build an Emoji Reactor", + "intro": [ + "In this workshop, you will build an emoji reactor to practice querySelector and querySelectorAll." + ] + }, + "lab-favorite-icon-toggler": { + "title": "Build a Favorite Icon Toggler", + "intro": [ + "In this lab, you'll build a favorite icon toggler by utilizing JavaScript click events." + ] + }, + "lecture-understanding-the-event-object-and-event-delegation": { + "title": "Understanding the Event Object and Event Delegation", + "intro": [ + "In these lectures, you will learn about the event object, the change event, event bubbling, and event delegation." + ] + }, + "workshop-music-instrument-filter": { + "title": "Build a Music Instrument Filter", + "intro": [ + "In this workshop, you will build a music instrument filter with JavaScript." + ] + }, + "lab-real-time-counter": { + "title": "Build a Real Time Counter", + "intro": [ + "In this lab, you'll build a real-time character counter", + "You'll practice how to work with the input event when the user types in the input field." + ] + }, + "lab-lightbox-viewer": { + "title": "Build a Lightbox Viewer", + "intro": [ + "In this lab, you'll build a lightbox viewer for viewing images in a focused mode.", + "You'll practice click events and toggling classes." + ] + }, + "workshop-rps-game": { + "title": "Build a Rock, Paper, Scissors Game", + "intro": [ + "In this workshop, you will review DOM manipulation and events by building a Rock, Paper, Scissors Game." + ] + }, + "lab-football-team-cards": { + "title": "Build a Set of Football Team Cards", + "intro": [ + "In this lab, you'll use DOM manipulation, object destructuring, event handling, and data filtering to build a set of football team cards." + ] + }, + "review-dom-manipulation-and-click-events-with-javascript": { + "title": "DOM Manipulation and Click Events with JavaScript Review", + "intro": [ + "Before you're quizzed on the DOM, you should review what you've learned about it.", + "Open up this page to review concepts including how to work with the DOM, Web APIs, the addEventListener() method, change events, event bubbling and more." + ] + }, + "quiz-dom-manipulation-and-click-event-with-javascript": { + "title": "DOM Manipulation and Click Events with JavaScript Quiz", + "intro": [ + "Test your knowledge of DOM manipulation and click events in JavaScript with this quiz." + ] + }, + "lecture-understanding-aria-expanded-aria-live-and-common-aria-states": { + "title": "Understanding aria-expanded, aria-live, and Common ARIA States", + "intro": [ + "In these lectures you will learn more about ARIA attributes like aria-expanded, aria-live, and common ARIA states." + ] + }, + "workshop-planets-tablist": { + "title": "Build a Planets Tablist", + "intro": [ + "In this workshop, you will build a dynamic tabbed interface that showcases facts about the planets in the solar system." + ] + }, + "workshop-note-taking-app": { + "title": "Build a Note Taking App", + "intro": [ + "In this workshop, you are going to build an accessible note taking app.", + "This will provide you with the opportunity to practice working with aria-live attribute." + ] + }, + "lab-theme-switcher": { + "title": "Build a Theme Switcher", + "intro": [ + "In this lab, you will build a theme switcher and practice working with the aria-haspopup, aria-expanded, and aria-controls attributes." + ] + }, + "review-js-a11y": { + "title": "JavaScript and Accessibility Review", + "intro": [ + "Before you're quizzed on JavaScript and accessibility, you should review what you've learned about it.", + "Open up this page to review concepts including how to work with the aria-expanded, aria-live, and aria-controls attributes." + ] + }, + "quiz-js-a11y": { + "title": "JavaScript and Accessibility Quiz", + "intro": [ + "Test your knowledge of JavaScript and accessibility best practices with this quiz." + ] + }, + "lecture-debugging-techniques": { + "title": "Debugging Techniques", + "intro": [ + "In these lectures, you will learn about the common errors in JavaScript and the techniques you can use to fix them – a process called debugging." + ] + }, + "lab-random-background-color-changer": { + "title": "Debug a Random Background Color Changer", + "intro": [ + "In this lab, you'll debug a random background color changer and fix the errors to make it work properly." + ] + }, + "review-debugging-javascript": { + "title": "Debugging JavaScript Review", + "intro": [ + "Before you're quizzed on common debugging techniques, you should review what you've learned.", + "Open up this page to review concepts including how to work with the throw statement, try...catch...finally and more." + ] + }, + "quiz-debugging-javascript": { + "title": "Debugging JavaScript Quiz", + "intro": ["Test your knowledge of JavaScript debugging with this quiz."] + }, + "lecture-working-with-regular-expressions": { + "title": "Working with Regular Expressions", + "intro": [ + "In these lectures, you will learn about regular expressions in JavaScript. You will learn about the methods for working with regular expressions, modifiers, character classes, lookaheads, lookbehinds, back-references, quantifiers, and more." + ] + }, + "workshop-spam-filter": { + "title": "Build a Spam Filter", + "intro": [ + "Regular expressions, often shortened to \"regex\" or \"regexp\", are patterns that help programmers match, search, and replace text. Regular expressions are powerful, but can be difficult to understand because they use so many special characters.", + "In this workshop, you'll use capture groups, positive lookaheads, negative lookaheads, and other techniques to match any text you want." + ] + }, + "lab-palindrome-checker": { + "title": "Build a Palindrome Checker", + "intro": [ + "For this lab, you'll build an application that checks whether a given word is a palindrome." + ] + }, + "lab-regex-sandbox": { + "title": "Build a RegEx Sandbox", + "intro": ["In this lab you'll build a regex sandbox."] + }, + "lab-spinal-case-converter": { + "title": "Implement a Spinal Case Converter", + "intro": [ + "In this lab, you will create a function that converts a given string to spinal case which is a style of writing where all letters are lowercase and separated by hyphens." + ] + }, + "lab-pig-latin": { + "title": "Implement a Pig Latin Translator", + "intro": [ + "In this lab, you'll implement a Pig Latin translator using JavaScript.", + "You'll practice string manipulation, conditional logic, and regular expressions." + ] + }, + "lab-smart-word-replacement": { + "title": "Build a Smart Word Replacement Function", + "intro": [ + "In this lab, you will use regex to create a function that performs a search and replace operation on a given string." + ] + }, + "review-javascript-regular-expressions": { + "title": "JavaScript Regular Expressions Review", + "intro": [ + "Before you're quizzed on Regular Expressions, you should review what you've learned.", + "Open up this page to review concepts like lookaheads, lookbehinds, common regex modifiers and more." + ] + }, + "quiz-javascript-regular-expressions": { + "title": "JavaScript Regular Expressions Quiz", + "intro": [ + "Test your knowledge of JavaScript Regular Expressions with this quiz." + ] + }, + "lab-markdown-to-html-converter": { + "title": "Build a Markdown to HTML Converter", + "intro": [ + "For this lab, you'll build a Markdown to HTML converter using JavaScript.", + "You'll practice regular expressions, string manipulation, and more." + ] + }, + "lecture-understanding-form-validation": { + "title": "Understanding Form Validation", + "intro": [ + "In these lectures, you will learn about form validation in JavaScript. You will learn about the various ways to validate forms, how the preventDefault() method works, and how the submit event works." + ] + }, + "workshop-envelope-budget-app": { + "title": "Build an Envelope Budget App", + "intro": [ + "Sometimes when you're coding a web application, you'll need to be able to accept input from a user. In this envelope budget app workshop, you'll practice how to validate user input, perform calculations based on that input, and dynamically update your interface to display the results.", + "You'll also practice basic regular expressions, template literals, the addEventListener() method, and more." + ] + }, + "lab-customer-complaint-form": { + "title": "Build a Customer Complaint Form", + "intro": [ + "For this lab, you'll use JavaScript to validate a customer complaint form.", + "You'll practice how to validate form inputs, display error messages, and prevent the form from submitting if there are errors." + ] + }, + "review-form-validation-with-javascript": { + "title": "Form Validation with JavaScript Review", + "intro": [ + "Before you're quizzed on form validation, you should review what you've learned.", + "Open up this page to review concepts including the preventDefault() method, the submit event and more." + ] + }, + "quiz-form-validation-with-javascript": { + "title": "Form Validation with JavaScript Quiz", + "intro": [ + "Test what you've learned about JavaScript form validation with this quiz." + ] + }, + "lecture-working-with-dates": { + "title": "Working with Dates", + "intro": [ + "In these lectures, you will learn about the JavaScript date object. You will learn about the methods for working with dates and how to format dates." + ] + }, + "lab-date-conversion": { + "title": "Build a Date Conversion Program", + "intro": [ + "In this lab, you'll build a program to convert a date from one format to another." + ] + }, + "review-javascript-dates": { + "title": "JavaScript Dates Review", + "intro": [ + "Before you're quizzed on working with dates, you should review what you've learned.", + "Open up this page to review the Date() object and common methods." + ] + }, + "quiz-javascript-dates": { + "title": "JavaScript Dates Quiz", + "intro": [ + "Test what you've learned about JavaScript Dates with this quiz." + ] + }, + "lecture-working-with-audio-and-video": { + "title": "Working with Audio and Video", + "intro": [ + "In these lectures, you will learn how to work with audio and video files using JavaScript. You will learn about the Audio and Video constructors, their methods and properties, audio and video formats, codecs, the HTMLMediaElement API, and much more." + ] + }, + "workshop-music-player": { + "title": "Build a Music Player", + "intro": [ + "In this workshop, you'll code a basic MP3 player using HTML, CSS, and JavaScript.", + "The project covers fundamental concepts such as handling audio playback, managing a playlist, implementing play, pause, next, and previous functionalities and dynamically update your user interface based on the current song." + ] + }, + "review-javascript-audio-and-video": { + "title": "JavaScript Audio and Video Review", + "intro": [ + "Before you're quizzed on working with audio and video in JavaScript, you should review what you've learned about them.", + "Open up this page to review concepts including the Audio constructor, the HTMLMediaElement API and more." + ] + }, + "quiz-javascript-audio-and-video": { + "title": "JavaScript Audio and Video Quiz", + "intro": [ + "Test what you've learned about JavaScript audio and video with this quiz." + ] + }, + "lab-drum-machine": { + "title": "Build a Drum Machine", + "intro": [ + "For this lab you will use the audio element to build a drum machine." + ] + }, + "lecture-working-with-maps-and-sets": { + "title": "Working with Maps and Sets", + "intro": [ + "In these lectures, you will learn about JavaScript Map and Set. You will also learn how they both differ from WeakSets and WeakMaps." + ] + }, + "workshop-plant-nursery-catalog": { + "title": "Build a Plant Nursery Catalog", + "intro": [ + "In this workshop, you will practice using Maps and Sets by building a plant nursery catalog." + ] + }, + "review-javascript-maps-and-sets": { + "title": "JavaScript Maps and Sets Review", + "intro": [ + "Before you're quizzed on JavaScript Maps and Sets, you should review what you've learned about them.", + "Open up this page to review concepts such as the Map and Set objects, as well as WeakSet and WeakMap." + ] + }, + "quiz-javascript-maps-and-sets": { + "title": "JavaScript Maps and Sets Quiz", + "intro": [ + "Test what you've learned about JavaScript Maps and Sets with this quiz." + ] + }, + "lab-voting-system": { + "title": "Build a Voting System", + "intro": [ + "In this lab, you'll build a voting system using Maps and Sets.", + "You'll practice how to use the Map object to store key-value pairs and the Set object to store unique values." + ] + }, + "lecture-working-with-client-side-storage-and-crud-operations": { + "title": "Working with Client-Side Storage and CRUD Operations", + "intro": [ + "In these lectures, you will learn about client-side storage and CRUD operations in JavaScript. You will learn about localStorage and sessionStorage alongside their methods and properties, cookies, the Cache API, IndexDB, and much more." + ] + }, + "workshop-todo-app": { + "title": "Build a Todo App using Local Storage", + "intro": [ + "Local storage is a web browser feature that lets web applications store key-value pairs persistently within a user's browser. This allows web apps to save data during one session, then retrieve it in a later page session.", + "In this workshop, you'll learn how to handle form inputs, manage local storage, perform CRUD (Create, Read, Update, Delete) operations on tasks, implement event listeners, and toggle UI elements." + ] + }, + "lab-bookmark-manager-app": { + "title": "Build a Bookmark Manager App", + "intro": [ + "For this lab, you'll build a bookmark manager app.", + "You'll utilize local storage to store bookmarks, and practice how to add, remove, and display bookmarks." + ] + }, + "review-local-storage-and-crud": { + "title": "Local Storage and CRUD Review", + "intro": [ + "Before you are quizzed on working with localStorage, you first need to review the concepts.", + "Open up this page to review the localStorage property, sessionStorage property and more." + ] + }, + "quiz-local-storage-and-crud": { + "title": "Local Storage and CRUD Quiz", + "intro": [ + "Test what you've learned about local storage and CRUD with this quiz." + ] + }, + "lecture-understanding-how-to-work-with-classes-in-javascript": { + "title": "Understanding How to Work with Classes in JavaScript", + "intro": [ + "In these lectures, you will learn about classes in JavaScript. You will learn about inheritance, the this keyword, static properties and methods, and more." + ] + }, + "workshop-shopping-cart": { + "title": "Build a Shopping Cart", + "intro": [ + "In this workshop you'll create a shopping cart using JavaScript classes.", + "You will practice how to use the this keyword, create class instances, implement methods for data manipulation and more." + ] + }, + "lab-project-idea-board": { + "title": "Build a Project Idea Board", + "intro": [ + "In this lab, you'll build a project idea board using OOP in JavaScript.", + "You'll practice how to create classes, add methods to classes, and create instances of classes." + ] + }, + "review-javascript-classes": { + "title": "JavaScript Classes Review", + "intro": [ + "Before you're quizzed on how to work with classes, you should review what you've learned about them.", + "Open up this page to review concepts including the this keyword, class inheritance and more." + ] + }, + "quiz-javascript-classes": { + "title": "JavaScript Classes Quiz", + "intro": [ + "Test what you've learned about JavaScript classes with this quiz." + ] + }, + "lab-bank-account-manager": { + "title": "Build a Bank Account Management Program", + "intro": [ + "In this lab, you'll build a simple transaction management system for a bank account." + ] + }, + "lecture-understanding-recursion-and-the-call-stack": { + "title": "Understanding Recursion and the Call Stack", + "intro": [ + "In this lecture, you will learn about recursion and the call stack." + ] + }, + "workshop-countup": { + "title": "Build a Countup", + "intro": [ + "In this workshop you will build a countdown function that returns an array of numbers counting up from 1 to a given number." + ] + }, + "lab-countdown": { + "title": "Build a Countdown", + "intro": [ + "For this lab, you will build a countdown function that returns an array of numbers counting down from given number to 1." + ] + }, + "lab-range-of-numbers": { + "title": "Build a Range of Numbers Generator", + "intro": [ + "In this lab, you'll use recursion to generate an array of numbers within a specified range.", + "You'll practice recursive function calls, base cases, and building arrays through recursion." + ] + }, + "workshop-decimal-to-binary-converter": { + "title": "Build a Decimal to Binary Converter", + "intro": [ + "Recursion is a programming concept where a function calls itself. This can reduce a complex problem into simpler sub-problems, until they become straightforward to solve.", + "In this workshop, you'll build a decimal-to-binary converter using JavaScript. You'll practice the fundamental concepts of recursion, explore the call stack, and build out a visual representation of the recursion process through an animation." + ] + }, + "lab-permutation-generator": { + "title": "Build a Permutation Generator", + "intro": [ + "For this lab, you'll build a permutation generator that produces all possible permutations of a given string." + ] + }, + "review-recursion": { + "title": "Recursion Review", + "intro": [ + "Before you're quizzed on recursion, you should review what you've learned.", + "Open up this page to review what is recursion and what is it used for." + ] + }, + "quiz-recursion": { + "title": "Recursion Quiz", + "intro": ["Test your knowledge of Recursion with this quiz."] + }, + "lecture-working-with-common-data-structures-js": { + "title": "Working with Common Data Structures", + "intro": [ + "Learn about common data structures and how to work with them in JavaScript." + ] + }, + "workshop-linked-list-js": { + "title": "Build a Linked List", + "intro": [ + "In the previous lessons, you learned about some common data structures.", + "In this workshop, you will build a linked list using JavaScript." + ] + }, + "lab-linked-list-operations": { + "title": "Implement Linked List Operations", + "intro": [ + "In this lab you will implement common linked list operations such as insertion, deletion, and traversal." + ] + }, + "lab-implement-a-stack": { + "title": "Implement a Stack", + "intro": [ + "In this lab, you will implement a stack data structure using functions." + ] + }, + "lab-implement-a-queue": { + "title": "Implement a Queue", + "intro": [ + "In this lab, you will implement a queue data structure using functions." + ] + }, + "review-data-structures-js": { + "title": "Data Structures Review", + "intro": [ + "Before you're quizzed on data structures, you should review what you've learned about them.", + "Open up this page to review concepts like the different data structures, algorithms, time and space complexity, and big O notation." + ] + }, + "quiz-data-structures-js": { + "title": "Data Structures Quiz", + "intro": [ + "Test what you've learned about data structures in JavaScript with this quiz." + ] + }, + "lecture-introduction-to-common-searching-and-sorting-algorithms": { + "title": "Introduction to Common Searching and Sorting Algorithms", + "intro": [ + "Learn about fundamental searching and sorting algorithms, including linear search, binary search, and merge sort.", + "These lessons cover algorithm implementations, time and space complexity analysis, and the divide and conquer programming paradigm." + ] + }, + "workshop-binary-search-js": { + "title": "Implement the Binary Search Algorithm", + "intro": [ + "The binary search algorithm is a searching algorithm used to find a target item in a sorted list.", + "In this workshop, you'll implement the binary search algorithm and return the path it took to find the target or return 'Value not found'." + ] + }, + "workshop-merge-sort-js": { + "title": "Implement the Merge Sort Algorithm", + "intro": [ + "The merge sort algorithm is a sorting algorithm based on the divide and conquer principle.", + "In this workshop, you'll implement the merge sort algorithm to sort a list of random numbers." + ] + }, + "lab-bubble-sort-algorithm": { + "title": "Implement the Bubble Sort Algorithm", + "intro": [ + "In this lab, you will implement the bubble sort algorithm to sort an array of integers in ascending order." + ] + }, + "lab-selection-sort-js": { + "title": "Implement the Selection Sort Algorithm", + "intro": [ + "In this lab you will implement the selection sort algorithm." + ] + }, + "lab-insertion-sort": { + "title": "Implement the Insertion Sort Algorithm", + "intro": [ + "In this lab, you will implement the insertion sort algorithm to sort an array of integers in ascending order." + ] + }, + "lab-quicksort-js": { + "title": "Implement the Quicksort Algorithm", + "intro": [ + "In this lab you will implement the quicksort algorithm to sort an array of integers." + ] + }, + "review-searching-and-sorting-algorithms-js": { + "title": "Searching and Sorting Algorithms Review", + "intro": [ + "Before you are quizzed on Algorithms, you should review what you've learned about searching and sorting algorithms." + ] + }, + "quiz-searching-and-sorting-algorithms-js": { + "title": "Searching and Sorting Algorithms Quiz", + "intro": [ + "Test your knowledge of searching and sorting algorithms with this quiz." + ] + }, + "lecture-understanding-graphs-and-trees-js": { + "title": "Understanding Graphs and Trees", + "intro": [ + "In this lesson, you will learn about fundamental data structures like graphs, trees, and their practical applications in computer science." + ] + }, + "workshop-shortest-path-algorithm-js": { + "title": "Implement the Shortest Path Algorithm", + "intro": [ + "The shortest path algorithm finds the minimum distance between nodes in a weighted graph.", + "In this workshop, you'll implement the shortest path algorithm in JavaScript and return both the shortest distances and the paths taken." + ] + }, + "lab-adjacency-list-to-matrix-converter-js": { + "title": "Build an Adjacency List to Matrix Converter", + "intro": [ + "In this lab, you will implement a function that converts an adjacency list representation of a graph into an adjacency matrix representation." + ] + }, + "workshop-breadth-first-search-js": { + "title": "Implement the Breadth-First Search Algorithm", + "intro": [ + "In this workshop, you will use the breadth-first search algorithm to generate all valid combinations of parentheses." + ] + }, + "lab-depth-first-search-js": { + "title": "Implement the Depth-First Search Algorithm", + "intro": [ + "In this lab, you will implement a solution for the depth-first search algorithm." + ] + }, + "lab-n-queens-problem-js": { + "title": "Implement the N-Queens Algorithm", + "intro": [ + "In this lab, you will implement a solution for the N-Queens problem." + ] + }, + "review-graphs-and-trees-js": { + "title": "Graphs and Trees Review", + "intro": [ + "Graphs and Trees Review", + "Before you are quizzed on graphs and trees, you should review what you've learned." + ] + }, + "quiz-graph-and-trees-js": { + "title": "Graphs and Trees Quiz", + "intro": [ + "Graphs and Trees Quiz", + "Test what you've learned about graphs and trees with this quiz." + ] + }, + "lecture-understanding-dynamic-programming-js": { + "title": "Understanding Dynamic Programming", + "intro": [ + "In this lesson, you will learn about dynamic programming, an algorithmic technique used to solve complex problems efficiently by breaking them down into simpler subproblems." + ] + }, + "lab-nth-fibonacci-number-js": { + "title": "Build an Nth Fibonacci Number Calculator", + "intro": [ + "In this lab, you'll practice dynamic programming by implementing a Fibonacci sequence calculator in JavaScript." + ] + }, + "lab-prime-number-sum-calculator": { + "title": "Build a Prime Number Sum Calculator", + "intro": [ + "In this lab you will build a prime number sum calculator that takes a number and returns the sum of all prime numbers that are less than or equal to that number." + ] + }, + "review-dynamic-programming-js": { + "title": "Dynamic Programming Review", + "intro": [ + "Before you're quizzed on dynamic programming, you should review what you've learned about it." + ] + }, + "quiz-dynamic-programming-js": { + "title": "Dynamic Programming Quiz", + "intro": [ + "Test what you've learned about dynamic programming in JavaScript with this quiz." + ] + }, + "lecture-understanding-functional-programming": { + "title": "Understanding Functional Programming", + "intro": [ + "In these lectures, you will learn about functional programming and how to nest functions using a technique called currying." + ] + }, + "workshop-recipe-ingredient-converter": { + "title": "Build a Recipe Ingredient Converter", + "intro": [ + "In the previous lectures, you learned the core concepts behind functional programming and currying.", + "Now you will be able to apply what you have learned about currying and functional programming by building a recipe ingredient converter application." + ] + }, + "lab-optional-arguments-sum-function": { + "title": "Build an Optional Arguments Sum Function", + "intro": [ + "In this lab you will build a function that accepts up to two arguments, and sum them, but if there is only one argument returns a function that waits for the second number to sum." + ] + }, + "lab-sorting-visualizer": { + "title": "Build a Sorting Visualizer", + "intro": [ + "For this lab, you'll use JavaScript to visualize the steps that the Bubble Sort algorithm takes to reorder an array of integers." + ] + }, + "review-javascript-functional-programming": { + "title": "JavaScript Functional Programming Review", + "intro": [ + "Before you're quizzed on functional programming, you should review what you've learned.", + "Open up this page to review concepts on functional programming, currying and more." + ] + }, + "quiz-javascript-functional-programming": { + "title": "JavaScript Functional Programming Quiz", + "intro": [ + "Test what you've learned about JavaScript functional programming with this quiz." + ] + }, + "lecture-understanding-asynchronous-programming": { + "title": "Understanding Asynchronous Programming", + "intro": [ + "In these lectures, you will learn about asynchronous programming in JavaScript. You will learn about the differences between synchronous and asynchronous programming, how the async keyword works, the Fetch API, promises, async/await, the Geolocation API, and much more." + ] + }, + "workshop-fcc-authors-page": { + "title": "Build an fCC Authors Page", + "intro": [ + "One common aspect of web development is learning how to fetch data from an external API, then work with asynchronous JavaScript.", + "In this workshop you will practice how to use the fetch method, dynamically update the DOM to display the fetched data and paginate your data so you can load results in batches." + ] + }, + "lab-fcc-forum-leaderboard": { + "title": "Build an fCC Forum Leaderboard", + "intro": [ + "For this lab you'll practice asynchronous JavaScript by coding your own freeCodeCamp forum leaderboard." + ] + }, + "review-asynchronous-javascript": { + "title": "Asynchronous JavaScript Review", + "intro": [ + "Review asynchronous JavaScript concepts to prepare for the upcoming quiz." + ] + }, + "quiz-asynchronous-javascript": { + "title": "Asynchronous JavaScript Quiz", + "intro": [ + "Test what you've learned about asynchronous JavaScript with this quiz." + ] + }, + "lab-weather-app": { + "title": "Build a Weather App", + "intro": [ + "In this lab you'll build a Weather App using an API", + "You'll practice how to fetch data from the API, store and display it on your app." + ] + }, + "review-javascript": { + "title": "JavaScript Review", + "intro": [ + "Before you take the JavaScript prep exam, you should review everything you've learned about JavaScript.", + "Open up this page to review all of the concepts taught including variables, strings, booleans, functions, objects, arrays, debugging, working with the DOM and more." + ] + }, + "exam-javascript-certification": { + "title": "JavaScript Certification Exam", + "intro": ["Pass this exam to earn your JavaScript Certification."] + } + } + }, + "front-end-development-libraries-v9": { + "title": "Front-End Development Libraries Certification", + "intro": [ + "This course teaches you the libraries that developers use to build webpages: React, TypeScript, and more.", + "To earn your Front-End Development Libraries Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the Front-End Development Libraries Certification exam." + ], + "note": "", + "chapters": { + "front-end-development-libraries": "Front-End Development Libraries", + "front-end-development-libraries-certification-exam": "Front-End Development Libraries Certification Exam" + }, + "modules": { + "react-fundamentals": "React Fundamentals", + "react-state-hooks-and-routing": "React State, Hooks, and Routing", + "lab-currency-converter": "Build a Currency Converter", + "lab-tic-tac-toe": "Build a Tic-Tac-Toe Game", + "performance": "Performance", + "testing": "Testing", + "css-libraries-and-frameworks": "CSS Libraries and Frameworks", + "lab-photography-exhibit": "Design a Photography Exhibit", + "typescript-fundamentals": "TypeScript Fundamentals", + "lab-flashcard-quiz-app": "Build a Flashcard Quiz App", + "lab-digital-pet-game": "Build a Digital Pet Game", + "review-front-end-libraries": "Front-End Libraries Review", + "front-end-development-libraries-certification-exam": "Front-End Development Libraries Certification Exam" + }, + "blocks": { + "lecture-introduction-to-javascript-libraries-and-frameworks": { + "title": "Introduction to JavaScript Libraries and Frameworks", + "intro": [ + "In these lessons, you will get an introduction to JavaScript libraries and frameworks. You will learn about the roles of JavaScript libraries and frameworks, single page applications (SPAs) and the issue surrounding them, and React, the most popular front-end JavaScript library." + ] + }, + "workshop-reusable-mega-navbar": { + "title": "Build a Reusable Mega Navbar", + "intro": [ + "In the previous lessons, you learned how to work with components in React.", + "In this workshop, you will build a reusable Navbar component using React." + ] + }, + "lab-reusable-footer": { + "title": "Build a Reusable Footer", + "intro": ["In this lab, you'll use React to build a reusable footer."] + }, + "lecture-working-with-data-in-react": { + "title": "Working with Data in React", + "intro": [ + "In these lessons, you will learn how to work with data in React. You will learn about props and how to pass them around, conditional rendering, how to render lists, and how to use inline styles." + ] + }, + "workshop-reusable-profile-card-component": { + "title": "Build a Reusable Profile Card Component", + "intro": [ + "In this workshop, you will learn how to work with props by building a reusable profile card component." + ] + }, + "lab-mood-board": { + "title": "Build a Mood Board", + "intro": [ + "In this lab, you'll create a mood board using React.", + "You'll practice how to pass data from a parent component to a child component using props." + ] + }, + "review-react-basics": { + "title": "React Basics Review", + "intro": [ + "Review basic React concepts to prepare for the upcoming quiz." + ] + }, + "quiz-react-basics": { + "title": "React Basics Quiz", + "intro": ["Test your knowledge of React basics with this quiz."] + }, + "lecture-working-with-state-and-responding-to-events-in-react": { + "title": "Working with State and Responding to Events in React", + "intro": [ + "In these lessons, you will learn about working with state and responding to events with React." + ] + }, + "workshop-toggle-text-app": { + "title": "Toggle Text App", + "intro": [ + "In this workshop, you will continue to learn about the useState() hook by building an application that hides and shows a piece of text on the screen." + ] + }, + "lab-color-picker": { + "title": "Build a Color Picker App", + "intro": [ + "In this lab you'll build a Color Picker.", + "You'll practice using state and hooks to manage the properties of an element." + ] + }, + "lecture-understanding-effects-and-referencing-values-in-react": { + "title": "Understanding Effects and Referencing Values in React", + "intro": [ + "In these lessons, you will learn about effects and referencing values with React." + ] + }, + "workshop-fruit-search-app": { + "title": "Build a Fruit Search App", + "intro": [ + "In this workshop, you will continue to learn about the useEffect() hook by building an application that fetches fruit data from an API based on user input and displays the results dynamically." + ] + }, + "lab-one-time-password-generator": { + "title": "Build a One-Time Password Generator", + "intro": [ + "In this lab you'll build a one-time password generator.", + "You'll practice using the useEffect hooks to create a timer and generate a random OTP." + ] + }, + "review-react-state-and-hooks": { + "title": "React State and Hooks Review", + "intro": [ + "Before you're quizzed on React state and hooks, you should review what you've learned.", + "Open up this page to review working with state, custom hooks and more." + ] + }, + "quiz-react-state-and-hooks": { + "title": "React State and Hooks Quiz", + "intro": [ + "Test what you've learned about React's useState and useEffect hooks with this quiz." + ] + }, + "lecture-working-with-forms-in-react": { + "title": "Working with Forms in React", + "intro": [ + "In these lessons, you will learn about working with forms in React." + ] + }, + "workshop-superhero-application-form": { + "title": "Build a Superhero Application Form", + "intro": [ + "In this workshop, you will build a superhero application form." + ] + }, + "lab-event-rsvp": { + "title": "Build an Event RSVP", + "intro": [ + "In this lab, you'll build an Event RSVP form using React.", + "You'll practice using the useState hook to manage form input and display user responses." + ] + }, + "lecture-working-with-data-fetching-and-memoization-in-react": { + "title": "Working with Data Fetching and Memoization in React", + "intro": [ + "In these lessons, you will learn about data fetching and memoization in React." + ] + }, + "workshop-shopping-list-app": { + "title": "Build a Shopping List App", + "intro": [ + "In this workshop, you'll use the useMemo() and useCallback() hooks in React to build a simple shopping list app. You'll learn more about state and the lifecycle of React components, and how to use memoization to reduce re-renders and make your apps more efficient." + ] + }, + "lecture-routing-react-frameworks-and-dependency-management-tools": { + "title": "Routing, React Frameworks, and Dependency Management Tools", + "intro": [ + "In these lessons, you will learn about routing in React, React frameworks, and dependency management tools." + ] + }, + "lecture-react-strategies-and-debugging": { + "title": "React Strategies and Debugging", + "intro": [ + "In these lessons, you will learn about different strategies and debugging in React." + ] + }, + "review-react-forms-data-fetching-and-routing": { + "title": "React Forms, Data Fetching and Routing Review", + "intro": [ + "Before you take the React forms, data fetching and routing quiz, you should review everything you've learned so far.", + "Open up this page, to review all of the concepts taught including routing, forms, state management, prop drilling, data fetching and more." + ] + }, + "quiz-react-forms-data-fetching-and-routing": { + "title": "React Forms, Data Fetching and Routing Quiz", + "intro": [ + "Test what you've learned about routing, forms, and data fetching with this quiz." + ] + }, + "lab-currency-converter": { + "title": "Build a Currency Converter", + "intro": [ + "For this lab, you'll build a currency converter app.", + "You'll use React state, memoization, and controlled components to convert between currencies." + ] + }, + "lab-tic-tac-toe": { + "title": "Build a Tic-Tac-Toe Game", + "intro": [ + "In this lab, you'll build a Tic-Tac-Toe game using React.", + "You'll practice managing state, handling user interactions, and updating the UI dynamically." + ] + }, + "lecture-understanding-performance-in-web-applications": { + "title": "Understanding Performance in Web Applications", + "intro": [ + "In these lessons, you will learn performance in web applications." + ] + }, + "review-web-performance": { + "title": "Web Performance Review", + "intro": [ + "Before you take the web performance quiz, you should review everything you've learned so far.", + "Open up this page to review all of the concepts taught including INP, key metrics for measuring performance, Performance Web APIs and more." + ] + }, + "quiz-web-performance": { + "title": "Web Performance Quiz", + "intro": [ + "Test what you've learned about Web Performance with this quiz." + ] + }, + "lecture-understanding-the-different-types-of-testing": { + "title": "Understanding the Different Types of Testing", + "intro": [ + "In these lessons, you will learn about the different types of testing." + ] + }, + "review-testing": { + "title": "Testing Review", + "intro": [ + "Before you take the testing quiz, you should review everything you've learned so far.", + "Open up this page to review all of the concepts taught including unit testing, end-to-end testing, functional testing and more." + ] + }, + "quiz-testing": { + "title": "Testing Quiz", + "intro": ["Test what you've learned on testing with this quiz."] + }, + "lecture-working-with-css-libraries-and-frameworks": { + "title": "Working with CSS Libraries and Frameworks", + "intro": [ + "In these lessons, you will learn how to work with CSS libraries and frameworks." + ] + }, + "workshop-error-message-component": { + "title": "Build an Error Message Component", + "intro": [ + "In this workshop, you will learn the basics of Tailwind CSS by building out an error message component." + ] + }, + "workshop-tailwind-cta-component": { + "title": "Build a CTA Component", + "intro": [ + "In this workshop, you will build a call to action (CTA) component using Tailwind CSS." + ] + }, + "workshop-tailwind-pricing-component": { + "title": "Build a Pricing Component", + "intro": [ + "In this workshop, you will build a pricing component using Tailwind CSS.", + "You will practice working with Tailwind CSS grid utility classes." + ] + }, + "lab-music-shopping-cart-page": { + "title": "Build a Music Shopping Cart Page", + "intro": [ + "In this lab, you will build a music shopping cart page with Tailwind CSS.", + "You will practice working with Tailwind CSS utility classes for flexbox layouts, colors, breakpoints and more." + ] + }, + "review-css-libraries-and-frameworks": { + "title": "CSS Libraries and Frameworks Review", + "intro": [ + "Before you take the CSS libraries and frameworks quiz, you should review everything you've learned so far.", + "Open up this page to review all of the concepts taught including CSS frameworks, CSS preprocessors, Sass and more." + ] + }, + "quiz-css-libraries-and-frameworks": { + "title": "CSS Libraries and Frameworks Quiz", + "intro": [ + "Test what you've learned about CSS Libraries and Frameworks with this quiz." + ] + }, + "lab-photography-exhibit": { + "title": "Design a Photography Exhibit", + "intro": [ + "In this lab, you will practice working with Tailwind CSS by designing a photography exhibit webpage." + ] + }, + "lecture-introduction-to-typescript": { + "title": "Introduction to TypeScript", + "intro": [ + "In these lessons, you will learn what TypeScript is and how to use it." + ] + }, + "workshop-type-safe-user-profile": { + "title": "Build a Type Safe User Profile", + "intro": [ + "In this workshop, you will practice working with type annotations, array types, object types and more by building out a user profile." + ] + }, + "workshop-type-safe-math-toolkit": { + "title": "Build a Type Safe Math Toolkit", + "intro": [ + "In this workshop, you will practice typing functions by building a math toolkit project." + ] + }, + "lecture-understanding-type-composition": { + "title": "Understanding Type Composition", + "intro": [ + "In these lessons, you will learn how to work with union types, interfaces, void types and more." + ] + }, + "workshop-shape-manager": { + "title": "Build a Shape Manager", + "intro": [ + "In this workshop, you will practice basic TypeScript features like types and interfaces by building a shape manager program." + ] + }, + "lab-motorcycle-shop": { + "title": "Build a Motorcycle Shop", + "intro": [ + "For this lab, you will use TypeScript to build a Motorcycle Shop." + ] + }, + "lecture-working-with-generics-and-type-narrowing": { + "title": "Working with Generics and Type Narrowing", + "intro": [ + "In these lessons, you will learn about generics and type narrowing in TypeScript." + ] + }, + "workshop-bug-emoji-picker": { + "title": "Build a Bug Emoji Picker", + "intro": [ + "In this workshop, you will learn about TypeScript abstract classes and generics by building a bug species selector that displays different bug emojis." + ] + }, + "lab-product-showcase": { + "title": "Build a Product Showcase", + "intro": [ + "In this lab, you will practice generics and type narrowing in TypeScript." + ] + }, + "lecture-working-with-typescript-configuration-files": { + "title": "Working with TypeScript Configuration Files", + "intro": [ + "In this lesson, you will learn about TypeScript configuration files and how to use them." + ] + }, + "workshop-fortune-teller-app": { + "title": "Build a Fortune Telling App", + "intro": [ + "In this workshop, you will continue to practice working with TypeScript by building a fortune telling app." + ] + }, + "workshop-build-a-football-player-card-builder": { + "title": "Build a Football Player Card Builder", + "intro": [ + "In this workshop, you'll learn how to work with React in TypeScript by building a football player card builder." + ] + }, + "review-typescript": { + "title": "TypeScript Review", + "intro": [ + "Before you take the TypeScript quiz, you should review everything you've learned so far.", + "Open up this page to review all of the concepts taught including data types in TypeScript, generics, type narrowing and more." + ] + }, + "quiz-typescript": { + "title": "TypeScript Quiz", + "intro": ["Test what you've learned on TypeScript with this quiz."] + }, + "lab-flashcard-quiz-app": { + "title": "Build a Flashcard Quiz App", + "intro": [ + "In this lab, you will practice using TypeScript by building a flashcard quiz app." + ] + }, + "lab-digital-pet-game": { + "title": "Build a Digital Pet Game", + "intro": [ + "In this lab, you'll practice what you learned about TypeScript and React by building a digital pet game." + ] + }, + "review-front-end-libraries": { + "title": "Front-End Libraries Review", + "intro": [ + "Review the Front-End Libraries concepts to prepare for the upcoming quiz." + ] + }, + "exam-front-end-development-libraries-certification": { + "title": "Front-End Development Libraries Certification Exam", + "intro": [ + "Pass this exam to earn your Front-End Development Libraries Certification" + ] + } + } + }, + "python-v9": { + "title": "Python Certification", + "intro": [ + "This course teaches you the fundamentals of Python programming.", + "To earn your Python Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the Python Certification exam." + ], + "chapters": { + "python": "Python", + "python-certification-exam": "Python Certification Exam" + }, + "modules": { + "python-basics": "Python Basics", + "python-installation": "Install Python", + "python-loops-and-sequences": "Loops and Sequences", + "python-dictionaries-and-sets": "Dictionaries and Sets", + "lab-user-configuration-manager": "Build a User Configuration Manager", + "python-error-handling": "Error Handling", + "python-classes-and-objects": "Classes and Objects", + "lab-budget-app": "Build a Budget App", + "python-object-oriented-programming": "Object-Oriented Programming (OOP)", + "lab-polygon-area-calculator": "Build a Polygon Area Calculator", + "python-linear-data-structures": "Linear Data Structures", + "lab-hash-table": "Build a Hash Table", + "python-recursion": "Recursion", + "python-algorithms": "Algorithms", + "lab-tower-of-hanoi": "Implement the Tower of Hanoi Algorithm", + "python-graphs-and-trees": "Graphs and Trees", + "python-dynamic-programming": "Dynamic Programming", + "review-python": "Python Review", + "python-certification-exam": "Python Certification Exam" + }, + "blocks": { + "lecture-introduction-to-python": { + "title": "Introduction to Python", + "intro": [ + "In these lessons, you will learn what Python is and common uses in the industry." + ] + }, + "lecture-understanding-variables-and-data-types": { + "title": "Understanding Variables and Data Types", + "intro": [ + "In these lessons, you will learn about variables and data types in Python." + ] + }, + "workshop-report-card-printer": { + "title": "Build a Report Card Printer", + "intro": [ + "In this workshop, you will practice working with primitive data types in Python by creating and printing data for a simple report card." + ] + }, + "lecture-introduction-to-python-strings": { + "title": "Introduction to Strings", + "intro": ["In these lessons, you will learn about strings in Python."] + }, + "workshop-employee-profile-generator": { + "title": "Build an Employee Profile Generator", + "intro": [ + "In this workshop, you will practice the fundamentals of string manipulation in Python by building a tool that generates formatted employee badges and analyzes employee codes." + ] + }, + "lecture-numbers-and-mathematical-operations": { + "title": "Numbers and Mathematical Operations", + "intro": [ + "In these lessons, you will learn about numbers and mathematical operations in Python." + ] + }, + "workshop-bill-splitter": { + "title": "Build a Bill Splitter", + "intro": [ + "In this workshop you will build a bill splitter to practice working with numbers and mathematical operations in Python" + ] + }, + "lecture-booleans-and-conditionals": { + "title": "Booleans and Conditionals", + "intro": [ + "In these lessons, you will learn about booleans and conditionals in Python." + ] + }, + "workshop-movie-ticket-booking-calculator": { + "title": "Build a Movie Ticket Booking Calculator", + "intro": [ + "In this workshop, you will practice how to use booleans and conditional statements in Python by building a movie ticket booking calculator." + ] + }, + "lab-travel-weather-planner": { + "title": "Build a Travel Weather Planner", + "intro": [ + "In this lab, you will build a travel weather planner using conditionals." + ] + }, + "lecture-understanding-functions-and-scope": { + "title": "Understanding Functions and Scope", + "intro": [ + "In these lessons, you will learn about functions and scope in Python." + ] + }, + "lab-discount-calculator": { + "title": "Build an Apply Discount Function", + "intro": [ + "In this lab, you will practice basic Python by building a calculator to apply a discount to a price." + ] + }, + "workshop-caesar-cipher": { + "title": "Build a Caesar Cipher", + "intro": [ + "In this workshop, you'll build a Caesar cipher using basic Python concepts such as strings, conditionals, functions, and more." + ] + }, + "lab-rpg-character": { + "title": "Build an RPG Character", + "intro": [ + "In this lab you will practice basic python by building an RPG character." + ] + }, + "review-python-basics": { + "title": "Python Basics Review", + "intro": [ + "Before you're quizzed on Python basics, you should review what you've learned about it.", + "In this review page, you will review working with strings, functions, comparison operators and more." + ] + }, + "quiz-python-basics": { + "title": "Python Basics Quiz", + "intro": [ + "Test what you've learned about Python basics with this quiz." + ] + }, + "lecture-python-installation": { + "title": "Installing Python and Running Code Locally", + "intro": [ + "In these lessons, you will learn how to install Python on your local device and run code locally." + ] + }, + "review-python-installation": { + "title": "Python Installation Review", + "intro": [ + "Before you are quizzed on working with Python locally, you should review the concepts covered in the lessons." + ] + }, + "quiz-python-installation": { + "title": "Python Installation Quiz", + "intro": [ + "Test what you've learned about installing Python locally with this quiz." + ] + }, + "lecture-working-with-loops-and-sequences": { + "title": "Working with Loops and Sequences", + "intro": [ + "Learn about working with loops and sequences in these lessons." + ] + }, + "workshop-pin-extractor": { + "title": "Build a Pin Extractor", + "intro": [ + "In this workshop you will build a function to extract secret pins hidden in poems." + ] + }, + "lab-number-pattern-generator": { + "title": "Build a Number Pattern Generator", + "intro": ["In this lab you will build a number pattern generator."] + }, + "review-loops-and-sequences": { + "title": "Loops and Sequences Review", + "intro": [ + "Before you're quizzed on loops and sequences, you should review what you've learned about them.", + "Open up this page to review concepts around loops, lists, tuples and some of their common methods." + ] + }, + "quiz-loops-and-sequences": { + "title": "Loops and Sequences Quiz", + "intro": [ + "Test what you've learned about loops and sequences in Python with this quiz." + ] + }, + "lecture-working-with-dictionaries-and-sets": { + "title": "Working with Dictionaries and Sets", + "intro": [ + "Learn about working with dictionaries and sets in these lessons." + ] + }, + "lecture-working-with-modules": { + "title": "Working with Modules", + "intro": ["Learn about working with modules in these lessons."] + }, + "workshop-medical-data-validator": { + "title": "Build a Medical Data Validator", + "intro": [ + "In this workshop, you'll practice working with dictionaries and sets while validating a collection of medical data." + ] + }, + "review-dictionaries-and-sets": { + "title": "Dictionaries and Sets review", + "intro": [ + "Before you're quizzed on dictionaries and sets, you should review what you've learned about them.", + "Open up this page to review concepts around dictionaries, sets, and how to import modules." + ] + }, + "quiz-dictionaries-and-sets": { + "title": "Dictionaries and Sets Quiz", + "intro": [ + "Test what you've learned about dictionaries and sets in Python with this quiz." + ] + }, + "lab-user-configuration-manager": { + "title": "Build a User Configuration Manager", + "intro": [ + "In this lab, you will practice working with dictionaries in Python." + ] + }, + "lecture-understanding-error-handling": { + "title": "Understanding Error Handling", + "intro": [ + "In these lessons, you will learn about error handling in Python. You will learn about the different types of errors, some good debugging practices, what exceptions are, and how to handle them." + ] + }, + "lab-isbn-validator": { + "title": "Debug an ISBN Validator", + "intro": [ + "In this lab, you will start with a bugged app, and you will need to debug and fix the bugs until it is working properly." + ] + }, + "review-error-handling": { + "title": "Error Handling Review", + "intro": [ + "Before you're quizzed on error handling, you should review what you've learned about it." + ] + }, + "quiz-error-handling": { + "title": "Error Handling Quiz", + "intro": [ + "Test what you've learned about Error Handling in Python with this quiz." + ] + }, + "lecture-classes-and-objects": { + "title": "Classes and Objects", + "intro": ["Learn about classes and objects in these lessons."] + }, + "workshop-musical-instrument-inventory": { + "title": "Build a Musical Instrument Inventory", + "intro": [ + "In this workshop, you will learn about classes, objects, and methods in Python by building a simple musical instrument inventory." + ] + }, + "lab-planet-class": { + "title": "Build a Planet Class", + "intro": [ + "In this lab you will create a class that represents a planet." + ] + }, + "workshop-email-simulator": { + "title": "Build an Email Simulator", + "intro": [ + "In this workshop you will implement classes and objects by building an email simulator that simulates sending, receiving, and managing emails between different users." + ] + }, + "review-classes-and-objects": { + "title": "Classes and Objects Review", + "intro": [ + "Before you're quizzed on classes and objects, you should review what you've learned about them.", + "Open up this page to review concepts like how classes work, what are objects, methods, attributes, special methods and more." + ] + }, + "quiz-classes-and-objects": { + "title": "Classes and Objects Quiz", + "intro": [ + "Test what you've learned about classes and objects in Python with this quiz." + ] + }, + "lab-budget-app": { + "title": "Build a Budget App", + "intro": [ + "In this lab you will build a budget app and practice creating a class and methods for that class." + ] + }, + "lecture-understanding-object-oriented-programming-and-encapsulation": { + "title": "Understanding Object Oriented Programming and Encapsulation", + "intro": [ + "Learn about understanding object oriented programming and encapsulation in these lessons." + ] + }, + "workshop-salary-tracker": { + "title": "Build a Salary Tracker", + "intro": [ + "In this workshop, you'll practice encapsulation, properties, and other OOP concepts by building a salary tracking system for employees." + ] + }, + "lab-game-character-stats": { + "title": "Build a Game Character Stats Tracker", + "intro": [ + "In this lab, you will build a game character with different stats using object-oriented programming." + ] + }, + "lecture-understanding-inheritance-and-polymorphism": { + "title": "Understanding Inheritance and Polymorphism", + "intro": [ + "Learn about understanding inheritance and polymorphism in these lessons." + ] + }, + "workshop-media-catalogue": { + "title": "Build a Media Catalogue", + "intro": [ + "In this workshop, you will create a media catalogue application using object-oriented programming principles." + ] + }, + "lecture-understanding-abstraction": { + "title": "Understanding Abstraction", + "intro": ["Learn about understanding abstraction in these lessons."] + }, + "workshop-discount-calculator": { + "title": "Build a Discount Calculator", + "intro": [ + "In this workshop you will build a flexible discount pricing calculator through abstract base classes, allowing multiple discount algorithms to be applied interchangeably without modifying the core logic." + ] + }, + "lab-player-interface": { + "title": "Build a Player Interface", + "intro": [ + "In this lab, you'll use the abc module to build a player interface." + ] + }, + "review-object-oriented-programming": { + "title": "Object Oriented Programming Review", + "intro": [ + "Before you're quizzed on object oriented programming, you should review what you've learned about it." + ] + }, + "quiz-object-oriented-programming": { + "title": "Object Oriented Programming Quiz", + "intro": [ + "Test what you've learned about object oriented programming in python with this quiz." + ] + }, + "lab-polygon-area-calculator": { + "title": "Build a Polygon Area Calculator", + "intro": [ + "In this lab, you will use object-oriented programming to calculate the areas of different polygons like squares and rectangles." + ] + }, + "lecture-working-with-common-data-structures": { + "title": "Working with Common Data Structures", + "intro": [ + "Learn about working with common data structures in these lessons." + ] + }, + "workshop-linked-list-class": { + "title": "Build a Linked List", + "intro": [ + "In this workshop, you'll practice working with data structures by building a linked list." + ] + }, + "review-data-structures": { + "title": "Data Structures Review", + "intro": [ + "Before you're quizzed on data structures, you should review what you've learned about them.", + "Open up this page to review concepts like the different data structures, algorithms, time and space complexity, and big O notation." + ] + }, + "quiz-data-structures": { + "title": "Data Structures Quiz", + "intro": [ + "Test what you've learned about data structures in Python with this quiz." + ] + }, + "lab-hash-table": { + "title": "Build a Hash Table", + "intro": [ + "A hash table is a data structure that is used to store key-value pairs and is optimized for quick lookups.", + "In this lab, you will use your knowledge about data structures to build a hash table." + ] + }, + "lecture-understanding-recursion-and-the-call-stack-python": { + "title": "Understanding Recursion and the Call Stack", + "intro": [ + "In this lecture, you will learn how recursive functions and the call stack work in Python." + ] + }, + "workshop-countup-python": { + "title": "Build a Countup Function", + "intro": [ + "In this workshop, you will build a function that uses recursion to create a list of numbers." + ] + }, + "lab-range-of-numbers-python": { + "title": "Build a Range of Numbers Generator", + "intro": [ + "In this lab, you will use recursion to generate a list of numbers within a specified range." + ] + }, + "review-recursion-python": { + "title": "Review Recursion", + "intro": [ + "Review the concepts of recursion, base cases, and the call stack." + ] + }, + "quiz-recursion-python": { + "title": "Recursion Quiz", + "intro": [ + "Test your understanding of recursion, base cases, and the call stack." + ] + }, + "lecture-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms", + "intro": [ + "Learn about fundamental searching and sorting algorithms, including linear search, binary search, and merge sort.", + "These lessons cover algorithm implementations, time and space complexity analysis, and the divide and conquer programming paradigm." + ] + }, + "workshop-binary-search": { + "title": "Implement the Binary Search Algorithm", + "intro": [ + "The binary search algorithm is a searching algorithm used to find a target item in a sorted list.", + "In this workshop, you'll implement the binary search algorithm and return the path it took to find the target or return 'Value not found'." + ] + }, + "lab-bisection-method": { + "title": "Implement the Bisection Method", + "intro": [ + "In this lab, you will implement the bisection method to find the square root of a number." + ] + }, + "workshop-merge-sort": { + "title": "Implement the Merge Sort Algorithm", + "intro": [ + "The merge sort algorithm is a sorting algorithm based on the divide and conquer principle.", + "In this workshop, you'll implement the merge sort algorithm to sort a list of random numbers." + ] + }, + "lab-quicksort": { + "title": "Implement the Quicksort Algorithm", + "intro": [ + "In this lab you will implement the quicksort algorithm to sort a list of integers." + ] + }, + "lab-selection-sort": { + "title": "Implement the Selection Sort Algorithm", + "intro": [ + "In this lab you will implement the selection sort algorithm." + ] + }, + "lab-luhn-algorithm": { + "title": "Implement the Luhn Algorithm", + "intro": [ + "In this lab, you will implement the Luhn algorithm to validate identification numbers such as credit card numbers." + ] + }, + "review-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms Review", + "intro": [ + "Before you're quizzed on searching and sorting algorithms, you should review what you've learned about them." + ] + }, + "quiz-searching-and-sorting-algorithms": { + "title": "Searching and Sorting Algorithms Quiz", + "intro": [ + "Test what you've learned about searching and sorting algorithms in Python with this quiz." + ] + }, + "lab-tower-of-hanoi": { + "title": "Implement the Tower of Hanoi Algorithm", + "intro": [ + "In this lab, you will implement an algorithm to solve the Tower of Hanoi puzzle." + ] + }, + "lecture-understanding-graphs-and-trees": { + "title": "Understanding Graphs and Trees", + "intro": [ + "In this lesson, you will learn about fundamental data structures like graphs, trees, and their practical applications in computer science." + ] + }, + "workshop-shortest-path-algorithm": { + "title": "Implement the Shortest Path Algorithm", + "intro": [ + "In this workshop you will implement an algorithm to find the shortest path between two nodes in a graph." + ] + }, + "lab-adjacency-list-to-matrix-converter": { + "title": "Build an Adjacency List to Matrix Converter", + "intro": [ + "In this lab, you will implement a function that converts an adjacency list representation of a graph into an adjacency matrix representation." + ] + }, + "workshop-breadth-first-search": { + "title": "Implement the Breadth-First Search Algorithm", + "intro": [ + "In this workshop, you will use the bread-first search algorithm to generate all valid combinations of parentheses." + ] + }, + "lab-depth-first-search": { + "title": "Implement the Depth-First Search Algorithm", + "intro": [ + "In this lab, you will implement the Depth-First Search Algorithm." + ] + }, + "lab-n-queens-problem": { + "title": "Implement the N-Queens Algorithm", + "intro": [ + "In this lab, you will implement a solution for the N-Queens problem." + ] + }, + "review-graphs-and-trees": { + "title": "Graphs and Trees Review", + "intro": [ + "Before you're quizzed on graphs and trees, you should review what you've learned about them." + ] + }, + "quiz-graphs-and-trees": { + "title": "Graphs and Trees Quiz", + "intro": [ + "Test what you've learned about graphs and trees in Python with this quiz." + ] + }, + "lecture-understanding-dynamic-programming": { + "title": "Understanding Dynamic Programming", + "intro": [ + "In this lesson, you will learn about dynamic programming, an algorithmic technique used to solve complex problems efficiently by breaking them down into simpler subproblems." + ] + }, + "lab-nth-fibonacci-number": { + "title": "Build an Nth Fibonacci Number Calculator", + "intro": [ + "In this lab you will implement a Fibonacci sequence calculator using a dynamic programming approach." + ] + }, + "review-dynamic-programming": { + "title": "Dynamic Programming Review", + "intro": [ + "Before you're quizzed on dynamic programming, you should review what you've learned about it." + ] + }, + "quiz-dynamic-programming": { + "title": "Dynamic Programming Quiz", + "intro": [ + "Test what you've learned about dynamic programming in python with this quiz." + ] + }, + "review-python": { + "title": "Python Review", + "intro": ["Review Python concepts to prepare for the upcoming exam."] + }, + "exam-python-certification": { + "title": "Python Certification Exam", + "intro": ["Pass this exam to earn your Python Certification"] + } + } + }, + "relational-databases-v9": { + "title": "Relational Databases Certification", + "intro": [ + "This course teaches you the fundamentals of relational databases.", + "To earn your Relational Databases Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the Relational Databases Certification exam." + ], + "chapters": { + "relational-databases": "Relational Databases", + "relational-databases-certification-exam": "Relational Databases Certification Exam" + }, + "modules": { + "code-editors": "Code Editors", + "bash-fundamentals": "Bash Fundamentals", + "sql-and-postgresql": "SQL and PostgreSQL", + "lab-celestial-bodies-database": "Build a Celestial Bodies Database", + "bash-scripting": "Bash Scripting", + "sql-and-bash": "SQL and Bash", + "lab-world-cup-database": "Build a World Cup Database", + "lab-salon-appointment-scheduler": "Build a Salon Appointment Scheduler", + "git": "Git", + "lab-periodic-table-database": "Build a Periodic Table Database", + "lab-number-guessing-game": "Build a Number Guessing Game", + "review-relational-databases": "Relational Databases Review", + "relational-databases-certification-exam": "Relational Databases Certification Exam" + }, + "blocks": { + "lecture-working-with-code-editors-and-ides": { + "title": "Working with Code Editors and IDEs", + "intro": [ + "In these lessons, you will learn how to work with code editors and IDEs. You will learn various concepts about the most popular code editor, VS Code such as its installation, how to create a project in it, keyboard shortcuts, and extensions." + ] + }, + "lecture-understanding-the-command-line-and-working-with-bash": { + "title": "Understanding the Command Line and Working with Bash", + "intro": [ + "Learn about the Command Line and Working with Bash in these lessons." + ] + }, + "workshop-bash-boilerplate": { + "title": "Build a Boilerplate", + "intro": [ + "The terminal allows you to send text commands to your computer that can manipulate the file system, run programs, automate tasks, and much more.", + "In this 170-lesson workshop, you will learn terminal commands by creating a website boilerplate using only the command line." + ] + }, + "review-bash-commands": { + "title": "Bash Commands Review", + "intro": [ + "Review the Bash Commands concepts to prepare for the upcoming quiz." + ] + }, + "quiz-bash-commands": { + "title": "Bash Commands Quiz", + "intro": ["Test what you've learned bash commands with this quiz."] + }, + "lecture-working-with-relational-databases": { + "title": "Working with Relational Databases", + "intro": [ + "Learn how to work with Relational Databases in these lessons." + ] + }, + "workshop-database-of-video-game-characters": { + "title": "Build a Database of Video Game Characters", + "intro": [ + "A relational database organizes data into tables that are linked together through relationships.", + "In this 165-lesson workshop, you will learn the basics of a relational database by creating a PostgreSQL database filled with video game characters." + ] + }, + "review-sql-and-postgresql": { + "title": "SQL and PostgreSQL Review", + "intro": [ + "Review SQL and PostgreSQL concepts to prepare for the upcoming quiz." + ] + }, + "quiz-sql-and-postgresql": { + "title": "SQL and PostgreSQL Quiz", + "intro": [ + "Test what you've learned about SQL and PostgreSQL with this quiz." + ] + }, + "lab-celestial-bodies-database": { + "title": "Build a Celestial Bodies Database", + "intro": [ + "For this project, you will build a database of celestial bodies using PostgreSQL." + ] + }, + "lecture-understanding-bash-scripting": { + "title": "Understanding Bash Scripting", + "intro": ["Learn about Bash Scripting in these lessons."] + }, + "workshop-bash-five-programs": { + "title": "Build Five Programs", + "intro": [ + "Bash scripts combine terminal commands and logic into programs that can execute or automate tasks, and much more.", + "In this 220-lesson workshop, you will learn more terminal commands and how to use them within Bash scripts by creating five small programs." + ] + }, + "review-bash-scripting": { + "title": "Bash Scripting Review", + "intro": [ + "Review the bash scripting concepts you've learned to prepare for the upcoming quiz." + ] + }, + "quiz-bash-scripting": { + "title": "Bash Scripting Quiz", + "intro": ["Test what you've learned on bash scripting in this quiz."] + }, + "lecture-working-with-sql": { + "title": "Working With SQL", + "intro": [ + "In these lessons, you will learn about SQL injection, normalization, and the N+1 problem." + ] + }, + "workshop-sql-student-database-part-1": { + "title": "Build a Student Database: Part 1", + "intro": [ + "SQL, or Structured Query Language, is the language for communicating with a relational database.", + "In this 140-lesson workshop, you will create a Bash script that uses SQL to enter information about your computer science students into PostgreSQL." + ] + }, + "workshop-sql-student-database-part-2": { + "title": "Build a Student Database: Part 2", + "intro": [ + "SQL join commands are used to combine information from multiple tables in a relational database", + "In this 140-lesson workshop, you will complete your student database while diving deeper into SQL commands." + ] + }, + "workshop-kitty-ipsum-translator": { + "title": "Build a Kitty Ipsum Translator", + "intro": [ + "There's more to Bash commands than you might think.", + "In this 140-lesson workshop, you will learn some more complex commands, and the details of how commands work." + ] + }, + "workshop-bike-rental-shop": { + "title": "Build a Bike Rental Shop", + "intro": [ + "In this 210-lesson workshop, you will build an interactive Bash program that stores rental information for your bike rental shop using PostgreSQL." + ] + }, + "review-bash-and-sql": { + "title": "Bash and SQL Review", + "intro": [ + "Review the Bash and SQL concepts to prepare for the upcoming quiz." + ] + }, + "quiz-bash-and-sql": { + "title": "Bash and SQL Quiz", + "intro": ["Test what you've learned in this quiz on Bash and SQL."] + }, + "lab-world-cup-database": { + "title": "Build a World Cup Database", + "intro": [ + "For this project, you will create a Bash script that enters information from World Cup games into PostgreSQL, then query the database for useful statistics." + ] + }, + "lab-salon-appointment-scheduler": { + "title": "Build a Salon Appointment Scheduler", + "intro": [ + "For this lab, you will create an interactive Bash program that uses PostgreSQL to track the customers and appointments for your salon." + ] + }, + "lecture-working-with-nano": { + "title": "Working With Nano", + "intro": ["Learn about Nano in this lesson."] + }, + "workshop-castle": { + "title": "Build a Castle", + "intro": [ + "Nano is a program that allows you to edit files right in the terminal.", + "In this 40-lesson workshop, you will learn how to edit files in the terminal with Nano while building a castle." + ] + }, + "lecture-introduction-to-git-and-github": { + "title": "Introduction to Git and GitHub", + "intro": ["Learn how to work with Git and GitHub in these lessons."] + }, + "lecture-working-with-code-reviews-branching-deployment-and-ci-cd": { + "title": "Working With Code Reviews, Branching, Deployment, and CI/CD", + "intro": [ + "Learn about code reviews, branching, deployment, and CI/CD in these lessons." + ] + }, + "workshop-sql-reference-object": { + "title": "Build an SQL Reference Object", + "intro": [ + "Git is a version control system that keeps track of all the changes you make to your codebase.", + "In this 240-lesson workshop, you will learn how Git keeps track of your code by creating an object containing commonly used SQL commands." + ] + }, + "review-git": { + "title": "Git Review", + "intro": ["Review Git concepts to prepare for the upcoming quiz."] + }, + "quiz-git": { + "title": "Git Quiz", + "intro": ["Test what you've learned on Git with this quiz."] + }, + "lab-periodic-table-database": { + "title": "Build a Periodic Table Database", + "intro": [ + "For this lab, you will create a Bash script to get information about chemical elements from a periodic table database." + ] + }, + "lab-number-guessing-game": { + "title": "Build a Number Guessing Game", + "intro": [ + "For this lab, you will use Bash scripting, PostgreSQL, and Git to create a number guessing game that runs in the terminal and saves user information." + ] + }, + "review-relational-databases": { + "title": "Relational Databases Review", + "intro": [ + "Review relational databases concepts to prepare for the exam." + ] + }, + "exam-relational-databases-certification": { + "title": "Relational Databases Certification Exam", + "intro": [ + "Pass this exam to earn your Relational Databases Certification" + ] + } + } + }, + "back-end-development-and-apis-v9": { + "title": "Back-End Development and APIs Certification", + "intro": [ + "This course teaches you the fundamentals of back-end development and APIs.", + "To earn your Back-End Development and APIs Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the Back-End Development and APIs Certification exam." + ], + "note": "", + "chapters": { + "back-end-development-and-apis": "Back-End Development and APIs", + "back-end-development-and-apis-certification-exam": "Back-End Development and APIs Certification Exam" + }, + "modules": { + "introduction-to-nodejs": "Introduction to Node.js", + "nodejs-core-modules": "Node.js Core Modules", + "node-package-manager": "Node Package Manager", + "lab-prime-number-checker-module": "Build a Prime Number Checker Module", + "http-and-the-web-standards-model": "HTTP and the Web Standards Model", + "introduction-to-express": "Introduction to Express", + "lab-personal-profile-app": "Build a Personal Profile App", + "express-middleware": "Express Middleware", + "rest-api-and-web-services": "REST API and Web Services", + "lab-timestamp-microservice": "Build a Timestamp Microservice", + "error-handling-in-express": "Error Handling in Express", + "websockets": "WebSockets", + "lab-chat-app": "Build a Chat App", + "security-and-privacy": "Security and Privacy", + "authentication": "Authentication", + "lab-family-movie-watchlist-api": "Build a Family Movie Watchlist API", + "review-back-end-development-and-apis": "Back-End Development and APIs Review", + "back-end-development-and-apis-certification-exam": "Back-End Development and APIs Certification Exam" + }, + "blocks": { + "lecture-working-with-nodejs-and-event-driven-architecture": { + "title": "Working with Node.js and Event-Driven Architecture", + "intro": [ + "Learn about Node.js core libraries, how to install Node.js on your computer, and the advantages and disadvantages of using Node.js on the back-end." + ] + }, + "workshop-nodejs-repl": { + "title": "Learn Node.js REPL", + "intro": [ + "You will learn the Node.js REPL and command-line interface by exploring the runtime from the terminal." + ] + }, + "review-node-js-intro": { + "title": "NodeJS Intro Review", + "intro": [ + "Review the basics of NodeJS to prepare for the upcoming quiz." + ] + }, + "quiz-node-js-intro": { + "title": "NodeJS Intro Quiz", + "intro": ["Test what you have learned about NodeJS in this quiz."] + }, + "lecture-working-with-node-core-modules": { + "title": "Working with Node Core Modules", + "intro": [ + "Learn about the node.js core modules, such as fs, buffer, stream, path modules, and more, so you can understand what Node gives you out of the box to build efficient applications without relying on third-party libraries." + ] + }, + "workshop-build-a-file-processor": { + "title": "Build a File Processor", + "intro": [ + "You will learn Node.js built-in modules like fs, path, and crypto by using them for file operations and data processing." + ] + }, + "review-node-js-core-modules": { + "title": "Node JS Core Modules Review", + "intro": [ + "Review Node JS Core Modules concepts to prepare for the upcoming quiz." + ] + }, + "quiz-node-js-core-modules": { + "title": "NodeJS Core Modules Quiz", + "intro": [ + "Test what you've learned about Node.js core modules with this quiz." + ] + }, + "lecture-introduction-to-npm": { + "title": "Introduction to npm", + "intro": [ + "In these lessons, you will learn about npm, and how it can help you manage your project's dependencies." + ] + }, + "lecture-working-with-npm-scripts": { + "title": "Working with npm Scripts", + "intro": [ + "Learn about npm scripts, publishing packages to the npm registry, and working with CommonJS and ES modules. These lessons cover essential Node.js development tools and module systems." + ] + }, + "workshop-build-a-case-converter": { + "title": "Build a Case Converter", + "intro": [ + "You will learn how to initialize, configure, and publish an NPM module by building a case converter." + ] + }, + "review-npm": { + "title": "NPM Review", + "intro": ["Review npm concepts to prepare for the upcoming quiz."] + }, + "quiz-npm": { + "title": "NPM Quiz", + "intro": ["Test what you have learned about npm in this quiz."] + }, + "lab-prime-number-checker-module": { + "title": "Build a Prime Number Checker Module", + "intro": [ + "Practice building and exporting an NPM module by creating a prime number checker." + ] + }, + "lecture-understanding-how-http-dns-tcpip-work": { + "title": "Understanding how HTTP, DNS and TCP/IP work", + "intro": [ + "Learn the fundamental concepts of how the internet works, focusing on HTTP, DNS, and TCP/IP." + ] + }, + "lecture-understanding-the-http-request-response-model": { + "title": "Understanding the HTTP Request-Response Model", + "intro": [ + "Learn the fundamentals of how web communication works through the HTTP request-response model, explore different types of web assets and responses, and understand how forms handle data submission using various HTTP methods." + ] + }, + "lecture-understanding-the-web-standards-model": { + "title": "Understanding the Web Standards Model", + "intro": [ + "In these lectures, you will learn about the web standard model, standard bodies, the process, lifecycle, and the principles behind web stadards." + ] + }, + "workshop-build-a-web-server": { + "title": "Build a Web Server", + "intro": [ + "You will learn the Node.js http module by building a web server to serve a multi-page client application." + ] + }, + "review-http-and-the-web-standards-model": { + "title": "HTTP and the Web Standards Model Review", + "intro": [ + "Review HTTP, DNS, TCP/IP, the request-response model, and web standards before you take the quiz." + ] + }, + "quiz-http-and-the-web-standards-model": { + "title": "HTTP and the Web Standards Model Quiz", + "intro": [ + "Test your knowledge of HTTP, DNS, TCP/IP, the request-response model, and web standards.", + "" + ] + }, + "lecture-working-with-express": { + "title": "Working with Express", + "intro": [ + "In these lessons, you will learn what Express.js is, why developers use it for building web servers and APIs, and how to set up a basic Express application with routes and request handling." + ] + }, + "lecture-understanding-routing-in-express-js": { + "title": "Understanding Routing in ExpressJS", + "intro": [ + "Understanding Routing in ExpressJS", + "In these lessons, you will learn about routing in ExpressJS, which is how you define the different endpoints of your web application and how they respond to client requests." + ] + }, + "workshop-build-a-random-joke-app": { + "title": "Build a Random Joke App", + "intro": [ + "You will learn basic Express routing and response methods by building a random joke app." + ] + }, + "review-introduction-to-express": { + "title": "Introduction to Express Review", + "intro": [ + "Review Express.js, routing, response methods, and serving static files before you take the quiz." + ] + }, + "quiz-introduction-to-express": { + "title": "Introduction to Express Quiz", + "intro": [ + "Test your knowledge of web services, REST, microservices, Express.js, and routing." + ] + }, + "lab-personal-profile-app": { + "title": "Build a Personal Profile App", + "intro": [ + "Practice building an Express server and JSON API by creating a personal profile application." + ] + }, + "lecture-express-middleware": { + "title": "Express Middleware", + "intro": [ + "In these lessons, you will learn how middleware works in Express, including application-level, router-level, and error-handling middleware, as well as examples of built-in and third-party middleware." + ] + }, + "workshop-build-a-submission-form": { + "title": "Build a Submission Form", + "intro": [ + "You will learn application-level and router-level middleware by building a structured submission form." + ] + }, + "lab-data-sanitizer": { + "title": "Build a Data Sanitizer", + "intro": [ + "Practice creating custom Express middleware by building a data sanitizer and validator." + ] + }, + "review-express-middleware": { + "title": "Express Middleware Review", + "intro": [ + "Review middleware concepts in Express, including application-level, router-level, error-handling, and built-in and third-party middleware before you take the quiz." + ] + }, + "quiz-express-middleware": { + "title": "Express Middleware Quiz", + "intro": [ + "Test your knowledge of Express middleware, including application-level, router-level, error-handling, and built-in and third-party middleware." + ] + }, + "lecture-understanding-rest-api-and-web-services": { + "title": "Understanding the REST API and Web Services", + "intro": [ + "In these lessons, you will learn about REST APIs and web services, and how they allow different applications to communicate with each other over the internet." + ] + }, + "workshop-build-a-weather-service-api": { + "title": "Build a Weather Service API", + "intro": [ + "You will learn route parameters and modular routing with express.Router by building a weather service API." + ] + }, + "review-rest-api-and-web-services": { + "title": "REST API and Web Services Review", + "intro": [ + "Review web services, the REST architecture, HTTP status codes, and microservices." + ] + }, + "quiz-rest-api-and-web-services": { + "title": "REST API and Web Services Quiz", + "intro": [ + "Test your knowledge of web services, the REST architecture, HTTP status codes, and monoliths vs. microservices." + ] + }, + "lab-timestamp-microservice": { + "title": "Build a Timestamp Microservice", + "intro": [ + "Practice building a RESTful API with date parsing logic by creating a timestamp microservice." + ] + }, + "lecture-understanding-error-handling-and-health-checks": { + "title": "Understanding Error Handling and Health Checks", + "intro": [ + "In these lessons, you'll learn about error handling and health checks in Express." + ] + }, + "workshop-build-a-bank-api": { + "title": "Build a Bank API", + "intro": [ + "You will learn Express 5 error handling, health checks, and graceful shutdowns by building a bank API." + ] + }, + "review-error-handling-in-express": { + "title": "Error Handling in Express Review", + "intro": [ + "Review HTTP status codes, error handling, debugging, logging, health checks, and graceful shutdowns before you take the quiz." + ] + }, + "quiz-error-handling-in-express": { + "title": "Error Handling in Express Quiz", + "intro": [ + "Test your knowledge of HTTP status codes, error handling, debugging, logging, health checks, and graceful shutdowns." + ] + }, + "lecture-understanding-websockets": { + "title": "Understanding WebSockets", + "intro": [ + "Learn how WebSockets enable real-time, bidirectional communication between clients and servers, and how the Pub/Sub messaging architecture routes messages to the right subscribers in real-time applications." + ] + }, + "workshop-build-a-resource-monitor": { + "title": "Build a Resource Monitor", + "intro": [ + "You will learn Node.js WebSockets and real-time data streaming by building a system resource monitor." + ] + }, + "review-websockets": { + "title": "WebSockets Review", + "intro": [ + "Review WebSockets and Pub/Sub concepts before taking the quiz." + ] + }, + "quiz-websockets": { + "title": "WebSockets Quiz", + "intro": [ + "Test your knowledge of WebSockets and Pub/Sub with this quiz." + ] + }, + "lab-chat-app": { + "title": "Build a Chat App", + "intro": [ + "Practice building a real-time multi-client chat server using Node.js WebSockets." + ] + }, + "lecture-understanding-security-and-privacy-in-web-applications": { + "title": "Understanding Security and Privacy in Web Applications", + "intro": [ + "Learn how security and privacy work in web applications, covering HTTPS, cookies, CSP, common threats, privacy laws, and more." + ] + }, + "review-security-and-privacy": { + "title": "Security and Privacy Review", + "intro": [ + "Review security and privacy concepts covered in the lectures before taking the quiz." + ] + }, + "quiz-security-and-privacy": { + "title": "Security and Privacy Quiz", + "intro": [ + "Test your knowledge of security and privacy concepts covered in this module." + ] + }, + "lecture-introduction-to-authentication-and-authorization": { + "title": "Introduction to Authentication and Authorization", + "intro": [ + "Learn how authentication and authorization work, how JWTs protect your API routes, how to defend against CSRF attacks, and how to use Passport.js and Helmet.js to secure your Node.js applications." + ] + }, + "workshop-jwt-protected-routes": { + "title": "Build JWT Protected Routes", + "intro": [ + "You will learn authentication and role-based authorization by building an Express application with JWT-protected routes." + ] + }, + "review-authentication-and-authorization": { + "title": "Authentication and Authorization Review", + "intro": [ + "Review authentication and authorization concepts before you take the quiz." + ] + }, + "quiz-authentication-and-authorization": { + "title": "Authentication and Authorization Quiz", + "intro": [ + "Test your knowledge of authentication and authorization concepts covered in this module." + ] + }, + "lab-family-movie-watchlist-api": { + "title": "Build a Family Movie Watchlist API", + "intro": [ + "Practice implementing authentication and authorization in an Express application by building a family movie watchlist API." + ] + }, + "review-back-end-development-and-apis": { + "title": "Back-End Development and APIs Review", + "intro": [ + "Review Back-End Development and APIs concepts to prepare for the upcoming exam." + ] + }, + "exam-back-end-development-and-apis-certification": { + "title": "Back-End Development and APIs Certification Exam", + "intro": [ + "Pass this exam to earn your Back-End Development and APIs Certification" + ] + } + } + }, + "full-stack-developer-v9": { + "title": "Certified Full-Stack Developer Curriculum", + "intro": [ + "This certification represents the culmination of your full-stack developer journey. It demonstrates your ability to build complete, modern web applications from start to finish.", + "To qualify for the exam, you must earn the certifications below. Pass the exam to earn your Full-Stack Developer Certification." + ], + "note": "", + "chapters": { + "certified-full-stack-developer-exam": "Certified Full-Stack Developer Exam" + }, + "modules": { + "certified-full-stack-developer-exam": "Certified Full-Stack Developer Exam" + }, + "module-intros": { + "certified-full-stack-developer-exam": { + "note": "Coming Late 2026", + "intro": [ + "This exam will test what you have learned throughout the previous six certifications." + ] + } + }, + "blocks": { + "exam-certified-full-stack-developer": { + "title": "Certified Full-Stack Developer Exam", + "intro": ["Pass this exam to become a Certified Full-Stack Developer."] + } + } + }, + "html-forms-and-tables": { + "title": "Learn HTML Forms and Tables", + "summary": [ + "Learn how to build accessible forms and data tables with semantic HTML." + ], + "intro": [ + "Learn how to build accessible forms and data tables with semantic HTML.", + "Practice structuring inputs, labels, and tabular data so everyone can navigate and submit information confidently." + ], + "blocks": { + "lecture-working-with-forms": { + "title": "Working with Forms", + "intro": [ + "In these lessons, you will learn about forms, the role of labels, inputs and buttons in creating forms, client-side form validation, and form states." + ] + }, + "workshop-hotel-feedback-form": { + "title": "Build a Hotel Feedback Form", + "intro": [ + "In this workshop, you will build a Hotel Feedback Form.", + "You will practice working with the label, input, fieldset, legend, textarea, and button elements." + ] + }, + "lecture-working-with-tables": { + "title": "Working with Tables", + "intro": [ + "In these lessons, you will learn about HTML tables, how to create them, and when to use them." + ] + }, + "workshop-final-exams-table": { + "title": "Build a Final Exams Table", + "intro": [ + "In this workshop, you will practice working with HTML tables by building a table of final exams." + ] + }, + "lab-book-catalog-table": { + "title": "Build a Book Catalog Table", + "intro": [ + "In this lab, you'll review HTML tables by building a book information table.", + "You'll practice the different table components like the thead, tbody, th, tr, and td elements." + ] + }, + "lecture-working-with-html-tools": { + "title": "Working with HTML Tools", + "intro": [ + "In these lectures, you will learn about HTML tools and how they let you write better code. These tools include HTML validators, DOM Inspector, and the browser developer tools." + ] + }, + "lab-survey-form": { + "title": "Build a Survey Form", + "intro": [ + "In this lab, you'll review HTML forms by creating a survey form.", + "You'll practice working with the label element, the different input elements, the required attribute, and more. " + ] + }, + "review-html-tables-and-forms": { + "title": "HTML Tables and Forms Review", + "intro": [ + "Before you are quizzed on HTML forms, tables and tools, you first need to review the concepts.", + "Open up this page to review the table, input, and button elements as well as commonly used tools like the HTML validator and more." + ] + }, + "quiz-html-tables-and-forms": { + "title": "HTML Tables and Forms Quiz", + "intro": [ + "The following quiz will test your knowledge of HTML tables, forms and commonly used HTML tools.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + } + } + }, + "a1-professional-spanish": { + "title": "A1 Professional Spanish Certification (Beta)", + "note": "This certification is currently in active development. New content will be published as our instructional design team develops it. Once all content is available, we will release the certification exam.", + "intro": [ + "This course teaches you the fundamentals of Spanish at the A1 level of the Common European Framework of Reference (CEFR), with lessons focused on professional settings. Each module is broken down into sections:", + "- A Warm-up section for quick review.", + "- Learn sections with new vocabulary and grammar.", + "- Practice sections to check your comprehension and writing skills.", + "- A Review section with key grammar and vocabulary." + ], + "chapters": { + "es-a1-chapter-welcome-to-a1-professional-spanish": "Welcome to A1 Professional Spanish", + "es-a1-chapter-spanish-fundamentals": "Spanish Fundamentals", + "es-a1-chapter-greetings-and-introductions": "Greetings and Introductions", + "es-a1-chapter-basic-personal-details": "Basic Personal Details", + "es-a1-chapter-describing-company-and-people": "Describing a Company and Its People" + }, + "modules": { + "es-a1-module-introduction-and-certification-overview": "Introduction and Certification Overview", + "es-a1-module-letters-sounds-and-first-numbers": "Letters, Sounds and First Numbers", + "es-a1-module-greetings-and-farewells": "Greetings and Farewells", + "es-a1-module-introducing-yourself": "Introducing Yourself", + "es-a1-module-first-questions": "First Questions", + "es-a1-module-numbers-10-to-29": "Numbers 10 to 29", + "es-a1-module-sharing-your-personal-details": "Sharing Your Personal Details", + "es-a1-module-numbers-30-to-100": "Numbers 30 to 100", + "es-a1-module-describing-a-company": "Describing a Company", + "es-a1-module-describing-people-at-work": "Describing People at Work" + }, + "module-intros": { + "es-a1-module-describing-a-company": { + "note": "Coming 2026", + "intro": [ + "In this module, you will learn how to identify and describe basic information about a company, such as name, website, location, number of employees, and departments." + ] + }, + "es-a1-module-describing-people-at-work": { + "note": "Coming 2026", + "intro": [ + "In this module, you will learn third-person descriptions and how to identify simple corrections in short conversations." + ] + } + }, + "blocks": { + "es-a1-warm-up-greetings-and-farewells-basics": { + "title": "Greetings and Farewells Basics", + "intro": ["", ""] + }, + "es-a1-learn-greetings-during-the-day": { + "title": "Greetings During the Day", + "intro": ["", ""] + }, + "es-a1-practice-greetings-and-farewells": { + "title": "Greetings and Farewells Practice", + "intro": ["", ""] + }, + "es-a1-review-greetings-and-farewells": { + "title": "Greetings and Farewells Review", + "intro": ["", ""] + }, + "es-a1-quiz-greetings-and-farewells": { + "title": "Greetings and Farewells Quiz", + "intro": ["", ""] + }, + "es-a1-learn-certification-introduction": { + "title": "Certification Introduction", + "intro": ["", ""] + }, + "es-a1-learn-alphabet-and-accents": { + "title": "Alphabet and Accents", + "intro": ["", ""] + }, + "es-a1-learn-punctuation": { "title": "Punctuation", "intro": ["", ""] }, + "es-a1-quiz-spanish-fundamentals": { + "title": "Spanish Fundamentals Quiz", + "intro": ["", ""] + }, + "es-a1-warm-up-introducing-yourself-basics": { + "title": "Introducing Yourself Basics", + "intro": ["", ""] + }, + "es-a1-learn-meet-luna": { "title": "Meet Luna", "intro": ["", ""] }, + "es-a1-learn-meet-mateo": { "title": "Meet Mateo", "intro": ["", ""] }, + "es-a1-learn-meet-julieta": { + "title": "Meet Julieta", + "intro": ["", ""] + }, + "es-a1-practice-introducing-yourself": { + "title": "Introducing Yourself Practice", + "intro": ["", ""] + }, + "es-a1-review-introducing-yourself": { + "title": "Introducing Yourself Review", + "intro": ["", ""] + }, + "es-a1-quiz-introducing-yourself": { + "title": "Introducing Yourself Quiz", + "intro": ["", ""] + }, + "es-a1-warm-up-first-questions-basics": { + "title": "First Questions Basics", + "intro": ["", ""] + }, + "es-a1-learn-meet-angela-and-basti": { + "title": "Meet Angela and Basti", + "intro": ["", ""] + }, + "es-a1-practice-first-questions": { + "title": "First Questions Practice", + "intro": ["", ""] + }, + "es-a1-review-first-questions": { + "title": "First Questions Review", + "intro": ["", ""] + }, + "es-a1-quiz-first-questions": { + "title": "First Questions Quiz", + "intro": ["", ""] + }, + "es-a1-learn-vowels": { "title": "Vowels", "intro": ["", ""] }, + "es-a1-learn-consonants-and-special-characters": { + "title": "Consonants and Special Characters", + "intro": ["", ""] + }, + "es-a1-review-spanish-fundamentals": { + "title": "Spanish Fundamentals Review", + "intro": ["", ""] + }, + "es-a1-practice-the-alphabet": { + "title": "The Spanish Alphabet Practice", + "intro": ["", ""] + }, + "es-a1-warm-up-remember-first-numbers": { + "title": "Remember First Numbers", + "intro": ["", ""] + }, + "es-a1-learn-numbers-10-to-29": { + "title": "Numbers 10 to 29", + "intro": ["", ""] + }, + "es-a1-practice-using-numbers-10-to-29": { + "title": "Using Numbers 10 to 29", + "intro": ["", ""] + }, + "es-a1-review-numbers-10-to-29": { + "title": "Numbers 10 to 29 Review", + "intro": ["", ""] + }, + "es-a1-quiz-numbers-10-to-29": { + "title": "Numbers 10 to 29 Quiz", + "intro": ["", ""] + }, + "es-a1-warm-up-getting-ready-to-share-personal-details": { + "title": "Getting Ready to Share Personal Details", + "intro": ["", ""] + }, + "es-a1-learn-basic-personal-information": { + "title": "Basic Personal Information", + "intro": ["", ""] + }, + "es-a1-learn-contact-information-and-spelling": { + "title": "Contact Information and Spelling", + "intro": ["", ""] + }, + "es-a1-practice-personal-details-in-action": { + "title": "Personal Details in Action", + "intro": ["", ""] + }, + "es-a1-review-sharing-your-personal-details": { + "title": "Sharing Your Personal Details Review", + "intro": ["", ""] + }, + "es-a1-quiz-sharing-your-personal-details": { + "title": "Sharing Your Personal Details Quiz", + "intro": ["", ""] + }, + "es-a1-learn-the-first-ten-numbers": { + "title": "The First Ten Numbers", + "intro": ["", ""] + }, + "es-a1-practice-the-first-ten-numbers": { + "title": "The First Ten Numbers Practice", + "intro": ["", ""] + }, + "es-a1-learn-numbers-30-to-60": { + "title": "Numbers 30 to 60", + "intro": ["", ""] + }, + "es-a1-warm-up-describing-a-company-basics": { + "title": "Describing a Company Basics", + "intro": ["", ""] + }, + "es-a1-learn-numbers-61-to-100": { + "title": "Numbers 61 to 100", + "intro": ["", ""] + }, + "es-a1-practice-using-the-first-100-numbers": { + "title": "Using The First 100 Numbers", + "intro": ["", ""] + }, + "es-a1-review-first-100-numbers": { + "title": "First 100 Numbers Review", + "intro": ["", ""] + }, + "es-a1-quiz-numbers-30-to-100": { + "title": "Numbers 30 to 100 Quiz", + "intro": ["", ""] + }, + "es-a1-learn-what-the-company-does": { + "title": "What the Company Does", + "intro": ["", ""] + }, + "es-a1-learn-asking-about-a-company": { + "title": "Asking about a Company", + "intro": ["", ""] + }, + "es-a1-practice-company-profile": { + "title": "Company Profile", + "intro": ["", ""] + }, + "es-a1-review-talking-about-a-company": { + "title": "Talking About a Company", + "intro": ["", ""] + }, + "es-a1-quiz-describing-a-company": { + "title": "Describing a Company Quiz", + "intro": ["", ""] + }, + "es-a1-warm-up-describing-people-at-work-basics": { + "title": "Describing People at Work Basics", + "intro": ["", ""] + }, + "es-a1-learn-mini-biographies": { + "title": "Mini Biographies ", + "intro": ["", ""] + }, + "es-a1-practice-asking-about-mini-biographies": { + "title": "Asking About Mini Biographies", + "intro": ["", ""] + }, + "es-a1-learn-short-workplace-profile": { + "title": "Short Workplace Profile ", + "intro": ["", ""] + }, + "es-a1-practice-asking-about-short-workplace-profiles": { + "title": "Asking About Short Workplace Profiles", + "intro": ["", ""] + }, + "es-a1-review-describing-people-at-work": { + "title": "Describing People at Work", + "intro": ["", ""] + }, + "es-a1-quiz-describing-people-at-work": { + "title": "Describing People at Work", + "intro": ["", ""] + }, + "es-a1-learn-talking-about-colleagues": { + "title": "Talking About Colleagues", + "intro": ["", ""] + }, + "es-a1-practice-what-departments-do": { + "title": "What Departments Do", + "intro": ["", ""] + } + } + }, + "responsive-web-design-v9": { + "title": "Responsive Web Design Certification", + "intro": [ + "This course teaches the fundamentals of HTML and CSS, including modern layout, design, accessibility, and responsive web development. You'll build practical projects and gain the skills to create professional, user-friendly webpages.", + "To earn your Responsive Web Design Certification:", + "- Complete the five required projects to qualify for the certification exam.", + "- Pass the Responsive Web Design Certification exam." + ], + "chapters": { + "html": "HTML", + "computers": "Computers", + "css": "CSS", + "responsive-web-design-certification-exam": "Responsive Web Design Certification Exam" + }, + "modules": { + "basic-html": "Basic HTML", + "semantic-html": "Semantic HTML", + "html-forms-and-tables": "Forms and Tables", + "lab-survey-form": "Build a Survey Form", + "html-and-accessibility": "Accessibility", + "review-html": "HTML Review", + "computer-basics": "Computer Basics", + "basic-css": "Basic CSS", + "design-for-developers": "Design", + "absolute-and-relative-units": "Absolute and Relative Units", + "pseudo-classes-and-elements": "Pseudo Classes and Elements", + "css-colors": "Colors", + "styling-forms": "Styling Forms", + "css-box-model": "The Box Model", + "css-flexbox": "Flexbox", + "lab-page-of-playing-cards": "Build a Page of Playing Cards", + "css-typography": "Typography", + "css-and-accessibility": "Accessibility", + "css-positioning": "Positioning", + "attribute-selectors": "Attribute Selectors", + "lab-book-inventory-app": "Build a Book Inventory App", + "responsive-design": "Responsive Design", + "lab-technical-documentation-page": "Build a Technical Documentation Page", + "css-variables": "Variables", + "css-grid": "Grid", + "lab-product-landing-page": "Build a Product Landing Page", + "css-animations": "Animations", + "review-css": "CSS Review", + "responsive-web-design-certification-exam": "Responsive Web Design Certification Exam" + }, + "blocks": { + "workshop-curriculum-outline": { + "title": "Build a Curriculum Outline", + "intro": [ + "Welcome to freeCodeCamp!", + "This workshop will serve as your introduction to HTML and coding in general. You will learn about headings and paragraph elements." + ] + }, + "lab-debug-camperbots-profile-page": { + "title": "Debug Camperbot's Profile Page", + "intro": [ + "Camperbot is learning how to code too and needs some help with their HTML.", + "In this lab, you will help Camperbot find and fix the errors in their code." + ] + }, + "lecture-understanding-html-attributes": { + "title": "Understanding HTML Attributes", + "intro": [ + "In these lectures, you will learn more about HTML (HyperText Markup Language), a markup language for creating web pages.", + "You will learn about HTML's role on the web, and what HTML attributes are." + ] + }, + "lab-debug-pet-adoption-page": { + "title": "Debug a Pet Adoption Page", + "intro": [ + "In this lab, you will need to find and fix the errors in this pet adoption page." + ] + }, + "lecture-understanding-the-html-boilerplate": { + "title": "Understanding the HTML Boilerplate", + "intro": [ + "In these lectures, you will learn about the HTML boilerplate which is a ready-made template for your webpages.", + "You will learn how to work with the link element, meta element and more." + ] + }, + "workshop-cat-photo-app": { + "title": "Build a Cat Photo App", + "intro": [ + "HTML stands for HyperText Markup Language and it represents the content and structure of a web page.", + "In this workshop, you will learn how to work with basic HTML elements such as headings, paragraphs, images, links, and lists." + ] + }, + "lab-recipe-page": { + "title": "Build a Recipe Page", + "intro": [ + "In this lab, you'll review HTML basics by creating a web page of your favorite recipe. You'll create an HTML boilerplate and work with headings, lists, images, and more." + ] + }, + "lecture-html-fundamentals": { + "title": "HTML Fundamentals", + "intro": [ + "In these lectures, you will learn about HTML fundamentals like the div element, the id and class attributes, the HTML boilerplate, HTML entities, and more." + ] + }, + "workshop-bookstore-page": { + "title": "Build a Bookstore Page", + "intro": [ + "In this workshop, you will practice working with classes, ids and the div element by building a bookstore page." + ] + }, + "lecture-understanding-how-html-affects-seo": { + "title": "Understanding How HTML Affects SEO", + "intro": [ + "In these lectures, you will learn how your HTML code impacts search engine optimization." + ] + }, + "lab-travel-agency-page": { + "title": "Build a Travel Agency Page", + "intro": [ + "In this lab, you'll review working with HTML fundamentals by creating a web page for a travel agency. You'll work with images, the figure element, the figcaption element, the anchor element, and more." + ] + }, + "lecture-working-with-audio-and-video-elements": { + "title": "Working with Audio and Video Elements", + "intro": [ + "In these lectures, you will learn how to work with the audio and video elements." + ] + }, + "workshop-html-music-player": { + "title": "Build an HTML Music Player", + "intro": [ + "In this workshop, you'll use HTML to create a basic music player.", + "This project will cover the audio element, the audio player setup, and more." + ] + }, + "workshop-html-video-player": { + "title": "Build an HTML Video Player", + "intro": [ + "In this workshop, you'll use HTML to create a basic video player.", + "This project will cover the video element, the video player setup, and more." + ] + }, + "lab-html-audio-and-video-player": { + "title": "Build an HTML Audio and Video Player", + "intro": [ + "In this lab, you will build an HTML audio and video player using the video and audio elements with controls and source attributes." + ] + }, + "lecture-working-with-images-and-svgs": { + "title": "Working with Images and SVGs", + "intro": [ + "In these lectures, you will learn how to work with SVGs and learn about techniques for optimizing your images." + ] + }, + "workshop-build-a-heart-icon": { + "title": "Build a Heart Icon", + "intro": [ + "In this workshop, you will practice working with SVGs by building a heart icon" + ] + }, + "lecture-working-with-media": { + "title": "Working with the iframe Element", + "intro": [ + "In these lectures, you will learn how to work with the iframe element which is used to embed an external site on your web page." + ] + }, + "workshop-build-a-video-display-using-iframe": { + "title": "Build a Video Display Using iframe", + "intro": [ + "In this workshop, you'll learn how to work with the iframe element by building a video display." + ] + }, + "lab-video-compilation-page": { + "title": "Build a Video Compilation Page", + "intro": [ + "In this lab, you'll create a video compilation web page. You'll practice working with the iframe element." + ] + }, + "lecture-working-with-links": { + "title": "Working with Links", + "intro": [ + "In these lectures, you will learn about links, the target attribute, different link states, absolute, and relative paths, and more." + ] + }, + "review-basic-html": { + "title": "Basic HTML Review", + "intro": [ + "Before you are quizzed on the HTML knowledge you have gained so far, you first need to review the concepts.", + "Open up this page to review the HTML boilerplate, audio and video elements, the different target attribute values and more." + ] + }, + "quiz-basic-html": { + "title": "Basic HTML Quiz", + "intro": [ + "The following quiz will test your knowledge of the basic HTML concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + }, + "lecture-importance-of-semantic-html": { + "title": "Importance of Semantic HTML", + "intro": [ + "In these lectures, you will learn about semantic HTML and why you should care about it, semantic elements, how semantic HTML differs from presentational HTML, and more." + ] + }, + "lecture-understanding-nuanced-semantic-elements": { + "title": "Understanding Nuanced Semantic Elements", + "intro": [ + "In these lectures, you will learn when you should use certain semantic elements like the em element over the i element, description lists, and more." + ] + }, + "workshop-major-browsers-list": { + "title": "Build a List of Major Web Browsers", + "intro": [ + "In this workshop, you will build a description list and work with the dl, dt, and dd elements." + ] + }, + "lecture-working-with-text-and-time-semantic-elements": { + "title": "Working with Text and Time Semantic Elements ", + "intro": [ + "In this lecture, you will learn about the importance of semantics in conveying meaning for text and time-related content including the time and blockquote elements, and more." + ] + }, + "workshop-quincys-job-tips": { + "title": "Build Quincy's Job Tips Page", + "intro": [ + "In this workshop, you will practice working with semantic HTML by using the q, blockquote, and cite elements." + ] + }, + "lecture-working-with-specialized-semantic-elements": { + "title": "Working with Specialized Semantic Elements", + "intro": [ + "In this lecture, you will learn about specialized semantic elements like u, s, code elements and more." + ] + }, + "workshop-blog-page": { + "title": "Build a Cat Blog Page", + "intro": [ + "In this workshop, you will build an HTML-only blog page using semantic elements including the main, nav, article, and footer elements." + ] + }, + "lab-event-hub": { + "title": "Build an Event Hub", + "intro": [ + "In this lab, you'll build an event hub and review semantic elements like header, nav, article, and more." + ] + }, + "review-semantic-html": { + "title": "Semantic HTML Review", + "intro": [ + "Before you are quizzed on semantic HTML, you first need to review the concepts.", + "Open up this page to review the em, strong, blockquote, address and more semantic HTML elements." + ] + }, + "quiz-semantic-html": { + "title": "Semantic HTML Quiz", + "intro": [ + "The following quiz will test your knowledge on semantic HTML concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + }, + "lecture-working-with-forms": { + "title": "Working with Forms", + "intro": [ + "In these lectures, you will learn about forms, the role of labels, inputs and buttons in creating forms, client-side form validation, and form states." + ] + }, + "workshop-hotel-feedback-form": { + "title": "Build a Hotel Feedback Form", + "intro": [ + "In this workshop, you will build a Hotel Feedback Form.", + "You will practice working with the label, input, fieldset, legend, textarea, and button elements." + ] + }, + "lecture-working-with-tables": { + "title": "Working with Tables", + "intro": [ + "In these lectures, you will learn about HTML tables, how to create them, and when to use them." + ] + }, + "workshop-final-exams-table": { + "title": "Build a Final Exams Table", + "intro": [ + "In this workshop, you will practice working with HTML tables by building a table of final exams." + ] + }, + "lab-book-catalog-table": { + "title": "Build a Book Catalog Table", + "intro": [ + "In this lab, you'll review HTML tables by building a book information table.", + "You'll practice the different table components like the thead, tbody, th, tr, and td elements." + ] + }, + "lecture-working-with-html-tools": { + "title": "Working with HTML Tools", + "intro": [ + "In these lectures, you will learn about HTML tools and how they let you write better code. These tools include HTML validators, DOM Inspector, and the browser developer tools." + ] + }, + "review-html-tables-and-forms": { + "title": "HTML Tables and Forms Review", + "intro": [ + "Before you are quizzed on HTML forms, tables and tools, you first need to review the concepts.", + "Open up this page to review the table, input, and button elements as well as commonly used tools like the HTML validator and more." + ] + }, + "quiz-html-tables-and-forms": { + "title": "HTML Tables and Forms Quiz", + "intro": [ + "The following quiz will test your knowledge of HTML tables, forms and commonly used HTML tools.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + }, + "lab-survey-form": { + "title": "Build a Survey Form", + "intro": [ + "In this lab, you'll review HTML forms by creating a survey form.", + "You'll practice working with the label element, the different input elements, the required attribute, and more. " + ] + }, + "lecture-importance-of-accessibility-and-good-html-structure": { + "title": "Importance of Accessibility and Good HTML Structure", + "intro": [ + "In these lectures, you will learn about accessibility and its importance, assistive tools for people with disabilities, HTML attributes that let you create inclusive websites, accessibility best practices, and much more." + ] + }, + "workshop-debug-coding-journey-blog-page": { + "title": "Debug a Coding Journey Blog Page", + "intro": [ + "In this workshop, you will debug and fix accessibility errors in a coding blog page." + ] + }, + "lecture-accessible-tables-forms": { + "title": "Working with Accessible Tables and Forms", + "intro": [ + "In these lectures, you will learn about how to create accessible tables and forms." + ] + }, + "workshop-tech-conference-schedule": { + "title": "Build a Tech Conference Schedule Table", + "intro": [ + "In this workshop, you will build an accessible tech conference schedule table." + ] + }, + "lab-debug-donation-form": { + "title": "Debug a Donation Form", + "intro": [ + "In this lab you will debug a donation form by fixing HTML syntax errors and improving accessibility." + ] + }, + "lecture-introduction-to-aria": { + "title": "Introduction to ARIA", + "intro": [ + "In these lectures, you will learn about working with ARIA roles." + ] + }, + "workshop-accessible-audio-controller": { + "title": "Build an Accessible Audio Controller", + "intro": [ + "In this workshop, you will practice accessible HTML by building an audio controller that uses the aria-labelledby attribute." + ] + }, + "lecture-accessible-media-elements": { + "title": "Working with Accessible Media Elements", + "intro": [ + "In these lectures, you will learn about how to create accessible links, audio and video content." + ] + }, + "lab-checkout-page": { + "title": "Build a Checkout Page", + "intro": [ + "In this lab, you'll create an accessible checkout page.", + "You'll practice concepts like alt attributes and ARIA roles." + ] + }, + "lab-movie-review-page": { + "title": "Design a Movie Review Page", + "intro": [ + "In this lab, you'll create a movie review page.", + "You'll practice concepts like semantic HTML, alt attributes, accessible lists, and hiding decorative content from screen readers using aria-hidden." + ] + }, + "lab-multimedia-player": { + "title": "Build a Multimedia Player", + "intro": [ + "In this lab, you'll build a multimedia player.", + "You will practice working with the audio and video elements, the controls attribute, and the aria-label attribute." + ] + }, + "review-html-accessibility": { + "title": "HTML Accessibility Review", + "intro": [ + "Before you are quizzed on HTML and accessibility, you first need to review the concepts.", + "Open up this page to review concepts including the aria-hidden, aria-describedby, tabindex attributes and more." + ] + }, + "quiz-html-accessibility": { + "title": "HTML Accessibility Quiz", + "intro": [ + "The following quiz will test your knowledge on the accessibility concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + }, + "review-html": { + "title": "HTML Review", + "intro": [ + "Before you take the HTML prep exam, you first need to review the concepts taught in the previous modules.", + "Open up this page to review concepts around the basics of HTML elements, semantic HTML, tables, forms and accessibility." + ] + }, + "lecture-understanding-computer-internet-and-tooling-basics": { + "title": "Understanding Computer, Internet, and Tooling Basics", + "intro": [ + "In these lectures, you will learn about the computer, its different parts, internet service providers (ISPs), and the tools professional developers use." + ] + }, + "lecture-working-with-file-systems": { + "title": "Working with File Systems", + "intro": [ + "In these lectures, you will learn how to work with file and folder systems on your computers. You will learn how to create, move, and delete files and folders, the best practices for naming and organizing files and folders, and more." + ] + }, + "lecture-browsing-the-web-effectively": { + "title": "Browsing the Web Effectively", + "intro": [ + "In these lectures, you will learn about what websites, search engine, and web browsers are, the different browsers available, and how to get the best out of a search engine." + ] + }, + "review-computer-basics": { + "title": "Computer Basics Review", + "intro": [ + "Before you are quizzed on basic computer and internet concepts, you first need to review.", + "Open up this page to review concepts like RAM, Internet service providers, common web browsers, search engines and more." + ] + }, + "quiz-computer-basics": { + "title": "Computer Basics Quiz", + "intro": [ + "Test what you've learned in this quiz of basic computer knowledge." + ] + }, + "lecture-what-is-css": { + "title": "What Is CSS?", + "intro": [ + "The following lectures are all about CSS. You will learn what CSS is and its role on the web, a CSS rule and its anatomy, the three ways to write CSS and when to use each, inline and block elements, and many more." + ] + }, + "workshop-cafe-menu": { + "title": "Design a Cafe Menu", + "intro": [ + "CSS tells the browser how to display your webpage. You can use CSS to set the color, font, size, and other aspects of HTML elements.", + "In this workshop, you'll learn CSS by designing a menu page for a cafe." + ] + }, + "lab-business-card": { + "title": "Design a Business Card", + "intro": [ + "In this lab, you'll create a business card and style it using CSS.", + "You'll practice style properties like color, font-size, text-align, and more." + ] + }, + "lecture-css-specificity-the-cascade-algorithm-and-inheritance": { + "title": "CSS Specificity, the Cascade Algorithm, and Inheritance", + "intro": [ + "In these lectures, you will learn about CSS specificity, the common selectors and their specificities, the cascade algorithm, inheritance, and more." + ] + }, + "review-basic-css": { + "title": "CSS Fundamentals Review", + "intro": [ + "Before you are quizzed on basic CSS concepts, you first need to review.", + "Open up this page to review concepts including margin, padding, CSS combinators, CSS specificity and more." + ] + }, + "quiz-basic-css": { + "title": "CSS Fundamentals Quiz", + "intro": [ + "Test what you've learned in this quiz of basic CSS knowledge." + ] + }, + "lecture-styling-lists-and-links": { + "title": "Styling Lists and Links", + "intro": [ + "In these lectures, you will learn the properties you need to know to effectively style lists and links, including link states like link, visited, hover, and active." + ] + }, + "lab-stylized-to-do-list": { + "title": "Build a Stylized To-Do List", + "intro": [ + "In this lab, you'll build a To-Do list and apply different styles to the links", + "You'll practice style properties like text-decoration, list-style-type and how to change styles on hover or click." + ] + }, + "lecture-working-with-backgrounds-and-borders": { + "title": "Working with Backgrounds and Borders", + "intro": [ + "In these lectures, you will learn about the properties and values you need to know to style backgrounds and borders of elements, alongside the accessibility considerations for backgrounds." + ] + }, + "lab-blog-post-card": { + "title": "Design a Blog Post Card", + "intro": [ + "In this lab, you'll design a blog post card using HTML and CSS", + "You'll practice concepts like background-color, border-radius, margins, paddings, and more." + ] + }, + "review-css-backgrounds-and-borders": { + "title": "Lists, Links, CSS Background and Borders Review", + "intro": [ + "Before you are quizzed on CSS backgrounds and borders, you first need to review.", + "Open up this page to review concepts including the background-image property, border property and more." + ] + }, + "quiz-css-backgrounds-and-borders": { + "title": "CSS Backgrounds and Borders Quiz", + "intro": [ + "Test what you've learned in this quiz of backgrounds and borders in CSS." + ] + }, + "lecture-user-interface-design-fundamentals": { + "title": "User Interface Design Fundamentals", + "intro": [ + "In these lectures, you will learn about the fundamentals of user interface (UI) design. You will learn about the terms you need to know to communicate with designers, visual hierarchy, scaling, alignment, whitespace, and much more." + ] + }, + "lecture-user-centered-design": { + "title": "User-Centered Design", + "intro": [ + "In these lectures, you will learn about best practices for designing user-facing features like dark mode, breadcrumbs, modal dialogs, and much more. You will also learn how to conduct user research, user requirements and testing." + ] + }, + "lecture-common-design-tools": { + "title": "Common Design Tools", + "intro": [ + "In these lectures, you will learn about the common design tools developers should know. You will also learn about design briefs and how developers work with them." + ] + }, + "review-design-fundamentals": { + "title": "Design Fundamentals Review", + "intro": [ + "Before you are quizzed on the design fundamentals you have learned so far, you first need to review.", + "Open up this page to review concepts like user-centered design, scale, alignment, good visual hierarchy and more." + ] + }, + "quiz-design-fundamentals": { + "title": "Design Fundamentals Quiz", + "intro": [ + "Test what you've learned in this quiz of UI design fundamentals." + ] + }, + "lecture-working-with-relative-and-absolute-units": { + "title": "Working with Relative and Absolute Units", + "intro": [ + "In these lectures, you will learn about relative and absolute units, and how they both impact what you see in the browser." + ] + }, + "lab-event-flyer-page": { + "title": "Build an Event Flyer Page", + "intro": [ + "In this lab, you'll create an event flyer page.", + "You will practice aligning elements using absolute and relative CSS." + ] + }, + "review-css-relative-and-absolute-units": { + "title": "CSS Relative and Absolute Units Review", + "intro": [ + "Before you are quizzed on relative and absolute units, you first need to review.", + "Open up this page to review concepts like percentages, px, rem, em, and more." + ] + }, + "quiz-css-relative-and-absolute-units": { + "title": "CSS Relative and Absolute Units Quiz", + "intro": [ + "Test what you've learned in this quiz of relative and absolute units in CSS." + ] + }, + "lecture-working-with-pseudo-classes-and-pseudo-elements-in-css": { + "title": "Working with Pseudo-Classes and Pseudo-Elements in CSS", + "intro": [ + "In these lectures, you will learn about pseudo-classes and pseudo-elements, alongside their examples and how they work." + ] + }, + "workshop-greeting-card": { + "title": "Design a Greeting Card", + "intro": [ + "In the previous lectures, you learned how to work with the different types of pseudo-classes.", + "In this workshop, you will have a chance to practice what you have learned by designing a greeting card." + ] + }, + "workshop-parent-teacher-conference-form": { + "title": "Design a Parent Teacher Conference Form", + "intro": [ + "In this workshop, you will practice how to style radio buttons with different types of pseudo-selectors by building a parent-teacher conference form.", + "You'll practice concepts including the ::before pseudo-element selector, the transform property, and more." + ] + }, + "lab-job-application-form": { + "title": "Build a Job Application Form", + "intro": [ + "In this lab you'll build a job application form and style it using pseudo-classes.", + "You'll practice concepts like :hover, :active, :focus, and more." + ] + }, + "review-css-pseudo-classes": { + "title": "CSS Pseudo-classes Review", + "intro": [ + "Before you're quizzed on CSS pseudo-classes and pseudo-elements, you should review what you've learned about them.", + "Open up this page to review concepts like the ::before and ::after pseudo-elements as well as the :hover, :active pseudo-classes and more." + ] + }, + "quiz-css-pseudo-classes": { + "title": "CSS Pseudo-classes Quiz", + "intro": ["Test your knowledge of CSS pseudo-classes with this quiz."] + }, + "lecture-working-with-colors-in-css": { + "title": "Working with Colors in CSS", + "intro": [ + "In these lectures, you will learn about linear and radial gradients, the color theory, different kinds of colors like named, RGB, Hex, and HSL colors. You will learn how these colors work, and which to use in specific cases." + ] + }, + "workshop-colored-markers": { + "title": "Build a Set of Colored Markers", + "intro": [ + "In this workshop, you'll build a set of colored markers. You'll practice different ways to set color values and how to pair colors with each other." + ] + }, + "lab-colored-boxes": { + "title": "Design a Set of Colored Boxes", + "intro": [ + "In this lab, you'll create a color grid and practice adding background colors to the grid items using hex codes, RGB, and predefined color names." + ] + }, + "review-css-colors": { + "title": "CSS Colors Review", + "intro": [ + "Before you're quizzed on CSS colors, you should review what you've learned about them.", + "Open up this page to review concepts like the rgb() function, hsl() function, hex codes, and more." + ] + }, + "quiz-css-colors": { + "title": "CSS Colors Quiz", + "intro": ["Test your knowledge of CSS colors with this quiz."] + }, + "lecture-best-practices-for-styling-forms": { + "title": "Best Practices for Styling Forms", + "intro": [ + "In these lectures, you will learn about the best practices for styling forms and issues you can encounter while styling special inputs like color and datetime-local." + ] + }, + "workshop-registration-form": { + "title": "Design a Registration Form", + "intro": [ + "In this workshop, you'll learn how to design HTML forms by designing a signup page. You'll learn how to control what types of data people can type into your form, and some new CSS tools for styling your page." + ] + }, + "lab-contact-form": { + "title": "Design a Contact Form", + "intro": [ + "In this lab, you'll design a contact form in HTML and style it using CSS." + ] + }, + "workshop-game-settings-panel": { + "title": "Build a Game Settings Panel", + "intro": [ + "In this workshop, you will practice styling checkboxes by building a game settings panel." + ] + }, + "lab-feature-selection": { + "title": "Design a Feature Selection Page", + "intro": [ + "In this lab, you'll build a feature selection page with custom-styled checkboxes.", + "You'll create feature cards with labels and checkboxes, then give custom styling to the checkboxes." + ] + }, + "review-styling-forms": { + "title": "Styling Forms Review", + "intro": [ + "Before you're quizzed on styling forms, you should review what you've learned.", + "Open up this page to review how to style form inputs, working with appearance: none and more." + ] + }, + "quiz-styling-forms": { + "title": "Styling Forms Quiz", + "intro": [ + "In this quiz, you will test your knowledge of how to style forms." + ] + }, + "lecture-working-with-css-transforms-overflow-and-filters": { + "title": "Working with CSS Transforms, Overflow, and Filters", + "intro": [ + "In these lectures, you will learn about working with CSS transforms, overflow, and filters. You will also learn about the box model and how it works." + ] + }, + "workshop-rothko-painting": { + "title": "Design a Rothko Painting", + "intro": [ + "Every HTML element is its own box – with its own spacing and a border. This is called the Box Model.", + "In this workshop, you'll use CSS and the Box Model to create your own Rothko-style rectangular art pieces." + ] + }, + "lab-confidential-email-page": { + "title": "Build a Confidential Email Page", + "intro": [ + "In this lab, you'll create a web page using HTML and mask the content using CSS properties." + ] + }, + "review-css-layout-and-effects": { + "title": "CSS Layouts and Effects Review", + "intro": [ + "Before you are quizzed on CSS Layouts and Effects, you first need to review.", + "Open up this page to review concepts like the transform property, the box model, the overflow property and more." + ] + }, + "quiz-css-layout-and-effects": { + "title": "CSS Layout and Effects Quiz", + "intro": [ + "In this quiz, you will test your knowledge of the box model, transforms, filters, and overflow in CSS." + ] + }, + "lecture-working-with-css-flexbox": { + "title": "Working with CSS Flexbox", + "intro": [ + "In these lectures, you will learn how CSS flexbox works, its properties, and when you should use it." + ] + }, + "workshop-flexbox-photo-gallery": { + "title": "Build a Flexbox Photo Gallery", + "intro": [ + "In this workshop, you'll use Flexbox to build a responsive photo gallery webpage." + ] + }, + "workshop-colorful-boxes": { + "title": "Design a Set of Colorful Boxes", + "intro": [ + "In this workshop, you will practice working with CSS flexbox by designing a set of colored boxes." + ] + }, + "lab-pricing-plans-layout": { + "title": "Design a Pricing Plans Layout Page", + "intro": [ + "In this lab, you'll use flexbox to create a common three-card tier layout.", + "You'll practice aligning elements using flexbox properties like flex, flex-grow, order, and more." + ] + }, + "review-css-flexbox": { + "title": "CSS Flexbox Review", + "intro": [ + "Before you're quizzed on CSS flexbox, you should review what you've learned.", + "Open up this page to review concepts like the flex-direction, justify-content, align-items, flex-wrap properties, and more." + ] + }, + "quiz-css-flexbox": { + "title": "CSS Flexbox Quiz", + "intro": ["Test what you've learned on CSS flexbox with this quiz."] + }, + "lab-page-of-playing-cards": { + "title": "Build a Page of Playing Cards", + "intro": [ + "In this lab, you'll use flexbox to create a webpage of playing cards.", + "You'll practice aligning elements using flexbox properties like flex-direction, justify-content, align-self, and more." + ] + }, + "lecture-working-with-css-fonts": { + "title": "Working with CSS Fonts", + "intro": [ + "In these lectures, you will learn about typography and its best practices, fonts, and the text-shadow property." + ] + }, + "workshop-nutritional-label": { + "title": "Build a Nutritional Label", + "intro": [ + "Typography is the art of styling your text to be easily readable and suit its purpose.", + "In this workshop, you'll use typography to build a nutrition label webpage. You'll practice how to style text, adjust line height, and position your text using CSS." + ] + }, + "lab-newspaper-article": { + "title": "Build a Newspaper Article", + "intro": [ + "In this lab, you'll build a newspaper article page using HTML and CSS.", + "You'll style the fonts using properties like font-family, font-size, font-weight, and more." + ] + }, + "review-css-typography": { + "title": "CSS Typography Review", + "intro": [ + "Before you're quizzed on the fundamentals of typography, you should review what you've learned.", + "Open up this page to review concepts like web safe fonts, the font-family property and more." + ] + }, + "quiz-css-typography": { + "title": "CSS Typography Quiz", + "intro": ["Test your knowledge of typography with this quiz."] + }, + "lecture-best-practices-for-accessibility-and-css": { + "title": "Best Practices for Accessibility and CSS", + "intro": [ + "In these lectures, you will learn about best practices for accessibility in CSS, and the tools for checking good color contrast on websites." + ] + }, + "workshop-accessibility-quiz": { + "title": "Build a Quiz Webpage", + "intro": [ + "Accessibility is the process of making your webpages usable for everyone, including people with disabilities.", + "In this workshop, you'll build a quiz webpage. You'll learn accessibility tools such as keyboard shortcuts, ARIA attributes, and design best practices." + ] + }, + "lab-tribute-page": { + "title": "Build a Tribute Page", + "intro": [ + "In this lab, you'll build a tribute page for a subject of your choosing, fictional or real." + ] + }, + "review-css-accessibility": { + "title": "CSS Accessibility Review", + "intro": [ + "Before you're quizzed on CSS and accessibility, you should review what you've learned.", + "Open up this page to review concepts like color contrast tools and accessibility best practices." + ] + }, + "quiz-css-accessibility": { + "title": "CSS Accessibility Quiz", + "intro": [ + "In this quiz, you'll test what you've learned about making your webpages accessible with CSS." + ] + }, + "lecture-understanding-how-to-work-with-floats-and-positioning-in-css": { + "title": "Understanding How to Work with Floats and Positioning in CSS", + "intro": [ + "In these lectures, you will learn how to use CSS positioning and floats. You will learn about absolute, relative, fixed, and sticky positioning. You will also use the z-index property." + ] + }, + "workshop-cat-painting": { + "title": "Build a Cat Painting", + "intro": [ + "Mastering CSS positioning is essential for creating visually appealing and responsive web layouts.", + "In this workshop, you will build a cat painting. You'll learn about how to work with absolute positioning, the z-index property, and the transform property." + ] + }, + "lab-house-painting": { + "title": "Build a House Painting", + "intro": [ + "In this lab, you'll build a house painting using CSS.", + "You'll design individual elements of the house and position them using CSS properties like position, top, left, and more." + ] + }, + "review-css-positioning": { + "title": "CSS Positioning Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS positioning, you should review what you've learned.", + "Open up this page to review concepts like floats, relative positioning, absolute positioning and more." + ] + }, + "quiz-css-positioning": { + "title": "CSS Positioning Quiz", + "intro": ["Test your knowledge of CSS positioning with this quiz."] + }, + "lecture-working-with-attribute-selectors": { + "title": "Working with Attribute Selectors", + "intro": [ + "In these lectures, you will learn about attribute selectors and how to use them to target elements like links and lists." + ] + }, + "workshop-balance-sheet": { + "title": "Build a Balance Sheet", + "intro": [ + "In this workshop, you'll build a balance sheet using pseudo selectors. You'll learn how to change the style of an element when you hover over it with your mouse, and trigger other events on your webpage." + ] + }, + "review-css-attribute-selectors": { + "title": "CSS Attribute Selectors Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS attribute selectors, you should review what you've learned about them.", + "Open up this page to review concepts like how to work with different attribute selectors that target links with the href and title attributes." + ] + }, + "quiz-css-attribute-selectors": { + "title": "CSS Attribute Selectors Quiz", + "intro": [ + "Test your knowledge of CSS attribute selectors with this quiz." + ] + }, + "lab-book-inventory-app": { + "title": "Build a Book Inventory App", + "intro": [ + "In this lab, you'll create a book inventory app.", + "You'll practice CSS attribute selectors like [attribute], [attribute=value], [attribute~=value], and more." + ] + }, + "lecture-best-practices-for-responsive-web-design": { + "title": "Best Practices for Responsive Web Design", + "intro": [ + "In these lectures, you will learn about the best practices for responsive web design, the roles concepts like grid, flexbox, media queries, and media breakpoints play in responsive design, and more." + ] + }, + "workshop-piano": { + "title": "Design a Piano", + "intro": [ + "Responsive Design tells your webpage how it should look on different-sized screens.", + "In this workshop, you'll use CSS and responsive design to code a piano. You'll also practice media queries and pseudo selectors." + ] + }, + "review-responsive-web-design": { + "title": "Responsive Web Design Review", + "intro": [ + "Before you're quizzed on the fundamentals of responsive design, you should review what you've learned.", + "Open up this page to review concepts like media queries, media breakpoints and mobile first approach design." + ] + }, + "quiz-responsive-web-design": { + "title": "Responsive Web Design Quiz", + "intro": [ + "Test what you've learned about making your webpages responsive with this quiz." + ] + }, + "lab-technical-documentation-page": { + "title": "Build a Technical Documentation Page", + "intro": [ + "In this lab, you'll build a technical documentation page to serve as instruction or reference for a topic.", + "You'll also practice media queries to create a responsive design." + ] + }, + "lecture-working-with-css-variables": { + "title": "Working with CSS Variables", + "intro": [ + "In these lectures, you will learn how to define and use custom properties (also known as CSS variables). You will also learn about the @property rule and how it works." + ] + }, + "workshop-city-skyline": { + "title": "Build a City Skyline", + "intro": [ + "CSS variables help you organize your styles and reuse them.", + "In this workshop, you'll build a city skyline. You'll practice how to configure CSS variables so you can reuse them whenever you want." + ] + }, + "lab-availability-table": { + "title": "Build an Availability Table", + "intro": [ + "For this lab, you'll create an availability table that shows the availability of people for a meeting.", + "You'll practice using CSS variables to store and reuse colors, fonts, and other styles." + ] + }, + "review-css-variables": { + "title": "CSS Variables Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS variables, you should review what you've learned.", + "Open up this page to review how to work with CSS custom properties (CSS variables) and the @property rule." + ] + }, + "quiz-css-variables": { + "title": "CSS Variables Quiz", + "intro": ["Test your knowledge of CSS variables with this quiz."] + }, + "lecture-working-with-css-grid": { + "title": "Working with CSS Grid", + "intro": [ + "In these lectures, you will learn about CSS grid, its several properties and how to use them, and how CSS grid differs from flexbox." + ] + }, + "workshop-magazine": { + "title": "Build a Magazine", + "intro": [ + "CSS Grid gives you control over the rows and columns of your webpage design.", + "In this workshop, you'll build a magazine article. You'll practice how to use CSS Grid, including concepts like grid rows and grid columns." + ] + }, + "lab-newspaper-layout": { + "title": "Design a Newspaper Layout", + "intro": [ + "In this lab, you will design a newspaper layout using CSS Grid, including concepts like grid rows and grid columns." + ] + }, + "lecture-debugging-css": { + "title": "Debugging CSS", + "intro": [ + "In this lecture, you'll learn how to debug CSS using your browser's developer tools and CSS validators." + ] + }, + "review-css-grid": { + "title": "CSS Grid Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS Grid, you should review what you've learned.", + "Open up this page to review how to work with the different CSS Grid properties like grid-template-columns, grid-gap and more." + ] + }, + "quiz-css-grid": { + "title": "CSS Grid Quiz", + "intro": ["Test your knowledge of CSS Grid with this quiz."] + }, + "lab-product-landing-page": { + "title": "Build a Product Landing Page", + "intro": [ + "In this project, you'll build a product landing page to market a product of your choice." + ] + }, + "lecture-animations-and-accessibility": { + "title": "Animations and Accessibility", + "intro": [ + "In these lectures, you will learn about CSS animations and their accessibility concerns. You will also learn how prefers-reduced-motion can help address those accessibility concerns." + ] + }, + "workshop-ferris-wheel": { + "title": "Build an Animated Ferris Wheel", + "intro": [ + "You can use CSS animation to draw attention to specific sections of your webpage and make it more engaging.", + "In this workshop, you'll build a Ferris wheel. You'll practice how to use CSS to animate elements, transform them, and adjust their speed." + ] + }, + "lab-moon-orbit": { + "title": "Build a Moon Orbit", + "intro": [ + "In this lab, you'll create an animation of the moon orbiting the earth.", + "You'll practice animation properties like animation-name, animation-duration, animation-timing-function, and more." + ] + }, + "workshop-flappy-penguin": { + "title": "Build a Flappy Penguin", + "intro": [ + "You can transform HTML elements to create appealing designs that draw your reader's eye. You can use transforms to rotate elements, scale them, and more.", + "In this workshop, you'll build a penguin. You'll use CSS transforms to position and resize the parts of your penguin, create a background, and animate your work." + ] + }, + "lab-personal-portfolio": { + "title": "Build a Personal Portfolio", + "intro": [ + "In this project, you'll build your own personal portfolio page." + ] + }, + "review-css-animations": { + "title": "CSS Animations Review", + "intro": [ + "Before you're quizzed on working with CSS animations, you should review what you've learned about them.", + "Open up this page to review concepts including prefers-reduced-motion, the @keyframes rule and more." + ] + }, + "quiz-css-animations": { + "title": "CSS Animations Quiz", + "intro": ["Test your knowledge of CSS animations with this quiz."] + }, + "review-css": { + "title": "CSS Review", + "intro": [ + "Before you take the CSS prep exam, you first need to review the concepts taught in the previous modules.", + "Open up this page to review concepts around the basics of CSS, responsive web design, animations, accessibility and more." + ] + }, + "exam-responsive-web-design-certification": { + "title": "Responsive Web Design Certification Exam", + "intro": [ + "Pass this exam to earn your Responsive Web Design Certification Exam" + ] + } + } + }, + "a2-professional-spanish": { + "title": "A2 Professional Spanish Certification (Beta)", + "note": "This certification is currently in active development. New content will be published as our instructional design team develops it. Once all content is available, we will release the certification exam.", + "intro": ["Placeholder intro"], + "blocks": { + "talk-about-who-you-are-by-using-key-verbs": { + "title": "Talk About Who You Are by Using Key Verbs", + "intro": [ + "Learn how to introduce yourself in Spanish in a simple and professional way. In this module you'll learn how to say who you are, where you are from, what you do, how you feel, and what you like or don't like." + ] + }, + "get-to-know-others-by-asking-simple-questions": { + "title": "Get to Know Others by Asking Simple Questions", + "intro": [ + "Learn how to ask and answer questions in simple conversations. Through five short dialogues, practice talking about routines, feelings, preferences, workspaces, and personal information. You'll also learn to ask polite questions, give short answers, and use negation naturally." + ] + } + } + }, + "a2-professional-chinese": { + "title": "A2 Professional Chinese Certification (Beta)", + "note": "This certification is currently in active development. New content will be published as our instructional design team develops it. Once all content is available, we will release the certification exam.", + "intro": ["Placeholder intro"], + "blocks": { + "talk-about-what-you-do-by-using-key-verbs": { + "title": "Talk About What You Do by Using Key Verbs", + "intro": [ + "Learn how to introduce yourself in Chinese in a simple and professional way. In this module you'll learn how to say who you are, where you are from, what you do, how you feel, and what you like or don't like." + ] + }, + "get-to-know-colleagues-by-asking-simple-questions": { + "title": "Get to Know Colleagues by Asking Simple Questions", + "intro": [ + "Learn how to ask and answer questions in simple conversations. Through five short dialogues, practice talking about routines, feelings, preferences, workspaces, and personal information. You'll also learn to ask polite questions, give short answers, and use negation naturally." + ] + } + } + }, + "a1-professional-chinese": { + "title": "A1 Professional Chinese Certification (Beta)", + "note": "This certification is currently in active development. New content will be published as our instructional design team develops it. Once all content is available, we will release the certification exam.", + "intro": [ + "In this A1 Professional Chinese Curriculum, you'll learn the building blocks of the Chinese language. This will follow the A1 level of the Common European Framework of Reference (CEFR). And we've focused on vocabulary that is particularly useful for professional settings.", + "The curriculum is broken down into several modules that include warm-up, learning, practice, review pages, and quizzes to make sure that you truly understand the material before moving on to the next module.", + "Each chapter includes hundreds of interactive tasks designed to help you take your first steps in learning Chinese with confidence." + ], + "chapters": { + "zh-a1-chapter-welcome-to-a1-professional-chinese": "Welcome to A1 Professional Chinese", + "zh-a1-chapter-pinyin": "Pinyin", + "zh-a1-chapter-greetings-and-introductions": "Greetings and Introductions", + "zh-a1-chapter-numbers-and-personal-information": "Numbers and Personal Information", + "zh-a1-chapter-expressing-what-you-can-and-cant-do": "Expressing What You Can and Can't Do" + }, + "modules": { + "zh-a1-module-introduction-and-certification-overview": "Introduction and Certification Overview", + "zh-a1-module-initials-and-finals": "Initials and Finals", + "zh-a1-module-greetings-and-basic-introductions": "Greetings and Basic Introductions", + "zh-a1-module-asking-and-giving-basic-information": "Asking and Giving Basic Information", + "zh-a1-module-numbers-below-100": "Numbers Below 100", + "zh-a1-module-communicating-personal-information": "Communicating Personal Information", + "zh-a1-module-talking-about-personal-skills": "Talking about Personal Skills", + "zh-a1-module-discussing-team-skills": "Discussing Team Skills" + }, + "module-intros": { + "zh-a1-module-introducing-others": { + "note": "Coming 2026", + "intro": [ + "In this module, you will practice understanding short monologues that introduce information about other people, such as name, role, nationality, and age." + ] + }, + "zh-a1-module-getting-to-know-the-team": { + "note": "Coming 2026", + "intro": [ + "In this module, you will practice understanding a short conversation that asks and answers simple questions about colleagues." + ] + }, + "zh-a1-module-communicating-personal-information": { + "note": "Coming 2026", + "intro": [ + "In this module, you will practice understanding conversations that communicate personal information, such as age and phone numbers." + ] + }, + "zh-a1-module-talking-about-personal-skills": { + "note": "Coming 2026", + "intro": [ + "In this module, you will practice understanding short monologues about what people can and cannot do, such as languages and work skills." + ] + }, + "zh-a1-module-discussing-team-skills": { + "note": "Coming 2026", + "intro": [ + "In this module, you will practice understanding a short conversation about who can do which tasks on a team and how a project starts." + ] + } + }, + "blocks": { + "zh-a1-learn-certification-introduction": { + "title": "Certification Introduction", + "intro": ["", ""] + }, + "zh-a1-learn-simple-finals": { + "title": "Simple Finals", + "intro": ["", ""] + }, + "zh-a1-learn-initials": { "title": "Initials", "intro": ["", ""] }, + "zh-a1-learn-compound-finals": { + "title": "Compound Finals", + "intro": ["", ""] + }, + "zh-a1-learn-nasal-finals": { + "title": "Nasal Finals", + "intro": ["", ""] + }, + "zh-a1-warm-up-greeting-new-colleagues": { + "title": "Greeting New Colleagues", + "intro": ["", ""] + }, + "zh-a1-learn-understanding-greetings-and-introductions": { + "title": "Understanding Greetings and Introductions", + "intro": ["", ""] + }, + "zh-a1-practice-introducing-yourself": { + "title": "​Introducing Yourself", + "intro": ["", ""] + }, + "zh-a1-review-greetings-and-introductions": { + "title": "Greetings and Introductions Review", + "intro": ["", ""] + }, + "zh-a1-quiz-greetings-and-introductions": { + "title": "Greetings and Introductions Quiz", + "intro": ["", ""] + }, + "zh-a1-learn-understanding-questions-and-answers": { + "title": "Understanding Questions and Answers", + "intro": ["", ""] + }, + "zh-a1-practice-exchanging-basic-information": { + "title": "Exchanging Basic Information", + "intro": ["", ""] + }, + "zh-a1-review-introduction-questions": { + "title": "Introduction Questions Review", + "intro": ["", ""] + }, + "zh-a1-quiz-introduction-questions": { + "title": "Introduction Questions Quiz", + "intro": ["", ""] + }, + "zh-a1-warm-up-introducing-others-basics": { + "title": "Introducing Others Basics", + "intro": ["", ""] + }, + "zh-a1-learn-meeting-the-team": { + "title": "Meeting the Team", + "intro": ["", ""] + }, + "zh-a1-learn-a-new-colleague": { + "title": "A New Colleague", + "intro": ["", ""] + }, + "zh-a1-learn-my-family": { "title": "My Family", "intro": ["", ""] }, + "zh-a1-practice-introducing-others": { + "title": "Introducing Others Practice", + "intro": ["", ""] + }, + "zh-a1-review-introducing-others": { + "title": "Introducing Others Review", + "intro": ["", ""] + }, + "zh-a1-quiz-check-your-introduction": { + "title": "Check Your Introduction", + "intro": ["", ""] + }, + "zh-a1-warm-up-knowing-the-team-basics": { + "title": "Knowing the Team Basics", + "intro": ["", ""] + }, + "zh-a1-learn-asking-about-the-team": { + "title": "Asking about the Team", + "intro": ["", ""] + }, + "zh-a1-practice-talking-about-others": { + "title": "Talking about Others", + "intro": ["", ""] + }, + "zh-a1-review-team-introduction": { + "title": "Team Introduction Review", + "intro": ["", ""] + }, + "zh-a1-quiz-team-introduction": { + "title": "Team Introduction Quiz", + "intro": ["", ""] + }, + "zh-a1-warm-up-personal-skills-basics": { + "title": "Personal Skills Basics", + "intro": ["", ""] + }, + "zh-a1-learn-can-or-cannot": { + "title": "Can or Can't", + "intro": ["", ""] + }, + "zh-a1-practice-personal-skills": { + "title": "Personal Skills Practice", + "intro": ["", ""] + }, + "zh-a1-review-describing-skills": { + "title": "Describing Skills Review", + "intro": ["", ""] + }, + "zh-a1-quiz-describing-skills": { + "title": "Describing Skills Quiz", + "intro": ["", ""] + }, + "zh-a1-warm-up-team-skills-basics": { + "title": "Team Skills Basics", + "intro": ["", ""] + }, + "zh-a1-learn-who-can-do-what-on-the-team": { + "title": "Who Can Do What on the Team", + "intro": ["Learn to discuss team member capabilities and roles."] + }, + "zh-a1-practice-talking-about-skills": { + "title": "Talking about Skills", + "intro": ["Practice discussing various skills in team contexts."] + }, + "zh-a1-review-discussing-team-skills": { + "title": "Discussing Team Skills Review", + "intro": ["", ""] + }, + "zh-a1-quiz-discussing-team-skills": { + "title": "Discussing Team Skills Quiz", + "intro": ["", ""] + }, + "zh-a1-warm-up-meeting-new-teammates": { + "title": "Meeting New Teammates", + "intro": ["", ""] + }, + "zh-a1-learn-special-spelling-rules": { + "title": "Special Spelling Rules", + "intro": ["", ""] + }, + "zh-a1-practice-pinyin": { + "title": "Pinyin Practice", + "intro": ["", ""] + }, + "zh-a1-learn-numbers-0-to-10": { + "title": "Numbers 0 to 10", + "intro": ["", ""] + }, + "zh-a1-practice-numbers-0-to-10": { + "title": "Numbers 0 to 10 Practice", + "intro": ["", ""] + }, + "zh-a1-learn-numbers-11-to-19": { + "title": "Numbers 11 to 19", + "intro": ["", ""] + }, + "zh-a1-practice-numbers-11-to-19": { + "title": "Numbers 11 to 19 Practice", + "intro": ["", ""] + }, + "zh-a1-learn-numbers-20-to-99": { + "title": "Numbers 20 to 99", + "intro": ["", ""] + }, + "zh-a1-practice-numbers-20-to-99": { + "title": "Numbers 20 to 99 Practice", + "intro": ["", ""] + }, + "zh-a1-review-numbers-below-100": { + "title": "Numbers Below 100 Review", + "intro": ["", ""] + }, + "zh-a1-quiz-numbers-below-100": { + "title": "Numbers Below 100 Quiz", + "intro": ["", ""] + } + } + }, + "basic-html": { + "title": "Learn Basic HTML", + "summary": [ + "Learn how to build simple webpages using HTML tags to add text, images, and links." + ], + "intro": [ + "HTML stands for HyperText Markup Language and represents the content and structure for a web page. In this course, you will learn the basics of writing HTML." + ], + "blocks": { + "workshop-curriculum-outline": { + "title": "Build a Curriculum Outline", + "intro": [ + "Welcome to freeCodeCamp!", + "This workshop will serve as your introduction to HTML and coding in general. You will learn about headings and paragraph elements." + ] + }, + "lab-debug-camperbots-profile-page": { + "title": "Debug Camperbot's Profile Page", + "intro": [ + "Camperbot is learning how to code too and needs some help with their HTML.", + "In this lab, you will help Camperbot find and fix the errors in their code." + ] + }, + "lecture-understanding-html-attributes": { + "title": "Understanding HTML Attributes", + "intro": [ + "In these lectures, you will learn more about HTML (HyperText Markup Language), a markup language for creating web pages.", + "You will learn about HTML's role on the web, and what HTML attributes are." + ] + }, + "lab-debug-pet-adoption-page": { + "title": "Debug a Pet Adoption Page", + "intro": [ + "In this lab, you will need to find and fix the errors in this pet adoption page." + ] + }, + "lecture-understanding-the-html-boilerplate": { + "title": "Understanding the HTML Boilerplate", + "intro": [ + "In these lectures, you will learn about the HTML boilerplate, which is a ready-made template for your webpages.", + "You will learn how to work with the link element, meta element and more." + ] + }, + "workshop-cat-photo-app": { + "title": "Build a Cat Photo App", + "intro": [ + "HTML stands for HyperText Markup Language and it represents the content and structure of a web page.", + "In this workshop, you will learn how to work with basic HTML elements such as headings, paragraphs, images, links, and lists." + ] + }, + "lab-recipe-page": { + "title": "Build a Recipe Page", + "intro": [ + "In this lab, you'll review HTML basics by creating a web page of your favorite recipe. You'll create an HTML boilerplate and work with headings, lists, images, and more." + ] + }, + "lecture-html-fundamentals": { + "title": "HTML Fundamentals", + "intro": [ + "In these lectures, you will learn about HTML fundamentals like the div element, the id and class attributes, the script element, HTML entities, and more." + ] + }, + "workshop-bookstore-page": { + "title": "Build a Bookstore Page", + "intro": [ + "In this workshop, you will practice working with classes, ids, and the div element by building a bookstore page." + ] + }, + "lecture-understanding-how-html-affects-seo": { + "title": "Understanding How HTML Affects SEO", + "intro": [ + "In these lectures, you will learn how your HTML code impacts search engine optimization." + ] + }, + "lab-travel-agency-page": { + "title": "Build a Travel Agency Page", + "intro": [ + "In this lab, you'll review working with HTML fundamentals by creating a web page for a travel agency. You'll work with images, the figure element, the figcaption element, the a element, and more." + ] + }, + "lecture-working-with-audio-and-video-elements": { + "title": "Working with Audio and Video Elements", + "intro": [ + "In this lecture, you will learn how to work with the audio and video elements." + ] + }, + "workshop-html-music-player": { + "title": "Build an HTML Music Player", + "intro": [ + "In this workshop, you'll use HTML to create a basic music player.", + "This project will cover the audio element, the audio player setup, and more." + ] + }, + "workshop-html-video-player": { + "title": "Build an HTML Video Player", + "intro": [ + "In this workshop, you'll use HTML to create a basic video player.", + "This project will cover the video element, the video player setup, and more." + ] + }, + "lab-html-audio-and-video-player": { + "title": "Build an HTML Audio and Video Player", + "intro": [ + "In this lab, you will build an HTML audio and video player using the video and audio elements with controls and source attributes." + ] + }, + "lecture-working-with-images-and-svgs": { + "title": "Working with Images and SVGs", + "intro": [ + "In these lectures, you will learn how to work with SVGs and explore techniques for optimizing your images." + ] + }, + "workshop-build-a-heart-icon": { + "title": "Build a Heart Icon", + "intro": [ + "In this workshop, you will practice working with SVGs by building a heart icon." + ] + }, + "lecture-working-with-media": { + "title": "Working with the iframe Element", + "intro": [ + "In these lectures, you will learn how to work with the iframe element which is used to embed an external site on your web page." + ] + }, + "workshop-build-a-video-display-using-iframe": { + "title": "Build a Video Display Using iframe", + "intro": [ + "In this workshop, you'll learn how to work with the iframe element by building a video display." + ] + }, + "lab-video-compilation-page": { + "title": "Build a Video Compilation Page", + "intro": [ + "In this lab, you'll create a video compilation web page. You'll practice working with the iframe element." + ] + }, + "lecture-working-with-links": { + "title": "Working with Links", + "intro": [ + "In these lectures, you will learn about links, the target attribute, different link states, absolute and relative paths, and more." + ] + }, + "review-basic-html": { + "title": "Basic HTML Review", + "intro": [ + "Before you are quizzed on the HTML knowledge you have gained so far, you first need to review the concepts.", + "Open up this page to review the HTML boilerplate, audio and video elements, the different target attribute values and more." + ] + }, + "quiz-basic-html": { + "title": "Basic HTML Quiz", + "intro": [ + "The following quiz will test your knowledge of the basic HTML concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + } + } + }, + "semantic-html": { + "title": "Learn Semantic HTML", + "summary": [ + "Discover how to write cleaner, more meaningful HTML using semantic tags that improve structure, accessibility, and SEO." + ], + "intro": [ + "In this interactive course, you will practice writing semantic HTML." + ], + "blocks": { + "lecture-importance-of-semantic-html": { + "title": "Importance of Semantic HTML", + "intro": [ + "In these lectures, you will learn about semantic HTML and why you should care about it, semantic elements, how semantic HTML differs from presentational HTML, and more." + ] + }, + "lecture-understanding-nuanced-semantic-elements": { + "title": "Understanding Nuanced Semantic Elements", + "intro": [ + "In these lectures, you will learn when you should use certain semantic elements like the em element over the i element, description lists, and more." + ] + }, + "workshop-major-browsers-list": { + "title": "Build a List of Major Web Browsers", + "intro": [ + "In this workshop, you will build a description list and work with the dl, dt, and dd elements." + ] + }, + "lecture-working-with-text-and-time-semantic-elements": { + "title": "Working with Text and Time Semantic Elements ", + "intro": [ + "In this lecture, you will learn about the importance of semantics in conveying meaning for text and time-related content including the time and blockquote elements, and more." + ] + }, + "workshop-quincys-job-tips": { + "title": "Build Quincy's Job Tips Page", + "intro": [ + "In this workshop, you will practice working with semantic HTML by using the q, blockquote, and cite elements." + ] + }, + "lecture-working-with-specialized-semantic-elements": { + "title": "Working with Specialized Semantic Elements", + "intro": [ + "In this lecture, you will learn about specialized semantic elements like u, s, code elements and more." + ] + }, + "workshop-blog-page": { + "title": "Build a Cat Blog Page", + "intro": [ + "In this workshop, you will build an HTML-only blog page using semantic elements including the main, nav, article, and footer elements." + ] + }, + "lab-event-hub": { + "title": "Build an Event Hub", + "intro": [ + "In this lab, you'll build an event hub and review semantic elements like header, nav, article, and more." + ] + }, + "review-semantic-html": { + "title": "Semantic HTML Review", + "intro": [ + "Before you are quizzed on semantic HTML, you first need to review the concepts.", + "Open up this page to review the em, strong, blockquote, address and more semantic HTML elements." + ] + }, + "quiz-semantic-html": { + "title": "Semantic HTML Quiz", + "intro": [ + "The following quiz will test your knowledge on semantic HTML concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + } + } + }, + "html-and-accessibility": { + "title": "Learn HTML and Accessibility", + "summary": [ + "Learn how to write inclusive HTML using accessibility best practices and ARIA." + ], + "intro": [ + "Practice writing accessible HTML structures and form experiences." + ], + "blocks": { + "lecture-importance-of-accessibility-and-good-html-structure": { + "title": "Importance of Accessibility and Good HTML Structure", + "intro": [ + "In these lessons, you will learn about accessibility and its importance, assistive tools for people with disabilities, HTML attributes that let you create inclusive websites, accessibility best practices, and much more." + ] + }, + "workshop-debug-coding-journey-blog-page": { + "title": "Debug a Coding Journey Blog Page", + "intro": [ + "In this workshop, you will debug and fix accessibility errors in a coding blog page." + ] + }, + "lecture-accessible-tables-forms": { + "title": "Working with Accessible Tables and Forms", + "intro": [ + "In these lessons, you will learn about how to create accessible tables and forms." + ] + }, + "workshop-tech-conference-schedule": { + "title": "Build a Tech Conference Schedule Table", + "intro": [ + "In this workshop, you will build an accessible tech conference schedule table." + ] + }, + "lab-debug-donation-form": { + "title": "Debug a Donation Form", + "intro": [ + "In this lab you will debug a donation form by fixing HTML syntax errors and improving accessibility." + ] + }, + "lecture-introduction-to-aria": { + "title": "Introduction to ARIA", + "intro": [ + "In these lectures, you will learn about working with ARIA roles." + ] + }, + "workshop-accessible-audio-controller": { + "title": "Build an Accessible Audio Controller", + "intro": [ + "In this workshop, you will practice accessible HTML by building an audio controller that uses the aria-labelledby attribute." + ] + }, + "lecture-accessible-media-elements": { + "title": "Working with Accessible Media Elements", + "intro": [ + "In these lectures, you will learn about how to create accessible links, audio and video content." + ] + }, + "lab-checkout-page": { + "title": "Build a Checkout Page", + "intro": [ + "In this lab, you'll create an accessible checkout page.", + "You'll practice concepts like alt attributes and ARIA roles." + ] + }, + "lab-movie-review-page": { + "title": "Design a Movie Review Page", + "intro": [ + "In this lab, you'll create a movie review page.", + "You'll practice concepts like semantic HTML, alt attributes, accessible lists, and hiding decorative content from screen readers using aria-hidden." + ] + }, + "lab-multimedia-player": { + "title": "Build a Multimedia Player", + "intro": [ + "In this lab, you'll build a multimedia player.", + "You will practice working with the audio and video elements, the controls attribute, and the aria-label attribute." + ] + }, + "review-html-accessibility": { + "title": "HTML Accessibility Review", + "intro": [ + "Before you are quizzed on HTML and accessibility, you first need to review the concepts.", + "Open up this page to review concepts including the aria-hidden, aria-describedby, tabindex attributes and more." + ] + }, + "quiz-html-accessibility": { + "title": "HTML Accessibility Quiz", + "intro": [ + "The following quiz will test your knowledge on the accessibility concepts you have learned so far.", + "If you're getting ready for the exam, there are several quiz sets available for practice. After completing a quiz, you can revisit this page to access a new set of questions." + ] + } + } + }, + "computer-basics": { + "title": "Learn Computer Basics", + "summary": [ + "Build a foundation in computer, internet, and tooling basics for web development." + ], + "intro": [ + "Get comfortable with the tools and concepts that power modern web development." + ], + "blocks": { + "lecture-understanding-computer-internet-and-tooling-basics": { + "title": "Understanding Computer, Internet, and Tooling Basics", + "intro": [ + "In these lessons, you will learn about computers and their different parts, how to work safely with a keyboard and mouse, how to sign into your computer securely, internet service providers (ISPs), and the tools professional developers use." + ] + }, + "lecture-working-with-file-systems": { + "title": "Working with File Systems", + "intro": [ + "In these lessons, you will learn how to work with file and folder systems on your computers. You will learn how to create, move, and delete files and folders, the best practices for naming and organizing files and folders, and more." + ] + }, + "lecture-browsing-the-web-effectively": { + "title": "Browsing the Web Effectively", + "intro": [ + "In these lessons, you will learn about what websites, search engine, and web browsers are, the different browsers available, and how to get the best out of a search engine." + ] + }, + "review-computer-basics": { + "title": "Computer Basics Review", + "intro": [ + "Before you are quizzed on basic computer and internet concepts, you first need to review.", + "Open up this page to review concepts like RAM, Internet service providers, common web browsers, search engines and more." + ] + }, + "quiz-computer-basics": { + "title": "Computer Basics Quiz", + "intro": [ + "Test what you've learned in this quiz of basic computer knowledge." + ] + } + } + }, + "basic-css": { + "title": "Learn Basic CSS", + "summary": [ + "Learn core CSS concepts and start styling real-world layouts." + ], + "intro": [ + "Learn the fundamentals of CSS and apply them to practical layouts." + ], + "blocks": { + "lecture-what-is-css": { + "title": "What Is CSS?", + "intro": [ + "The following lessons are all about CSS. You will learn what CSS is and its role on the web, a CSS rule and its anatomy, the three ways to write CSS and when to use each, inline and block elements, and many more." + ] + }, + "workshop-cafe-menu": { + "title": "Design a Cafe Menu", + "intro": [ + "CSS tells the browser how to display your webpage. You can use CSS to set the color, font, size, and other aspects of HTML elements.", + "In this workshop, you'll learn CSS by designing a menu page for a cafe." + ] + }, + "lab-business-card": { + "title": "Design a Business Card", + "intro": [ + "In this lab, you'll create a business card and style it using CSS.", + "You'll practice style properties like color, font-size, text-align, and more." + ] + }, + "lecture-css-specificity-the-cascade-algorithm-and-inheritance": { + "title": "CSS Specificity, the Cascade Algorithm, and Inheritance", + "intro": [ + "In these lessons, you will learn about CSS specificity, the common selectors and their specificities, the cascade algorithm, inheritance, and more." + ] + }, + "review-basic-css": { + "title": "CSS Fundamentals Review", + "intro": [ + "Before you are quizzed on basic CSS concepts, you first need to review.", + "Open up this page to review concepts including margin, padding, CSS combinators, CSS specificity and more." + ] + }, + "quiz-basic-css": { + "title": "CSS Fundamentals Quiz", + "intro": [ + "Test what you've learned in this quiz of basic CSS knowledge." + ] + }, + "lecture-styling-lists-and-links": { + "title": "Styling Lists and Links", + "intro": [ + "In these lessons, you will learn the properties you need to know to effectively style lists and links, including link states like link, visited, hover, and active." + ] + }, + "lab-stylized-to-do-list": { + "title": "Build a Stylized To-Do List", + "intro": [ + "In this lab, you'll build a To-Do list and apply different styles to the links", + "You'll practice style properties like text-decoration, list-style-type and how to change styles on hover or click." + ] + }, + "lecture-working-with-backgrounds-and-borders": { + "title": "Working with Backgrounds and Borders", + "intro": [ + "In these lessons, you will learn about the properties and values you need to know to style backgrounds and borders of elements, alongside the accessibility considerations for backgrounds." + ] + }, + "lab-blog-post-card": { + "title": "Design a Blog Post Card", + "intro": [ + "In this lab, you'll design a blog post card using HTML and CSS", + "You'll practice concepts like background-color, border-radius, margins, paddings, and more." + ] + }, + "review-css-backgrounds-and-borders": { + "title": "Lists, Links, CSS Background and Borders Review", + "intro": [ + "Before you are quizzed on CSS backgrounds and borders, you first need to review.", + "Open up this page to review concepts including the background-image property, border property and more." + ] + }, + "quiz-css-backgrounds-and-borders": { + "title": "CSS Backgrounds and Borders Quiz", + "intro": [ + "Test what you've learned in this quiz of backgrounds and borders in CSS." + ] + } + } + }, + "design-for-developers": { + "title": "Introduction to UI/UX Design", + "summary": [ + "Explore UI design fundamentals and user-centered design principles for developers." + ], + "intro": [ + "Learn the design principles that help developers build better interfaces." + ], + "blocks": { + "lecture-user-interface-design-fundamentals": { + "title": "User Interface Design Fundamentals", + "intro": [ + "In these lessons, you will learn about the fundamentals of user interface (UI) design. You will learn about the terms you need to know to communicate with designers, visual hierarchy, scaling, alignment, whitespace, and much more." + ] + }, + "lecture-user-centered-design": { + "title": "User-Centered Design", + "intro": [ + "In these lessons, you will learn about best practices for designing user-facing features like dark mode, breadcrumbs, modal dialogs, and much more. You will also learn how to conduct user research, user requirements and testing." + ] + }, + "lecture-common-design-tools": { + "title": "Common Design Tools", + "intro": [ + "In these lessons, you will learn about the common design tools developers should know. You will also learn about design briefs and how developers work with them." + ] + }, + "review-design-fundamentals": { + "title": "Design Fundamentals Review", + "intro": [ + "Before you are quizzed on the design fundamentals you have learned so far, you first need to review.", + "Open up this page to review concepts like user-centered design, scale, alignment, good visual hierarchy and more." + ] + }, + "quiz-design-fundamentals": { + "title": "Design Fundamentals Quiz", + "intro": [ + "Test what you've learned in this quiz of UI design fundamentals." + ] + } + } + }, + "absolute-and-relative-units": { + "title": "Learn Absolute and Relative Units in CSS", + "summary": [ + "Understand when to use absolute and relative CSS units to build flexible layouts." + ], + "intro": ["Learn to size elements responsively with CSS units."], + "blocks": { + "lecture-working-with-relative-and-absolute-units": { + "title": "Working with Relative and Absolute Units", + "intro": [ + "In these lessons, you will learn about relative and absolute units, and how they both impact what you see in the browser." + ] + }, + "lab-event-flyer-page": { + "title": "Build an Event Flyer Page", + "intro": [ + "In this lab, you'll create an event flyer page.", + "You will practice aligning elements using absolute and relative CSS." + ] + }, + "review-css-relative-and-absolute-units": { + "title": "CSS Relative and Absolute Units Review", + "intro": [ + "Before you are quizzed on relative and absolute units, you first need to review.", + "Open up this page to review concepts like percentages, px, rem, em, and more." + ] + }, + "quiz-css-relative-and-absolute-units": { + "title": "CSS Relative and Absolute Units Quiz", + "intro": [ + "Test what you've learned in this quiz of relative and absolute units in CSS." + ] + } + } + }, + "pseudo-classes-and-elements": { + "title": "Learn CSS Pseudo Classes and Elements", + "summary": [ + "Use pseudo-classes and pseudo-elements to create richer, more interactive styles." + ], + "intro": [ + "Add interaction and detail with CSS pseudo-classes and pseudo-elements." + ], + "blocks": { + "lecture-working-with-pseudo-classes-and-pseudo-elements-in-css": { + "title": "Working with Pseudo-Classes and Pseudo-Elements in CSS", + "intro": [ + "In these lessons, you will learn about pseudo-classes and pseudo-elements, alongside their examples and how they work." + ] + }, + "workshop-greeting-card": { + "title": "Design a Greeting Card", + "intro": [ + "In the previous lessons, you learned how to work with the different types of pseudo-classes.", + "In this workshop, you will have a chance to practice what you have learned by designing a greeting card." + ] + }, + "workshop-parent-teacher-conference-form": { + "title": "Design a Parent Teacher Conference Form", + "intro": [ + "In this workshop, you will practice how to style radio buttons with different types of pseudo-selectors by building a parent-teacher conference form.", + "You'll practice concepts including the ::before pseudo-element selector, the transform property, and more." + ] + }, + "lab-job-application-form": { + "title": "Build a Job Application Form", + "intro": [ + "In this lab you'll build a job application form and style it using pseudo-classes.", + "You'll practice concepts like :hover, :active, :focus, and more." + ] + }, + "review-css-pseudo-classes": { + "title": "CSS Pseudo-classes Review", + "intro": [ + "Before you're quizzed on CSS pseudo-classes and pseudo-elements, you should review what you've learned about them.", + "Open up this page to review concepts like the ::before and ::after pseudo-elements as well as the :hover, :active pseudo-classes and more." + ] + }, + "quiz-css-pseudo-classes": { + "title": "CSS Pseudo-classes Quiz", + "intro": ["Test your knowledge of CSS pseudo-classes with this quiz."] + } + } + }, + "css-colors": { + "title": "Learn CSS Colors", + "summary": [ + "Work with CSS color formats and build cohesive color palettes." + ], + "intro": ["Learn to apply color with CSS to create polished visuals."], + "blocks": { + "lecture-working-with-colors-in-css": { + "title": "Working with Colors in CSS", + "intro": [ + "In these lessons, you will learn about linear and radial gradients, the color theory, different kinds of colors like named, RGB, Hex, and HSL colors. You will learn how these colors work, and which to use in specific cases." + ] + }, + "workshop-colored-markers": { + "title": "Build a Set of Colored Markers", + "intro": [ + "In this workshop, you'll build a set of colored markers. You'll practice different ways to set color values and how to pair colors with each other." + ] + }, + "lab-colored-boxes": { + "title": "Design a Set of Colored Boxes", + "intro": [ + "In this lab, you'll create a color grid and practice adding background colors to the grid items using hex codes, RGB, and predefined color names." + ] + }, + "review-css-colors": { + "title": "CSS Colors Review", + "intro": [ + "Before you're quizzed on CSS colors, you should review what you've learned about them.", + "Open up this page to review concepts like the rgb() function, hsl() function, hex codes, and more." + ] + }, + "quiz-css-colors": { + "title": "CSS Colors Quiz", + "intro": ["Test your knowledge of CSS colors with this quiz."] + } + } + }, + "styling-forms": { + "title": "Learn How to Style Forms Using CSS", + "summary": ["Apply CSS techniques to create clean, usable form layouts."], + "intro": ["Style form elements to improve usability and visual clarity."], + "blocks": { + "lecture-best-practices-for-styling-forms": { + "title": "Best Practices for Styling Forms", + "intro": [ + "In these lessons, you will learn about the best practices for styling forms and issues you can encounter while styling special inputs like color and datetime-local." + ] + }, + "workshop-registration-form": { + "title": "Design a Registration Form", + "intro": [ + "In this workshop, you'll learn how to design HTML forms by designing a signup page. You'll learn how to control what types of data people can type into your form, and some new CSS tools for styling your page." + ] + }, + "lab-contact-form": { + "title": "Design a Contact Form", + "intro": [ + "In this lab, you'll design a contact form in HTML and style it using CSS." + ] + }, + "workshop-game-settings-panel": { + "title": "Build a Game Settings Panel", + "intro": [ + "In this workshop, you will practice styling checkboxes by building a game settings panel." + ] + }, + "lab-feature-selection": { + "title": "Design a Feature Selection Page", + "intro": [ + "In this lab, you'll build a feature selection page with custom-styled checkboxes.", + "You'll create feature cards with labels and checkboxes, then give custom styling to the checkboxes." + ] + }, + "review-styling-forms": { + "title": "Styling Forms Review", + "intro": [ + "Before you're quizzed on styling forms, you should review what you've learned.", + "Open up this page to review how to style form inputs, working with appearance: none and more." + ] + }, + "quiz-styling-forms": { + "title": "Styling Forms Quiz", + "intro": [ + "In this quiz, you will test your knowledge of how to style forms." + ] + } + } + }, + "css-box-model": { + "title": "Learn the CSS Box Model", + "summary": [ + "Master the CSS box model, spacing, and layout effects for precise designs." + ], + "intro": ["Learn how spacing, borders, and layout effects work together."], + "blocks": { + "lecture-working-with-css-transforms-overflow-and-filters": { + "title": "Working with CSS Transforms, Overflow, and Filters", + "intro": [ + "In these lessons, you will learn about working with CSS transforms, overflow, and filters. You will also learn about the box model and how it works." + ] + }, + "workshop-rothko-painting": { + "title": "Design a Rothko Painting", + "intro": [ + "Every HTML element is its own box – with its own spacing and a border. This is called the Box Model.", + "In this workshop, you'll use CSS and the Box Model to create your own Rothko-style rectangular art pieces." + ] + }, + "lab-confidential-email-page": { + "title": "Build a Confidential Email Page", + "intro": [ + "In this lab, you'll create a web page using HTML and mask the content using CSS properties." + ] + }, + "review-css-layout-and-effects": { + "title": "CSS Layouts and Effects Review", + "intro": [ + "Before you are quizzed on CSS Layouts and Effects, you first need to review.", + "Open up this page to review concepts like the transform property, the box model, the overflow property and more." + ] + }, + "quiz-css-layout-and-effects": { + "title": "CSS Layout and Effects Quiz", + "intro": [ + "In this quiz, you will test your knowledge of the box model, transforms, filters, and overflow in CSS." + ] + } + } + }, + "css-flexbox": { + "title": "Learn CSS Flexbox", + "summary": [ + "Build responsive layouts using the Flexbox model and alignment tools." + ], + "intro": ["Use Flexbox to build responsive, aligned layouts."], + "blocks": { + "lecture-working-with-css-flexbox": { + "title": "Working with CSS Flexbox", + "intro": [ + "In these lessons, you will learn how CSS flexbox works, its properties, and when you should use it." + ] + }, + "workshop-flexbox-photo-gallery": { + "title": "Build a Flexbox Photo Gallery", + "intro": [ + "In this workshop, you'll use Flexbox to build a responsive photo gallery webpage." + ] + }, + "workshop-colorful-boxes": { + "title": "Design a Set of Colorful Boxes", + "intro": [ + "In this workshop, you will practice working with CSS flexbox by designing a set of colored boxes." + ] + }, + "lab-pricing-plans-layout": { + "title": "Build a Pricing Plans Layout", + "intro": [ + "In this lab, you'll create a pricing plans layout.", + "You'll practice aligning elements using flexbox properties like flex-direction, justify-content, align-self, and more." + ] + }, + "lab-page-of-playing-cards": { + "title": "Build a Page of Playing Cards", + "intro": [ + "In this lab, you'll use flexbox to create a webpage of playing cards.", + "You'll practice aligning elements using flexbox properties like flex-direction, justify-content, align-self, and more." + ] + }, + "review-css-flexbox": { + "title": "CSS Flexbox Review", + "intro": [ + "Before you're quizzed on CSS flexbox, you should review what you've learned.", + "Open up this page to review concepts like the flex-direction, justify-content, align-items, flex-wrap properties, and more." + ] + }, + "quiz-css-flexbox": { + "title": "CSS Flexbox Quiz", + "intro": ["Test what you've learned on CSS flexbox with this quiz."] + } + } + }, + "css-typography": { + "title": "Learn CSS Typography", + "summary": [ + "Learn how to style text for readability, hierarchy, and visual balance." + ], + "intro": ["Use typography to improve readability and visual hierarchy."], + "blocks": { + "lecture-working-with-css-fonts": { + "title": "Working with CSS Fonts", + "intro": [ + "In these lessons, you will learn about typography and its best practices, fonts, and the text-shadow property." + ] + }, + "workshop-nutritional-label": { + "title": "Build a Nutritional Label", + "intro": [ + "Typography is the art of styling your text to be easily readable and suit its purpose.", + "In this workshop, you'll use typography to build a nutrition label webpage. You'll practice how to style text, adjust line height, and position your text using CSS." + ] + }, + "lab-newspaper-article": { + "title": "Build a Newspaper Article", + "intro": [ + "In this lab, you'll build a newspaper article page using HTML and CSS.", + "You'll style the fonts using properties like font-family, font-size, font-weight, and more." + ] + }, + "review-css-typography": { + "title": "CSS Typography Review", + "intro": [ + "Before you're quizzed on the fundamentals of typography, you should review what you've learned.", + "Open up this page to review concepts like web safe fonts, the font-family property and more." + ] + }, + "quiz-css-typography": { + "title": "CSS Typography Quiz", + "intro": ["Test your knowledge of typography with this quiz."] + } + } + }, + "css-and-accessibility": { + "title": "Learn CSS and Accessibility", + "summary": [ + "Apply CSS techniques that support accessible and inclusive interfaces." + ], + "intro": ["Design with accessibility in mind while styling UI elements."], + "blocks": { + "lecture-best-practices-for-accessibility-and-css": { + "title": "Best Practices for Accessibility and CSS", + "intro": [ + "In these lessons, you will learn about best practices for accessibility in CSS, and the tools for checking good color contrast on websites." + ] + }, + "workshop-accessibility-quiz": { + "title": "Build a Quiz Webpage", + "intro": [ + "Accessibility is the process of making your webpages usable for everyone, including people with disabilities.", + "In this workshop, you'll build a quiz webpage. You'll learn accessibility tools such as keyboard shortcuts, ARIA attributes, and design best practices." + ] + }, + "lab-tribute-page": { + "title": "Build a Tribute Page", + "intro": [ + "In this lab, you'll build a tribute page for a subject of your choosing, fictional or real." + ] + }, + "review-css-accessibility": { + "title": "CSS Accessibility Review", + "intro": [ + "Before you're quizzed on CSS and accessibility, you should review what you've learned.", + "Open up this page to review concepts like color contrast tools and accessibility best practices." + ] + }, + "quiz-css-accessibility": { + "title": "CSS Accessibility Quiz", + "intro": [ + "In this quiz, you'll test what you've learned about making your webpages accessible with CSS." + ] + } + } + }, + "css-positioning": { + "title": "Learn CSS Positioning", + "summary": [ + "Use positioning and floats to control layout and element flow." + ], + "intro": ["Control layout with floats and CSS positioning tools."], + "blocks": { + "lecture-understanding-how-to-work-with-floats-and-positioning-in-css": { + "title": "Understanding How to Work with Floats and Positioning in CSS", + "intro": [ + "In these lessons, you will learn how to use CSS positioning and floats. You will learn about absolute, relative, fixed, and sticky positioning. You will also use the z-index property." + ] + }, + "workshop-cat-painting": { + "title": "Build a Cat Painting", + "intro": [ + "Mastering CSS positioning is essential for creating visually appealing and responsive web layouts.", + "In this workshop, you will build a cat painting. You'll learn about how to work with absolute positioning, the z-index property, and the transform property." + ] + }, + "lab-house-painting": { + "title": "Build a House Painting", + "intro": [ + "In this lab, you'll build a house painting using CSS.", + "You'll design individual elements of the house and position them using CSS properties like position, top, left, and more." + ] + }, + "review-css-positioning": { + "title": "CSS Positioning Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS positioning, you should review what you've learned.", + "Open up this page to review concepts like floats, relative positioning, absolute positioning and more." + ] + }, + "quiz-css-positioning": { + "title": "CSS Positioning Quiz", + "intro": ["Test your knowledge of CSS positioning with this quiz."] + } + } + }, + "attribute-selectors": { + "title": "Learn CSS Attribute Selectors", + "summary": ["Target elements precisely with CSS attribute selectors."], + "intro": ["Select elements with precision using attribute selectors."], + "blocks": { + "lecture-working-with-attribute-selectors": { + "title": "Working with Attribute Selectors", + "intro": [ + "In these lessons, you will learn about attribute selectors and how to use them to target elements like links and lists." + ] + }, + "workshop-balance-sheet": { + "title": "Build a Balance Sheet", + "intro": [ + "In this workshop, you'll build a balance sheet using pseudo selectors. You'll learn how to change the style of an element when you hover over it with your mouse, and trigger other events on your webpage." + ] + }, + "lab-book-inventory-app": { + "title": "Build a Book Inventory App", + "intro": [ + "In this lab, you'll create a book inventory app.", + "You'll practice CSS attribute selectors like [attribute], [attribute=value], [attribute~=value], and more." + ] + }, + "review-css-attribute-selectors": { + "title": "CSS Attribute Selectors Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS attribute selectors, you should review what you've learned about them.", + "Open up this page to review concepts like how to work with different attribute selectors that target links with the href and title attributes." + ] + }, + "quiz-css-attribute-selectors": { + "title": "CSS Attribute Selectors Quiz", + "intro": [ + "Test your knowledge of CSS attribute selectors with this quiz." + ] + } + } + }, + "responsive-design": { + "title": "Learn Responsive Design", + "summary": [ + "Learn responsive design principles and build layouts that adapt to any screen." + ], + "intro": ["Make layouts adapt to different screen sizes and devices."], + "blocks": { + "lecture-best-practices-for-responsive-web-design": { + "title": "Best Practices for Responsive Web Design", + "intro": [ + "In these lessons, you will learn about the best practices for responsive web design, the roles concepts like grid, flexbox, media queries, and media breakpoints play in responsive design, and more." + ] + }, + "workshop-piano": { + "title": "Design a Piano", + "intro": [ + "Responsive Design tells your webpage how it should look on different-sized screens.", + "In this workshop, you'll use CSS and responsive design to code a piano. You'll also practice media queries and pseudo selectors." + ] + }, + "lab-technical-documentation-page": { + "title": "Build a Technical Documentation Page", + "intro": [ + "In this lab, you'll build a technical documentation page to serve as instruction or reference for a topic.", + "You'll also practice media queries to create a responsive design." + ] + }, + "review-responsive-web-design": { + "title": "Responsive Web Design Review", + "intro": [ + "Before you're quizzed on the fundamentals of responsive design, you should review what you've learned.", + "Open up this page to review concepts like media queries, media breakpoints and mobile first approach design." + ] + }, + "quiz-responsive-web-design": { + "title": "Responsive Web Design Quiz", + "intro": [ + "Test what you've learned about making your webpages responsive with this quiz." + ] + } + } + }, + "css-variables": { + "title": "Learn CSS Variables", + "summary": ["Use CSS variables to build reusable, theme-friendly styles."], + "intro": ["Create maintainable styles using CSS custom properties."], + "blocks": { + "lecture-working-with-css-variables": { + "title": "Working with CSS Variables", + "intro": [ + "In these lessons, you will learn how to define and use custom properties (also known as CSS variables). You will also learn about the @property rule and how it works." + ] + }, + "workshop-city-skyline": { + "title": "Build a City Skyline", + "intro": [ + "CSS variables help you organize your styles and reuse them.", + "In this workshop, you'll build a city skyline. You'll practice how to configure CSS variables so you can reuse them whenever you want." + ] + }, + "lab-availability-table": { + "title": "Build an Availability Table", + "intro": [ + "For this lab, you'll create an availability table that shows the availability of people for a meeting.", + "You'll practice using CSS variables to store and reuse colors, fonts, and other styles." + ] + }, + "review-css-variables": { + "title": "CSS Variables Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS variables, you should review what you've learned.", + "Open up this page to review how to work with CSS custom properties (CSS variables) and the @property rule." + ] + }, + "quiz-css-variables": { + "title": "CSS Variables Quiz", + "intro": ["Test your knowledge of CSS variables with this quiz."] + } + } + }, + "css-grid": { + "title": "Learn CSS Grid", + "summary": ["Design complex layouts using the CSS Grid system."], + "intro": ["Build multi-dimensional layouts with CSS Grid."], + "blocks": { + "lecture-working-with-css-grid": { + "title": "Working with CSS Grid", + "intro": [ + "In these lessons, you will learn about CSS grid, its several properties and how to use them, and how CSS grid differs from flexbox." + ] + }, + "workshop-magazine": { + "title": "Build a Magazine", + "intro": [ + "CSS Grid gives you control over the rows and columns of your webpage design.", + "In this workshop, you'll build a magazine article. You'll practice how to use CSS Grid, including concepts like grid rows and grid columns." + ] + }, + "lab-newspaper-layout": { + "title": "Design a Newspaper Layout", + "intro": [ + "In this lab, you will design a newspaper layout using CSS Grid, including concepts like grid rows and grid columns." + ] + }, + "lecture-debugging-css": { + "title": "Debugging CSS", + "intro": [ + "In this lesson, you'll learn how to debug CSS using your browser's developer tools and CSS validators." + ] + }, + "lab-product-landing-page": { + "title": "Build a Product Landing Page", + "intro": [ + "In this project, you'll build a product landing page to market a product of your choice." + ] + }, + "review-css-grid": { + "title": "CSS Grid Review", + "intro": [ + "Before you're quizzed on the fundamentals of CSS Grid, you should review what you've learned.", + "Open up this page to review how to work with the different CSS Grid properties like grid-template-columns, grid-gap and more." + ] + }, + "quiz-css-grid": { + "title": "CSS Grid Quiz", + "intro": ["Test your knowledge of CSS Grid with this quiz."] + } + } + }, + "css-animations": { + "title": "Learn CSS Animations", + "summary": ["Create engaging UI motion with accessible CSS animations."], + "intro": [ + "Add motion with CSS animations while keeping usability in mind." + ], + "blocks": { + "lecture-animations-and-accessibility": { + "title": "Animations and Accessibility", + "intro": [ + "In these lessons, you will learn about CSS animations and their accessibility concerns. You will also learn how prefers-reduced-motion can help address those accessibility concerns." + ] + }, + "workshop-ferris-wheel": { + "title": "Build an Animated Ferris Wheel", + "intro": [ + "You can use CSS animation to draw attention to specific sections of your webpage and make it more engaging.", + "In this workshop, you'll build a Ferris wheel. You'll practice how to use CSS to animate elements, transform them, and adjust their speed." + ] + }, + "lab-moon-orbit": { + "title": "Build a Moon Orbit", + "intro": [ + "In this lab, you'll create an animation of the moon orbiting the earth.", + "You'll practice animation properties like animation-name, animation-duration, animation-timing-function, and more." + ] + }, + "workshop-flappy-penguin": { + "title": "Build a Flappy Penguin", + "intro": [ + "You can transform HTML elements to create appealing designs that draw your reader's eye. You can use transforms to rotate elements, scale them, and more.", + "In this workshop, you'll build a penguin. You'll use CSS transforms to position and resize the parts of your penguin, create a background, and animate your work." + ] + }, + "lab-personal-portfolio": { + "title": "Build a Personal Portfolio", + "intro": [ + "In this project, you'll build your own personal portfolio page." + ] + }, + "review-css-animations": { + "title": "CSS Animations Review", + "intro": [ + "Before you're quizzed on working with CSS animations, you should review what you've learned about them.", + "Open up this page to review concepts including prefers-reduced-motion, the @keyframes rule and more." + ] + }, + "quiz-css-animations": { + "title": "CSS Animations Quiz", + "intro": ["Test your knowledge of CSS animations with this quiz."] + } + } + }, + "dev-playground": { + "title": "Dev Playground", + "intro": ["Playground for creating and testing challenges"], + "blocks": { + "daily-coding-challenges-javascript": { + "title": "Daily Coding Challenges JavaScript", + "intro": ["Place to create JavaScript daily coding challenges."] + }, + "daily-coding-challenges-python": { + "title": "Daily Coding Challenges Python", + "intro": ["Place to create Python daily coding challenges."] + } + } + }, + "full-stack-open": { + "title": "Full-Stack Open", + "intro": ["A good intro is to be added here."], + "blocks": { + "workshop-blog-page": { + "title": "Build a Cat Blog Page", + "intro": [ + "In this workshop, you will build an HTML-only blog page using semantic elements including the main, nav, article, and footer elements." + ] + } + }, + "chapters": { + "part-0": "Fundamentals of Web Apps", + "part-1": "Introduction to React", + "part-2": "Communicating with Servers", + "part-3": "Programming a Server with NodeJS and Express", + "part-4": "Testing Express Servers, User Administration", + "part-5": "Testing React Apps", + "part-6": "Advanced State Management", + "part-7": "React router, custom hooks, styling app with CSS and webpack", + "part-8": "GraphQL", + "part-9": "TypeScript", + "part-10": "React Native", + "part-11": "CI/CD", + "part-12": "Containers", + "part-13": "Using Relational Databases" + }, + "modules": { "basic-html": "Basic HTML" }, + "module-intros": { + "basic-html": { + "title": "Basic HTML", + "intro": [ + "Learn how to build simple webpages using HTML tags to add text, images, and links." + ] + } + } + }, + "daily-coding-challenge": { + "title": "Daily Coding Challenge", + "blocks": { + "daily-coding-challenge": { "title": "Daily Coding Challenge" } + } + }, + "misc-text": { + "browse-other": "Browse our other free certifications", + "courses": "Courses", + "requirements": "Requirements", + "steps": "Steps", + "expand": "Expand course", + "collapse": "Collapse course", + "legacy-header": "Legacy Courses", + "legacy-desc": "These courses are no longer part of the certification path, but are still available for you to further your learning.", + "legacy-go-back": "Go to the current version of the curriculum.", + "course-maintenance": "These courses are undergoing maintenance. If they are not working, you can learn how to run them locally at <0>https://www.freecodecamp.org/news/how-to-run-freecodecamps-relational-databases-curriculum-using-docker-vscode-and-coderoad.", + "course-disabling-soon": "The browser version of these courses will be temporarily disabled soon and your virtual machines will be deleted. Any progress in your virtual machines will be lost. If you have any files you want from them, you should save them to your computer. We apologize for any inconvenience. We hope to have an improved browser version of these courses available again in the next few weeks.", + "course-disabled": "These courses are temporarily unavailable to run in the browser. We apologize for any inconvenience. You can learn how to run them locally at <0>https://www.freecodecamp.org/news/how-to-run-freecodecamps-relational-databases-curriculum-using-docker-vscode-and-coderoad. We hope to have an improved browser version available again soon.", + "run-locally": "For now, we recommend running the courses locally on your computer. You can learn how at <0>https://www.freecodecamp.org/news/how-to-run-freecodecamps-relational-databases-curriculum-using-docker-vscode-and-coderoad.", + "progress-wont-save": "Your progress will not be saved to your freeCodeCamp account when running them locally.", + "go-back-to-learn": "Go back to the stable version of the curriculum.", + "read-database-cert-article": "Please read this forum post before proceeding.", + "enable-cookies": "You must enable third-party cookies before starting.", + "english-only": "The courses in this section are only available in English. We are only able to translate the titles and introductions at the moment, not the lessons themselves.", + "exam-english-only": "Please note that the certification exam is currently available only in English. The rest of the courses are available in some languages." + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/links.json new file mode 100644 index 0000000000000000000000000000000000000000..405d44d66b14f877776374af1f432e8a3ada592a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/links.json @@ -0,0 +1,43 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://cdn.freecodecamp.org/non-profit-docs/freeCodeCamp-determination-letter.pdf", + "download-990-url": "https://cdn.freecodecamp.org/non-profit-docs/freeCodeCamp-2019-f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp", + "one-time-external-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#how-can-i-make-a-one-time-donation", + "mail-check-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#can-i-mail-a-physical-check" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/meta-tags.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/meta-tags.json new file mode 100644 index 0000000000000000000000000000000000000000..9ff1ce8ef2720dd97e3bafa3b446ef9d5b0c1448 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/meta-tags.json @@ -0,0 +1,32 @@ +{ + "title": "Learn to Code for Free. Coding Courses & Certifications | freeCodeCamp", + "description": "Learn to Code for Free", + "social-description": "Learn to Code for Free", + "keywords": [ + "python", + "javascript", + "js", + "git", + "github", + "website", + "web", + "development", + "free", + "code", + "camp", + "course", + "courses", + "html", + "css", + "react", + "redux", + "api", + "front", + "back", + "end", + "learn", + "tutorial", + "programming" + ], + "youre-unsubscribed": "You have been unsubscribed" +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/motivation.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/motivation.json new file mode 100644 index 0000000000000000000000000000000000000000..628e77f4d5f7cb9fcab247d9e4cb932bfc948fac --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/motivation.json @@ -0,0 +1,891 @@ +{ + "compliments": [ + "Over the top!", + "Down the rabbit hole we go!", + "Bring that rain!", + "Target acquired.", + "Feel that need for speed!", + "You've got guts!", + "We have liftoff!", + "To infinity and beyond!", + "Encore!", + "Onward!", + "Challenge destroyed!", + "It's on like Donkey Kong!", + "Power level? It's over 9000!", + "Coding spree!", + "Code long and prosper.", + "The crowd goes wild!", + "One for the Guinness book!", + "Flawless victory!", + "Most efficient!", + "You've got the touch!", + "You're on fire!", + "The town is now red!", + "To the nines!", + "To the Batmobile!", + "Pull out all the stops!", + "You're a wizard, Harry!", + "You're an all star!", + "Way to go!", + "Outta sight!", + "You're crushing it!", + "What sorcery is this?", + "The world rejoices!", + "That's the way it's done!", + "You rock!", + "Woo-hoo!", + "We knew you could do it!", + "Hyper Combo Finish!", + "Nothing but net!", + "Boom-shakalaka!", + "You're a shooting star!", + "You're unstoppable!", + "Way cool!", + "Walk on that sunshine!", + "Keep on trucking!", + "Off the charts!", + "There is no spoon!", + "Cranked it up to 11!", + "Escape velocity reached!", + "You make this look easy!", + "Passed with flying colors!", + "You've got this!", + "Happy, happy, joy, joy!", + "Tomorrow, the world!", + "Your powers combined!", + "It's alive. It's alive!", + "Sonic Boom!", + "Here's looking at you, Code!", + "Ride like the wind!", + "Legen - wait for it - dary!", + "Ludicrous Speed! Go!", + "Most triumphant!", + "One loop to rule them all!", + "By the power of Grayskull!", + "You did it!", + "Storm that castle!", + "Face-melting guitar solo!", + "Checkmate!", + "Bodacious!", + "Tubular!", + "You're outta sight!", + "Keep calm and code on!", + "Even sad panda smiles!", + "Even grumpy cat approves!", + "Kool Aid Man says oh yeah!", + "Bullseye!", + "Far out!", + "You're heating up!", + "Standing ovation!", + "Nice one!", + "All right!", + "Hasta la vista, challenge!", + "Terminated.", + "Off the hook!", + "Thundercats, Hooo!", + "Shiver me timbers!", + "Raise the roof!", + "Bingo!", + "Even Honey Badger cares!", + "Helm, Warp Nine. Engage!", + "Gotta code 'em all!", + "Spool up the FTL drive!", + "Cool beans!", + "They're in another castle.", + "Power UP!", + "Pikachu chooses you!", + "I gotta have more cowbell.", + "Gotta go fast!", + "Yippee!", + "Cowabunga!", + "Moon Prism Power!", + "Plus Ultra!", + "Everything's coming up Milhouse!", + "King of the Pirates!", + "Thunder Breathing First Form!", + "It's time to duel!", + "You better believe it!", + "Do a barrel roll!", + "You can do this all day!", + "It's super effective!", + "This is the way!", + "You're king of the world!", + "It's morphin' time!", + "Just keep swimming!", + "You are the one who knocks!", + "Inconceivable!", + "Great Scott!", + "By Grabthar's hammer!", + "Get to the choppa!", + "It's clobberin' time!", + "Somebody stop me!", + "Oh, hi Mark!", + "Groovy!", + "The Dude abides!", + "Are you not entertained?", + "There can be only one!", + "You are the danger!", + "You know kung fu!", + "Elementary, my dear Watson!", + "Maximum effort!" + ], + "motivationalQuotes": [ + { + "quote": "Whatever you are, be a good one.", + "author": "Abraham Lincoln" + }, + { + "quote": "A change in perspective is worth 80 IQ points.", + "author": "Alan Kay" + }, + { + "quote": "The best way to predict the future is to invent it.", + "author": "Alan Kay" + }, + { + "quote": "The future is not laid out on a track. It is something that we can decide, and to the extent that we do not violate any known laws of the universe, we can probably make it work the way that we want to.", + "author": "Alan Kay" + }, + { + "quote": "We can only see a short distance ahead, but we can see plenty there that needs to be done.", + "author": "Alan Turing" + }, + { + "quote": "In the depth of winter, I finally learned that within me there lay an invincible summer.", + "author": "Albert Camus" + }, + { + "quote": "A person who never made a mistake never tried anything new.", + "author": "Albert Einstein" + }, + { + "quote": "Creativity is intelligence having fun.", + "author": "Albert Einstein" + }, + { + "quote": "I have no special talents. I am only passionately curious.", + "author": "Albert Einstein" + }, + { + "quote": "Life is like riding a bicycle. To keep your balance, you must keep moving.", + "author": "Albert Einstein" + }, + { + "quote": "Make everything as simple as possible, but not simpler.", + "author": "Albert Einstein" + }, + { + "quote": "Never memorize something that you can look up.", + "author": "Albert Einstein" + }, + { + "quote": "Once we accept our limits, we go beyond them.", + "author": "Albert Einstein" + }, + { + "quote": "Play is the highest form of research.", + "author": "Albert Einstein" + }, + { + "quote": "We cannot solve our problems with the same thinking we used when we created them.", + "author": "Albert Einstein" + }, + { + "quote": "Wisdom is not a product of schooling but of the lifelong attempt to acquire it.", + "author": "Albert Einstein" + }, + { + "quote": "Your imagination is your preview of life's coming attractions.", + "author": "Albert Einstein" + }, + { + "quote": "There is only one corner of the universe you can be certain of improving, and that's your own self.", + "author": "Aldous Huxley" + }, + { + "quote": "I am thankful for my struggle because, without it, I wouldn't have stumbled across my strength.", + "author": "Alex Elle" + }, + { + "quote": "The most common way people give up their power is by thinking they don't have any.", + "author": "Alice Walker" + }, + { + "quote": "Follow your inner moonlight. Don't hide the madness.", + "author": "Allen Ginsberg" + }, + { + "quote": "The most difficult thing is the decision to act. The rest is merely tenacity.", + "author": "Amelia Earhart" + }, + { + "quote": "Life shrinks or expands in proportion with one's courage.", + "author": "Anaïs Nin" + }, + { + "quote": "Weeks of programming can save you hours of planning.", + "author": "Unknown" + }, + { + "quote": "Quality is not an act, it is a habit.", + "author": "Aristotle" + }, + { + "quote": "Start where you are. Use what you have. Do what you can.", + "author": "Arthur Ashe" + }, + { + "quote": "Nothing is impossible, the word itself says 'I'm possible'!", + "author": "Audrey Hepburn" + }, + { + "quote": "Every strike brings me closer to the next home run.", + "author": "Babe Ruth" + }, + { + "quote": "By failing to prepare, you are preparing to fail.", + "author": "Benjamin Franklin" + }, + { + "quote": "Tell me and I forget. Teach me and I remember. Involve me and I learn.", + "author": "Benjamin Franklin" + }, + { + "quote": "Well done is better than well said.", + "author": "Benjamin Franklin" + }, + { + "quote": "There are no short cuts to any place worth going.", + "author": "Beverly Sills" + }, + { + "quote": "Controlling complexity is the essence of computer programming.", + "author": "Brian Kernighan" + }, + { + "quote": "I fear not the man who has practiced 10,000 kicks once, but I fear the man who has practiced one kick 10,000 times.", + "author": "Bruce Lee" + }, + { + "quote": "There are far, far better things ahead than any we leave behind.", + "author": "C.S. Lewis" + }, + { + "quote": "We are what we believe we are.", + "author": "C.S. Lewis" + }, + { + "quote": "With the possible exception of the equator, everything begins somewhere.", + "author": "C.S. Lewis" + }, + { + "quote": "You are never too old to set another goal, or to dream a new dream.", + "author": "C.S. Lewis" + }, + { + "quote": "Somewhere, something incredible is waiting to be known.", + "author": "Carl Sagan" + }, + { + "quote": "When you have a dream, you've got to grab it and never let go.", + "author": "Carol Burnett" + }, + { + "quote": "If you're not making mistakes, then you're not making decisions.", + "author": "Catherine Cook" + }, + { + "quote": "Find what you love and let it kill you.", + "author": "Charles Bukowski" + }, + { + "quote": "What matters most is how well you walk through the fire.", + "author": "Charles Bukowski" + }, + { + "quote": "It is not the strongest of the species that survive, nor the most intelligent, but the one most responsive to change.", + "author": "Charles Darwin" + }, + { + "quote": "The details are not the details. They make the design.", + "author": "Charles Eames" + }, + { + "quote": "Creativity is more than just being different. Anybody can plan weird. That's easy. What's hard is to be as simple as Bach. Making the simple, awesomely simple, that's creativity.", + "author": "Charles Mingus" + }, + { + "quote": "Life is 10% what happens to you and 90% how you react to it.", + "author": "Charles R. Swindoll" + }, + { + "quote": "You will do foolish things, but do them with enthusiasm.", + "author": "Colette" + }, + { + "quote": "It does not matter how slowly you go as long as you do not stop.", + "author": "Confucius" + }, + { + "quote": "Real knowledge is to know the extent of one's ignorance.", + "author": "Confucius" + }, + { + "quote": "The past cannot be changed. The future is yet in your power.", + "author": "Confucius" + }, + { + "quote": "Looking at code you wrote more than two weeks ago is like looking at code you are seeing for the first time.", + "author": "Dan Hurvitz" + }, + { + "quote": "Someday is not a day of the week.", + "author": "Denise Brennan-Nelson" + }, + { + "quote": "UNIX is simple. It just takes a genius to understand its simplicity.", + "author": "Dennis Ritchie" + }, + { + "quote": "The way I see it, if you want the rainbow, you gotta put up with the rain!", + "author": "Dolly Parton" + }, + { + "quote": "Computers are good at following instructions, but not at reading your mind.", + "author": "Donald Knuth" + }, + { + "quote": "A good programmer is someone who always looks both ways before crossing a one-way street.", + "author": "Doug Linder" + }, + { + "quote": "Creativity is a wild mind and a disciplined eye.", + "author": "Dorothy Parker" + }, + { + "quote": "Tough times never last, but tough people do.", + "author": "Dr. Robert Schuller" + }, + { + "quote": "If things start happening, don't worry, don't stew, just go right along and you'll start happening too.", + "author": "Dr. Seuss" + }, + { + "quote": "Do not go gentle into that good night. Rage, rage against the dying of the light.", + "author": "Dylan Thomas" + }, + { + "quote": "The question of whether computers can think is like the question of whether submarines can swim.", + "author": "E.W. Dijkstra" + }, + { + "quote": "Any code of your own that you haven't looked at for six or more months might as well have been written by someone else.", + "author": "Eagleson's Law" + }, + { + "quote": "Do one thing every day that scares you.", + "author": "Eleanor Roosevelt" + }, + { + "quote": "With the new day comes new strength and new thoughts.", + "author": "Eleanor Roosevelt" + }, + { + "quote": "You must do the things you think you cannot do.", + "author": "Eleanor Roosevelt" + }, + { + "quote": "Light tomorrow with today.", + "author": "Elizabeth Barrett Browning" + }, + { + "quote": "If your dreams do not scare you, they are not big enough.", + "author": "Ellen Johnson Sirleaf" + }, + { + "quote": "Forever is composed of nows.", + "author": "Emily Dickinson" + }, + { + "quote": "Computer science education cannot make anybody an expert programmer any more than studying brushes and pigment can make somebody an expert painter.", + "author": "Eric Raymond" + }, + { + "quote": "If you don't risk anything, you risk even more.", + "author": "Erica Jong" + }, + { + "quote": "The world breaks everyone, and afterward, many are strong at the broken places.", + "author": "Ernest Hemingway" + }, + { + "quote": "There is nothing noble in being superior to your fellow man; true nobility is being superior to your former self.", + "author": "Ernest Hemingway" + }, + { + "quote": "Never confuse a single defeat with a final defeat.", + "author": "F. Scott Fitzgerald" + }, + { + "quote": "I attribute my success to this - I never gave or took any excuse.", + "author": "Florence Nightingale" + }, + { + "quote": "The best revenge is massive success.", + "author": "Frank Sinatra" + }, + { + "quote": "The only limit to our realization of tomorrow, will be our doubts of today.", + "author": "Franklin D. Roosevelt" + }, + { + "quote": "Right or wrong, it's very pleasant to break something from time to time.", + "author": "Fyodor Dostoevsky" + }, + { + "quote": "The harder I work, the luckier I get.", + "author": "Gary Player" + }, + { + "quote": "Giving up is the only sure way to fail.", + "author": "Gena Showalter" + }, + { + "quote": "The only truly secure system is one that is powered off, cast in a block of concrete and sealed in a lead-lined room with armed guards.", + "author": "Gene Spafford" + }, + { + "quote": "A life spent making mistakes is not only more honorable, but more useful than a life spent doing nothing.", + "author": "George Bernard Shaw" + }, + { + "quote": "First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack.", + "author": "George Carrette" + }, + { + "quote": "Discovering the unexpected is more important than confirming the known.", + "author": "George Box" + }, + { + "quote": "We only see what we know.", + "author": "Goethe" + }, + { + "quote": "Without hard work, nothing grows but weeds.", + "author": "Gordon B. Hinckley" + }, + { + "quote": "The function of good software is to make the complex appear to be simple.", + "author": "Grady Booch" + }, + { + "quote": "When you know that you're capable of dealing with whatever comes, you have the only security the world has to offer.", + "author": "Harry Browne" + }, + { + "quote": "Pain is inevitable. Suffering is optional.", + "author": "Haruki Murakami" + }, + { + "quote": "Optimism is the faith that leads to achievement. Nothing can be done without hope and confidence.", + "author": "Helen Keller" + }, + { + "quote": "The price of anything is the amount of life you exchange for it.", + "author": "Henry David Thoreau" + }, + { + "quote": "Whether you think you can or think you can't, you're right.", + "author": "Henry Ford" + }, + { + "quote": "The most exciting phrase to hear in science, the one that heralds discoveries, is not 'Eureka!' but 'Now that's funny…'", + "author": "Isaac Asimov" + }, + { + "quote": "What you do makes a difference. And you have to decide what kind of difference you want to make.", + "author": "Jane Goodall" + }, + { + "quote": "We are all failures. At least the best of us are.", + "author": "J.M. Barrie" + }, + { + "quote": "You can't wait for inspiration. You have to go after it with a club.", + "author": "Jack London" + }, + { + "quote": "Don't wish it were easier, wish you were better.", + "author": "Jim Rohn" + }, + { + "quote": "By seeking and blundering we learn.", + "author": "Johann Wolfgang von Goethe" + }, + { + "quote": "Knowing is not enough; we must apply. Wishing is not enough; we must do.", + "author": "Johann Wolfgang von Goethe" + }, + { + "quote": "We first make our habits, then our habits make us.", + "author": "John Dryden" + }, + { + "quote": "The power of imagination makes us infinite.", + "author": "John Muir" + }, + { + "quote": "May you live every day of your life.", + "author": "Jonathan Swift" + }, + { + "quote": "Perseverance is failing 19 times and succeeding the 20th.", + "author": "Julie Andrews" + }, + { + "quote": "The work of today is the history of tomorrow, and we are its makers.", + "author": "Juliette Gordon Low" + }, + { + "quote": "If you reveal your secrets to the wind, you should not blame the wind for revealing them to the trees.", + "author": "Kahlil Gibran" + }, + { + "quote": "Optimism is an occupational hazard of programming; feedback is the treatment.", + "author": "Kent Beck" + }, + { + "quote": "Opportunity does not knock, it presents itself when you beat down the door.", + "author": "Kyle Chandler" + }, + { + "quote": "To iterate is human, to recurse divine.", + "author": "Peter Deutsch" + }, + { + "quote": "A good traveler has no fixed plans and is not intent on arriving.", + "author": "Lao Tzu" + }, + { + "quote": "An ant on the move does more than a dozing ox.", + "author": "Lao Tzu" + }, + { + "quote": "Do the difficult things while they are easy and do the great things while they are small. A journey of a thousand miles must begin with a single step.", + "author": "Lao Tzu" + }, + { + "quote": "That's the thing about people who think they hate computers. What they really hate is lousy programmers.", + "author": "Larry Niven" + }, + { + "quote": "It had long since come to my attention that people of accomplishment rarely sat back and let things happen to them. They went out and happened to things.", + "author": "Elinor Smith" + }, + { + "quote": "If you're any good at all, you know you can be better.", + "author": "Lindsay Buckingham" + }, + { + "quote": "If people never did silly things, nothing intelligent would ever get done.", + "author": "Ludwig Wittgenstein" + }, + { + "quote": "You only live once, but if you do it right, once is enough.", + "author": "Mae West" + }, + { + "quote": "Live as if you were to die tomorrow. Learn as if you were to live forever.", + "author": "Mahatma Gandhi" + }, + { + "quote": "Strength does not come from physical capacity. It comes from an indomitable will.", + "author": "Mahatma Gandhi" + }, + { + "quote": "One person's 'paranoia' is another person's 'engineering redundancy'.", + "author": "Marcus J. Ranum" + }, + { + "quote": "Nothing in life is to be feared, it is only to be understood. Now is the time to understand more, so that we may fear less.", + "author": "Marie Curie" + }, + { + "quote": "If you have everything under control, you're not moving fast enough.", + "author": "Mario Andretti" + }, + { + "quote": "Education: the path from cocky ignorance to miserable uncertainty.", + "author": "Mark Twain" + }, + { + "quote": "It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so.", + "author": "Mark Twain" + }, + { + "quote": "The secret of getting ahead is getting started.", + "author": "Mark Twain" + }, + { + "quote": "The two most important days in your life are the day you are born and the day you find out why.", + "author": "Mark Twain" + }, + { + "quote": "Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails.", + "author": "Mark Twain" + }, + { + "quote": "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.", + "author": "Martin Fowler" + }, + { + "quote": "I know, somehow, that only when it is dark enough can you see the stars.", + "author": "Martin Luther King Jr." + }, + { + "quote": "It is never too late to be what you might have been.", + "author": "Mary Anne Evans" + }, + { + "quote": "Nothing will work unless you do.", + "author": "Maya Angelou" + }, + { + "quote": "You can't use up creativity. The more you use, the more you have.", + "author": "Maya Angelou" + }, + { + "quote": "We delight in the beauty of the butterfly, but rarely admit the changes it has gone through to achieve that beauty.", + "author": "Maya Angelou" + }, + { + "quote": "We may encounter many defeats, but we must not be defeated.", + "author": "Maya Angelou" + }, + { + "quote": "Everybody has talent, but ability takes hard work.", + "author": "Michael Jordan" + }, + { + "quote": "I've missed more than 9,000 shots during my career. I've lost almost 300 games. 26 times, I've been trusted to take the game winning shot and missed. I've failed over and over and over again in my life. And that is why I succeed.", + "author": "Michael Jordan" + }, + { + "quote": "Impossible is just a big word thrown around by small men who find it easier to live in the world they've been given than to explore the power they have to change it. Impossible is not a fact. It's an opinion. Impossible is not a declaration. It's a dare. Impossible is potential. Impossible is temporary. Impossible is nothing.", + "author": "Muhammad Ali" + }, + { + "quote": "A winner is a dreamer who never gives up.", + "author": "Nelson Mandela" + }, + { + "quote": "It always seems impossible until it's done.", + "author": "Nelson Mandela" + }, + { + "quote": "Failure will never overtake me if my determination to succeed is strong enough.", + "author": "Og Mandino" + }, + { + "quote": "I am not young enough to know everything.", + "author": "Oscar Wilde" + }, + { + "quote": "There is only one thing that makes a dream impossible to achieve: the fear of failure.", + "author": "Paulo Coelho" + }, + { + "quote": "Never go to bed mad. Stay up and fight.", + "author": "Phyllis Diller" + }, + { + "quote": "You can't cross the sea merely by standing and staring at the water.", + "author": "Rabindranath Tagore" + }, + { + "quote": "The only person you are destined to become is the person you decide to be.", + "author": "Ralph Waldo Emerson" + }, + { + "quote": "What you do speaks so loudly that I cannot hear what you say.", + "author": "Ralph Waldo Emerson" + }, + { + "quote": "People who are crazy enough to think they can change the world, are the ones who do.", + "author": "Rob Siltanen" + }, + { + "quote": "The best way out is always through.", + "author": "Robert Frost" + }, + { + "quote": "Today's accomplishments were yesterday's impossibilities.", + "author": "Robert H. Schuller" + }, + { + "quote": "Don't be satisfied with stories, how things have gone with others. Unfold your own myth.", + "author": "Rumi" + }, + { + "quote": "Forget safety. Live where you fear to live. Destroy your reputation. Be notorious.", + "author": "Rumi" + }, + { + "quote": "Sell your cleverness and buy bewilderment.", + "author": "Rumi" + }, + { + "quote": "The cure for pain is in the pain.", + "author": "Rumi" + }, + { + "quote": "Have no fear of perfection - you'll never reach it.", + "author": "Salvador Dalí" + }, + { + "quote": "Don't watch the clock. Do what it does. Keep going.", + "author": "Sam Levenson" + }, + { + "quote": "Ever Tried. Ever failed. No matter. Try again. Fail again. Fail better.", + "author": "Samuel Beckett" + }, + { + "quote": "The more you know, the more you realize you know nothing.", + "author": "Socrates" + }, + { + "quote": "The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.", + "author": "Stephen Hawking" + }, + { + "quote": "The universe doesn't allow perfection.", + "author": "Stephen Hawking" + }, + { + "quote": "Whether you want to uncover the secrets of the universe, or you want to pursue a career in the 21st century, basic computer programming is an essential skill to learn.", + "author": "Stephen Hawking" + }, + { + "quote": "The scariest moment is always just before you start.", + "author": "Stephen King" + }, + { + "quote": "You can, you should, and if you're brave enough to start, you will.", + "author": "Stephen King" + }, + { + "quote": "Arise, Awake and Stop not until the goal is reached.", + "author": "Swami Vivekananda" + }, + { + "quote": "It is said that your life flashes before your eyes just before you die. That is true, it's called Life.", + "author": "Terry Pratchett" + }, + { + "quote": "Believe you can and you're halfway there.", + "author": "Theodore Roosevelt" + }, + { + "quote": "I have not failed. I've just found 10,000 ways that won't work.", + "author": "Thomas A. Edison" + }, + { + "quote": "Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.", + "author": "Thomas A. Edison" + }, + { + "quote": "The harder the conflict, the more glorious the triumph.", + "author": "Thomas Paine" + }, + { + "quote": "The Web as I envisaged it, we have not seen it yet. The future is still so much bigger than the past.", + "author": "Tim Berners-Lee" + }, + { + "quote": "Failure is the condiment that gives success its flavor.", + "author": "Truman Capote" + }, + { + "quote": "Those who say it cannot be done should not interrupt the person doing it.", + "author": "Unknown" + }, + { + "quote": "Look at usual things with unusual eyes.", + "author": "Vico Magistetti" + }, + { + "quote": "Even if you fall on your face, you're still moving forward.", + "author": "Victor Kiam" + }, + { + "quote": "It's not whether you get knocked down, it's whether you get up.", + "author": "Vince Lombardi" + }, + { + "quote": "I dream my painting and I paint my dream.", + "author": "Vincent van Gogh" + }, + { + "quote": "Great things are done by a series of small things brought together.", + "author": "Vincent van Gogh" + }, + { + "quote": "Let us cultivate our garden.", + "author": "Voltaire" + }, + { + "quote": "Aim for the moon. If you miss, you may hit a star.", + "author": "W. Clement Stone" + }, + { + "quote": "The way to get started is to quit talking and begin doing.", + "author": "Walt Disney" + }, + { + "quote": "You miss 100% of the shots you don't take.", + "author": "Wayne Gretzky" + }, + { + "quote": "Don't let yesterday take up too much of today.", + "author": "Will Rogers" + }, + { + "quote": "Even if you're on the right track, you'll get run over if you just sit there.", + "author": "Will Rogers" + }, + { + "quote": "Do not wait to strike till the iron is hot; but make it hot by striking.", + "author": "William Butler Yeats" + }, + { + "quote": "You cannot swim for new horizons until you have courage to lose sight of the shore.", + "author": "William Faulkner" + }, + { + "quote": "Be not afraid of greatness. Some are born great, some achieve greatness, and others have greatness thrust upon them.", + "author": "William Shakespeare" + }, + { + "quote": "We know what we are, but not what we may be.", + "author": "William Shakespeare" + }, + { + "quote": "In theory there is no difference between theory and practice. In practice there is.", + "author": "Yogi Berra" + }, + { + "quote": "You can see a lot by just looking.", + "author": "Yogi Berra" + }, + { + "quote": "There is no elevator to success, you have to take the stairs.", + "author": "Zig Ziglar" + }, + { + "quote": "You don't have to be great to start, but you have to start to be great.", + "author": "Zig Ziglar" + } + ] +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/translations.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/translations.json new file mode 100644 index 0000000000000000000000000000000000000000..17d13c7b3fb8d8acbfe9dd4be891e2b76a84a0b1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/english/translations.json @@ -0,0 +1,1633 @@ +{ + "buttons": { + "logged-in-cta-btn": "Get started (it's free)", + "get-started": "Get Started", + "logged-out-cta-btn": "Sign in to save your progress (it's free)", + "view-curriculum": "View the Curriculum", + "first-lesson": "Go to the first lesson", + "close": "Close", + "edit": "Edit", + "copy": "Copy", + "view": "View", + "submit-continue": "Submit and continue", + "view-code": "View Code", + "view-project": "View Project", + "view-cert-title": "View {{certTitle}}", + "show-cert": "Show Certification", + "claim-cert": "Claim Certification", + "save-progress": "Save Progress", + "accepted-honesty": "You have agreed to our Academic Honesty Policy.", + "agree-honesty": "I agree to freeCodeCamp's Academic Honesty Policy.", + "save-portfolio": "Save this portfolio item", + "remove-portfolio": "Remove this portfolio item", + "add-portfolio": "Add a new portfolio Item", + "download-data": "Download your data", + "public": "Public", + "private": "Private", + "off": "Off", + "on": "On", + "sign-in": "Sign in", + "sign-up-email-list": "Sign up for Quincy's weekly emails", + "sign-out": "Sign out", + "catalog": "Catalog", + "curriculum": "Curriculum", + "contribute": "Contribute", + "podcast": "Podcast", + "forum": "Forum", + "radio": "Radio", + "profile": "Profile", + "news": "News", + "donate": "Donate", + "supporters": "Supporters", + "exam-app": "Exam App", + "go-to-supporters": "Go to Supporters Page", + "update-settings": "Update my account settings", + "sign-me-out": "Sign me out of freeCodeCamp", + "flag-user": "Flag This User's Account for Abuse", + "current-challenge": "Go to current challenge", + "try-again": "Try again", + "menu": "Menu", + "settings": "Settings", + "take-me": "Take me to the Challenges", + "check-answer": "Check your answer", + "submit": "Submit", + "get-hint": "Get a Hint", + "ask-for-help": "Ask for Help", + "create-post": "Create a help post on the forum", + "cancel": "Cancel", + "reset-lesson": "Reset this lesson", + "revert": "Revert", + "revert-to-saved-code": "Revert to Saved Code", + "run": "Run", + "run-test": "Run the Tests (Ctrl + Enter)", + "check-code": "Check Your Code", + "check-code-ctrl": "Check Your Code (Ctrl + Enter)", + "check-code-cmd": "Check Your Code (Command + Enter)", + "command-enter": "⌘ + Enter", + "ctrl-enter": "Ctrl + Enter", + "reset": "Reset", + "ask-socrates": "Ask Socrates (beta)", + "reset-step": "Reset This Step", + "help": "Help", + "get-help": "Get Help", + "watch-video": "Watch a Video", + "resubscribe": "You can click here to resubscribe", + "click-here": "Click here to sign in", + "save": "Save", + "save-code": "Save your Code", + "show-demo": "Show Demo", + "no-thanks": "No thanks", + "yes-please": "Yes please", + "update-email": "Update my Email", + "verify-email": "Verify Email", + "submit-and-go": "Submit and go to next challenge", + "submit-and-go-ctrl": "Submit and go to next challenge (Ctrl + Enter)", + "submit-and-go-cmd": "Submit and go to next challenge (Command + Enter)", + "go-to-next": "Go to next challenge", + "go-to-next-ctrl": "Go to next challenge (Ctrl + Enter)", + "go-to-next-cmd": "Go to next challenge (Command + Enter)", + "ask-later": "Ask me later", + "start-coding": "Start coding!", + "go-to-settings": "Go to settings to claim your certification", + "click-start-course": "Start the course", + "click-start-project": "Start the project", + "click-start-exam": "Start the exam", + "go-to-course": "Go to course", + "change-language": "Change Language", + "resume-project": "Resume project", + "start-project": "Start project", + "tweet": "Tweet", + "previous-question": "Previous question", + "next-question": "Next question", + "exit-exam": "Exit the exam", + "exit": "Exit", + "finish-exam": "Finish the exam", + "finish": "Finish", + "exit-quiz": "Exit the quiz", + "finish-quiz": "Finish the quiz", + "submit-exam-results": "Submit my results", + "verify-trophy": "Verify Trophy", + "link-account": "Link Account", + "unlink-account": "Unlink Account", + "update-card": "Update your card", + "donate-now": "Donate Now", + "confirm-amount": "Confirm amount", + "play": "Play Video", + "pause": "Pause Video", + "closed-caption": "Closed caption", + "share-on-x": "Share on X", + "share-on-bluesky": "Share on BlueSky", + "share-on-threads": "Share on Threads", + "share-on-facebook": "Share on Facebook", + "play-scene": "Press Play", + "download-latest-version": "Download the Latest Version", + "more-ways-to-sign-in": "More ways to sign in", + "sign-in-with-google": "Sign in with Google", + "go-to-dcc-today": "Go to Today's Challenge", + "go-to-dcc-archive": "Go to Daily Coding Challenge Archive", + "challenge-source": "View Challenge Source", + "outline": "Outline" + }, + "daily-coding-challenges": { + "title": "Daily Coding Challenges", + "map-title": "Try the coding challenge of the day:", + "not-found": "Daily Coding Challenge Not Found.", + "release-note": "The daily challenge updates at midnight US Central time." + }, + "weekdays": { + "short": { + "sunday": "S", + "monday": "M", + "tuesday": "T", + "wednesday": "W", + "thursday": "T", + "friday": "F", + "saturday": "S" + }, + "long": { + "sunday": "Sunday", + "monday": "Monday", + "tuesday": "Tuesday", + "wednesday": "Wednesday", + "thursday": "Thursday", + "friday": "Friday", + "saturday": "Saturday" + } + }, + "landing": { + "big-heading-1": "Learn to code — for free.", + "big-heading-2": "Build projects.", + "big-heading-1-b": "Build Your Skills for Free.", + "big-heading-3": "Earn certifications.", + "advance-career": "Advance your career by learning in-demand skills in Programming, DevOps, Cybersecurity, AI Engineering, and English for Developers.", + "h2-heading": "More than 100,000 freeCodeCamp.org graduates have gotten jobs at tech companies including:", + "graduates-work": "More than 100,000 freeCodeCamp graduates work in companies such as", + "hero-img-description": "freeCodeCamp students at a local study group in South Korea.", + "hero-img-alt": "A group of people, including a White man, a Black woman, and an Asian woman, gathered around a laptop.", + "hero-img-uis": "A group of screenshots showing the freeCodeCamp editor interface on both a mobile and desktop device and a certification.", + "as-seen-in": "As seen in:", + "testimonials": { + "heading": "Here is what our alumni say about freeCodeCamp:", + "shawn": { + "img-alt": "Shawn Wang, a young-looking Asian man, smiling for a selfie with a snow-capped mountain in the background.", + "location": "Shawn Wang in Singapore", + "occupation": "Software Engineer at Amazon", + "testimony": "\"It's scary to change careers. I only gained confidence that I could code by working through the hundreds of hours of free lessons on freeCodeCamp. Within a year I had a six-figure job as a Software Engineer. freeCodeCamp changed my life.\"" + }, + "sarah": { + "img-alt": "Sarah Chima, a young-looking Black woman, smiling for the camera while sitting in a chair.", + "location": "Sarah Chima in Nigeria", + "occupation": "Software Engineer at ChatDesk", + "testimony": "\"freeCodeCamp was the gateway to my career as a software developer. The well-structured curriculum took my coding knowledge from a total beginner level to a very confident level. It was everything I needed to land my first dev job at an amazing company.\"" + }, + "emma": { + "img-alt": "Emma Bostian, a young-looking White woman, smiling for the camera in front of green foliage.", + "location": "Emma Bostian in Sweden", + "occupation": "Software Engineer at Spotify", + "testimony": "\"I've always struggled with learning JavaScript. I've taken many courses but freeCodeCamp's course was the one which stuck. Studying JavaScript as well as data structures and algorithms on freeCodeCamp gave me the skills and confidence I needed to land my dream job as a software engineer at Spotify.\"" + } + }, + "benefits": { + "heading": "Why learn with freeCodeCamp:", + "list": [ + { + "title": "Large Community", + "description": "Join our vibrant learning community of students, alumni, and educators." + }, + { + "title": "Free Education", + "description": "Learn from our charity and save money on your education. This is made possible by the generous support of our monthly donors." + }, + { + "title": "Extensive Certifications", + "description": "Earn industry-recognized, verifiable certifications in high-demand technologies." + }, + { + "title": "Comprehensive Curriculum", + "description": "Enhance your technical skills with our linear, world-class, project-based curriculum." + } + ], + "cta": "Start Learning Now (it's free)" + }, + "catalog": { + "heading": "Explore Course Catalog", + "seeAll": "See All Courses" + }, + "certification-heading": "Earn free verified certifications in:", + "core-certs-heading": "Recommended curriculum:", + "learn-english-heading": "Learn English for Developers:", + "learn-spanish-heading": "Learn Professional Spanish:", + "learn-chinese-heading": "Learn Professional Chinese:", + "professional-certs-heading": "Professional certifications:", + "interview-prep-heading": "Prepare for the developer interview job search:", + "legacy-curriculum-heading": "Our archived coursework:", + "next-heading": "Try our beta curriculum:", + "upcoming-heading": "Upcoming curriculum:", + "catalog-heading": "Explore our Catalog:", + "archive-link": "Looking for older coursework? Check out <0>our archive page.", + "faq": "Frequently asked questions:", + "faqs": [ + { + "question": "What exactly is freeCodeCamp?", + "answer": [ + "freeCodeCamp is a community of people from all around the world who are learning to code together. We're a 501(c)(3) public charity." + ] + }, + { + "question": "How will freeCodeCamp help me learn to code?", + "answer": [ + "You will learn to code by building dozens of projects, step-by-step, right in your browser, code editor, or mobile app.", + "You will also earn free verified certifications along the way." + ] + }, + { + "question": "Is freeCodeCamp really free?", + "answer": [ + "Yes. Every aspect of freeCodeCamp is 100% free. The courses, the projects, and even the certifications." + ] + }, + { + "question": "Can freeCodeCamp help me get a job as a software developer?", + "answer": [ + "Yes. Every year, thousands of people who join the freeCodeCamp community get their first software developer job." + ] + }, + { + "question": "What skills will I learn?", + "answer": [ + "You will learn the skills most developers use on the job: HTML, CSS, JavaScript, Python, Linux, Git, and SQL, and more. You'll also learn how to use powerful libraries for web development, mobile app development, data science, and artificial intelligence." + ] + }, + { + "question": "How long does it take to learn all this?", + "answer": [ + "freeCodeCamp is self-paced. Realistically, it may take several years of practicing coding to learn these skills well enough to get a job as a software engineer. Don't quit school or your day job until you feel ready." + ] + }, + { + "question": "How do I get started?", + "answer": [ + "If you're a beginner, you should start at the beginning of the freeCodeCamp core curriculum. If you're more advanced, we still recommend starting at the beginning, but you can skip to whatever area you wish." + ] + }, + { + "question": "How do I earn the free verified certifications?", + "answer": [ + "For each certification, you need to build its 5 certification projects, and get all of the project tests to pass to be able to claim your certification." + ] + }, + { + "question": "I don't see [name of tool] in the freeCodeCamp core curriculum.", + "answer": [ + "Aside from the freeCodeCamp core curriculum, We have thousands of free, full-length books, courses, and programming tutorials. We almost certainly teach whatever programming tools you want to learn. Just use the search bar." + ] + } + ] + }, + "settings": { + "share-projects": "Share your non-freeCodeCamp projects, articles or accepted pull requests.", + "privacy": "The settings in this section enable you to control what is shown on your freeCodeCamp public portfolio. Press save to save your changes.", + "data": "To see what data we hold on your account, click the \"Download your data\" button below", + "disabled": "Your certifications will be disabled, if set to private.", + "private-name": "Your name will not appear on your certifications, if this is set to private.", + "claim-legacy": "Once you've earned the following freeCodeCamp certifications, you'll be able to claim the {{cert}}:", + "for": "Settings for {{username}}", + "profile-note": "You can go to <0>your profile to update your personal information.", + "sound-mode": "This adds the pleasant sound of acoustic guitar throughout the website. You'll get musical feedback as you type in the editor, complete challenges, claim certifications, and more.", + "sound-volume": "Campfire Volume:", + "scrollbar-width": "Editor Scrollbar Width", + "reset-editor-layout-tooltip": "Reset the editor layout to its default state", + "reset-editor-layout": "Reset Editor Layout", + "shortcuts-explained": "Within a challenge, press ESC followed by the question mark to show a list of available shortcuts.", + "username": { + "contains invalid characters": "Username \"{{username}}\" contains invalid characters. Use only alphanumeric values like 'camperbot', or 'camperbot123'.", + "is too short": "Username \"{{username}}\" is too short", + "is a reserved error code": "Username \"{{username}}\" is a reserved error code", + "must be lowercase": "Username \"{{username}}\" must be lowercase", + "unavailable": "Username not available", + "validating": "Validating username...", + "available": "Username is available", + "change": "Please note, changing your username will also change the URL to your profile and your certifications." + }, + "labels": { + "username": "Username", + "name": "Name", + "location": "Location", + "picture": "Picture", + "about": "About", + "personal": "Personal Website", + "title": "Title", + "url": "URL", + "image": "Image", + "description": "Description", + "project-name": "Project Name", + "solution": "Solution", + "solution-for": "Solution for {{projectTitle}}", + "results-for": "Results for {{projectTitle}}", + "my-profile": "My profile", + "my-name": "My name", + "my-location": "My stated location (freeCodeCamp does not track your actual location)", + "my-about": "My about", + "my-points": "My points", + "my-heatmap": "My heatmap", + "my-certs": "My certifications", + "my-portfolio": "My portfolio", + "my-experience": "My experience", + "my-timeline": "My timeline", + "my-donations": "My donations", + "night-mode": "Night Mode", + "sound-mode": "Campfire Mode", + "keyboard-shortcuts": "Enable Keyboard Shortcuts" + }, + "headings": { + "personal": "Personal", + "account": "Account", + "certs": "Certifications", + "legacy-certs": "Legacy Certifications", + "honesty": "Academic Honesty Policy", + "internet": "Your Internet Presence", + "portfolio": "Portfolio Settings", + "privacy": "Privacy", + "personal-info": "Personal Information" + }, + "danger": { + "heading": "Danger Zone", + "be-careful": "Please be careful. Changes in this section are permanent.", + "reset": "Reset all of my progress", + "delete": "Delete my account", + "delete-title": "Delete My Account", + "delete-p1": "This will really delete all your data, including all your progress and account information.", + "delete-p2": "We won't be able to recover any of it for you later, even if you change your mind.", + "delete-p3": "If there's something we could do better, send us an email instead and we'll do our best: <0>{{email}}", + "nevermind": "Nevermind, I don't want to delete my account", + "certain": "I am 100% certain. Delete everything related to this account", + "reset-heading": "Reset My Progress", + "reset-p1": "This will permanently delete and reset all of the following:", + "reset-item-1": "Your progress through each step/challenge (all completed challenges will be lost)", + "reset-item-2": "Any saved code, including partially completed challenges, and certification project code", + "reset-item-3": "All completed and claimed certifications", + "reset-p2": "You will effectively be set back to the very first day you signed up.", + "reset-p3": "We won't be able to recover any of it for you later, even if you change your mind.", + "nevermind-2": "Nevermind, I don't want to delete all of my progress", + "reset-confirm": "Reset everything. I want to start from the beginning", + "verify-text": "To verify, type \"{{ verifyText }}\" below:", + "verify-reset-text": "I agree that all progress will be lost", + "verify-delete-text": "I agree to delete my account" + }, + "email": { + "missing": "You do not have an email associated with this account.", + "heading": "Email", + "not-verified": "Your email has not been verified.", + "check": "Please check your email, or <0>request a new verification email here.", + "current": "Current Email", + "new": "New Email", + "confirm": "Confirm New Email", + "weekly": "Send me Quincy's weekly email" + }, + "socrates": { + "p1": "Socrates", + "p2": "Offers tailored hints based on your input in workshops. You can turn this off at any time." + }, + "honesty": { + "p1": "Before you can claim a verified certification, you must accept our Academic Honesty Pledge, which reads:", + "p2": "\"I understand that plagiarism means copying someone else’s work and presenting the work as if it were my own, without clearly attributing the original author.\"", + "p3": "\"I understand that plagiarism is an act of intellectual dishonesty, and that people usually get kicked out of university or fired from their jobs if they get caught plagiarizing.\"", + "p4": "\"Aside from using open source libraries such as jQuery and Bootstrap, and short snippets of code which are clearly attributed to their original author, 100% of the code in my projects was written by me, or along with another person going through the freeCodeCamp curriculum with whom I was pair programming in real time.\"", + "p5": "\"I pledge that I did not plagiarize any of my freeCodeCamp.org work. I understand that freeCodeCamp.org’s team will audit my projects to confirm this.\"", + "p6": "In the situations where we discover instances of unambiguous plagiarism, we will replace the person in question’s certification with a message that \"Upon review, this account has been flagged for academic dishonesty.\"", + "p7": "As an academic institution that grants achievement-based certifications, we take academic honesty very seriously. If you have any questions about this policy, or suspect that someone has violated it, you can email <0>{{email}} and we will investigate." + }, + "classroom-mode": { + "heading": "Classroom Mode", + "buttons": { + "agree": "I agree, share my learning data", + "accepted": "You have agreed to share your learning data." + }, + "p1": "\"Classroom Mode\" enables syncing your learning progress with the Classroom app, making it accessible to educators and institutions with whom you're affiliated.", + "p2": "When you enable this feature, you authorize freeCodeCamp to share your learning data—including completed challenges, projects, and time tracking—with the Classroom app and your educator, regardless of your profile privacy settings.", + "p3": "If you have any questions or concerns about \"Classroom Mode\", please contact support at <0>{{email}}.", + "p4": "Currently your data is <0>{{status}} with the Classroom app. {{message}}", + "status": { + "shared": "being shared", + "not-shared": "not being shared" + }, + "message": { + "shared": "Please contact support if you wish to revoke your consent.", + "not-shared": "You can give your consent below to allow data sharing." + } + } + }, + "exam": { + "attempts": "Attempts", + "no-attempts-yet": "No attempts yet", + "date-taken": "Date Taken", + "score": "Score", + "status": "Status", + "pending": "Pending", + "passed": "Passed", + "failed": "Failed", + "in-progress": "In Progress", + "denied": "Retake Required", + "download-header": "Download the freeCodeCamp Exam Environment App", + "explanation": "To earn a certification, you must take an exam to test your understanding of the material you have learned. Taking the exam is absolutely free of charge.", + "version": "The latest version of our app is: {{version}}.", + "download-details": "Manually download the app", + "unable-to-detect-os": "We were unable to detect your operating system. Please manually download the app below.", + "download-trouble": "If you have trouble downloading the correct version, do not hesitate to contact support:", + "open-exam-application": "Open Exam Environment Application" + }, + "profile": { + "you-change-privacy": "You need to change your privacy setting in order for your portfolio to be seen by others. This is a preview of how your portfolio will look when made public.", + "username-change-privacy": "{{username}} needs to change their privacy setting in order for you to view their portfolio.", + "supporter": "Supporter", + "contributor": "Top Contributor", + "contributor-prolific": "Among most prolific volunteers in {{year}}", + "no-certs": "No certifications have been earned under the current curriculum", + "fcc-certs": "freeCodeCamp Certifications", + "longest-streak": "Longest Streak:", + "current-streak": "Current Streak:", + "portfolio": "Portfolio", + "badges": "Badges", + "donated": "Donated to the community", + "projects": "Projects", + "stats": "Stats", + "activity": "Activity", + "timeline": "Timeline", + "none-completed": "No challenges have been completed yet.", + "get-started": "Get started here.", + "challenge": "Challenge", + "completed": "Completed", + "add-linkedin": "Add this certification to my LinkedIn profile", + "add-twitter": "Share this certification on X", + "tweet": "I just earned the {{certTitle}} certification @freeCodeCamp! Check it out here: {{certURL}}", + "avatar": "{{username}}'s avatar", + "joined": "Joined {{date}}", + "from": "From {{location}}", + "total-points": "Total Points:", + "points_one": "{{count}} point on {{date}}", + "points_other": "{{count}} points on {{date}}", + "page-number": "{{pageNumber}} of {{totalPages}}", + "edit-my-profile": "Edit My Profile", + "add-bluesky": "Share this certification on BlueSky", + "add-threads": "Share this certification on Threads", + "add-facebook": "Share this certification on Facebook", + "experience": { + "heading": "Experience", + "share-experience": "Share your professional experience", + "add": "Add experience", + "save": "Save experience", + "remove": "Remove experience", + "job-title": "Job title", + "company": "Company", + "location": "Location", + "start-date": "Start date", + "end-date": "End date", + "end-date-helper": "Leave blank if current position", + "description": "Description", + "present": "Present", + "date-format-error": "Please enter the date in MM/YYYY format.", + "date-invalid": "Please enter a valid date." + }, + "completeness": { + "heading": "Profile {{percentage}}% complete", + "title": "Profile Completion", + "progress": "{{percentage}}% complete", + "name": "Add your name", + "location": "Add your location", + "picture": "Upload a profile picture", + "about": "Write an about section", + "social": "Add a social link", + "portfolio": "Add a portfolio project", + "experience": "Add your experience", + "privacy": "Make your profile public" + } + }, + "footer": { + "tax-exempt-status": "freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charitable organization (United States Federal Tax Identification Number: 82-0779546).", + "mission-statement": "Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public.", + "donation-initiatives": "Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.", + "donate-text": "You can <1>make a tax-deductible donation here.", + "trending-guides": "Trending Guides", + "mobile-app": "Mobile App", + "our-nonprofit": "Our Charity", + "links": { + "about": "About", + "alumni": "Alumni Network", + "open-source": "Open Source", + "shop": "Shop", + "support": "Support", + "sponsors": "Sponsors", + "honesty": "Academic Honesty", + "coc": "Code of Conduct", + "privacy": "Privacy Policy", + "tos": "Terms of Service", + "copyright": "Copyright Policy" + }, + "language": "Language:" + }, + "learn": { + "heading": "Welcome to freeCodeCamp's curriculum.", + "skip-to-content": "Skip to content", + "welcome-1": "Welcome back, {{name}}.", + "welcome-2": "Welcome to freeCodeCamp.org", + "start-at-beginning": "If you are new to coding, we recommend you <0>start at the beginning.", + "happy-coding": "Happy coding!", + "upcoming-lessons": "Upcoming Lessons", + "learn": "Learn", + "add-subtitles": "Help improve or add subtitles", + "wrong-answer": "Sorry, that's not the right answer. Give it another try?", + "check-answer": "Click the button below to check your answer.", + "assignment-not-complete_one": "Please complete the assignment", + "assignment-not-complete_other": "Please complete the assignments", + "assignments_one": "Assignment", + "assignments_other": "Assignments", + "question": "Question", + "questions": "Questions", + "answered-mcq": "You have unanswered questions and/or incorrect answers.", + "explanation": "Explanation", + "transcript": "Transcript", + "solution-link": "Solution Link", + "source-code-link": "Source Code Link", + "ms-link": "Microsoft Link", + "submit-and-go": "Submit and go to my next challenge", + "congratulations": "Congratulations, your code passes. Submit your code to continue.", + "congratulations-code-passes": "Congratulations. Your code passes.", + "i-completed": "I've completed this challenge", + "example-code": "Example Code", + "test-output": "Your test output will go here", + "running-tests": "// running tests", + "tests-completed": "// tests completed", + "console-output": "// console output", + "unavailable-local-resource": "Failed to load resource: \"{{source}}\" is not an available local {{resourceType}} file. Use: {{allowedSources}}.", + "unavailable-local-resource-no-allowed": "Failed to load resource: \"{{source}}\" is not an available local {{resourceType}} file in this challenge.", + "local-resource-type": { + "stylesheet": "stylesheet", + "script": "script" + }, + "example-app": "Build an app that is functionally similar to <0>this example project. Try not to copy the example project, give it your own personal style.", + "syntax-error": "Your code raised an error before any tests could run. Please fix it and try again.", + "indentation-error": "Your code has an indentation error. You may need to add pass on a new line to form a valid block of code.", + "sign-in-save": "Sign in to save your progress", + "hints-used-today": "hints used today", + "donor-socrates-benefit": "Supporters get higher daily limits.", + "socrates-not-enabled": "Socrates is not enabled for your account.", + "socrates-check-code-first": "Check your code before asking Socrates for a hint.", + "socrates-code-passes": "Congratulations, your code passes! Press submit and continue to the next challenge.", + "socrates-write-code-first": "Please write some code before asking Socrates for a hint.", + "socrates-generic-error": "Something went wrong while asking Socrates. Please try again.", + "socrates-no-access": "You do not have access to Socrates.", + "socrates-daily-limit": "You have reached the daily hint limit. Please try again tomorrow.", + "socrates-rate-limit": "You have reached the hint limit. Please wait a moment before trying again.", + "socrates-unable-to-generate": "Socrates was unable to generate a hint. Please try again.", + "socrates-unavailable": "Socrates is temporarily unavailable. Please try again later.", + "socrates-invalid-request": "Something went wrong with your request. Please try again.", + "download-solution": "Download my solution", + "download-results": "Download my results", + "percent-complete": "{{percent}}% complete", + "project-complete": "Completed", + "tried-rsa": "If you've already tried the <0>Read-Search-Ask method, then you can ask for help on the freeCodeCamp forum.", + "read-search-ask-checkbox": "I have tried the <0>Read-Search-Ask method", + "similar-questions-checkbox": "I have searched for <0>similar questions that have already been answered on the forum", + "minimum-characters": "Please describe in at least {{characters}} more characters", + "characters-left": "You can add {{characters}} more characters to your query", + "must-confirm-statements": "You must confirm the following statements before you can submit your post to the forum.", + "min-50-max-500": "50 character minimum, 500 character maximum", + "rsa": "Read, search, ask", + "rsa-forum": "Before making a new post please <0>check if your question has already been answered on the forum.", + "reset": "Reset this lesson?", + "reset-warn": "Are you sure you wish to reset this lesson ({{title}})? The code editors and tests will be reset.", + "reset-warn-2": "This cannot be undone.", + "reset-progress-heading": "Reset Progress for {{label}}", + "reset-progress-description": "This will permanently delete and reset the '{{label}}' section. Your progress through each step/challenge, including any saved code will be lost, forever.", + "reset-progress-warning": "We won't be able to recover any of it for you later, even if you change your mind.", + "reset-progress-nevermind": "Nevermind, I don't want to reset my progress", + "reset-progress-confirm": "Reset my progress. I understand this cannot be undone", + "reset-progress-verify": "I agree to reset my progress", + "reset-progress-aria-chapter": "Reset progress for {{chapterLabel}}", + "reset-progress-aria-module": "Reset progress for {{moduleLabel}}", + "reset-progress-aria-block": "Reset progress for {{blockLabel}}", + "reset-progress-in-flight": "Resetting your progress, please wait...", + "reset-progress-success": "Your progress for '{{label}}' has been reset.", + "reset-progress-failure": "We could not reset your progress. Please try again, or contact support if the problem persists.", + "reset-progress-dismiss": "Dismiss", + "revert-warn": "Are you sure you wish to revert this lesson? Your latest changes will be undone and the code reverted to the most recently saved version.", + "scrimba-tip": "Tip: If the mini-browser is covering the code, click and drag to move it. Also, feel free to stop and edit the code in the video at any time.", + "chal-preview": "Challenge Preview", + "donation-record-not-found": "Your donation record has not been found.", + "donation-heading": "Progress towards donation goal", + "sign-in-card-update": "Sign in to update your card", + "sign-in-see-benefits": "Sign in to see your supporter benefits", + "card-has-been-updated": "Your card has been updated successfully.", + "contact-support-mistake": "If you think there has been a mistake, please contact us at donors@freecodecamp.org", + "editor-tabs": { + "code": "Code", + "tests": "Tests:", + "restart": "Restart", + "restart-step": "Restart Step", + "console": "Console", + "instructions": "Instructions", + "notes": "Notes", + "preview": "Preview", + "editor": "Editor", + "interactive-editor": "Interactive Editor", + "terminal": "Terminal" + }, + "editor-alerts": { + "tab-trapped": "Pressing tab will now insert the tab character", + "tab-free": "Pressing tab will now move focus to the next focusable element" + }, + "help-translate": "We are still translating this certification.", + "help-translate-link": "Help us translate.", + "project-preview-title": "Here's a preview of what you will build", + "demo-project-title": "Here's an example of a project that meets the requirements", + "github-required": "<0>Create a GitHub account if you don't have one. You'll need it when you create the virtual Linux server machine. This process may take a few minutes.", + "codespaces": { + "intro": "This course runs in a virtual Linux machine using GitHub Codespaces. Follow these instructions to start the course:", + "step-1": "<0>Create a GitHub account if you don't have one", + "step-2": "Click the start button below", + "step-3": "On that page, click the create button", + "step-4": "Once the virtual Linux machine is finished loading, start the CodeRoad extension by:", + "step-5": "Clicking the \"hamburger\" menu near the top left of the VSCode window,", + "step-6": "Going to the <0>View menu,", + "step-7": "Clicking on the <0>Command Palette option,", + "step-8": "and running the <0>CodeRoad: Start command", + "step-9": "Follow the instructions in CodeRoad to complete the course", + "continue-project": "Clicking the start button below will start a new project. If you have previously started the {{title}} course, go to <0>your Codespaces to re-open a previous workspace.", + "learn-more": "Learn more about <0>Codespace workspaces.", + "reuse-tab-warning": "Don't bookmark the link the start button opens, or reuse an old browser tab from a previous session. Doing so opens a new workspace instead of resuming your previous one, and it may look like your progress was lost. Use your Codespaces list to resume instead.", + "logout-warning": "If you log out of freeCodeCamp before you complete the entire {{course}} course, your progress will not be saved to your freeCodeCamp account.", + "sub-step-3": "Navigate to your <0>Codespaces secrets page", + "sub-step-4": "Create a new secret named <0>CODEROAD_WEBHOOK_TOKEN", + "sub-step-5": "In the <0>Value field, paste your token", + "sub-step-6": "In the <0>Repository access field, select the <1>freeCodeCamp/rdb-alpha repository", + "sub-step-7": "Click the <0>Add secret button", + "summary": "Codespaces Setup" + }, + "freecodecamp-os": { + "token-modal": "When you run the course, a modal will appear asking for your user token. Paste the token you copied above into it. You only need to do this once per environment.", + "local": { + "intro": "This course runs in a dev container on your computer using the freeCodeCamp - Courses VS Code extension. To run the course, you first need to download each of the following if you don't already have them:", + "heading": "Then, follow these instructions to start the course:", + "step-1": "Open a terminal and clone the back-end-development-and-apis repo if you don't already have it with <0>git clone https://github.com/freeCodeCamp/back-end-development-and-apis", + "step-2": "Navigate to the <0>back-end-development-and-apis directory in the terminal with <1>cd back-end-development-and-apis, and open VS Code with <2>code .", + "step-3": "Open the command palette in VS Code by expanding the \"View\" menu and clicking \"Command Palette...\" and enter <0>Dev Containers: Rebuild and Reopen in Container in the input.", + "step-4": "A new VS Code window will open and begin building the dev container. It will take several minutes the first time.", + "step-5": "Once it is finished building, open the command palette again and enter <0>freeCodeCamp: Run Course to start the course.", + "step-6": "The Simple Browser will open when it is done. If it is a blank white page, use the refresh button to update it and see the course home page.", + "step-7": "Click on one of the available projects to start it, then follow the instructions in the project to complete it." + }, + "codespaces": { + "intro": "This course runs in a virtual Linux machine using GitHub Codespaces and the freeCodeCamp - Courses VS Code extension. Follow these instructions to start the course:", + "step-1": "<0>Create a GitHub account if you don't have one", + "step-2": "Click the start button below", + "step-3": "On the page that opens, click the create button", + "step-4": "Once the virtual Linux machine is finished loading, open the command palette and run the <0>freeCodeCamp: Run Course command", + "step-5": "The Simple Browser will open when it is done. If it is a blank white page, use the refresh button to update it and see the course home page.", + "step-6": "Click on one of the available projects to start it, then follow the instructions in the project to complete it.", + "continue-project": "Clicking the start button below will start a new machine. If you have previously started the {{title}} course, go to the <0>repository page to re-open a previous workspace." + } + }, + "local": { + "intro": "This course runs in a virtual Linux machine on your computer. To run the course, you first need to download each of the following if you don't already have them:", + "download-vscode": "<0>VS Code and the <1>Dev Containers extension", + "heading": "Then, follow these instructions to start the course:", + "step-1": "Open a terminal and clone the RDB Alpha repo if you don't already have it with <0>git clone https://github.com/freeCodeCamp/rdb-alpha", + "step-2": "Navigate to the <0>rdb-alpha directory in the terminal with <1>cd rdb-alpha, and open VS Code with <2>code .", + "sub-step-heading": "If you want to save your progress to your freeCodeCamp account, do the following:", + "sub-step-1": "Generate a user token if you don't already have one:", + "generate-token-btn": "Generate User Token", + "sub-step-2": "Copy your user token:", + "copy-token-btn": "Copy User Token", + "logout-warning": "If you log out of freeCodeCamp before you complete the entire {{course}} course, your user token will be deleted and your progress will not be saved to your freeCodeCamp account.", + "sub-step-3": "In the VS Code that opened, find and open the file named <0>Dockerfile. At the bottom of the file, paste your token in as the value for the <1>CODEROAD_WEBHOOK_TOKEN variable. It should look like this: <2>ENV CODEROAD_WEBHOOK_TOKEN=your-token-here", + "step-3": "Open the command palette in VS Code by expanding the \"View\" menu and clicking \"Command Palette...\" and enter <0>Dev Containers: Rebuild and Reopen in Container in the input.", + "step-4": "A new VS Code window will open and begin building the Docker image. It will take several minutes the first time.", + "step-5": "Once it is finished building, open the command palette again and enter <0>CodeRoad: Start to open CodeRoad.", + "step-6": "In the CodeRoad window, click \"Start New Tutorial\" and then the \"URL\" tab at the top.", + "step-7": "Copy the course URL below, paste it in the URL input, and click \"Load\".", + "copy-url": "Copy Course URL", + "step-8": "Click \"Start\" to begin.", + "step-9": "Follow the instructions in CodeRoad to complete the course. Note: You may need to restart the terminal once for terminal settings to take effect and the tests to pass.", + "summary": "Local Setup" + }, + "step-1": "Step 1: Complete the project", + "step-2": "Step 2: Submit your code", + "submit-public-url": "When you have completed the project, save all the required files into a public repository and submit the URL to it below.", + "complete-both-steps": "Complete both steps below to finish the challenge.", + "runs-in-vm": "The project runs in a virtual machine, complete the user stories described in there and get all the tests to pass to finish step 1.", + "completed": "Completed", + "not-completed": "Not completed", + "not-started": "Not started", + "steps-completed": "{{completedSteps}} of {{totalSteps}} steps complete", + "test": "Test", + "sorry-try-again": "Sorry, your code does not pass. Try again.", + "sorry-keep-trying": "Sorry, your code does not pass. Keep trying.", + "sorry-getting-there": "Sorry, your code does not pass. You're getting there.", + "sorry-hang-in-there": "Sorry, your code does not pass. Hang in there.", + "sorry-dont-giveup": "Sorry, your code does not pass. Don't give up.", + "challenges-completed": "{{completedCount}} of {{totalChallenges}} challenges completed", + "season-greetings-fcc": "Season's Greetings from the freeCodeCamp community 🎉", + "if-getting-value": "If you're getting a lot out of freeCodeCamp, now is a great time to donate to support our charity's mission.", + "building-a-university": "We're Building a Free Computer Science University Degree Program 🎉", + "if-help-university": "We've already made a ton of progress. Donate now to help our charity with the road ahead.", + "preview-external-window": "Preview currently showing in external window.", + "fill-in-the-blank": { + "heading": "Fill in the blank", + "blank": "blank" + }, + "quiz": { + "correct-answer": "Correct!", + "incorrect-answer": "Incorrect.", + "unanswered-questions": "The following questions are unanswered: {{ unansweredQuestions }}. You must answer all questions.", + "have-n-correct-questions": "You have {{ correctAnswerCount }} out of {{ total }} questions correct.", + "finish-modal-header": "Finish Quiz", + "finish-modal-body": "Are you sure you want to finish the quiz?", + "finish-modal-yes": "Yes, I am finished", + "finish-modal-no": "No, I would like to continue the quiz", + "exit-modal-header": "Exit Quiz", + "exit-modal-body": "Are you sure you want to leave the quiz? You will lose any progress you have made.", + "exit-modal-yes": "Yes, I want to leave the quiz", + "exit-modal-no": "No, I would like to continue the quiz" + }, + "exam": { + "qualified": "Congratulations, you have completed all the requirements to qualify for the exam.", + "not-qualified": "You have not met the requirements to be eligible for the exam. To qualify, please complete the following challenges:", + "time": "Time: {{ t }}", + "questions": "Question {{ n }} of {{ t }}", + "passed": "Passed", + "not-passed": "Not Passed", + "number-of-questions": "Number of questions: {{ n }}", + "correct-answers": "Correct answers: {{ n }}", + "percent-correct": "Percent correct: {{ n }}%", + "passed-message": "Congratulations! You passed the exam and can claim your certification.", + "not-passed-message": "Sorry, but you did not answer enough questions correctly to pass the exam.", + "results-header": "{{ title }} Results", + "question-results": "You correctly answered {{ n }} out of {{ q }} questions", + "percent-results": "{{ p }}% correct", + "finish-header": "Finish Exam", + "finish": "Are you sure you want to finish the exam? You will not be able to change any answers. Your results will be final.", + "finish-yes": "Yes, I am finished", + "finish-no": "No, I would like to continue the exam", + "exit-header": "Exit Exam", + "exit": "Are you sure you want to leave the exam? You will lose any progress you have made.", + "exit-yes": "Yes, I want to leave the exam", + "exit-no": "No, I would like to continue the exam", + "not-honest": "You need to <0>accept the Academic Honesty Policy to take this exam" + }, + "ms": { + "link-header": "Link your Microsoft account", + "link-signin": "To complete this challenge, you must first link your Microsoft username to your freeCodeCamp account. Sign in to link your Microsoft username.", + "linked": "The Microsoft account with username \"{{ msUsername }}\" is currently linked to your freeCodeCamp account. If this is not your Microsoft username, remove the link.", + "unlinked": "To complete this challenge, you must first link your Microsoft username to your freeCodeCamp account by following these instructions:", + "link-li-1": "Using a browser where you are logged into your Microsoft account, go to <0>https://learn.microsoft.com/users/me/transcript", + "link-li-2": "Find and click the \"Share link\" button.", + "link-li-3": "If you do not have a transcript link, click the \"Create link\" button to create one.", + "link-li-4": "Click the \"Copy link\" button to copy the transcript URL.", + "link-li-5": "Paste the URL into the input below, it should look similar to this: <0>https://learn.microsoft.com/LOCALE/users/USERNAME/transcript/ID", + "link-li-6": "Click \"Link Account\" to link your Microsoft username.", + "transcript-label": "Your Microsoft Transcript Link", + "invalid-transcript": "Your transcript link is not correct, it should have the following form: <1>https://learn.microsoft.com/LOCALE/users/USERNAME/transcript/ID - check the UPPERCASE items in your link are correct." + }, + "block-type": { + "lecture": "Theory", + "workshop": "Workshop", + "lab": "Lab", + "review": "Review", + "quiz": "Quiz", + "cert-project": "Certification Project", + "exam": "Exam", + "warm-up": "Warm-up", + "learn": "Learn", + "practice": "Practice", + "video": "Video" + }, + "archive": { + "title": "Archived Coursework", + "content-not-updated": "The content in this section is not being updated, but is still available for you to further your learning. We recommend trying <0>our current curriculum." + }, + "search": { + "search-challenges-in-curriculum": "Search lessons in the curriculum", + "search-challenges-results": "Showing {{resultCount}} matching lessons for \"{{term}}\".", + "search-challenges-no-results": "No results found for \"{{term}}\"." + } + }, + "donate": { + "title": "Support our charity", + "processing": "We are processing your donation.", + "redirecting": "Redirecting...", + "thanks": "Thanks for donating", + "thank-you": "Thank You for Being a Supporter", + "thank-you-continued": "Thank you for your continued support", + "success-card-update": "Your card has been updated successfully.", + "additional": "You can make an additional one-time donation of any amount using this link: <0>{{url}}", + "help-more": "Help Our Charity Do More", + "error": "Something went wrong with your donation.", + "error-card-update": "Something went wrong with updating your card.", + "error-2": "Something is not right. Please contact donors@freecodecamp.org", + "error-3": "Please try again or contact donors@freecodecamp.org", + "free-tech": "Your donations will support free technology education for people all over the world.", + "visit-supporters": "Visit the Supporters page to learn about your Supporter benefits.", + "gift-frequency": "Select gift frequency:", + "gift-amount": "Select gift amount:", + "confirm": "Confirm your donation:", + "confirm-one-time": "Confirm your one-time donation of ${{usd}}:", + "confirm-monthly": "Confirm your donation of ${{usd}} / month:", + "confirm-yearly": "Confirm your donation of ${{usd}} / year:", + "confirm-multitier": "Donating ${{usd}} / month:", + "edit-amount": "edit amount", + "wallet-label": "${{usd}} donation to freeCodeCamp", + "wallet-label-1": "${{usd}} / month donation to freeCodeCamp", + "your-donation": "Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world.", + "your-donation-2": "Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world each month.", + "your-donation-3": "Your ${{usd}} donation will provide {{hours}} hours of learning to people around the world each year.", + "repeats-monthly": "Your donation will repeat monthly until canceled.", + "become-supporter": "Become a Supporter", + "progress-modal-cta-1": "Donate now to help our charity build a free accredited Computer Science degree for all.", + "progress-modal-cta-2": "Donate now to sponsor 53 hours of server time for our charity's website.", + "progress-modal-cta-3": "Donate now to help our charity translate lessons into 32 languages for learners worldwide.", + "progress-modal-cta-4": "Donate now to support development of our charity's new Python curriculum.", + "progress-modal-cta-5": "Donate now to help our charity design lessons on new programming tools.", + "progress-modal-cta-6": "Donate now to support our charity's open source projects.", + "progress-modal-cta-7": "Donate now to help our charity hire even more amazing teachers.", + "progress-modal-cta-8": "Donate now to help us develop new courses on emerging tools and programming concepts.", + "progress-modal-cta-9": "Donate now to support our math for developers curriculum.", + "progress-modal-cta-10": "Donate now to help us develop free professional programming certifications for all.", + "help-us-reach-20k": "Donate now to help our charity reach our goal of 20,000 monthly supporters this year.", + "beta-certification": "This certification is currently in beta. Please consider donating to support the completion of its development.", + "unfinished-certification": "This certification is currently in active development. While there isn't a claimable certification available at the moment, one will be available soon. In the meantime, you're welcome to explore the courses we have created below.", + "consider-donating": "Please consider donating to support the completion of its development.", + "unfinished-certification-2": "This certification will take you a substantial amount of time and effort to complete. If you start now, you may be ready to take the final exam when we launch it in the coming months.", + "consider-donating-2": "If you want to help us speed up development of this curriculum, please consider becoming a supporter of our charity.", + "help-us-develop": "Help us develop free professional programming certifications for all.", + "nicely-done": "Nicely done. You just completed {{block}}.", + "credit-card": "Credit Card", + "credit-card-2": "Or donate with a credit card:", + "or-card": "Or donate with card", + "paypal": "with PayPal:", + "need-email": "We need a valid email address to which we can send your donation tax receipt.", + "went-wrong": "Something went wrong processing your donation. Your card has not been charged.", + "valid-info": "Please enter valid email address, credit card number, and expiration date.", + "valid-email": "Please enter a valid email address.", + "valid-card": "Please enter valid credit card number and expiration date.", + "email-receipt": "Email (we'll send you a tax-deductible donation receipt):", + "need-help": "Need help with your current or past donations?", + "forward-receipt": "Forward a copy of your donation receipt to donors@freecodecamp.org and tell us how we can help.", + "efficiency": "freeCodeCamp is a highly efficient education charity.", + "why-donate-1": "When you donate to freeCodeCamp, you help people learn new skills and provide for their families.", + "why-donate-2": "You also help us create new resources for you to use to expand your own technology skills.", + "bigger-donation": "Want to make a bigger one-time donation, mail us a check, or give in other ways?", + "other-ways": "Here are many <0>other ways you can support our charity's mission.", + "if-support-further": "If you want to support our charity further, please consider <0>making a one-time donation, <1>sending us a check, or <2>learning about other ways you could support our charity.", + "failed-pay": "Uh - oh. It looks like your transaction didn't go through. Could you please try again?", + "try-another-method": "Uh - oh. It looks like your transaction didn't go through. Could you please try another payment method?", + "try-again": "Please try again.", + "card-number": "Your Card Number:", + "expiration": "Expiration Date:", + "secure-donation": "Secure donation", + "faq": "Frequently asked questions:", + "only-you": "Only you can see this message. Congratulations on earning this certification. It's no easy task. Running freeCodeCamp isn't easy either. Nor is it cheap. Help us help you and many other people around the world. Make a tax-deductible supporting donation to our charity today.", + "get-help": "How can I get help with my donations?", + "offer-refunds": "Does freeCodeCamp offer refunds?", + "donations-are-voluntary": "Donations to freeCodeCamp are voluntary charitable contributions and are non-refundable. Once a donation has been processed, we do not offer refunds.", + "cancel-future-donations": "If you started a monthly donation, you can cancel future donations at any time by forwarding a copy of your donation receipt to donors@freecodecamp.org and telling us you would like to cancel.", + "without-your-authorization": "If you believe a donation was made without your authorization, or if you see a duplicate charge, please email donors@freecodecamp.org so we can review it.", + "how-transparent": "How transparent is freeCodeCamp?", + "very-transparent": "Very. We have a Platinum transparency rating from GuideStar.org.", + "download-irs": "You can <0>download our IRS Determination Letter here.", + "download-990": "You can <0>download our most recent 990 (annual tax report) here.", + "how-efficient": "How efficient is freeCodeCamp?", + "fcc-budget": "freeCodeCamp's budget is much smaller than most comparable charities. We do not use professional fundraising firms. We keep our fundraising operations small so more of our budget can support our educational mission.", + "help-millions": "However, on a budget of only a few hundred thousand dollars per year, we have been able to help millions of people.", + "how-one-time": "How can I make a one-time donation?", + "one-time": "If you prefer to make one-time donations, you can support freeCodeCamp's mission whenever you have cash to spare. You can use <0>this link to donate any amount through PayPal.", + "wire-transfer": "You can also send money to freeCodeCamp directly through a wire transfer. If you need our wire details, email Quincy at quincy@freecodecamp.org", + "does-crypto": "Does freeCodeCamp accept donations in Bitcoin or other cryptocurrencies?", + "yes-cryptocurrency": "Yes. Please email Quincy at quincy@freecodecamp.org and he can send you freeCodeCamp's wallet information. He can also provide you with a donation receipt if you need one for your taxes.", + "can-check": "Can I mail a physical check?", + "yes-check": "Yes, we would welcome a check. You can mail it to us at:", + "how-matching-gift": "How can I set up matching gifts from my employer, or payroll deductions?", + "employers-vary": "This varies from employer to employer, and our charity is already listed in many of the big donation-matching databases.", + "some-volunteer": "Some people are able to volunteer for freeCodeCamp and their employer matches by donating a fixed amount per hour they volunteer. Other employers will match any donations the donors make up to a certain amount", + "help-matching-gift": "If you need help with this, please email Quincy directly: quincy@freecodecamp.org", + "how-endowment": "How can I set up an endowment gift to freeCodeCamp?", + "endowment": "Endowment gifts can help sustain freeCodeCamp's mission over the long term. Since this is a more manual process, Quincy can help walk you through it personally. Please email him directly at quincy@freecodecamp.org.", + "how-legacy": "How can I set up a legacy gift to freeCodeCamp?", + "we-honored": "We would be honored to put such a gift to good use helping people around the world learn to code. Depending on where you live, this may also be tax exempt.", + "legacy-gift-message": "I give, devise, and bequeath [the sum of _____ USD (or other currency) OR _____ percent of the rest and residue of my estate] to freeCodeCamp.org (Free Code Camp, Inc. tax identification number 82-0779546), a charitable corporation organized under the laws of the State of Delaware, United States, currently located at 3905 Hedgcoxe Rd, PO Box 250352, Plano, Texas, 75025 United States, to be used for its general charitable purposes at its discretion.", + "thank-wikimedia": "We would like to thank the Wikimedia Foundation for providing this formal language for us to use.", + "legacy-gift-questions": "If you have any questions about this process, please email Quincy at quincy@freecodecamp.org.", + "how-stock": "How can I donate stock to freeCodeCamp?", + "welcome-stock": "We would welcome your stock donations. Please email Quincy directly and he can help you with this, and share our charity's brokerage account details: quincy@freecodecamp.org.", + "how-receipt": "Can I get a donation receipt so that I can deduct my donation from my taxes?", + "just-forward": "Absolutely. Just forward the receipt from your transaction to donors@freecodecamp.org, tell us you'd like a receipt and any special instructions you may have, and we'll reply with a receipt for you.", + "how-update": "I set up a monthly donation. How can I update, pause, or cancel it?", + "take-care-of-this": "Forward a copy of your donation receipt to donors@freecodecamp.org and tell us what you would like to change.", + "help-update-change-cancel": "We can help you update your monthly donation amount, change your payment method, pause your monthly donation, or cancel future monthly donations. Canceling a monthly donation stops future charges.", + "anything-else": "Is there anything else I can learn about donating to freeCodeCamp?", + "other-support": "If there is some other way you'd like to support our charity and its mission that isn't listed here, or if you have any questions at all, please email Quincy at quincy@freecodecamp.org.", + "how-will-donation-appear": "How will my donation appear on my bank or card statement?", + "as-freecodecamp-inc": "Your donation may appear on your bank or card statement as \"freeCodeCamp\", \"Free Code Camp\", \"Free Code Camp, Inc.\", or the name of one of our payment processors.", + "do-not-recognize": "If you do not recognize a charge, please email donors@freecodecamp.org before filing a dispute. We can help you identify the donation, update or cancel future monthly donations, and answer any questions.", + "are-benefits-a-product": "Are Supporter benefits a product I am buying?", + "benefits-are-thanks": "No. Donations to freeCodeCamp are charitable contributions. Supporter benefits, such as removed donation prompt popups, a Supporter badge, profile styling, and access to Supporter Discord channels, are our way of thanking donors.", + "benefits-not-sold-separately": "These benefits may change over time and are not sold separately. Your donation supports freeCodeCamp's charitable mission of helping people learn to code for free.", + "is-donation-tax-deductible": "Is my donation tax-deductible?", + "freecodecamp-is-a-charitable-organization": "Free Code Camp, Inc. is a tax-exempt 501(c)(3) charitable organization in the United States. Our tax identification number is 82-0779546.", + "donations-may-be-deductible": "Donations may be tax-deductible for donors in the United States, depending on your individual tax situation. Donors outside the United States should check the rules in their country.", + "annual-donation-receipt": "We cannot provide tax advice, but we can provide an annual donation receipt. If you need help with that, email us at donors@freecodecamp.org.", + "bear-progress-alt": "Illustration of an adorable teddy bear with a pleading expression holding an empty money jar.", + "bear-completion-alt": "Illustration of an adorable teddy bear holding a large trophy.", + "flying-bear": "Illustration of an adorable teddy bear wearing a graduation cap and flying with a Supporter badge.", + "crucial-contribution": "Your contributions are crucial in creating resources that empower millions of people to learn new skills and support their families.", + "support-benefits-title": "Benefits of becoming a Supporter:", + "support-benefits-1": "No more donation prompt popups while signed in", + "support-benefits-2": "A Supporter badge on your profile page", + "support-benefits-3": "A golden halo around your profile image", + "support-benefits-4": "Access to special Supporter Discord channels - <0>join our Discord and use the <1>/supporter command to get access", + "support-benefits-6": "You’ll get higher usage limits for select beta features.", + "support-benefits-disclaimer": "Supporter benefits are our way of thanking donors and may change over time.", + "exclusive-features": "Here is the list of exclusive features for you as a Supporter:", + "current-initiatives-title": "Your donations help us:", + "your-donation-helps-followings": "Your donation makes the following initiatives possible:", + "current-initiatives-1": "Build new JavaScript and Python curricula", + "current-initiatives-2": "Create free English and math curricula", + "current-initiatives-3": "Translate our curriculum and tutorials into 32 languages", + "current-initiatives-4": "Develop a free accredited computer science bachelor's degree", + "community-achievements-title": "Our recent community achievements:", + "community-achievements-1": "Published <0>193 full-length courses on YouTube", + "community-achievements-2": "Published <0>850 text-based coding tutorials and <0>5 free books through freeCodeCamp Press", + "community-achievements-3": "Merged <0>2,455 code contributions into our open source repositories on GitHub", + "community-achievements-4": "Translated <0>1.5 million words to make our curriculum and tutorials more accessible to speakers of many world languages", + "careful-with-every-donation": "We are careful with every donation and put donor support directly toward our charitable mission.", + "get-benefits": "Get the benefits and the knowledge that you're helping our charity change education for the better. Become a Supporter today.", + "modal-benefits-title": "Support us", + "help-us-more-certifications": "Help us build more certifications", + "remove-donation-popups": "Remove donation popups", + "help-millions-learn": "Help millions of people learn", + "reach-goals-faster": "Reach your goals faster", + "remove-distractions": "Remove distractions", + "remove-interruptions": "Remove interruptions", + "acquire-skills-faster": "Acquire skills faster", + "animation-description": "This is a 20 second animated advertisement to encourage campers to become supporters of freeCodeCamp. The animation starts with a teddy bear who becomes a supporter. As a result, distracting pop-ups disappear and the bear gets to complete all of its goals. Then, it graduates and becomes an education super hero helping people around the world.", + "animation-countdown": "This animation will stop after {{secondsRemaining}} seconds." + }, + "report": { + "sign-in": "You need to be signed in to report a user", + "details": "Please provide as much detail as possible about the account or behavior you are reporting.", + "portfolio": "Report a users portfolio", + "portfolio-2": "Do you want to report {{username}}'s portfolio for abuse?", + "notify-1": "We will notify the community moderators' team, and send a copy of this report to your email: {{email}}", + "notify-2": "We may get back to you for more information, if required.", + "what": "What would you like to report?", + "submit": "Submit the report" + }, + "404": { + "page-not-found": "Page not found", + "not-found": "404 Not Found:", + "heres-a-quote": "We couldn't find what you were looking for, but here is a quote:" + }, + "search": { + "label": "Search", + "placeholder": { + "default": "Search our books and courses", + "numbered": "Search {{ roundedTotalRecords }}+ of our books and courses" + }, + "see-results": "See all results for {{searchQuery}}", + "try": "Looking for something? Try the search bar on this page.", + "no-results": "No results found", + "result-list": "Search results" + }, + "misc": { + "coming-soon": "Coming Soon", + "note": "Note", + "caution": "Caution", + "offline": "You appear to be offline, your progress may not be saved", + "server-offline": "The server could not be reached and your progress may not be saved. Please contact <0>support if this message persists", + "unsubscribed": "You have successfully been unsubscribed", + "keep-coding": "Whatever you go on to, keep coding!", + "email-signup": "Email Sign Up", + "email-signup-not-signed-in": "Sign in to adjust your newsletter preferences.", + "brand-new-account": "Welcome to your brand new freeCodeCamp account. Let's get started.", + "duplicate-account-warning": "If you meant to sign into an existing account instead of creating this account, <0>click here to delete this account and try another email address.", + "quincy": "- Quincy Larson, the teacher who founded freeCodeCamp.org", + "email-blast": "Each Friday I send an email with 5 links about programming and computer science. I send these to about 6 million people. Would you like me to send this to you, too?", + "update-email-1": "Update your email address", + "update-email-2": "Update your email address here:", + "email": "Email", + "and": "and", + "update-your-card": "Update your card", + "supporters-page-title": "Supporters page", + "change-theme": "Sign in to change theme.", + "translation-pending": "Help us translate", + "certification-project": "Certification Project", + "iframe-preview": "{{title}} preview", + "iframe-alert": "Normally this link would bring you to another website! It works. This is a link to: {{externalLink}}", + "iframe-form-submit-alert": "Normally this form would be submitted! It works. This will be submitted to: {{externalLink}}", + "document-notfound": "document not found", + "slow-load-msg": "Looks like this is taking longer than usual, please try refreshing the page.", + "navigation-warning": "If you leave this page, you will lose your progress. Are you sure?", + "fsd-b-description": "This comprehensive course prepares you to become a Certified Full-Stack Developer. You'll learn to build complete web applications using HTML, CSS, JavaScript, React, TypeScript, Node.js, Python, and more.", + "fsd-b-cta": "Start Learning", + "continue-learning": "Continue Learning", + "fsd-b-benefit-1-title": "100k+ Students", + "fsd-b-benefit-1-description": "Join more than 100k students taking this certification.", + "fsd-b-benefit-2-title": "Professional Certification", + "fsd-b-benefit-2-description": "Prove your skills with an official, verifiable certification.", + "fsd-b-benefit-3-title": "500+ Exercises", + "fsd-b-benefit-3-description": "Solidify your knowledge with plenty of practice.", + "or": "OR" + }, + "mobile-app-modal": { + "heading": "We see you are on mobile!", + "body": "This course is available in our app for a better experience.", + "ios": "Download on the App Store", + "android": "Get it on Google Play", + "open-app": "Open in App", + "do-not-show": "Do not show me again" + }, + "icons": { + "gold-cup": "Gold Cup", + "avatar": "Default Avatar", + "avatar-2": "An avatar coding with a laptop", + "donate": "Donate with PayPal", + "fail": "Test Failed", + "not-passed": "Not Passed", + "waiting": "Waiting", + "passed": "Passed", + "failed": "Failed", + "hint": "Hint", + "heart": "Heart", + "initial": "Initial", + "input-reset": "Clear search terms", + "input-search": "Submit search terms", + "info": "Intro Information", + "spacer": "Spacer", + "toggle": "Toggle Checkmark", + "magnifier": "Submit search terms" + }, + "aria": { + "fcc-curriculum": "freeCodeCamp Curriculum", + "answer": "Answer", + "linkedin": "Link to {{username}}'s LinkedIn", + "github": "Link to {{username}}'s GitHub", + "website": "Link to {{username}}'s website", + "twitter": "Link to {{username}}'s X", + "bluesky": "Link to {{username}}'s Bluesky", + "next-month": "Go to next month", + "previous-month": "Go to previous month", + "first-page": "Go to first page", + "previous-page": "Go to previous page", + "next-page": "Go to next page", + "last-page": "Go to last page", + "primary-nav": "primary", + "breadcrumb-nav": "breadcrumb", + "timeline-pagination-nav": "Timeline Pagination", + "submit": "Use Ctrl + Enter to submit.", + "running-tests": "Running tests", + "hide-preview": "Hide the preview", + "move-preview-to-new-window": "Move the preview to a new window and focus it", + "move-preview-to-main-window": "Move the preview to this window and close the external preview window", + "close-external-preview-window": "Close the external preview window", + "show-preview": "Show the preview in this window", + "open-preview-in-new-window": "Open the preview in a new window and focus it", + "step": "Step", + "steps": "Steps", + "steps-for": "Steps for {{blockTitle}}", + "task": "Task", + "dialogues-and-tasks-for": "Dialogues and tasks for {{blockTitle}}", + "code-example": "{{codeName}} code example", + "opens-new-window": "Opens in new window", + "rsa-checkbox": "I have tried the Read-Search-Ask method", + "similar-questions-checkbox": "I have searched for similar questions that have already been answered on the forum", + "edit-my-profile": "Edit my profile", + "add-portfolio": "Add portfolio project", + "edit-portfolio": "Edit portfolio project", + "add-experience": "Add experience", + "edit-experience": "Edit experience", + "editor-a11y-off-macos": "{{editorName}} editor content. Press Option+F1 for accessibility options.", + "editor-a11y-off-non-macos": "{{editorName}} editor content. Press Alt+F1 for accessibility options.", + "editor-a11y-on-macos": "{{editorName}} editor content. Accessibility mode set to 'on'. Press Command+E to disable or press Option+F1 for more options.", + "editor-a11y-on-non-macos": "{{editorName}} editor content. Accessibility mode set to 'on'. Press Ctrl+E to disable or press Alt+F1 for more options.", + "terminal-output": "Terminal output", + "not-available": "Not available", + "interactive-editor-desc": "Turn static code examples into interactive editors. This allows you to edit and run the code directly on the page.", + "hide-terminal": "Hide the terminal", + "move-terminal-to-new-window": "Move the terminal to a new window and focus it", + "move-terminal-to-main-window": "Move the terminal to this window and close the external terminal window", + "close-external-terminal-window": "Close the external terminal window", + "pinyin-to-hanzi-input-desc": "This task uses Pinyin-to-Hanzi inputs. Type pinyin with tone numbers (1 to 5). When you enter a correct syllable, it will turn into a Chinese character. If you press backspace after a Chinese character, it will change back to pinyin and remove the last thing you typed: if it's a tone number, the tone is removed; if it's a letter, the letter is removed.", + "pinyin-tone-input-desc": "This task uses Pinyin Tone inputs. Type pinyin with tone numbers (1 to 5). When you enter a tone number, it will be converted to a tone mark. If you press backspace, the last thing you typed is removed: if it's a tone number, the tone is removed; if it's a letter, the letter is removed." + }, + "flash": { + "no-email-in-userinfo": "We could not retrieve an email from your chosen provider. Please try another provider or use the 'Continue with Email' option.", + "honest-first": "To claim a certification, you must first agree to our academic honesty policy", + "really-weird": "Something really weird happened, if it happens again, please consider raising an issue on https://github.com/freeCodeCamp/freeCodeCamp/issues/new", + "generic-error": "Something went wrong. Please try again in a moment or contact support@freecodecamp.org if the error persists.", + "went-wrong": "Something went wrong, please check and try again", + "account-deleted": "Your account has been successfully deleted", + "progress-reset": "Your progress has been reset", + "module-reset": "Your module progress has been reset", + "not-authorized": "You are not authorized to continue on this route", + "could-not-find": "We couldn't find what you were looking for. Please check and try again", + "wrong-updating": "Something went wrong updating your account. Please check and try again", + "updated-about-me": "We have updated your personal information", + "updated-socials": "We have updated your social links", + "updated-sound": "We have updated your sound settings", + "updated-themes": "We have updated your theme", + "keyboard-shortcut-updated": "We have updated your keyboard shortcuts settings", + "subscribe-to-quincy-updated": "We have updated your subscription to Quincy's email", + "socrates-updated": "We have updated your Socrates settings", + "portfolio-item-updated": "We have updated your portfolio", + "experience-updated": "We have updated your experience", + "email-invalid": "Email format is invalid", + "email-valid": "Your email has successfully been changed, happy coding!", + "bad-challengeId": "currentChallengeId is not a valid challenge ID", + "theme-invalid": "Theme is invalid", + "theme-set": "Theme already set", + "theme-updated": "Your theme has been updated!", + "username-used": "Username is already associated with this account", + "username-taken": "Username is already associated with a different account", + "username-restricted": "That username is reserved and can't be used.", + "username-updated": "We have updated your username to {{username}}", + "privacy-updated": "We have updated your privacy settings", + "could-not-logout": "We could not log you out, please try again in a moment", + "email-encoded-wrong": "The email encoded in the link is incorrectly formatted", + "oops-not-right": "Oops, something is not right, please request a fresh link to sign in / sign up", + "expired-link": "Looks like the link you clicked has expired, please request a fresh link, to sign in", + "signin-success": "Success! You have signed in to your account. Happy Coding!", + "social-auth-gone": "We are moving away from social authentication for privacy reasons. Next time we recommend using your email address: {{email}} to sign in instead.", + "name-needed": "We need your name to put it on your certification. Please add your name in your profile and click save. Then we can issue your certification.", + "incomplete-steps": "It looks like you have not completed the necessary steps. Please complete the required projects to claim the {{name}} Certification.", + "already-claimed": "It looks like you already have claimed the {{name}} Certification", + "cert-claim-success": "@{{username}}, you have successfully claimed the {{name}} Certification! Congratulations on behalf of the freeCodeCamp.org team!", + "wrong-name": "Something went wrong with the verification of {{name}}, please try again. If you continue to receive this error, you can send a message to support@freeCodeCamp.org to get help.", + "error-claiming": "Error claiming {{certName}}", + "username-not-found": "We could not find a user with the username \"{{username}}\"", + "add-name": "This user needs to add their name to their account in order for others to be able to view their certification.", + "not-eligible": "This user is not eligible for freeCodeCamp.org certifications at this time.", + "profile-private": "{{username}} has chosen to make their profile private. They will need to make their profile public in order for others to be able to view their certification.", + "certs-private": "{{username}} has chosen to make their certifications private. They will need to make their certifications public in order for others to be able to view them.", + "certs-claimable": "You can now claim the {{certName}} certification! Visit your settings page to claim your certification.", + "not-honest": "{{username}} has not yet agreed to our Academic Honesty Pledge.", + "user-not-certified": "It looks like user {{username}} is not {{cert}} certified", + "invalid-challenge": "That does not appear to be a valid challenge submission", + "no-links-provided": "You have not provided the valid links for us to inspect your work.", + "no-social": "No social account found", + "invalid-social": "Invalid social account", + "no-account": "No {{website}} account associated", + "unlink-success": "You've successfully unlinked your {{website}}", + "provide-username": "Check if you have provided a username and a report", + "report-sent": "A report was sent to the team with {{email}} in copy", + "report-error": "Unable to report this user at this time.", + "certificate-missing": "The certification you tried to view does not exist", + "create-token-err": "An error occurred while creating your user token", + "delete-token-err": "An error occurred while deleting your user token", + "token-created": "You have successfully created a new user token.", + "token-deleted": "Your user token has been deleted.", + "start-project-err": "Something went wrong trying to start the project. Please try again.", + "complete-project-first": "You must complete the project first.", + "local-code-save-error": "Oops, your code did not save, your browser's local storage may be full.", + "local-code-saved": "Saved! Your code was saved to your browser's local storage.", + "timeline-private": "{{username}} has chosen to make their timeline private. They will need to make their timeline public in order for others to be able to view their certification.", + "code-saved": "Your code was saved to the database. It will be here when you return.", + "code-save-error": "An error occurred trying to save your code.", + "code-save-less": "Slow Down! Your code was not saved. Try again in a few seconds.", + "challenge-save-too-big": "Sorry, you cannot save your code. Your code is {{user-size}} bytes. We allow a maximum of {{max-size}} bytes. Please make your code smaller and try again or request assistance on https://forum.freecodecamp.org", + "challenge-submit-too-big": "Sorry, you cannot submit your code. Your code is {{user-size}} bytes. We allow a maximum of {{max-size}} bytes. Please make your code smaller and try again or request assistance on https://forum.freecodecamp.org", + "invalid-update-flag": "You are attempting to access forbidden resources. Please request assistance on https://forum.freecodecamp.org if this is a valid request.", + "generate-exam-error": "An error occurred trying to generate your exam.", + "cert-not-found": "The certification {{certSlug}} does not exist.", + "reset-editor-layout": "Your editor layout has been reset.", + "user-token-generated": "A user token was created for you.", + "user-token-generate-error": "Something went wrong trying to generate a user token for you.", + "user-token-copied": "User token copied to clipboard.", + "user-token-copy-error": "Something went wrong trying to copy your token.", + "course-url-copied": "Course URL copied to clipboard.", + "course-url-copy-error": "Something went wrong trying to copy the course URL.", + "ms": { + "transcript": { + "link-err-1": "Please include a Microsoft transcript URL in the request.", + "link-err-2": "Something went wrong trying to get your transcript from Microsoft.", + "link-err-3": "A username was not found in your Microsoft transcript.", + "link-err-4": "That Microsoft username is being used by another freeCodeCamp account.", + "link-err-5": "Something went wrong trying to save your Microsoft account.", + "link-err-6": "Something went wrong trying to link your Microsoft username to your freeCodeCamp account.", + "linked": "Your Microsoft username has been linked to your freeCodeCamp account.", + "unlinked": "The link to your Microsoft username has been removed.", + "unlink-err": "Something went wrong trying to remove the link to your Microsoft username." + }, + "profile": { + "err": "We could not find a Microsoft user ID for Microsoft user \"{{msUsername}}\"" + }, + "trophy": { + "err-1": "We could not find a Microsoft username associated with your freeCodeCamp account.", + "err-2": "You are trying to submit a challenge that does not appear to be a trophy challenge.", + "err-3": "We could not get your Microsoft profile from your Microsoft ID.", + "err-4": "It appears that the Microsoft user \"{{msUsername}}\" has not earned this trophy.", + "err-5": "Something went wrong trying to verify your trophy. Please check and try again.", + "err-6": "It looks like your Microsoft account might be private. Set it to public and try again.", + "verified": "Your trophy from Microsoft's learning platform was verified." + } + }, + "survey": { + "err-1": "The survey submitted is not in the correct format.", + "err-2": "It looks like you have already completed this survey.", + "err-3": "Something went wrong trying to save your survey.", + "success": "Thank you. Your survey was submitted." + }, + "classroom-mode-updated": "We have updated your classroom mode settings", + "user-fetch-error": "Unable to retrieve your user information. You can still use the site, but your progress may not be saved." + }, + "validation": { + "max-characters": "There is a maximum limit of 288 characters, you have {{charsLeft}} left", + "max-characters-500": "There is a maximum limit of 500 characters, you have {{charsLeft}} left", + "same-email": "This email is the same as your current email", + "invalid-email": "We could not validate your email correctly, please ensure it is correct", + "email-mismatch": "Both new email addresses must be the same", + "title-required": "A title is required", + "title-short": "Title is too short", + "title-long": "Title is too long", + "company-required": "Company is required", + "company-short": "Company name is too short", + "company-long": "Company name is too long", + "start-date-required": "Start date is required", + "invalid-url": "We could not validate your URL correctly, please ensure it is correct", + "invalid-protocol": "URL must start with http or https", + "url-not-image": "URL must link directly to an image file", + "use-valid-url": "Please use a valid URL", + "editor-url": "Remember to submit the Live App URL.", + "http-url": "An unsecure (http) URL cannot be used.", + "own-work-url": "Remember to submit your own work.", + "publicly-visible-url": "Remember to submit a publicly visible app URL.", + "ms-learn-link": "Please use a valid Microsoft Learn trophy link.", + "path-url": "You probably want to submit the root path i.e. https://example.com, not https://example.com/path", + "source-code-link-required": "Remember to submit the link to your source code.", + "source-code-link-public": "Source code link must be publicly visible." + }, + "certification": { + "executive": "Executive Director, freeCodeCamp.org", + "ms-president": "President, Microsoft Developer Division", + "verify": "Verify this certification at:", + "issued": "Issued", + "fulltext": "<0>This certifies that <1>{{user}} <2>successfully completed the <3>{{title}} <4>Developer Certification on {{time}} <5>representing approximately {{completionTime}} hours of work", + "fulltextNoHours": "<0>This certifies that <1>{{user}} <2>successfully completed the <3>{{title}} <4>Developer Certification on {{time}}", + "fulltextLanguageExam": "<0>This certifies that <1>{{user}} <2>has successfully passed the <3>{{title}} <4>exam on {{time}} <5>demonstrating competence in grammar, listening, and reading portions of the CEFR standards for this level based on the content covered in the curriculum.", + "quincy-larson-signature": "Quincy Larson's Signature", + "julia-liuson-signature": "Julia Liuson's Signature", + "project": { + "heading-legacy-full-stack": "As part of this Legacy Full-Stack certification, {{user}} completed the following certifications:", + "heading-exam": "As part of this certification, {{user}} passed the following exam: ", + "heading": "As part of this certification, {{user}} built the following projects and got all automated test suites to pass:", + "solution": "Solution", + "no-solution": "error displaying solution, email support@freeCodeCamp.org to get help.", + "no-solution-to-display": "No solution to display", + "source": "Source", + "footnote": "If you suspect that any of these projects violate the <2>academic honesty policy, please <5>report this to our team.", + "title": { + "Build a Personal Portfolio Webpage": "Build a Personal Portfolio Webpage", + "Build a Random Quote Machine": "Build a Random Quote Machine", + "Build a 25 + 5 Clock": "Build a 25 + 5 Clock", + "Build a JavaScript Calculator": "Build a JavaScript Calculator", + "Show the Local Weather": "Show the Local Weather", + "Use the TwitchTV JSON API": "Use the TwitchTV JSON API", + "Stylize Stories on Camper News": "Stylize Stories on Camper News", + "Build a Wikipedia Viewer": "Build a Wikipedia Viewer", + "Build a Tic Tac Toe Game": "Build a Tic Tac Toe Game", + "Build a Simon Game": "Build a Simon Game", + "Timestamp Microservice": "Timestamp Microservice", + "Request Header Parser Microservice": "Request Header Parser Microservice", + "URL Shortener Microservice": "URL Shortener Microservice", + "Image Search Abstraction Layer": "Image Search Abstraction Layer", + "File Metadata Microservice": "File Metadata Microservice", + "Build a Voting App": "Build a Voting App", + "Build a Nightlife Coordination App": "Build a Nightlife Coordination App", + "Chart the Stock Market": "Chart the Stock Market", + "Manage a Book Trading Club": "Manage a Book Trading Club", + "Build a Pinterest Clone": "Build a Pinterest Clone", + "Build a Markdown Previewer": "Build a Markdown Previewer", + "Build a Camper Leaderboard": "Build a Camper Leaderboard", + "Build a Recipe Box": "Build a Recipe Box", + "Build the Game of Life": "Build the Game of Life", + "Build a Roguelike Dungeon Crawler Game": "Build a Roguelike Dungeon Crawler Game", + "Visualize Data with a Bar Chart": "Visualize Data with a Bar Chart", + "Visualize Data with a Scatterplot Graph": "Visualize Data with a Scatterplot Graph", + "Visualize Data with a Heat Map": "Visualize Data with a Heat Map", + "Show National Contiguity with a Force Directed Graph": "Show National Contiguity with a Force Directed Graph", + "Map Data Across the Globe": "Map Data Across the Globe", + "Metric-Imperial Converter": "Metric-Imperial Converter", + "Issue Tracker": "Issue Tracker", + "Personal Library": "Personal Library", + "Stock Price Checker": "Stock Price Checker", + "Anonymous Message Board": "Anonymous Message Board", + "Build a Tribute Page": "Build a Tribute Page", + "Build a Survey Form": "Build a Survey Form", + "Build a Product Landing Page": "Build a Product Landing Page", + "Build a Technical Documentation Page": "Build a Technical Documentation Page", + "Palindrome Checker": "Palindrome Checker", + "Roman Numeral Converter": "Roman Numeral Converter", + "Caesars Cipher": "Caesars Cipher", + "Telephone Number Validator": "Telephone Number Validator", + "Cash Register": "Cash Register", + "Build a Drum Machine": "Build a Drum Machine", + "Visualize Data with a Choropleth Map": "Visualize Data with a Choropleth Map", + "Visualize Data with a Treemap Diagram": "Visualize Data with a Treemap Diagram", + "Exercise Tracker": "Exercise Tracker", + "Sudoku Solver": "Sudoku Solver", + "American British Translator": "American British Translator", + "Arithmetic Formatter": "Arithmetic Formatter", + "Time Calculator": "Time Calculator", + "Budget App": "Budget App", + "Polygon Area Calculator": "Polygon Area Calculator", + "Probability Calculator": "Probability Calculator", + "Mean-Variance-Standard Deviation Calculator": "Mean-Variance-Standard Deviation Calculator", + "Demographic Data Analyzer": "Demographic Data Analyzer", + "Medical Data Visualizer": "Medical Data Visualizer", + "Page View Time Series Visualizer": "Page View Time Series Visualizer", + "Sea Level Predictor": "Sea Level Predictor", + "Port Scanner": "Port Scanner", + "SHA-1 Password Cracker": "SHA-1 Password Cracker", + "Secure Real Time Multiplayer Game": "Secure Real Time Multiplayer Game", + "Rock Paper Scissors": "Rock Paper Scissors", + "Cat and Dog Image Classifier": "Cat and Dog Image Classifier", + "Book Recommendation Engine using KNN": "Book Recommendation Engine using KNN", + "Linear Regression Health Costs Calculator": "Linear Regression Health Costs Calculator", + "Neural Network SMS Text Classifier": "Neural Network SMS Text Classifier", + "Celestial Bodies Database": "Celestial Bodies Database", + "World Cup Database": "World Cup Database", + "Salon Appointment Scheduler": "Salon Appointment Scheduler", + "Periodic Table Database": "Periodic Table Database", + "Number Guessing Game": "Number Guessing Game", + "Build a freeCodeCamp Forum Homepage": "Build a freeCodeCamp Forum Homepage" + } + }, + "title": { + "responsive-web-design": "Legacy Responsive Web Design V8", + "responsive-web-design-cert": "Legacy Responsive Web Design V8 Certification", + "javascript-algorithms-and-data-structures": "Legacy JavaScript Algorithms and Data Structures V7", + "javascript-algorithms-and-data-structures-cert": "Legacy JavaScript Algorithms and Data Structures V7 Certification", + "javascript-algorithms-and-data-structures-v8": "Legacy JavaScript Algorithms and Data Structures V8", + "javascript-algorithms-and-data-structures-v8-cert": "Legacy JavaScript Algorithms and Data Structures V8 Certification", + "front-end-development-libraries": "Front-End Development Libraries V8", + "front-end-development-libraries-cert": "Front-End Development Libraries V8 Certification", + "data-visualization": "Data Visualization V8", + "data-visualization-cert": "Data Visualization V8 Certification", + "relational-database-v8": "Relational Database V8", + "relational-database-v8-cert": "Relational Database V8 Certification", + "back-end-development-and-apis": "Back-End Development and APIs V8", + "back-end-development-and-apis-cert": "Back-End Development and APIs V8 Certification", + "quality-assurance-v7": "Quality Assurance", + "quality-assurance-v7-cert": "Quality Assurance Certification", + "scientific-computing-with-python-v7": "Scientific Computing with Python", + "scientific-computing-with-python-v7-cert": "Scientific Computing with Python Certification", + "data-analysis-with-python-v7": "Data Analysis with Python", + "data-analysis-with-python-v7-cert": "Data Analysis with Python Certification", + "information-security-v7": "Information Security", + "information-security-v7-cert": "Information Security Certification", + "machine-learning-with-python-v7": "Machine Learning with Python", + "machine-learning-with-python-v7-cert": "Machine Learning with Python Certification", + "college-algebra-with-python-v8": "College Algebra with Python", + "college-algebra-with-python-v8-cert": "College Algebra with Python Certification", + "foundational-c-sharp-with-microsoft": "Foundational C# with Microsoft", + "foundational-c-sharp-with-microsoft-cert": "Foundational C# with Microsoft Certification", + "learn-python-for-beginners": "Learn Python for Beginners", + "introduction-to-algorithms-and-data-structures": "Introduction to Algorithms and Data Structures", + "learn-rag-mcp-fundamentals": "Learn RAG and MCP Fundamentals", + "introduction-to-precalculus": "Introduction to Precalculus", + "learn-oop-with-python": "Learn OOP with Python", + "a2-english-for-developers": "A2 English for Developers (Beta)", + "a2-english-for-developers-cert": "A2 English for Developers Certification (Beta)", + "b1-english-for-developers": "B1 English for Developers (Beta)", + "b1-english-for-developers-cert": "B1 English for Developers Certification (Beta)", + "responsive-web-design-v9": "Responsive Web Design", + "responsive-web-design-v9-cert": "Responsive Web Design Certification", + "javascript-v9": "JavaScript", + "javascript-v9-cert": "JavaScript Certification", + "front-end-development-libraries-v9": "Front-End Development Libraries", + "front-end-development-libraries-v9-cert": "Front-End Development Libraries Certification", + "python-v9": "Python", + "python-v9-cert": "Python Certification", + "relational-databases-v9": "Relational Database", + "relational-databases-v9-cert": "Relational Database Certification", + "back-end-development-and-apis-v9": "Back-End Development and APIs", + "back-end-development-and-apis-v9-cert": "Back-End Development and APIs Certification", + "full-stack-developer-v9": "Full-Stack Developer", + "full-stack-developer-v9-cert": "Full-Stack Developer Certification", + "a1-professional-spanish": "A1 Professional Spanish", + "a1-professional-spanish-cert": "A1 Professional Spanish Certification", + "a2-professional-spanish": "A2 Professional Spanish", + "a2-professional-spanish-cert": "A2 Professional Spanish Certification", + "a2-professional-chinese": "A2 Professional Chinese", + "a2-professional-chinese-cert": "A2 Professional Chinese Certification", + "a1-professional-chinese": "A1 Professional Chinese", + "a1-professional-chinese-cert": "A1 Professional Chinese Certification", + "legacy-front-end": "Legacy Front-End", + "legacy-front-end-cert": "Legacy Front-End Certification", + "legacy-back-end": "Legacy Back-End", + "legacy-back-end-cert": "Legacy Back-End Certification", + "legacy-data-visualization": "Legacy Data Visualization", + "legacy-data-visualization-cert": "Legacy Data Visualization Certification", + "information-security-and-quality-assurance": "Legacy Information Security and Quality Assurance", + "information-security-and-quality-assurance-cert": "Legacy Information Security and Quality Assurance Certification", + "full-stack": "Legacy Full-Stack", + "full-stack-cert": "Legacy Full-Stack Certification", + "introduction-to-bash": "Introduction to Bash", + "introduction-to-sql-and-postgresql": "Introduction to SQL and PostgreSQL", + "learn-bash-scripting": "Learn Bash Scripting", + "learn-sql-and-bash": "Learn SQL and Bash", + "introduction-to-nano": "Introduction to Nano", + "introduction-to-git-and-github": "Introduction to Git and GitHub", + "introduction-to-variables-and-strings-in-javascript": "Introduction to Variables and Strings in JavaScript", + "introduction-to-booleans-and-numbers-in-javascript": "Introduction to Booleans and Numbers in JavaScript", + "introduction-functions-in-javascript": "Introduction to Functions in JavaScript", + "introduction-to-arrays-in-javascript": "Introduction to Arrays in JavaScript", + "introduction-to-objects-in-javascript": "Introduction to Objects in JavaScript", + "introduction-to-loops-in-javascript": "Introduction to Loops in JavaScript", + "javascript-fundamentals-review": "JavaScript Fundamentals Review", + "introduction-to-higher-order-functions-and-callbacks-in-javascript": "Introduction to Higher-Order Functions and Callbacks in JavaScript", + "learn-dom-manipulation-and-events-with-javascript": "Learn DOM Manipulation and Events with JavaScript", + "introduction-to-javascript-and-accessibility": "Introduction to JavaScript and Accessibility", + "learn-javascript-debugging": "Learn JavaScript Debugging", + "learn-basic-regex-with-javascript": "Learn Basic Regex with JavaScript", + "introduction-to-dates-in-javascript": "Introduction to Dates in JavaScript", + "learn-audio-and-video-events-with-javascript": "Learn Audio and Video Events with JavaScript", + "introduction-to-maps-and-sets-in-javascript": "Introduction to Maps and Sets in JavaScript", + "learn-localstorage-and-crud-operations-with-javascript": "Learn localStorage and CRUD Operations with JavaScript", + "introduction-to-javascript-classes": "Introduction to JavaScript Classes", + "learn-recursion-with-javascript": "Learn Recursion with JavaScript", + "introduction-to-functional-programming-with-javascript": "Introduction to Functional Programming with JavaScript", + "introduction-to-asynchronous-javascript": "Introduction to Asynchronous JavaScript", + "learn-data-visualization-with-d3": "Learn Data Visualization with D3", + "introduction-to-python-basics": "Introduction to Python Basics", + "learn-python-loops-and-sequences": "Learn Python Loops and Sequences", + "learn-python-dictionaries-and-sets": "Learn Python Dictionaries and Sets", + "learn-error-handling-in-python": "Learn Error Handling in Python", + "learn-python-classes-and-objects": "Learn Python Classes and Objects", + "introduction-to-oop-in-python": "Introduction to OOP in Python", + "introduction-to-linear-data-structures-in-python": "Introduction to Linear Data Structures in Python", + "learn-algorithms-in-python": "Learn Algorithms in Python", + "learn-graphs-and-trees-in-python": "Learn Graphs and Trees in Python", + "learn-dynamic-programming-in-python": "Learn Dynamic Programming in Python" + } + }, + "certification-card": { + "title": "Claim Your Certification", + "intro": "Complete the following steps to claim and view your {{i18nCertText}}", + "complete-project": "Complete {{i18nCertText}} Projects", + "accept-honesty": "Accept our Academic Honesty Policy", + "set-name": "Set your name, and make it public", + "set-certs-public": "Set your certification settings to public", + "set-profile-public": "Set your profile settings to public", + "set-claim": "Claim and view your certification" + }, + "forum-help": { + "browser-info": "Your browser information:", + "user-agent": "User Agent is: {{userAgent}}", + "challenge": "Challenge Information:", + "whats-happening": "Tell us what's happening:", + "describe": "Describe your issue in detail here. Example: \nMy h1 element is missing an opening tag. Need help checking my code. \nOR \nMy for loop runs infinitely. How to prevent this?", + "camper-project": "Your project link(s)", + "camper-code": "Your code so far", + "warning": "WARNING", + "too-long-one": "The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.", + "too-long-two": "You will need to take an additional step here so the code you wrote presents in an easy to read format.", + "too-long-three": "Please copy/paste all the editor code showing in the challenge from where you just linked.", + "add-code-one": "Replace these two sentences with your copied code.", + "add-code-two": "Please leave the ``` line above and the ``` line below,", + "add-code-three": "because they allow your code to properly format in the post.", + "git-info": "GitHub Link: {{gitLink}}" + }, + "user-token": { + "title": "User Token", + "create": "Create a new token", + "create-p1": "It looks like you don't have a user token. Create one to save your progress on this section", + "create-p2": "Create a user token to save your progress on the curriculum sections that use a virtual machine.", + "delete": "Delete my user token", + "delete-title": "Delete My User Token", + "delete-p1": "Your user token is used to save your progress on curriculum sections that use a virtual machine. If you suspect it has been compromised, you can delete it without losing any progress. A new one will be created automatically the next time you open a project.", + "delete-p2": "If you suspect your token has been compromised, you can delete it to make it unusable. Progress on previously submitted lessons will not be lost.", + "delete-p3": "You will need to create a new token to save future progress on the curriculum sections that use a virtual machine.", + "no-thanks": "No thanks, I would like to keep my token", + "yes-please": "Yes please, I would like to delete my token" + }, + "exam-token": { + "exam-token": "Exam Token", + "note": "Your exam token is a secret key that allows you to access exams. Do not share this token with anyone.", + "invalidation-1": "It looks like you have a valid exam token. If you generate a new one, your existing token will be invalidated.", + "invalidation-2": "If you generate a new token, your existing token will be invalidated.", + "generate-exam-token": "Generate Exam Token", + "your-exam-token": "Your Exam Token is: {{token}}", + "error": "There was an error generating your token, please try again in a moment.", + "no-token": "It looks like you don't have a valid exam token.", + "copy": "Copy Exam Token", + "copied": "Token copied to clipboard", + "copy-error": "Error copying token to clipboard", + "token-usage": "Your Exam Environment authorization token is used to log you into the desktop application.", + "generated": "A new Exam Environment authorization token has been generated for your account.", + "non-staff-testing": "Only freeCodeCamp staff are allowed to generate exam tokens on non-production environments at this time." + }, + "shortcuts": { + "title": "Keyboard shortcuts", + "table-header-action": "Action", + "table-header-key": "Key(s)", + "navigation-mode": "Navigation Mode", + "execute-challenge": "Execute Challenge", + "focus-editor": "Focus Editor", + "focus-instructions-panel": "Focus Instructions Panel", + "navigate-previous": "Navigate To Previous Exercise", + "navigate-next": "Navigate To Next Exercise", + "play-video": "Play Video" + }, + "signout": { + "heading": "Sign out of your account", + "p1": "Warning: If you continue, your progress will no longer be saved.", + "p2": "This action will sign you out of your account on this device and browser session only. Please confirm if you would like to proceed.", + "certain": "Yes, sign out of my account", + "nevermind": "Nevermind, I don't want to sign out" + }, + "staging-warning": { + "heading": "Warning: This is an early access test deployment", + "p1": "We welcome you to try this platform in a test-only mode and get early access to upcoming features. Sometimes these changes are referred to as next, beta, staging, etc. interchangeably.", + "p2": "We thank you for reporting bugs that you encounter and help in making freeCodeCamp.org better.", + "p3": "Your progress MAY NOT be saved on your next visit, and any certifications claimed on this deployment are not valid.", + "certain": "Accept and Dismiss" + }, + "survey": { + "foundational-c-sharp": { + "title": "Foundational C# with Microsoft Survey", + "q1": { + "q": "Please describe your role:", + "o1": "Student developer", + "o2": "Beginner developer (less than 2 years experience)", + "o3": "Intermediate developer (between 2 and 5 years experience)", + "o4": "Experienced developer (more than 5 years experience)" + }, + "q2": { + "q": "Prior to this course, how experienced were you with .NET and C#?", + "o1": "Novice (no prior experience)", + "o2": "Beginner", + "o3": "Intermediate", + "o4": "Advanced", + "o5": "Expert" + } + }, + "misc": { + "take": "Take the survey", + "submit": "Submit the survey", + "exit": "Exit the survey", + "two-questions": "Congratulations on getting this far. Before you can start the exam, please answer these two short survey questions." + } + }, + "speaking-modal": { + "heading": "Speaking Practice", + "repeat-sentence": "Repeat aloud this sentence:", + "play": "Play", + "playing": "Playing...", + "record": "Record", + "stop": "Stop", + "incorrect-words": "Incorrect words: {{words}}.", + "misplaced-words": "Misplaced words: {{words}}.", + "correct-congratulations": "That's correct! Congratulations!", + "very-good": "Very good!", + "try-again": "Try again.", + "no-audio-available": "No audio file available.", + "no-speech-detected": "Recording stopped. No speech detected.", + "speech-recognition-not-supported": "Speech recognition not supported in this browser.", + "recording-speak-now": "Recording. Speak now.", + "recording-stopped-processing": "Recording stopped. Processing...", + "microphone-access-error": "Error: Could not access microphone.", + "speaking-button": "Practice speaking" + }, + "curriculum": { + "catalog": { + "title": "Explore our Catalog", + "levels": { + "beginner": "Beginner", + "intermediate": "Intermediate", + "advanced": "Advanced" + }, + "duration-singular": "{{duration}} hour", + "duration": "{{duration}} hours", + "no-results": "No courses found. Try adjusting your filters to see more results.", + "topic": { + "html": "HTML", + "css": "CSS", + "js": "JavaScript", + "react": "React", + "python": "Python", + "data-analysis": "Data Analysis", + "machine-learning": "Machine Learning", + "d3": "D3", + "api": "APIs", + "information-security": "Information Security", + "computer-fundamentals": "Computer Fundamentals", + "computer-science": "Computer Science", + "math": "Math", + "databases": "Databases", + "bash": "Bash", + "git": "Git", + "editors": "Editors", + "ai": "AI" + } + } + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/espanol/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/espanol/links.json new file mode 100644 index 0000000000000000000000000000000000000000..f838b0b8c559ce25612920c74ae2090fbd5cf724 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/espanol/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/espanol/news/acerca-de-freecodecamp-preguntas-frecuentes/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/espanol/news/preguntas-comunes-de-soporte-tecnico/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/espanol/news/politica-de-honestidad-academica/", + "coc-url": "https://www.freecodecamp.org/espanol/news/codigo-de-conducta/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/espanol/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/espanol/news/", + "podcast": "https://www.freecodecamp.org/espanol/news/el-podcast-de-freecodecamp-en-espanol/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/german/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/german/links.json new file mode 100644 index 0000000000000000000000000000000000000000..3a6286c313f246c58f70540417116f6ec5af330a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/german/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/german/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/german/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/italian/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/italian/links.json new file mode 100644 index 0000000000000000000000000000000000000000..25acf627f18203947de067923ebb863b7870abaf --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/italian/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/italian/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/italian/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/japanese/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/japanese/links.json new file mode 100644 index 0000000000000000000000000000000000000000..c2f876793be7d9c11bceb4a5a527091a90679d40 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/japanese/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/japanese/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/japanese/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/japanese/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/japanese/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/japanese/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/japanese/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://www.freecodecamp.org/japanese/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/korean/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/korean/links.json new file mode 100644 index 0000000000000000000000000000000000000000..5b273959775719c526cc187199ba3c0fec6088aa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/korean/links.json @@ -0,0 +1,43 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp", + "one-time-external-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#how-can-i-make-a-one-time-donation", + "mail-check-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp/#can-i-mail-a-physical-check" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/", + "forum": "https://forum.freecodecamp.org/", + "news": "https://www.freecodecamp.org/korean/news/search/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/portuguese/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/portuguese/links.json new file mode 100644 index 0000000000000000000000000000000000000000..e3c63456533bbb3bebc69ff0ac91c94ef9757f43 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/portuguese/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/portuguese/news/sobre-o-freecodecamp-perguntas-frequentes/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/portuguese/news/perguntas-frequentes-sobre-suporte-tecnico-faq-do-freecodecamp/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/portuguese/news/politica-de-honestidade-academica-do-freecodecamp/", + "coc-url": "https://www.freecodecamp.org/portuguese/news/codigo-de-conduta-do-freecodecamp/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/portuguese/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/portuguese/news/", + "podcast": "https://open.spotify.com/show/70m92At5oht4zY4f87lLEE?si=6tozUAOBQFSVyaqixy6aCg" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/swahili/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/swahili/links.json new file mode 100644 index 0000000000000000000000000000000000000000..1447e85c2dade52d13ce1b30a79e3a83bda67b8b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/swahili/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/news/about/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/news/support/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/news/academic-honesty-policy/", + "coc-url": "https://www.freecodecamp.org/news/code-of-conduct/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/", + "forum": "https://forum.freecodecamp.org/", + "news": "https://freecodecamp.org/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/ukrainian/links.json b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/ukrainian/links.json new file mode 100644 index 0000000000000000000000000000000000000000..04b6c7836355542614a165bae5d869fcda18f5f6 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/locales/ukrainian/links.json @@ -0,0 +1,41 @@ +{ + "help-translate-link-url": "https://contribute.freecodecamp.org/getting-started/#translations", + "top-contributors": "https://www.freecodecamp.org/news/freecodecamp-top-contributors/", + "footer": { + "about-url": "https://www.freecodecamp.org/ukrainian/news/chapy-freecodecamp/", + "shop-url": "https://shop.freecodecamp.org/", + "support-url": "https://www.freecodecamp.org/ukrainian/news/chapy-freecodecamp-populyarni-zapytannya-tekhnichniy-pidtrymtsi/", + "sponsors-url": "https://www.freecodecamp.org/news/sponsors/", + "honesty-url": "https://www.freecodecamp.org/ukrainian/news/polityka-akademichnoyi-dobrochesnosti-freecodecamp/", + "coc-url": "https://www.freecodecamp.org/ukrainian/news/kodeks-povedinky-freecodecamp/", + "privacy-url": "https://www.freecodecamp.org/news/privacy-policy/", + "tos-url": "https://www.freecodecamp.org/news/terms-of-service/", + "copyright-url": "https://www.freecodecamp.org/news/copyright-policy/" + }, + "donate": { + "other-ways-url": "https://www.freecodecamp.org/news/how-to-donate-to-free-code-camp", + "download-irs-url": "https://s3.amazonaws.com/freecodecamp/Free+Code+Camp+Inc+IRS+Determination+Letter.pdf", + "download-990-url": "https://freecodecamp.s3.amazonaws.com/freeCodeCamp+2019+f990.pdf", + "one-time-url": "https://paypal.me/freecodecamp" + }, + "nav": { + "contribute": "https://contribute.freecodecamp.org/#/i18n/ukrainian/index", + "forum": "https://forum.freecodecamp.org/", + "news": "https://www.freecodecamp.org/ukrainian/news/", + "podcast": "https://freecodecamp.libsyn.com/" + }, + "help": { + "HTML-CSS": "curriculum-help", + "JavaScript": "curriculum-help", + "Python": "curriculum-help", + "Backend Development": "curriculum-help", + "C-Sharp": "curriculum-help", + "English": "curriculum-help", + "Spanish Curriculum": "curriculum-help", + "Chinese Curriculum": "curriculum-help", + "Odin": "curriculum-help", + "Euler": "curriculum-help", + "Rosetta": "curriculum-help", + "General": "curriculum-help" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/i18n/schema-validation.ts b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/schema-validation.ts new file mode 100644 index 0000000000000000000000000000000000000000..98ed44ceb119b58ca1838a5504c9f1240213ca54 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/i18n/schema-validation.ts @@ -0,0 +1,246 @@ +import path from 'path'; +import { readFile } from 'fs/promises'; +import { availableLangs } from '@freecodecamp/shared/config/i18n'; +import introSchema from './locales/english/intro.json'; +import linksSchema from './locales/english/links.json'; +import metaTagsSchema from './locales/english/meta-tags.json'; +import motivationSchema from './locales/english/motivation.json'; +import translationsSchema from './locales/english/translations.json'; + +type MotivationalQuotes = { quote: string; author: string }[]; + +/** + * Flattens a nested object structure into a single + * object with property chains as keys. + * @param {Object} obj Object to flatten + * @param {String} namespace Used for property chaining + */ +const flattenAnObject = (obj: Record, namespace = '') => { + const flattened: Record = {}; + Object.keys(obj).forEach(key => { + const value = obj[key]; + const field = namespace ? `${namespace}.${key}` : key; + if (Array.isArray(value)) { + flattened[field] = value; + } else if (typeof value === 'object') { + Object.assign( + flattened, + flattenAnObject(value as Record, field) + ); + } else { + flattened[field] = value; + } + }); + return flattened; +}; + +/** + * Checks if a translation object is missing keys + * that are present in the schema. + * @param {String[]} file Array of translation object's keys + * @param {String[]} schema Array of matching schema's keys + * @param {String} path string path to file + */ +const findMissingKeys = (file: string[], schema: string[], path: string) => { + const missingKeys = []; + for (const key of schema) { + if (!file.includes(key)) { + missingKeys.push(key); + } + } + if (missingKeys.length) { + console.warn( + `${path} is missing these required keys: ${missingKeys.join(', ')}` + ); + } +}; + +/** + * Checks if a translation object has extra + * keys which are NOT present in the schema. + * @param {String[]} file Array of translation object's keys + * @param {String[]} schema Array of matching schema's keys + * @param {String} path string path to file + */ +const findExtraneousKeys = (file: string[], schema: string[], path: string) => { + const extraKeys = []; + for (const key of file) { + if (!schema.includes(key)) { + extraKeys.push(key); + } + } + if (extraKeys.length) { + console.warn( + `${path} has these keys that are not in the schema: ${extraKeys.join( + ', ' + )}` + ); + } +}; + +/** + * Validates that all values in the object are non-empty. Includes + * validation of nested objects. + * @param {Object} obj The object to check the values of + * @param {String} namespace String for tracking nested properties + */ +const noEmptyObjectValues = ( + obj: Record, + namespace = '' +): string[] => { + const emptyKeys = []; + for (const key of Object.keys(obj)) { + const value = obj[key]; + const field = namespace ? `${namespace}.${key}` : key; + if (Array.isArray(value)) { + if (!value.length) { + emptyKeys.push(field); + } + } else if (typeof value === 'object') { + emptyKeys.push( + noEmptyObjectValues(value as Record, field) + ); + } else if (!value) { + emptyKeys.push(field); + } + } + return emptyKeys.flat(); +}; + +/** + * Grab the schema keys once, to avoid overhead of + * fetching within iterative function. + */ +const translationSchemaKeys = Object.keys(flattenAnObject(translationsSchema)); +const motivationSchemaKeys = Object.keys(flattenAnObject(motivationSchema)); +const introSchemaKeys = Object.keys(flattenAnObject(introSchema)); +const metaTagsSchemaKeys = Object.keys(flattenAnObject(metaTagsSchema)); +const linksSchemaKeys = Object.keys(flattenAnObject(linksSchema)); + +/** + * Function that checks the translations.json file + * for each available client language. + * @param {String[]} languages List of languages to test + */ +const translationSchemaValidation = (languages: string[]) => { + languages.forEach(language => { + void readJsonFile(language, 'translations').then(fileJson => { + schemaValidation( + language, + 'translations', + fileJson, + translationSchemaKeys + ); + }); + }); +}; + +/** + * Function that checks the motivation.json file + * for each available client language. + * @param {String[]} languages List of languages to test + */ +const motivationSchemaValidation = (languages: string[]) => { + languages.forEach(language => { + void readJsonFile(language, 'motivation').then(fileJson => { + schemaValidation(language, 'motivation', fileJson, motivationSchemaKeys); + }); + }); +}; + +/** + * Function that checks the intro.json file + * for each available client language. + * @param {String[]} languages List of languages to test + */ +const introSchemaValidation = (languages: string[]) => { + languages.forEach(language => { + void readJsonFile(language, 'intro').then(fileJson => { + schemaValidation(language, 'intro', fileJson, introSchemaKeys); + }); + }); +}; + +/** + * Function that checks the meta-tags.json file + * for each available client language. + * @param {String[]} languages List of languages to test + */ +const metaTagsSchemaValidation = (languages: string[]) => { + languages.forEach(language => { + void readJsonFile(language, 'meta-tags').then(fileJson => { + schemaValidation(language, 'meta-tags', fileJson, metaTagsSchemaKeys); + }); + }); +}; + +/** + * Function that checks the links.json file + * for each available client language. + * @param {String[]} languages List of languages to test + */ +const linksSchemaValidation = (languages: string[]) => { + languages.forEach(language => { + void readJsonFile(language, 'links').then(fileJson => { + schemaValidation(language, 'links', fileJson, linksSchemaKeys); + }); + }); +}; + +/** + * Common Function that checks the json file + * @param {String} language the language to test + * @param {String} fileName the fileName of json file to test + * @param {Object} fileJson the fileJson got by readJsonFile + * @param {String[]} schemaKeys Array of matching schema's keys + */ +const schemaValidation = ( + language: string, + fileName: string, + fileJson: Record, + schemaKeys: string[] +) => { + const fileKeys = Object.keys(flattenAnObject(fileJson)); + findMissingKeys(fileKeys, schemaKeys, `${language}/${fileName}.json`); + findExtraneousKeys(fileKeys, schemaKeys, `${language}/${fileName}.json`); + const emptyKeys = noEmptyObjectValues(fileJson); + if (emptyKeys.length) { + console.warn( + `${language}/${fileName}.json has these empty keys: ${emptyKeys.join( + ', ' + )}` + ); + } + // Special line to assert that objects in motivational quote are correct + if ( + fileName === 'motivation' && + !(fileJson.motivationalQuotes as MotivationalQuotes).every( + object => + Object.prototype.hasOwnProperty.call(object, 'quote') && + Object.prototype.hasOwnProperty.call(object, 'author') + ) + ) { + console.warn(`${language}/${fileName}.json has malformed quote objects.`); + } + console.info(`${language} ${fileName}.json validation complete`); +}; + +const readJsonFile = async (language: string, fileName: string) => { + const filePath = path.join( + __dirname, + `/locales/${language}/${fileName}.json` + ); + const file = await readFile(filePath, 'utf8'); + const fileJson = JSON.parse(file) as Record; + return fileJson; +}; + +const translatedLangs = availableLangs.client.filter( + x => String(x) !== 'english' +); + +translationSchemaValidation(translatedLangs); +motivationSchemaValidation(translatedLangs); +introSchemaValidation(translatedLangs); +metaTagsSchemaValidation(translatedLangs); +linksSchemaValidation(translatedLangs); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/package.json b/github_code/freeCodeCamp__freeCodeCamp/client/package.json new file mode 100644 index 0000000000000000000000000000000000000000..46459a5ad20a2f1589955a92871d96f03a1d73b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/package.json @@ -0,0 +1,189 @@ +{ + "name": "@freecodecamp/client", + "version": "0.0.1", + "description": "The freeCodeCamp.org open-source codebase and curriculum", + "license": "BSD-3-Clause", + "private": true, + "engines": { + "node": ">=24", + "pnpm": ">=10" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/freeCodeCamp/freeCodeCamp.git" + }, + "bugs": { + "url": "https://github.com/freeCodeCamp/freeCodeCamp/issues" + }, + "homepage": "https://github.com/freeCodeCamp/freeCodeCamp#readme", + "author": "freeCodeCamp ", + "main": "index.js", + "scripts": { + "build": "NODE_OPTIONS=\"--max-old-space-size=7168 --no-deprecation\" gatsby build --prefix-paths", + "clean": "gatsby clean", + "copy:scripts": "tsx ./tools/copy-browser-scripts.ts", + "create:i18n": "tsx ./tools/create-i18n.ts", + "create:env": "DEBUG=fcc:* tsx ./tools/create-env.ts", + "create:external-curriculum": "tsx ./tools/external-curriculum/build", + "create:trending": "tsx ./tools/download-trending.ts", + "create:search-placeholder": "tsx ./tools/generate-search-placeholder", + "develop": "NODE_OPTIONS=\"--max-old-space-size=7168 --no-deprecation\" gatsby develop --inspect=9230", + "lint": "eslint --max-warnings 0", + "setup": "pnpm clean && pnpm create:env && pnpm create:i18n && pnpm create:trending && pnpm create:search-placeholder && pnpm create:external-curriculum && pnpm copy:scripts", + "serve": "gatsby serve -p 8000", + "serve-ci": "serve -l 8000 -c serve.json public", + "prestand-alone": "pnpm run prebuild", + "stand-alone": "gatsby develop", + "test": "vitest run", + "test:watch": "vitest", + "test:ui": "vitest --ui", + "type-check": "tsc --noEmit" + }, + "dependencies": { + "@babel/plugin-proposal-export-default-from": "7.23.3", + "@babel/plugin-proposal-function-bind": "7.23.3", + "@babel/plugin-transform-runtime": "^7.19.6", + "@babel/preset-env": "7.23.7", + "@babel/preset-react": "7.23.3", + "@babel/preset-typescript": "7.23.3", + "@codesandbox/sandpack-react": "2.20.0", + "@codesandbox/sandpack-themes": "2.0.21", + "@fortawesome/fontawesome-svg-core": "7.2.0", + "@fortawesome/free-brands-svg-icons": "7.2.0", + "@fortawesome/free-solid-svg-icons": "7.2.0", + "@fortawesome/react-fontawesome": "3.3.1", + "@freecodecamp/challenge-builder": "workspace:*", + "@freecodecamp/ui": "6.0.1", + "@gatsbyjs/reach-router": "1.3.9", + "@growthbook/growthbook-react": "1.6.5", + "@loadable/component": "5.16.7", + "@paypal/react-paypal-js": "10.3.0", + "@redux-devtools/extension": "3.3.0", + "@redux-saga/core": "^1.4.2", + "@reduxjs/toolkit": "2.11.2", + "@stripe/react-stripe-js": "1.16.5", + "@stripe/stripe-js": "1.54.2", + "@types/react-speech-recognition": "3.9.6", + "@xterm/addon-fit": "0.11.0", + "@xterm/xterm": "6.0.0", + "algoliasearch": "4.27.0", + "assert": "2.0.0", + "babel-plugin-preval": "5.1.0", + "babel-plugin-prismjs": "2.1.0", + "bezier-easing": "2.1.0", + "browser-cookies": "1.2.0", + "canvas-confetti": "^1.6.0", + "crypto-browserify": "3.12.1", + "date-fns": "4.1.0", + "date-fns-tz": "3.2.0", + "eslint-config-react-app": "^7.0.1", + "final-form": "4.20.10", + "gatsby": "5.16.1", + "gatsby-cli": "5.16.0", + "gatsby-plugin-postcss": "6.16.0", + "gatsby-plugin-react-helmet": "6.16.0", + "gatsby-plugin-remove-serviceworker": "1.0.0", + "gatsby-source-filesystem": "5.16.0", + "gatsby-transformer-remark": "6.16.0", + "i18next": "25.10.10", + "instantsearch.js": "4.95.0", + "lodash": "4.18.1", + "lodash-es": "4.18.1", + "micromark": "4.0.2", + "monaco-editor": "0.55.1", + "nanoid": "3.3.12", + "normalize-url": "6.1.0", + "path-browserify": "1.0.1", + "pinyin-tone": "2.4.0", + "postcss": "8.5.13", + "prismjs": "1.30.0", + "process": "0.11.10", + "prop-types": "15.8.1", + "qrcode.react": "^3.1.0", + "query-string": "7.1.3", + "react": "18.3.1", + "react-calendar-heatmap": "1.10.0", + "react-dom": "18.3.1", + "react-final-form": "6.5.9", + "react-gtm-module": "2.0.11", + "react-helmet": "6.1.0", + "react-hotkeys": "2.0.0", + "react-i18next": "15.7.4", + "react-instantsearch": "7.31.0", + "react-instantsearch-core": "7.31.0", + "react-monaco-editor": "0.59.0", + "react-redux": "8.1.3", + "react-reflex": "4.2.7", + "react-responsive": "9.0.2", + "react-scroll": "1.9.3", + "react-speech-recognition": "4.0.1", + "react-spinkit": "3.0.0", + "react-tooltip": "4.5.1", + "react-transition-group": "4.4.5", + "react-youtube": "10.1.0", + "redux": "4.2.1", + "redux-actions": "2.6.5", + "redux-observable": "1.2.0", + "redux-saga": "1.4.2", + "reselect": "4.1.8", + "rxjs": "6.6.7", + "sanitize-html": "2.17.4", + "store": "2.0.12", + "stream-browserify": "3.0.0", + "tone": "15.1.22", + "typescript": "5.9.3", + "util": "0.12.5", + "uuid": "8.3.2", + "validator": "13.15.35" + }, + "devDependencies": { + "@babel/plugin-syntax-dynamic-import": "7.8.3", + "@freecodecamp/browser-scripts": "workspace:*", + "@freecodecamp/curriculum": "workspace:*", + "@freecodecamp/eslint-config": "workspace:*", + "@freecodecamp/shared": "workspace:*", + "@testing-library/jest-dom": "^6.8.0", + "@testing-library/react": "14.3.1", + "@testing-library/user-event": "14.6.1", + "@total-typescript/ts-reset": "^0.5.0", + "@types/canvas-confetti": "^1.6.0", + "@types/gatsbyjs__reach-router": "1.3.0", + "@types/js-yaml": "4.0.9", + "@types/loadable__component": "5.13.10", + "@types/lodash-es": "^4.17.6", + "@types/prismjs": "^1.26.0", + "@types/react": "18.3.28", + "@types/react-dom": "18.3.7", + "@types/react-gtm-module": "2.0.4", + "@types/react-helmet": "6.1.11", + "@types/react-redux": "7.1.34", + "@types/react-scroll": "1.8.10", + "@types/react-spinkit": "3.0.10", + "@types/react-test-renderer": "16.9.12", + "@types/react-transition-group": "4.4.12", + "@types/redux-actions": "2.6.5", + "@types/sanitize-html": "^2.8.0", + "@types/store": "^2.0.2", + "@types/validator": "^13.7.12", + "@vitest/ui": "^4.0.15", + "autoprefixer": "10.4.27", + "babel-plugin-macros": "3.1.0", + "core-js": "3.49.0", + "dotenv": "16.6.1", + "eslint": "^9.39.1", + "eslint-plugin-flowtype": "^8.0.3", + "gatsby-plugin-pnpm-gatsby-5": "1.2.11", + "gatsby-plugin-schema-snapshot": "4.16.0", + "gatsby-plugin-webpack-bundle-analyser-v2": "1.1.32", + "i18next-fs-backend": "2.6.5", + "joi": "18.1.2", + "js-yaml": "4.1.0", + "monaco-editor-webpack-plugin": "7.1.1", + "react-test-renderer": "18.3.1", + "readdirp": "3.6.0", + "redux-saga-test-plan": "4.0.6", + "serve": "13.0.4", + "url": "0.11.4", + "vitest": "^4.0.15" + } +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/postcss.config.js b/github_code/freeCodeCamp__freeCodeCamp/client/postcss.config.js new file mode 100644 index 0000000000000000000000000000000000000000..119e6185905998fe5893a1a8b2fe8e142e52fb2f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/postcss.config.js @@ -0,0 +1,7 @@ +module.exports = { + plugins: { + autoprefixer: { + overrideBrowserslist: ['last 2 versions'] + } + } +}; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/schema.gql b/github_code/freeCodeCamp__freeCodeCamp/client/schema.gql new file mode 100644 index 0000000000000000000000000000000000000000..7e76feade0aba8b123a02bedbab9fba323efdc1e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/schema.gql @@ -0,0 +1,577 @@ +### Type definitions saved at 2026-03-10T08:56:46.271Z ### + +enum RemoteFileFit { + COVER + FILL + OUTSIDE + CONTAIN +} + +enum RemoteFileFormat { + AUTO + JPG + PNG + WEBP + AVIF +} + +enum RemoteFileLayout { + FIXED + FULL_WIDTH + CONSTRAINED +} + +enum RemoteFilePlaceholder { + DOMINANT_COLOR + BLURRED + TRACED_SVG + NONE +} + +enum RemoteFileCropFocus { + CENTER + TOP + RIGHT + BOTTOM + LEFT + ENTROPY + EDGES + FACES +} + +type RemoteFileResize { + width: Int + height: Int + src: String +} + +""" +Remote Interface +""" +interface RemoteFile { + id: ID! + mimeType: String! + filename: String! + filesize: Int + width: Int + height: Int + publicUrl: String! + resize( + width: Int + height: Int + aspectRatio: Float + fit: RemoteFileFit = COVER + + """ + The image formats to generate. Valid values are AUTO (meaning the same + format as the source image), JPG, PNG, WEBP and AVIF. + The default value is [AUTO, WEBP, AVIF], and you should rarely need to + change this. Take care if you specify JPG or PNG when you do + not know the formats of the source images, as this could lead to unwanted + results such as converting JPEGs to PNGs. Specifying + both PNG and JPG is not supported and will be ignored. + """ + format: RemoteFileFormat = AUTO + cropFocus: [RemoteFileCropFocus] + quality: Int = 75 + ): RemoteFileResize + + """ + Data used in the component. See https://gatsby.dev/img for more info. + """ + gatsbyImage( + """ + The layout for the image. + FIXED: A static image sized, that does not resize according to the screen width + FULL_WIDTH: The image resizes to fit its container. Pass a "sizes" option if + it isn't going to be the full width of the screen. + CONSTRAINED: Resizes to fit its container, up to a maximum width, at which point it will remain fixed in size. + """ + layout: RemoteFileLayout = CONSTRAINED + + """ + The display width of the generated image for layout = FIXED, and the display + width of the largest image for layout = CONSTRAINED. + The actual largest image resolution will be this value multiplied by the largest value in outputPixelDensities + Ignored if layout = FLUID. + """ + width: Int + + """ + If set, the height of the generated image. If omitted, it is calculated from + the supplied width, matching the aspect ratio of the source image. + """ + height: Int + + """ + Format of generated placeholder image, displayed while the main image loads. + BLURRED: a blurred, low resolution image, encoded as a base64 data URI + DOMINANT_COLOR: a solid color, calculated from the dominant color of the image (default). + TRACED_SVG: deprecated. Will use DOMINANT_COLOR. + NONE: no placeholder. Set the argument "backgroundColor" to use a fixed background color. + """ + placeholder: RemoteFilePlaceholder = DOMINANT_COLOR + + """ + If set along with width or height, this will set the value of the other + dimension to match the provided aspect ratio, cropping the image if needed. + If neither width or height is provided, height will be set based on the intrinsic width of the source image. + """ + aspectRatio: Float + + """ + The image formats to generate. Valid values are AUTO (meaning the same + format as the source image), JPG, PNG, WEBP and AVIF. + The default value is [AUTO, WEBP, AVIF], and you should rarely need to + change this. Take care if you specify JPG or PNG when you do + not know the formats of the source images, as this could lead to unwanted + results such as converting JPEGs to PNGs. Specifying + both PNG and JPG is not supported and will be ignored. + """ + formats: [RemoteFileFormat!] = [AUTO, WEBP, AVIF] + + """ + A list of image pixel densities to generate for FIXED and CONSTRAINED + images. You should rarely need to change this. It will never generate images + larger than the source, and will always include a 1x image. + Default is [ 1, 2 ] for fixed images, meaning 1x, 2x, and [0.25, 0.5, 1, 2] + for fluid. In this case, an image with a fluid layout and width = 400 would + generate images at 100, 200, 400 and 800px wide. + """ + outputPixelDensities: [Float] = [0.25, 0.5, 1, 2] + + """ + Specifies the image widths to generate. You should rarely need to change + this. For FIXED and CONSTRAINED images it is better to allow these to be + determined automatically, + based on the image size. For FULL_WIDTH images this can be used to override + the default, which is [750, 1080, 1366, 1920]. + It will never generate any images larger than the source. + """ + breakpoints: [Int] = [750, 1080, 1366, 1920] + + """ + The "sizes" property, passed to the img tag. This describes the display size of the image. + This does not affect the generated images, but is used by the browser to + decide which images to download. You can leave this blank for fixed images, + or if the responsive image + container will be the full width of the screen. In these cases we will generate an appropriate value. + """ + sizes: String + + """ + Background color applied to the wrapper, or when "letterboxing" an image to another aspect ratio. + """ + backgroundColor: String + fit: RemoteFileFit = COVER + cropFocus: [RemoteFileCropFocus] + quality: Int = 75 + ): GatsbyImageData +} + +type File implements Node @dontInfer { + sourceInstanceName: String! + absolutePath: String! + relativePath: String! + extension: String! + size: Int! + prettySize: String! + modifiedTime: Date! @dateformat + accessTime: Date! @dateformat + changeTime: Date! @dateformat + birthTime: Date! @dateformat + root: String! + dir: String! + base: String! + ext: String! + name: String! + relativeDirectory: String! + dev: Int! + mode: Int! + nlink: Int! + uid: Int! + gid: Int! + rdev: Int! + ino: Float! + atimeMs: Float! + mtimeMs: Float! + ctimeMs: Float! + atime: Date! @dateformat + mtime: Date! @dateformat + ctime: Date! @dateformat + birthtime: Date @deprecated(reason: "Use `birthTime` instead") + birthtimeMs: Float @deprecated(reason: "Use `birthTime` instead") +} + +type Directory implements Node @dontInfer { + sourceInstanceName: String! + absolutePath: String! + relativePath: String! + extension: String! + size: Int! + prettySize: String! + modifiedTime: Date! @dateformat + accessTime: Date! @dateformat + changeTime: Date! @dateformat + birthTime: Date! @dateformat + root: String! + dir: String! + base: String! + ext: String! + name: String! + relativeDirectory: String! + dev: Int! + mode: Int! + nlink: Int! + uid: Int! + gid: Int! + rdev: Int! + ino: Float! + atimeMs: Float! + mtimeMs: Float! + ctimeMs: Float! + atime: Date! @dateformat + mtime: Date! @dateformat + ctime: Date! @dateformat + birthtime: Date @deprecated(reason: "Use `birthTime` instead") + birthtimeMs: Float @deprecated(reason: "Use `birthTime` instead") +} + +type Site implements Node @derivedTypes @dontInfer { + buildTime: Date @dateformat + siteMetadata: SiteSiteMetadata + port: Int + host: String + flags: SiteFlags + trailingSlash: String + pathPrefix: String + polyfill: Boolean + jsxRuntime: String + graphqlTypegen: Boolean +} + +type SiteSiteMetadata { + title: String + description: String + siteUrl: String +} + +type SiteFlags { + DEV_SSR: Boolean +} + +type SiteFunction implements Node @dontInfer { + functionRoute: String! + pluginName: String! + originalAbsoluteFilePath: String! + originalRelativeFilePath: String! + relativeCompiledFilePath: String! + absoluteCompiledFilePath: String! + matchPath: String +} + +type SitePage implements Node @dontInfer { + path: String! + component: String! + internalComponentName: String! + componentChunkName: String! + matchPath: String + pageContext: JSON @proxy(from: "context", fromNode: false) + pluginCreator: SitePlugin @link(by: "id", from: "pluginCreatorId") +} + +type SitePlugin implements Node @dontInfer { + resolve: String + name: String + version: String + nodeAPIs: [String] + browserAPIs: [String] + ssrAPIs: [String] + pluginFilepath: String + pluginOptions: JSON + packageJson: JSON +} + +type SiteBuildMetadata implements Node @dontInfer { + buildTime: Date @dateformat +} + +type ChallengeNodeChallengeHooks { + afterEach: String + beforeAll: String + beforeEach: String + afterAll: String +} + +type SuperBlockStructure implements Node @derivedTypes @dontInfer { + chapters: [SuperBlockStructureChapters] + superBlock: String + blocks: [String] +} + +type SuperBlockStructureChapters @derivedTypes { + dashedName: String + modules: [SuperBlockStructureChaptersModules] + chapterType: String + comingSoon: Boolean +} + +type SuperBlockStructureChaptersModules { + dashedName: String + blocks: [String] + moduleType: String + comingSoon: Boolean +} + +type ChallengeNode implements Node @derivedTypes @dontInfer { + sourceInstanceName: String + challenge: ChallengeNodeChallenge +} + +type ChallengeNodeChallenge @derivedTypes { + id: String + title: String + challengeType: Int + dashedName: String + demoType: String + challengeFiles: [ChallengeNodeChallengeChallengeFiles] + solutions: [[ChallengeNodeChallengeSolutions]] + assignments: [String] + tests: [ChallengeNodeChallengeTests] + description: String + translationPending: Boolean + sourceLocation: String + block: String + blockLabel: String + blockLayout: String + hasEditableBoundaries: Boolean + order: Int + instructions: String + questions: [ChallengeNodeChallengeQuestions] + superBlock: String + superOrder: Int + challengeOrder: Int + isLastChallengeInBlock: Boolean + required: [ChallengeNodeChallengeRequired] + helpCategory: String + usesMultifileEditor: Boolean + disableLoopProtectTests: Boolean + disableLoopProtectPreview: Boolean + certification: String + fields: ChallengeNodeChallengeFields + quizzes: [ChallengeNodeChallengeQuizzes] + chapter: String + module: String + hooks: ChallengeNodeChallengeHooks + nodules: [ChallengeNodeChallengeNodules] + forumTopicId: Int + videoId: String + bilibiliIds: ChallengeNodeChallengeBilibiliIds + saveSubmissionToDB: Boolean + lang: String + scene: ChallengeNodeChallengeScene + explanation: String + fillInTheBlank: ChallengeNodeChallengeFillInTheBlank + inputType: String + videoUrl: String + url: String + template: String + transcript: String + isExam: Boolean + videoLocaleIds: ChallengeNodeChallengeVideoLocaleIds + notes: String + prerequisites: [ChallengeNodeChallengePrerequisites] + msTrophyId: String +} + +type ChallengeNodeChallengeChallengeFiles { + head: String + tail: String + id: String + editableRegionBoundaries: [Int] + history: [String] + name: String + ext: String + path: String + fileKey: String + contents: String + seed: String +} + +type ChallengeNodeChallengeSolutions { + head: String + tail: String + id: String + history: [String] + name: String + ext: String + path: String + fileKey: String + contents: String + seed: String +} + +type ChallengeNodeChallengeTests { + text: String + testString: String +} + +type ChallengeNodeChallengeQuestions @derivedTypes { + text: String + answers: [ChallengeNodeChallengeQuestionsAnswers] + solution: Int +} + +type ChallengeNodeChallengeQuestionsAnswers { + answer: String + feedback: String + audioId: String +} + +type ChallengeNodeChallengeRequired { + src: String + link: String + raw: Boolean +} + +type ChallengeNodeChallengeFields { + slug: String + blockHashSlug: String +} + +type ChallengeNodeChallengeQuizzes @derivedTypes { + questions: [ChallengeNodeChallengeQuizzesQuestions] +} + +type ChallengeNodeChallengeQuizzesQuestions @derivedTypes { + text: String + distractors: [String] + answer: String + audioData: ChallengeNodeChallengeQuizzesQuestionsAudioData +} + +type ChallengeNodeChallengeQuizzesQuestionsAudioData @derivedTypes { + audio: ChallengeNodeChallengeQuizzesQuestionsAudioDataAudio + transcript: [ChallengeNodeChallengeQuizzesQuestionsAudioDataTranscript] +} + +type ChallengeNodeChallengeQuizzesQuestionsAudioDataAudio { + filename: String + startTimestamp: Float + finishTimestamp: Float +} + +type ChallengeNodeChallengeQuizzesQuestionsAudioDataTranscript { + character: String + text: String +} + +type ChallengeNodeChallengeNodules @derivedTypes { + type: String + contents: String + files: [ChallengeNodeChallengeNodulesFiles] +} + +type ChallengeNodeChallengeNodulesFiles { + contents: String + ext: String + name: String + contentsHtml: String +} + +type ChallengeNodeChallengeBilibiliIds { + aid: Int + bvid: String + cid: Int +} + +type ChallengeNodeChallengeScene @derivedTypes { + setup: ChallengeNodeChallengeSceneSetup + commands: [ChallengeNodeChallengeSceneCommands] +} + +type ChallengeNodeChallengeSceneSetup @derivedTypes { + background: String + characters: [ChallengeNodeChallengeSceneSetupCharacters] + audio: ChallengeNodeChallengeSceneSetupAudio + alwaysShowDialogue: Boolean +} + +type ChallengeNodeChallengeSceneSetupCharacters @derivedTypes { + character: String + position: ChallengeNodeChallengeSceneSetupCharactersPosition + opacity: Int +} + +type ChallengeNodeChallengeSceneSetupCharactersPosition { + x: Int + y: Int + z: Float +} + +type ChallengeNodeChallengeSceneSetupAudio { + filename: String + startTime: Float + startTimestamp: Float + finishTimestamp: Float +} + +type ChallengeNodeChallengeSceneCommands @derivedTypes { + character: String + opacity: Int + startTime: Float + finishTime: Float + dialogue: ChallengeNodeChallengeSceneCommandsDialogue + position: ChallengeNodeChallengeSceneCommandsPosition + background: String +} + +type ChallengeNodeChallengeSceneCommandsDialogue { + text: String + align: String +} + +type ChallengeNodeChallengeSceneCommandsPosition { + x: Int + y: Int + z: Float +} + +type ChallengeNodeChallengeFillInTheBlank @derivedTypes { + sentence: String + blanks: [ChallengeNodeChallengeFillInTheBlankBlanks] +} + +type ChallengeNodeChallengeFillInTheBlankBlanks { + answer: String + feedback: String +} + +type ChallengeNodeChallengeVideoLocaleIds { + espanol: String + italian: String + portuguese: String +} + +type ChallengeNodeChallengePrerequisites { + id: String + title: String +} + +type CertificateNode implements Node @derivedTypes @dontInfer { + sourceInstanceName: String + challenge: CertificateNodeChallenge +} + +type CertificateNodeChallenge @derivedTypes { + id: String + title: String + certification: String + challengeType: Int + tests: [CertificateNodeChallengeTests] +} + +type CertificateNodeChallengeTests { + id: String + title: String +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/__tests__/integration/handled-error.test.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/__tests__/integration/handled-error.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ba72b81a37cff3c168ba23f4b8e505303dbb4f4 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/__tests__/integration/handled-error.test.ts @@ -0,0 +1,42 @@ +import { describe, it, expect } from 'vitest'; +import { + wrapHandledError, + unwrapHandledError +} from '../../utils/handled-error'; + +describe('handled-error integration', () => { + const handledA = { + type: 'info', + message: 'something helpful', + redirectTo: '/a-path-we-choose' + }; + const handledB = { + type: 'danger', + message: 'Oh noes!', + redirectTo: '/whoops' + }; + const handledC = { + type: 'success', + message: 'great news!', + redirectTo: '/awesome' + }; + const handledD = {}; + + it('can wrap and unwrap handled errors', () => { + expect.assertions(4); + const wrappedA = wrapHandledError(new Error(), handledA); + const wrappedB = wrapHandledError(new Error(), handledB); + const wrappedC = wrapHandledError(new Error(), handledC); + const wrappedD = wrapHandledError(new Error(), handledD); + + const unwrappedA = unwrapHandledError(wrappedA); + const unwrappedB = unwrapHandledError(wrappedB); + const unwrappedC = unwrapHandledError(wrappedC); + const unwrappedD = unwrapHandledError(wrappedD); + + expect(unwrappedA).toEqual(handledA); + expect(unwrappedB).toEqual(handledB); + expect(unwrappedC).toEqual(handledC); + expect(unwrappedD).toEqual(handledD); + }); +}); diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/__mocks__/index.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/__mocks__/index.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c6aee6202e44b77b82a26b2e924d57e1471ad807 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/__mocks__/index.tsx @@ -0,0 +1,7 @@ +const analytics = { + event: function (): void { + // comment necessary for linting. + } +}; + +export default analytics; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/call-ga.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/call-ga.ts new file mode 100644 index 0000000000000000000000000000000000000000..06d2d1bcf9921fc6ff30995ff4bdd3e298c7ee89 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/call-ga.ts @@ -0,0 +1,136 @@ +import { + DonationAmount, + DonationDuration +} from '@freecodecamp/shared/config/donation-settings'; +import { ChallengeFiles } from '../redux/prop-types'; +import TagManager from '.'; + +type DonationEventAction = + | 'Donate Page PayPal Payment Submission' + | 'Donate Page Stripe Card Payment Submission' + | 'Donate Page Stripe Payment Submission' + | 'Modal PayPal Payment Submission' + | 'Modal Stripe Card Payment Submission' + | 'Modal Stripe Payment Submission' + | 'Certificate PayPal Payment Submission' + | 'Certificate Stripe Card Payment Submission' + | 'Certificate Stripe Payment Submission'; + +interface DonationEvent { + event: 'donation'; + action: DonationEventAction; + duration: DonationDuration; + amount: DonationAmount; + completed_challenges: number; + completed_challenges_session: number; + isSignedIn: boolean; +} + +type DonationRelatedEventAction = + | 'Learn Donation Alert Click' + | 'Certification Donation Alert Click' + | 'Modal Become Supporter Click' + | 'Socrates LowerJaw Become Supporter Click' + | 'Donate Page Patreon Payment Redirection' + | 'Modal Patreon Payment Redirection' + | 'Amount Confirmation Clicked' + | 'Select Amount Tab Clicked' + | 'Edit Amount Clicked' + | 'Certificate Patreon Payment Redirection'; + +interface DonationRelatedEvent { + event: 'donation_related'; + action: DonationRelatedEventAction; + amount?: DonationAmount; +} + +type DonationViewEventAction = + | 'Displayed Block Donation Modal' + | 'Displayed Progress Donation Modal' + | 'Displayed Donate Page' + | 'Displayed Certificate Donation'; + +interface DonationViewEvent { + event: 'donation_view'; + action: DonationViewEventAction; +} + +interface PageViewEvent { + event: 'pageview'; + pagePath: string; +} + +interface ExperimentViewEvent { + event: 'experiment_viewed'; + event_category: 'experiment'; + experiment_id: string; + variation_id: number; +} + +interface ChallengeFailedEvent { + event: 'challenge_failed'; + challenge_id: string; + challenge_path: string; + challenge_files: ChallengeFiles; +} + +interface UserData { + event: 'user_data'; + user_id: string; +} + +interface SignIn { + event: 'sign_in'; +} + +interface SignOut { + event: 'sign_out'; + user_id: undefined; +} + +interface ChallengeTestCodeButtonClickEvent { + event: 'challenge_test_code_button_click'; +} + +interface ChallengeSubmitButtonClickEvent { + event: 'challenge_submit_button_click'; +} + +interface CallSocratesEvent { + event: 'call_socrates'; + action: 'Socrates LowerJaw Button Click'; + is_donating: boolean; + attempts: number | null; + limit: number | null; + optimized_request: Record | null; +} + +interface SendSocratesEvent { + event: 'send_socrates'; + action: 'Socrates Request Sent'; + is_donating: boolean; + attempts: number | null; + limit: number | null; + optimized_request: Record | null; +} + +export type GAevent = + | DonationViewEvent + | DonationEvent + | DonationRelatedEvent + | PageViewEvent + | ExperimentViewEvent + | ChallengeFailedEvent + | UserData + | SignOut + | SignIn + | ChallengeTestCodeButtonClickEvent + | ChallengeSubmitButtonClickEvent + | CallSocratesEvent + | SendSocratesEvent; + +export default function callGA(payload: GAevent) { + TagManager.dataLayer({ + dataLayer: payload + }); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/index.ts b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f39d6bf6380fe0b6c1e766f153975bf6d08c7b0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/analytics/index.ts @@ -0,0 +1,23 @@ +import TagManager from 'react-gtm-module'; + +import { + devAnalyticsId, + prodAnalyticsId +} from '../../config/analytics-settings'; + +import envData from '../../config/env.json'; + +const { deploymentEnv } = envData; + +const analyticsIDSelector = () => { + if (deploymentEnv === 'staging') return devAnalyticsId; + else return prodAnalyticsId; +}; + +const gtmId = analyticsIDSelector(); + +if (typeof document !== `undefined`) { + TagManager.initialize({ gtmId }); +} + +export default TagManager; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/chapter-icon.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/chapter-icon.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b0fdb83417795d96276c10e3fca0a616a5fcd830 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/chapter-icon.tsx @@ -0,0 +1,73 @@ +import React from 'react'; +import { + A1SpanishChapters, + FsdChapters, + A1ChineseChapters +} from '@freecodecamp/shared/config/chapters'; +import DatabaseIcon from './icons/database'; +import JavaScriptIcon from './icons/javascript'; +import ReactIcon from './icons/react'; +import ResponsiveDesign from './icons/responsive-design'; +import FreeCodeCampIcon from './icons/freecodecamp'; +import Html from './icons/html'; +import Css from './icons/css'; +import NodeIcon from './icons/node'; +import Python from './icons/python'; +import Graduation from './icons/graduation'; +import { + faBuilding, + faComments, + faCubes, + faDoorOpen, + faHands, + faIdCard +} from '@fortawesome/free-solid-svg-icons'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; + +const iconMap = { + [FsdChapters.Welcome]: FreeCodeCampIcon, + [FsdChapters.Html]: Html, + [FsdChapters.Css]: Css, + [FsdChapters.Javascript]: JavaScriptIcon, + [FsdChapters.FrontendLibraries]: ReactIcon, + [FsdChapters.RelationalDatabases]: DatabaseIcon, + [FsdChapters.BackendJavascript]: NodeIcon, + [FsdChapters.Python]: Python, + [FsdChapters.Career]: Graduation, + [FsdChapters.RwdExam]: Graduation, + [FsdChapters.JsExam]: Graduation, + [FsdChapters.Fed]: ReactIcon, + [FsdChapters.FedExam]: Graduation, + [FsdChapters.PythonExam]: Graduation, + [FsdChapters.RdbExam]: Graduation, + [FsdChapters.Bed]: NodeIcon, + [FsdChapters.BedExam]: Graduation, + [FsdChapters.FsdExam]: Graduation, + [A1ChineseChapters.zhA1Welcome]: faDoorOpen, + [A1ChineseChapters.zhA1PinYin]: faCubes, + [A1ChineseChapters.zhA1Greetings]: faComments, + [A1ChineseChapters.zhA1GreetingsLegacy]: faComments, + [A1ChineseChapters.zhA1NumbersAndPersonalInformation]: faIdCard, + [A1ChineseChapters.zhA1Family]: faIdCard, + [A1ChineseChapters.zhA1Expressing]: faHands, + [A1SpanishChapters.esA1Welcome]: faDoorOpen, + [A1SpanishChapters.esA1Fundamentals]: faCubes, + [A1SpanishChapters.esA1Greetings]: faComments, + [A1SpanishChapters.esA1Details]: faIdCard, + [A1SpanishChapters.esA1Describing]: faBuilding +}; + +type ChapterIconProps = { + chapter: FsdChapters; +} & React.SVGProps; + +export function ChapterIcon(props: ChapterIconProps): JSX.Element { + const { chapter, ...iconProps } = props; + const Icon = iconMap[chapter] ?? ResponsiveDesign; + + if (typeof Icon === 'object') { + return ; + } + + return ; +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-chinese.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-chinese.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d2f1f24535a39477bc8eb8007fab70a5ea10d012 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-chinese.tsx @@ -0,0 +1,77 @@ +import React from 'react'; + +function A1ChineseIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +A1ChineseIcon.displayName = 'A1ChineseIcon'; + +export default A1ChineseIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-spanish.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-spanish.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f580b1fcd0cb4e53b5ff47d3fa38a0dd97efdde7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a1-spanish.tsx @@ -0,0 +1,77 @@ +import React from 'react'; + +function A1SpanishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +A1SpanishIcon.displayName = 'A1SpanishIcon'; + +export default A1SpanishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-chinese.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-chinese.tsx new file mode 100644 index 0000000000000000000000000000000000000000..09da704351cc6e08a8ce3294bbb8cdea62ed7bbb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-chinese.tsx @@ -0,0 +1,77 @@ +import React from 'react'; + +function A2ChineseIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +A2ChineseIcon.displayName = 'A2ChineseIcon'; + +export default A2ChineseIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-english.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-english.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f9a52edc2dae65f64542b40d09123155bc38f1ee --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-english.tsx @@ -0,0 +1,80 @@ +import React from 'react'; + +function A2EnglishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +A2EnglishIcon.displayName = 'A2EnglishIcon'; + +export default A2EnglishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-spanish.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-spanish.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b6db8bc7033f9c4bf88094912823381bc351cbf8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/a2-spanish.tsx @@ -0,0 +1,77 @@ +import React from 'react'; + +function A2SpanishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +A2SpanishIcon.displayName = 'A2SpanishIcon'; + +export default A2SpanishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/algorithm.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/algorithm.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c66c75ec5b684e4247d266211e0f4fbeaf5d7d4c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/algorithm.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function Algorithm( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +Algorithm.displayName = 'Algorithm'; + +export default Algorithm; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/analytics.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/analytics.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d04155bcf78a7fb21eef94aeb482334e338a8e87 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/analytics.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function Analytics( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +Analytics.displayName = 'Analytics'; + +export default Analytics; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/api.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/api.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d1aeadbb5faa6475d9f3245280de4092634b1fbb --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/api.tsx @@ -0,0 +1,19 @@ +import React from 'react'; +function APIIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +APIIcon.displayName = 'APIIcon'; + +export default APIIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b1-english.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b1-english.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e75413b7e16f0c8d739ae8ecaa13ff31d9d00c83 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b1-english.tsx @@ -0,0 +1,80 @@ +import React from 'react'; + +function B1EnglishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +B1EnglishIcon.displayName = 'B1EnglishIcon'; + +export default B1EnglishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b2-english.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b2-english.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3788b6056ec979d8521572fb89692774c87911db --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/b2-english.tsx @@ -0,0 +1,80 @@ +import React from 'react'; + +function B2EnglishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +B2EnglishIcon.displayName = 'B2EnglishIcon'; + +export default B2EnglishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c-sharp-logo.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c-sharp-logo.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d34cb765a5939fc9d29e2f9facaa5db247d47cfa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c-sharp-logo.tsx @@ -0,0 +1,24 @@ +import React from 'react'; + +function CSharpLogo( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CSharpLogo.displayName = 'CSharpLogo'; +export default CSharpLogo; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c1-english.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c1-english.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b8e79943965b5a593a874bb434e4526e7cafc054 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c1-english.tsx @@ -0,0 +1,24 @@ +import React from 'react'; + +function C1EnglishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +C1EnglishIcon.displayName = 'C1EnglishIcon'; + +export default C1EnglishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c2-english.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c2-english.tsx new file mode 100644 index 0000000000000000000000000000000000000000..27669ed8b46d75b66b6af2718f771cd4eaca88fa --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/c2-english.tsx @@ -0,0 +1,25 @@ +import React from 'react'; + +function C2EnglishIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +C2EnglishIcon.displayName = 'C2EnglishIcon'; + +export default C2EnglishIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/calendar.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/calendar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0d896a0190b63aed714f919b26ef62daca76637c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/calendar.tsx @@ -0,0 +1,21 @@ +import React from 'react'; + +function CalendarIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CalendarIcon.displayName = 'CalendarIcon'; + +export default CalendarIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/cap.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/cap.tsx new file mode 100644 index 0000000000000000000000000000000000000000..24f827bfee6deabf70d009598ef289c276f21c1f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/cap.tsx @@ -0,0 +1,29 @@ +import React from 'react'; +function CapIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CapIcon.displayName = 'CapIcon'; + +export default CapIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/caret.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/caret.tsx new file mode 100644 index 0000000000000000000000000000000000000000..70cd4e05738d9e184ddc6a05984b9f7d08b0862b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/caret.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +function Caret(): JSX.Element { + return ( + + + + ); +} + +Caret.displayName = 'Caret'; + +export default Caret; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/certification.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/certification.tsx new file mode 100644 index 0000000000000000000000000000000000000000..10df0b2b8435134a3fd28a15b424b6d60fb367d2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/certification.tsx @@ -0,0 +1,68 @@ +import React from 'react'; + +function CertificationIcon(): JSX.Element { + return ( + + + + + + + + + + + + + + + + + + + + + ); +} + +CertificationIcon.displayName = 'CertificationIcon'; + +export default CertificationIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/clipboard.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/clipboard.tsx new file mode 100644 index 0000000000000000000000000000000000000000..8ec6a43284197fee789d77c83bd6c4d07eb41286 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/clipboard.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function Clipboard( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +Clipboard.displayName = 'Clipboard'; + +export default Clipboard; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/closedcaptions.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/closedcaptions.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f93f081e9d311607adcd07328eb00647f9ad9186 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/closedcaptions.tsx @@ -0,0 +1,19 @@ +import React from 'react'; + +function ClosedCaptionsIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +ClosedCaptionsIcon.displayName = 'ClosedCaptionsIcon'; + +export default ClosedCaptionsIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/code.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/code.tsx new file mode 100644 index 0000000000000000000000000000000000000000..fcd3b4f6537e996498c274f6ae459957dccfd0f9 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/code.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function Code( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +Code.displayName = 'Code'; + +export default Code; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/college-algebra.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/college-algebra.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6e26f752aaf8ea24c35342879abef659c71c973f --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/college-algebra.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function CollegeAlgebra( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CollegeAlgebra.displayName = 'CollegeAlgebra'; + +export default CollegeAlgebra; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/community.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/community.tsx new file mode 100644 index 0000000000000000000000000000000000000000..78519de9c8264c595ee9f10d0d2fe162efdb3ae5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/community.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +function CommunityIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CommunityIcon.displayName = 'CommunityIcon'; + +export default CommunityIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/css.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/css.tsx new file mode 100644 index 0000000000000000000000000000000000000000..95bdab948c6fc46a4fce08085fab663dddde9cf8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/css.tsx @@ -0,0 +1,15 @@ +import React from 'react'; + +function Css( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +Css.displayName = 'Css'; + +export default Css; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/curriculum.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/curriculum.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2fa7cbd9cfd8f0de3beaf7ab8bef9bf3f86b82b7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/curriculum.tsx @@ -0,0 +1,27 @@ +import React from 'react'; +function CurriculumIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +CurriculumIcon.displayName = 'CurriculumIcon'; + +export default CurriculumIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/d3.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/d3.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d735e8ff36a9eabaa9420d9343cfab036e277fa0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/d3.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function D3Icon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +D3Icon.displayName = 'D3'; + +export default D3Icon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/daily-coding-challenge.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/daily-coding-challenge.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ddfdb93108a81bee43a2eaa1e9b975b46c650394 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/daily-coding-challenge.tsx @@ -0,0 +1,21 @@ +import React from 'react'; + +function DailyCodingChallengeIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +DailyCodingChallengeIcon.displayName = 'DailyCodingChallengeIcon'; + +export default DailyCodingChallengeIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/database.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/database.tsx new file mode 100644 index 0000000000000000000000000000000000000000..374198d157d64d85f24f33162ccb335e3b7dbe3e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/database.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function DatabaseIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +DatabaseIcon.displayName = 'Database'; + +export default DatabaseIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/default-avatar.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/default-avatar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6cf3370e336ffbdd46f6555e5e726412611b0d49 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/default-avatar.tsx @@ -0,0 +1,95 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +function DefaultAvatar( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + const { t } = useTranslation(); + + return ( + + ); +} + +DefaultAvatar.displayName = 'DefaultAvatar'; + +export default DefaultAvatar; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dot-net-logo.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dot-net-logo.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a5c0bea6e6e6566915480462bf8eca6f9d9326fe --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dot-net-logo.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +function DotNetLogo( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + .NET + + + ); +} + +DotNetLogo.displayName = 'DotNetLogo'; +export default DotNetLogo; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dropdown.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dropdown.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5b2f9333aaa021b209a414e97068b4eda48ed992 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dropdown.tsx @@ -0,0 +1,28 @@ +import React from 'react'; + +function DropDown(): JSX.Element { + return ( + + ); +} + +DropDown.displayName = 'DropDown'; + +export default DropDown; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dumbbell.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dumbbell.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d45d3111002331ebf12c90999de4d9be50a251b5 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/dumbbell.tsx @@ -0,0 +1,50 @@ +import React from 'react'; +function DumbbellIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +DumbbellIcon.displayName = 'DumbbellIcon'; + +export default DumbbellIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/fail.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/fail.tsx new file mode 100644 index 0000000000000000000000000000000000000000..98fb3632e5c0c632cea93fd8e324f47bb7ac0665 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/fail.tsx @@ -0,0 +1,52 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +function RedFail(): JSX.Element { + const { t } = useTranslation(); + + return ( + + ); +} + +RedFail.displayName = 'RedFail'; + +export default RedFail; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/free.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/free.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f88738addba88266656037d29e8e5795ab978a65 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/free.tsx @@ -0,0 +1,27 @@ +import React from 'react'; +function FreeIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +FreeIcon.displayName = 'FreeIcon'; + +export default FreeIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp-logo.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp-logo.tsx new file mode 100644 index 0000000000000000000000000000000000000000..1e1a28f8321dfd7145fa12fa8f7cf2778487fef0 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp-logo.tsx @@ -0,0 +1,114 @@ +import React from 'react'; + +function FreeCodeCampLogo( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +} + +FreeCodeCampLogo.displayName = 'FreeCodeCampLogo'; + +export default FreeCodeCampLogo; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp.tsx new file mode 100644 index 0000000000000000000000000000000000000000..1316044a46bff29a1f2f8ce164f1bb6053445f6d --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/freecodecamp.tsx @@ -0,0 +1,15 @@ +import React from 'react'; + +function FreeCodeCampIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +FreeCodeCampIcon.displayName = 'FreeCodeCampIcon'; + +export default FreeCodeCampIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/graduation.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/graduation.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f4a37f976f88cb17697edb5112f9d0fc0995bb0c --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/graduation.tsx @@ -0,0 +1,23 @@ +import React from 'react'; + +function Graduation( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +Graduation.displayName = 'Graduation'; + +export default Graduation; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-not-completed.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-not-completed.tsx new file mode 100644 index 0000000000000000000000000000000000000000..bed54acf1b5886a05510434fc781845d1243d4d3 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-not-completed.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +interface GreenNotCompletedProps + extends JSX.IntrinsicAttributes, React.SVGProps { + hushScreenReaderText?: boolean; +} + +function GreenNotCompleted(props: GreenNotCompletedProps): JSX.Element { + const { t } = useTranslation(); + const { hushScreenReaderText = false, ...rest } = props; + return ( + <> + {!hushScreenReaderText && ( + {t('icons.not-passed')} + )} + + + ); +} + +GreenNotCompleted.displayName = 'GreenNotCompleted'; + +export default GreenNotCompleted; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-pass.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-pass.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b5c0f7cc4936f9673a3386aa63fc0c38e8b3a53e --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/green-pass.tsx @@ -0,0 +1,59 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +interface GreenPassProps + extends JSX.IntrinsicAttributes, React.SVGProps { + hushScreenReaderText?: boolean; +} +function GreenPass(props: GreenPassProps): JSX.Element { + const { t } = useTranslation(); + const { hushScreenReaderText = false, ...rest } = props; + return ( + + + + ); +} + +GreenPass.displayName = 'GreenPass'; + +export default GreenPass; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/help.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/help.tsx new file mode 100644 index 0000000000000000000000000000000000000000..744fa8dc4636f9bdf265eb0aeb06ff9e60aa5ca1 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/help.tsx @@ -0,0 +1,26 @@ +import React from 'react'; + +function Help( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +Help.displayName = 'Help'; + +export default Help; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/html.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/html.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a9e0ae5aeb89fe094048c276c16938caf127f766 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/html.tsx @@ -0,0 +1,15 @@ +import React from 'react'; + +function Html( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +Html.displayName = 'Html'; + +export default Html; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/initial.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/initial.tsx new file mode 100644 index 0000000000000000000000000000000000000000..3dc99c0774653cbf920dcd226a86eb04f7c20f1a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/initial.tsx @@ -0,0 +1,58 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +function Initial( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + const { t } = useTranslation(); + + return ( + + + {t('icons.initial')} + + + + + + + ); +} + +Initial.displayName = 'Initial'; + +export default Initial; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/input-reset.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/input-reset.tsx new file mode 100644 index 0000000000000000000000000000000000000000..25c5311b8a236fc110dc036bd01331c31a639e20 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/input-reset.tsx @@ -0,0 +1,24 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +const InputReset = (): JSX.Element => { + const { t } = useTranslation(); + + return ( + <> + {t('icons.input-reset')} + + + + + ); +}; + +InputReset.displayName = 'InputReset'; +export default InputReset; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/javascript.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/javascript.tsx new file mode 100644 index 0000000000000000000000000000000000000000..94e49c9c0781c960ae022dcdf129f3f1969446a8 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/javascript.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function JavaScriptIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +JavaScriptIcon.displayName = 'JavaScriptIcon'; + +export default JavaScriptIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/language-globe.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/language-globe.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5ab89640f7988cc6ce71a96f46fb80bc18c2fd3b --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/language-globe.tsx @@ -0,0 +1,56 @@ +import React from 'react'; + +function LanguageGlobe( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + + + + + ); +} + +LanguageGlobe.displayName = 'LanguageGlobe'; + +export default LanguageGlobe; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/link-button.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/link-button.tsx new file mode 100644 index 0000000000000000000000000000000000000000..799df61f905972f6f340c4a6ec40cf273616f4da --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/link-button.tsx @@ -0,0 +1,36 @@ +import React from 'react'; + +export default function LinkButton( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/magnifier.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/magnifier.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9c6faed41623a27f68e8c15a7cd821935a476ea2 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/magnifier.tsx @@ -0,0 +1,24 @@ +import React from 'react'; +import { useTranslation } from 'react-i18next'; + +const Magnifier = (): JSX.Element => { + const { t } = useTranslation(); + + return ( + <> + {t('icons.magnifier')} + + + + + ); +}; + +Magnifier.displayName = 'Magnifier'; +export default Magnifier; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/microsoft-logo.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/microsoft-logo.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9b84c063b338096fbf3ec5be693867def7f67be7 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/microsoft-logo.tsx @@ -0,0 +1,26 @@ +import React from 'react'; + +function MicrosoftLogo( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + + + + + ); +} + +MicrosoftLogo.displayName = 'MicrosoftLogo'; +export default MicrosoftLogo; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/node.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/node.tsx new file mode 100644 index 0000000000000000000000000000000000000000..c5358815d80bb0f83f5c6582e6ba063268107a10 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/node.tsx @@ -0,0 +1,15 @@ +import React from 'react'; + +function NodeIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + + + ); +} + +NodeIcon.displayName = 'NodeIcon'; + +export default NodeIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/outline-lightbulb.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/outline-lightbulb.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b2858a4aaad2da9940942c548926d74d91571e0a --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/outline-lightbulb.tsx @@ -0,0 +1,29 @@ +import React from 'react'; + +function OutlineLightbulb( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +OutlineLightbulb.displayName = 'OutlineLightbulb'; + +export default OutlineLightbulb; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/python.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/python.tsx new file mode 100644 index 0000000000000000000000000000000000000000..ee7e7a803026345361bb686bc3db78b0b97e2c89 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/python.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function PythonIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +PythonIcon.displayName = 'PythonIcon'; + +export default PythonIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/react.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/react.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f479f7758fa4bafc32392be35bb1ccacaba87178 --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/react.tsx @@ -0,0 +1,20 @@ +import React from 'react'; + +function ReactIcon( + props: JSX.IntrinsicAttributes & React.SVGProps +): JSX.Element { + return ( + + ); +} + +ReactIcon.displayName = 'ReactIcon'; + +export default ReactIcon; diff --git a/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/reset.tsx b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/reset.tsx new file mode 100644 index 0000000000000000000000000000000000000000..78223dd89dc7e137e43f0555f61c4399ed9930da --- /dev/null +++ b/github_code/freeCodeCamp__freeCodeCamp/client/src/assets/icons/reset.tsx @@ -0,0 +1,11 @@ +import React from 'react'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faTrashCan } from '@fortawesome/free-solid-svg-icons'; + +function Reset(): JSX.Element { + return