Pular para o conteúdo principal

@cactus-agents/auth

Serviço de autenticação + lógica de refresh de token. Framework-agnostic.

Instalação

pnpm add @cactus-agents/auth

Uso básico

A forma recomendada é usar createAuthFromClient, que aceita um ApiClient diretamente:

import { createApiClient } from '@cactus-agents/api-client';
import { createAuthFromClient } from '@cactus-agents/auth';

const client = createApiClient({ baseUrl, tenant, language });
const auth = createAuthFromClient(client);

const result = await auth.login({
login: 'user@email.com',
password: 'senha123',
});

// result.access_token
// result.user
// result.userInfo

Uso de baixo nível (fetcher manual)

Se precisar de controle total sobre o adapter HTTP, use createAuthService:

import { createAuthService } from '@cactus-agents/auth';

const authService = createAuthService({
get: (path) => myHttpClient.get(path),
post: (path, body) => myHttpClient.post(path, body),
});

API — AuthService

login(payload)

interface LoginPayload {
login: string; // email ou CPF
password: string;
captcha_token?: string;
app_source?: string;
two_factor_code?: number;
}

interface LoginResponse {
access_token: string;
expires_in: number;
token_type: string;
user: AuthUser;
userInfo: AuthUserInfo;
type?: 'cancelled_account' | 'two_factor_code';
}

logout()

POST /auth/logout — sem body, sem retorno.

getUserProfile()

GET /auth/user-profile?check_spa_again=1

Retorna { user: AuthUser, userInfo: AuthUserInfo }.

refreshToken()

POST /users/refresh-token

Retorna { access_token: string }.

registerSimplified(payload)

POST /bff/register-simplified

interface RegisterSimplifiedPayload {
email: string;
password: string;
country: string;
nationalities: string; // JSON string
optIn: boolean;
ddi?: string;
phone?: string;
name?: string;
birth_date?: string;
number?: string; // documento
captcha_token?: string;
app_source?: string;
affiliation_code?: string;

// ─── Tracking de marketing (paridade com legado Nuxt) ─────────────────
// Anexados pelo template a partir do cookie `cookie_tracking` + `_ga`.
// Detalhes de captura, política de atribuição (last-touch) e aliases de URL
// em → ../architecture/marketing-tracking.md
utm_source?: string;
utm_campaign?: string;
utm_content?: string;
utm_medium?: string;
/** Mapeado de `utm_src` na URL. Campo legado mantido para BI. */
src?: string;
/** Client ID do Google Analytics (cookie `_ga`). */
ga_client_id?: string;
}

Retorna LoginResponse (mesmo formato do login).

forgotPassword(payload)

POST /auth/passwords/reset/options

interface ForgotPasswordPayload {
login: string;
captcha_token?: string;
}

validateDocument(payload)

interface ValidateDocumentPayload {
number: string;
captcha_token?: string;
}

interface ValidateDocumentResponse {
docnumber?: string;
docnumber_valid?: boolean;
birth_date?: string;
gender?: string;
mother_name?: string;
name?: string;
}

Token Refresh

Funções puras para gerenciar o ciclo de refresh (intervalo de 6h, mesmo do Vue legado):

import {
initialRefreshState,
shouldRefreshToken,
markTokenSaved,
markRefreshStarted,
markRefreshCompleted,
} from '@cactus-agents/auth';

let state = markTokenSaved(); // marca quando token é salvo

// A cada navegação ou intervalo:
if (shouldRefreshToken(state)) {
state = markRefreshStarted(state);
try {
const { access_token } = await authService.refreshToken();
state = markRefreshCompleted(state, true);
} catch {
state = markRefreshCompleted(state, false);
}
}

Tipos principais

AuthUser

interface AuthUser {
id: number;
email: string;
username: string;
name: string;
first_name: string;
last_name: string;
phone: string;
ddi: string;
birth_date: string;
gender: number;
country: string;
language: string;
currency: string;
document: AuthUserDocument | null;
country_data: AuthUserCountryData | null;
wallet: AuthUserWallet | null;
token: string;
is_active: number;
cancelled_account: number;
bonus_enabled: number;
ftd_date: string | null;
ftd_value: number;
mother_name: string;
created_at: string;
updated_at: string;
last_login: string;
affiliation_code?: string;
latestKyc?: AuthLatestKyc;
}

AuthUserInfo

interface AuthUserInfo {
validate_email_at: string;
login_at: string;
login_attempt_qty: number;
seven_days_since_last_login: boolean;
strong_password: number;
force_request_kyc: boolean;
two_factor_enabled: boolean;
two_factor_type?: string;
validate_sms_at: string;
force_request_kyc_reasons?: ForceRequestKycReason[];
two_factor_at?: string | null;
two_factor_code?: string | null;
latitude?: number;
longitude?: number;
location_at?: string;
nationalities?: string;
tc_accepted_at?: string | null;
privacy_accepted_at?: string | null;
lgpd_accepted_at?: string | null;
law_accepted_at?: string | null;
mkt_accepted_at?: string | null;
// Responsible gaming limits
spa_bet_limit?: number | null;
spa_loss_limit?: number | null;
spa_deposit_limit?: number | null;
spa_withdrawal_limit?: number | null;
spa_time_limit?: number | null;
spa_period_limit?: string | null;
spa_note?: string | null;
}

Exports

O pacote exporta os seguintes tipos e funções:

ExportTipoDescrição
createAuthServicefunctionCria AuthService a partir de fetcher manual
createAuthFromClientfunctionCria AuthService a partir de ApiClient
AuthServicetypeInterface do serviço de auth
AuthFetchertypeInterface do fetcher esperado pelo auth
LoginPayloadtypePayload de login
LoginResponsetypeResposta de login
RegisterSimplifiedPayloadtypePayload de registro simplificado
ForgotPasswordPayloadtypePayload de esqueci a senha
ValidateDocumentPayloadtypePayload de validação de documento
ValidateDocumentResponsetypeResposta de validação de documento
AuthUsertypeDados do usuário
AuthUserInfotypeInfo complementar do usuário
AuthUserDocumenttypeDocumento do usuário
AuthUserCountryDatatypeDados do país do usuário
AuthUserWallettypeCarteira do usuário
AuthLatestKyctypeÚltimo KYC do usuário
RefreshTokenResponsetypeResposta de refresh de token
ForceRequestKycReasontypeMotivos para forçar KYC
TokenRefreshStatetypeEstado do ciclo de refresh
initialRefreshStatefunctionEstado inicial do refresh
shouldRefreshTokenfunctionVerifica se deve fazer refresh
markTokenSavedfunctionMarca token como salvo
markRefreshStartedfunctionMarca início do refresh
markRefreshCompletedfunctionMarca fim do refresh