@lenne.tech/nest-server 12.10.1 → 12.11.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 (108) hide show
  1. package/.claude/rules/better-auth.md +19 -0
  2. package/.claude/rules/configurable-features.md +11 -9
  3. package/.claude/rules/package-management.md +1 -1
  4. package/.claude/rules/role-system.md +4 -1
  5. package/.claude/rules/testing.md +4 -4
  6. package/CLAUDE.md +5 -0
  7. package/FRAMEWORK-API.md +2 -1
  8. package/dist/core/common/decorators/unified-field.decorator.js +5 -2
  9. package/dist/core/common/decorators/unified-field.decorator.js.map +1 -1
  10. package/dist/core/common/helpers/config.helper.js +31 -9
  11. package/dist/core/common/helpers/config.helper.js.map +1 -1
  12. package/dist/core/common/helpers/graceful-shutdown.helper.js +3 -1
  13. package/dist/core/common/helpers/graceful-shutdown.helper.js.map +1 -1
  14. package/dist/core/common/helpers/graphql-ws-connection.helper.d.ts +8 -3
  15. package/dist/core/common/helpers/graphql-ws-connection.helper.js +44 -0
  16. package/dist/core/common/helpers/graphql-ws-connection.helper.js.map +1 -1
  17. package/dist/core/common/helpers/http-stream-auth.helper.d.ts +13 -0
  18. package/dist/core/common/helpers/http-stream-auth.helper.js +90 -0
  19. package/dist/core/common/helpers/http-stream-auth.helper.js.map +1 -0
  20. package/dist/core/common/helpers/shutdown-state.helper.d.ts +3 -0
  21. package/dist/core/common/helpers/shutdown-state.helper.js +11 -0
  22. package/dist/core/common/helpers/shutdown-state.helper.js.map +1 -0
  23. package/dist/core/common/interfaces/cron-job-config-with-utc-offset.interface.d.ts +1 -1
  24. package/dist/core/common/interfaces/cron-job-config.interface.d.ts +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +14 -0
  26. package/dist/core/common/services/core-cron-jobs.service.d.ts +13 -0
  27. package/dist/core/common/services/core-cron-jobs.service.js +129 -4
  28. package/dist/core/common/services/core-cron-jobs.service.js.map +1 -1
  29. package/dist/core/modules/better-auth/better-auth.config.js +48 -4
  30. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.d.ts +8 -0
  32. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js +47 -0
  33. package/dist/core/modules/better-auth/core-better-auth-jwt-session.cache.js.map +1 -0
  34. package/dist/core/modules/better-auth/core-better-auth-models.d.ts +1 -0
  35. package/dist/core/modules/better-auth/core-better-auth-models.js +7 -0
  36. package/dist/core/modules/better-auth/core-better-auth-models.js.map +1 -1
  37. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.d.ts +11 -0
  38. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js +62 -0
  39. package/dist/core/modules/better-auth/core-better-auth-sign-in-factors.helper.js.map +1 -0
  40. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +1 -0
  41. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +28 -1
  42. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  43. package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -1
  44. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  45. package/dist/core/modules/better-auth/core-better-auth.middleware.js +2 -2
  46. package/dist/core/modules/better-auth/core-better-auth.middleware.js.map +1 -1
  47. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -0
  48. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  49. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +10 -0
  50. package/dist/core/modules/better-auth/core-better-auth.service.js +105 -19
  51. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  52. package/dist/core/modules/health-check/core-health-check-readiness.controller.d.ts +6 -0
  53. package/dist/core/modules/health-check/core-health-check-readiness.controller.js +36 -0
  54. package/dist/core/modules/health-check/core-health-check-readiness.controller.js.map +1 -0
  55. package/dist/core/modules/health-check/core-health-check.helpers.d.ts +10 -0
  56. package/dist/core/modules/health-check/core-health-check.helpers.js +31 -0
  57. package/dist/core/modules/health-check/core-health-check.helpers.js.map +1 -0
  58. package/dist/core/modules/health-check/core-health-check.module.d.ts +9 -0
  59. package/dist/core/modules/health-check/core-health-check.module.js +13 -2
  60. package/dist/core/modules/health-check/core-health-check.module.js.map +1 -1
  61. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -1
  62. package/dist/core/modules/health-check/core-health-check.service.js +66 -29
  63. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  64. package/dist/core/modules/sync/core-sync.service.d.ts +2 -0
  65. package/dist/core/modules/sync/core-sync.service.js +11 -1
  66. package/dist/core/modules/sync/core-sync.service.js.map +1 -1
  67. package/dist/core.module.js +5 -1
  68. package/dist/core.module.js.map +1 -1
  69. package/dist/index.d.ts +4 -0
  70. package/dist/index.js +4 -0
  71. package/dist/index.js.map +1 -1
  72. package/dist/main.js.map +1 -1
  73. package/docs/REQUEST-LIFECYCLE.md +4 -4
  74. package/docs/offline-sync-protocol.md +5 -3
  75. package/migration-guides/12.10.x-to-12.11.x.md +295 -0
  76. package/package.json +17 -17
  77. package/src/core/common/decorators/unified-field.decorator.ts +14 -4
  78. package/src/core/common/helpers/config.helper.ts +55 -8
  79. package/src/core/common/helpers/graceful-shutdown.helper.ts +10 -3
  80. package/src/core/common/helpers/graphql-ws-connection.helper.ts +99 -4
  81. package/src/core/common/helpers/http-stream-auth.helper.ts +197 -0
  82. package/src/core/common/helpers/shutdown-state.helper.ts +28 -0
  83. package/src/core/common/interfaces/cron-job-config-with-utc-offset.interface.ts +1 -1
  84. package/src/core/common/interfaces/cron-job-config.interface.ts +1 -1
  85. package/src/core/common/interfaces/server-options.interface.ts +113 -1
  86. package/src/core/common/services/core-cron-jobs.service.ts +241 -14
  87. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +26 -10
  88. package/src/core/modules/better-auth/README.md +37 -8
  89. package/src/core/modules/better-auth/better-auth.config.ts +83 -12
  90. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +1 -1
  91. package/src/core/modules/better-auth/core-better-auth-jwt-session.cache.ts +104 -0
  92. package/src/core/modules/better-auth/core-better-auth-models.ts +5 -0
  93. package/src/core/modules/better-auth/core-better-auth-sign-in-factors.helper.ts +105 -0
  94. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +37 -1
  95. package/src/core/modules/better-auth/core-better-auth.controller.ts +6 -3
  96. package/src/core/modules/better-auth/core-better-auth.middleware.ts +4 -3
  97. package/src/core/modules/better-auth/core-better-auth.module.ts +1 -1
  98. package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -0
  99. package/src/core/modules/better-auth/core-better-auth.service.ts +160 -27
  100. package/src/core/modules/health-check/core-health-check-readiness.controller.ts +27 -0
  101. package/src/core/modules/health-check/core-health-check.helpers.ts +65 -0
  102. package/src/core/modules/health-check/core-health-check.module.ts +37 -2
  103. package/src/core/modules/health-check/core-health-check.service.ts +154 -59
  104. package/src/core/modules/sync/README.md +18 -6
  105. package/src/core/modules/sync/core-sync.service.ts +35 -6
  106. package/src/core.module.ts +9 -1
  107. package/src/index.ts +4 -0
  108. package/src/main.ts +2 -1
