All files / src/database CoreDb.ts

100% Statements 9/9
100% Branches 0/0
100% Functions 5/5
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66            1x                                                                         1x 1x       1x 1x 1x       1x       3x       1x      
import { randomUUID } from 'crypto';
import GKey from './entity/GKey';
import { CoreDBCon, CoreDBPrefab, CoreEntityWrapper } from '../classes';
import { generateSeed } from '../modules';
import type { ICoreDb } from '../lib';
 
export const CORE_DB_VERSION = '0';
 
/**
 * CoreDb handles the storage, retrieval, and deletion of cryptographic keys (GKey entities) within the underlying database.
 *
 * @class
 * @extends CoreDBPrefab<any>
 * @implements ICoreDb
 *
 * @constructor
 * @param {CoreDBCon<any, any>} db - The CoreDBCon instance that this CoreDb wraps.
 *
 * @method initPrefabDB
 * @returns {Promise<void>}
 * @description Generates a seed and a unique identifier, then stores them in the configuration. This method is called to initialize the prefab database.
 *
 * @method deleteKey
 * @param {string} e_id - The identifier of the GKey to delete.
 * @returns {Promise<void>}
 * @description Removes the GKey identified by `e_id` from the database.
 *
 * @method getKey
 * @param {string} e_id - The identifier of the GKey to retrieve.
 * @returns {Promise<GKey|null>}
 * @description Retrieves a GKey object by its identifier. Returns `null` if no matching key is found.
 *
 * @method setKey
 * @param {string} secret - The secret key value.
 * @param {Buffer} iv - The initialization vector.
 * @param {Buffer} auth - The authentication data.
 * @returns {Promise<string>}
 * @description Creates a new GKey entry with the provided parameters and returns the newly generated identifier.
 */
export default class CoreDb extends CoreDBPrefab<any> implements ICoreDb {
  private gKey: CoreEntityWrapper<GKey>;
 
  constructor(db: CoreDBCon<any, any>) {
    super(db);
    this.gKey = this.registerEntity<GKey>(new GKey());
  }
 
  async initPrefabDB(): Promise<void> {
    const seed = generateSeed();
    await this.setConfig('seed', seed);
    await this.setConfig('uid', randomUUID());
  }
 
  async deleteKey(e_id: string): Promise<void> {
    await this.gKey.delete(e_id);
  }
 
  getKey(e_id: string): Promise<GKey | null> {
    return this.gKey.getObjById(e_id);
  }
 
  async setKey(secret: string, iv: Buffer, auth: Buffer): Promise<string> {
    return (await this.gKey.createObject(new GKey({ secret, iv, auth }))).e_id;
  }
}