@nathapp/nestjs-auth-2fa 4.0.3 → 4.1.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @nathapp/nestjs-auth-2fa@4.0.3 build
2
+ > @nathapp/nestjs-auth-2fa@4.1.1 build
3
3
  > rimraf dist && tsc -p tsconfig.json
4
4
 
package/README.md CHANGED
@@ -13,4 +13,82 @@
13
13
 
14
14
  5. Guard is not provided in module, required manually provide
15
15
 
16
- 6. TOTP replay protection (default `OtpLibTwoFactorAuthProvider`) is in-process only: once a (secret, time-window) slot verifies, the same token is rejected for that window within a TTL of `(window * 2 + 2) * step` seconds (tracked slots are capped at 10,000 with expired-entry sweeping). Because the state lives in the Node process memory, multi-instance / distributed deployments MUST supply a custom `TwoFactorAuthProvider` backed by shared storage (e.g. Redis) to enforce replay protection across nodes. Rate limiting is still the consumer's responsibility.
16
+ ## TOTP replay protection
17
+
18
+ Since 4.0.3, the default `OtpLibTwoFactorAuthProvider` accepts each valid
19
+ (secret, time-step) slot only once. Enrollment confirmation consumes the slot
20
+ just like login or step-up verification, so reusing that code immediately is
21
+ rejected. Retention is `(window * 2 + 2) * step` seconds: 120 seconds for the
22
+ default `window: 1` and 30-second step. This is replay-record retention, not an
23
+ extension of the code's validity or a blanket 120-second block on new codes.
24
+
25
+ Replay protection defaults to `true`. Applications that intentionally allow
26
+ same-step reuse can explicitly disable it:
27
+
28
+ ```typescript
29
+ TwoFactorAuthModule.register({
30
+ type: TwoFactorType.TOTP,
31
+ issuer: 'MyApp',
32
+ replayProtection: false,
33
+ });
34
+ ```
35
+
36
+ Disabling replay protection permits reuse of a valid code throughout its
37
+ accepted window. Prefer passing proof of the completed MFA challenge through
38
+ an enrollment/login flow when a second TOTP verification is unnecessary.
39
+
40
+ ### Store scope and repeated registration
41
+
42
+ The default `InMemoryTotpReplayStore` is **provider-local**. Direct injection and
43
+ the guard's provider map share the default provider within a registration,
44
+ but different registrations or manually constructed providers have separate
45
+ stores unless a common `replayStore` is supplied. The memory store holds at
46
+ most 10,000 live slots, sweeps expired entries at capacity, and rejects new
47
+ slots when full. It does not evict unexpired records to make room.
48
+
49
+ For repeated module registrations, export one application-owned store and
50
+ inject it into every options factory. `useExisting` aliases that same instance:
51
+
52
+ ```typescript
53
+ import { Module } from '@nestjs/common';
54
+ import {
55
+ InMemoryTotpReplayStore, TotpReplayStore, TwoFactorAuthModule, TwoFactorType,
56
+ } from '@nathapp/nestjs-auth-2fa';
57
+
58
+ @Module({
59
+ providers: [
60
+ InMemoryTotpReplayStore,
61
+ { provide: TotpReplayStore, useExisting: InMemoryTotpReplayStore },
62
+ ],
63
+ exports: [TotpReplayStore],
64
+ })
65
+ export class ReplayStoreModule {}
66
+
67
+ TwoFactorAuthModule.registerAsync({
68
+ imports: [ReplayStoreModule],
69
+ inject: [TotpReplayStore],
70
+ useFactory: (store: TotpReplayStore) => ({
71
+ type: TwoFactorType.TOTP,
72
+ issuer: 'MyApp',
73
+ replayStore: store,
74
+ }),
75
+ });
76
+ ```
77
+
78
+ Custom multi-provider registrations pass `replayProtection` / `replayStore`
79
+ through each TOTP registration's `options` object. Supply the same store there
80
+ as well if they must share consumption with the default provider.
81
+
82
+ ### Distributed storage
83
+
84
+ Across processes, implement `TotpReplayStore.consume(key, ttlMs)` using atomic
85
+ shared storage, such as Redis `SET key value PX ttlMs NX`. Return `true` only
86
+ when the key was newly consumed and `false` for an existing record. Namespace
87
+ keys consistently across applications that need to share protection. The
88
+ provider passes a SHA-256 secret hash plus the matched step, never the raw
89
+ secret. Store failures must throw/reject, not return success.
90
+
91
+ `consume` may return `boolean` or `Promise<boolean>`. The default memory store
92
+ keeps `verify` synchronous. When supplying an asynchronous store, direct
93
+ callers must `await provider.verify(token, { secret })`; guards already await
94
+ verification. Rate limiting remains the application's responsibility.
@@ -3,6 +3,7 @@ import { TwoFactorType, TwoFactorPolicy } from "../enum";
3
3
  import { TwoFactorSettingProvider } from "../provider/two-factor-setting.provider";
4
4
  import { TwoFactorAuthProvider } from "../provider/two-factor.provider";
5
5
  import { ProviderClassOrAsyncOptions } from "@nathapp/nestjs-common";
6
+ import type { SynchronousTotpReplayStore, TotpReplayStore } from "../provider/totp-replay-store";
6
7
  export declare const TWO_FACTOR_AUTH_MODULE_OPTIONS = "TWO_FACTOR_AUTH_MODULE_OPTIONS";
7
8
  export declare const TWO_FACTOR_AUTH_PROVIDER = "TWO_FACTOR_AUTH_PROVIDER";
8
9
  export declare const TWO_FACTOR_SETTING_PROVIDER = "TWO_FACTOR_SETTING_PROVIDER";
@@ -12,12 +13,14 @@ export interface TwoFactorProviderRegistration {
12
13
  provider: Type<TwoFactorAuthProvider>;
13
14
  options?: Record<string, unknown>;
14
15
  }
15
- export type TwoFactorAuthOptions = TotpAuthOptions;
16
- export interface TotpAuthOptions {
16
+ export type TwoFactorAuthOptions<TStore extends TotpReplayStore = SynchronousTotpReplayStore> = TotpAuthOptions<TStore>;
17
+ export interface TotpAuthOptions<TStore extends TotpReplayStore = SynchronousTotpReplayStore> {
17
18
  type: TwoFactorType.TOTP;
18
19
  issuer: string;
19
20
  bytesLength?: number;
20
21
  window?: number;
22
+ replayProtection?: boolean;
23
+ replayStore?: TStore;
21
24
  }
22
25
  export declare const DEFAULT_TWO_FACTOR_GUARD_OPTIONS: {
23
26
  from: "body";
@@ -33,7 +36,7 @@ export type TwoFactorAuthModuleOptions = {
33
36
  guardOptions?: TwoFactorGuardOptions;
34
37
  defaultPolicy?: TwoFactorPolicy;
35
38
  providers?: TwoFactorProviderRegistration[];
36
- } & TwoFactorAuthOptions;
39
+ } & TwoFactorAuthOptions<TotpReplayStore>;
37
40
  export type TwoFactorAuthModuleOptionsWithoutProvider = Omit<TwoFactorAuthModuleOptions, 'guardOptions'> & {
38
41
  guardOptions?: Omit<TwoFactorGuardOptions, 'twoFactorSettingProvider'>;
39
42
  };
@@ -1 +1 @@
1
- {"version":3,"file":"two-factor-auth.interface.js","sourceRoot":"","sources":["../../lib/module/two-factor-auth.interface.ts"],"names":[],"mappings":";;;AAMa,QAAA,8BAA8B,GAAG,gCAAgC,CAAC;AAElE,QAAA,wBAAwB,GAAG,0BAA0B,CAAC;AAEtD,QAAA,2BAA2B,GAAG,6BAA6B,CAAC;AAE5D,QAAA,wBAAwB,GAAG,0BAA0B,CAAC;AAgCtD,QAAA,gCAAgC,GAAG;IAC9C,IAAI,EAAE,MAAe;IACrB,KAAK,EAAE,KAAK;CACb,CAAC"}
1
+ {"version":3,"file":"two-factor-auth.interface.js","sourceRoot":"","sources":["../../lib/module/two-factor-auth.interface.ts"],"names":[],"mappings":";;;AAOa,QAAA,8BAA8B,GAAG,gCAAgC,CAAC;AAElE,QAAA,wBAAwB,GAAG,0BAA0B,CAAC;AAEtD,QAAA,2BAA2B,GAAG,6BAA6B,CAAC;AAE5D,QAAA,wBAAwB,GAAG,0BAA0B,CAAC;AAyCtD,QAAA,gCAAgC,GAAG;IAC9C,IAAI,EAAE,MAAe;IACrB,KAAK,EAAE,KAAK;CACb,CAAC"}
@@ -18,7 +18,7 @@ exports.createTwoFactorProvider = createTwoFactorProvider;
18
18
  const createTwoFactorProvidersMap = () => {
19
19
  return {
20
20
  provide: two_factor_auth_interface_2.TWO_FACTOR_PROVIDERS_MAP,
21
- useFactory: (options) => {
21
+ useFactory: (options, defaultProvider) => {
22
22
  const providersMap = new Map();
23
23
  if (options.providers && options.providers.length > 0) {
24
24
  for (const providerReg of options.providers) {
@@ -27,12 +27,11 @@ const createTwoFactorProvidersMap = () => {
27
27
  }
28
28
  }
29
29
  else if (options.type === enum_1.TwoFactorType.TOTP) {
30
- const totpProvider = new provider_1.OtpLibTwoFactorAuthProvider(options);
31
- providersMap.set(enum_1.TwoFactorType.TOTP, totpProvider);
30
+ providersMap.set(enum_1.TwoFactorType.TOTP, defaultProvider);
32
31
  }
33
32
  return providersMap;
34
33
  },
35
- inject: [two_factor_auth_interface_1.TWO_FACTOR_AUTH_MODULE_OPTIONS],
34
+ inject: [two_factor_auth_interface_1.TWO_FACTOR_AUTH_MODULE_OPTIONS, two_factor_auth_interface_1.TWO_FACTOR_AUTH_PROVIDER],
36
35
  };
37
36
  };
38
37
  exports.createTwoFactorProvidersMap = createTwoFactorProvidersMap;
@@ -1 +1 @@
1
- {"version":3,"file":"two-factor.provider.js","sourceRoot":"","sources":["../../lib/module/two-factor.provider.ts"],"names":[],"mappings":";;;AACA,2EAAyJ;AACzJ,0CAAiF;AACjF,kCAAwC;AACxC,2EAAuE;AAMhE,MAAM,uBAAuB,GAAG,GAAa,EAAE;IACpD,OAAO;QACL,OAAO,EAAE,oDAAwB;QACjC,UAAU,EAAE,CAAC,OAAmC,EAAE,EAAE;YAClD,OAAO,IAAI,sCAA2B,CAAC,OAA+B,CAAC,CAAC;QAC1E,CAAC;QACD,MAAM,EAAE,CAAC,0DAA8B,CAAC;KACzC,CAAA;AACH,CAAC,CAAA;AARY,QAAA,uBAAuB,2BAQnC;AAgCM,MAAM,2BAA2B,GAAG,GAAa,EAAE;IACxD,OAAO;QACL,OAAO,EAAE,oDAAwB;QACjC,UAAU,EAAE,CAAC,OAAmC,EAAE,EAAE;YAClD,MAAM,YAAY,GAAG,IAAI,GAAG,EAAwC,CAAC;YAGrE,IAAG,OAAO,CAAC,SAAS,IAAI,OAAO,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACrD,KAAI,MAAM,WAAW,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;oBAC3C,MAAM,gBAAgB,GAAG,IAAI,WAAW,CAAC,QAAQ,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;oBACvE,YAAY,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,EAAE,gBAAgB,CAAC,CAAC;gBACvD,CAAC;YACH,CAAC;iBAAM,IAAG,OAAO,CAAC,IAAI,KAAK,oBAAa,CAAC,IAAI,EAAE,CAAC;gBAE9C,MAAM,YAAY,GAAG,IAAI,sCAA2B,CAAC,OAA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AAI,EAAE,CAAC;gBAE9C,YAAY,CAAC,GAAG,CAAC,oBAAa,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;YACxD,CAAC;YAED,OAAO,YAAY,CAAC;QACtB,CAAC;QACD,MAAM,EAAE,CAAC,0DAA8B,EAAE,oDAAwB,CAAC;KACnE,CAAA;AACH,CAAC,CAAA;AArBY,QAAA,2BAA2B,+BAqBvC"}
@@ -1,2 +1,3 @@
1
1
  export * from './two-factor.provider';
2
2
  export * from './two-factor-setting.provider';
3
+ export * from './totp-replay-store';
@@ -16,4 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./two-factor.provider"), exports);
18
18
  __exportStar(require("./two-factor-setting.provider"), exports);
19
+ __exportStar(require("./totp-replay-store"), exports);
19
20
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/provider/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAAsC;AACtC,gEAA8C"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/provider/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wDAAsC;AACtC,gEAA8C;AAC9C,sDAAoC"}
@@ -0,0 +1,10 @@
1
+ export declare abstract class TotpReplayStore {
2
+ abstract consume(key: string, ttlMs: number): boolean | Promise<boolean>;
3
+ }
4
+ export interface SynchronousTotpReplayStore extends TotpReplayStore {
5
+ consume(key: string, ttlMs: number): boolean;
6
+ }
7
+ export declare class InMemoryTotpReplayStore extends TotpReplayStore {
8
+ private readonly usedWindows;
9
+ consume(key: string, ttlMs: number): boolean;
10
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryTotpReplayStore = exports.TotpReplayStore = void 0;
4
+ class TotpReplayStore {
5
+ }
6
+ exports.TotpReplayStore = TotpReplayStore;
7
+ class InMemoryTotpReplayStore extends TotpReplayStore {
8
+ constructor() {
9
+ super(...arguments);
10
+ this.usedWindows = new Map();
11
+ }
12
+ consume(key, ttlMs) {
13
+ var _a;
14
+ const now = Date.now();
15
+ if (((_a = this.usedWindows.get(key)) !== null && _a !== void 0 ? _a : 0) > now)
16
+ return false;
17
+ if (this.usedWindows.size >= 10000) {
18
+ for (const [slot, expiry] of this.usedWindows) {
19
+ if (expiry <= now)
20
+ this.usedWindows.delete(slot);
21
+ }
22
+ if (this.usedWindows.size >= 10000)
23
+ return false;
24
+ }
25
+ this.usedWindows.set(key, now + ttlMs);
26
+ return true;
27
+ }
28
+ }
29
+ exports.InMemoryTotpReplayStore = InMemoryTotpReplayStore;
30
+ //# sourceMappingURL=totp-replay-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"totp-replay-store.js","sourceRoot":"","sources":["../../lib/provider/totp-replay-store.ts"],"names":[],"mappings":";;;AAKA,MAAsB,eAAe;CAEpC;AAFD,0CAEC;AAQD,MAAa,uBAAwB,SAAQ,eAAe;IAA5D;;QACmB,gBAAW,GAAG,IAAI,GAAG,EAAkB,CAAC;IAiB3D,CAAC;IAfC,OAAO,CAAC,GAAW,EAAE,KAAa;;QAChC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,CAAC,MAAA,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,mCAAI,CAAC,CAAC,GAAG,GAAG;YAAE,OAAO,KAAK,CAAC;QAGzD,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,IAAI,KAAK,EAAE,CAAC;YACnC,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;gBAC9C,IAAI,MAAM,IAAI,GAAG;oBAAE,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACnD,CAAC;YACD,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,IAAI,KAAK;gBAAE,OAAO,KAAK,CAAC;QACnD,CAAC;QAED,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,KAAK,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAlBD,0DAkBC"}
@@ -1,20 +1,20 @@
1
1
  import { TotpAuthOptions } from "../module";
2
2
  import { TwoFactorType } from "../enum";
3
3
  import { TwoFactorVerifyContext } from "./two-factor-setting.provider";
4
+ import { SynchronousTotpReplayStore, TotpReplayStore } from "./totp-replay-store";
4
5
  export declare abstract class TwoFactorAuthProvider {
5
6
  abstract readonly type: TwoFactorType;
6
7
  abstract verify(token: string, context: TwoFactorVerifyContext): boolean | Promise<boolean>;
7
8
  }
8
- export declare class OtpLibTwoFactorAuthProvider extends TwoFactorAuthProvider {
9
+ export declare class OtpLibTwoFactorAuthProvider<TStore extends TotpReplayStore = SynchronousTotpReplayStore> extends TwoFactorAuthProvider {
9
10
  readonly type = TwoFactorType.TOTP;
10
11
  private readonly options;
11
12
  private readonly qrcodePackage;
12
13
  private readonly authenticator;
13
- private readonly usedWindows;
14
- constructor(options: TotpAuthOptions);
14
+ private readonly replayStore;
15
+ constructor(options: TotpAuthOptions<TStore>);
15
16
  generateSecret(): string;
16
- verify(token: string, context: TwoFactorVerifyContext): boolean;
17
- private sweepExpiredWindows;
17
+ verify(token: string, context: TwoFactorVerifyContext): boolean | ReturnType<TStore['consume']>;
18
18
  toKeyUri(secret: string, account: string): string;
19
19
  toDataUrl(secret: string, account: string): Promise<string>;
20
20
  }
@@ -4,23 +4,25 @@ exports.OtpLibTwoFactorAuthProvider = exports.TwoFactorAuthProvider = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const nestjs_common_1 = require("@nathapp/nestjs-common");
6
6
  const enum_1 = require("../enum");
7
+ const totp_replay_store_1 = require("./totp-replay-store");
7
8
  function definedOnly(options) {
8
9
  const defined = Object.entries(options !== null && options !== void 0 ? options : {}).filter(([, value]) => value !== undefined);
9
10
  return Object.fromEntries(defined);
10
11
  }
11
- const USED_WINDOWS_CAP = 10000;
12
12
  class TwoFactorAuthProvider {
13
13
  }
14
14
  exports.TwoFactorAuthProvider = TwoFactorAuthProvider;
15
15
  class OtpLibTwoFactorAuthProvider extends TwoFactorAuthProvider {
16
16
  constructor(options) {
17
+ var _a;
17
18
  super();
18
19
  this.type = enum_1.TwoFactorType.TOTP;
19
- this.usedWindows = new Map();
20
20
  this.options = Object.assign({
21
21
  bytesLength: 32,
22
- window: 1
22
+ window: 1,
23
+ replayProtection: true,
23
24
  }, definedOnly(options));
25
+ this.replayStore = (_a = this.options.replayStore) !== null && _a !== void 0 ? _a : new totp_replay_store_1.InMemoryTotpReplayStore();
24
26
  const otplib = (0, nestjs_common_1.loadPackage)('otplib');
25
27
  if (typeof otplib.authenticator.clone === 'function') {
26
28
  this.authenticator = otplib.authenticator.clone();
@@ -36,14 +38,14 @@ class OtpLibTwoFactorAuthProvider extends TwoFactorAuthProvider {
36
38
  try {
37
39
  this.qrcodePackage = (0, nestjs_common_1.loadPackage)('qrcode');
38
40
  }
39
- catch (_a) {
41
+ catch (_b) {
40
42
  }
41
43
  }
42
44
  generateSecret() {
43
45
  return this.authenticator.generateSecret(this.options.bytesLength);
44
46
  }
45
47
  verify(token, context) {
46
- var _a, _b;
48
+ var _a;
47
49
  if (!context.secret) {
48
50
  throw new Error('TOTP verification requires secret in context');
49
51
  }
@@ -52,7 +54,7 @@ class OtpLibTwoFactorAuthProvider extends TwoFactorAuthProvider {
52
54
  const opts = this.authenticator.allOptions();
53
55
  const stepMs = opts.step * 1000;
54
56
  const now = opts.epoch;
55
- let matched = false;
57
+ const matchedSteps = [];
56
58
  for (let delta = -verifyWindow; delta <= verifyWindow; delta++) {
57
59
  const windowMs = now + delta * stepMs;
58
60
  const expected = this.authenticator.clone({ epoch: windowMs }).generate(secret);
@@ -61,28 +63,19 @@ class OtpLibTwoFactorAuthProvider extends TwoFactorAuthProvider {
61
63
  const tokenBuf = Buffer.from(tokenStr);
62
64
  const expectedBuf = Buffer.from(expectedStr);
63
65
  if (tokenBuf.length === expectedBuf.length && (0, crypto_1.timingSafeEqual)(tokenBuf, expectedBuf)) {
64
- const stepCounter = Math.floor(windowMs / stepMs);
65
- const slotKey = `${(0, crypto_1.createHash)('sha256').update(secret).digest('hex')}:${stepCounter}`;
66
- if (((_b = this.usedWindows.get(slotKey)) !== null && _b !== void 0 ? _b : 0) > Date.now()) {
67
- }
68
- else {
69
- this.usedWindows.set(slotKey, Date.now() + (verifyWindow * 2 + 2) * stepMs);
70
- matched = true;
71
- }
66
+ matchedSteps.push(Math.floor(windowMs / stepMs));
72
67
  }
73
68
  }
74
- if (this.usedWindows.size > USED_WINDOWS_CAP) {
75
- this.sweepExpiredWindows();
76
- }
77
- return matched;
78
- }
79
- sweepExpiredWindows() {
80
- const nowMs = Date.now();
81
- for (const [slotKey, expiry] of this.usedWindows) {
82
- if (expiry <= nowMs) {
83
- this.usedWindows.delete(slotKey);
84
- }
69
+ if (matchedSteps.length === 0)
70
+ return false;
71
+ if (!this.options.replayProtection)
72
+ return true;
73
+ const secretHash = (0, crypto_1.createHash)('sha256').update(secret).digest('hex');
74
+ const claims = matchedSteps.map(step => this.replayStore.consume(`${secretHash}:${step}`, (verifyWindow * 2 + 2) * stepMs));
75
+ if (claims.some(claim => typeof claim !== 'boolean')) {
76
+ return Promise.all(claims).then(results => results.every(Boolean));
85
77
  }
78
+ return claims.every(Boolean);
86
79
  }
87
80
  toKeyUri(secret, account) {
88
81
  return this.authenticator.keyuri(account, this.options.issuer, secret);
@@ -1 +1 @@
1
- {"version":3,"file":"two-factor.provider.js","sourceRoot":"","sources":["../../lib/provider/two-factor.provider.ts"],"names":[],"mappings":";;;AAAA,mCAAqD;AACrD,0DAAqD;AAErD,kCAAwC;AAQxC,SAAS,WAAW,CAAmB,OAAW;IAChD,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CA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M,CAAC,CAAC;IACzE,CAAC;IAED,SAAS,CAAC,MAAc,EAAE,OAAe;QACvC,IAAG,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACrD,CAAC;QAED,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC9C,CAAC;CACF;AAnHD,kEAmHC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-auth-2fa",
3
- "version": "4.0.3",
3
+ "version": "4.1.1",
4
4
  "description": "nestjs-auth-2fa",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -33,8 +33,8 @@
33
33
  "lib": "lib"
34
34
  },
35
35
  "dependencies": {
36
- "@nathapp/nestjs-auth": "^4.0.3",
37
- "@nathapp/nestjs-common": "^4.0.3"
36
+ "@nathapp/nestjs-auth": "^4.1.1",
37
+ "@nathapp/nestjs-common": "^4.1.0"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@nathapp/nestjs-auth": "^4.0.0-rc.0",