Skip to content

feat: add scheduled refresh token and password reset cleanup job#114

Merged
GitAddRemote merged 19 commits into
mainfrom
fix/ISSUE-98-token-cleanup-job
Apr 22, 2026
Merged

feat: add scheduled refresh token and password reset cleanup job#114
GitAddRemote merged 19 commits into
mainfrom
fix/ISSUE-98-token-cleanup-job

Conversation

@GitAddRemote
Copy link
Copy Markdown
Owner

@GitAddRemote GitAddRemote commented Apr 11, 2026

Summary

Implements a scheduled token cleanup job that periodically purges expired and revoked refresh tokens and used/expired password reset tokens from the database.

  • Registers the cleanup cron via `OnApplicationBootstrap` + `SchedulerRegistry` (not `@Cron()`) so the cron expression can be driven by environment variables loaded at runtime
  • `SchedulerRegistry` is injected with `@Optional()` so the service constructs cleanly in test environments where `ScheduleModule` is excluded from `AppModule`
  • Cron expression is read from `REFRESH_TOKEN_CLEANUP_CRON` env var; invalid or blank values fall back to the default `0 3 * * *` (3 AM daily) with a logged warning
  • Skips cron registration and cleanup queries in test environments (`NODE_ENV === 'test'` or `JEST_WORKER_ID` set)
  • Adds migration for indexes supporting efficient cleanup DELETEs: partial indexes on `revoked`/`used` booleans and range indexes on `"expiresAt"` for both tables
  • Upgrades `Dockerfile` base image from `node:14` to `node:20-slim` (Debian/glibc — alpine was avoided because musl libc breaks bcrypt native prebuilds; Node 18 was EOL so bumped to 20 to match CI)

Test plan

  • Unit tests in `token-cleanup.service.spec.ts` (11 tests pass)
    • Early return when `NODE_ENV=test`
    • Early return when `JEST_WORKER_ID` set
    • Early return when `schedulerRegistry` is absent (`@Optional()` path)
    • Cron registration with default and custom expressions
    • Fallback to default on invalid cron expression
    • Blank/whitespace env var treated as unset
    • Cleanup deletes revoked/expired refresh tokens and used/expired password resets
    • No throw when a DB query fails
  • Migration has working `up()` and `down()` methods

