@miguelmorales13/nestkit 0.11.0 → 0.18.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 (126) hide show
  1. package/README.md +619 -35
  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 +12 -10
  11. package/dist/auth/index.js +5 -3
  12. package/dist/auth/oauth/http.d.ts +10 -3
  13. package/dist/auth/oauth/index.cjs +189 -29
  14. package/dist/auth/oauth/index.d.ts +6 -4
  15. package/dist/auth/oauth/index.js +169 -9
  16. package/dist/auth/oauth/magic-link.dto.d.ts +6 -0
  17. package/dist/auth/oauth/memory-magic-link.store.d.ts +19 -0
  18. package/dist/auth/oauth/oauth-auth.service.d.ts +46 -5
  19. package/dist/auth/oauth/oauth.controller.d.ts +5 -1
  20. package/dist/auth/oauth/oauth.options.d.ts +34 -1
  21. package/dist/auth/oauth/oauth.ports.d.ts +38 -0
  22. package/dist/bootstrap/index.cjs +9 -6
  23. package/dist/bootstrap/index.js +8 -5
  24. package/dist/{chunk-TJHRABML.cjs → chunk-3AUOOEQO.cjs} +12 -7
  25. package/dist/{chunk-NVCI3CQI.cjs → chunk-4HHZFOVC.cjs} +10 -5
  26. package/dist/{chunk-EYURGACO.js → chunk-4PFAKLT3.js} +1 -1
  27. package/dist/chunk-52IOOHNX.cjs +205 -0
  28. package/dist/chunk-6RAPVLJM.js +212 -0
  29. package/dist/{chunk-7I2Y7V52.js → chunk-A2DGK4ZL.js} +26 -3
  30. package/dist/chunk-APUFKA4K.cjs +212 -0
  31. package/dist/chunk-AXMW5JF7.cjs +83 -0
  32. package/dist/{chunk-KDAA6GFF.js → chunk-DYHSOULW.js} +12 -7
  33. package/dist/chunk-ETRUVZTJ.js +43 -0
  34. package/dist/{chunk-54ZXIB5T.cjs → chunk-FNUZGYUF.cjs} +4 -4
  35. package/dist/{chunk-FDNGAYTZ.cjs → chunk-HDFPSA2V.cjs} +6 -6
  36. package/dist/{chunk-V2M75FN3.cjs → chunk-HVHYZXBB.cjs} +2 -2
  37. package/dist/chunk-IFNYRZP2.js +205 -0
  38. package/dist/{chunk-A3B2EY4V.js → chunk-IKXSVEJ7.js} +7 -2
  39. package/dist/{chunk-YFYHLYHN.js → chunk-M3GQDRWR.js} +7 -1
  40. package/dist/{chunk-J7TURDAL.cjs → chunk-MSTXS3MU.cjs} +28 -5
  41. package/dist/chunk-PNK5WMPP.cjs +30 -0
  42. package/dist/chunk-Q5Y33L7B.cjs +19 -0
  43. package/dist/{chunk-ZA56XBCK.cjs → chunk-SDWHKPXI.cjs} +23 -0
  44. package/dist/chunk-TCAMLNUZ.js +27 -0
  45. package/dist/{chunk-AOCF5QCZ.js → chunk-UNEVXCFW.js} +2 -2
  46. package/dist/chunk-VVMRZEIW.js +30 -0
  47. package/dist/chunk-W2T2VFLC.cjs +57 -0
  48. package/dist/chunk-X4PQJZ4G.js +83 -0
  49. package/dist/chunk-Y72D5L6I.cjs +27 -0
  50. package/dist/{chunk-ORWJ7LES.js → chunk-ZFIDAX7K.js} +1 -1
  51. package/dist/chunk-ZJMLEP5H.js +57 -0
  52. package/dist/crud/crud.controller.d.ts +3 -1
  53. package/dist/crud/crud.service.d.ts +63 -4
  54. package/dist/crud/index.cjs +7 -2
  55. package/dist/crud/index.d.ts +2 -1
  56. package/dist/crud/index.js +6 -1
  57. package/dist/crud/list-query.dto.d.ts +23 -0
  58. package/dist/crud/repository.port.d.ts +33 -1
  59. package/dist/errors/app.exception.d.ts +9 -1
  60. package/dist/errors/common.exceptions.d.ts +6 -5
  61. package/dist/errors/global-exception.filter.d.ts +9 -0
  62. package/dist/errors/index.cjs +8 -5
  63. package/dist/errors/index.js +9 -6
  64. package/dist/i18n/i18n.interceptor.d.ts +16 -0
  65. package/dist/i18n/i18n.module.d.ts +49 -3
  66. package/dist/i18n/index.cjs +26 -2
  67. package/dist/i18n/index.d.ts +8 -0
  68. package/dist/i18n/index.js +25 -1
  69. package/dist/i18n/locale.d.ts +53 -0
  70. package/dist/i18n/message.d.ts +36 -0
  71. package/dist/i18n/nestjs-i18n.translator.d.ts +9 -0
  72. package/dist/i18n/runtime.d.ts +55 -0
  73. package/dist/i18n/translator.port.d.ts +29 -0
  74. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  75. package/dist/idempotency/idempotency.module.d.ts +27 -0
  76. package/dist/idempotency/idempotency.options.d.ts +29 -0
  77. package/dist/idempotency/idempotency.port.d.ts +43 -0
  78. package/dist/idempotency/index.cjs +207 -0
  79. package/dist/idempotency/index.d.ts +7 -0
  80. package/dist/idempotency/index.js +207 -0
  81. package/dist/idempotency/memory.store.d.ts +24 -0
  82. package/dist/index.cjs +48 -15
  83. package/dist/index.js +51 -18
  84. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  85. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  86. package/dist/invoicing/amounts.d.ts +52 -0
  87. package/dist/invoicing/index.cjs +578 -0
  88. package/dist/invoicing/index.d.ts +11 -0
  89. package/dist/invoicing/index.js +578 -0
  90. package/dist/invoicing/invoicing.module.d.ts +42 -0
  91. package/dist/invoicing/invoicing.options.d.ts +51 -0
  92. package/dist/invoicing/invoicing.port.d.ts +156 -0
  93. package/dist/invoicing/lines.d.ts +21 -0
  94. package/dist/invoicing/provider-http.d.ts +21 -0
  95. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  96. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  97. package/dist/payments/index.cjs +796 -0
  98. package/dist/payments/index.d.ts +12 -0
  99. package/dist/payments/index.js +796 -0
  100. package/dist/payments/money.d.ts +20 -0
  101. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  102. package/dist/payments/payments.module.d.ts +45 -0
  103. package/dist/payments/payments.options.d.ts +84 -0
  104. package/dist/payments/payments.port.d.ts +174 -0
  105. package/dist/payments/provider-http.d.ts +26 -0
  106. package/dist/response/api-response.d.ts +7 -0
  107. package/dist/response/index.cjs +12 -4
  108. package/dist/response/index.d.ts +2 -0
  109. package/dist/response/index.js +12 -4
  110. package/dist/response/paginated.d.ts +25 -0
  111. package/dist/response/response.interceptor.d.ts +4 -0
  112. package/dist/stripe/index.cjs +4 -3
  113. package/dist/stripe/index.js +3 -2
  114. package/dist/tracking/index.cjs +3 -3
  115. package/dist/tracking/index.d.ts +1 -1
  116. package/dist/tracking/index.js +2 -2
  117. package/dist/tracking/request-context.d.ts +32 -0
  118. package/package.json +25 -3
  119. package/dist/chunk-3CLYZC3T.cjs +0 -104
  120. package/dist/chunk-EBO6UKHL.js +0 -20
  121. package/dist/chunk-IYUUYCP5.js +0 -36
  122. package/dist/chunk-JOVBJDJ2.js +0 -104
  123. package/dist/chunk-M3EL5O6T.cjs +0 -36
  124. package/dist/chunk-R7BVS6CI.cjs +0 -13
  125. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  126. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -1,12 +1,14 @@
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 _chunk4HHZFOVCcjs = require('../../chunk-4HHZFOVC.cjs');
5
+ require('../../chunk-SDWHKPXI.cjs');
5
6
 
