@ministerjs/auth 2.0.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ declare class AuthController<User extends Record<string, any> = Record<string, a
5
5
  constructor(driver: AuthDriver<User>);
6
6
  login(body: AuthPayload, request: Request, response: Response): Promise<AuthResponse<User>>;
7
7
  checkIn(request: Request, response: Response): Promise<AuthResponse<User>>;
8
+ refresh(request: Request, response: Response): Promise<AuthResponse<User>>;
8
9
  logout(request: Request, response: Response): Promise<LogoutResponse>;
9
10
  }
10
11
  export { AuthController };
@@ -1,5 +1,6 @@
1
1
  import { DynamicModule, Type } from "@nestjs/common";
2
2
  import type { AuthDriver } from "./types";
3
+ import { JwtAuthGuard, type JwtAuthGuardOptions } from "./guards/JwtAuthGuard";
3
4
  type DriverProvider<User> = AuthDriver<User> | {
4
5
  useValue: AuthDriver<User>;
5
6
  } | {
@@ -26,6 +27,7 @@ interface AuthModuleAsyncOptions<User = any> {
26
27
  declare class AuthModule {
27
28
  static register<User = any>(options: AuthModuleOptions<User>): DynamicModule;
28
29
  static registerAsync<User = any>(options: AuthModuleAsyncOptions<User>): DynamicModule;
30
+ static createGuard(options: JwtAuthGuardOptions): JwtAuthGuard;
29
31
  private static normalizeDriverProvider;
30
32
  }
31
33
  export type { AuthModuleOptions, AuthModuleAsyncOptions, DriverProvider };
@@ -1,7 +1,13 @@
1
1
  import type { CookieOptions, Request, Response } from "express";
2
2
  import { type SignOptions } from "jsonwebtoken";
3
- import type { AuthDriver, AuthPayload } from "./types";
4
- type PrismaClientLike = Record<string, any>;
3
+ import type { AuthDriver, LoginPayload, AuditEvent } from "./types";
4
+ import type { LockoutStore, RefreshTokenStore } from "./stores";
5
+ interface PrismaModelDelegate {
6
+ findUnique(args: {
7
+ where: Record<string, unknown>;
8
+ }): Promise<any>;
9
+ }
10
+ type PrismaClientLike = Record<string, PrismaModelDelegate | undefined>;
5
11
  interface JwtPrismaDriverOptions {
6
12
  prisma: PrismaClientLike;
7
13
  /**
@@ -38,12 +44,52 @@ interface JwtPrismaDriverOptions {
38
44
  cookieOptions?: Partial<CookieOptions>;
39
45
  /**
40
46
  * Função de comparação de senha (p.ex. bcrypt.compare).
47
+ * Obrigatório — não há fallback para comparação em plain-text.
41
48
  */
42
- comparePassword?: (provided: string, stored: unknown) => Promise<boolean> | boolean;
49
+ comparePassword: (provided: string, stored: unknown) => Promise<boolean> | boolean;
43
50
  /**
44
51
  * Permite alterar a shape do usuário retornado.
45
52
  */
46
53
  transformUser?: <T extends Record<string, any>>(user: T) => any;
54
+ /**
55
+ * Habilita proteção CSRF via double-submit cookie.
56
+ * No login, emite um cookie `csrf_token` (não-httpOnly) que o cliente
57
+ * deve enviar no header `x-csrf-token` em requisições autenticadas.
58
+ */
59
+ csrf?: boolean;
60
+ /**
61
+ * Callback de auditoria chamado em cada evento de autenticação.
62
+ */
63
+ onAudit?: (event: AuditEvent) => void | Promise<void>;
64
+ /**
65
+ * Callback de rate limiting chamado antes de cada tentativa de login.
66
+ * Retorne `false` para bloquear a tentativa.
67
+ */
68
+ onRateLimitCheck?: (ip: string, identifier: string) => Promise<boolean> | boolean;
69
+ /**
70
+ * Configuração de account lockout.
71
+ */
72
+ lockout?: {
73
+ /** Número máximo de tentativas antes de bloquear (default: 5). */
74
+ maxAttempts?: number;
75
+ /** Janela de tempo em ms para contar falhas (default: 15 min). */
76
+ windowMs?: number;
77
+ /** Store customizado para persistir falhas (default: InMemoryLockoutStore). */
78
+ store?: LockoutStore;
79
+ };
80
+ /**
81
+ * Configuração de refresh token rotation.
82
+ * Quando habilitado, login emite um par access + refresh token.
83
+ */
84
+ refreshToken?: {
85
+ enabled: boolean;
86
+ /** Nome do cookie do refresh token (default: "refresh_token"). */
87
+ cookieName?: string;
88
+ /** Tempo de expiração do refresh token (default: "30d"). */
89
+ expiresIn?: SignOptions["expiresIn"];
90
+ /** Store para persistir refresh tokens (default: InMemoryRefreshTokenStore). */
91
+ store?: RefreshTokenStore;
92
+ };
47
93
  }
48
94
  declare class JwtPrismaCookieAuthDriver<User extends Record<string, any>> implements AuthDriver<User> {
49
95
  private readonly prismaModel;
@@ -56,10 +102,22 @@ declare class JwtPrismaCookieAuthDriver<User extends Record<string, any>> implem
56
102
  private readonly cookieOptions;
57
103
  private readonly comparePassword;
58
104
  private readonly transformUser;
105
+ private readonly csrf;
106
+ private readonly onAudit?;
107
+ private readonly onRateLimitCheck?;
108
+ private readonly lockoutStore?;
109
+ private readonly lockoutMaxAttempts;
110
+ private readonly refreshTokenEnabled;
111
+ private readonly refreshTokenCookieName;
112
+ private readonly refreshTokenExpiresIn;
113
+ private readonly refreshTokenStore?;
59
114
  constructor(options: JwtPrismaDriverOptions);
60
- login(payload: AuthPayload, _req: Request, res: Response): Promise<User>;
115
+ login(payload: LoginPayload, req: Request, res: Response): Promise<User>;
61
116
  checkIn(req: Request, res: Response): Promise<User | null>;
62
- logout(_req: Request, res: Response): Promise<void>;
117
+ logout(req: Request, res: Response): Promise<void>;
118
+ refresh(req: Request, res: Response): Promise<User | null>;
119
+ private issueRefreshToken;
120
+ private emitAudit;
63
121
  }
64
- export type { JwtPrismaDriverOptions };
122
+ export type { PrismaModelDelegate, PrismaClientLike, JwtPrismaDriverOptions };
65
123
  export { JwtPrismaCookieAuthDriver };
@@ -0,0 +1,17 @@
1
+ import { CanActivate, ExecutionContext } from "@nestjs/common";
2
+ interface JwtAuthGuardOptions {
3
+ jwtSecret: string;
4
+ cookieName?: string;
5
+ csrfEnabled?: boolean;
6
+ }
7
+ declare class JwtAuthGuard implements CanActivate {
8
+ private readonly jwtSecret;
9
+ private readonly cookieName;
10
+ private readonly csrfEnabled;
11
+ constructor(options: JwtAuthGuardOptions);
12
+ canActivate(context: ExecutionContext): boolean;
13
+ private extractToken;
14
+ private validateCsrf;
15
+ }
16
+ export type { JwtAuthGuardOptions };
17
+ export { JwtAuthGuard };
@@ -0,0 +1,8 @@
1
+ import { CanActivate, ExecutionContext } from "@nestjs/common";
2
+ import { Reflector } from "@nestjs/core";
3
+ declare class RolesGuard implements CanActivate {
4
+ private readonly reflector;
5
+ constructor(reflector: Reflector);
6
+ canActivate(context: ExecutionContext): boolean;
7
+ }
8
+ export { RolesGuard };
@@ -0,0 +1,2 @@
1
+ export * from "./JwtAuthGuard";
2
+ export * from "./RolesGuard";
@@ -1,5 +1,8 @@
1
1
  export * from "./types";
2
2
  export * from "./token";
3
+ export * from "./stores";
4
+ export * from "./rbac";
5
+ export * from "./guards";
3
6
  export * from "./AuthController";
4
7
  export * from "./AuthModule";
5
8
  export * from "./JwtPrismaCookieAuthDriver";
@@ -0,0 +1,3 @@
1
+ declare const ROLES_KEY = "ministerjs:roles";
2
+ declare const Roles: (...roles: string[]) => import("@nestjs/common").CustomDecorator<string>;
3
+ export { ROLES_KEY, Roles };
@@ -0,0 +1,36 @@
1
+ interface LockoutStore {
2
+ recordFailure(key: string): Promise<void>;
3
+ getFailures(key: string): Promise<number>;
4
+ reset(key: string): Promise<void>;
5
+ }
6
+ declare class InMemoryLockoutStore implements LockoutStore {
7
+ private readonly windowMs;
8
+ private entries;
9
+ constructor(windowMs: number);
10
+ recordFailure(key: string): Promise<void>;
11
+ getFailures(key: string): Promise<number>;
12
+ reset(key: string): Promise<void>;
13
+ }
14
+ interface RefreshTokenStore {
15
+ save(jti: string, userId: string, expiresAt: Date): Promise<void>;
16
+ find(jti: string): Promise<{
17
+ userId: string;
18
+ expiresAt: Date;
19
+ } | null>;
20
+ revoke(jti: string): Promise<void>;
21
+ revokeAll(userId: string): Promise<void>;
22
+ }
23
+ interface RefreshTokenEntry {
24
+ userId: string;
25
+ expiresAt: Date;
26
+ }
27
+ declare class InMemoryRefreshTokenStore implements RefreshTokenStore {
28
+ private tokens;
29
+ private userJtis;
30
+ save(jti: string, userId: string, expiresAt: Date): Promise<void>;
31
+ find(jti: string): Promise<RefreshTokenEntry | null>;
32
+ revoke(jti: string): Promise<void>;
33
+ revokeAll(userId: string): Promise<void>;
34
+ }
35
+ export type { LockoutStore, RefreshTokenStore };
36
+ export { InMemoryLockoutStore, InMemoryRefreshTokenStore };
@@ -1,5 +1,9 @@
1
1
  import type { Request, Response } from "express";
2
- export type AuthPayload = Record<string, any>;
2
+ export interface LoginPayload {
3
+ [key: string]: string;
4
+ }
5
+ /** @deprecated Use LoginPayload */
6
+ export type AuthPayload = LoginPayload;
3
7
  export interface AuthResponse<User> {
4
8
  message: string;
5
9
  data: User;
@@ -7,11 +11,37 @@ export interface AuthResponse<User> {
7
11
  export interface LogoutResponse {
8
12
  message: string;
9
13
  }
14
+ export interface JwtAccessPayload {
15
+ sub: string;
16
+ roles?: string[];
17
+ iat?: number;
18
+ exp?: number;
19
+ }
20
+ export interface JwtRefreshPayload {
21
+ sub: string;
22
+ jti: string;
23
+ iat?: number;
24
+ exp?: number;
25
+ }
26
+ export interface AuthenticatedUser {
27
+ id: string;
28
+ roles: string[];
29
+ [key: string]: unknown;
30
+ }
31
+ export interface AuditEvent {
32
+ action: "login" | "logout" | "checkin" | "refresh" | "lockout";
33
+ userId?: string;
34
+ ip?: string;
35
+ userAgent?: string;
36
+ timestamp: Date;
37
+ success: boolean;
38
+ metadata?: Record<string, unknown>;
39
+ }
10
40
  export interface AuthDriver<User = any> {
11
41
  /**
12
42
  * Deve validar o payload recebido e retornar o usuário autenticado.
13
43
  */
14
- login(payload: AuthPayload, request: Request, response: Response): Promise<User> | User;
44
+ login(payload: LoginPayload, request: Request, response: Response): Promise<User> | User;
15
45
  /**
16
46
  * Deve recuperar o usuário a partir do contexto (cookies, headers, sessão, etc.).
17
47
  * Retorne `null` ou `undefined` quando não houver sessão ativa.
@@ -21,4 +51,9 @@ export interface AuthDriver<User = any> {
21
51
  * Deve encerrar a sessão/tokens do usuário.
22
52
  */
23
53
  logout(request: Request, response: Response): Promise<void> | void;
54
+ /**
55
+ * Renova os tokens usando um refresh token.
56
+ * Opcional — drivers que não implementam retornam undefined.
57
+ */
58
+ refresh?(request: Request, response: Response): Promise<User | null | undefined> | User | null | undefined;
24
59
  }
@@ -17,12 +17,14 @@ declare class Auth<User extends Record<string, any>> {
17
17
  on: Ref<boolean, boolean>;
18
18
  loading: Ref<boolean, boolean>;
19
19
  checkedIn: Ref<boolean, boolean>;
20
+ roles: Ref<string[]>;
20
21
  private fetch;
21
22
  private mapUser;
22
23
  private afterLogout;
23
24
  private afterCheckIn;
24
25
  private routes;
25
26
  constructor({ fetch, mapUser, routes, afterLogout, afterCheckIn, }: Options<User>);
27
+ signUp(payload: Record<string, any>): Promise<void>;
26
28
  login(payload: Record<string, any>): Promise<void>;
27
29
  checkIn(): Promise<void>;
28
30
  logout(): Promise<void>;