Files
Server/modules/prestartup.js
T
azures04 22542243f6 Add auth, JWT tokens, and bootstrap startup
Introduce bootstrap entrypoint and prestartup to ping DB and generate/manage RSA keypair. Add security module for key IO. Implement JWT-based access and refresh tokens (tokensService) with refresh_tokens table and repo. Add auth, provider and user services, and refresh-token management. Update repositories (users, credentials, providers, servers) with SQL fixes and new helper methods. Move DDL execution to bootstrap (remove from server). Update package.json main and add dependencies (bcryptjs, jsonwebtoken). Update .env.example and .gitignore accordingly.
2026-09-02 01:55:58 +02:00

53 lines
1.5 KiB
JavaScript

const security = require("./security")
const serversRepo = require("../repositories/serversRepo")
const logger = require("./logger")
const { pool } = require("./database")
const LOCAL_SERVER_ID = process.env.SERVER_UUID
async function setupKeys() {
const existing = await serversRepo.findById(LOCAL_SERVER_ID)
if (existing) {
checkKeys(existing.publicKey)
return existing
}
const { privateKeyPem, publicKeyPem } = security.generateServerKeyPair()
security.saveKeyPairToDisk({ privateKeyPem, publicKeyPem })
logger.log("Local server keypair generated and stored in data/secrets", ["KEYS", "yellow"])
return await serversRepo.createAndAssignIdManually(LOCAL_SERVER_ID, "internal", publicKeyPem)
}
function checkKeys(publicKeyFromDb) {
const { privateExists, publicExists } = security.keyFilesExist()
if (!privateExists) {
throw new Error(
"Private key file missing for local server, but server row exists in DB.",
"Cannot regenerate without invalidating existing signatures/tokens."
)
}
if (!publicExists) {
security.restorePublicKeyFile(publicKeyFromDb)
logger.warn("Public key file was missing, restored from DB.", ["KEYS", "yellow"])
}
}
async function pingDb() {
try {
await pool.query("SELECT 1")
} catch (err) {
console.log(err)
logger.error("Could'nt connect to db", ["PRESTARTUP", "cyan"])
process.exit(1)
}
}
module.exports = {
pingDb,
checkKeys,
setupKeys,
}