@@ -1,6 +1,6 @@
1
1
  import { Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
2
2
  import { CronExpression, SchedulerRegistry } from '@nestjs/schedule';
3
- import { CronJob } from 'cron';
3
+ import { CronJob, CronTime } from 'cron';
4
4
 
5
5
  import { CronJobConfigWithTimeZone } from '../interfaces/cron-job-config-with-time-zone.interface.js';
6
6
  import { CronJobConfigWithUtcOffset } from '../interfaces/cron-job-config-with-utc-offset.interface.js';
@@ -98,6 +98,18 @@ export interface CoreCronJobsOptions {
98
98
  redisService?: CoreRedisService;
99
99
  }
100
100
 
101
+ /**
102
+ * A new schedule for {@link CoreCronJobs.rescheduleCronJob}: a cron expression or a date (the job keeps its time zone
103
+ * or UTC offset), or the schedule fields of a job config. Only the schedule changes — `distributed`, `runParallel`,
104
+ * `throwException` and the job function stay as configured.
105
+ */
106
+ export type CronJobSchedule =
107
+ | CronExpression
108
+ | Date
109
+ | Pick<CronJobConfigWithTimeZone, 'cronTime' | 'timeZone' | 'utcOffset'>
110
+ | Pick<CronJobConfigWithUtcOffset, 'cronTime' | 'timeZone' | 'utcOffset'>
111
+ | string;
112
+
101
113
  /**
102
114
  * Cron jobs service to extend
103
115
  *
@@ -108,6 +120,8 @@ export interface CoreCronJobsOptions {
108
120
  * - Otherwise: the local cron timer stays, but each tick first acquires a lease
109
121
  * (Redis `SET NX` when available, else the SQL lease table of the default source, else a `cron-locks` document in
110
122
  * MongoDB).
123
+ *
124
+ * A job's schedule can be changed at runtime with {@link CoreCronJobs.rescheduleCronJob} (12.11.0), in both modes.
111
125
  */
112
126
  export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicationShutdown {
113
127
  /**
@@ -159,6 +173,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
159
173
  /** Shared BullMQ worker, created only in BullMQ mode */
160
174
  protected bullWorker?: any;
161
175
 
176
+ /** Set when the application shuts down: no job is (re)scheduled after that */
177
+ protected cronJobsClosed = false;
178
+
162
179
  /** Whether the "deduplication inactive" warning was already emitted */
163
180
  protected dedupWarned = false;
164
181
 
@@ -183,6 +200,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
183
200
  void this.restoreBullSchedulers();
184
201
  };
185
202
 
203
+ /** The reschedule in progress; rescheduleCronJob() calls run one after the other */
204
+ protected rescheduling: Promise<void> = Promise.resolve();
205
+
186
206
  // ===================================================================================================================
187
207
  // Initializations
188
208
  // ===================================================================================================================
@@ -219,6 +239,9 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
219
239
  * Close the BullMQ worker and queue
220
240
  */
221
241
  async onApplicationShutdown(): Promise<void> {
242
+ this.cronJobsClosed = true;
243
+ // A reschedule already running finishes first; it never rejects here (rescheduleCronJob() reports to its caller)
244
+ await this.rescheduling;
222
245
  this.stopBullSchedulerCheck();
223
246
  // A check already running finishes its current job before the queue closes; it never rejects.
224
247
  await this.bullSchedulerCheck;
@@ -237,6 +260,221 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
237
260
  this.bullQueue = undefined;
238
261
  }
239
262
 
263
+ // ===================================================================================================================
264
+ // Runtime changes
265
+ // ===================================================================================================================
266
+
267
+ /**
268
+ * Change the schedule of a registered cron job at runtime (12.11.0) — for a schedule a project keeps in its own
269
+ * settings rather than in the `cronJobs` configuration.
270
+ *
271
+ * `schedule` is a cron expression or a date (the job keeps its time zone or UTC offset), or `{ cronTime, timeZone }` /
272
+ * `{ cronTime, utcOffset }`. It is validated before anything changes: an invalid expression, an unknown time zone or
273
+ * a date in the past rejects and leaves the job as it was. Only the schedule changes; `distributed`, `runParallel`
274
+ * and `throwException` stay as configured, and so do the leases, the running lease and the BullMQ job options.
275
+ *
276
+ * - Local timer: the timer is replaced. The next tick follows the new schedule, a distributed job takes its tick
277
+ * lease keyed on the new schedule's instant, a tick that is running finishes. A recurring job the Hub stopped on
278
+ * this replica stays stopped.
279
+ * - BullMQ job scheduler: the scheduler is written to Redis with the new pattern and `bullJobOptions` — skipped when
280
+ * Redis already holds exactly this pattern and time zone, so calling this on every replica plans no tick twice —
281
+ * and restoreBullSchedulers() brings the NEW schedule back after a data loss. A schedule BullMQ cannot express (a
282
+ * date, a UTC offset) moves the job to a local timer with lease: its scheduler is removed with the removal marker,
283
+ * so a replica that still schedules the job through BullMQ does not bring it back. A cron expression moves the job
284
+ * back to BullMQ.
285
+ *
286
+ * WHERE IT APPLIES: a BullMQ scheduler lives in Redis and changes for the whole fleet at once, a local timer only in
287
+ * this process. Call it on EVERY replica (from the settings change each replica observes, and at startup), or the
288
+ * replicas run the job on different schedules. A reschedule is not stored: the next bootstrap schedules the job from
289
+ * the configuration again, so a project re-applies a stored schedule after `super.onApplicationBootstrap()`.
290
+ *
291
+ * `runOnInit` is not repeated — a reschedule is not a start. Calls run one after the other. Rejects for a job that is
292
+ * not registered: unknown, disabled, without `cronTime` or job method, before bootstrap or after shutdown.
293
+ */
294
+ async rescheduleCronJob(name: string, schedule: CronJobSchedule): Promise<void> {
295
+ const run = this.rescheduling.then(() => this.applyCronJobSchedule(name, schedule));
296
+ this.rescheduling = run.catch(() => undefined);
297
+ return run;
298
+ }
299
+
300
+ /**
301
+ * Apply a new schedule to a registered job: validate it, then move the job to the mode the schedule needs — the same
302
+ * rule initCronJobs() applies (BullMQ for a distributed job with a cron expression and no UTC offset while BullMQ is
303
+ * active, a local timer otherwise). See rescheduleCronJob().
304
+ */
305
+ protected async applyCronJobSchedule(name: string, schedule: CronJobSchedule): Promise<void> {
306
+ const current = this.jobConfigs[name];
307
+ const scheduledWithBull = this.bullScheduledJobs.has(name);
308
+ if (this.cronJobsClosed || !current || (!scheduledWithBull && !this.schedulerRegistry.doesExist('cron', name))) {
309
+ throw new Error(`CronJob ${name} is not registered and cannot be rescheduled`);
310
+ }
311
+ const next = this.withSchedule(name, current, schedule);
312
+ // sendAt() refuses what has no next instant (a date in the past); the constructor an invalid expression or zone
313
+ new CronTime(next.cronTime as any, next.timeZone as any, next.utcOffset as any).sendAt();
314
+
315
+ // A scheduler check that runs finishes before the job changes under it
316
+ await this.bullSchedulerCheck;
317
+ const withBull = !!this.bullQueue && next.distributed !== false && this.canUseBullScheduler(next);
318
+ if (withBull) {
319
+ await this.rescheduleWithBull(name, next);
320
+ } else {
321
+ await this.rescheduleLocally(name, next, scheduledWithBull);
322
+ }
323
+
324
+ if (this.config.log) {
325
+ const cronTime = next.cronTime instanceof Date ? next.cronTime.toISOString() : String(next.cronTime);
326
+ cronLogger.log(`CronJob ${name} rescheduled to "${cronTime}" (${withBull ? 'BullMQ scheduler' : 'local timer'})`);
327
+ }
328
+ }
329
+
330
+ /** The job's config with the new schedule; a cron expression or date keeps the time zone or UTC offset */
331
+ protected withSchedule(
332
+ name: string,
333
+ current: CronJobConfigWithTimeZone,
334
+ schedule: CronJobSchedule,
335
+ ): CronJobConfigWithTimeZone {
336
+ if (typeof schedule === 'string' || schedule instanceof Date) {
337
+ return { ...current, cronTime: schedule };
338
+ }
339
+ if (!schedule || typeof schedule !== 'object' || !schedule.cronTime) {
340
+ throw new Error(`CronJob ${name} cannot be rescheduled without a cronTime`);
341
+ }
342
+ const next: Record<string, unknown> = { ...current, cronTime: schedule.cronTime };
343
+ if (schedule.utcOffset !== undefined && schedule.utcOffset !== null) {
344
+ // timeZone and utcOffset exclude each other, as in initCronJobs()
345
+ next.timeZone = null;
346
+ next.utcOffset = schedule.utcOffset;
347
+ } else if (schedule.timeZone) {
348
+ next.timeZone = schedule.timeZone;
349
+ next.utcOffset = undefined;
350
+ }
351
+ return next as unknown as CronJobConfigWithTimeZone;
352
+ }
353
+
354
+ /** Whether BullMQ can express a schedule: a cron expression without a UTC offset (BullMQ knows only time zones) */
355
+ protected canUseBullScheduler(config: CronJobConfigWithTimeZone): boolean {
356
+ return typeof config.cronTime === 'string' && !config.utcOffset;
357
+ }
358
+
359
+ /**
360
+ * Reschedule a job through its BullMQ scheduler — or move it there from a local timer. Redis is written first: when
361
+ * that fails, the job keeps running as it did and the call rejects.
362
+ */
363
+ protected async rescheduleWithBull(name: string, config: CronJobConfigWithTimeZone): Promise<void> {
364
+ const previous = this.jobConfigs[name];
365
+ // The schedule restoreBullSchedulers() brings back after a data loss
366
+ this.jobConfigs[name] = config;
367
+ try {
368
+ // The job runs through BullMQ again, so a removal marker an earlier schedule left no longer applies
369
+ const removedKey = this.bullSchedulerRemovedKey(name);
370
+ if (removedKey) {
371
+ await this.getRedisClient()?.del(removedKey);
372
+ }
373
+ if (!(await this.bullSchedulerMatches(name, config))) {
374
+ await this.upsertBullScheduler(name, config);
375
+ }
376
+ } catch (error) {
377
+ this.jobConfigs[name] = previous;
378
+ throw error;
379
+ }
380
+ this.bullScheduledJobs.add(name);
381
+ // The local timer the job ran on, or the stopped registry entry of its previous schedule
382
+ this.removeCronJobRegistryEntry(name);
383
+ this.schedulerRegistry.addCronJob(name, this.createBullRegistryEntry(name, config));
384
+ if (!this.bullSchedulerCheckTimer) {
385
+ this.startBullSchedulerCheck();
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Reschedule a job on a local timer — or move it there from its BullMQ scheduler, which is removed with the removal
391
+ * marker first: a replica that still schedules the job through BullMQ must not register it again.
392
+ */
393
+ protected async rescheduleLocally(
394
+ name: string,
395
+ config: CronJobConfigWithTimeZone,
396
+ scheduledWithBull: boolean,
397
+ ): Promise<void> {
398
+ if (scheduledWithBull) {
399
+ this.bullScheduledJobs.delete(name);
400
+ try {
401
+ await this.markBullSchedulerRemoved(name);
402
+ await this.bullQueue?.removeJobScheduler(name);
403
+ } catch (error) {
404
+ // The job stays with its scheduler; a marker written before the removal failed would hide a later data loss
405
+ this.bullScheduledJobs.add(name);
406
+ try {
407
+ const removedKey = this.bullSchedulerRemovedKey(name);
408
+ if (removedKey) {
409
+ await this.getRedisClient()?.del(removedKey);
410
+ }
411
+ } catch {
412
+ // Redis is not answering — the next registerBullJob() deletes the marker
413
+ }
414
+ throw error;
415
+ }
416
+ }
417
+ const previous = scheduledWithBull ? undefined : this.registeredCronJob(name);
418
+ // The Hub stopped a recurring job on this replica: the new timer stays stopped too (a one-shot date stops itself)
419
+ const keepStopped = !!previous && !previous.isActive && !previous.cronTime?.realDate;
420
+ this.removeCronJobRegistryEntry(name);
421
+ this.jobConfigs[name] = config;
422
+ // A reschedule is not a start: no runOnInit
423
+ this.registerLocalJob(name, { ...config, runOnInit: false }, config.distributed !== false);
424
+ if (keepStopped) {
425
+ void this.registeredCronJob(name)?.stop();
426
+ }
427
+ }
428
+
429
+ /**
430
+ * Whether Redis already holds this job's scheduler with exactly this pattern and time zone. An upsert is not free —
431
+ * BullMQ drops the tick the scheduler planned last and plans from now — so an unchanged schedule is not written again.
432
+ * A listing that fails answers `false`: the schedule is then written.
433
+ */
434
+ protected async bullSchedulerMatches(name: string, config: CronJobConfigWithTimeZone): Promise<boolean> {
435
+ try {
436
+ const listed: { key?: string; pattern?: string; tz?: null | string }[] = await this.bullQueue.getJobSchedulers();
437
+ const scheduler = listed.find((entry) => entry?.key === name);
438
+ return (
439
+ !!scheduler &&
440
+ scheduler.pattern === config.cronTime &&
441
+ (scheduler.tz ?? undefined) === (config.timeZone ?? undefined)
442
+ );
443
+ } catch {
444
+ return false;
445
+ }
446
+ }
447
+
448
+ /**
449
+ * The STOPPED CronJob that stands for a BullMQ-scheduled job in the SchedulerRegistry — see registerBullJob(). It never
450
+ * fires on its own; the Hub reads its schedule, and a manual trigger runs the leased tick.
451
+ */
452
+ protected createBullRegistryEntry(name: string, config: CronJobConfigWithTimeZone): CronJob {
453
+ return new CronJob(
454
+ config.cronTime,
455
+ () => this.runInitTick(name),
456
+ null,
457
+ false,
458
+ config.timeZone,
459
+ config.context,
460
+ false,
461
+ config.utcOffset,
462
+ config.unrefTimeout,
463
+ );
464
+ }
465
+
466
+ /** The job's CronJob in the SchedulerRegistry, if it has one */
467
+ protected registeredCronJob(name: string): CronJob | undefined {
468
+ return this.schedulerRegistry.doesExist('cron', name) ? this.schedulerRegistry.getCronJob(name) : undefined;
469
+ }
470
+
471
+ /** Stop the job's CronJob and take it out of the SchedulerRegistry (deleteCronJob() stops it) */
472
+ protected removeCronJobRegistryEntry(name: string): void {
473
+ if (this.schedulerRegistry.doesExist('cron', name)) {
474
+ this.schedulerRegistry.deleteCronJob(name);
475
+ }
476
+ }
477
+
240
478
  /**
241
479
  * Init cron jobs
242
480
  */
@@ -308,7 +546,7 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
308
546
 
309
547
  // Init cron job as BullMQ job scheduler, when possible
310
548
  if (bullMqActive && distributed) {
311
- if (typeof config.cronTime === 'string' && !config.utcOffset) {
549
+ if (this.canUseBullScheduler(config)) {
312
550
  await this.registerBullJob(name, config);
313
551
  this.bullScheduledJobs.add(name);
314
552
  continue;
@@ -815,18 +1053,7 @@ export abstract class CoreCronJobs implements OnApplicationBootstrap, OnApplicat
815
1053
  // the BullMQ scheduler owns the schedule — while `nextDate()`/`lastDate()` still answer for
816
1054
  // the panel, and a manual trigger goes through the same leased tick as everywhere else.
817
1055
  if (!this.schedulerRegistry.doesExist('cron', name)) {
818
- const registryJob = new CronJob(
819
- config.cronTime,
820
- () => this.runInitTick(name),
821
- null,
822
- false,
823
- config.timeZone,
824
- config.context,
825
- false,
826
- config.utcOffset,
827
- config.unrefTimeout,
828
- );
829
- this.schedulerRegistry.addCronJob(name, registryJob);
1056
+ this.schedulerRegistry.addCronJob(name, this.createBullRegistryEntry(name, config));
830
1057
  }
831
1058
 
832
1059
  if (this.config.log) {
@@ -470,6 +470,20 @@ After integration, verify:
470
470
  `302` to `<appUrl>/auth/login?error=state_not_found`, not the API's "Error" page (`betterAuth.errorUrl`)
471
471
  - [ ] The login page shows a text of its own for each `error` code and never renders `error_description`
472
472
 
473
+ ### Optional: Sign-in through a provider alone (`emailAndPassword.enabled: false`, no plugin sign-in route, 12.11.0+)
474
+
475
+ The provider decides who gets in, so nothing of the framework's own may keep someone in after it withdrew the
476
+ assignment (README → "Sign-in through a provider alone"):
477
+
478
+ - [ ] `GET /iam/features` answers `emailAndPassword: false`, `passkey: false`, `twoFactor: false`; the login page hides
479
+ the e-mail form on `emailAndPassword: false`
480
+ - [ ] `POST /iam/passkey/verify-authentication` answers `404` — unless the project switched Passkey on deliberately
481
+ with `passkey: true`
482
+ - [ ] `POST /iam/sign-in/social` with `{ "provider": "microsoft", "idToken": { "token": "…" } }` answers
483
+ `ID_TOKEN_NOT_SUPPORTED` (only a native app or Google One Tap sets `disableIdTokenSignIn: false`)
484
+ - [ ] After `POST /iam/sign-out` the JWT of that session answers `401` at once
485
+ - [ ] Where a withdrawal must take effect within a fixed time: `session: { expiresInHours: <n>, extendOnUse: false }`
486
+
473
487
  ### Additional checks for Migration scenario:
474
488
 
475
489
  - [ ] Sign-in via Legacy Auth works for BetterAuth-created users
@@ -480,16 +494,18 @@ After integration, verify:
480
494
 
481
495
  ## Common Mistakes
482
496
 
483
- | Mistake | Symptom | Fix |
484
- | ------------------------------------------------------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
485
- | Forgot to re-declare decorators in Resolver | GraphQL endpoints missing (404) | Copy resolver from reference, keep ALL decorators |
486
- | Forgot `CoreBetterAuthUserMapper` in UserService | Auth systems not synced, users can't cross-authenticate | Add `@Optional()` parameter and pass to super() |
487
- | Missing `fallbackSecrets` in ServerModule | Session issues without explicit secret | Add `fallbackSecrets: [envConfig.jwt?.secret, ...]` |
488
- | Wrong `basePath` in config | 404 on BetterAuth endpoints | Ensure basePath matches controller (default: `/iam`) |
489
- | Using wrong CoreModule signature | Build errors or missing features | New projects: 1-parameter, Existing: 3-parameter |
490
- | AuthResolver override missing `checkLegacyGraphQLEnabled()` | Legacy endpoint disabling doesn't work (no HTTP 410) | Call `this.checkLegacyGraphQLEnabled('signIn')` in overrides |
491
- | Missing `signUpValidator` in custom Resolver (v11.13.0+) | Sign-up validation not working | Add `@Optional() signUpValidator?: CoreBetterAuthSignUpValidatorService` to constructor and pass to `super()` |
492
- | Missing `termsAndPrivacyAccepted` parameter in Resolver (v11.13.0+) | GraphQL error "Unknown argument" | Add `@Args('termsAndPrivacyAccepted', { nullable: true })` to `betterAuthSignUp` method |
497
+ | Mistake | Symptom | Fix |
498
+ | ----------------------------------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
499
+ | Forgot to re-declare decorators in Resolver | GraphQL endpoints missing (404) | Copy resolver from reference, keep ALL decorators |
500
+ | Forgot `CoreBetterAuthUserMapper` in UserService | Auth systems not synced, users can't cross-authenticate | Add `@Optional()` parameter and pass to super() |
501
+ | Missing `fallbackSecrets` in ServerModule | Session issues without explicit secret | Add `fallbackSecrets: [envConfig.jwt?.secret, ...]` |
502
+ | Wrong `basePath` in config | 404 on BetterAuth endpoints | Ensure basePath matches controller (default: `/iam`) |
503
+ | Using wrong CoreModule signature | Build errors or missing features | New projects: 1-parameter, Existing: 3-parameter |
504
+ | AuthResolver override missing `checkLegacyGraphQLEnabled()` | Legacy endpoint disabling doesn't work (no HTTP 410) | Call `this.checkLegacyGraphQLEnabled('signIn')` in overrides |
505
+ | Missing `signUpValidator` in custom Resolver (v11.13.0+) | Sign-up validation not working | Add `@Optional() signUpValidator?: CoreBetterAuthSignUpValidatorService` to constructor and pass to `super()` |
506
+ | Missing `termsAndPrivacyAccepted` parameter in Resolver (v11.13.0+) | GraphQL error "Unknown argument" | Add `@Args('termsAndPrivacyAccepted', { nullable: true })` to `betterAuthSignUp` method |
507
+ | A JWT client keeps the JWT it had before `verify-totp` while enabling 2FA (12.11.0+) | `401` right after 2FA was switched on | Use the `token` of the `verify-totp` answer: the first confirmation replaces the session, and a JWT is bound to its session |
508
+ | An SSO-only project (`emailAndPassword.enabled: false`) expects Passkey or 2FA (12.11.0+) | Passkey and 2FA routes answer `404` | Switch them on deliberately with `passkey: true` / `twoFactor: true` — they keep a user signed in after the provider withdrew the assignment |
493
509
 
494
510
  ---
495
511
 
@@ -407,14 +407,15 @@ const config = {
407
407
 
408
408
  The following table shows which features are active based on your configuration:
409
409
 
410
- | Configuration | BetterAuth | JWT | 2FA | Passkey |
411
- | ------------------------------------- | :--------: | :-: | :-: | :---------: |
412
- | _not set_ (no URLs) | ✅ | ✅ | ✅ | ⚠️ disabled |
413
- | `env: 'local'/'ci'/'e2e'` (auto URLs) | ✅ | ✅ | ✅ | ✅ auto |
414
- | `baseUrl` set | ✅ | ✅ | ✅ | ✅ auto |
415
- | `betterAuth: false` | ❌ | ❌ | ❌ | ❌ |
416
- | `{ passkey: false }` | ✅ | ✅ | ✅ | ❌ |
417
- | `{ twoFactor: false }` | ✅ | ✅ | ❌ | ✅ auto |
410
+ | Configuration | BetterAuth | JWT | 2FA | Passkey |
411
+ | ----------------------------------------------------- | :--------: | :-: | :-------------------------: | :-----------------------: |
412
+ | _not set_ (no URLs) | ✅ | ✅ | ✅ | ⚠️ disabled |
413
+ | `env: 'local'/'ci'/'e2e'` (auto URLs) | ✅ | ✅ | ✅ | ✅ auto |
414
+ | `baseUrl` set | ✅ | ✅ | ✅ | ✅ auto |
415
+ | `betterAuth: false` | ❌ | ❌ | ❌ | ❌ |
416
+ | `{ passkey: false }` | ✅ | ✅ | ✅ | ❌ |
417
+ | `{ twoFactor: false }` | ✅ | ✅ | ❌ | ✅ auto |
418
+ | `{ emailAndPassword: { enabled: false } }` (12.11.0+) | ✅ | ✅ | ❌ unless `twoFactor: true` | ❌ unless `passkey: true` |
418
419
 
419
420
  **Key points:**
420
421
 
@@ -705,6 +706,34 @@ without a warning. `enabled` is the framework's own switch and is not handed on.
705
706
  `betterAuth.options.socialProviders` is not the place for provider options: it replaces the whole block, so the
706
707
  provider disappears from `GET /iam/features` and `emailAndPassword.disableSignUp` no longer closes it.
707
708
 
709
+ ### Sign-in through a provider alone (12.11.0)
710
+
711
+ A project that signs in through a single sign-on provider alone (`emailAndPassword: { enabled: false }`, e.g.
712
+ Microsoft Entra) expects the provider to decide who gets in. Since 12.11.0 nothing the framework offers keeps someone
713
+ in after the provider withdrew the assignment or role:
714
+
715
+ | What | Since 12.11.0 | Before |
716
+ | -------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
717
+ | Passkey and two-factor | Off while sign-in runs through a provider alone (`emailAndPassword` off and no plugin with a sign-in route of its own — `username()` / `phoneNumber()` keep both on); `passkey: true` / `twoFactor: true` (or `{ enabled: true, … }`) switches them on deliberately. Their routes answer 404, also for a passkey registered earlier. The boot names what it switched off, as a warning for a factor with settings of its own | On: a passkey registered once after a provider sign-in kept signing its owner in |
718
+ | A client-submitted id token (`POST /iam/sign-in/social` / `/iam/link-social` with `idToken`) | Refused with `ID_TOKEN_NOT_SUPPORTED` for every provider unless the provider sets `disableIdTokenSignIn: false` (native apps, Google One Tap). The redirect flow is unaffected | Accepted: an id token kept from an earlier sign-in (`/iam/get-access-token` hands it out) signed its owner in again for about an hour, without asking the provider |
719
+ | The Better-Auth JWT | Bound to the session it was issued from (claim `sid`): refused once that session is signed out, revoked, expired or its user deleted — at once on this replica and, with `redis`, on every replica; otherwise within 10 s. A JWT without `sid` (issued before 12.11.0) is refused, and the client fetches a new one with its session (`GET /iam/token`). After a session rotation (the first `verify-totp` while enabling 2FA) the answer carries the JWT of the new session | Valid until its own expiry (15 minutes) after a sign-out, and a JWT client's sign-out ended no session at all |
720
+ | `GET /iam/features` | Reports `emailAndPassword` (also in the GraphQL `betterAuthFeatures`), so a frontend can hide the e-mail form | — |
721
+
722
+ A session that is not extended while it is used ends a fixed time after the sign-in, so a withdrawal at the provider
723
+ reaches it at the latest then:
724
+
725
+ ```typescript
726
+ betterAuth: {
727
+ emailAndPassword: { enabled: false },
728
+ session: { expiresInHours: 8, extendOnUse: false }, // sign in again after 8 hours, every time
729
+ socialProviders: { microsoft: { clientId, clientSecret, tenantId } },
730
+ },
731
+ ```
732
+
733
+ `session.expiresInHours` maps to Better-Auth's `session.expiresIn` (default 7 days), `extendOnUse: false` to
734
+ `session.disableSessionRefresh`. A value of `expiresInHours` that is not a positive number is ignored with a warning.
735
+ `betterAuth.options.session` still wins key by key.
736
+
708
737
  #### Microsoft Entra ID: one organization, identity only
709
738
 
710
739
  ```typescript
@@ -13,7 +13,13 @@ import { IBetterAuth, ICorsConfig } from '../../common/interfaces/server-options
13
13
  import { ConfigService } from '../../common/services/config.service.js';
14
14
  import { detectCookiePrefixDrift, resolveBetterAuthCookiePrefix } from './better-auth-cookie-prefix.helper.js';
15
15
  import { withSqlStorage } from './better-auth-sql.helper.js';
16
+ import { jwtSessionEnded } from './core-better-auth-jwt-session.cache.js';
16
17
  import { projectProvidesOpenApiPlugin } from './core-better-auth-openapi.helper.js';
18
+ import {
19
+ isPasskeyConfigured,
20
+ isTwoFactorConfigured,
21
+ signInFactorsOffWithoutPassword,
22
+ } from './core-better-auth-sign-in-factors.helper.js';
17
23
  import { requireBetterAuthMongoAdapter } from '../../common/persistence/mongo/mongo-packages.js';
18
24
 
19
25
  /**
@@ -552,6 +558,20 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
552
558
  for (const notice of passkeyNormalization.notices) {
553
559
  logger.log(notice);
554
560
  }
561
+ const factorsOffWithoutPassword = signInFactorsOffWithoutPassword(config);
562
+ if (factorsOffWithoutPassword.length) {
563
+ const names = factorsOffWithoutPassword.map((factor) => factor.name);
564
+ const message =
565
+ `${names.join(' and ')} off: sign-in runs through a provider alone (emailAndPassword.enabled: false, no plugin ` +
566
+ 'with a sign-in route of its own), so the provider alone decides who gets in. Switch them on explicitly with ' +
567
+ `${names.map((name) => `${name}: true`).join(' / ')}.`;
568
+ // A factor that carried settings of its own was meant to be on: say so loudly, since its users lose it
569
+ if (factorsOffWithoutPassword.some((factor) => factor.configured)) {
570
+ logger.warn(message);
571
+ } else {
572
+ logger.log(message);
573
+ }
574
+ }
555
575
  for (const warning of passkeyNormalization.warnings) {
556
576
  logger.warn(warning);
557
577
  }
@@ -619,6 +639,8 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
619
639
  // strip `Secure` from the cookies Better-Auth's native handlers forward.
620
640
  const secureCookies = betterAuthBaseUrl.startsWith('https://');
621
641
 
642
+ const sessionOptions = resolveSessionOptions(config);
643
+
622
644
  const betterAuthConfig: Record<string, unknown> = {
623
645
  // Through Nest's logger; a project's own `options.logger` is merged over it (see below).
624
646
  logger: { log: logThroughNest },
@@ -663,6 +685,7 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
663
685
  basePath,
664
686
  baseURL: betterAuthBaseUrl,
665
687
  database: sqlPool ? undefined : (requireBetterAuthMongoAdapter()(db) as any),
688
+ ...(sessionOptions && { session: sessionOptions }),
666
689
  // Enable email/password authentication by default (required by Better-Auth 1.x)
667
690
  // Can be disabled by setting config.emailAndPassword.enabled = false
668
691
  emailAndPassword: {
@@ -810,6 +833,12 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
810
833
  };
811
834
  }
812
835
 
836
+ // `session` is merged, not replaced: `betterAuth.session` sets expiresIn / disableSessionRefresh, and a project's
837
+ // `options.session` (cookie cache, freshAge, …) keeps them unless it sets them itself.
838
+ if (sessionOptions && restOptions.session && typeof restOptions.session === 'object') {
839
+ finalConfig.session = { ...sessionOptions, ...(restOptions.session as Record<string, unknown>) };
840
+ }
841
+
813
842
  // `logger` is merged, not replaced: a project that only sets `level` or `disabled` keeps the Nest routing,
814
843
  // one that passes its own `log` handler gets exactly that.
815
844
  if (restOptions.logger && typeof restOptions.logger === 'object') {
@@ -918,7 +947,8 @@ export function buildBetterAuthOptions(options: CreateBetterAuthOptions): Better
918
947
 
919
948
  /**
920
949
  * Ends the GraphQL WebSocket connections that rode on a session the moment the session is deleted —
921
- * a sign-out, a revoked session, a password reset with `revokeSessionsOnPasswordReset`, a deleted user.
950
+ * a sign-out, a revoked session, a password reset with `revokeSessionsOnPasswordReset`, a deleted user — and, since
951
+ * 12.11.0, the JWTs issued from it (`jwtSessionEnded()`).
922
952
  *
923
953
  * Without it such a connection stays open until `graphQl.subscriptionRevalidationMs` (30 s by
924
954
  * default) catches it on its next event. Better-Auth's `onPasswordReset` cannot do this job: all
@@ -941,8 +971,12 @@ export function wsSessionRevocationPlugin(): BetterAuthPlugin {
941
971
  databaseHooks: {
942
972
  session: {
943
973
  delete: {
944
- after: async (session: { userId?: unknown }) => {
974
+ after: async (session: { id?: unknown; userId?: unknown }) => {
945
975
  try {
976
+ // A JWT issued from this session stops working at once (12.11.0), not when it expires.
977
+ if (session?.id) {
978
+ jwtSessionEnded(String(session.id));
979
+ }
946
980
  if (session?.userId) {
947
981
  revalidateWsConnectionsOf({ iamId: String(session.userId) });
948
982
  }
@@ -1093,6 +1127,10 @@ function buildPlugins(
1093
1127
  plugins.push(
1094
1128
  jwt({
1095
1129
  jwt: {
1130
+ // The id of the session the JWT is issued from (12.11.0): verifyJwtToken() accepts the JWT only while that
1131
+ // session lives (core-better-auth-jwt-session.cache.ts). The rest of the payload is Better-Auth's default,
1132
+ // the session user.
1133
+ definePayload: ({ session, user }) => ({ ...user, sid: session.id }),
1096
1134
  expirationTime: jwtConfig.expiresIn || '15m',
1097
1135
  },
1098
1136
  }),
@@ -1100,10 +1138,9 @@ function buildPlugins(
1100
1138
  }
1101
1139
 
1102
1140
  // Two-Factor Authentication Plugin
1103
- // 2FA is enabled by default unless explicitly disabled (twoFactor: false or twoFactor: { enabled: false })
1104
- const twoFactorExplicitlyDisabled =
1105
- config.twoFactor === false || (typeof config.twoFactor === 'object' && config.twoFactor?.enabled === false);
1106
- if (!twoFactorExplicitlyDisabled) {
1141
+ // On unless switched off (twoFactor: false or { enabled: false }); with sign-in through a provider alone only when
1142
+ // switched on explicitly (12.11.0, see isSignInFactorEnabled())
1143
+ if (isTwoFactorConfigured(config)) {
1107
1144
  const twoFactorConfig = typeof config.twoFactor === 'object' ? config.twoFactor : {};
1108
1145
  plugins.push(
1109
1146
  twoFactor({
@@ -1232,6 +1269,13 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
1232
1269
  ...providerOptions,
1233
1270
  clientId: provider.clientId,
1234
1271
  clientSecret: provider.clientSecret,
1272
+ // Since 12.11.0 a client cannot sign in or link an account with an id token it submits itself
1273
+ // (`POST /sign-in/social` / `/link-social` with `idToken`) unless the project opens it with an explicit
1274
+ // `false`. Better-Auth verifies such a token's signature, audience and expiry, and asks the provider nothing:
1275
+ // an id token kept from an earlier sign-in (`/get-access-token` hands it out) signed its owner in again for
1276
+ // its whole lifetime (about an hour at Microsoft), after the provider had withdrawn the assignment or role.
1277
+ // The redirect flow never uses it. Native apps and Google One Tap need it and set `false`.
1278
+ disableIdTokenSignIn: provider.disableIdTokenSignIn !== false,
1235
1279
  disableSignUp: typeof provider.disableSignUp === 'boolean' ? provider.disableSignUp : signUpClosed,
1236
1280
  };
1237
1281
  }
@@ -1241,6 +1285,36 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
1241
1285
  return socialProvidersConfig;
1242
1286
  }
1243
1287
 
1288
+ /**
1289
+ * Better-Auth's session options from `betterAuth.session` (12.11.0): `expiresIn` in seconds and `disableSessionRefresh`
1290
+ * — `undefined` when nothing is set, so Better-Auth's defaults (7 days, extended daily) apply unchanged.
1291
+ *
1292
+ * An `expiresInHours` that is not a positive finite number is ignored with a warning: a misconfigured lifetime must
1293
+ * fall back to the default, never to a lifetime nobody chose.
1294
+ */
1295
+ function resolveSessionOptions(config: IBetterAuth): Record<string, unknown> | undefined {
1296
+ const session = config.session;
1297
+ if (!session || typeof session !== 'object') {
1298
+ return undefined;
1299
+ }
1300
+ const options: Record<string, unknown> = {};
1301
+ if (session.expiresInHours !== undefined) {
1302
+ const hours = session.expiresInHours as unknown;
1303
+ if (typeof hours === 'number' && Number.isFinite(hours) && hours > 0) {
1304
+ options.expiresIn = Math.round(hours * 3600);
1305
+ } else {
1306
+ logger.warn(
1307
+ `betterAuth.session.expiresInHours must be a positive number of hours (received ${JSON.stringify(hours)}); ` +
1308
+ "Better-Auth's default of 7 days applies.",
1309
+ );
1310
+ }
1311
+ }
1312
+ if (session.extendOnUse === false) {
1313
+ options.disableSessionRefresh = true;
1314
+ }
1315
+ return Object.keys(options).length ? options : undefined;
1316
+ }
1317
+
1244
1318
  /**
1245
1319
  * Splits a provider's `scope` string on commas and whitespace into the list Better-Auth expects, dropping empty
1246
1320
  * entries: `'openid profile email'` and `'openid,profile,email'` both become `['openid', 'profile', 'email']`.
@@ -1741,12 +1815,9 @@ function normalizePasskeyConfig(
1741
1815
  const notices: string[] = [];
1742
1816
  const warnings: string[] = [];
1743
1817
 
1744
- // Check if Passkey is explicitly DISABLED
1745
- // passkey: false OR passkey: { enabled: false }
1746
- const isExplicitlyDisabled =
1747
- config.passkey === false || (typeof config.passkey === 'object' && config.passkey?.enabled === false);
1748
-
1749
- if (isExplicitlyDisabled) {
1818
+ // Passkey switched off: passkey: false OR passkey: { enabled: false } — or, with sign-in through a provider alone, not
1819
+ // switched on explicitly (12.11.0, see isSignInFactorEnabled())
1820
+ if (!isPasskeyConfigured(config)) {
1750
1821
  return { enabled: false, normalizedConfig: null, notices, trustedOrigins: null, warnings };
1751
1822
  }
1752
1823
 
@@ -357,7 +357,7 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
357
357
  // Extract session token from cookies or Authorization header.
358
358
  // In JWT mode, extractSessionToken correctly returns null for JWTs.
359
359
  // Fall back to the session resolved by CoreBetterAuthMiddleware (which
360
- // resolves JWTs to DB sessions via getActiveSessionForUser).
360
+ // resolves a JWT to its own DB session via getJwtSession()).
361
361
  let sessionToken = extractSessionToken(req, basePath);
362
362
  if (!sessionToken) {
363
363
  const betterAuthReq = req as any;