p2p https and login fix, removed static domain from ejs files

This commit is contained in:
mrfry 2023-04-07 16:32:22 +02:00
parent ae3bd7c55a
commit e858d7f23e
13 changed files with 210 additions and 79 deletions

View file

@ -105,7 +105,7 @@ function GetApp(): ModuleType {
function reloadRootRedirectURL() {
if (utils.FileExists(paths.rootRedirectToFile)) {
rootRedirectURL = utils.ReadFile(paths.rootRedirectToFile)
rootRedirectURL = utils.ReadFile(paths.rootRedirectToFile).trim()
}
}

View file

@ -19,7 +19,6 @@
------------------------------------------------------------------------- */
import { Response } from 'express'
import http from 'http'
import logger from '../../../utils/logger'
import {
@ -60,6 +59,7 @@ import {
SelfInfoSchema,
} from '../../../types/typeSchemas'
import { paths } from '../../../utils/files'
import { GetResult, get, post } from '../../../utils/networkUtils'
interface MergeResult {
newData: Subject[]
@ -87,47 +87,17 @@ interface RemotePeerInfo {
}
}
interface RequestResult<T> {
data?: T
error?: Error
options?: http.RequestOptions
}
interface SyncDataRes {
questionDbs?: QuestionDb[]
remoteInfo?: RemotePeerInfo
encryptedUsers?: string
count: {
count?: {
qdbs: number
subjects: number
questions: number
}
}
// FIXME: to utils/http.ts
function get<T>(options: http.RequestOptions): Promise<RequestResult<T>> {
return new Promise((resolve) => {
const req = http.get(options, function (res) {
const bodyChunks: Uint8Array[] = []
res.on('data', (chunk) => {
bodyChunks.push(chunk)
}).on('end', () => {
const body = Buffer.concat(bodyChunks).toString()
try {
resolve({ data: JSON.parse(body) })
} catch (e) {
console.log(body)
resolve({ error: e, options: options })
}
})
})
req.on('error', function (e) {
resolve({ error: e, options: options })
// reject(e)
})
})
}
function updateThirdPartyPeers(
newVal: Omit<PeerInfo, 'publicKey' | 'name' | 'contact'>[]
) {
@ -341,6 +311,54 @@ function setupQuestionsForMerge(qdb: QuestionDb, peer: PeerInfo) {
}
}
async function authAndGetNewData({
peer,
selfInfo,
lastSyncWithPeer,
lastSync,
}: {
peer: PeerInfo
selfInfo: PeerInfo
lastSyncWithPeer: number
lastSync: number
}): Promise<GetResult<SyncDataRes & { peer: PeerInfo }>> {
const { data, error, cookies } = await post<{
result: string
msg: string
}>({
hostname: peer.host,
path: '/api/login',
port: peer.port,
bodyObject: { pw: peer.pw },
http: peer.http,
})
if (error || !data || data.result !== 'success') {
return {
error: data ? new Error(data.msg) : error,
data: {
peer: peer,
},
}
}
const getRes = await get<SyncDataRes>(
{
headers: {
cookie: cookies.join(),
},
host: peer.host,
port: peer.port,
path: `/api/getnewdatasince?host=${encodeURIComponent(
peerToString(selfInfo)
)}${lastSync ? `&since=${lastSyncWithPeer}` : ''}`,
},
peer.http
)
return { ...getRes, data: { ...getRes.data, peer: peer } }
}
function setup(data: SubmoduleData): Submodule {
const {
app,
@ -453,32 +471,35 @@ function setup(data: SubmoduleData): Submodule {
// FUNCTIONS
// ---------------------------------------------------------------------------------------
function getSelfInfo(includeQdbInfo?: boolean) {
function getSelfInfo(includeVerboseInfo?: boolean) {
const result: RemotePeerInfo = {
selfInfo: selfInfo,
myPeers: peers,
}
result.serverRevision = utils.getGitRevision(__dirname)
result.scriptRevision = utils.getGitRevision(
paths.moodleTestUserscriptDir
)
result.qminingPageRevision = utils.getGitRevision(paths.qminingPageDir)
result.dataEditorRevision = utils.getGitRevision(
paths.dataEditorPageDir
)
result.qminingPageBuildTime = utils
.statFile(paths.qminingIndexPath)
?.mtime.getTime()
result.serverBuildTime = utils
.statFile(paths.serverPath)
?.mtime.getTime()
result.dataEditorBuildTime = utils
.statFile(paths.dataEditorIndexPath)
?.mtime.getTime()
result.scriptVersion = utils.getScriptVersion()
result.userCount = dbtools.TableInfo(userDB, 'users').dataCount
if (includeQdbInfo) {
if (includeVerboseInfo) {
result.serverRevision = utils.getGitRevision(__dirname)
result.scriptRevision = utils.getGitRevision(
paths.moodleTestUserscriptDir
)
result.qminingPageRevision = utils.getGitRevision(
paths.qminingPageDir
)
result.dataEditorRevision = utils.getGitRevision(
paths.dataEditorPageDir
)
result.qminingPageBuildTime = utils
.statFile(paths.qminingIndexPath)
?.mtime.getTime()
result.serverBuildTime = utils
.statFile(paths.serverPath)
?.mtime.getTime()
result.dataEditorBuildTime = utils
.statFile(paths.dataEditorIndexPath)
?.mtime.getTime()
result.scriptVersion = utils.getScriptVersion()
result.userCount = dbtools.TableInfo(userDB, 'users').dataCount
const questionDbCount = getQuestionDbs().length
const { subjCount, questionCount } = countOfQdbs(getQuestionDbs())
result.qdbInfo = {
@ -585,19 +606,12 @@ function setup(data: SubmoduleData): Submodule {
const requests = peers.map((peer) => {
const lastSyncWithPeer = peer.lastSync || 0
return new Promise<RequestResult<SyncDataRes & { peer: PeerInfo }>>(
(resolve) => {
get<SyncDataRes>({
host: peer.host,
port: peer.port,
path: `/getnewdatasince?host=${encodeURIComponent(
peerToString(selfInfo)
)}${lastSync ? `&since=${lastSyncWithPeer}` : ''}`,
}).then((res) => {
resolve({ ...res, data: { ...res.data, peer: peer } })
})
}
)
return authAndGetNewData({
peer: peer,
selfInfo: selfInfo,
lastSyncWithPeer: lastSyncWithPeer,
lastSync: lastSync,
})
})
const allResults = await Promise.all(requests)
@ -912,6 +926,10 @@ function setup(data: SubmoduleData): Submodule {
// ---------------------------------------------------------------------------------------
// APP SETUP
// ---------------------------------------------------------------------------------------
app.get('/selfInfo', (_req: Request, res: Response<PeerInfo>) => {
res.json(selfInfo)
})
app.get('/p2pinfo', (_req: Request, res: Response<RemotePeerInfo>) => {
res.json(getSelfInfo(true))
})

View file

@ -68,7 +68,7 @@ function createDefaultUser(userDb: Database) {
const pw = uuidv4()
const insertRes = dbtools.Insert(userDb, 'users', {
pw: pw,
avaiblePWRequests: 0,
avaiblePWRequests: 50,
created: utils.GetDateString(),
})
logger.Log('ID and PW for user #1: ', 'yellowbg')