Files
Server/services/tokensService.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

103 lines
2.7 KiB
JavaScript

const jwt = require("jsonwebtoken")
const security = require("../modules/security")
const tokenRepo = require("../repositories/refreshTokensRepo")
const { DefaultError } = require("../errors/errors")
const privateKey = security.readPrivateKey()
const publicKey = security.readPublicKey()
async function signToken(user) {
try {
const payload = {
id: user.id,
identifier: user.identifier,
displayName: user.displayName,
avatarUrl: user.avatarUrl
}
const token = await jwt.sign(payload, privateKey, {
algorithm: "RS256",
issuer: process.env.FQDN,
expiresIn: parseInt(process.env.ACCESS_TOKEN_EXPIRY)
})
return token
} catch (error) {
throw error
}
}
async function verifyAccessToken(token) {
try {
const result = jwt.verify(token, publicKey, {
algorithms: ["RS256"],
issuer: process.env.FQDN
})
console.log(result)
return result
} catch (error) {
throw error
}
}
async function signRefreshToken(userId) {
try {
const isTokenExisting = await tokenRepo.findByUserId(userId)
if (!Array.isArray(isTokenExisting)) {
await tokenRepo.removeByUserId(userId)
}
const now = Date.now()
const expiresIn = parseInt(process.env.REFRESH_TOKEN_EXPIRY)
const expiresAtInMs = new Date(now + (expiresIn * 1000))
const token = jwt.sign(
{ userId },
privateKey,
{
algorithm: "RS256",
issuer: process.env.FQDN,
expiresIn: expiresIn
}
)
await tokenRepo.create(userId, token, expiresAtInMs)
return token
} catch (error) {
throw error
}
}
async function revokeRefreshToken(token) {
try {
return await tokenRepo.removeByTokenHash(token)
} catch (error) {
throw error
}
}
async function verifyRefreshToken(token) {
try {
const result = jwt.verify(token, publicKey, {
algorithms: ["RS256"],
issuer: process.env.FQDN
})
if (!result) {
throw new DefaultError(500, "Internal Server Error")
}
const refreshTokenInDb = await tokenRepo.findByTokenHash(token)
if (refreshTokenInDb == null) {
throw new DefaultError(403, "Bad refresh token", "Refresh token doesn't exists")
}
return true
} catch (error) {
throw error
}
}
async function verifyAccessTokenFromServer(token) {
// TO-DO: Integrate server federation
}
module.exports = {
signToken,
signRefreshToken,
verifyAccessToken,
revokeRefreshToken,
verifyRefreshToken,
}