added nethub

This commit is contained in:
srgooglo 2021-06-09 15:11:49 +02:00
parent d4cd4dfd14
commit 3928826ef3
15 changed files with 3596 additions and 8 deletions

5
.gitignore vendored
View File

@ -1,4 +1,7 @@
node_modules node_modules
*/**/node_modules */**/node_modules
*/**/dist */**/dist
*/**/dumps.log */**/dumps.log
*/**/origin.server
*/**/server.registry

View File

@ -7,8 +7,16 @@
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
], ],
"scripts": {
"dev:server": "cd ./packages/server && npm run dev",
"dev:nethub": "cd ./packages/nethub && npm run dev",
"dev:relic": "cd ./packages/relic && npm run dev"
},
"dependencies": { "dependencies": {
"corenode": "^0.24.9", "corenode": "^0.24.9",
"@babel/runtime": "^7.14.0" "@babel/runtime": "^7.14.0"
},
"devDependencies": {
"nodemon": "^2.0.7"
} }
} }

View File

@ -0,0 +1,5 @@
{
"development": {
"origitGit": ""
}
}

View File

View File

@ -0,0 +1 @@
# nethub

View File

@ -0,0 +1,31 @@
{
"name": "nethub",
"version": "0.1.2",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"publishConfig": {
"access": "public"
},
"license": "MIT",
"files": [
"dist",
"load.addon.js"
],
"scripts": {
"start": "corenode ./dist/index.js",
"dev": "nodemon --ignore dist/ --exec 'corenode build && corenode' ./dist/index.js"
},
"dependencies": {
"axios": "^0.21.1",
"corenode": "^0.24.9",
"cors": "^2.8.5",
"express": "^4.17.1",
"express-fileupload": "^1.2.1",
"morgan": "^1.10.0",
"uuid": "^8.3.2",
"websocket": "^1.0.34"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}

View File

@ -0,0 +1,286 @@
const express = require("express")
const os = require('os')
const path = require('path')
const fs = require('fs')
//* LIBS
const { objectToArrayMap } = require("@corenode/utils")
const TOKENIZER = require("./lib/tokenizer")
//* GLOBALS
const SERVER_REGISTRY = "server.registry"
const SERVER_GENFILE = "origin.server"
const SERVER_REGISTRYPATH = path.resolve(process.cwd(), SERVER_REGISTRY)
const SERVER_GENFILEPATH = path.resolve(process.cwd(), SERVER_GENFILE)
const SERVER_VERSION = global.SERVER_VERSION = runtime.helpers.getVersion()
const SERVER = require("express")()
//* SERVER HUB REGISTRY
const HUB = {
entries: [],
oids: [],
registry: {},
set: (oid, data) => {
HUB.registry[oid] = data
HUB.update()
},
del: (oid) => {
const addressIndex = HUB.oids.indexOf(oid)
delete HUB.registry[oid]
delete HUB.oids[addressIndex]
delete HUB.entries[addressIndex]
HUB.update()
},
update: () => {
const data = {
entries: HUB.entries,
oids: HUB.oids,
registry: HUB.registry,
}
return fs.writeFileSync(SERVER_REGISTRYPATH, JSON.stringify(data, null, 2), { encoding: "utf-8" })
},
read: () => {
if (fs.existsSync(SERVER_REGISTRYPATH)) {
const data = JSON.parse(fs.readFileSync(SERVER_REGISTRYPATH, 'utf8')) ?? {}
HUB.entries = data.entries
HUB.oids = data.oids
HUB.registry = data.registry
}
}
}
//* SERVER GEN
const GEN = {
stat: () => {
return fs.lstatSync(SERVER_GENFILEPATH)
},
get: (key) => {
if (fs.existsSync(SERVER_GENFILEPATH)) {
return JSON.parse(fs.readFileSync(SERVER_GENFILEPATH, 'utf8')) ?? {}
}
return {}
},
write: (mutation) => {
let data = GEN.get()
data = { ...data, ...mutation }
GEN.data = data
return fs.writeFileSync(SERVER_GENFILEPATH, JSON.stringify(data, null, 2), { encoding: "utf-8" })
},
create: () => {
let data = {
created: Date.now(),
serverToken: TOKENIZER.generate()
}
GEN.write(data)
},
file: SERVER_GENFILE,
filepath: SERVER_GENFILEPATH,
}
//* DEFAULTS
const DEFAULT_MIDDLEWARES = [
require('cors')(),
require('morgan')("dev")
]
const DEFAULT_HEADERS = {
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
"Access-Control-Allow-Credentials": "true",
}
const DEFAULT_PORT = 1010
//* HELPERS
function getUptime() {
const { lastStart } = global.GENDATA
const now = Date.now()
return now - lastStart
}
function getRegistryFromEntry(entry){
const index = HUB.entries.indexOf(entry)
const oid = HUB.oids[index]
return HUB.registry[oid]
}
//* GLOBAL FUNCTIONS
function init() {
//? check if origin.server exists
if (!fs.existsSync(SERVER_GENFILEPATH)) {
GEN.create()
}
//? check origin.server integrity
const GENDATA = global.GENDATA = GEN.get()
const GENSTAT = global.GENSTAT = GEN.stat()
if (typeof GENDATA.created === "undefined") {
console.warn("Server generation file not contains an creation date")
GEN.write({ created: Date.parse(GENSTAT.birthtime) })
}
if (typeof GENDATA.serverToken === "undefined") {
console.warn("Missing server token!")
GEN.create()
}
//? set last start
GEN.write({ lastStart: Date.now() })
//? read registry
HUB.read()
//? continue starting server
start()
}
function start() {
//? set middlewares
SERVER.use(express.json())
SERVER.use(express.urlencoded({ extended: true }))
SERVER.use((req, res, next) => {
objectToArrayMap(DEFAULT_HEADERS).forEach((entry) => {
res.setHeader(entry.key, entry.value)
})
next()
})
DEFAULT_MIDDLEWARES.forEach((middleware) => {
SERVER.use(middleware)
})
//? set routes
SERVER.get("/", (req, res, next) => {
res.json({
uptime: getUptime(),
created: global.GENDATA.created,
time: new Date().getTime(),
originID: `${os.hostname()}`,
version: SERVER_VERSION
})
})
// TODO: set websocket server heap & events
SERVER.get("/hearbeat", (req, res, next) => {
res.json({
uptime: getUptime()
})
})
SERVER.put("/registry", (req, res, next) => {
let { entry, oid } = req.body
const address = req.headers['x-real-ip'] || req.connection.remoteAddress
let mutation = {}
//? validate oid token
if (typeof oid !== "undefined") {
if (!TOKENIZER.valid(oid)) {
res.status(403)
return res.json({
error: `[${oid}] Is an invalid OID!`
})
}
}
if (typeof HUB.registry[oid] !== "undefined") {
mutation = HUB.registry[oid]
//? check if is allowed
if (HUB.registry[oid]?.address !== address) {
res.status(403)
return res.json({
error: `[${oid}] is already registered, is not allowed to override registry with this current address (${address})`
})
}
mutation.lastUpdated = Date.now()
} else {
//? check duplications
if (HUB.entries.includes(entry)) {
const duplicate = getRegistryFromEntry(entry)
res.status(409)
return res.json({
error: `[${entry}] This entry has been already registered, with oid [${duplicate.oid}]`
})
}
if (typeof oid === "undefined") {
oid = TOKENIZER.generate(address)
}
HUB.entries.push(entry)
HUB.oids.push(oid)
mutation.oid = oid
mutation.created = Date.now()
}
mutation["address"] = address
mutation["entry"] = entry
//? successfully
HUB.set(oid, mutation)
res.json({
...HUB.registry[oid],
originToken: global.GENDATA.serverToken
})
})
SERVER.get("/registry", (req, res, next) => {
const { oid } = req.query
const address = req.headers['x-real-ip'] || req.connection.remoteAddress
if (typeof HUB.registry[oid] === "undefined") {
res.status(404)
return res.json({
error: `[${oid}] Not founded in this hub!`
})
}
res.json(HUB.registry[oid])
})
SERVER.delete("/registry", (req, res, next) => {
const { oid } = req.query
const address = req.headers['x-real-ip'] || req.connection.remoteAddress
if (typeof HUB.registry[oid] === "undefined") {
res.status(404)
return res.json({
error: `[${oid}] Not founded in this hub!`
})
}
if (HUB.registry[oid]?.address !== address) {
res.status(403)
return res.json({
error: `[${oid}] Is not allowed to delete this registry with this current address (${address})`
})
}
HUB.del(oid)
res.json({
oid
})
})
//? set to listen
SERVER.listen(DEFAULT_PORT, () => {
console.log(`✅ Ready on port ${DEFAULT_PORT}!`)
})
}
//? start server
init()

View File

@ -0,0 +1,12 @@
const { validate, version, v5, v4 } = require('uuid')
const os = require('os')
function generate(hostname) {
return v5(hostname ?? os.hostname(), v4())
}
function valid(uuid) {
return validate(uuid) && version(uuid) === 5
}
module.exports = { generate, valid }

1
packages/relic/README.md Normal file
View File

@ -0,0 +1 @@
# relic

View File

@ -5,7 +5,7 @@ const defaultRelicOrigin = _import("./defaultOrigin.json")
let sockets = {} let sockets = {}
function registerNewBridge() { function registerNewBridge() {
} }
function resolveOrigin(origin) { function resolveOrigin(origin) {

View File

@ -2,7 +2,7 @@
"name": "uploadServer", "name": "uploadServer",
"version": "0.1.0", "version": "0.1.0",
"scripts": { "scripts": {
"start": "relic-server ." "start": "rcs ."
}, },
"dependencies": { "dependencies": {
"@ragestudio/relic-server": "^0.2.2" "@ragestudio/relic-server": "^0.2.2"

File diff suppressed because it is too large Load Diff

View File

@ -4,11 +4,11 @@
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",
"scripts": { "scripts": {
"start": "corenode ./dist/index.js", "start": "corenode ./bin/index.js",
"dev": "nodemon --ignore dist/ --exec 'corenode build && corenode' dist/index.js" "dev": "nodemon --ignore dist/ --exec 'corenode build && corenode' ./bin/index.js"
}, },
"bin": { "bin": {
"relic-server": "corenode ./bin/index.js" "rcs": "corenode ./bin/index.js"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@ -32,4 +32,4 @@
"devDependencies": { "devDependencies": {
"nodemon": "^2.0.7" "nodemon": "^2.0.7"
} }
} }

View File

@ -1,9 +1,11 @@
const express = require("express") const express = require("express")
const { objectToArrayMap } = require("@corenode/utils") const { objectToArrayMap } = require("@corenode/utils")
const uuid = require("uuid") const uuid = require("uuid")
const os = require("os")
const { Controller } = require("@@classes") const { Controller } = require("@@classes")
const { getLocalEndpoints, fetchController } = require("./lib/helpers") const { getLocalEndpoints, fetchController } = require("./lib/helpers")
const nethub = require("./lib/nethub")
const SERVER_VERSION = global.SERVER_VERSION = runtime.helpers.getVersion() const SERVER_VERSION = global.SERVER_VERSION = runtime.helpers.getVersion()
const defaultMiddlewares = [ const defaultMiddlewares = [
@ -42,7 +44,7 @@ class RequestServer {
// set server basics // set server basics
this.httpServer = require("express")() this.httpServer = require("express")()
this.usid = uuid.v4() // unique session identifier this.usid = uuid.v5(os.hostname(), uuid.v4()) // unique session identifier
this._everyRequest = null this._everyRequest = null
this._onRequest = {} this._onRequest = {}
@ -102,6 +104,7 @@ class RequestServer {
} }
init() { init() {
nethub.heartbeat()
const localEndpoints = getLocalEndpoints() const localEndpoints = getLocalEndpoints()
this.httpServer.use(express.json()) this.httpServer.use(express.json())

View File

@ -0,0 +1,27 @@
const axios = require('axios')
const NETHUB_URI = global.NETHUB_URI = "https://nethub.ragestudio.net"
const axiosInstance = axios.create({
baseURL: NETHUB_URI
})
function heartbeat(params) {
axiosInstance.get("heartbeat")
.then((res) => {
console.log(res.response.data)
})
.catch((err) => {
console.log(err)
})
}
function registerOrigin() {
}
function getOrigin() {
}
module.exports = { heartbeat, registerOrigin, getOrigin }