Closes #98

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a scheduled cleanup job in the auth module to purge revoked/expired refresh tokens and used/expired password reset records, preventing unbounded table growth and reducing retention of sensitive token data (Issue #98).

Changes:

  • Introduces TokenCleanupService with a Nest @Cron job to delete revoked/expired rows from refresh_tokens and password_resets.
  • Registers the cleanup service in AuthModule.
  • Documents REFRESH_TOKEN_CLEANUP_CRON in backend/.env.example.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
backend/src/modules/auth/token-cleanup.service.ts Adds the scheduled cleanup job implementation and logging.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService as an auth provider.
backend/.env.example Documents the cron env var used to configure the schedule.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
@GitAddRemote GitAddRemote self-assigned this Apr 12, 2026
Add TokenCleanupService to the auth module with a @Cron job that
runs daily at 3am (configurable via REFRESH_TOKEN_CLEANUP_CRON) and
deletes all refresh_tokens rows where revoked=true or expires_at < now,
and all password_resets rows where used=true or expires_at < now.

- Job skips early when NODE_ENV=test
- Logs row count and duration on success, error stack on failure
- Does not rethrow on failure so job errors cannot crash the process
- ScheduleModule is already conditionally excluded in test env (AppModule)

Closes #98
@GitAddRemote GitAddRemote force-pushed the fix/ISSUE-98-token-cleanup-job branch from 943ff4a to 0507031 Compare April 13, 2026 00:24
…ice, add tests

- Replace expires_at with "expiresAt" in both QueryBuilder WHERE clauses —
  TypeORM quotes identifiers so the DB column is case-sensitive "expiresAt",
  not expires_at, which would always error and silently skip cleanup
- Remove ConfigService import and constructor injection — it was never used;
  @Cron() is evaluated at module-load time before DI so ConfigService
  cannot supply the cron expression regardless
- Add TokenCleanupService unit tests covering early return in test env,
  correct WHERE clauses for both delete operations, and error handling
Copilot AI review requested due to automatic review settings April 13, 2026 14:42
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a scheduled maintenance task in the backend auth module to periodically purge expired/revoked authentication artifacts from the database, addressing table growth and reducing retention of sensitive token records.

Changes:

  • Introduces TokenCleanupService with a configurable daily @Cron job to delete revoked/expired refresh_tokens and used/expired password_resets.
  • Wires the service into AuthModule providers.
  • Adds unit tests for early-return behavior, delete query conditions, and non-throwing failure handling; documents the cron env var in .env.example.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
backend/src/modules/auth/token-cleanup.service.ts New cron-driven cleanup logic for refresh tokens and password reset tokens.
backend/src/modules/auth/token-cleanup.service.spec.ts Unit tests covering skip behavior in tests, delete query clauses, and error handling.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService in the auth module providers.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON default cron expression.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.spec.ts Outdated
…_WORKER_ID guard

@Cron() expressions are evaluated at module-load time in Node.js CJS, before
dotenv runs, so REFRESH_TOKEN_CLEANUP_CRON from .env was never read. Switching
to OnApplicationBootstrap + SchedulerRegistry means the cron is registered
after ConfigModule has fully loaded all env vars.

- Remove @Cron() decorator; implement OnApplicationBootstrap
- Register cron via SchedulerRegistry using ConfigService.get() so .env
  values are honoured; falls back to '0 3 * * *' if unset
- Add JEST_WORKER_ID guard to onApplicationBootstrap() so cron is never
  registered in Jest worker processes even if NODE_ENV is not 'test'
- Add cron as a direct dependency (was transitive via @nestjs/schedule)
- Update spec: explicit NODE_ENV mock in cleanupExpiredTokens early-return
  test for determinism; add onApplicationBootstrap() coverage
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an auth-module scheduled cleanup job intended to periodically purge revoked/expired refresh tokens (and used/expired password resets) to prevent unbounded table growth and reduce retention of sensitive token records.

Changes:

  • Introduces TokenCleanupService that registers a cron job on bootstrap and executes DB DELETEs for expired/revoked tokens.
  • Adds unit tests for cron registration guards and deletion query construction/error handling.
  • Adds REFRESH_TOKEN_CLEANUP_CRON to .env.example and adds cron as a direct dependency.

Reviewed changes

Copilot reviewed 5 out of 6 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
pnpm-lock.yaml Adds cron dependency entry and updates lock metadata.
backend/package.json Adds cron dependency for runtime CronJob usage.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON with default schedule.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService in Auth module providers.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-time cron registration and cleanup queries + logging.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit coverage for bootstrap guards and cleanup behavior.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/package.json
Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
- Add @optional() to SchedulerRegistry injection so service can be

  instantiated in test environments where ScheduleModule is excluded

- Validate cron expression at runtime; fall back to '0 3 * * *' on invalid value

- Treat blank/whitespace REFRESH_TOKEN_CLEANUP_CRON as unset (|| not ??)

- Upgrade Dockerfile base image from node:14 to node:18-alpine

- Add migration for token cleanup indexes (partial + range indexes on

  revoked, expiresAt for refresh_tokens and used, expiresAt for password_resets)

- Expand spec: test @optional() path, invalid cron fallback, blank env var
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an Auth-module scheduled maintenance job to remove expired/revoked refresh tokens and used/expired password reset tokens, plus supporting DB indexes and runtime configuration.

Changes:

  • Introduces TokenCleanupService that registers a cron job at bootstrap using SchedulerRegistry and a configurable cron expression.
  • Adds unit tests covering bootstrap registration and cleanup query behavior.
  • Adds a migration creating indexes to support efficient cleanup deletes; updates Docker base image and dependency set (adds cron).

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
pnpm-lock.yaml Locks cron dependency and updates lockfile metadata.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-registered cron + cleanup DELETE queries and logging.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit coverage for cron registration paths and cleanup execution.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService provider in AuthModule.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes (partial + expiresAt) to speed up cleanup deletes.
backend/package.json Adds direct dependency on cron.
backend/Dockerfile Upgrades base image to Node 18 Alpine.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts
Comment thread backend/src/modules/auth/token-cleanup.service.ts
Comment thread backend/Dockerfile Outdated
Merge conflict resolutions:

- .env.example: keep both REFRESH_TOKEN_CLEANUP_CRON and ALLOWED_ORIGIN

- package.json: keep both cron and cookie-parser dependencies

- auth.module.ts: keep TokenCleanupService, drop RefreshTokenStrategy

  (superseded by custom cookie-reading RefreshTokenAuthGuard on main)

- pnpm-lock.yaml: regenerated with pnpm install

Review item fixes:

- Log correct (effective) expression after fallback, not the invalid one

- Extend cleanupExpiredTokens() guard to also skip when JEST_WORKER_ID set

- Switch Dockerfile from node:18-alpine to node:18-slim (musl/bcrypt compat)

- Add spec case for JEST_WORKER_ID guard in cleanupExpiredTokens

- Unset JEST_WORKER_ID in non-test-env describe block so DB tests can run
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an environment-configurable scheduled cleanup job to the backend auth module to purge expired/revoked refresh tokens and used/expired password reset tokens, along with supporting DB indexes and runtime/container updates.

Changes:

  • Introduces TokenCleanupService that registers a cron job at bootstrap via SchedulerRegistry, with runtime-configurable expression and test-environment guards.
  • Adds unit tests covering cron registration behavior and cleanup delete queries.
  • Adds a migration for cleanup-oriented indexes and updates backend runtime dependencies/container base image.

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pnpm-lock.yaml Locks the new cron dependency (and related lockfile metadata updates).
backend/src/modules/auth/token-cleanup.service.ts Implements scheduled token cleanup via OnApplicationBootstrap + SchedulerRegistry with env-driven cron expression and safeguards.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit tests for cron registration and cleanup delete behavior/guards.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService as an auth module provider.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes (partial boolean + expiresAt) to support cleanup DELETE performance.
backend/package.json Adds direct cron dependency.
backend/Dockerfile Updates base image to Node 18 (slim) for dependency compatibility.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Outdated
Comment thread backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Outdated
The previous comments said the WHERE clause 'mirrors cleanup query', which

implied full coverage of the OR condition. Each partial index only covers

one predicate (revoked = true / used = true); the range index on expiresAt

handles the other side. Updated comments to describe what each index

actually covers.
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a scheduled maintenance job to the auth subsystem to periodically delete expired/revoked refresh tokens and used/expired password reset tokens, with runtime-configurable cron scheduling and supporting DB indexes.

Changes:

  • Introduces TokenCleanupService that registers a CronJob via SchedulerRegistry on bootstrap (env-driven schedule, safe no-op in test/Jest environments).
  • Adds unit tests covering cron registration behavior and cleanup query execution/guards.
  • Adds a migration creating indexes to support efficient cleanup deletes, plus wires the service into AuthModule and documents the env var in .env.example.

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pnpm-lock.yaml Adds the cron dependency to the lockfile (and related metadata updates).
backend/package.json Adds cron as a direct backend dependency.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-time cron registration and token cleanup delete logic.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit tests for cron registration guards/fallbacks and delete behavior.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService in the auth module providers.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds partial/range indexes to support cleanup queries efficiently.
backend/Dockerfile Updates Node base image version for backend container builds.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/Dockerfile Outdated
Comment thread backend/Dockerfile Outdated
Node 18 reached EOL; CI already runs on Node 20. Switching to node:20-slim
(Debian/glibc) keeps the runtime in sync with CI and avoids the musl libc
issues that alpine would introduce for bcrypt's native prebuilds.
GitAddRemote added a commit that referenced this pull request Apr 21, 2026
- Enable @typescript-eslint/no-explicit-any: error in eslint.config.js
  (was off, conflicting with .eslintrc.js)
- Normalize caught errors before recordSyncFailure() in all four sync
  services (error instanceof Error ? error : new Error(String(error)))
  to avoid silent loss of context when thrown value isn't an Error
- Replace null as unknown as Date with IsNull() in uex-sync.service.ts
  for type-safe null comparison in TypeORM where clause
- Remove token-cleanup.service.ts and its auth.module.ts registration
  from this branch (belongs in PR #114, not here)
- Remove REFRESH_TOKEN_CLEANUP_CRON from .env.example (same reason)
…branch

Each partial index covers only one predicate of the cleanup OR condition
(revoked=true or used=true), not the full clause. The expiresAt range
indexes cover the other branch. Comments were misleading by implying
full OR coverage.
Copilot AI review requested due to automatic review settings April 21, 2026 05:18
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an auth-module scheduled cleanup job to periodically delete expired/revoked refresh tokens and used/expired password reset tokens, with runtime-configurable cron scheduling and supporting DB indexes to keep the cleanup efficient as tables grow.

Changes:

  • Introduces TokenCleanupService that registers a CronJob via SchedulerRegistry during OnApplicationBootstrap, driven by REFRESH_TOKEN_CLEANUP_CRON with safe fallback/guards for test environments.
  • Adds unit tests covering cron registration behavior, test-env guards, and cleanup query behavior/error handling.
  • Adds a migration for cleanup-oriented indexes and updates runtime/deployment config (new env var, Docker base image bump, cron dependency).

Reviewed changes

Copilot reviewed 7 out of 8 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm-lock.yaml Locks cron dependency addition for backend workspace.
backend/src/modules/auth/token-cleanup.service.ts Implements scheduled cleanup job registration and delete queries with logging/guards.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit tests for cron setup, guards, and cleanup behavior.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService in Auth module providers.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes to support efficient cleanup deletes.
backend/package.json Adds direct cron dependency.
backend/Dockerfile Updates runtime base image to Node 20 slim.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts
…in data-source

- Add REFRESH_TOKEN_CLEANUP_CRON to Joi envValidationSchema as an optional

  string with default '0 3 * * *', consistent with other env var documentation

  and early-misconfiguration detection

- Import and register AddTokenCleanupIndexes1765038000000 in data-source.ts

  so migration:run picks up the cleanup indexes; migration order is preserved
The no-explicit-any ESLint rule (enabled in PR #122) flagged three

remaining 'as any' casts in the @optional() spec case. Replaced with

'as unknown as Repository<T>' / 'as unknown as ConfigService'.
Copilot AI review requested due to automatic review settings April 22, 2026 01:39
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an Auth-module scheduled maintenance job to periodically remove expired/revoked refresh tokens and used/expired password reset tokens, including configuration, tests, and DB indexes to keep the cleanup efficient as tables grow.

Changes:

  • Introduces TokenCleanupService that registers a cron job at bootstrap via SchedulerRegistry, driven by REFRESH_TOKEN_CLEANUP_CRON (with safe fallbacks/guards for test environments).
  • Adds unit tests covering cron registration/guard behavior and cleanup query execution/error handling.
  • Adds a migration for cleanup-supporting indexes, wires it into the TypeORM data source list, and updates runtime/deps/env docs (cron dependency + Docker base image + .env.example).

Reviewed changes

Copilot reviewed 9 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm-lock.yaml Locks the added cron dependency version for the backend workspace.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-registered cron job + DB cleanup deletes + logging/guards.
backend/src/modules/auth/token-cleanup.service.spec.ts Unit tests for cron registration and cleanup behavior (incl. test-env guards and failure handling).
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService as an Auth module provider.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes (partial + range) to support efficient cleanup deletes.
backend/src/data-source.ts Adds the new migration to the explicitly-imported migration list.
backend/src/config/env.validation.ts Adds REFRESH_TOKEN_CLEANUP_CRON to Joi env validation with a default.
backend/package.json Adds cron as a direct dependency.
backend/Dockerfile Updates backend runtime base image to node:20-slim.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Extracts '0 3 * * *' into DEFAULT_CLEANUP_CRON in token-cleanup.constants.ts.

Both env.validation.ts (Joi default) and token-cleanup.service.ts (runtime

fallback) now import from the same source, eliminating the duplication that

could drift if the default schedule ever changes.
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an Auth-module scheduled maintenance task to keep token-related tables from growing unboundedly, plus supporting configuration and DB indexes.

Changes:

  • Introduces TokenCleanupService that registers a runtime-configurable cron job (via SchedulerRegistry) to delete revoked/expired refresh tokens and used/expired password reset tokens.
  • Adds unit tests for cron registration guards/fallbacks and for the cleanup DELETE behavior.
  • Adds migration + datasource registration for cleanup-supporting indexes; updates env validation, .env.example, Docker base image, and deps.

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm-lock.yaml Adds cron dependency resolution in lockfile.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-time cron registration and cleanup DELETE queries with logging and error isolation.
backend/src/modules/auth/token-cleanup.service.spec.ts Unit tests for registration guards, cron expression fallback behavior, and cleanup query execution/error handling.
backend/src/modules/auth/token-cleanup.constants.ts Defines default cron expression constant.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService provider in AuthModule.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes to support efficient cleanup deletes (partial + expiresAt).
backend/src/data-source.ts Registers the new migration in the explicit migrations list.
backend/src/config/env.validation.ts Adds REFRESH_TOKEN_CLEANUP_CRON env var defaulting to the shared constant.
backend/package.json Adds cron as a direct dependency.
backend/Dockerfile Updates base image to node:20-slim.
backend/.env.example Documents and provides example REFRESH_TOKEN_CLEANUP_CRON.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts
The silent || fallback was inconsistent with the PR description.

Now emits a logger.warn when the trimmed config value is empty string

before falling back to the default. Updated the blank/whitespace spec

case to assert the warning is logged.
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an auth-module scheduled maintenance job that deletes expired/revoked refresh tokens and used/expired password reset tokens, with runtime-configurable cron scheduling and supporting DB indexes.

Changes:

  • Introduces TokenCleanupService that registers a CronJob at bootstrap via SchedulerRegistry (env-driven expression with validation/fallbacks; skipped in test/Jest worker contexts).
  • Adds unit tests for cron registration behavior and cleanup delete logic (including error isolation between tables).
  • Adds a migration creating indexes to support efficient cleanup deletes; wires migration into data-source.ts and documents env var in .env.example.

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
pnpm-lock.yaml Locks newly added cron dependency.
backend/package.json Adds cron dependency for CronJob usage.
backend/Dockerfile Updates base image to node:20-slim.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService provider and ensures entities are available via TypeOrmModule.forFeature.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-registered cron + cleanup delete queries with guards and logging.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit coverage for bootstrap registration and cleanup behavior.
backend/src/modules/auth/token-cleanup.constants.ts Defines default cron expression constant.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds/drops indexes to support cleanup queries.
backend/src/data-source.ts Includes the new migration in the explicitly-listed migrations array.
backend/src/config/env.validation.ts Adds REFRESH_TOKEN_CLEANUP_CRON to validated env schema with default.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.spec.ts
Tests that call onApplicationBootstrap() with a non-test NODE_ENV were

creating real CronJob instances and calling job.start(), leaving active

libuv timers that can cause Jest to hang. Added a jest.mock('cron')

factory at the top of the file so CronJob is a no-op mock throughout.
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an auth-module scheduled maintenance job to keep token-related tables from growing unbounded by periodically deleting expired/revoked refresh tokens and used/expired password reset tokens, with schedule controlled via environment configuration.

Changes:

  • Introduces TokenCleanupService that registers a runtime-configurable cron job (via OnApplicationBootstrap + SchedulerRegistry) and performs cleanup DELETEs.
  • Adds unit tests for cron registration/guards and cleanup query behavior.
  • Adds DB migration + config/env + Docker/dependency updates to support the job (indexes, env var, Node base image, cron dependency).

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pnpm-lock.yaml Adds cron dependency entry to lockfile.
backend/src/modules/auth/token-cleanup.service.ts Implements bootstrap-time cron registration and cleanup DELETE queries with logging and guards.
backend/src/modules/auth/token-cleanup.service.spec.ts Adds unit tests for registration/guards and cleanup behavior.
backend/src/modules/auth/token-cleanup.constants.ts Defines default cron expression constant.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService provider in AuthModule.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds indexes (including partial indexes) to support efficient cleanup deletes.
backend/src/data-source.ts Registers the new migration in the explicit migrations list.
backend/src/config/env.validation.ts Adds REFRESH_TOKEN_CLEANUP_CRON env var with default.
backend/package.json Adds cron as a direct dependency.
backend/Dockerfile Updates base image to Node 20 slim.
backend/.env.example Documents REFRESH_TOKEN_CLEANUP_CRON configuration.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread backend/src/modules/auth/token-cleanup.service.ts Outdated
Comment thread backend/src/modules/auth/token-cleanup.service.spec.ts Outdated
… spec

- Replace 'revoked = :revoked' / 'used = :used' with inlined 'revoked = TRUE'

  / 'used = TRUE' so Postgres can reliably use the partial indexes added in

  this PR (a bind param prevents the planner from matching the WHERE clause)

- Update CronJob mock to throw for known-invalid expressions so the try/catch

  fallback path in onApplicationBootstrap() is actually exercised

- Update spec assertions to reflect the new non-parameterised WHERE clauses
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an Auth-module scheduled maintenance task that cleans up expired/revoked refresh tokens and used/expired password reset tokens, keeping the database from growing unbounded and reducing retention of sensitive token records.

Changes:

  • Introduces TokenCleanupService that registers a cron job at bootstrap via SchedulerRegistry, with runtime-configurable cron expression and safe fallbacks.
  • Adds unit tests covering cron registration/guards and delete behavior (including failure isolation).
  • Adds DB indexes (via migration) to support efficient cleanup deletes; wires the migration into the explicit data-source.ts migration list.

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated no comments.

Show a summary per file
File Description
pnpm-lock.yaml Locks the newly added cron dependency resolution.
backend/src/modules/auth/token-cleanup.service.ts Implements runtime cron registration + cleanup DELETEs with logging and test-environment guards.
backend/src/modules/auth/token-cleanup.service.spec.ts Unit tests for cron registration paths, env guards, cleanup behavior, and failure handling.
backend/src/modules/auth/token-cleanup.constants.ts Defines the default cleanup cron expression.
backend/src/modules/auth/auth.module.ts Registers TokenCleanupService provider and ensures required entities are in forFeature.
backend/src/migrations/1765038000000-AddTokenCleanupIndexes.ts Adds partial/range indexes to support efficient cleanup queries.
backend/src/data-source.ts Explicitly imports and registers the new migration.
backend/src/config/env.validation.ts Adds REFRESH_TOKEN_CLEANUP_CRON to validated env config with a default value.
backend/package.json Adds cron as a direct backend dependency.
backend/Dockerfile Updates the backend base image to node:20-slim.
backend/.env.example Documents/configures REFRESH_TOKEN_CLEANUP_CRON example value.
Files not reviewed (1)
  • pnpm-lock.yaml: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@GitAddRemote GitAddRemote merged commit 2fee4cd into main Apr 22, 2026
13 checks passed
@GitAddRemote GitAddRemote deleted the fix/ISSUE-98-token-cleanup-job branch April 22, 2026 02:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tech Story: Add scheduled refresh token cleanup job

2 participants