@miguelmorales13/nestkit 0.10.0 → 0.16.0

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.
Files changed (97) hide show
  1. package/README.md +518 -12
  2. package/dist/audit/audit.module.d.ts +23 -0
  3. package/dist/audit/audit.options.d.ts +16 -0
  4. package/dist/audit/audit.port.d.ts +37 -0
  5. package/dist/audit/audit.service.d.ts +29 -0
  6. package/dist/audit/index.cjs +72 -0
  7. package/dist/audit/index.d.ts +7 -0
  8. package/dist/audit/index.js +72 -0
  9. package/dist/audit/sinks.d.ts +18 -0
  10. package/dist/auth/index.cjs +4 -3
  11. package/dist/auth/index.js +2 -1
  12. package/dist/auth/oauth/index.cjs +81 -13
  13. package/dist/auth/oauth/index.js +75 -7
  14. package/dist/auth/oauth/oauth-auth.service.d.ts +29 -1
  15. package/dist/auth/oauth/oauth.options.d.ts +11 -0
  16. package/dist/bootstrap/index.cjs +6 -5
  17. package/dist/bootstrap/index.js +5 -4
  18. package/dist/chunk-47FXU74G.cjs +205 -0
  19. package/dist/{chunk-54ZXIB5T.cjs → chunk-4GT66KQS.cjs} +4 -4
  20. package/dist/{chunk-J7TURDAL.cjs → chunk-67B7IYAV.cjs} +2 -2
  21. package/dist/{chunk-NVCI3CQI.cjs → chunk-C5DV4RAX.cjs} +6 -1
  22. package/dist/{chunk-KDAA6GFF.js → chunk-DABTRWA6.js} +12 -7
  23. package/dist/{chunk-ZA56XBCK.cjs → chunk-EBPEMVZU.cjs} +15 -0
  24. package/dist/{chunk-EYURGACO.js → chunk-JV4EAOF2.js} +1 -1
  25. package/dist/chunk-KP2ZHJSR.js +35 -0
  26. package/dist/{chunk-7I2Y7V52.js → chunk-KRC47OX6.js} +1 -1
  27. package/dist/chunk-LK3OINS7.js +205 -0
  28. package/dist/{chunk-A3B2EY4V.js → chunk-MLOQDUBN.js} +6 -1
  29. package/dist/chunk-TCAMLNUZ.js +27 -0
  30. package/dist/{chunk-V2M75FN3.cjs → chunk-U7QK24HL.cjs} +2 -2
  31. package/dist/{chunk-AOCF5QCZ.js → chunk-UIVBPNH4.js} +4 -4
  32. package/dist/{chunk-TJHRABML.cjs → chunk-UWDHAZVE.cjs} +12 -7
  33. package/dist/chunk-XHW4CTBS.js +57 -0
  34. package/dist/chunk-XX5ROVSC.cjs +57 -0
  35. package/dist/chunk-Y72D5L6I.cjs +27 -0
  36. package/dist/crud/crud.controller.d.ts +3 -1
  37. package/dist/crud/crud.service.d.ts +63 -4
  38. package/dist/crud/index.cjs +7 -2
  39. package/dist/crud/index.d.ts +2 -1
  40. package/dist/crud/index.js +6 -1
  41. package/dist/crud/list-query.dto.d.ts +23 -0
  42. package/dist/crud/repository.port.d.ts +33 -1
  43. package/dist/errors/index.cjs +4 -4
  44. package/dist/errors/index.js +4 -4
  45. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  46. package/dist/idempotency/idempotency.module.d.ts +27 -0
  47. package/dist/idempotency/idempotency.options.d.ts +29 -0
  48. package/dist/idempotency/idempotency.port.d.ts +43 -0
  49. package/dist/idempotency/index.cjs +206 -0
  50. package/dist/idempotency/index.d.ts +7 -0
  51. package/dist/idempotency/index.js +206 -0
  52. package/dist/idempotency/memory.store.d.ts +24 -0
  53. package/dist/index.cjs +24 -13
  54. package/dist/index.js +29 -18
  55. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  56. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  57. package/dist/invoicing/amounts.d.ts +52 -0
  58. package/dist/invoicing/index.cjs +577 -0
  59. package/dist/invoicing/index.d.ts +11 -0
  60. package/dist/invoicing/index.js +577 -0
  61. package/dist/invoicing/invoicing.module.d.ts +42 -0
  62. package/dist/invoicing/invoicing.options.d.ts +51 -0
  63. package/dist/invoicing/invoicing.port.d.ts +156 -0
  64. package/dist/invoicing/lines.d.ts +21 -0
  65. package/dist/invoicing/provider-http.d.ts +21 -0
  66. package/dist/media/index.cjs +57 -7
  67. package/dist/media/index.d.ts +2 -2
  68. package/dist/media/index.js +56 -6
  69. package/dist/media/media.options.d.ts +20 -0
  70. package/dist/media/media.service.d.ts +18 -1
  71. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  72. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  73. package/dist/payments/index.cjs +795 -0
  74. package/dist/payments/index.d.ts +12 -0
  75. package/dist/payments/index.js +795 -0
  76. package/dist/payments/money.d.ts +20 -0
  77. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  78. package/dist/payments/payments.module.d.ts +45 -0
  79. package/dist/payments/payments.options.d.ts +84 -0
  80. package/dist/payments/payments.port.d.ts +174 -0
  81. package/dist/payments/provider-http.d.ts +26 -0
  82. package/dist/response/api-response.d.ts +7 -0
  83. package/dist/response/index.cjs +12 -4
  84. package/dist/response/index.d.ts +2 -0
  85. package/dist/response/index.js +12 -4
  86. package/dist/response/paginated.d.ts +25 -0
  87. package/dist/response/response.interceptor.d.ts +4 -0
  88. package/dist/tracking/index.cjs +3 -3
  89. package/dist/tracking/index.d.ts +1 -1
  90. package/dist/tracking/index.js +2 -2
  91. package/dist/tracking/request-context.d.ts +22 -0
  92. package/package.json +25 -3
  93. package/dist/chunk-3CLYZC3T.cjs +0 -104
  94. package/dist/chunk-EBO6UKHL.js +0 -20
  95. package/dist/chunk-JOVBJDJ2.js +0 -104
  96. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  97. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -0,0 +1,16 @@
