@miguelmorales13/nestkit 0.16.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 (79) hide show
  1. package/README.md +152 -28
  2. package/dist/audit/index.cjs +12 -12
  3. package/dist/audit/index.js +2 -2
  4. package/dist/auth/index.cjs +12 -11
  5. package/dist/auth/index.js +5 -4
  6. package/dist/auth/oauth/http.d.ts +10 -3
  7. package/dist/auth/oauth/index.cjs +189 -30
  8. package/dist/auth/oauth/index.d.ts +6 -4
  9. package/dist/auth/oauth/index.js +169 -10
  10. package/dist/auth/oauth/magic-link.dto.d.ts +6 -0
  11. package/dist/auth/oauth/memory-magic-link.store.d.ts +19 -0
  12. package/dist/auth/oauth/oauth-auth.service.d.ts +46 -5
  13. package/dist/auth/oauth/oauth.controller.d.ts +5 -1
  14. package/dist/auth/oauth/oauth.options.d.ts +34 -1
  15. package/dist/auth/oauth/oauth.ports.d.ts +38 -0
  16. package/dist/bootstrap/index.cjs +8 -6
  17. package/dist/bootstrap/index.js +7 -5
  18. package/dist/{chunk-UWDHAZVE.cjs → chunk-3AUOOEQO.cjs} +2 -2
  19. package/dist/{chunk-C5DV4RAX.cjs → chunk-4HHZFOVC.cjs} +6 -6
  20. package/dist/{chunk-JV4EAOF2.js → chunk-4PFAKLT3.js} +1 -1
  21. package/dist/{chunk-47FXU74G.cjs → chunk-52IOOHNX.cjs} +2 -2
  22. package/dist/chunk-6RAPVLJM.js +212 -0
  23. package/dist/{chunk-KRC47OX6.js → chunk-A2DGK4ZL.js} +26 -3
  24. package/dist/chunk-APUFKA4K.cjs +212 -0
  25. package/dist/chunk-AXMW5JF7.cjs +83 -0
  26. package/dist/{chunk-DABTRWA6.js → chunk-DYHSOULW.js} +1 -1
  27. package/dist/{chunk-KP2ZHJSR.js → chunk-ETRUVZTJ.js} +8 -0
  28. package/dist/{chunk-4GT66KQS.cjs → chunk-FNUZGYUF.cjs} +4 -4
  29. package/dist/{chunk-FDNGAYTZ.cjs → chunk-HDFPSA2V.cjs} +6 -6
  30. package/dist/{chunk-U7QK24HL.cjs → chunk-HVHYZXBB.cjs} +2 -2
  31. package/dist/{chunk-LK3OINS7.js → chunk-IFNYRZP2.js} +1 -1
  32. package/dist/{chunk-MLOQDUBN.js → chunk-IKXSVEJ7.js} +2 -2
  33. package/dist/{chunk-YFYHLYHN.js → chunk-M3GQDRWR.js} +7 -1
  34. package/dist/{chunk-67B7IYAV.cjs → chunk-MSTXS3MU.cjs} +28 -5
  35. package/dist/chunk-PNK5WMPP.cjs +30 -0
  36. package/dist/chunk-Q5Y33L7B.cjs +19 -0
  37. package/dist/{chunk-EBPEMVZU.cjs → chunk-SDWHKPXI.cjs} +8 -0
  38. package/dist/{chunk-UIVBPNH4.js → chunk-UNEVXCFW.js} +4 -4
  39. package/dist/chunk-VVMRZEIW.js +30 -0
  40. package/dist/{chunk-XX5ROVSC.cjs → chunk-W2T2VFLC.cjs} +3 -3
  41. package/dist/chunk-X4PQJZ4G.js +83 -0
  42. package/dist/{chunk-ORWJ7LES.js → chunk-ZFIDAX7K.js} +1 -1
  43. package/dist/{chunk-XHW4CTBS.js → chunk-ZJMLEP5H.js} +1 -1
  44. package/dist/crud/index.cjs +4 -4
  45. package/dist/crud/index.js +3 -3
  46. package/dist/errors/app.exception.d.ts +9 -1
  47. package/dist/errors/common.exceptions.d.ts +6 -5
  48. package/dist/errors/global-exception.filter.d.ts +9 -0
  49. package/dist/errors/index.cjs +8 -5
  50. package/dist/errors/index.js +7 -4
  51. package/dist/i18n/i18n.interceptor.d.ts +16 -0
  52. package/dist/i18n/i18n.module.d.ts +49 -3
  53. package/dist/i18n/index.cjs +26 -2
  54. package/dist/i18n/index.d.ts +8 -0
  55. package/dist/i18n/index.js +25 -1
  56. package/dist/i18n/locale.d.ts +53 -0
  57. package/dist/i18n/message.d.ts +36 -0
  58. package/dist/i18n/nestjs-i18n.translator.d.ts +9 -0
  59. package/dist/i18n/runtime.d.ts +55 -0
  60. package/dist/i18n/translator.port.d.ts +29 -0
  61. package/dist/idempotency/index.cjs +6 -5
  62. package/dist/idempotency/index.js +3 -2
  63. package/dist/index.cjs +36 -14
  64. package/dist/index.js +41 -19
  65. package/dist/invoicing/index.cjs +14 -13
  66. package/dist/invoicing/index.js +3 -2
  67. package/dist/payments/index.cjs +15 -14
  68. package/dist/payments/index.js +3 -2
  69. package/dist/response/index.cjs +3 -3
  70. package/dist/response/index.js +2 -2
  71. package/dist/stripe/index.cjs +4 -3
  72. package/dist/stripe/index.js +3 -2
  73. package/dist/tracking/index.cjs +3 -3
  74. package/dist/tracking/index.js +2 -2
  75. package/dist/tracking/request-context.d.ts +10 -0
  76. package/package.json +1 -1
  77. package/dist/chunk-IYUUYCP5.js +0 -36
  78. package/dist/chunk-M3EL5O6T.cjs +0 -36
  79. package/dist/chunk-R7BVS6CI.cjs +0 -13
@@ -1,13 +1,14 @@
1
1
  import {
2
2
  CurrentUser,
3
3
  JwtAuthGuard
4
- } from "../../chunk-MLOQDUBN.js";
5
- import "../../chunk-KP2ZHJSR.js";
4
+ } from "../../chunk-IKXSVEJ7.js";
5
+ import "../../chunk-ETRUVZTJ.js";
6
6
  import {
7
7
  UnauthorizedAppException,
8
8
  ValidationAppException
9
- } from "../../chunk-ORWJ7LES.js";
10
- import "../../chunk-YFYHLYHN.js";
9
+ } from "../../chunk-ZFIDAX7K.js";
10
+ import "../../chunk-M3GQDRWR.js";
11
+ import "../../chunk-VVMRZEIW.js";
11
12
  import {
12
13
  __decorateClass,
13
14
  __decorateParam
@@ -127,6 +128,8 @@ async function exchangeCodeForToken(provider, code) {
127
128
  var OAUTH_AUTH_OPTIONS = /* @__PURE__ */ Symbol("OAUTH_AUTH_OPTIONS");
128
129
  var OAUTH_STORE = /* @__PURE__ */ Symbol("OAUTH_STORE");
129
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");
130
133
  function resolveOAuthOptions(options) {
131
134
  const webUrl = options.webUrl.replace(/\/$/, "");
132
135
  return {
@@ -141,6 +144,12 @@ function resolveOAuthOptions(options) {
141
144
  sameSite: options.cookie?.sameSite ?? "lax",
142
145
  secure: options.cookie?.secure ?? process.env.NODE_ENV === "production"
143
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
+ },
144
153
  linkCookieName: options.linkCookieName ?? "link_intent",
145
154
  stateCookieName: options.stateCookieName ?? "oauth_state",
146
155
  accessTtlSeconds: options.accessTtlSeconds ?? 15 * 60,
@@ -159,9 +168,10 @@ function resolveOAuthOptions(options) {
159
168
  }
160
169
 
161
170
  // src/auth/oauth/oauth-auth.service.ts
162
- import { Inject, Injectable, ServiceUnavailableException } from "@nestjs/common";
163
- import { createHash, randomUUID, timingSafeEqual } from "crypto";
171
+ import { Inject, Injectable, Optional, ServiceUnavailableException } from "@nestjs/common";
172
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "crypto";
164
173
  import jwt from "jsonwebtoken";
174
+ var MAGIC_LINK_PROVIDER = "email";
165
175
  function hashToken(token) {
166
176
  return createHash("sha256").update(token).digest("hex");
167
177
  }
@@ -171,9 +181,11 @@ function requireSecret(explicit, envName) {
171
181
  return value;
172
182
  }
173
183
  var OAuthAuthService = class {
174
- constructor(options, store, sessions) {
184
+ constructor(options, store, sessions, magicLinks, magicLinkSender) {
175
185
  this.store = store;
176
186
  this.sessions = sessions;
187
+ this.magicLinks = magicLinks;
188
+ this.magicLinkSender = magicLinkSender;
177
189
  this.options = resolveOAuthOptions(options);
178
190
  }
179
191
  get config() {
@@ -296,6 +308,69 @@ var OAuthAuthService = class {
296
308
  if (changes && (changes.name !== user.name || changes.avatarUrl !== user.avatarUrl)) {
297
309
  user = await this.store.updateUser(user.id, changes);
298
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) {
299
374
  if (this.options.singleSession) {
300
375
  await this.sessions.revokeAllForUser(user.id);
301
376
  }
@@ -452,12 +527,51 @@ OAuthAuthService = __decorateClass([
452
527
  Injectable(),
453
528
  __decorateParam(0, Inject(OAUTH_AUTH_OPTIONS)),
454
529
  __decorateParam(1, Inject(OAUTH_STORE)),
455
- __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))
456
535
  ], OAuthAuthService);
457
536
  function normaliseEmail(email) {
458
537
  return email.trim().toLowerCase();
459
538
  }
460
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
+
461
575
  // src/auth/oauth/oauth-callback.filter.ts
462
576
  import {
463
577
  Catch,
@@ -476,7 +590,9 @@ function clearCookie(reply, name, options) {
476
590
  reply.clearCookie?.(name, options);
477
591
  }
478
592
  function redirect(reply, url) {
479
- 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);
480
596
  }
481
597
 
482
598
  // src/auth/oauth/oauth-callback.filter.ts
@@ -501,8 +617,10 @@ OAuthCallbackFilter = __decorateClass([
501
617
 
502
618
  // src/auth/oauth/oauth.controller.ts
503
619
  import {
620
+ Body,
504
621
  Controller,
505
622
  Get,
623
+ Inject as Inject3,
506
624
  Param,
507
625
  Post,
508
626
  Query,
@@ -515,6 +633,8 @@ function createOAuthController(options = {}) {
515
633
  const Guard = options.guard ?? JwtAuthGuard;
516
634
  const userId = options.userId ?? ((user) => user.sub);
517
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.
518
638
  constructor(auth) {
519
639
  this.auth = auth;
520
640
  }
@@ -545,6 +665,23 @@ function createOAuthController(options = {}) {
545
665
  });
546
666
  return { ok: true };
547
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
+ }
548
685
  start(provider, reply) {
549
686
  const { url, state, expiresAt } = this.auth.authorizeUrl(provider);
550
687
  setCookie(reply, this.auth.config.stateCookieName, state, {
@@ -619,6 +756,21 @@ function createOAuthController(options = {}) {
619
756
  __decorateParam(0, CurrentUser()),
620
757
  __decorateParam(1, Res({ passthrough: true }))
621
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);
622
774
  __decorateClass([
623
775
  Get(":provider"),
624
776
  __decorateParam(0, Param("provider")),
@@ -634,7 +786,8 @@ function createOAuthController(options = {}) {
634
786
  __decorateParam(4, Res())
635
787
  ], OAuthControllerHost.prototype, "callback", 1);
636
788
  OAuthControllerHost = __decorateClass([
637
- Controller(options.path ?? "auth")
789
+ Controller(options.path ?? "auth"),
790
+ __decorateParam(0, Inject3(OAuthAuthService))
638
791
  ], OAuthControllerHost);
639
792
  return OAuthControllerHost;
640
793
  }
@@ -663,6 +816,12 @@ OAuthAuthModule = __decorateClass([
663
816
  Module({})
664
817
  ], OAuthAuthModule);
665
818
  export {
819
+ MAGIC_LINK_PROVIDER,
820
+ MAGIC_LINK_SENDER,
821
+ MAGIC_LINK_STORE,
822
+ MagicLinkRequestDto,
823
+ MagicLinkVerifyDto,
824
+ MemoryMagicLinkStore,
666
825
  OAUTH_AUTH_OPTIONS,
667
826
  OAUTH_STORE,
668
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,12 +1,14 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunk4GT66KQScjs = require('../chunk-4GT66KQS.cjs');
4
- require('../chunk-67B7IYAV.cjs');
5
- require('../chunk-UWDHAZVE.cjs');
3
+ var _chunkFNUZGYUFcjs = require('../chunk-FNUZGYUF.cjs');
4
+ require('../chunk-3AUOOEQO.cjs');
5
+ require('../chunk-MSTXS3MU.cjs');
6
+ require('../chunk-AXMW5JF7.cjs');
6
7
  require('../chunk-Y72D5L6I.cjs');
7
- require('../chunk-EBPEMVZU.cjs');
8
- require('../chunk-R7BVS6CI.cjs');
8
+ require('../chunk-SDWHKPXI.cjs');
9
+ require('../chunk-Q5Y33L7B.cjs');
10
+ require('../chunk-PNK5WMPP.cjs');
9
11
  require('../chunk-2REOCMUD.cjs');
10
12
 
11
13
 
12
- exports.applyNestKitDefaults = _chunk4GT66KQScjs.applyNestKitDefaults;
14
+ exports.applyNestKitDefaults = _chunkFNUZGYUFcjs.applyNestKitDefaults;
@@ -1,11 +1,13 @@
1
1
  import {
2
2
  applyNestKitDefaults
3
- } from "../chunk-UIVBPNH4.js";
4
- import "../chunk-KRC47OX6.js";
5
- import "../chunk-DABTRWA6.js";
3
+ } from "../chunk-UNEVXCFW.js";
4
+ import "../chunk-DYHSOULW.js";
5
+ import "../chunk-A2DGK4ZL.js";
6
+ import "../chunk-X4PQJZ4G.js";
6
7
  import "../chunk-TCAMLNUZ.js";
7
- import "../chunk-KP2ZHJSR.js";
8
- import "../chunk-YFYHLYHN.js";
8
+ import "../chunk-ETRUVZTJ.js";
9
+ import "../chunk-M3GQDRWR.js";
10
+ import "../chunk-VVMRZEIW.js";
9
11
  import "../chunk-4MGIQFAJ.js";
10
12
  export {
11
13
  applyNestKitDefaults
@@ -3,7 +3,7 @@
3
3
  var _chunkY72D5L6Icjs = require('./chunk-Y72D5L6I.cjs');
4
4
 
5
5
 
6
- var _chunkEBPEMVZUcjs = require('./chunk-EBPEMVZU.cjs');
6
+ var _chunkSDWHKPXIcjs = require('./chunk-SDWHKPXI.cjs');
7
7
 
8
8
 
9
9
  var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
@@ -17,7 +17,7 @@ var ResponseInterceptor = class {
17
17
  _operators.map.call(void 0, (data) => {
18
18
  const envelope = {
19
19
  success: true,
20
- requestId: _nullishCoalesce(_chunkEBPEMVZUcjs.RequestContext.getRequestId(), () => ( "unknown")),
20
+ requestId: _nullishCoalesce(_chunkSDWHKPXIcjs.RequestContext.getRequestId(), () => ( "unknown")),
21
21
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
22
22
  };
23
23
  return _chunkY72D5L6Icjs.isPaginated.call(void 0, data) ? { ...envelope, data: data.items, meta: data.meta } : { ...envelope, data };
@@ -1,9 +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 _chunkEBPEMVZUcjs = require('./chunk-EBPEMVZU.cjs');
3
+ var _chunkSDWHKPXIcjs = require('./chunk-SDWHKPXI.cjs');
4
4
 
5
5
 
6
- var _chunkFDNGAYTZcjs = require('./chunk-FDNGAYTZ.cjs');
6
+ var _chunkHDFPSA2Vcjs = require('./chunk-HDFPSA2V.cjs');
7
7
 
8
8
 
9
9
  var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
@@ -32,14 +32,14 @@ var TokenService = class {
32
32
  try {
33
33
  return _jsonwebtoken2.default.verify(token, requireEnv("JWT_ACCESS_SECRET"));
34
34
  } catch (e) {
35
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid or expired access token");
35
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid or expired access token");
36
36
  }
37
37
  }
38
38
  verifyRefreshToken(token) {
39
39
  try {
40
40
  return _jsonwebtoken2.default.verify(token, requireEnv("JWT_REFRESH_SECRET"));
41
41
  } catch (e2) {
42
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Invalid or expired refresh token");
42
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Invalid or expired refresh token");
43
43
  }
44
44
  }
45
45
  };
@@ -55,11 +55,11 @@ var JwtAuthGuard = class {
55
55
  const header = req.headers.authorization;
56
56
  const token = _optionalChain([header, 'optionalAccess', _2 => _2.startsWith, 'call', _3 => _3("Bearer ")]) ? header.slice("Bearer ".length) : void 0;
57
57
  if (!token) {
58
- throw new (0, _chunkFDNGAYTZcjs.UnauthorizedAppException)("Missing Authorization bearer token");
58
+ throw new (0, _chunkHDFPSA2Vcjs.UnauthorizedAppException)("Missing Authorization bearer token");
59
59
  }
60
60
  const user = this.tokens.verifyAccessToken(token);
61
61
  req.user = user;
62
- _chunkEBPEMVZUcjs.RequestContext.setActor({ id: user.sub, tenantId: user.tenantId, roles: user.roles });
62
+ _chunkSDWHKPXIcjs.RequestContext.setActor({ id: user.sub, tenantId: user.tenantId, roles: user.roles });
63
63
  return true;
64
64
  }
65
65
  };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  RequestContext
3
- } from "./chunk-KP2ZHJSR.js";
3
+ } from "./chunk-ETRUVZTJ.js";
4
4
  import {
5
5
  __decorateClass
6
6
  } from "./chunk-4MGIQFAJ.js";
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); 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
- var _chunkXX5ROVSCcjs = require('./chunk-XX5ROVSC.cjs');
3
+ var _chunkW2T2VFLCcjs = require('./chunk-W2T2VFLC.cjs');
4
4
 
5
5
 
6
6
 
@@ -117,7 +117,7 @@ var BaseCrudService = class {
117
117
  const audit = this.options.audit;
118
118
  if (!audit) return;
119
119
  await audit.recorder.record(
120
- _chunkXX5ROVSCcjs.withRequestContext.call(void 0, {
120
+ _chunkW2T2VFLCcjs.withRequestContext.call(void 0, {
121
121
  action,
122
122
  resource: audit.resource,
123
123
  resourceId,