6
7
 
7
8
 
8
- var _chunkFDNGAYTZcjs = require('../../chunk-FDNGAYTZ.cjs');
9
- require('../../chunk-R7BVS6CI.cjs');
9
+ var _chunkHDFPSA2Vcjs = require('../../chunk-HDFPSA2V.cjs');
10
+ require('../../chunk-Q5Y33L7B.cjs');
11
+ require('../../chunk-PNK5WMPP.cjs');
10
12
 
11
13
 
12
14
 
@@ -126,6 +128,8 @@ async function exchangeCodeForToken(provider, code) {
126
128
  var OAUTH_AUTH_OPTIONS = /* @__PURE__ */ Symbol("OAUTH_AUTH_OPTIONS");
127
129
  var OAUTH_STORE = /* @__PURE__ */ Symbol("OAUTH_STORE");
128
130
  var REFRESH_TOKEN_STORE = /* @__PURE__ */ Symbol("REFRESH_TOKEN_STORE");
131
+ var MAGIC_LINK_STORE = /* @__PURE__ */ Symbol("MAGIC_LINK_STORE");
132
+ var MAGIC_LINK_SENDER = /* @__PURE__ */ Symbol("MAGIC_LINK_SENDER");
129
133
  function resolveOAuthOptions(options) {
130
134
  const webUrl = options.webUrl.replace(/\/$/, "");
131
135
  return {
@@ -140,6 +144,12 @@ function resolveOAuthOptions(options) {
140
144
  sameSite: _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.cookie, 'optionalAccess', _8 => _8.sameSite]), () => ( "lax")),
141
145
  secure: _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.cookie, 'optionalAccess', _10 => _10.secure]), () => ( process.env.NODE_ENV === "production"))
