├── .DS_Store
├── .choreo
└── endpoints.yaml
├── .dockerignore
├── .gitignore
├── .idea
├── .gitignore
├── CodeX-API.iml
├── modules.xml
├── prettier.xml
└── vcs.xml
├── .trivyignore
├── Dockerfile
├── LICENSE.md
├── README.md
├── SETUP.md
├── outputs
└── .DS_Store
├── package.json
└── src
├── .DS_Store
├── file-system
├── .DS_Store
├── createCodeFile.js
└── removeCodeFile.js
├── index.js
└── run-code
├── index.js
├── info.js
└── instructions.js
/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jaagrav/CodeX-API/e32c7a33c7c165263ea1302006d0fd83f5082334/.DS_Store
--------------------------------------------------------------------------------
/.choreo/endpoints.yaml:
--------------------------------------------------------------------------------
1 | version: 0.1
2 | endpoints:
3 | - name: root
4 | port: 8080
5 | type: REST
6 | networkVisibility: Public
7 | context: /
8 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | package-lock.json
3 | codes/
4 | classes/
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 |
--------------------------------------------------------------------------------
/.idea/CodeX-API.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/prettier.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.trivyignore:
--------------------------------------------------------------------------------
1 | *
2 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:18.04
2 |
3 | # Set environment variables
4 | ENV PYTHON_VERSION 3.7.7
5 | ENV PYTHON_PIP_VERSION 20.1
6 | ENV DEBIAN_FRONTEND noninteractive
7 | ENV NODE_VERSION 16
8 |
9 | # Update and install dependencies
10 | RUN apt-get update && apt-get -y install gcc mono-mcs golang-go \
11 | default-jre default-jdk python3-pip python3 curl && \
12 | curl -fsSL https://deb.nodesource.com/setup_16.x | bash - && \
13 | apt-get update && \
14 | apt-get install -y nodejs && \
15 | rm -rf /var/lib/apt/lists/*
16 |
17 | # Verify that Node.js is installed
18 | RUN node -v && npm -v
19 |
20 | # Create a non-root user with a UID between 10000 and 20000
21 | RUN useradd -m -u 10001 appuser
22 |
23 | # Verify that the user is set correctly
24 | RUN id -u appuser
25 |
26 | # Set up the working directory with correct permissions
27 | WORKDIR /app
28 | COPY . /app
29 | RUN chown -R appuser:appuser /app
30 |
31 | # Temporarily switch to root to run npm install
32 | USER root
33 | RUN npm install --unsafe-perm
34 |
35 | # Switch back to non-root user
36 | USER appuser
37 |
38 | # Expose the application port
39 | EXPOSE 8080
40 |
41 | # Start the application
42 | CMD ["npm", "start"]
43 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2022
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining
6 | a copy of this software and associated documentation files (the
7 | "Software"), to deal in the Software without restriction, including
8 | without limitation the rights to use, copy, modify, merge, publish,
9 | distribute, sublicense, and/or sell copies of the Software, and to
10 | permit persons to whom the Software is furnished to do so, subject to
11 | the following conditions:
12 |
13 | The above copyright notice and this permission notice shall be
14 | included in all copies or substantial portions of the Software.
15 |
16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CodeX API
2 |
3 | 
4 |
5 | > This API is still in very early stages of development. So consider not using the API in production since things might change in the future.
6 |
7 | ### Introducing the new CodeX API
8 |
9 | Here's how you can execute code in various languages on your own website for free (no, there's no fucking catch, it's literally free),
10 |
11 | ### Execute Code and fetch output
12 |
13 | #### `POST` /
14 |
15 | This endpoint allows you to execute your script and fetch output results.
16 |
17 | ### What are the Input Parameters for execute api call?
18 |
19 | | Parameter | Description |
20 | | ---------- | ----------------------------------------------------------------------------------------------------------------------------- |
21 | | "code" | Should contain the script that needs to be executed |
22 | | "language" | Language that the script is written in for example: java, cpp, etc. (Check language as a payload down below in next question) |
23 | | "input" | In case the script requires any kind of input for execution, leave empty if no input required |
24 |
25 | ### What are the languages that are supported for execution?
26 |
27 | Whichever language you might mention in the language field, it would be automatically executed with the latest version of it's compiler.
28 | | Languages | Language as a payload |
29 | |-----------|-----------------------|
30 | | Java | java |
31 | | Python | py |
32 | | C++ | cpp |
33 | | C | c |
34 | | GoLang | go |
35 | | C# | cs |
36 | | NodeJS | js |
37 |
38 | More coming very soon!
39 |
40 | ### NodeJS Example to Execute API Call?
41 |
42 | ```js
43 | var axios = require('axios');
44 | var qs = require('qs');
45 | var data = qs.stringify({
46 | 'code': 'val = int(input("Enter your value: ")) + 5\nprint(val)',
47 | 'language': 'py',
48 | 'input': '7'
49 | });
50 | var config = {
51 | method: 'post',
52 | url: 'https://api.codex.jaagrav.in',
53 | headers: {
54 | 'Content-Type': 'application/x-www-form-urlencoded'
55 | },
56 | data : data
57 | };
58 |
59 | axios(config)
60 | .then(function (response) {
61 | console.log(JSON.stringify(response.data));
62 | })
63 | .catch(function (error) {
64 | console.log(error);
65 | });
66 | ```
67 |
68 | ### Sample Output
69 |
70 | The output is a JSON object comprising only one parameter that is the output.
71 |
72 | ```json
73 | {
74 | "timeStamp": 1672439982964,
75 | "status": 200,
76 | "output": "Enter your value: 12\n",
77 | "error": "",
78 | "language": "py",
79 | "info": "Python 3.6.9\n"
80 | }
81 | ```
82 |
83 | > Since a lot of people had issues with executing the previous API from backend or serverless function, unlike the previous version of the API, this version of the API won't throw any Cross Origin errors so you can use this from the front end without any worries. Thank me later ;)
84 |
85 | #### `GET` /list
86 |
87 | This endpoint allows you to list all languages supported and their versions.
88 |
89 | ```json
90 | {
91 | "timeStamp": 1672440064864,
92 | "status": 200,
93 | "supportedLanguages": [
94 | {
95 | "language": "java",
96 | "info": "openjdk 11.0.17 2022-10-18\nOpenJDK Runtime Environment (build 11.0.17+8-post-Ubuntu-1ubuntu218.04)\nOpenJDK 64-Bit Server VM (build 11.0.17+8-post-Ubuntu-1ubuntu218.04, mixed mode, sharing)\n"
97 | },
98 | {
99 | "language": "cpp",
100 | "info": "g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0\nCopyright (C) 2017 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
101 | },
102 | {
103 | "language": "py",
104 | "info": "Python 3.6.9\n"
105 | },
106 | {
107 | "language": "c",
108 | "info": "gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0\nCopyright (C) 2017 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
109 | },
110 | {
111 | "language": "js",
112 | "info": "v16.13.2\n"
113 | },
114 | {
115 | "language": "go",
116 | "info": "go version go1.10.4 linux/amd64\n"
117 | },
118 | {
119 | "language": "cs",
120 | "info": "Mono C# compiler version 4.6.2.0\n"
121 | }
122 | ]
123 | }
124 | ```
125 |
126 | > This API is deployed on a free instance on [choreo](https://choreo.dev/) so shoutout to @wso2 for providing a platform that helped bringing back the CodeX API after a long down time. Since I am using a free tier, the API might be slow sometimes, so please be patient while I try to fund this project.
127 |
128 | Happy hacking!
129 |
--------------------------------------------------------------------------------
/SETUP.md:
--------------------------------------------------------------------------------
1 | # Setup CodeX-API Locally
2 |
3 | In order to setup this project locally on your machine, you can either run the docker image or run the nodejs app directly using node. Although running directly using node is not recommended since we're dealing with installing so many languages like java, c, c++, etc. You'd need to install SDKs and Compilers for each of the language supported by this API for testing purposes.
4 |
5 | ### Install project (using Docker)
6 |
7 | ```bash
8 | docker build --no-cache -t codex-api .
9 |
10 | docker run -p 3000:3000 codex-api
11 | ```
12 |
--------------------------------------------------------------------------------
/outputs/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jaagrav/CodeX-API/e32c7a33c7c165263ea1302006d0fd83f5082334/outputs/.DS_Store
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "codex-api",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "src/index.js",
6 | "scripts": {
7 | "start": "node .",
8 | "test": "echo \"Error: no test specified\" && exit 1"
9 | },
10 | "author": "Jaagrav Seal",
11 | "license": "ISC",
12 | "dependencies": {
13 | "cors": "^2.8.5",
14 | "express": "^4.18.1",
15 | "uuid": "^8.3.2"
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jaagrav/CodeX-API/e32c7a33c7c165263ea1302006d0fd83f5082334/src/.DS_Store
--------------------------------------------------------------------------------
/src/file-system/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Jaagrav/CodeX-API/e32c7a33c7c165263ea1302006d0fd83f5082334/src/file-system/.DS_Store
--------------------------------------------------------------------------------
/src/file-system/createCodeFile.js:
--------------------------------------------------------------------------------
1 | const { v4: getUUID } = require("uuid");
2 | const { existsSync, mkdirSync, writeFileSync } = require("fs");
3 | const { join } = require("path");
4 |
5 | const CODES_DIR = process.env.CODES_DIR || "/tmp/codes";
6 | const OUTPUTS_DIR = process.env.OUTPUTS_DIR || "/tmp/outputs";
7 |
8 | if (!existsSync(CODES_DIR)) mkdirSync(CODES_DIR, { recursive: true });
9 | if (!existsSync(OUTPUTS_DIR)) mkdirSync(OUTPUTS_DIR, { recursive: true });
10 |
11 | const createCodeFile = async (language, code) => {
12 | const jobID = getUUID();
13 | const fileName = `${jobID}.${language}`;
14 | const filePath = join(CODES_DIR, fileName);
15 |
16 | await writeFileSync(filePath, code?.toString());
17 |
18 | return {
19 | fileName,
20 | filePath,
21 | jobID,
22 | };
23 | };
24 |
25 | module.exports = {
26 | createCodeFile,
27 | };
28 |
--------------------------------------------------------------------------------
/src/file-system/removeCodeFile.js:
--------------------------------------------------------------------------------
1 | const { unlinkSync } = require("fs");
2 | const { join } = require("path");
3 |
4 | const CODES_DIR = process.env.CODES_DIR || "/tmp/codes";
5 | const OUTPUTS_DIR = process.env.OUTPUTS_DIR || "/tmp/outputs";
6 |
7 | const removeCodeFile = async (uuid, lang, outputExt) => {
8 | const codeFile = join(CODES_DIR, `${uuid}.${lang}`);
9 | const outputFile = join(OUTPUTS_DIR, `${uuid}.${outputExt}`);
10 |
11 | try {
12 | unlinkSync(codeFile);
13 | } catch (err) {
14 | console.error(`Failed to delete code file: ${codeFile}`, err);
15 | }
16 |
17 | if (outputExt) {
18 | try {
19 | unlinkSync(outputFile);
20 | } catch (err) {
21 | console.error(`Failed to delete output file: ${outputFile}`, err);
22 | }
23 | }
24 | };
25 |
26 | module.exports = {
27 | removeCodeFile,
28 | };
29 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | const {runCode} = require("./run-code");
2 | const {supportedLanguages} = require("./run-code/instructions");
3 |
4 | const express = require("express");
5 | const bodyParser = require("body-parser");
6 | const app = express();
7 | const port = process.env.PORT || 8080;
8 | const cors = require("cors");
9 | const {info} = require("./run-code/info");
10 |
11 | app.use(bodyParser.json());
12 | app.use(bodyParser.urlencoded({extended: true}));
13 | app.use(cors());
14 |
15 | const sendResponse = (res, statusCode, body) => {
16 | const timeStamp = Date.now()
17 |
18 | res.status(statusCode).send({
19 | timeStamp,
20 | status: statusCode,
21 | ...body
22 | })
23 | }
24 |
25 | app.post("/", async (req, res) => {
26 | try {
27 | const output = await runCode(req.body)
28 | sendResponse(res, 200, output)
29 | } catch (err) {
30 | sendResponse(res, err?.status || 500, err)
31 | }
32 | })
33 |
34 | app.get('/list', async (req, res) => {
35 | const body = []
36 |
37 | for(const language of supportedLanguages) {
38 | body.push({
39 | language,
40 | info: await info(language),
41 | })
42 | }
43 |
44 | sendResponse(res, 200, {supportedLanguages: body})
45 | })
46 |
47 | app.listen(port);
48 |
--------------------------------------------------------------------------------
/src/run-code/index.js:
--------------------------------------------------------------------------------
1 | const {commandMap, supportedLanguages} = require("./instructions")
2 | const {createCodeFile} = require("../file-system/createCodeFile")
3 | const {removeCodeFile} = require("../file-system/removeCodeFile")
4 | const {info} = require("./info")
5 |
6 | const {spawn} = require("child_process");
7 |
8 | async function runCode({language = "", code = "", input = ""}) {
9 | const timeout = 30;
10 |
11 | if (code === "")
12 | throw {
13 | status: 400,
14 | error: "No Code found to execute."
15 | }
16 |
17 | if (!supportedLanguages.includes(language))
18 | throw {
19 | status: 400,
20 | error: `Please enter a valid language. Check documentation for more details: https://github.com/Jaagrav/CodeX-API#readme. The languages currently supported are: ${supportedLanguages.join(', ')}.`
21 | }
22 |
23 | const {jobID} = await createCodeFile(language, code);
24 | const {compileCodeCommand, compilationArgs, executeCodeCommand, executionArgs, outputExt} = commandMap(jobID, language);
25 |
26 | if (compileCodeCommand) {
27 | await new Promise((resolve, reject) => {
28 | const compileCode = spawn(compileCodeCommand, compilationArgs || [])
29 | compileCode.stderr.on('data', (error) => {
30 | reject({
31 | status: 200,
32 | output: '',
33 | error: error.toString(),
34 | language
35 | })
36 | });
37 | compileCode.on('exit', () => {
38 | resolve()
39 | })
40 | })
41 | }
42 |
43 | const result = await new Promise((resolve, reject) => {
44 | const executeCode = spawn(executeCodeCommand, executionArgs || []);
45 | let output = "", error = "";
46 |
47 | const timer = setTimeout(async () => {
48 | executeCode.kill("SIGHUP");
49 |
50 | await removeCodeFile(jobID, language, outputExt);
51 |
52 | reject({
53 | status: 408,
54 | error: `CodeX API Timed Out. Your code took too long to execute, over ${timeout} seconds. Make sure you are sending input as payload if your code expects an input.`
55 | })
56 | }, timeout * 1000);
57 |
58 | if (input !== "") {
59 | input.split('\n').forEach((line) => {
60 | executeCode.stdin.write(`${line}\n`);
61 | });
62 | executeCode.stdin.end();
63 | }
64 |
65 | executeCode.stdin.on('error', (err) => {
66 | console.log('stdin err', err);
67 | });
68 |
69 | executeCode.stdout.on('data', (data) => {
70 | output += data.toString();
71 | });
72 |
73 | executeCode.stderr.on('data', (data) => {
74 | error += data.toString();
75 | });
76 |
77 | executeCode.on('exit', (err) => {
78 | clearTimeout(timer);
79 | resolve({output, error});
80 | });
81 | })
82 |
83 | await removeCodeFile(jobID, language, outputExt);
84 |
85 | return {
86 | ...result,
87 | language,
88 | info: await info(language)
89 | }
90 | }
91 |
92 | module.exports = {runCode}
--------------------------------------------------------------------------------
/src/run-code/info.js:
--------------------------------------------------------------------------------
1 | const {commandMap} = require("./instructions")
2 | const util = require('util');
3 | const exec = util.promisify(require('child_process').exec);
4 |
5 | const info = async (language) => {
6 | const {compilerInfoCommand} = commandMap('', language);
7 |
8 | const {stdout} = await exec(compilerInfoCommand);
9 |
10 | return stdout;
11 | }
12 |
13 | module.exports = {info}
--------------------------------------------------------------------------------
/src/run-code/instructions.js:
--------------------------------------------------------------------------------
1 | const {join} = require('path')
2 |
3 | const CODES_DIR = process.env.CODES_DIR || "/tmp/codes";
4 | const OUTPUTS_DIR = process.env.OUTPUTS_DIR || "/tmp/outputs";
5 |
6 | const commandMap = (jobID, language) => {
7 | switch (language) {
8 | case 'java':
9 | return {
10 | executeCodeCommand: 'java',
11 | executionArgs: [
12 | `${CODES_DIR}/${jobID}.java`
13 | ],
14 | compilerInfoCommand: 'java --version'
15 | };
16 | case 'cpp':
17 | return {
18 | compileCodeCommand: 'g++',
19 | compilationArgs: [
20 | `${CODES_DIR}/${jobID}.cpp`,
21 | '-o',
22 | `${OUTPUTS_DIR}/${jobID}.out`
23 | ],
24 | executeCodeCommand: `${OUTPUTS_DIR}/${jobID}.out`,
25 | outputExt: 'out',
26 | compilerInfoCommand: 'g++ --version'
27 | };
28 | case 'py':
29 | return {
30 | executeCodeCommand: 'python3',
31 | executionArgs: [
32 | `${CODES_DIR}/${jobID}.py`
33 | ],
34 | compilerInfoCommand: 'python3 --version'
35 | }
36 | case 'c':
37 | return {
38 | compileCodeCommand: 'gcc',
39 | compilationArgs: [
40 | `${CODES_DIR}/${jobID}.c`,
41 | '-o',
42 | `${OUTPUTS_DIR}/${jobID}.out`
43 | ],
44 | executeCodeCommand: `${OUTPUTS_DIR}/${jobID}.out`,
45 | outputExt: 'out',
46 | compilerInfoCommand: 'gcc --version'
47 | }
48 | case 'js':
49 | return {
50 | executeCodeCommand: 'node',
51 | executionArgs: [
52 | `${CODES_DIR}/${jobID}.js`
53 | ],
54 | compilerInfoCommand: 'node --version'
55 | }
56 | case 'go':
57 | return {
58 | executeCodeCommand: 'go',
59 | executionArgs: [
60 | 'run',
61 | `${CODES_DIR}/${jobID}.go`
62 | ],
63 | compilerInfoCommand: 'go version'
64 | }
65 | case 'cs':
66 | return {
67 | compileCodeCommand: 'mcs',
68 | compilationArgs: [
69 | `-out:${OUTPUTS_DIR}/${jobID}.exe`,
70 | `${CODES_DIR}/${jobID}.cs`,
71 | ],
72 | executeCodeCommand: 'mono',
73 | executionArgs: [
74 | `${OUTPUTS_DIR}/${jobID}.exe`
75 | ],
76 | outputExt: 'exe',
77 | compilerInfoCommand: 'mcs --version'
78 | }
79 | }
80 | }
81 |
82 | const supportedLanguages = ['java', 'cpp', 'py', 'c', 'js', 'go', 'cs'];
83 |
84 | module.exports = {commandMap, supportedLanguages}
85 |
--------------------------------------------------------------------------------