Fixed some bugs in api and auth services, completed auth cores.
This commit is contained in:
28
stream/src/core/securitycore.js
Normal file
28
stream/src/core/securitycore.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import crypto from 'crypto';
|
||||
|
||||
const SECRET = process.env.SENSOR_SECURITY_SECRET;
|
||||
|
||||
/**
|
||||
* Calcola l'HMAC-SHA256 del codice sensore con il secret token server-side.
|
||||
* - return {String} l'hash in formato hex
|
||||
*/
|
||||
export function getHmac(code) {
|
||||
return crypto.createHmac('sha256', SECRET || '').update(code).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica timing-safe del codice a partire dal suo hash salvato..
|
||||
* - return {Boolean} true se il codice è valido, false altrimenti
|
||||
*/
|
||||
export function verify(code, hash) {
|
||||
if (!code || !hash || !SECRET) return false;
|
||||
try {
|
||||
const computed = getHmac(code);
|
||||
const a = Buffer.from(computed, 'hex');
|
||||
const b = Buffer.from(hash, 'hex');
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
26
stream/src/core/sessioncore.js
Normal file
26
stream/src/core/sessioncore.js
Normal file
@@ -0,0 +1,26 @@
|
||||
import { queryData as data } from '../data/db.js'
|
||||
|
||||
const maxTries = 10;
|
||||
|
||||
/*
|
||||
Generates a random, unique session ID like `s00123`.
|
||||
*/
|
||||
function makeID() {
|
||||
const n = Math.floor(Math.random() * 100_000).toString().padStart(5, '0');
|
||||
return `s${n}`;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
Creates a new session by generating a unique ID and checking for conflicts in the database.
|
||||
*/
|
||||
export async function newSession() {
|
||||
for (let i = 0; i < maxTries; i++) {
|
||||
const id = makeID();
|
||||
const { rows } = await data(`select 1 from telemetrysessions where session_id = $1 and ended_at is null`, [id]);
|
||||
if (rows.length === 0) {
|
||||
return id;
|
||||
}
|
||||
}
|
||||
throw new Error('Failed to create session');
|
||||
}
|
||||
Reference in New Issue
Block a user