142
146
  },
147
+ magicLink: {
148
+ ttlSeconds: _nullishCoalesce(_optionalChain([options, 'access', _11 => _11.magicLink, 'optionalAccess', _12 => _12.ttlSeconds]), () => ( 15 * 60)),
149
+ allowSignUp: _nullishCoalesce(_optionalChain([options, 'access', _13 => _13.magicLink, 'optionalAccess', _14 => _14.allowSignUp]), () => ( true)),
150
+ linkUrl: _nullishCoalesce(_optionalChain([options, 'access', _15 => _15.magicLink, 'optionalAccess', _16 => _16.linkUrl]), () => ( ((token) => `${webUrl}/magic-link#token=${encodeURIComponent(token)}`))),
151
+ invalidLinkMessage: _nullishCoalesce(_optionalChain([options, 'access', _17 => _17.magicLink, 'optionalAccess', _18 => _18.invalidLinkMessage]), () => ( (() => "This sign-in link is invalid or has expired. Request a new one.")))
152
+ },
143
153
  linkCookieName: _nullishCoalesce(options.linkCookieName, () => ( "link_intent")),
144
154
  stateCookieName: _nullishCoalesce(options.stateCookieName, () => ( "oauth_state")),
145
155
  accessTtlSeconds: _nullishCoalesce(options.accessTtlSeconds, () => ( 15 * 60)),
