New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

@tc-libs/helper

Package Overview
Dependencies
Maintainers
1
Versions
117
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@tc-libs/helper

Package di utilita condivise per NestJS. Espone un `HelperModule` registrabile e una serie di servizi iniettabili per:

latest
npmnpm
Version
3.9.0
Version published
Maintainers
1
Created
Source

@tc-libs/helper

Package di utilita condivise per NestJS. Espone un HelperModule registrabile e una serie di servizi iniettabili per:

  • date e intervalli temporali
  • stringhe, slug, password e riferimenti casuali
  • numeri e percentuali
  • hashing
  • cifratura Base64, AES e JWT
  • gestione access token, refresh token e permission token
  • controlli geografici su raggio

Quando usarlo

Usa questa libreria quando vuoi centralizzare logica tecnica riusabile invece di duplicare helper statici nei singoli servizi applicativi.

I package authentication, pagination, request, setting, task e altri dipendono gia da questi servizi.

Installazione nel modulo Nest

Registrazione sincrona

import { Module } from '@nestjs/common';
import { HelperModule } from '@tc-libs/helper';

@Module({
  imports: [
    HelperModule.register(
      {
        jwt: {
          defaultSecretKey: process.env.JWT_DEFAULT_SECRET!,
          defaultExpirationTime: 3600,
        },
        auth: {
          subject: 'access',
          audience: 'my-api',
          issuer: 'my-service',
          accessToken: {
            secretKey: process.env.ACCESS_TOKEN_SECRET!,
            expirationTime: 3600,
            notBeforeExpirationTime: 0,
            encryptKey: process.env.ACCESS_TOKEN_ENCRYPT_KEY!,
            encryptIv: process.env.ACCESS_TOKEN_ENCRYPT_IV!,
          },
          refreshToken: {
            secretKey: process.env.REFRESH_TOKEN_SECRET!,
            expirationTime: 86400,
            expirationTimeRememberMe: 2592000,
            notBeforeExpirationTime: 0,
            encryptKey: process.env.REFRESH_TOKEN_ENCRYPT_KEY!,
            encryptIv: process.env.REFRESH_TOKEN_ENCRYPT_IV!,
          },
          permissionToken: {
            secretKey: process.env.PERMISSION_TOKEN_SECRET!,
            expirationTime: 900,
            notBeforeExpirationTime: 0,
            encryptKey: process.env.PERMISSION_TOKEN_ENCRYPT_KEY!,
            encryptIv: process.env.PERMISSION_TOKEN_ENCRYPT_IV!,
          },
        },
      },
      true,
    ),
  ],
})
export class AppModule {}

Registrazione asincrona

HelperModule.registerAsync(
  {
    imports: [ConfigModule],
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => ({
      jwt: {
        defaultSecretKey: configService.getOrThrow<string>('JWT_DEFAULT_SECRET'),
        defaultExpirationTime: 3600,
      },
      auth: {
        subject: 'access',
        audience: 'my-api',
        issuer: 'my-service',
        accessToken: {
          secretKey: configService.getOrThrow<string>('ACCESS_TOKEN_SECRET'),
          expirationTime: 3600,
          notBeforeExpirationTime: 0,
          encryptKey: configService.getOrThrow<string>('ACCESS_TOKEN_ENCRYPT_KEY'),
          encryptIv: configService.getOrThrow<string>('ACCESS_TOKEN_ENCRYPT_IV'),
        },
        refreshToken: {
          secretKey: configService.getOrThrow<string>('REFRESH_TOKEN_SECRET'),
          expirationTime: 86400,
          expirationTimeRememberMe: 2592000,
          notBeforeExpirationTime: 0,
          encryptKey: configService.getOrThrow<string>('REFRESH_TOKEN_ENCRYPT_KEY'),
          encryptIv: configService.getOrThrow<string>('REFRESH_TOKEN_ENCRYPT_IV'),
        },
        permissionToken: {
          secretKey: configService.getOrThrow<string>('PERMISSION_TOKEN_SECRET'),
          expirationTime: 900,
          notBeforeExpirationTime: 0,
          encryptKey: configService.getOrThrow<string>('PERMISSION_TOKEN_ENCRYPT_KEY'),
          encryptIv: configService.getOrThrow<string>('PERMISSION_TOKEN_ENCRYPT_IV'),
        },
      },
    }),
  },
  true,
);