1
+ import type { AuditSinkPort } from './audit.port.js';
2
+ /** DI token carrying the resolved {@link AuditOptions}. */
3
+ export declare const AUDIT_OPTIONS: unique symbol;
4
+ export interface AuditOptions {
5
+ /** Where entries go. Defaults to the application log. */
6
+ sink?: AuditSinkPort;
7
+ /**
8
+ * What happens when the sink throws.
9
+ *
10
+ * `'continue'` (default) logs and carries on: the operation already
11
+ * succeeded, and losing the entry is better than losing the sale.
12
+ * `'fail'` propagates, for the rule that says an unrecorded action did not
13
+ * happen.
14
+ */
15
+ onError?: 'continue' | 'fail';
16
+ }
@@ -0,0 +1,37 @@
1
+ /** DI token for the audit sink. Inject with `@Inject(AUDIT_SINK)`. */
2
+ export declare const AUDIT_SINK: unique symbol;
3
+ /**
4
+ * Something that happened and that someone may have to answer for later.
5
+ *
6
+ * `actorId` and `requestId` are filled in from the request context when they
7
+ * are not passed explicitly, which is what makes this usable from a service
8
+ * that never received the user as an argument.
9
+ */
10
+ export interface AuditEvent {
11
+ /** What happened, as a verb the business would recognise: `created`, `deleted`, `refunded`. */
12
+ action: string;
13
+ /** What it happened to: the entity or resource name. */
14
+ resource: string;
15
+ resourceId?: string;
16
+ /** Who did it. Defaults to the actor on the request context. */
17
+ actorId?: string;
18
+ tenantId?: string;
19
+ /** Ties the entry to everything else logged for the same request. */
20
+ requestId?: string;
21
+ at?: Date;
22
+ /** State before and after, when the caller has both. */
23
+ before?: unknown;
24
+ after?: unknown;
25
+ /** Anything else worth keeping: an IP, a reason, the ticket that justified it. */
26
+ metadata?: Record<string, unknown>;
27
+ }
28
+ /**
29
+ * Where the trail is written.
30
+ *
31
+ * The library does not persist anything: a trail belongs in the consumer's
32
+ * database, under its retention rules, and often in a table nobody is allowed
33
+ * to update. Implementing this against that table is the whole integration.
34
+ */
35
+ export interface AuditSinkPort {
36
+ record(event: AuditEvent): Promise<void>;
37
+ }
@@ -0,0 +1,29 @@
1
+ import { type AuditEvent, type AuditSinkPort } from './audit.port.js';
2
+ import { type AuditOptions } from './audit.options.js';
3
+ /**
4
+ * Fills in what the caller should not have to carry: who, which request, when.
5
+ *
6
+ * Pure and exported because `BaseCrudService` needs the same defaults without
7
+ * taking a dependency on the service.
8
+ */
9
+ export declare function withRequestContext(event: AuditEvent): AuditEvent;
10
+ /**
11
+ * Records what happened.
12
+ *
13
+ * ```ts
14
+ * await this.audit.record({ action: 'refunded', resource: 'invoice', resourceId: id,
15
+ * metadata: { motive: '02' } });
16
+ * ```
17
+ *
18
+ * A failing sink does **not** fail the operation by default. An audit trail
19
+ * that takes the API down turns a logging outage into a business outage, and
20
+ * the write it was recording already happened. Consumers under a rule that
21
+ * says otherwise — no entry, no operation — set `onError: 'fail'`.
22
+ */
23
+ export declare class AuditService {
24
+ private readonly sink;
25
+ private readonly options;
26
+ private readonly logger;
27
+ constructor(sink: AuditSinkPort, options?: AuditOptions);
28
+ record(event: AuditEvent): Promise<void>;
29
+ }
@@ -0,0 +1,72 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
+
3
+
4
+
5
+
6
+ var _chunkXX5ROVSCcjs = require('../chunk-XX5ROVSC.cjs');
7
+ require('../chunk-EBPEMVZU.cjs');
8
+
9
+
10
+ var _chunk2REOCMUDcjs = require('../chunk-2REOCMUD.cjs');
11
+
12
+ // src/audit/sinks.ts
13
+ var _common = require('@nestjs/common');
14
+ var LoggerAuditSink = class {
15
+ constructor() {
16
+ this.logger = new (0, _common.Logger)("Audit");
17
+ }
18
+ async record(event) {
19
+ this.logger.log(JSON.stringify({ ...event, at: (_nullishCoalesce(event.at, () => ( /* @__PURE__ */ new Date()))).toISOString() }));
20
+ }
21
+ };
22
+ var MemoryAuditSink = class {
23
+ constructor() {
24
+ this.events = [];
25
+ }
26
+ async record(event) {
27
+ this.events.push(event);
28
+ }
29
+ };
30
+
31
+ // src/audit/audit.module.ts
32
+
33
+ var AuditModule = class {
34
+ static forRoot(options = {}) {
35
+ const providers = [
36
+ { provide: _chunkXX5ROVSCcjs.AUDIT_OPTIONS, useValue: options },
37
+ { provide: _chunkXX5ROVSCcjs.AUDIT_SINK, useFactory: () => _nullishCoalesce(options.sink, () => ( new LoggerAuditSink())) },
38
+ _chunkXX5ROVSCcjs.AuditService
39
+ ];
40
+ return { module: AuditModule, providers, exports: [_chunkXX5ROVSCcjs.AUDIT_SINK, _chunkXX5ROVSCcjs.AUDIT_OPTIONS, _chunkXX5ROVSCcjs.AuditService] };
41
+ }
42
+ static forRootAsync(config) {
43
+ const providers = [
44
+ { provide: _chunkXX5ROVSCcjs.AUDIT_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) },
45
+ {
46
+ provide: _chunkXX5ROVSCcjs.AUDIT_SINK,
47
+ useFactory: (options) => _nullishCoalesce(options.sink, () => ( new LoggerAuditSink())),
48
+ inject: [_chunkXX5ROVSCcjs.AUDIT_OPTIONS]
49
+ },
50
+ _chunkXX5ROVSCcjs.AuditService
51
+ ];
52
+ return {
53
+ module: AuditModule,
54
+ imports: _nullishCoalesce(config.imports, () => ( [])),
55
+ providers,
56
+ exports: [_chunkXX5ROVSCcjs.AUDIT_SINK, _chunkXX5ROVSCcjs.AUDIT_OPTIONS, _chunkXX5ROVSCcjs.AuditService]
57
+ };
58
+ }
59
+ };
60
+ AuditModule = exports.AuditModule = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
61
+ _common.Global.call(void 0, ),
62
+ _common.Module.call(void 0, {})
63
+ ], AuditModule);
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+ exports.AUDIT_OPTIONS = _chunkXX5ROVSCcjs.AUDIT_OPTIONS; exports.AUDIT_SINK = _chunkXX5ROVSCcjs.AUDIT_SINK; exports.AuditModule = AuditModule; exports.AuditService = _chunkXX5ROVSCcjs.AuditService; exports.LoggerAuditSink = LoggerAuditSink; exports.MemoryAuditSink = MemoryAuditSink; exports.withRequestContext = _chunkXX5ROVSCcjs.withRequestContext;
@@ -0,0 +1,7 @@
1
+ export { AUDIT_SINK } from './audit.port.js';
2
+ export type { AuditEvent, AuditSinkPort } from './audit.port.js';
3
+ export { AUDIT_OPTIONS } from './audit.options.js';
4
+ export type { AuditOptions } from './audit.options.js';
5
+ export { AuditService, withRequestContext } from './audit.service.js';
6
+ export { LoggerAuditSink, MemoryAuditSink } from './sinks.js';
7
+ export { AuditModule } from './audit.module.js';
@@ -0,0 +1,72 @@
1
+ import {
2
+ AUDIT_OPTIONS,
3
+ AUDIT_SINK,
4
+ AuditService,
5
+ withRequestContext
6
+ } from "../chunk-XHW4CTBS.js";
7
+ import "../chunk-KP2ZHJSR.js";
8
+ import {
9
+ __decorateClass
10
+ } from "../chunk-4MGIQFAJ.js";
11
+
12
+ // src/audit/sinks.ts
13
+ import { Logger } from "@nestjs/common";
14
+ var LoggerAuditSink = class {
15
+ constructor() {
16
+ this.logger = new Logger("Audit");
17
+ }
18
+ async record(event) {
19
+ this.logger.log(JSON.stringify({ ...event, at: (event.at ?? /* @__PURE__ */ new Date()).toISOString() }));
20
+ }
21
+ };
22
+ var MemoryAuditSink = class {
23
+ constructor() {
24
+ this.events = [];
25
+ }
26
+ async record(event) {
27
+ this.events.push(event);
28
+ }
29
+ };
30
+
31
+ // src/audit/audit.module.ts
32
+ import { Global, Module } from "@nestjs/common";
33
+ var AuditModule = class {
34
+ static forRoot(options = {}) {
35
+ const providers = [
36
+ { provide: AUDIT_OPTIONS, useValue: options },
37
+ { provide: AUDIT_SINK, useFactory: () => options.sink ?? new LoggerAuditSink() },
38
+ AuditService
39
+ ];
40
+ return { module: AuditModule, providers, exports: [AUDIT_SINK, AUDIT_OPTIONS, AuditService] };
41
+ }
42
+ static forRootAsync(config) {
43
+ const providers = [
44
+ { provide: AUDIT_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
45
+ {
46
+ provide: AUDIT_SINK,
47
+ useFactory: (options) => options.sink ?? new LoggerAuditSink(),
48
+ inject: [AUDIT_OPTIONS]
49
+ },
50
+ AuditService
51
+ ];
52
+ return {
53
+ module: AuditModule,
54
+ imports: config.imports ?? [],
55
+ providers,
56
+ exports: [AUDIT_SINK, AUDIT_OPTIONS, AuditService]
57
+ };
58
+ }
59
+ };
60
+ AuditModule = __decorateClass([
61
+ Global(),
62
+ Module({})
63
+ ], AuditModule);
64
+ export {
65
+ AUDIT_OPTIONS,
66
+ AUDIT_SINK,
67
+ AuditModule,
68
+ AuditService,
69
+ LoggerAuditSink,
70
+ MemoryAuditSink,
71
+ withRequestContext
72
+ };
@@ -0,0 +1,18 @@
1
+ import type { AuditEvent, AuditSinkPort } from './audit.port.js';
2
+ /**
3
+ * Writes the trail to the application log as one JSON line per event.
4
+ *
5
+ * A reasonable default and a poor final answer: logs rotate, and the question
6
+ * an audit trail exists to answer ("who deleted this, in March") is asked long
7
+ * after the log is gone. Good for development and for shipping to a log
8
+ * pipeline; not a substitute for a table.
9
+ */
10
+ export declare class LoggerAuditSink implements AuditSinkPort {
11
+ private readonly logger;
12
+ record(event: AuditEvent): Promise<void>;
13
+ }
14
+ /** Keeps events in memory. For tests, and for seeing the shape in development. */
15
+ export declare class MemoryAuditSink implements AuditSinkPort {
16
+ readonly events: AuditEvent[];
17
+ record(event: AuditEvent): Promise<void>;
18
+ }
@@ -2,7 +2,8 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkNVCI3CQIcjs = require('../chunk-NVCI3CQI.cjs');
5
+ var _chunkC5DV4RAXcjs = require('../chunk-C5DV4RAX.cjs');
6
+ require('../chunk-EBPEMVZU.cjs');
6
7
 
7
8
 
8
9
 
@@ -106,7 +107,7 @@ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
106
107
 
107
108
  // src/auth/auth.service.ts
108
109
  var BaseAuthService = class {
109
- constructor(users, tokens = new (0, _chunkNVCI3CQIcjs.TokenService)()) {
110
+ constructor(users, tokens = new (0, _chunkC5DV4RAXcjs.TokenService)()) {
110
111
  this.users = users;
111
112
  this.tokens = tokens;
112
113
  }
@@ -204,4 +205,4 @@ function createAuthController(serviceToken, options = {}) {
204
205
 
205
206
 
206
207
 
207
- exports.BaseAuthService = BaseAuthService; exports.CurrentTenant = CurrentTenant; exports.CurrentUser = _chunkNVCI3CQIcjs.CurrentUser; exports.JwtAuthGuard = _chunkNVCI3CQIcjs.JwtAuthGuard; exports.LoginDto = LoginDto; exports.ROLES_KEY = ROLES_KEY; exports.RefreshDto = RefreshDto; exports.RegisterDto = RegisterDto; exports.RequireTenantGuard = RequireTenantGuard; exports.Roles = Roles; exports.RolesGuard = RolesGuard; exports.TokenService = _chunkNVCI3CQIcjs.TokenService; exports.createAuthController = createAuthController; exports.hashPassword = hashPassword; exports.verifyPassword = verifyPassword;
208
+ exports.BaseAuthService = BaseAuthService; exports.CurrentTenant = CurrentTenant; exports.CurrentUser = _chunkC5DV4RAXcjs.CurrentUser; exports.JwtAuthGuard = _chunkC5DV4RAXcjs.JwtAuthGuard; exports.LoginDto = LoginDto; exports.ROLES_KEY = ROLES_KEY; exports.RefreshDto = RefreshDto; exports.RegisterDto = RegisterDto; exports.RequireTenantGuard = RequireTenantGuard; exports.Roles = Roles; exports.RolesGuard = RolesGuard; exports.TokenService = _chunkC5DV4RAXcjs.TokenService; exports.createAuthController = createAuthController; exports.hashPassword = hashPassword; exports.verifyPassword = verifyPassword;
@@ -2,7 +2,8 @@ import {
2
2
  CurrentUser,
3
3
  JwtAuthGuard,
4
4
  TokenService
5
- } from "../chunk-A3B2EY4V.js";
5
+ } from "../chunk-MLOQDUBN.js";
6
+ import "../chunk-KP2ZHJSR.js";
6
7
  import {
7
8
  ConflictAppException,
8
9
  ForbiddenAppException,
@@ -1,7 +1,8 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
3
 
4
- var _chunkNVCI3CQIcjs = require('../../chunk-NVCI3CQI.cjs');
4
+ var _chunkC5DV4RAXcjs = require('../../chunk-C5DV4RAX.cjs');
5
+ require('../../chunk-EBPEMVZU.cjs');
5
6
 
6
7
 
7
8
 
@@ -141,9 +142,11 @@ function resolveOAuthOptions(options) {
141
142
  secure: _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.cookie, 'optionalAccess', _10 => _10.secure]), () => ( process.env.NODE_ENV === "production"))
142
143
  },
143
144
  linkCookieName: _nullishCoalesce(options.linkCookieName, () => ( "link_intent")),
145
+ stateCookieName: _nullishCoalesce(options.stateCookieName, () => ( "oauth_state")),
144
146
  accessTtlSeconds: _nullishCoalesce(options.accessTtlSeconds, () => ( 15 * 60)),
145
147
  refreshTtlSeconds: _nullishCoalesce(options.refreshTtlSeconds, () => ( 30 * 24 * 60 * 60)),
146
148
  linkTtlSeconds: _nullishCoalesce(options.linkTtlSeconds, () => ( 10 * 60)),
149
+ stateTtlSeconds: _nullishCoalesce(options.stateTtlSeconds, () => ( 10 * 60)),
147
150
  accessSecret: options.accessSecret,
148
151
  refreshSecret: options.refreshSecret,
149
152
  singleSession: _nullishCoalesce(options.singleSession, () => ( true)),
@@ -192,8 +195,60 @@ var OAuthAuthService = class {
192
195
  }
193
196
  return found;
194
197
  }
198
+ /**
199
+ * The provider's consent URL, together with the `state` that has to travel
200
+ * back with the callback.
201
+ *
202
+ * `state` is not decoration. Without it, anyone can hand a victim a
203
+ * callback URL carrying an authorization code for *their own* provider
204
+ * account: the victim's browser completes the flow and ends up signed in as
205
+ * the attacker, entering their data into an account someone else controls.
206
+ * The value goes out in the URL and, signed, into a cookie; the callback
207
+ * proceeds only when the two match, which a third party cannot arrange
208
+ * because they cannot write cookies for this domain.
209
+ *
210
+ * Signed rather than stored in a table: it needs no schema and no cleanup,
211
+ * and it expires on its own.
212
+ */
195
213
  authorizeUrl(name) {
196
- return buildAuthorizeUrl(this.provider(name));
214
+ const provider = this.provider(name);
215
+ const ttl = this.options.stateTtlSeconds;
216
+ const state = _jsonwebtoken2.default.sign(
217
+ // `nonce` makes two authorize requests within the same second produce
218
+ // different tokens; `typ` keeps this from being swapped with the link
219
+ // token, which is signed with the same secret.
220
+ { typ: "state", provider: provider.name, nonce: _crypto.randomUUID.call(void 0, ) },
221
+ requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
222
+ { expiresIn: ttl }
223
+ );
224
+ return {
225
+ url: buildAuthorizeUrl(provider, state),
226
+ state,
227
+ expiresAt: new Date(Date.now() + ttl * 1e3)
228
+ };
229
+ }
230
+ /**
231
+ * Whether the `state` the provider sent back is the one issued for this
232
+ * provider, to this browser, and still valid.
233
+ *
234
+ * Both halves are checked. Matching the cookie proves the callback belongs
235
+ * to the authorize request this browser started; verifying the signature
236
+ * proves the pair was not simply invented by whoever crafted the URL.
237
+ */
238
+ verifyState(received, fromCookie, provider) {
239
+ if (!received || !fromCookie) return false;
240
+ const a = Buffer.from(received);
241
+ const b = Buffer.from(fromCookie);
242
+ if (a.length !== b.length || !_crypto.timingSafeEqual.call(void 0, a, b)) return false;
243
+ try {
244
+ const payload = _jsonwebtoken2.default.verify(
245
+ received,
246
+ requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
247
+ );
248
+ return payload.typ === "state" && payload.provider === provider;
249
+ } catch (e2) {
250
+ return false;
251
+ }
197
252
  }
198
253
  /** Exchanges the callback's `code` for a normalised profile. */
199
254
  async profileFromCode(name, code) {
@@ -303,7 +358,7 @@ var OAuthAuthService = class {
303
358
  requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
304
359
  );
305
360
  return payload.typ === "link" && payload.sub ? payload.sub : null;
306
- } catch (e2) {
361
+ } catch (e3) {
307
362
  return null;
308
363
  }
309
364
  }
@@ -388,7 +443,7 @@ var OAuthAuthService = class {
388
443
  token,
389
444
  requireSecret(this.options.refreshSecret, "JWT_REFRESH_SECRET")
390
445
  );
391
- } catch (e3) {
446
+ } catch (e4) {
392
447
  throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid refresh token.");
393
448
  }
394
449
  }
@@ -457,7 +512,7 @@ OAuthCallbackFilter = exports.OAuthCallbackFilter = _chunk2REOCMUDcjs.__decorate
457
512
 
458
513
 
459
514
  function createOAuthController(options = {}) {
460
- const Guard = _nullishCoalesce(options.guard, () => ( _chunkNVCI3CQIcjs.JwtAuthGuard));
515
+ const Guard = _nullishCoalesce(options.guard, () => ( _chunkC5DV4RAXcjs.JwtAuthGuard));
461
516
  const userId = _nullishCoalesce(options.userId, () => ( ((user) => user.sub)));
462
517
  let OAuthControllerHost = class {
463
518
  constructor(auth) {
@@ -491,12 +546,24 @@ function createOAuthController(options = {}) {
491
546
  return { ok: true };
492
547
  }
493
548
  start(provider, reply) {
494
- redirect(reply, this.auth.authorizeUrl(provider));
549
+ const { url, state, expiresAt } = this.auth.authorizeUrl(provider);
550
+ setCookie(reply, this.auth.config.stateCookieName, state, {
551
+ ...this.cookieBase(),
552
+ expires: expiresAt
553
+ });
554
+ redirect(reply, url);
495
555
  }
496
- async callback(provider, code, request, reply) {
556
+ async callback(provider, code, state, request, reply) {
497
557
  if (!code) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
558
+ const stateCookie = _optionalChain([request, 'access', _19 => _19.cookies, 'optionalAccess', _20 => _20[this.auth.config.stateCookieName]]);
559
+ clearCookie(reply, this.auth.config.stateCookieName, {
560
+ path: this.auth.config.cookie.path
561
+ });
562
+ if (!this.auth.verifyState(state, stateCookie, provider)) {
563
+ throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
564
+ }
498
565
  const profile = await this.auth.profileFromCode(provider, code);
499
- const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _19 => _19.cookies, 'optionalAccess', _20 => _20[this.auth.config.linkCookieName]]));
566
+ const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _21 => _21.cookies, 'optionalAccess', _22 => _22[this.auth.config.linkCookieName]]));
500
567
  if (linkUserId) {
501
568
  clearCookie(reply, this.auth.config.linkCookieName, { path: this.auth.config.cookie.path });
502
569
  try {
@@ -539,17 +606,17 @@ function createOAuthController(options = {}) {
539
606
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
540
607
  _common.UseGuards.call(void 0, Guard),
541
608
  _common.Get.call(void 0, "me"),
542
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, ))
609
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkC5DV4RAXcjs.CurrentUser.call(void 0, ))
543
610
  ], OAuthControllerHost.prototype, "me", 1);
544
611
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
545
612
  _common.UseGuards.call(void 0, Guard),
546
613
  _common.Get.call(void 0, "linked-accounts"),
547
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, ))
614
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkC5DV4RAXcjs.CurrentUser.call(void 0, ))
548
615
  ], OAuthControllerHost.prototype, "linkedAccounts", 1);
549
616
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
550
617
  _common.UseGuards.call(void 0, Guard),
551
618
  _common.Post.call(void 0, "link-intent"),
552
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, )),
619
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkC5DV4RAXcjs.CurrentUser.call(void 0, )),
553
620
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
554
621
  ], OAuthControllerHost.prototype, "linkIntent", 1);
555
622
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
@@ -562,8 +629,9 @@ function createOAuthController(options = {}) {
562
629
  _common.UseFilters.call(void 0, OAuthCallbackFilter),
563
630
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
564
631
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Query.call(void 0, "code")),
565
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Req.call(void 0, )),
566
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Res.call(void 0, ))
632
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Query.call(void 0, "state")),
633
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Req.call(void 0, )),
634
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Res.call(void 0, ))
567
635
  ], OAuthControllerHost.prototype, "callback", 1);
568
636
  OAuthControllerHost = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
569
637
  _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "auth")))
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  CurrentUser,
3
3
  JwtAuthGuard
4
- } from "../../chunk-A3B2EY4V.js";
4
+ } from "../../chunk-MLOQDUBN.js";
5
+ import "../../chunk-KP2ZHJSR.js";
5
6
  import {
6
7
  UnauthorizedAppException,
7
8
  ValidationAppException
@@ -141,9 +142,11 @@ function resolveOAuthOptions(options) {
141
142
  secure: options.cookie?.secure ?? process.env.NODE_ENV === "production"
142
143
  },
143
144
  linkCookieName: options.linkCookieName ?? "link_intent",
145
+ stateCookieName: options.stateCookieName ?? "oauth_state",
144
146
  accessTtlSeconds: options.accessTtlSeconds ?? 15 * 60,
145
147
  refreshTtlSeconds: options.refreshTtlSeconds ?? 30 * 24 * 60 * 60,
146
148
  linkTtlSeconds: options.linkTtlSeconds ?? 10 * 60,
149
+ stateTtlSeconds: options.stateTtlSeconds ?? 10 * 60,
147
150
  accessSecret: options.accessSecret,
148
151
  refreshSecret: options.refreshSecret,
149
152
  singleSession: options.singleSession ?? true,
@@ -157,7 +160,7 @@ function resolveOAuthOptions(options) {
157
160
 
158
161
  // src/auth/oauth/oauth-auth.service.ts
159
162
  import { Inject, Injectable, ServiceUnavailableException } from "@nestjs/common";
160
- import { createHash, randomUUID } from "crypto";
163
+ import { createHash, randomUUID, timingSafeEqual } from "crypto";
161
164
  import jwt from "jsonwebtoken";
162
165
  function hashToken(token) {
163
166
  return createHash("sha256").update(token).digest("hex");
@@ -192,8 +195,60 @@ var OAuthAuthService = class {
192
195
  }
193
196
  return found;
194
197
  }
198
+ /**
199
+ * The provider's consent URL, together with the `state` that has to travel
200
+ * back with the callback.
201
+ *
202
+ * `state` is not decoration. Without it, anyone can hand a victim a
203
+ * callback URL carrying an authorization code for *their own* provider
204
+ * account: the victim's browser completes the flow and ends up signed in as
205
+ * the attacker, entering their data into an account someone else controls.
206
+ * The value goes out in the URL and, signed, into a cookie; the callback
207
+ * proceeds only when the two match, which a third party cannot arrange
208
+ * because they cannot write cookies for this domain.
209
+ *
210
+ * Signed rather than stored in a table: it needs no schema and no cleanup,
211
+ * and it expires on its own.
212
+ */
195
213
  authorizeUrl(name) {
196
- return buildAuthorizeUrl(this.provider(name));
214
+ const provider = this.provider(name);
215
+ const ttl = this.options.stateTtlSeconds;
216
+ const state = jwt.sign(
217
+ // `nonce` makes two authorize requests within the same second produce
218
+ // different tokens; `typ` keeps this from being swapped with the link
219
+ // token, which is signed with the same secret.
220
+ { typ: "state", provider: provider.name, nonce: randomUUID() },
221
+ requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET"),
222
+ { expiresIn: ttl }
223
+ );
224
+ return {
225
+ url: buildAuthorizeUrl(provider, state),
226
+ state,
227
+ expiresAt: new Date(Date.now() + ttl * 1e3)
228
+ };
229
+ }
230
+ /**
231
+ * Whether the `state` the provider sent back is the one issued for this
232
+ * provider, to this browser, and still valid.
233
+ *
234
+ * Both halves are checked. Matching the cookie proves the callback belongs
235
+ * to the authorize request this browser started; verifying the signature
236
+ * proves the pair was not simply invented by whoever crafted the URL.
237
+ */
238
+ verifyState(received, fromCookie, provider) {
239
+ if (!received || !fromCookie) return false;
240
+ const a = Buffer.from(received);
241
+ const b = Buffer.from(fromCookie);
242
+ if (a.length !== b.length || !timingSafeEqual(a, b)) return false;
243
+ try {
244
+ const payload = jwt.verify(
245
+ received,
246
+ requireSecret(this.options.accessSecret, "JWT_ACCESS_SECRET")
247
+ );
248
+ return payload.typ === "state" && payload.provider === provider;
249
+ } catch {
250
+ return false;
251
+ }
197
252
  }
198
253
  /** Exchanges the callback's `code` for a normalised profile. */
199
254
  async profileFromCode(name, code) {
@@ -491,10 +546,22 @@ function createOAuthController(options = {}) {
491
546
  return { ok: true };
492
547
  }
493
548
  start(provider, reply) {
494
- redirect(reply, this.auth.authorizeUrl(provider));
549
+ const { url, state, expiresAt } = this.auth.authorizeUrl(provider);
550
+ setCookie(reply, this.auth.config.stateCookieName, state, {
551
+ ...this.cookieBase(),
552
+ expires: expiresAt
553
+ });
554
+ redirect(reply, url);
495
555
  }
496
- async callback(provider, code, request, reply) {
556
+ async callback(provider, code, state, request, reply) {
497
557
  if (!code) throw new UnauthorizedAppException(this.auth.config.genericErrorMessage());
558
+ const stateCookie = request.cookies?.[this.auth.config.stateCookieName];
559
+ clearCookie(reply, this.auth.config.stateCookieName, {
560
+ path: this.auth.config.cookie.path
561
+ });
562
+ if (!this.auth.verifyState(state, stateCookie, provider)) {
563
+ throw new UnauthorizedAppException(this.auth.config.genericErrorMessage());
564
+ }
498
565
  const profile = await this.auth.profileFromCode(provider, code);
499
566
  const linkUserId = this.auth.readLinkToken(request.cookies?.[this.auth.config.linkCookieName]);
500
567
  if (linkUserId) {
@@ -562,8 +629,9 @@ function createOAuthController(options = {}) {
562
629
  UseFilters(OAuthCallbackFilter),
563
630
  __decorateParam(0, Param("provider")),
564
631
  __decorateParam(1, Query("code")),
565
- __decorateParam(2, Req()),
566
- __decorateParam(3, Res())
632
+ __decorateParam(2, Query("state")),
633
+ __decorateParam(3, Req()),
634
+ __decorateParam(4, Res())
567
635
  ], OAuthControllerHost.prototype, "callback", 1);
568
636
  OAuthControllerHost = __decorateClass([
569
637
  Controller(options.path ?? "auth")
@@ -29,7 +29,35 @@ export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
29
29
  * differently, and distinguishing them only tells a prober what exists.
30
30
  */
31
31
  provider(name: string): OAuthProviderConfig;
32
- authorizeUrl(name: string): string;
32
+ /**
33
+ * The provider's consent URL, together with the `state` that has to travel
34
+ * back with the callback.
35
+ *
36
+ * `state` is not decoration. Without it, anyone can hand a victim a
37
+ * callback URL carrying an authorization code for *their own* provider
38
+ * account: the victim's browser completes the flow and ends up signed in as
39
+ * the attacker, entering their data into an account someone else controls.
40
+ * The value goes out in the URL and, signed, into a cookie; the callback
41
+ * proceeds only when the two match, which a third party cannot arrange
42
+ * because they cannot write cookies for this domain.
43
+ *
44
+ * Signed rather than stored in a table: it needs no schema and no cleanup,
45
+ * and it expires on its own.
46
+ */
47
+ authorizeUrl(name: string): {
48
+ url: string;
49
+ state: string;
50
+ expiresAt: Date;
51
+ };
52
+ /**
53
+ * Whether the `state` the provider sent back is the one issued for this
54
+ * provider, to this browser, and still valid.
55
+ *
56
+ * Both halves are checked. Matching the cookie proves the callback belongs
57
+ * to the authorize request this browser started; verifying the signature
58
+ * proves the pair was not simply invented by whoever crafted the URL.
59
+ */
60
+ verifyState(received: string | undefined, fromCookie: string | undefined, provider: string): boolean;
33
61
  /** Exchanges the callback's `code` for a normalised profile. */
34
62
  profileFromCode(name: string, code: string): Promise<OAuthProfile>;
35
63
  /**
@@ -41,10 +41,21 @@ export interface OAuthAuthOptions<U extends OAuthUser = OAuthUser> {
41
41
  * already signed-in account. Default `link_intent`.
42
42
  */
43
43
  linkCookieName?: string;
44
+ /**
45
+ * Cookie holding the `state` that ties an authorize request to its
46
+ * callback. Defaults to `oauth_state`.
47
+ */
48
+ stateCookieName?: string;
44
49
  /** Defaults: 15 min access, 30 days refresh, 10 min link permission. */
45
50
  accessTtlSeconds?: number;
46
51
  refreshTtlSeconds?: number;
47
52
  linkTtlSeconds?: number;
53
+ /**
54
+ * How long a `state` stays valid. Defaults to ten minutes — long enough to
55
+ * type a password and pass a second factor, short enough that a leaked
56
+ * authorize URL is worthless by the time anyone finds it.
57
+ */
58
+ stateTtlSeconds?: number;
48
59
  /** Read from `JWT_ACCESS_SECRET` / `JWT_REFRESH_SECRET` when omitted. */
49
60
  accessSecret?: string;
50
61
  refreshSecret?: string;