@@ -161,6 +171,7 @@ function resolveOAuthOptions(options) {
161
171
  var _common = require('@nestjs/common');
162
172
  var _crypto = require('crypto');
163
173
  var _jsonwebtoken = require('jsonwebtoken'); var _jsonwebtoken2 = _interopRequireDefault(_jsonwebtoken);
174
+ var MAGIC_LINK_PROVIDER = "email";
164
175
  function hashToken(token) {
165
176
  return _crypto.createHash.call(void 0, "sha256").update(token).digest("hex");
166
177
  }
@@ -170,9 +181,11 @@ function requireSecret(explicit, envName) {
170
181
  return value;
171
182
  }
172
183
  var OAuthAuthService = class {
173
- constructor(options, store, sessions) {
184
+ constructor(options, store, sessions, magicLinks, magicLinkSender) {
174
185
  this.store = store;
175
186
  this.sessions = sessions;
187
+ this.magicLinks = magicLinks;
188
+ this.magicLinkSender = magicLinkSender;
176
189
  this.options = resolveOAuthOptions(options);
177
190
  }
178
191
  get config() {
@@ -189,7 +202,7 @@ var OAuthAuthService = class {
189
202
  */
190
203
  provider(name) {
191
204
  const found = this.options.providers.find((p) => p.name === name);
192
- if (!_optionalChain([found, 'optionalAccess', _11 => _11.clientId]) || !found.clientSecret) {
205
+ if (!_optionalChain([found, 'optionalAccess', _19 => _19.clientId]) || !found.clientSecret) {
193
206
  throw new (0, _common.ServiceUnavailableException)(this.options.unavailableMessage(name));
194
207
  }
195
208
  return found;
@@ -255,7 +268,7 @@ var OAuthAuthService = class {
255
268
  const accessToken = await exchangeCodeForToken(provider, code);
256
269
  const profile = await provider.fetchProfile(accessToken);
257
270
  if (!profile.email) {
258
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)(this.options.missingEmailMessage(name));
271
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.missingEmailMessage(name));
259
272
  }
260
273
  return { ...profile, email: normaliseEmail(profile.email) };
261
274
  }
@@ -270,7 +283,7 @@ var OAuthAuthService = class {
270
283
  async login(providerName, profile) {
271
284
  const provider = this.provider(providerName).name;
272
285
  const existing = await this.store.findAccount(provider, profile.providerAccountId);
273
- let user = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _12 => _12.user]), () => ( null));
286
+ let user = _nullishCoalesce(_optionalChain([existing, 'optionalAccess', _20 => _20.user]), () => ( null));
274
287
  if (!user) {
275
288
  const email = normaliseEmail(profile.email);
276
289
  user = await _asyncNullishCoalesce(await this.store.findUserByEmail(email), async () => ( await this.store.createUser({
@@ -295,6 +308,69 @@ var OAuthAuthService = class {
295
308
  if (changes && (changes.name !== user.name || changes.avatarUrl !== user.avatarUrl)) {
296
309
  user = await this.store.updateUser(user.id, changes);
297
310
  }
311
+ return this.establishSession(user);
312
+ }
313
+ /**
314
+ * Sends a sign-in link to an address.
315
+ *
316
+ * Answers nothing, whatever happened: whether the address is known is not
317
+ * something a caller should be able to learn from this endpoint, so an
318
+ * unknown one (with `allowSignUp: false`) simply gets no email. The sender's
319
+ * own failure does propagate — that is the mail provider being down, which
320
+ * says nothing about the address and is something the operator must see.
321
+ *
322
+ * Throttling is the consumer's job: this will send as often as it is asked.
323
+ */
324
+ async requestMagicLink(rawEmail) {
325
+ const { store, sender } = this.requireMagicLink();
326
+ const email = normaliseEmail(rawEmail);
327
+ if (!this.options.magicLink.allowSignUp && !await this.store.findUserByEmail(email)) {
328
+ return;
329
+ }
330
+ const token = _crypto.randomBytes.call(void 0, 32).toString("base64url");
331
+ const expiresAt = new Date(Date.now() + this.options.magicLink.ttlSeconds * 1e3);
332
+ await store.create(hashToken(token), email, expiresAt);
333
+ await sender.send({ email, url: this.options.magicLink.linkUrl(token), expiresAt });
334
+ }
335
+ /**
336
+ * Spends a link and opens a session for whoever it was sent to.
337
+ *
338
+ * Spent before anything else, and only continued when the store reports a
339
+ * live row — the same shape as `refresh`. The user is found by email, so a
340
+ * link lands on the account Google or Facebook created earlier, exactly as
341
+ * signing in with the other provider would. Nothing on the profile is
342
+ * touched: a link carries no name or photo, and running `syncProfile` with
343
+ * an empty profile would erase what the OAuth provider supplied.
344
+ */
345
+ async magicLinkLogin(rawToken) {
346
+ const { store } = this.requireMagicLink();
347
+ const invalid = () => new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.options.magicLink.invalidLinkMessage(), void 0, "MAGIC_LINK_INVALID");
348
+ const record = await store.consumeIfActive(hashToken(rawToken));
349
+ if (!record || record.expiresAt.getTime() <= Date.now()) throw invalid();
350
+ const email = normaliseEmail(record.email);
351
+ let user = await this.store.findUserByEmail(email);
352
+ if (!user) {
353
+ if (!this.options.magicLink.allowSignUp) throw invalid();
354
+ user = await this.store.createUser({ email });
355
+ }
356
+ return this.establishSession(user);
357
+ }
358
+ /** Whether the magic-link routes can work in this app. */
359
+ get magicLinkEnabled() {
360
+ return Boolean(this.magicLinks && this.magicLinkSender);
361
+ }
362
+ requireMagicLink() {
363
+ if (!this.magicLinks || !this.magicLinkSender) {
364
+ throw new (0, _common.ServiceUnavailableException)(this.options.unavailableMessage(MAGIC_LINK_PROVIDER));
365
+ }
366
+ return { store: this.magicLinks, sender: this.magicLinkSender };
367
+ }
368
+ /**
369
+ * The one place a session is opened. Every sign-in — OAuth or magic link —
370
+ * ends here, so `singleSession` and the token pair behave identically
371
+ * whichever door was used.
372
+ */
373
+ async establishSession(user) {
298
374
  if (this.options.singleSession) {
299
375
  await this.sessions.revokeAllForUser(user.id);
300
376
  }
@@ -311,9 +387,9 @@ var OAuthAuthService = class {
311
387
  async refresh(rawRefreshToken) {
312
388
  const payload = this.verifyRefresh(rawRefreshToken);
313
389
  const { count } = await this.sessions.revokeIfActive(hashToken(rawRefreshToken));
314
- if (count === 0) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid refresh token.");
390
+ if (count === 0) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid refresh token.");
315
391
  const user = await this.store.findUserById(payload.sub);
316
- if (!user) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid refresh token.");
392
+ if (!user) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid refresh token.");
317
393
  return this.issueTokenPair(user);
318
394
  }
319
395
  async logout(rawRefreshToken) {
@@ -321,7 +397,7 @@ var OAuthAuthService = class {
321
397
  }
322
398
  async currentUser(userId) {
323
399
  const user = await this.store.findUserById(userId);
324
- if (!user) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("User not found.");
400
+ if (!user) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("User not found.");
325
401
  return this.present(user);
326
402
  }
327
403
  /**
@@ -372,7 +448,7 @@ var OAuthAuthService = class {
372
448
  const provider = this.provider(providerName).name;
373
449
  const existing = await this.store.findAccount(provider, profile.providerAccountId);
374
450
  if (existing && existing.userId !== userId) {
375
- throw new (0, _chunkFDNGAYTZcjs.ValidationAppException)(
451
+ throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)(
376
452
  "That account is already connected to another profile.",
377
453
  { provider },
378
454
  "OAUTH_ACCOUNT_TAKEN"
@@ -380,7 +456,7 @@ var OAuthAuthService = class {
380
456
  }
381
457
  const alreadyLinked = await this.store.findAccountByUserAndProvider(userId, provider);
382
458
  if (alreadyLinked && alreadyLinked.providerAccountId !== profile.providerAccountId) {
383
- throw new (0, _chunkFDNGAYTZcjs.ValidationAppException)(
459
+ throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)(
384
460
  "You already have an account from that provider connected.",
385
461
  { provider },
386
462
  "OAUTH_PROVIDER_ALREADY_LINKED"
@@ -443,7 +519,7 @@ var OAuthAuthService = class {
443
519
  requireSecret(this.options.refreshSecret, "JWT_REFRESH_SECRET")
444
520
  );
445
521
  } catch (e4) {
446
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid refresh token.");
522
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid refresh token.");
447
523
  }
448
524
  }
449
525
  };
@@ -451,12 +527,51 @@ OAuthAuthService = exports.OAuthAuthService = _chunk2REOCMUDcjs.__decorateClass.
451
527
  _common.Injectable.call(void 0, ),
452
528
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, OAUTH_AUTH_OPTIONS)),
453
529
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, OAUTH_STORE)),
454
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Inject.call(void 0, REFRESH_TOKEN_STORE))
530
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 2, _common.Inject.call(void 0, REFRESH_TOKEN_STORE)),
531
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Optional.call(void 0, )),
532
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 3, _common.Inject.call(void 0, MAGIC_LINK_STORE)),
533
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Optional.call(void 0, )),
534
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Inject.call(void 0, MAGIC_LINK_SENDER))
455
535
  ], OAuthAuthService);
456
536
  function normaliseEmail(email) {
457
537
  return email.trim().toLowerCase();
458
538
  }
459
539
 
540
+ // src/auth/oauth/memory-magic-link.store.ts
541
+ var MemoryMagicLinkStore = class {
542
+ constructor(maxEntries = 1e4) {
543
+ this.maxEntries = maxEntries;
544
+ this.links = /* @__PURE__ */ new Map();
545
+ }
546
+ async create(tokenHash, email, expiresAt) {
547
+ if (this.links.size >= this.maxEntries) {
548
+ const oldest = this.links.keys().next().value;
549
+ if (oldest !== void 0) this.links.delete(oldest);
550
+ }
551
+ this.links.set(tokenHash, { email, expiresAt });
552
+ }
553
+ async consumeIfActive(tokenHash) {
554
+ const record = this.links.get(tokenHash);
555
+ this.links.delete(tokenHash);
556
+ if (!record || record.expiresAt.getTime() <= Date.now()) return null;
557
+ return record;
558
+ }
559
+ };
560
+
561
+ // src/auth/oauth/magic-link.dto.ts
562
+ var _classvalidator = require('class-validator');
563
+ var MagicLinkRequestDto = class {
564
+ };
565
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
566
+ _classvalidator.IsEmail.call(void 0, )
567
+ ], MagicLinkRequestDto.prototype, "email", 2);
568
+ var MagicLinkVerifyDto = class {
569
+ };
570
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
571
+ _classvalidator.IsString.call(void 0, ),
572
+ _classvalidator.MinLength.call(void 0, 16)
573
+ ], MagicLinkVerifyDto.prototype, "token", 2);
574
+
460
575
  // src/auth/oauth/oauth-callback.filter.ts
461
576
 
462
577
 
@@ -472,10 +587,12 @@ function setCookie(reply, name, value, options) {
472
587
  else throw new Error("No cookie support on the reply: register @fastify/cookie or cookie-parser.");
473
588
  }
474
589
  function clearCookie(reply, name, options) {
475
- _optionalChain([reply, 'access', _13 => _13.clearCookie, 'optionalCall', _14 => _14(name, options)]);
590
+ _optionalChain([reply, 'access', _21 => _21.clearCookie, 'optionalCall', _22 => _22(name, options)]);
476
591
  }
477
592
  function redirect(reply, url) {
478
- reply.redirect(url, 302);
593
+ const send = reply.redirect;
594
+ if (typeof reply.code === "function") send.call(reply, url, 302);
595
+ else send.call(reply, 302, url);
479
596
  }
480
597
 
481
598
  // src/auth/oauth/oauth-callback.filter.ts
@@ -510,22 +627,26 @@ OAuthCallbackFilter = exports.OAuthCallbackFilter = _chunk2REOCMUDcjs.__decorate
510
627
 
511
628
 
512
629
 
630
+
631
+
513
632
  function createOAuthController(options = {}) {
514
- const Guard = _nullishCoalesce(options.guard, () => ( _chunkNVCI3CQIcjs.JwtAuthGuard));
633
+ const Guard = _nullishCoalesce(options.guard, () => ( _chunk4HHZFOVCcjs.JwtAuthGuard));
515
634
  const userId = _nullishCoalesce(options.userId, () => ( ((user) => user.sub)));
516
635
  let OAuthControllerHost = class {
636
+ // Explicit token: the build emits no `design:paramtypes`, so a subclass
637
+ // with no constructor of its own would otherwise get `auth` undefined.
517
638
  constructor(auth) {
518
639
  this.auth = auth;
519
640
  }
520
641
  async refresh(request, reply) {
521
- const raw = _optionalChain([request, 'access', _15 => _15.cookies, 'optionalAccess', _16 => _16[this.auth.config.cookie.name]]);
522
- if (!raw) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("No refresh token.");
642
+ const raw = _optionalChain([request, 'access', _23 => _23.cookies, 'optionalAccess', _24 => _24[this.auth.config.cookie.name]]);
643
+ if (!raw) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("No refresh token.");
523
644
  const { accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.refresh(raw);
524
645
  this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
525
646
  return { accessToken };
526
647
  }
527
648
  async logout(request, reply) {
528
- const raw = _optionalChain([request, 'access', _17 => _17.cookies, 'optionalAccess', _18 => _18[this.auth.config.cookie.name]]);
649
+ const raw = _optionalChain([request, 'access', _25 => _25.cookies, 'optionalAccess', _26 => _26[this.auth.config.cookie.name]]);
529
650
  if (raw) await this.auth.logout(raw);
530
651
  clearCookie(reply, this.auth.config.cookie.name, { path: this.auth.config.cookie.path });
531
652
  return { success: true };
@@ -544,6 +665,23 @@ function createOAuthController(options = {}) {
544
665
  });
545
666
  return { ok: true };
546
667
  }
668
+ async requestMagicLink(body) {
669
+ await this.auth.requestMagicLink(body.email);
670
+ return { ok: true };
671
+ }
672
+ async verifyMagicLink(body, reply) {
673
+ const { user, accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.magicLinkLogin(
674
+ body.token
675
+ );
676
+ this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
677
+ return { accessToken, user };
678
+ }
679
+ async magicLinkCallback(token, reply) {
680
+ if (!token) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.magicLink.invalidLinkMessage());
681
+ const { accessToken, refreshToken, refreshTokenExpiresAt } = await this.auth.magicLinkLogin(token);
682
+ this.writeRefreshCookie(reply, refreshToken, refreshTokenExpiresAt);
683
+ redirect(reply, this.auth.config.onLoginRedirect(accessToken));
684
+ }
547
685
  start(provider, reply) {
548
686
  const { url, state, expiresAt } = this.auth.authorizeUrl(provider);
549
687
  setCookie(reply, this.auth.config.stateCookieName, state, {
@@ -553,16 +691,16 @@ function createOAuthController(options = {}) {
553
691
  redirect(reply, url);
554
692
  }
555
693
  async callback(provider, code, state, request, reply) {
556
- if (!code) throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
557
- const stateCookie = _optionalChain([request, 'access', _19 => _19.cookies, 'optionalAccess', _20 => _20[this.auth.config.stateCookieName]]);
694
+ if (!code) throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
695
+ const stateCookie = _optionalChain([request, 'access', _27 => _27.cookies, 'optionalAccess', _28 => _28[this.auth.config.stateCookieName]]);
558
696
  clearCookie(reply, this.auth.config.stateCookieName, {
559
697
  path: this.auth.config.cookie.path
560
698
  });
561
699
  if (!this.auth.verifyState(state, stateCookie, provider)) {
562
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
700
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)(this.auth.config.genericErrorMessage());
563
701
  }
564
702
  const profile = await this.auth.profileFromCode(provider, code);
565
- const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _21 => _21.cookies, 'optionalAccess', _22 => _22[this.auth.config.linkCookieName]]));
703
+ const linkUserId = this.auth.readLinkToken(_optionalChain([request, 'access', _29 => _29.cookies, 'optionalAccess', _30 => _30[this.auth.config.linkCookieName]]));
566
704
  if (linkUserId) {
567
705
  clearCookie(reply, this.auth.config.linkCookieName, { path: this.auth.config.cookie.path });
568
706
  try {
@@ -605,19 +743,34 @@ function createOAuthController(options = {}) {
605
743
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
606
744
  _common.UseGuards.call(void 0, Guard),
607
745
  _common.Get.call(void 0, "me"),
608
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, ))
746
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunk4HHZFOVCcjs.CurrentUser.call(void 0, ))
609
747
  ], OAuthControllerHost.prototype, "me", 1);
610
748
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
611
749
  _common.UseGuards.call(void 0, Guard),
612
750
  _common.Get.call(void 0, "linked-accounts"),
613
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, ))
751
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunk4HHZFOVCcjs.CurrentUser.call(void 0, ))
614
752
  ], OAuthControllerHost.prototype, "linkedAccounts", 1);
615
753
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
616
754
  _common.UseGuards.call(void 0, Guard),
617
755
  _common.Post.call(void 0, "link-intent"),
618
- _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunkNVCI3CQIcjs.CurrentUser.call(void 0, )),
756
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _chunk4HHZFOVCcjs.CurrentUser.call(void 0, )),
619
757
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
620
758
  ], OAuthControllerHost.prototype, "linkIntent", 1);
759
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
760
+ _common.Post.call(void 0, "magic-link"),
761
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, ))
762
+ ], OAuthControllerHost.prototype, "requestMagicLink", 1);
763
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
764
+ _common.Post.call(void 0, "magic-link/verify"),
765
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Body.call(void 0, )),
766
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, { passthrough: true }))
767
+ ], OAuthControllerHost.prototype, "verifyMagicLink", 1);
768
+ _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
769
+ _common.Get.call(void 0, "magic-link/callback"),
770
+ _common.UseFilters.call(void 0, OAuthCallbackFilter),
771
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Query.call(void 0, "token")),
772
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Res.call(void 0, ))
773
+ ], OAuthControllerHost.prototype, "magicLinkCallback", 1);
621
774
  _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
622
775
  _common.Get.call(void 0, ":provider"),
623
776
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "provider")),
@@ -633,7 +786,8 @@ function createOAuthController(options = {}) {
633
786
  _chunk2REOCMUDcjs.__decorateParam.call(void 0, 4, _common.Res.call(void 0, ))
634
787
  ], OAuthControllerHost.prototype, "callback", 1);
635
788
  OAuthControllerHost = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
636
- _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "auth")))
789
+ _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "auth"))),
790
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, OAuthAuthService))
637
791
  ], OAuthControllerHost);
638
792
  return OAuthControllerHost;
639
793
  }
@@ -674,4 +828,10 @@ OAuthAuthModule = exports.OAuthAuthModule = _chunk2REOCMUDcjs.__decorateClass.ca
674
828
 
675
829
 
676
830
 
677
- exports.OAUTH_AUTH_OPTIONS = OAUTH_AUTH_OPTIONS; exports.OAUTH_STORE = OAUTH_STORE; exports.OAuthAuthModule = OAuthAuthModule; exports.OAuthAuthService = OAuthAuthService; exports.OAuthCallbackFilter = OAuthCallbackFilter; exports.REFRESH_TOKEN_STORE = REFRESH_TOKEN_STORE; exports.buildAuthorizeUrl = buildAuthorizeUrl; exports.createOAuthController = createOAuthController; exports.exchangeCodeForToken = exchangeCodeForToken; exports.facebookProvider = facebookProvider; exports.googleProvider = googleProvider; exports.resolveOAuthOptions = resolveOAuthOptions;
831
+
832
+
833
+
834
+
835
+
836
+
837
+ exports.MAGIC_LINK_PROVIDER = MAGIC_LINK_PROVIDER; exports.MAGIC_LINK_SENDER = MAGIC_LINK_SENDER; exports.MAGIC_LINK_STORE = MAGIC_LINK_STORE; exports.MagicLinkRequestDto = MagicLinkRequestDto; exports.MagicLinkVerifyDto = MagicLinkVerifyDto; exports.MemoryMagicLinkStore = MemoryMagicLinkStore; exports.OAUTH_AUTH_OPTIONS = OAUTH_AUTH_OPTIONS; exports.OAUTH_STORE = OAUTH_STORE; exports.OAuthAuthModule = OAuthAuthModule; exports.OAuthAuthService = OAuthAuthService; exports.OAuthCallbackFilter = OAuthCallbackFilter; exports.REFRESH_TOKEN_STORE = REFRESH_TOKEN_STORE; exports.buildAuthorizeUrl = buildAuthorizeUrl; exports.createOAuthController = createOAuthController; exports.exchangeCodeForToken = exchangeCodeForToken; exports.facebookProvider = facebookProvider; exports.googleProvider = googleProvider; exports.resolveOAuthOptions = resolveOAuthOptions;
@@ -1,9 +1,11 @@
1
1
  export { googleProvider, facebookProvider, buildAuthorizeUrl, exchangeCodeForToken, } from './oauth-provider.js';