Servizi esportati

import {
  DateService,
  EncryptionService,
  GeoService,
  HashService,
  NumberService,
  PasswordService,
  StringService,
  TokenService,
} from '@tc-libs/helper';

DateService

Operazioni principali:

  • validazione date e timestamp
  • formattazione
  • differenze tra date in giorni, minuti, ore, secondi o millisecondi
  • forward/backward di intervalli temporali
  • start/end di giorno, mese e anno
  • estrazione di giorno, mese e anno

Esempio:

const expiresAt = this.dateService.forwardInMinutes(15);
const age = this.dateService.calculateAge(user.birthDate);

StringService

Operazioni principali:

  • validazione email
  • generazione stringhe casuali e riferimenti
  • controllo robustezza password
  • censura di valori sensibili
  • slugify

Esempio:

const slug = this.stringService.slugify('Listino Prezzi 2026');
const reference = this.stringService.randomReference(6, 'ORD');

NumberService

Operazioni principali:

  • check di numeri interi o reali in input stringa
  • conversione a number
  • generazione random
  • calcolo percentuali
const code = this.numberService.random(6);
const completion = this.numberService.percent(done, total);

HashService

Espone:

  • sha1Base64
  • sha256
const digest = this.hashService.sha256(payload);

PasswordService

Wrapper su bcryptjs per hashing e confronto password:

const hashed = await this.passwordService.hashPassword(plainPassword);
const isValid = await this.passwordService.compare(plainPassword, hashed);

EncryptionService

Espone primitive per:

  • Base64 encode/decode
  • AES-256 CBC encrypt/decrypt
  • sign, decode e verify JWT
const encrypted = this.encryptionService.aes256Encrypt(data, key, iv);
const token = this.encryptionService.jwtEncrypt(payload, {
  secretKey,
  expiredIn: 3600,
  audience: 'my-api',
  issuer: 'my-service',
  subject: 'access',
});

TokenService

Servizio ad alto livello costruito sopra EncryptionService e configurazione auth.

Casi d'uso principali:

  • creare access token
  • creare refresh token con supporto rememberMe
  • creare permission token
  • validare token
  • leggere payload JWT
  • cifrare/decifrare il payload contenuto nei token
const payload = this.tokenService.createPayloadAccessToken(
  { user: user._id, email: user.email },
  false,
);

const encryptedPayload = await this.tokenService.encryptAccessToken(payload);
const accessToken = this.tokenService.createAccessToken(encryptedPayload);

GeoService

Controlla se un punto e dentro un raggio espresso in metri:

const allowed = this.geoService.inRadius(
  { latitude: 45.4642, longitude: 9.19, radiusInMeters: 500 },
  { latitude: 45.465, longitude: 9.191 },
);

Export aggiuntivi

Oltre ai servizi, il package esporta:

  • interfacce per date, stringhe, numeri, cifratura e token
  • costanti data come ENUM_DATE_FORMAT e ENUM_DATE_DIFF
  • token di configurazione HELPER_CONFIG_OPTIONS
  • tipi HelperOptions e HelperAsyncOptions

Note operative

  • TokenService dipende dalla registrazione di HelperModule con configurazione completa.
  • EncryptionService usa JwtService, quindi va risolto tramite DI Nest invece di essere istanziato manualmente.
  • Le chiavi AES e gli IV devono essere coerenti con il formato atteso dall'applicazione che produce/consuma i token.

Sviluppo

nx build helper
nx test helper

FAQs

Package last updated on 01 Apr 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts