@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
  import {
2
2
  CurrentUser,
3
3
  JwtAuthGuard
4
- } from "../../chunk-A3B2EY4V.js";
4
+ } from "../../chunk-IKXSVEJ7.js";
5
+ import "../../chunk-ETRUVZTJ.js";
5
6
  import {
6
7
  UnauthorizedAppException,
7
8
  ValidationAppException
8
- } from "../../chunk-ORWJ7LES.js";
9
- import "../../chunk-YFYHLYHN.js";
9
+ } from "../../chunk-ZFIDAX7K.js";
10
+ import "../../chunk-M3GQDRWR.js";
11
+ import "../../chunk-VVMRZEIW.js";
10
12
  import {
11
13
  __decorateClass,
12
14
  __decorateParam
@@ -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: options.cookie?.sameSite ?? "lax",
141
145
  secure: options.cookie?.secure ?? process.env.NODE_ENV === "production"
142
146
  },
147
+ magicLink: {
148
+ ttlSeconds: options.magicLink?.ttlSeconds ?? 15 * 60,
149
+ allowSignUp: options.magicLink?.allowSignUp ?? true,
150
+ linkUrl: options.magicLink?.linkUrl ?? ((token) => `${webUrl}/magic-link#token=${encodeURIComponent(token)}`),
151
+ invalidLinkMessage: options.magicLink?.invalidLinkMessage ?? (() => "This sign-in link is invalid or has expired. Request a new one.")
152
+ },
143
153
  linkCookieName: options.linkCookieName ?? "link_intent",
144
154
  stateCookieName: options.stateCookieName ?? "oauth_state",
145
155
  accessTtlSeconds: options.accessTtlSeconds ?? 15 * 60,
@@ -158,9 +168,10 @@ function resolveOAuthOptions(options) {
158
168
  }
159
169
 
160
170
  // src/auth/oauth/oauth-auth.service.ts
161
- import { Inject, Injectable, ServiceUnavailableException } from "@nestjs/common";
162
- import { createHash, randomUUID, timingSafeEqual } from "crypto";
171
+ import { Inject, Injectable, Optional, ServiceUnavailableException } from "@nestjs/common";
172
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "crypto";
163
173
  import jwt from "jsonwebtoken";
