From fbe5a1adb098cf74f20ead9be51bf3d5a65f024a Mon Sep 17 00:00:00 2001 From: Akhil Mohan Date: Sun, 10 Dec 2023 20:36:20 +0530 Subject: [PATCH] feat(infisical-pg): added github,gitlab and google oauth --- backend-pg/package-lock.json | 372 ++++++++++++++++++ backend-pg/package.json | 9 + backend-pg/src/@types/fastify.d.ts | 5 + backend-pg/src/@types/passport-gitlab2.d.ts | 1 + backend-pg/src/db/seeds/1-user.ts | 3 +- backend-pg/src/db/seeds/2-org.ts | 1 + backend-pg/src/lib/config/env.ts | 16 +- backend-pg/src/lib/config/request.ts | 10 + backend-pg/src/lib/requests/github.ts | 18 + backend-pg/src/server/routes/v1/index.ts | 3 + backend-pg/src/server/routes/v1/sso-router.ts | 260 ++++++++++++ .../src/services/auth/auth-login-service.ts | 50 +++ .../src/services/auth/auth-login-type.ts | 11 + 13 files changed, 756 insertions(+), 3 deletions(-) create mode 100644 backend-pg/src/@types/passport-gitlab2.d.ts create mode 100644 backend-pg/src/lib/config/request.ts create mode 100644 backend-pg/src/lib/requests/github.ts create mode 100644 backend-pg/src/server/routes/v1/sso-router.ts diff --git a/backend-pg/package-lock.json b/backend-pg/package-lock.json index 97eaaa114..6f272fe32 100644 --- a/backend-pg/package-lock.json +++ b/backend-pg/package-lock.json @@ -13,10 +13,14 @@ "@fastify/cookie": "^9.2.0", "@fastify/cors": "^8.4.1", "@fastify/helmet": "^11.1.1", + "@fastify/passport": "^2.4.0", "@fastify/rate-limit": "^9.0.0", + "@fastify/session": "^10.7.0", "@fastify/swagger": "^8.12.0", "@fastify/swagger-ui": "^1.10.1", "@ucast/mongo2js": "^1.3.4", + "axios": "^1.6.2", + "axios-retry": "^4.0.0", "bcrypt": "^5.1.1", "dotenv": "^16.3.1", "eslint-config-airbnb-typescript": "^17.1.0", @@ -28,6 +32,9 @@ "knex": "^3.0.1", "nodemailer": "^6.9.7", "ora": "^7.0.1", + "passport-github": "^1.1.0", + "passport-gitlab2": "^5.0.0", + "passport-google-oauth20": "^2.0.0", "pg": "^8.11.3", "picomatch": "^3.0.1", "pino": "^8.16.2", @@ -40,6 +47,8 @@ "@types/jsrp": "^0.2.6", "@types/node": "^20.9.5", "@types/nodemailer": "^6.4.14", + "@types/passport-github": "^1.1.12", + "@types/passport-google-oauth20": "^2.0.14", "@types/picomatch": "^2.3.3", "@types/prompt-sync": "^4.2.3", "@typescript-eslint/eslint-plugin": "^6.13.2", @@ -589,6 +598,14 @@ "fast-json-stringify": "^5.7.0" } }, + "node_modules/@fastify/flash": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@fastify/flash/-/flash-5.1.0.tgz", + "integrity": "sha512-8/MwOWkky0RsSgSVRcpoY8Q+lGj+vx/QF60E0Opp+92KtLFWldr6eWUL+gpGJNmQiodsKCr0osjKIjySuUuM/g==", + "dependencies": { + "fastify-plugin": "^4.0.0" + } + }, "node_modules/@fastify/helmet": { "version": "11.1.1", "resolved": "https://registry.npmjs.org/@fastify/helmet/-/helmet-11.1.1.tgz", @@ -598,6 +615,15 @@ "helmet": "^7.0.0" } }, + "node_modules/@fastify/passport": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/@fastify/passport/-/passport-2.4.0.tgz", + "integrity": "sha512-ad/Bg8mi9qrB2jqx63+t6rwUr4KtJzAUj7P+OIObq8zX/LhPz8OyHg8Ou9oyevSo3vZHA8YFmZvLExP4Xwmlhw==", + "dependencies": { + "@fastify/flash": "^5.0.0", + "fastify-plugin": "^4.0.0" + } + }, "node_modules/@fastify/rate-limit": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-9.0.0.tgz", @@ -620,6 +646,15 @@ "mime": "^3.0.0" } }, + "node_modules/@fastify/session": { + "version": "10.7.0", + "resolved": "https://registry.npmjs.org/@fastify/session/-/session-10.7.0.tgz", + "integrity": "sha512-ECA75gnyaxcyIukgyO2NGT3XdbLReNl/pTKrrkRfDc6pVqNtdptwwfx9KXrIMOfsO4B3m84eF3wZ9GgnebiZ4w==", + "dependencies": { + "fastify-plugin": "^4.0.0", + "safe-stable-stringify": "^2.3.1" + } + }, "node_modules/@fastify/static": { "version": "6.12.0", "resolved": "https://registry.npmjs.org/@fastify/static/-/static-6.12.0.tgz", @@ -1064,6 +1099,55 @@ "@types/node": "*" } }, + "node_modules/@types/body-parser": { + "version": "1.19.5", + "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.5.tgz", + "integrity": "sha512-fB3Zu92ucau0iQ0JMCFQE7b/dv8Ot07NI3KaZIkIUNXq82k4eBAqUaneXfleGY9JWskeS9y+u0nXMyspcuQrCg==", + "dev": true, + "dependencies": { + "@types/connect": "*", + "@types/node": "*" + } + }, + "node_modules/@types/connect": { + "version": "3.4.38", + "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", + "integrity": "sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/express": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.21.tgz", + "integrity": "sha512-ejlPM315qwLpaQlQDTjPdsUFSc6ZsP4AN6AlWnogPjQ7CVi7PYF3YVz+CY3jE2pwYf7E/7HlDAN0rV2GxTG0HQ==", + "dev": true, + "dependencies": { + "@types/body-parser": "*", + "@types/express-serve-static-core": "^4.17.33", + "@types/qs": "*", + "@types/serve-static": "*" + } + }, + "node_modules/@types/express-serve-static-core": { + "version": "4.17.41", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.17.41.tgz", + "integrity": "sha512-OaJ7XLaelTgrvlZD8/aa0vvvxZdUmlCn6MtWeB7TkiKW70BQLc9XEPpDLPdbo52ZhXUCrznlWdCHWxJWtdyajA==", + "dev": true, + "dependencies": { + "@types/node": "*", + "@types/qs": "*", + "@types/range-parser": "*", + "@types/send": "*" + } + }, + "node_modules/@types/http-errors": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", + "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "dev": true + }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -1089,6 +1173,12 @@ "integrity": "sha512-2h3tFvkbHksiNcDiUdcJ08gXWG10fnahp30GJ2Tbt4vd4pfsbfkoKTaTbYykFoppaJ6DL3914nQ3PU1vVIlBRQ==", "dev": true }, + "node_modules/@types/mime": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@types/mime/-/mime-1.3.5.tgz", + "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==", + "dev": true + }, "node_modules/@types/node": { "version": "20.9.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.9.5.tgz", @@ -1107,6 +1197,57 @@ "@types/node": "*" } }, + "node_modules/@types/oauth": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/@types/oauth/-/oauth-0.9.4.tgz", + "integrity": "sha512-qk9orhti499fq5XxKCCEbd0OzdPZuancneyse3KtR+vgMiHRbh+mn8M4G6t64ob/Fg+GZGpa565MF/2dKWY32A==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/passport": { + "version": "1.0.16", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.16.tgz", + "integrity": "sha512-FD0qD5hbPWQzaM0wHUnJ/T0BBCJBxCeemtnCwc/ThhTg3x9jfrAcRUmj5Dopza+MfFS9acTe3wk7rcVnRIp/0A==", + "dev": true, + "dependencies": { + "@types/express": "*" + } + }, + "node_modules/@types/passport-github": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/@types/passport-github/-/passport-github-1.1.12.tgz", + "integrity": "sha512-VJpMEIH+cOoXB694QgcxuvWy2wPd1Oq3gqrg2Y9DMVBYs9TmH9L14qnqPDZsNMZKBDH+SvqRsGZj9SgHYeDgcA==", + "dev": true, + "dependencies": { + "@types/express": "*", + "@types/passport": "*", + "@types/passport-oauth2": "*" + } + }, + "node_modules/@types/passport-google-oauth20": { + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/@types/passport-google-oauth20/-/passport-google-oauth20-2.0.14.tgz", + "integrity": "sha512-ZaZpRUAeMl3vy298ulKO1wGLn9SQtj/CyIfZL/Px5xU9pybMiQU3mhXDCBiWSbg0EK9uXT4ZoWC3ktuWY+5fwQ==", + "dev": true, + "dependencies": { + "@types/express": "*", + "@types/passport": "*", + "@types/passport-oauth2": "*" + } + }, + "node_modules/@types/passport-oauth2": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@types/passport-oauth2/-/passport-oauth2-1.4.15.tgz", + "integrity": "sha512-9cUTP/HStNSZmhxXGuRrBJfEWzIEJRub2eyJu3CvkA+8HAMc9W3aKdFhVq+Qz1hi42qn+GvSAnz3zwacDSYWpw==", + "dev": true, + "dependencies": { + "@types/express": "*", + "@types/oauth": "*", + "@types/passport": "*" + } + }, "node_modules/@types/picomatch": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-2.3.3.tgz", @@ -1119,11 +1260,44 @@ "integrity": "sha512-Ox77gCSx0YyeakGt/qfOZUSFNSSi+sh3ABoGOiCwiO2KODx492BJnUm9oIXS+AHJtqp12iM4RduY6viTJ9bYwA==", "dev": true }, + "node_modules/@types/qs": { + "version": "6.9.10", + "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.10.tgz", + "integrity": "sha512-3Gnx08Ns1sEoCrWssEgTSJs/rsT2vhGP+Ja9cnnk9k4ALxinORlQneLXFeFKOTJMOeZUFD1s7w+w2AphTpvzZw==", + "dev": true + }, + "node_modules/@types/range-parser": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@types/range-parser/-/range-parser-1.2.7.tgz", + "integrity": "sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==", + "dev": true + }, "node_modules/@types/semver": { "version": "7.5.6", "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.6.tgz", "integrity": "sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==" }, + "node_modules/@types/send": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", + "integrity": "sha512-x2EM6TJOybec7c52BX0ZspPodMsQUd5L6PRwOunVyVUhXiBSKf3AezDL8Dgvgt5o0UfKNfuA0eMLr2wLT4AiBA==", + "dev": true, + "dependencies": { + "@types/mime": "^1", + "@types/node": "*" + } + }, + "node_modules/@types/serve-static": { + "version": "1.15.5", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.5.tgz", + "integrity": "sha512-PDRk21MnK70hja/YF8AHfC7yIsiQHn1rcXx7ijCFBX/k+XQJhQT/gw3xekXKJvx+5SXaMMS8oqQy09Mzvz2TuQ==", + "dev": true, + "dependencies": { + "@types/http-errors": "*", + "@types/mime": "*", + "@types/node": "*" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "6.13.2", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.13.2.tgz", @@ -1743,6 +1917,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/atomic-sleep": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", @@ -1793,6 +1972,27 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, + "node_modules/axios": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/axios-retry": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-4.0.0.tgz", + "integrity": "sha512-F6P4HVGITD/v4z9Lw2mIA24IabTajvpDZmKa6zq/gGwn57wN5j1P3uWrAV0+diqnW6kTM2fTqmWNfgYWGmMuiA==", + "dependencies": { + "is-retry-allowed": "^2.2.0" + }, + "peerDependencies": { + "axios": "0.x || 1.x" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -1817,6 +2017,14 @@ } ] }, + "node_modules/base64url": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/base64url/-/base64url-3.0.1.tgz", + "integrity": "sha512-ir1UPr3dkwexU7FdV8qBBbNDRUhMmIekYMFZfi+C/sLNnRESKPl23nB9b2pltqfOQNnGzsDdId90AEtG5tCx4A==", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/bcrypt": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz", @@ -2085,6 +2293,17 @@ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", "dev": true }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "10.0.1", "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", @@ -2263,6 +2482,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/delegates": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", @@ -3261,6 +3488,25 @@ "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==" }, + "node_modules/follow-redirects": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", @@ -3269,6 +3515,19 @@ "is-callable": "^1.1.3" } }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -4118,6 +4377,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/is-retry-allowed": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/is-retry-allowed/-/is-retry-allowed-2.2.0.tgz", + "integrity": "sha512-XVm7LOeLpTW4jV19QSH38vkswxoLud8sQ57YwJVTPWdiaI9I8keEhGFpBlslyVsgdQy4Opg8QOLb8YRgsyZiQg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-shared-array-buffer": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.2.tgz", @@ -4662,6 +4932,25 @@ "node": ">=10.0.0" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", @@ -4898,6 +5187,11 @@ "set-blocking": "^2.0.0" } }, + "node_modules/oauth": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", + "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==" + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -5135,6 +5429,66 @@ "node": ">=6" } }, + "node_modules/passport-github": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/passport-github/-/passport-github-1.1.0.tgz", + "integrity": "sha512-XARXJycE6fFh/dxF+Uut8OjlwbFEXgbPVj/+V+K7cvriRK7VcAOm+NgBmbiLM9Qv3SSxEAV+V6fIk89nYHXa8A==", + "dependencies": { + "passport-oauth2": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/passport-gitlab2": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/passport-gitlab2/-/passport-gitlab2-5.0.0.tgz", + "integrity": "sha512-cXQMgM6JQx9wHVh7JLH30D8fplfwjsDwRz+zS0pqC8JS+4bNmc1J04NGp5g2M4yfwylH9kQRrMN98GxMw7q7cg==", + "dependencies": { + "passport-oauth2": "^1.4.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/passport-google-oauth20": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/passport-google-oauth20/-/passport-google-oauth20-2.0.0.tgz", + "integrity": "sha512-KSk6IJ15RoxuGq7D1UKK/8qKhNfzbLeLrG3gkLZ7p4A6DBCcv7xpyQwuXtWdpyR0+E0mwkpjY1VfPOhxQrKzdQ==", + "dependencies": { + "passport-oauth2": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/passport-oauth2": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/passport-oauth2/-/passport-oauth2-1.7.0.tgz", + "integrity": "sha512-j2gf34szdTF2Onw3+76alNnaAExlUmHvkc7cL+cmaS5NzHzDP/BvFHJruueQ9XAeNOdpI+CH+PWid8RA7KCwAQ==", + "dependencies": { + "base64url": "3.x.x", + "oauth": "0.9.x", + "passport-strategy": "1.x.x", + "uid2": "0.0.x", + "utils-merge": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/jaredhanson" + } + }, + "node_modules/passport-strategy": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/passport-strategy/-/passport-strategy-1.0.0.tgz", + "integrity": "sha512-CB97UUvDKJde2V0KDWWB3lyf6PC3FaZP7YxZ2G8OAtn9p4HI9j9JLP9qjOGZFvyl8uwNT8qM+hGnz/n16NI7oA==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -5463,6 +5817,11 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/pstree.remy": { "version": "1.1.8", "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", @@ -6517,6 +6876,11 @@ "node": ">=0.8.0" } }, + "node_modules/uid2": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.4.tgz", + "integrity": "sha512-IevTus0SbGwQzYh3+fRsAMTVVPOoIVufzacXcHPmdlle1jUpq7BRL+mw3dgeLanvGZdwwbWhRV6XrcFNdBmjWA==" + }, "node_modules/unbox-primitive": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.0.2.tgz", @@ -6565,6 +6929,14 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", diff --git a/backend-pg/package.json b/backend-pg/package.json index 51b30aa9a..717f74acd 100644 --- a/backend-pg/package.json +++ b/backend-pg/package.json @@ -30,6 +30,8 @@ "@types/jsrp": "^0.2.6", "@types/node": "^20.9.5", "@types/nodemailer": "^6.4.14", + "@types/passport-github": "^1.1.12", + "@types/passport-google-oauth20": "^2.0.14", "@types/picomatch": "^2.3.3", "@types/prompt-sync": "^4.2.3", "@typescript-eslint/eslint-plugin": "^6.13.2", @@ -53,10 +55,14 @@ "@fastify/cookie": "^9.2.0", "@fastify/cors": "^8.4.1", "@fastify/helmet": "^11.1.1", + "@fastify/passport": "^2.4.0", "@fastify/rate-limit": "^9.0.0", + "@fastify/session": "^10.7.0", "@fastify/swagger": "^8.12.0", "@fastify/swagger-ui": "^1.10.1", "@ucast/mongo2js": "^1.3.4", + "axios": "^1.6.2", + "axios-retry": "^4.0.0", "bcrypt": "^5.1.1", "dotenv": "^16.3.1", "eslint-config-airbnb-typescript": "^17.1.0", @@ -68,6 +74,9 @@ "knex": "^3.0.1", "nodemailer": "^6.9.7", "ora": "^7.0.1", + "passport-github": "^1.1.0", + "passport-gitlab2": "^5.0.0", + "passport-google-oauth20": "^2.0.0", "pg": "^8.11.3", "picomatch": "^3.0.1", "pino": "^8.16.2", diff --git a/backend-pg/src/@types/fastify.d.ts b/backend-pg/src/@types/fastify.d.ts index d8d2b802f..b5d1af01c 100644 --- a/backend-pg/src/@types/fastify.d.ts +++ b/backend-pg/src/@types/fastify.d.ts @@ -29,6 +29,11 @@ declare module "fastify" { tokenVersionId: string; // the session id of token used user: TUsers; }; + // passport data + passportUser: { + isCompleted: string; + providerAuthToken: string; + }; } interface FastifyInstance { diff --git a/backend-pg/src/@types/passport-gitlab2.d.ts b/backend-pg/src/@types/passport-gitlab2.d.ts new file mode 100644 index 000000000..278a8fb09 --- /dev/null +++ b/backend-pg/src/@types/passport-gitlab2.d.ts @@ -0,0 +1 @@ +declare module "passport-gitlab2"; diff --git a/backend-pg/src/db/seeds/1-user.ts b/backend-pg/src/db/seeds/1-user.ts index c5166e3b7..6ca3caf17 100644 --- a/backend-pg/src/db/seeds/1-user.ts +++ b/backend-pg/src/db/seeds/1-user.ts @@ -1,6 +1,7 @@ import { Knex } from "knex"; -import { TableName } from "../schemas"; + import { AuthMethod } from "../../services/auth/auth-type"; +import { TableName } from "../schemas"; export const testUser = { email: "test@localhost.local" diff --git a/backend-pg/src/db/seeds/2-org.ts b/backend-pg/src/db/seeds/2-org.ts index fbf606c20..07f00ed7c 100644 --- a/backend-pg/src/db/seeds/2-org.ts +++ b/backend-pg/src/db/seeds/2-org.ts @@ -1,4 +1,5 @@ import { Knex } from "knex"; + import { OrgMembershipRole, OrgMembershipStatus, TableName } from "../schemas"; import { testUser } from "./1-user"; diff --git a/backend-pg/src/lib/config/env.ts b/backend-pg/src/lib/config/env.ts index 12951232c..6587bcc9e 100644 --- a/backend-pg/src/lib/config/env.ts +++ b/backend-pg/src/lib/config/env.ts @@ -27,14 +27,26 @@ const envSchema = z SMTP_PASSWORD: zpStr(z.string().optional()), SMTP_FROM_ADDRESS: zpStr(z.string().optional()), SMTP_FROM_NAME: zpStr(z.string().optional().default("Infisical")), - COOKIE_SECRET_SIGN_KEY: z.string().default("g5giLbOMpaJhqEogXApkiw2ZFW5Q0jvA"), + COOKIE_SECRET_SIGN_KEY: z + .string() + .min(32) + .default("#5VihU%rbXHcHwWwCot5L3vyPsx$7dWYw^iGk!EJg2bC*f$PD$%KCqx^R@#^LSEf"), SITE_URL: zpStr(z.string().optional()), // jwt options JWT_AUTH_SECRET: zpStr(z.string()), JWT_AUTH_LIFETIME: zpStr(z.string().default("10d")), JWT_SIGNUP_LIFETIME: zpStr(z.string().default("15m")), JWT_REFRESH_LIFETIME: zpStr(z.string().default("90d")), - JWT_MFA_LIFETIME: zpStr(z.string().default("5m")) + JWT_MFA_LIFETIME: zpStr(z.string().default("5m")), + JWT_PROVIDER_AUTH_LIFETIME: zpStr(z.string().default("15m")), + // Oauth + CLIENT_ID_GOOGLE_LOGIN: zpStr(z.string().optional()), + CLIENT_SECRET_GOOGLE_LOGIN: zpStr(z.string().optional()), + CLIENT_ID_GITHUB_LOGIN: zpStr(z.string().optional()), + CLIENT_SECRET_GITHUB_LOGIN: zpStr(z.string().optional()), + CLIENT_ID_GITLAB_LOGIN: zpStr(z.string().optional()), + CLIENT_SECRET_GITLAB_LOGIN: zpStr(z.string().optional()), + CLIENT_GITLAB_LOGIN_URL: zpStr(z.string().optional()) }) .transform((data) => ({ ...data, isSmtpConfigured: Boolean(data.SMTP_HOST) })); diff --git a/backend-pg/src/lib/config/request.ts b/backend-pg/src/lib/config/request.ts new file mode 100644 index 000000000..091713727 --- /dev/null +++ b/backend-pg/src/lib/config/request.ts @@ -0,0 +1,10 @@ +import axios from "axios"; +import axiosRetry from "axios-retry"; + +export const request = axios.create(); + +axiosRetry(request, { + retries: 3, + retryDelay: axiosRetry.exponentialDelay, + retryCondition: (err) => axiosRetry.isNetworkError(err) || axiosRetry.isRetryableError(err) +}); diff --git a/backend-pg/src/lib/requests/github.ts b/backend-pg/src/lib/requests/github.ts new file mode 100644 index 000000000..723e4957a --- /dev/null +++ b/backend-pg/src/lib/requests/github.ts @@ -0,0 +1,18 @@ +import { request } from "../config/request"; + +const INTEGRATION_GITHUB_API_URL = "https://api.github.com"; +type TGithubEmail = { + email: string; + primary: boolean; + verified: boolean; + visibility: null | string; +}; + +export const fetchGithubEmails = async (accessToken: string) => { + const { data } = await request.get(`${INTEGRATION_GITHUB_API_URL}/user/emails`, { + headers: { + Authorization: `Bearer ${accessToken}` + } + }); + return data; +}; diff --git a/backend-pg/src/server/routes/v1/index.ts b/backend-pg/src/server/routes/v1/index.ts index 2be02f37b..12fa0d96a 100644 --- a/backend-pg/src/server/routes/v1/index.ts +++ b/backend-pg/src/server/routes/v1/index.ts @@ -3,11 +3,14 @@ import { registerAuthRoutes } from "./auth-router"; import { registerInviteOrgRouter } from "./invite-org-router"; import { registerOrgRouter } from "./organization-router"; import { registerPasswordRouter } from "./password-router"; +import { registerSsoRouter } from "./sso-router"; import { registerUserActionRouter } from "./user-action-router"; import { registerUserRouter } from "./user-router"; export const registerV1Routes = async (server: FastifyZodProvider) => { + await server.register(registerSsoRouter, { prefix: "/sso" }); await server.register(registerAuthRoutes, { prefix: "/auth" }); + // await server.register(registerSSORouter, { prefix: "/sso" }); await server.register(registerPasswordRouter, { prefix: "/password" }); await server.register(registerOrgRouter, { prefix: "/organization" }); await server.register(registerAdminRouter, { prefix: "/admin" }); diff --git a/backend-pg/src/server/routes/v1/sso-router.ts b/backend-pg/src/server/routes/v1/sso-router.ts new file mode 100644 index 000000000..a01aaa797 --- /dev/null +++ b/backend-pg/src/server/routes/v1/sso-router.ts @@ -0,0 +1,260 @@ +import { Strategy as GitHubStrategy } from "passport-github"; +import { Strategy as GitLabStrategy } from "passport-gitlab2"; +import { Strategy as GoogleStrategy } from "passport-google-oauth20"; +import { z } from "zod"; +import { Authenticator } from "@fastify/passport"; +import fastifySession from "@fastify/session"; + +import { getConfig } from "@app/lib/config/env"; +import { BadRequestError } from "@app/lib/errors"; +import { fetchGithubEmails } from "@app/lib/requests/github"; +import { AuthMethod } from "@app/services/auth/auth-type"; + +export const registerSsoRouter = async (server: FastifyZodProvider) => { + const appCfg = getConfig(); + const passport = new Authenticator({ key: "sso", userProperty: "passportUser" }); + await server.register(fastifySession, { secret: appCfg.COOKIE_SECRET_SIGN_KEY }); + await server.register(passport.initialize()); + await server.register(passport.secureSession()); + + // passport oauth strategy for Google + const isGoogleOauthActive = Boolean( + appCfg.CLIENT_ID_GOOGLE_LOGIN && appCfg.CLIENT_SECRET_GOOGLE_LOGIN + ); + if (isGoogleOauthActive) { + passport.use( + new GoogleStrategy( + { + passReqToCallback: true, + clientID: appCfg.CLIENT_ID_GOOGLE_LOGIN as string, + clientSecret: appCfg.CLIENT_SECRET_GOOGLE_LOGIN as string, + callbackURL: "/api/v1/sso/google", + scope: ["profile", " email"] + }, + async (req, _accessToken, _refreshToken, profile, cb) => { + try { + const email = profile?.emails?.[0]?.value; + const serverCfg = server.services.superAdmin.getServerCfg(); + if (!email) + throw new BadRequestError({ + message: "Email not found", + name: "Oauth Google Register" + }); + + const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ + email, + firstName: profile?.name?.givenName || "", + lastName: profile?.name?.familyName || "", + authMethod: AuthMethod.GOOGLE, + callbackPort: req.query.state as string, + isSignupAllowed: Boolean(serverCfg.allowSignUp) + }); + cb(null, { isUserCompleted, providerAuthToken }); + } catch (error) { + cb(null, false); + } + } + ) + ); + } + + // Passport strategy for Github + const isGithubOauthActive = Boolean( + appCfg.CLIENT_SECRET_GITHUB_LOGIN && appCfg.CLIENT_ID_GITLAB_LOGIN + ); + if (isGithubOauthActive) { + passport.use( + new GitHubStrategy( + { + passReqToCallback: true, + clientID: appCfg.CLIENT_ID_GITHUB_LOGIN as string, + clientSecret: appCfg.CLIENT_SECRET_GITHUB_LOGIN as string, + callbackURL: "/api/v1/sso/github", + scope: ["user:email"] + }, + async (req, accessToken, _refreshToken, profile, cb) => { + const ghEmails = await fetchGithubEmails(accessToken); + const { email } = ghEmails.filter((gitHubEmail) => gitHubEmail.primary)[0]; + + const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ + email, + firstName: profile.displayName, + lastName: "", + authMethod: AuthMethod.GITHUB, + callbackPort: req.query.state as string + }); + + return cb(null, { isUserCompleted, providerAuthToken }); + } + ) + ); + } + + // passport strategy for gitlab + const isGitlabOauthActive = Boolean( + appCfg.CLIENT_ID_GITLAB_LOGIN && + appCfg.CLIENT_SECRET_GITLAB_LOGIN && + appCfg.CLIENT_GITLAB_LOGIN_URL + ); + if (isGitlabOauthActive) { + passport.use( + new GitLabStrategy( + { + passReqToCallback: true, + clientID: appCfg.CLIENT_ID_GITLAB_LOGIN, + clientSecret: appCfg.CLIENT_SECRET_GITLAB_LOGIN, + callbackURL: "/api/v1/sso/gitlab", + baseURL: appCfg.CLIENT_GITLAB_LOGIN_URL + }, + async (req: any, _accessToken: string, _refreshToken: string, profile: any, cb: any) => { + const email = profile.emails[0].value; + const { isUserCompleted, providerAuthToken } = await server.services.login.oauth2Login({ + email, + firstName: profile.displayName, + lastName: "", + authMethod: AuthMethod.GITLAB, + callbackPort: req.query.state as string + }); + + return cb(null, { isUserCompleted, providerAuthToken }); + } + ) + ); + } + + server.route({ + url: "/sso/redirect/google", + method: "GET", + schema: { + querystring: z.object({ + callback_port: z.string().optional() + }) + }, + preValidation: (req, res) => + ( + passport.authenticate("google", { + scope: ["profile", "email"], + session: false, + state: req.query.callback_port, + authInfo: false + // this is due to zod type difference + }) as any + )(req, res), + handler: () => {} + }); + + server.route({ + url: "/sso/google", + method: "GET", + preValidation: passport.authenticate("google", { + session: false, + failureRedirect: "/login/provider/error", + authInfo: false + // this is due to zod type difference + }) as any, + handler: (req, res) => { + if (req.passportUser.isCompleted) { + return res.redirect( + `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + return res.redirect( + `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + }); + + server.route({ + url: "/sso/redirect/github", + method: "GET", + schema: { + querystring: z.object({ + callback_port: z.string().optional() + }) + }, + preValidation: (req, res) => + ( + passport.authenticate("github", { + session: false, + state: req.query.callback_port, + authInfo: false + // this is due to zod type difference + }) as any + )(req, res), + handler: () => {} + }); + + server.route({ + url: "/sso/github", + method: "GET", + preValidation: passport.authenticate("github", { + session: false, + failureRedirect: "/login/provider/error", + authInfo: false + // this is due to zod type difference + }) as any, + handler: (req, res) => { + if (req.passportUser.isCompleted) { + return res.redirect( + `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + return res.redirect( + `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + }); + + server.route({ + url: "/sso/redirect/gitlab", + method: "GET", + schema: { + querystring: z.object({ + callback_port: z.string().optional() + }) + }, + preValidation: (req, res) => + ( + passport.authenticate("gitlab", { + session: false, + state: req.query.callback_port, + authInfo: false + // this is due to zod type difference + }) as any + )(req, res), + handler: () => {} + }); + + server.route({ + url: "/sso/gitlab", + method: "GET", + preValidation: passport.authenticate("gitlab", { + session: false, + failureRedirect: "/login/provider/error", + authInfo: false + // this is due to zod type difference + }) as any, + handler: (req, res) => { + if (req.passportUser.isCompleted) { + return res.redirect( + `${appCfg.SITE_URL}/login/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + return res.redirect( + `${appCfg.SITE_URL}/signup/sso?token=${encodeURIComponent( + req.passportUser.providerAuthToken + )}` + ); + } + }); +}; diff --git a/backend-pg/src/services/auth/auth-login-service.ts b/backend-pg/src/services/auth/auth-login-service.ts index 989980691..c8700d07c 100644 --- a/backend-pg/src/services/auth/auth-login-service.ts +++ b/backend-pg/src/services/auth/auth-login-service.ts @@ -3,6 +3,7 @@ import jwt from "jsonwebtoken"; import { TUsers, UserDeviceSchema } from "@app/db/schemas"; import { getConfig } from "@app/lib/config/env"; import { generateSrpServerKey, srpCheckClientProof } from "@app/lib/crypto"; +import { BadRequestError } from "@app/lib/errors"; import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service"; import { TokenType } from "../auth-token/auth-token-types"; @@ -11,6 +12,7 @@ import { TUserDalFactory } from "../user/user-dal"; import { TLoginClientProofDTO, TLoginGenServerPublicKeyDTO, + TOauthLoginDTO, TVerifyMfaTokenDTO } from "./auth-login-type"; import { AuthMethod, AuthTokenType } from "./auth-type"; @@ -228,6 +230,53 @@ export const authLoginServiceFactory = ({ const token = await generateUserTokens({ ...userEnc, id: userEnc.userId }, ip, userAgent); return { token, user: userEnc }; }; + /* + * OAuth2 login for google,github, and other oauth2 provider + * */ + const oauth2Login = async ({ + email, + firstName, + lastName, + authMethod, + callbackPort, + isSignupAllowed + }: TOauthLoginDTO) => { + let user = await userDal.findUserByEmail(email); + const appCfg = getConfig(); + const isOauthSignUpDisabled = !isSignupAllowed && !user; + if (isOauthSignUpDisabled) + throw new BadRequestError({ message: "User signup disabled", name: "Oauth 2 login" }); + + if (!user) { + user = await userDal.create({ email, firstName, lastName, authMethods: [authMethod] }); + } + const isLinkingRequired = !user?.authMethods?.includes(authMethod); + const isUserCompleted = user.isAccepted; + + const providerAuthToken = jwt.sign( + { + authTokenType: AuthTokenType.PROVIDER_TOKEN, + userId: user.id, + email: user.email, + firstName: user.firstName, + lastName: user.lastName, + authMethod, + isUserCompleted, + isLinkingRequired, + ...(callbackPort + ? { + callbackPort + } + : {}) + }, + appCfg.JWT_AUTH_SECRET, + { + expiresIn: appCfg.JWT_PROVIDER_AUTH_LIFETIME + } + ); + + return { isUserCompleted, providerAuthToken }; + }; /* * logout user by incrementing the version by 1 meaning any old session will become invalid @@ -241,6 +290,7 @@ export const authLoginServiceFactory = ({ loginGenServerPublicKey, loginExchangeClientProof, logout, + oauth2Login, resendMfaToken, verifyMfaToken, generateUserTokens diff --git a/backend-pg/src/services/auth/auth-login-type.ts b/backend-pg/src/services/auth/auth-login-type.ts index e17e98fe1..3d67fef87 100644 --- a/backend-pg/src/services/auth/auth-login-type.ts +++ b/backend-pg/src/services/auth/auth-login-type.ts @@ -1,3 +1,5 @@ +import { AuthMethod } from "./auth-type"; + export type TLoginGenServerPublicKeyDTO = { email: string; clientPublicKey: string; @@ -18,3 +20,12 @@ export type TVerifyMfaTokenDTO = { ip: string; userAgent: string; }; + +export type TOauthLoginDTO = { + email: string; + firstName: string; + lastName?: string; + authMethod: AuthMethod; + callbackPort?: string; + isSignupAllowed?: boolean; +};