2
2
  export type { OAuthProfile, OAuthProviderConfig, ProviderCredentials, } from './oauth-provider.js';
3
- export type { OAuthUser, OAuthAccount, OAuthStorePort, RefreshTokenStorePort, ProfileSyncPolicy, } from './oauth.ports.js';
4
- export { OAUTH_AUTH_OPTIONS, OAUTH_STORE, REFRESH_TOKEN_STORE, resolveOAuthOptions, } from './oauth.options.js';
5
- export type { OAuthAuthOptions, OAuthCookieOptions, ResolvedOAuthOptions, } from './oauth.options.js';
6
- export { OAuthAuthService } from './oauth-auth.service.js';
3
+ export type { OAuthUser, OAuthAccount, OAuthStorePort, RefreshTokenStorePort, ProfileSyncPolicy, MagicLinkStorePort, MagicLinkSenderPort, MagicLinkDelivery, } from './oauth.ports.js';
4
+ export { OAUTH_AUTH_OPTIONS, OAUTH_STORE, REFRESH_TOKEN_STORE, MAGIC_LINK_STORE, MAGIC_LINK_SENDER, resolveOAuthOptions, } from './oauth.options.js';
5
+ export type { OAuthAuthOptions, OAuthCookieOptions, MagicLinkOptions, ResolvedOAuthOptions, } from './oauth.options.js';
6
+ export { OAuthAuthService, MAGIC_LINK_PROVIDER } from './oauth-auth.service.js';
7
+ export { MemoryMagicLinkStore } from './memory-magic-link.store.js';
8
+ export { MagicLinkRequestDto, MagicLinkVerifyDto } from './magic-link.dto.js';
7
9
  export type { TokenPair } from './oauth-auth.service.js';
8
10
  export { OAuthCallbackFilter } from './oauth-callback.filter.js';
9
11
  export { createOAuthController } from './oauth.controller.js';