This commit is contained in:
Benjamin Toby
2024-12-05 08:03:33 +01:00
parent 9686a22c96
commit 3ffd2d6777
821 changed files with 3251 additions and 91996 deletions
@@ -1,236 +1,28 @@
"use strict";
(() => {
var exports = {};
exports.id = 3363;
exports.ids = [3363];
exports.modules = {
/***/ 3785:
/***/ ((module) => {
module.exports = require("generate-password");
/***/ }),
/***/ 6517:
/***/ ((module) => {
module.exports = require("lodash");
/***/ }),
/***/ 2261:
/***/ ((module) => {
module.exports = require("serverless-mysql");
/***/ }),
/***/ 4300:
/***/ ((module) => {
module.exports = require("buffer");
/***/ }),
/***/ 2081:
/***/ ((module) => {
module.exports = require("child_process");
/***/ }),
/***/ 6113:
/***/ ((module) => {
module.exports = require("crypto");
/***/ }),
/***/ 7147:
/***/ ((module) => {
module.exports = require("fs");
/***/ }),
/***/ 3685:
/***/ ((module) => {
module.exports = require("http");
/***/ }),
/***/ 1017:
/***/ ((module) => {
module.exports = require("path");
/***/ }),
/***/ 8210:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6517);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2081);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7547);
/* harmony import */ var _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6__);
// @ts-check
const fs = __webpack_require__(7147);
const generator = __webpack_require__(3785);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
"use strict";(()=>{var e={};e.id=7889,e.ids=[7889],e.modules={47795:e=>{e.exports=require("generate-password")},27825:e=>{e.exports=require("lodash")},75600:e=>{e.exports=require("next/dist/compiled/next-server/pages-api.runtime.prod.js")},9973:e=>{e.exports=require("serverless-mysql")},79428:e=>{e.exports=require("buffer")},79646:e=>{e.exports=require("child_process")},55511:e=>{e.exports=require("crypto")},29021:e=>{e.exports=require("fs")},81630:e=>{e.exports=require("http")},33873:e=>{e.exports=require("path")},96762:(e,r)=>{Object.defineProperty(r,"M",{enumerable:!0,get:function(){return function e(r,t){return t in r?r[t]:"then"in r&&"function"==typeof r.then?r.then(r=>e(r,t)):"function"==typeof r&&"default"===t?r:void 0}}})},66650:(e,r,t)=>{t.r(r),t.d(r,{config:()=>R,default:()=>y,routeModule:()=>A});var s={};t.r(s),t.d(s,{default:()=>g});var n=t(89947),a=t(2706),o=t(96762),i=t(6420),l=t.n(i),c=t(77538),u=t.n(c);t(27825);var p=t(33873),d=t.n(p),f=t(79646),m=t(51348),S=t.n(m),h=t(82703),E=t.n(h);t(29021);let _=t(47795);async function g(e,r){if("POST"!==e.method)return r.json({user:null,msg:"Registration Failed!"});let t=await l()(e,r,!0);if(!t)return r.json({success:!1,msg:"Unauthorized"});let{data:s,edit:n,grants:a}=e.body;try{let e=process.env.DSQL_DB_HOST||"127.0.0.1",n=`dsql_user_${t.id}`,{host:o,password:i}=s;if(!o.match(/./))throw Error("Invalid host");if(o.match(/^%$/))throw Error("Cannot set a catch-all host for this user.");let l=String(o).replace(/[^a-zA-Z0-9-\.\:\/\%]/g,""),c=i?.match(/./)?i:_.generate({length:16,numbers:!0,symbols:!0,uppercase:!0,exclude:"*#.'`\""}),u=await S()("SELECT * FROM mysql.user WHERE User = ? AND (Host = ? OR Host = ?)",[n,l,e]);if(u?.[0]?.User)throw Error("SQL User already exists. Remember if you have the '%' host on your primary user, it catches all other hosts.");if(l.match(/^%$/))throw Error("Can't create a catch-all host for this username. Catch-all host is only allowed on the primary user.");let p=await S()("SELECT COUNT(*) FROM mariadb_users WHERE user_id = ?",[t.id]);if(p?.[0]?.["COUNT(*)"]>=10)throw Error("User limit reached");let m=E()(c),h=await S()("INSERT INTO mariadb_users (user_id, username, host, password, grants) VALUES (?, ?, ?, ?, ?)",[t.id,n,l,m,JSON.stringify(a)]);if(!h?.insertId)throw Error("Error in adding SQL user");let g=d().resolve(process.cwd(),"./shell/mariadb-users");(0,f.execSync)(`node refreshUsersAndGrants.js --userId ${t.id} --username ${n} --host ${l}`,{cwd:g}),r.json({success:!0})}catch(e){console.log("Create MariaDB user ERROR:",e.message),u()({component:"/api/acceptUserInvitation/catch-error",message:e.message,user:t}),r.json({success:!1,msg:"Error in adding SQL user =>"+e.message,err:e.message})}}let y=(0,o.M)(s,"default"),R=(0,o.M)(s,"config"),A=new n.PagesAPIRouteModule({definition:{kind:a.A.PAGES_API,page:"/api/sql-users/create",pathname:"/api/sql-users/create",bundlePath:"",filename:""},userland:s})},77538:(e,r,t)=>{let s=t(29021),{IncomingMessage:n}=t(81630);e.exports=async function({user:e,message:r,component:t,noMail:n,req:a}){let o=new Date,i=(()=>{if(!a)return null;try{let e=a.headers["x-forwarded-for"],r=a.headers["x-real-ip"],t=a.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],n=t||s||r||a.socket.remoteAddress;if(!n)return null;return String(n)}catch(e){return null}})();try{let n=`🚀 SERVER ERROR ===========================
Error Message: ${r}
Component: ${t}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(n+=`
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}`),a?.url&&(n+=`
URL: ${a.url}`),a?.body&&(n+=`
Request Body: ${JSON.stringify(a.body,null,4)}`),i&&(n+=`
IP: ${i}`),n+=`
Date: ${o.toDateString()}
========================================`,s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let l=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",n),s.appendFileSync("./.tmp/error.log",`
${l}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},6420:(e,r,t)=>{t(81630);let s=t(51348),n=t(72907),a=t(29021);async function o(e,r,t,o){if(!e.cookies?.datasquirelAuthKey?.match(/./))return null;let i=n(e.cookies.datasquirelAuthKey);if(!i)return null;let l=JSON.parse(i);if(!l.csrf_k||t&&!e.headers["x-csrf-auth"]?.match(RegExp(`${l.csrf_k}`)))return null;let c=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!c)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(t&&!a.existsSync(`${c}/${l.csrf_k}`))return null;if(0==l.verification_status&&!t){let e=await s(`SELECT verification_status FROM users WHERE id='${l.id}'`);e&&e[0]&&1==e[0].verification_status&&r.setHeader("Set-Cookie",["user_refresh=1"])}return l?.date&&Date.now()-l.date>6048e5?null:l}e.exports=o},72907:(e,r,t)=>{let{scryptSync:s,createDecipheriv:n}=t(55511),{Buffer:a}=t(79428);e.exports=e=>{let r=n("aes-192-cbc",s(process.env.DSQL_ENCRYPTION_PASSWORD||"",process.env.DSQL_ENCRYPTION_SALT||"",24),a.alloc(16,0));try{let t=r.update(e,"hex","utf8");return t+=r.final("utf8")}catch(e){return null}}},82703:(e,r,t)=>{let{scryptSync:s,createCipheriv:n}=t(55511),{Buffer:a}=t(79428),o=t(48225);e.exports=(e,r,t)=>{let i=n("aes-192-cbc",s(r||process.env.DSQL_ENCRYPTION_PASSWORD||"",t||process.env.DSQL_ENCRYPTION_SALT||"",24),a.alloc(16,0));try{let r=i.update(e,"utf8","hex");return r+=i.final("hex")}catch(e){return o({component:"encrypt",message:e.message}),null}}},48225:(e,r,t)=>{let s=t(29021);e.exports=async function({user:e,message:r,component:t,noMail:n}){let a=`🚀 SERVER ERROR ===========================
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}
Error Message: ${r}
Component: ${t}
Date: ${Date()}
========================================`;s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let o=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",a),s.appendFileSync("./.tmp/error.log",`
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* API handler
* ==============================================================================
* @type {import("next").NextApiHandler}
*/ async function handler(req, res) {
/**
* Check method
*
* @description Check request method and return if invalid
*/ if (req.method !== "POST") return res.json({
user: null,
msg: "Registration Failed!"
});
/**
* User Auth
*
* @description User Auth
*/ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default()(req, res, true);
if (!user) {
return res.json({
success: false,
msg: "Unauthorized"
});
}
/**
* Validate Form
*
* @description Check if request body is valid
*/ const { data , edit , grants } = req.body;
/**
* Validate Form
*
* @description Check if request body is valid
*/ try {
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const username = `dsql_user_${user.id}`;
const { host , password } = data;
if (!host.match(/./)) {
throw new Error("Invalid host");
}
if (host.match(/^%$/)) {
throw new Error("Cannot set a catch-all host for this user.");
}
const sanitizedNewHost = String(host).replace(/[^a-zA-Z0-9-\.\:\/\%]/g, "");
const finPassword = password?.match(/./) ? password : generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\""
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const existinSQLUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5___default()(`SELECT * FROM mysql.user WHERE User = ? AND (Host = ? OR Host = ?)`, [
username,
sanitizedNewHost,
defaultMariadbUserHost
]);
const doesSQLUserExist = Boolean(existinSQLUser?.[0]?.User);
if (doesSQLUserExist) {
throw new Error("SQL User already exists. Remember if you have the '%' host on your primary user, it catches all other hosts.");
}
const absoluteHost = Boolean(sanitizedNewHost.match(/^%$/));
if (absoluteHost) {
throw new Error("Can't create a catch-all host for this username. Catch-all host is only allowed on the primary user.");
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const existingUsersCount = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5___default()(`SELECT COUNT(*) FROM mariadb_users WHERE user_id = ?`, [
user.id
]);
if (existingUsersCount?.[0]?.["COUNT(*)"] >= 10) {
throw new Error("User limit reached");
}
const encryptedPassword = _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6___default()(finPassword);
const newMariaDBUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_5___default()(`INSERT INTO mariadb_users (user_id, username, host, password, grants) VALUES (?, ?, ?, ?, ?)`, [
user.id,
username,
sanitizedNewHost,
encryptedPassword,
JSON.stringify(grants),
]);
if (!newMariaDBUser?.insertId) {
throw new Error("Error in adding SQL user");
}
const execPath = path__WEBPACK_IMPORTED_MODULE_3___default().resolve(process.cwd(), "./shell/mariadb-users");
const execSQLUserScript = (0,child_process__WEBPACK_IMPORTED_MODULE_4__.execSync)(`node refreshUsersAndGrants.js --userId ${user.id} --username ${username} --host ${sanitizedNewHost}`, {
cwd: execPath
});
res.json({
success: true
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error) {
console.log("Create MariaDB user ERROR:", error.message);
_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
component: "/api/acceptUserInvitation/catch-error",
message: error.message,
user: user
});
res.json({
success: false,
msg: "Error in adding SQL user =>" + error.message,
err: error.message
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,6825,3017,7547], () => (__webpack_exec__(8210)));
module.exports = __webpack_exports__;
})();
${o}`)}},51348:(e,r,t)=>{let s=t(9973),n=t(21580),a=s({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:process.env.DSQL_DB_NAME,port:process.env.DSQL_DB_PORT?Number(process.env.DSQL_DB_PORT):void 0,charset:"utf8mb4",ssl:n()}});async function o(...e){try{let r=await a.query(...e);return await a.end(),JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=o},21580:(e,r,t)=>{let s=t(29021);e.exports=function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let r=`${e}/ca-cert.pem`;if(!s.existsSync(r)){console.log(`${r} does not exist`);return}return{ca:s.readFileSync(`${e}/ca-cert.pem`)}}},2706:(e,r)=>{var t;Object.defineProperty(r,"A",{enumerable:!0,get:function(){return t}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE"}(t||(t={}))},89947:(e,r,t)=>{e.exports=t(75600)}};var r=require("../../../webpack-api-runtime.js");r.C(e);var t=r(r.s=66650);module.exports=t})();
File diff suppressed because one or more lines are too long
@@ -1,168 +1,16 @@
"use strict";
(() => {
var exports = {};
exports.id = 7049;
exports.ids = [7049];
exports.modules = {
/***/ 6517:
/***/ ((module) => {
module.exports = require("lodash");
/***/ }),
/***/ 2261:
/***/ ((module) => {
module.exports = require("serverless-mysql");
/***/ }),
/***/ 4300:
/***/ ((module) => {
module.exports = require("buffer");
/***/ }),
/***/ 6113:
/***/ ((module) => {
module.exports = require("crypto");
/***/ }),
/***/ 7147:
/***/ ((module) => {
module.exports = require("fs");
/***/ }),
/***/ 3685:
/***/ ((module) => {
module.exports = require("http");
/***/ }),
/***/ 9577:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6517);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__);
// @ts-check
const fs = __webpack_require__(7147);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
"use strict";(()=>{var e={};e.id=536,e.ids=[536],e.modules={27825:e=>{e.exports=require("lodash")},75600:e=>{e.exports=require("next/dist/compiled/next-server/pages-api.runtime.prod.js")},9973:e=>{e.exports=require("serverless-mysql")},79428:e=>{e.exports=require("buffer")},55511:e=>{e.exports=require("crypto")},29021:e=>{e.exports=require("fs")},81630:e=>{e.exports=require("http")},96762:(e,r)=>{Object.defineProperty(r,"M",{enumerable:!0,get:function(){return function e(r,t){return t in r?r[t]:"then"in r&&"function"==typeof r.then?r.then(r=>e(r,t)):"function"==typeof r&&"default"===t?r:void 0}}})},36968:(e,r,t)=>{t.r(r),t.d(r,{config:()=>_,default:()=>S,routeModule:()=>m});var s={};t.r(s),t.d(s,{default:()=>p});var n=t(89947),i=t(2706),a=t(96762),o=t(6420),u=t.n(o),l=t(77538),c=t.n(l);t(27825);var d=t(51348),f=t.n(d);async function p(e,r){if("POST"!==e.method)return r.json({user:null,msg:"Registration Failed!"});let t=await u()(e,r,!0);if(!t)return r.json({success:!1,msg:"Unauthorized"});let{id:s}=e.body;try{let e=await f()("SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?",[s,t.id]),n=e?.[0];if(!n?.id)throw Error("Active User couldn't be verified");if(String(n.primary)?.match(/1/))throw Error("Cannot Delete Primary User");let i=`dsql_user_${t.id}`,a=n.host;await f()("DELETE FROM mariadb_users WHERE user_id = ? AND id = ?",[t.id,n.id]),await f()(`DROP USER '${i}'@'${a}'`),r.json({success:!0})}catch(e){c()({component:"/api/acceptUserInvitation/catch-error",message:e.message,user:t}),r.json({success:!1,msg:"Error in adding SQL user =>"+e.message,err:e.message})}}t(29021);let S=(0,a.M)(s,"default"),_=(0,a.M)(s,"config"),m=new n.PagesAPIRouteModule({definition:{kind:i.A.PAGES_API,page:"/api/sql-users/delete",pathname:"/api/sql-users/delete",bundlePath:"",filename:""},userland:s})},77538:(e,r,t)=>{let s=t(29021),{IncomingMessage:n}=t(81630);e.exports=async function({user:e,message:r,component:t,noMail:n,req:i}){let a=new Date,o=(()=>{if(!i)return null;try{let e=i.headers["x-forwarded-for"],r=i.headers["x-real-ip"],t=i.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],n=t||s||r||i.socket.remoteAddress;if(!n)return null;return String(n)}catch(e){return null}})();try{let n=`🚀 SERVER ERROR ===========================
Error Message: ${r}
Component: ${t}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(n+=`
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}`),i?.url&&(n+=`
URL: ${i.url}`),i?.body&&(n+=`
Request Body: ${JSON.stringify(i.body,null,4)}`),o&&(n+=`
IP: ${o}`),n+=`
Date: ${a.toDateString()}
========================================`,s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let u=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",n),s.appendFileSync("./.tmp/error.log",`
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* API handler
* ==============================================================================
* @type {import("next").NextApiHandler}
*/ async function handler(req, res) {
/**
* Check method
*
* @description Check request method and return if invalid
*/ if (req.method !== "POST") return res.json({
user: null,
msg: "Registration Failed!"
});
/**
* User Auth
*
* @description User Auth
*/ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default()(req, res, true);
if (!user) {
return res.json({
success: false,
msg: "Unauthorized"
});
}
/**
* Validate Form
*
* @description Check if request body is valid
*/ const { id } = req.body;
/**
* Validate Form
*
* @description Check if request body is valid
*/ try {
const existingMariaDBUserArray = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`, [
id,
user.id
]);
/**
* @type {import("@/package-shared/types").MYSQL_mariadb_users_table_def | undefined}
*/ const activeMariadbUserObject = existingMariaDBUserArray?.[0];
if (!activeMariadbUserObject?.id) {
throw new Error("Active User couldn't be verified");
}
const isPrimary = String(activeMariadbUserObject.primary)?.match(/1/) ? true : false;
if (isPrimary) {
throw new Error("Cannot Delete Primary User");
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const username = `dsql_user_${user.id}`;
const host = activeMariadbUserObject.host;
const deleteUserFromDatasquirelDb = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`DELETE FROM mariadb_users WHERE user_id = ? AND id = ?`, [
user.id,
activeMariadbUserObject.id
]);
const deleteSQLUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`DROP USER '${username}'@'${host}'`);
res.json({
success: true
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error) {
_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
component: "/api/acceptUserInvitation/catch-error",
message: error.message,
user: user
});
res.json({
success: false,
msg: "Error in adding SQL user =>" + error.message,
err: error.message
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,6825], () => (__webpack_exec__(9577)));
module.exports = __webpack_exports__;
})();
${u}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},6420:(e,r,t)=>{t(81630);let s=t(51348),n=t(72907),i=t(29021);async function a(e,r,t,a){if(!e.cookies?.datasquirelAuthKey?.match(/./))return null;let o=n(e.cookies.datasquirelAuthKey);if(!o)return null;let u=JSON.parse(o);if(!u.csrf_k||t&&!e.headers["x-csrf-auth"]?.match(RegExp(`${u.csrf_k}`)))return null;let l=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!l)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(t&&!i.existsSync(`${l}/${u.csrf_k}`))return null;if(0==u.verification_status&&!t){let e=await s(`SELECT verification_status FROM users WHERE id='${u.id}'`);e&&e[0]&&1==e[0].verification_status&&r.setHeader("Set-Cookie",["user_refresh=1"])}return u?.date&&Date.now()-u.date>6048e5?null:u}e.exports=a},72907:(e,r,t)=>{let{scryptSync:s,createDecipheriv:n}=t(55511),{Buffer:i}=t(79428);e.exports=e=>{let r=n("aes-192-cbc",s(process.env.DSQL_ENCRYPTION_PASSWORD||"",process.env.DSQL_ENCRYPTION_SALT||"",24),i.alloc(16,0));try{let t=r.update(e,"hex","utf8");return t+=r.final("utf8")}catch(e){return null}}},51348:(e,r,t)=>{let s=t(9973),n=t(21580),i=s({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:process.env.DSQL_DB_NAME,port:process.env.DSQL_DB_PORT?Number(process.env.DSQL_DB_PORT):void 0,charset:"utf8mb4",ssl:n()}});async function a(...e){try{let r=await i.query(...e);return await i.end(),JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=a},21580:(e,r,t)=>{let s=t(29021);e.exports=function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let r=`${e}/ca-cert.pem`;if(!s.existsSync(r)){console.log(`${r} does not exist`);return}return{ca:s.readFileSync(`${e}/ca-cert.pem`)}}},2706:(e,r)=>{var t;Object.defineProperty(r,"A",{enumerable:!0,get:function(){return t}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE"}(t||(t={}))},89947:(e,r,t)=>{e.exports=t(75600)}};var r=require("../../../webpack-api-runtime.js");r.C(e);var t=r(r.s=36968);module.exports=t})();
File diff suppressed because one or more lines are too long
@@ -1,219 +1,28 @@
"use strict";
(() => {
var exports = {};
exports.id = 9685;
exports.ids = [9685];
exports.modules = {
/***/ 6517:
/***/ ((module) => {
module.exports = require("lodash");
/***/ }),
/***/ 2261:
/***/ ((module) => {
module.exports = require("serverless-mysql");
/***/ }),
/***/ 4300:
/***/ ((module) => {
module.exports = require("buffer");
/***/ }),
/***/ 2081:
/***/ ((module) => {
module.exports = require("child_process");
/***/ }),
/***/ 6113:
/***/ ((module) => {
module.exports = require("crypto");
/***/ }),
/***/ 7147:
/***/ ((module) => {
module.exports = require("fs");
/***/ }),
/***/ 3685:
/***/ ((module) => {
module.exports = require("http");
/***/ }),
/***/ 1017:
/***/ ((module) => {
module.exports = require("path");
/***/ }),
/***/ 2287:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6825);
/* harmony import */ var _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2163);
/* harmony import */ var _functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6517);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2224);
/* harmony import */ var _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1017);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2081);
/* harmony import */ var child_process__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(child_process__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(7547);
/* harmony import */ var _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6__);
// @ts-check
const fs = __webpack_require__(7147);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
"use strict";(()=>{var e={};e.id=2350,e.ids=[2350],e.modules={27825:e=>{e.exports=require("lodash")},75600:e=>{e.exports=require("next/dist/compiled/next-server/pages-api.runtime.prod.js")},9973:e=>{e.exports=require("serverless-mysql")},79428:e=>{e.exports=require("buffer")},79646:e=>{e.exports=require("child_process")},55511:e=>{e.exports=require("crypto")},29021:e=>{e.exports=require("fs")},81630:e=>{e.exports=require("http")},33873:e=>{e.exports=require("path")},96762:(e,r)=>{Object.defineProperty(r,"M",{enumerable:!0,get:function(){return function e(r,t){return t in r?r[t]:"then"in r&&"function"==typeof r.then?r.then(r=>e(r,t)):"function"==typeof r&&"default"===t?r:void 0}}})},46849:(e,r,t)=>{t.r(r),t.d(r,{config:()=>y,default:()=>g,routeModule:()=>R});var s={};t.r(s),t.d(s,{default:()=>_});var n=t(89947),o=t(2706),i=t(96762),a=t(6420),l=t.n(a),u=t(77538),c=t.n(u);t(27825);var d=t(51348),p=t.n(d),f=t(33873),S=t.n(f),m=t(79646),E=t(82703),h=t.n(E);async function _(e,r){if("POST"!==e.method)return r.json({user:null,msg:"Registration Failed!"});let t=await l()(e,r,!0);if(!t)return r.json({success:!1,msg:"Unauthorized"});let{data:s,edit:n,prev:o,grants:i}=e.body;try{if(!o?.id)throw Error("Invalid existing DB entry");let e=await p()("SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?",[o.id,t.id]),n=e?.[0];if(!n?.id)throw Error("Active User couldn't be verified");let a=`dsql_user_${t.id}`,{host:l,password:u}=s;if(!l)throw Error("No host provided");if(l.match(/^%$/))throw Error("Cannot set a catch-all host for this user.");let c=String(l).replace(/[^a-zA-Z0-9-\.\:\/\%]/g,"");if(n.host!=s.host){let e=await p()("SELECT * FROM mariadb_users WHERE user_id = ? AND host = ?",[t.id,c]);if(e?.[0]?.id)throw Error("User already exists with this host. Please choose another host.");await p()(`RENAME USER '${a}'@'${n.host}' TO '${a}'@'${c}'`)}let d=h()(u),f=d==n.password?n.password:d;await p()("UPDATE mariadb_users SET host = ?, password = ?, grants = ? WHERE id = ?",[c,f,JSON.stringify(i),n.id]),await p()(`SET PASSWORD FOR '${a}'@'${c}' = PASSWORD('${u}');`);let E=S().resolve(process.cwd(),"./shell/mariadb-users");(0,m.execSync)(`node refreshUsersAndGrants.js --userId ${t.id} --username ${a} --host ${c} --sql-user-id ${n.id}}`,{cwd:E}),r.json({success:!0})}catch(e){c()({component:"/api/acceptUserInvitation/catch-error",message:e.message,user:t}),r.json({success:!1,msg:"Error in adding SQL user =>"+e.message,err:e.message})}}t(29021);let g=(0,i.M)(s,"default"),y=(0,i.M)(s,"config"),R=new n.PagesAPIRouteModule({definition:{kind:o.A.PAGES_API,page:"/api/sql-users/update",pathname:"/api/sql-users/update",bundlePath:"",filename:""},userland:s})},77538:(e,r,t)=>{let s=t(29021),{IncomingMessage:n}=t(81630);e.exports=async function({user:e,message:r,component:t,noMail:n,req:o}){let i=new Date,a=(()=>{if(!o)return null;try{let e=o.headers["x-forwarded-for"],r=o.headers["x-real-ip"],t=o.headers["cf-connecting-ip"],s=Array.isArray(e)?e[0]:e?.split(",")[0],n=t||s||r||o.socket.remoteAddress;if(!n)return null;return String(n)}catch(e){return null}})();try{let n=`🚀 SERVER ERROR ===========================
Error Message: ${r}
Component: ${t}`;e?.id&&e?.first_name&&e?.last_name&&e?.email&&(n+=`
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}`),o?.url&&(n+=`
URL: ${o.url}`),o?.body&&(n+=`
Request Body: ${JSON.stringify(o.body,null,4)}`),a&&(n+=`
IP: ${a}`),n+=`
Date: ${i.toDateString()}
========================================`,s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let l=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",n),s.appendFileSync("./.tmp/error.log",`
${l}`)}catch(e){console.log("Server Error Reporting Error:",e.message)}}},6420:(e,r,t)=>{t(81630);let s=t(51348),n=t(72907),o=t(29021);async function i(e,r,t,i){if(!e.cookies?.datasquirelAuthKey?.match(/./))return null;let a=n(e.cookies.datasquirelAuthKey);if(!a)return null;let l=JSON.parse(a);if(!l.csrf_k||t&&!e.headers["x-csrf-auth"]?.match(RegExp(`${l.csrf_k}`)))return null;let u=process.env.DSQL_USER_LOGIN_KEYS_PATH;if(!u)return console.log("DSQL_USER_LOGIN_KEYS_PATH env variable not found. Please set this variable."),null;if(t&&!o.existsSync(`${u}/${l.csrf_k}`))return null;if(0==l.verification_status&&!t){let e=await s(`SELECT verification_status FROM users WHERE id='${l.id}'`);e&&e[0]&&1==e[0].verification_status&&r.setHeader("Set-Cookie",["user_refresh=1"])}return l?.date&&Date.now()-l.date>6048e5?null:l}e.exports=i},72907:(e,r,t)=>{let{scryptSync:s,createDecipheriv:n}=t(55511),{Buffer:o}=t(79428);e.exports=e=>{let r=n("aes-192-cbc",s(process.env.DSQL_ENCRYPTION_PASSWORD||"",process.env.DSQL_ENCRYPTION_SALT||"",24),o.alloc(16,0));try{let t=r.update(e,"hex","utf8");return t+=r.final("utf8")}catch(e){return null}}},82703:(e,r,t)=>{let{scryptSync:s,createCipheriv:n}=t(55511),{Buffer:o}=t(79428),i=t(48225);e.exports=(e,r,t)=>{let a=n("aes-192-cbc",s(r||process.env.DSQL_ENCRYPTION_PASSWORD||"",t||process.env.DSQL_ENCRYPTION_SALT||"",24),o.alloc(16,0));try{let r=a.update(e,"utf8","hex");return r+=a.final("hex")}catch(e){return i({component:"encrypt",message:e.message}),null}}},48225:(e,r,t)=>{let s=t(29021);e.exports=async function({user:e,message:r,component:t,noMail:n}){let o=`🚀 SERVER ERROR ===========================
User Id: ${e?.id}
User Name: ${e?.first_name} ${e?.last_name}
User Email: ${e?.email}
Error Message: ${r}
Component: ${t}
Date: ${Date()}
========================================`;s.existsSync("./.tmp/error.log")||s.writeFileSync("./.tmp/error.log","","utf-8");let i=s.readFileSync("./.tmp/error.log","utf-8");s.writeFileSync("./.tmp/error.log",o),s.appendFileSync("./.tmp/error.log",`
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* API handler
* ==============================================================================
* @type {import("next").NextApiHandler}
*/ async function handler(req, res) {
/**
* Check method
*
* @description Check request method and return if invalid
*/ if (req.method !== "POST") return res.json({
user: null,
msg: "Registration Failed!"
});
/**
* User Auth
*
* @description User Auth
*/ const user = await _functions_backend_userAuth__WEBPACK_IMPORTED_MODULE_0___default()(req, res, true);
if (!user) {
return res.json({
success: false,
msg: "Unauthorized"
});
}
/**
* Validate Form
*
* @description Check if request body is valid
*/ const { data , edit , prev , grants } = req.body;
/**
* @type {import("@/package-shared/types").MYSQL_mariadb_users_table_def | undefined}
*/ const existingMariaDBUser = prev;
/**
* Validate Form
*
* @description Check if request body is valid
*/ try {
if (!existingMariaDBUser?.id) {
throw new Error("Invalid existing DB entry");
}
const existingMariaDBUserArray = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`, [
existingMariaDBUser.id,
user.id
]);
/**
* @type {import("@/package-shared/types").MYSQL_mariadb_users_table_def | undefined}
*/ const activeMariadbUserObject = existingMariaDBUserArray?.[0];
if (!activeMariadbUserObject?.id) {
throw new Error("Active User couldn't be verified");
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const username = `dsql_user_${user.id}`;
const { host , password } = data;
if (!host) {
throw new Error("No host provided");
}
if (host.match(/^%$/)) {
throw new Error("Cannot set a catch-all host for this user.");
}
const sanitizedNewHost = String(host).replace(/[^a-zA-Z0-9-\.\:\/\%]/g, "");
if (activeMariadbUserObject.host != data.host) {
const existinUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`SELECT * FROM mariadb_users WHERE user_id = ? AND host = ?`, [
user.id,
sanitizedNewHost
]);
if (!existinUser?.[0]?.id) {
const renameUser = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`RENAME USER '${username}'@'${activeMariadbUserObject.host}' TO '${username}'@'${sanitizedNewHost}'`);
} else {
throw new Error("User already exists with this host. Please choose another host.");
}
}
const encryptedPassword = _package_shared_functions_backend_encrypt__WEBPACK_IMPORTED_MODULE_6___default()(password);
const finalPassword = encryptedPassword == activeMariadbUserObject.password ? activeMariadbUserObject.password : encryptedPassword;
const updateUserEntry = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`UPDATE mariadb_users SET host = ?, password = ?, grants = ? WHERE id = ?`, [
sanitizedNewHost,
finalPassword,
JSON.stringify(grants),
activeMariadbUserObject.id,
]);
const updateSQLUserPassword = await _package_shared_utils_backend_global_db_DB_HANDLER__WEBPACK_IMPORTED_MODULE_3___default()(`SET PASSWORD FOR '${username}'@'${sanitizedNewHost}' = PASSWORD('${password}');`);
const execPath = path__WEBPACK_IMPORTED_MODULE_4___default().resolve(process.cwd(), "./shell/mariadb-users");
const execSQLUserScript = (0,child_process__WEBPACK_IMPORTED_MODULE_5__.execSync)(`node refreshUsersAndGrants.js --userId ${user.id} --username ${username} --host ${sanitizedNewHost} --sql-user-id ${activeMariadbUserObject.id}}`, {
cwd: execPath
});
res.json({
success: true
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error) {
_functions_backend_serverError__WEBPACK_IMPORTED_MODULE_1___default()({
component: "/api/acceptUserInvitation/catch-error",
message: error.message,
user: user
});
res.json({
success: false,
msg: "Error in adding SQL user =>" + error.message,
err: error.message
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [2224,2163,6825,3017,7547], () => (__webpack_exec__(2287)));
module.exports = __webpack_exports__;
})();
${i}`)}},51348:(e,r,t)=>{let s=t(9973),n=t(21580),o=s({config:{host:process.env.DSQL_DB_HOST,user:process.env.DSQL_DB_USERNAME,password:process.env.DSQL_DB_PASSWORD,database:process.env.DSQL_DB_NAME,port:process.env.DSQL_DB_PORT?Number(process.env.DSQL_DB_PORT):void 0,charset:"utf8mb4",ssl:n()}});async function i(...e){try{let r=await o.query(...e);return await o.end(),JSON.parse(JSON.stringify(r))}catch(e){return console.log("DB Error =>",e),{success:!1,error:e.message}}}e.exports=i},21580:(e,r,t)=>{let s=t(29021);e.exports=function(){let e=process.env.DSQL_SSL_DIR;if(!e?.match(/./))return;let r=`${e}/ca-cert.pem`;if(!s.existsSync(r)){console.log(`${r} does not exist`);return}return{ca:s.readFileSync(`${e}/ca-cert.pem`)}}},2706:(e,r)=>{var t;Object.defineProperty(r,"A",{enumerable:!0,get:function(){return t}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE",e.IMAGE="IMAGE"}(t||(t={}))},89947:(e,r,t)=>{e.exports=t(75600)}};var r=require("../../../webpack-api-runtime.js");r.C(e);var t=r(r.s=46849);module.exports=t})();
File diff suppressed because one or more lines are too long