174
+ var MAGIC_LINK_PROVIDER = "email";
164
175
  function hashToken(token) {
165
176
  return createHash("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() {
@@ -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 = randomBytes(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 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 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
  }
@@ -451,12 +527,51 @@ OAuthAuthService = __decorateClass([
451
527
  Injectable(),
452
528
  __decorateParam(0, Inject(OAUTH_AUTH_OPTIONS)),
453
529
  __decorateParam(1, Inject(OAUTH_STORE)),
454
- __decorateParam(2, Inject(REFRESH_TOKEN_STORE))
530
+ __decorateParam(2, Inject(REFRESH_TOKEN_STORE)),
531
+ __decorateParam(3, Optional()),
532
+ __decorateParam(3, Inject(MAGIC_LINK_STORE)),
533
+ __decorateParam(4, Optional()),
534
+ __decorateParam(4, Inject(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
+ import { IsEmail, IsString, MinLength } from "class-validator";
563
+ var MagicLinkRequestDto = class {
564
+ };
565
+ __decorateClass([
566
+ IsEmail()
567
+ ], MagicLinkRequestDto.prototype, "email", 2);
568
+ var MagicLinkVerifyDto = class {
569
+ };
570
+ __decorateClass([
571
+ IsString(),
572
+ MinLength(16)
573
+ ], MagicLinkVerifyDto.prototype, "token", 2);
574
+
460
575
  // src/auth/oauth/oauth-callback.filter.ts
461
576
  import {
462
577
  Catch,
@@ -475,7 +590,9 @@ function clearCookie(reply, name, options) {
475
590
  reply.clearCookie?.(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
@@ -500,8 +617,10 @@ OAuthCallbackFilter = __decorateClass([
500
617
 
501
618
  // src/auth/oauth/oauth.controller.ts
502
619
  import {
620
+ Body,
503
621
  Controller,
504
622
  Get,
623
+ Inject as Inject3,
505
624
  Param,
506
625
  Post,
507
626
  Query,
@@ -514,6 +633,8 @@ function createOAuthController(options = {}) {
514
633
  const Guard = options.guard ?? JwtAuthGuard;
515
634
  const userId = 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
  }
@@ -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 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, {
@@ -618,6 +756,21 @@ function createOAuthController(options = {}) {
618
756
  __decorateParam(0, CurrentUser()),
619
757
  __decorateParam(1, Res({ passthrough: true }))
620
758
  ], OAuthControllerHost.prototype, "linkIntent", 1);
759
+ __decorateClass([
760
+ Post("magic-link"),
761
+ __decorateParam(0, Body())
762
+ ], OAuthControllerHost.prototype, "requestMagicLink", 1);
763
+ __decorateClass([
764
+ Post("magic-link/verify"),
765
+ __decorateParam(0, Body()),
766
+ __decorateParam(1, Res({ passthrough: true }))
767
+ ], OAuthControllerHost.prototype, "verifyMagicLink", 1);
768
+ __decorateClass([
769
+ Get("magic-link/callback"),
770
+ UseFilters(OAuthCallbackFilter),
771
+ __decorateParam(0, Query("token")),
772
+ __decorateParam(1, Res())
773
+ ], OAuthControllerHost.prototype, "magicLinkCallback", 1);
621
774
  __decorateClass([
622
775
  Get(":provider"),
623
776
  __decorateParam(0, Param("provider")),
@@ -633,7 +786,8 @@ function createOAuthController(options = {}) {
633
786
  __decorateParam(4, Res())
634
787
  ], OAuthControllerHost.prototype, "callback", 1);
635
788
  OAuthControllerHost = __decorateClass([
636
- Controller(options.path ?? "auth")
789
+ Controller(options.path ?? "auth"),
790
+ __decorateParam(0, Inject3(OAuthAuthService))
637
791
  ], OAuthControllerHost);
638
792
  return OAuthControllerHost;
639
793
  }
@@ -662,6 +816,12 @@ OAuthAuthModule = __decorateClass([
662
816
  Module({})
663
817
  ], OAuthAuthModule);
664
818
  export {
819
+ MAGIC_LINK_PROVIDER,
820
+ MAGIC_LINK_SENDER,
821
+ MAGIC_LINK_STORE,
822
+ MagicLinkRequestDto,
823
+ MagicLinkVerifyDto,
824
+ MemoryMagicLinkStore,
665
825
  OAUTH_AUTH_OPTIONS,
666
826
  OAUTH_STORE,
667
827
  OAuthAuthModule,
@@ -0,0 +1,6 @@
1
+ export declare class MagicLinkRequestDto {
2
+ email: string;
3
+ }
4
+ export declare class MagicLinkVerifyDto {
5
+ token: string;
6
+ }
@@ -0,0 +1,19 @@
1
+ import type { MagicLinkStorePort } from './oauth.ports.js';
2
+ /**
3
+ * In-memory `MagicLinkStorePort`, for development and tests.
4
+ *
5
+ * Not for production: links vanish on restart and are not shared between
6
+ * instances, so a link requested from one replica cannot be spent on
7
+ * another. Bounded, and the oldest goes first — a burst of requests must
8
+ * not grow the process without end.
9
+ */
10
+ export declare class MemoryMagicLinkStore implements MagicLinkStorePort {
11
+ private readonly maxEntries;
12
+ private readonly links;
13
+ constructor(maxEntries?: number);
14
+ create(tokenHash: string, email: string, expiresAt: Date): Promise<void>;
15
+ consumeIfActive(tokenHash: string): Promise<{
16
+ email: string;
17
+ expiresAt: Date;
18
+ } | null>;
19
+ }
@@ -1,23 +1,30 @@
1
1
  import { type OAuthProfile, type OAuthProviderConfig } from './oauth-provider.js';
2
2
  import { type OAuthAuthOptions, type ResolvedOAuthOptions } from './oauth.options.js';
3
- import type { OAuthStorePort, OAuthUser, RefreshTokenStorePort } from './oauth.ports.js';
3
+ import type { MagicLinkSenderPort, MagicLinkStorePort, OAuthStorePort, OAuthUser, RefreshTokenStorePort } from './oauth.ports.js';
4
+ /** The stored provider key a magic-link session reports as its origin. */
5
+ export declare const MAGIC_LINK_PROVIDER = "email";
4
6
  export interface TokenPair {
5
7
  accessToken: string;
6
8
  refreshToken: string;
7
9
  refreshTokenExpiresAt: Date;
8
10
  }
9
11
  /**
10
- * OAuth sign-in, account linking and rotating refresh sessions.
12
+ * OAuth sign-in, magic-link sign-in, account linking and rotating refresh
13
+ * sessions.
11
14
  *
12
15
  * Knows nothing about a database: everything it stores goes through
13
- * `OAuthStorePort` and `RefreshTokenStorePort`, so the same service runs on
14
- * Prisma, Drizzle or a hand-written repository.
16
+ * `OAuthStorePort`, `RefreshTokenStorePort` and, for magic links,
17
+ * `MagicLinkStorePort`, so the same service runs on Prisma, Drizzle or a
18
+ * hand-written repository. Every way in ends in the same `establishSession`,
19
+ * which is what makes a session indistinguishable by how it was opened.
15
20
  */
16
21
  export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
17
22
  private readonly store;
18
23
  private readonly sessions;
24
+ private readonly magicLinks?;
25
+ private readonly magicLinkSender?;
19
26
  private readonly options;
20
- constructor(options: OAuthAuthOptions<U>, store: OAuthStorePort<U>, sessions: RefreshTokenStorePort);
27
+ constructor(options: OAuthAuthOptions<U>, store: OAuthStorePort<U>, sessions: RefreshTokenStorePort, magicLinks?: MagicLinkStorePort | undefined, magicLinkSender?: MagicLinkSenderPort | undefined);
21
28
  get config(): ResolvedOAuthOptions<U>;
22
29
  /**
23
30
  * Looks up a configured provider, or explains that it is unavailable.
@@ -71,6 +78,40 @@ export declare class OAuthAuthService<U extends OAuthUser = OAuthUser> {
71
78
  login(providerName: string, profile: OAuthProfile): Promise<{
72
79
  user: unknown;
73
80
  } & TokenPair>;
81
+ /**
82
+ * Sends a sign-in link to an address.
83
+ *
84
+ * Answers nothing, whatever happened: whether the address is known is not
85
+ * something a caller should be able to learn from this endpoint, so an
86
+ * unknown one (with `allowSignUp: false`) simply gets no email. The sender's
87
+ * own failure does propagate — that is the mail provider being down, which
88
+ * says nothing about the address and is something the operator must see.
89
+ *
90
+ * Throttling is the consumer's job: this will send as often as it is asked.
91
+ */
92
+ requestMagicLink(rawEmail: string): Promise<void>;
93
+ /**
94
+ * Spends a link and opens a session for whoever it was sent to.
95
+ *
96
+ * Spent before anything else, and only continued when the store reports a
97
+ * live row — the same shape as `refresh`. The user is found by email, so a
98
+ * link lands on the account Google or Facebook created earlier, exactly as
99
+ * signing in with the other provider would. Nothing on the profile is
100
+ * touched: a link carries no name or photo, and running `syncProfile` with
101
+ * an empty profile would erase what the OAuth provider supplied.
102
+ */
103
+ magicLinkLogin(rawToken: string): Promise<{
104
+ user: unknown;
105
+ } & TokenPair>;
106
+ /** Whether the magic-link routes can work in this app. */
107
+ get magicLinkEnabled(): boolean;
108
+ private requireMagicLink;
109
+ /**
110
+ * The one place a session is opened. Every sign-in — OAuth or magic link —
111
+ * ends here, so `singleSession` and the token pair behave identically
112
+ * whichever door was used.
113
+ */
114
+ private establishSession;
74
115
  /**
75
116
  * Rotates a refresh token: the old one is spent, a new pair comes back.
76
117
  *
@@ -33,6 +33,10 @@ export interface CreateOAuthControllerOptions {
33
33
  * provider, so adding Apple later touches configuration only. The static
34
34
  * routes are declared first on purpose: Fastify's router always prefers a
35
35
  * static segment over a parametric one, but Express matches in declaration
36
- * order, and `me` would otherwise be read as a provider name.
36
+ * order, and `me` or `magic-link` would otherwise be read as a provider name.
37
+ *
38
+ * The magic-link routes are always generated. Without `MAGIC_LINK_STORE` and
39
+ * `MAGIC_LINK_SENDER` bound they answer 503, like `/auth/apple` with no
40
+ * credentials — one rule for every door that is not configured.
37
41
  */
38
42
  export declare function createOAuthController(options?: CreateOAuthControllerOptions): Type<object>;
@@ -5,6 +5,36 @@ export declare const OAUTH_AUTH_OPTIONS: unique symbol;
5
5
  export declare const OAUTH_STORE: unique symbol;
6
6
  /** Bind to an implementation of `RefreshTokenStorePort`. */
7
7
  export declare const REFRESH_TOKEN_STORE: unique symbol;
8
+ /** Bind to an implementation of `MagicLinkStorePort`. Optional: without it the magic-link routes answer 503. */
9
+ export declare const MAGIC_LINK_STORE: unique symbol;
10
+ /** Bind to an implementation of `MagicLinkSenderPort`. Optional, same rule. */
11
+ export declare const MAGIC_LINK_SENDER: unique symbol;
12
+ export interface MagicLinkOptions {
13
+ /**
14
+ * How long a link works. Default 15 minutes: long enough to open the inbox
15
+ * on another device, short enough that a forwarded or logged link is dead
16
+ * by the time anyone reads it.
17
+ */
18
+ ttlSeconds?: number;
19
+ /**
20
+ * Whether a link may create the account the first time, as an OAuth
21
+ * sign-in does. Default `true`. With `false`, an unknown address gets no
22
+ * email — and the same `ok` answer, so nothing reveals which is which.
23
+ */
24
+ allowSignUp?: boolean;
25
+ /**
26
+ * The URL that goes in the email. Default `${webUrl}/magic-link#token=…`:
27
+ * a page in the web app that reads the fragment and calls
28
+ * `POST /auth/magic-link/verify` **on a click**. Pointing the link at
29
+ * `GET /auth/magic-link/callback` instead skips that page, but then a mail
30
+ * scanner that prefetches links (Outlook Safe Links, corporate proxies)
31
+ * spends the single use before the person sees it. The fragment never
32
+ * reaches a server log either.
33
+ */
34
+ linkUrl?(token: string): string;
35
+ /** Shown when a link is unknown, used or expired. Reaches the user. */
36
+ invalidLinkMessage?(): string;
37
+ }
8
38
  export interface OAuthCookieOptions {
9
39
  /** Default `refresh_token`. */
10
40
  name?: string;
@@ -69,6 +99,8 @@ export interface OAuthAuthOptions<U extends OAuthUser = OAuthUser> {
69
99
  singleSession?: boolean;
70
100
  /** See `ProfileSyncPolicy`. Default resyncs name and photo every login. */
71
101
  syncProfile?: ProfileSyncPolicy<U>;
102
+ /** Passwordless sign-in by email. Needs `MAGIC_LINK_STORE` and `MAGIC_LINK_SENDER` bound. */
103
+ magicLink?: MagicLinkOptions;
72
104
  /**
73
105
  * Shapes the user in API responses. Without it the stored row goes out
74
106
  * whole, password hashes and internal columns included — so anything with
@@ -90,10 +122,11 @@ export interface OAuthAuthOptions<U extends OAuthUser = OAuthUser> {
90
122
  genericErrorMessage?(): string;
91
123
  }
92
124
  /** Everything above, with the defaults filled in. Internal. */
93
- export interface ResolvedOAuthOptions<U extends OAuthUser = OAuthUser> extends Required<Omit<OAuthAuthOptions<U>, 'accessSecret' | 'refreshSecret' | 'cookie' | 'mapUser' | 'syncProfile'>> {
125
+ export interface ResolvedOAuthOptions<U extends OAuthUser = OAuthUser> extends Required<Omit<OAuthAuthOptions<U>, 'accessSecret' | 'refreshSecret' | 'cookie' | 'mapUser' | 'syncProfile' | 'magicLink'>> {
94
126
  accessSecret?: string;
95
127
  refreshSecret?: string;
96
128
  cookie: Required<OAuthCookieOptions>;
129
+ magicLink: Required<MagicLinkOptions>;
97
130
  mapUser?(user: U): unknown;
98
131
  syncProfile: ProfileSyncPolicy<U>;
99
132
  }
@@ -84,3 +84,41 @@ export type ProfileSyncPolicy<U extends OAuthUser = OAuthUser> = (user: U, profi
84
84
  name?: string | null;
85
85
  avatarUrl?: string | null;
86
86
  } | null;
87
+ /**
88
+ * Persistence for magic links: one row per link sent, keyed by the SHA-256
89
+ * of the token — the same rule as refresh tokens, for the same reason.
90
+ *
91
+ * `consumeIfActive` **must be atomic** (a conditional `UPDATE … WHERE
92
+ * used_at IS NULL` or a `DELETE … RETURNING`, never read-then-write): a link
93
+ * forwarded to two devices, or opened by a mail scanner and then by the
94
+ * person, must sign in exactly once. A store may also invalidate the
95
+ * previous links of the same email on `create`, so only the latest one
96
+ * works; nestkit does not require it.
97
+ */
98
+ export interface MagicLinkStorePort {
99
+ create(tokenHash: string, email: string, expiresAt: Date): Promise<void>;
100
+ /**
101
+ * Marks the link used and returns what it was issued for, or `null` when
102
+ * it is unknown, already used or expired. The service checks `expiresAt`
103
+ * again, so a store that forgets to is still safe.
104
+ */
105
+ consumeIfActive(tokenHash: string): Promise<{
106
+ email: string;
107
+ expiresAt: Date;
108
+ } | null>;
109
+ }
110
+ export interface MagicLinkDelivery {
111
+ /** Normalised (trimmed, lower-cased). */
112
+ email: string;
113
+ /** The full link to put in the message. Built by `magicLink.linkUrl`. */
114
+ url: string;
115
+ expiresAt: Date;
116
+ }
117
+ /**
118
+ * Sends the link. nestkit never sends email itself — the consumer wires
119
+ * `email/resend`, `email/nodemailer` or anything else behind this, together
120
+ * with the template, the sender address and the language.
121
+ */
122
+ export interface MagicLinkSenderPort {
123
+ send(delivery: MagicLinkDelivery): Promise<void>;
124
+ }
@@ -1,11 +1,14 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunk54ZXIB5Tcjs = require('../chunk-54ZXIB5T.cjs');
4
- require('../chunk-TJHRABML.cjs');
5
- require('../chunk-J7TURDAL.cjs');
6
- require('../chunk-ZA56XBCK.cjs');
7
- require('../chunk-R7BVS6CI.cjs');
3
+ var _chunkFNUZGYUFcjs = require('../chunk-FNUZGYUF.cjs');
4
+ require('../chunk-3AUOOEQO.cjs');
5
+ require('../chunk-MSTXS3MU.cjs');
6
+ require('../chunk-AXMW5JF7.cjs');
7
+ require('../chunk-Y72D5L6I.cjs');
8
+ require('../chunk-SDWHKPXI.cjs');
9
+ require('../chunk-Q5Y33L7B.cjs');
10
+ require('../chunk-PNK5WMPP.cjs');
8
11
  require('../chunk-2REOCMUD.cjs');
9
12
 
10
13
 
11
- exports.applyNestKitDefaults = _chunk54ZXIB5Tcjs.applyNestKitDefaults;
14
+ exports.applyNestKitDefaults = _chunkFNUZGYUFcjs.applyNestKitDefaults;
@@ -1,10 +1,13 @@
1
1
  import {
2
2
  applyNestKitDefaults
3
- } from "../chunk-AOCF5QCZ.js";
4
- import "../chunk-KDAA6GFF.js";
5
- import "../chunk-7I2Y7V52.js";
6
- import "../chunk-EBO6UKHL.js";
7
- import "../chunk-YFYHLYHN.js";
3
+ } from "../chunk-UNEVXCFW.js";
4
+ import "../chunk-DYHSOULW.js";
5
+ import "../chunk-A2DGK4ZL.js";
6
+ import "../chunk-X4PQJZ4G.js";
7
+ import "../chunk-TCAMLNUZ.js";
8
+ import "../chunk-ETRUVZTJ.js";
9
+ import "../chunk-M3GQDRWR.js";
10
+ import "../chunk-VVMRZEIW.js";
8
11
  import "../chunk-4MGIQFAJ.js";
9
12
  export {
10
13
  applyNestKitDefaults
@@ -1,6 +1,9 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
2
 
3
- var _chunkZA56XBCKcjs = require('./chunk-ZA56XBCK.cjs');
3
+ var _chunkY72D5L6Icjs = require('./chunk-Y72D5L6I.cjs');
4
+
5
+
6
+ var _chunkSDWHKPXIcjs = require('./chunk-SDWHKPXI.cjs');
4
7
 
5
8
 
6
9
  var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
@@ -11,12 +14,14 @@ var _operators = require('rxjs/operators');
11
14
  var ResponseInterceptor = class {
12
15
  intercept(_context, next) {
13
16
  return next.handle().pipe(
14
- _operators.map.call(void 0, (data) => ({
15
- success: true,
16
- data,
17
- requestId: _nullishCoalesce(_chunkZA56XBCKcjs.RequestContext.getRequestId(), () => ( "unknown")),
18
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
19
- }))
17
+ _operators.map.call(void 0, (data) => {
18
+ const envelope = {
19
+ success: true,
20
+ requestId: _nullishCoalesce(_chunkSDWHKPXIcjs.RequestContext.getRequestId(), () => ( "unknown")),
21
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
22
+ };
23
+ return _chunkY72D5L6Icjs.isPaginated.call(void 0, data) ? { ...envelope, data: data.items, meta: data.meta } : { ...envelope, data };
24
+ })
20
25
  );
21
26
  }
22
27
  };
@@ -1,6 +1,9 @@
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(); } } 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
- var _chunkFDNGAYTZcjs = require('./chunk-FDNGAYTZ.cjs');
3
+ var _chunkSDWHKPXIcjs = require('./chunk-SDWHKPXI.cjs');
4
+
5
+
6
+ var _chunkHDFPSA2Vcjs = require('./chunk-HDFPSA2V.cjs');
4
7
 
5
8
 
6
9
  var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
@@ -29,14 +32,14 @@ var TokenService = class {
29
32
  try {
30
33
  return _jsonwebtoken2.default.verify(token, requireEnv("JWT_ACCESS_SECRET"));
31
34
  } catch (e) {
32
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid or expired access token");
35
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid or expired access token");
33
36
  }
34
37
  }
35
38
  verifyRefreshToken(token) {
36
39
  try {
37
40
  return _jsonwebtoken2.default.verify(token, requireEnv("JWT_REFRESH_SECRET"));
38
41
  } catch (e2) {
39
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid or expired refresh token");
42
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid or expired refresh token");
40
43
  }
41
44
  }
42
45
  };
@@ -52,9 +55,11 @@ var JwtAuthGuard = class {
52
55
  const header = req.headers.authorization;
53
56
  const token = _optionalChain([header, 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3("Bearer ")]) ? header.slice("Bearer ".length) : void 0;
54
57
  if (!token) {
55
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Missing Authorization bearer token");
58
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Missing Authorization bearer token");
56
59
  }
57
- req.user = this.tokens.verifyAccessToken(token);
60
+ const user = this.tokens.verifyAccessToken(token);
61
+ req.user = user;
62
+ _chunkSDWHKPXIcjs.RequestContext.setActor({ id: user.sub, tenantId: user.tenantId, roles: user.roles });
58
63
  return true;
59
64
  }
60
65
  };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  RequestContext
3
- } from "./chunk-EBO6UKHL.js";
3
+ } from "./chunk-ETRUVZTJ.js";
4
4
  import {
5
5
  __decorateClass
6
6
  } from "./chunk-4MGIQFAJ.js";