@open-mercato/scheduler 0.6.7-develop.6751.1.ac823a3d26 → 0.6.7-develop.6758.1.697eade236

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 (24) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/scheduler/api/targets/route.js +5 -4
  3. package/dist/modules/scheduler/api/targets/route.js.map +2 -2
  4. package/dist/modules/scheduler/commands/jobs.js +10 -3
  5. package/dist/modules/scheduler/commands/jobs.js.map +2 -2
  6. package/dist/modules/scheduler/data/validators.js +27 -1
  7. package/dist/modules/scheduler/data/validators.js.map +2 -2
  8. package/dist/modules/scheduler/lib/scheduler-safe-commands.js +73 -0
  9. package/dist/modules/scheduler/lib/scheduler-safe-commands.js.map +7 -0
  10. package/dist/modules/scheduler/services/localSchedulerService.js +9 -0
  11. package/dist/modules/scheduler/services/localSchedulerService.js.map +2 -2
  12. package/dist/modules/scheduler/workers/execute-schedule.worker.js +9 -0
  13. package/dist/modules/scheduler/workers/execute-schedule.worker.js.map +2 -2
  14. package/package.json +5 -5
  15. package/src/modules/scheduler/api/targets/__tests__/route.test.ts +76 -0
  16. package/src/modules/scheduler/api/targets/route.ts +7 -7
  17. package/src/modules/scheduler/commands/jobs.ts +11 -3
  18. package/src/modules/scheduler/data/__tests__/validators.test.ts +40 -8
  19. package/src/modules/scheduler/data/validators.ts +30 -1
  20. package/src/modules/scheduler/lib/scheduler-safe-commands.ts +98 -0
  21. package/src/modules/scheduler/services/__tests__/localSchedulerService.test.ts +97 -1
  22. package/src/modules/scheduler/services/localSchedulerService.ts +11 -0
  23. package/src/modules/scheduler/workers/__tests__/execute-schedule.worker.test.ts +12 -0
  24. package/src/modules/scheduler/workers/execute-schedule.worker.ts +15 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/workers/execute-schedule.worker.ts"],
4
- "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n \n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n targetJobId = await targetQueue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }))\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
5
- "mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAE3B,SAAS,0BAA0B;AACnC,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAG/D,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,aAAa;AAAA;AACf;AAuCA,eAAO,sBACL,KACA,KACe;AACf,SAAO,MAAM,kBAAkB;AAAA,IAC7B,OAAO,IAAI;AAAA,IACX,eAAe,IAAI;AAAA,EACrB,CAAC;AAGD,QAAM,UAAW,IAAI,WAAY,IAAqD;AAEtF,MAAI,CAAC,WAAW,CAAC,QAAQ,YAAY;AACnC,WAAO,MAAM,2CAA2C,EAAE,OAAO,IAAI,MAAM,CAAC;AAC5E,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAEA,QAAM,EAAE,WAAW,IAAI;AAEvB,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,cAAc,IAAI,QAAyB,aAAa;AAG9D,QAAM,WAAW,MAAM,GAAG,QAAQ,cAAc;AAAA,IAC9C,IAAI;AAAA,IACJ,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MAC5D,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,IAC3B;AAEA,UAAM,aAAa,6BAA6B,UAAU,GAA8B;AAExF,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
4
+ "sourcesContent": ["import type { QueuedJob, JobContext, WorkerMeta } from '@open-mercato/queue'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { CommandBus } from '@open-mercato/shared/lib/commands'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { emitSchedulerEvent } from '../events.js'\nimport { assertSchedulerSafeCommandAuthorized } from '../lib/scheduler-safe-commands.js'\nimport { buildScheduledCommandContext } from '../lib/commandContext.js'\nimport { buildQueueTargetPayload, buildSchedulerIdempotencyKey } from '../lib/queueTargetPayload.js'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('scheduler').child({ component: 'worker' })\n\n// Worker metadata for auto-discovery\nexport const metadata: WorkerMeta = {\n queue: 'scheduler-execution',\n concurrency: 5, // Process up to 5 schedules concurrently\n}\n\nexport type ExecuteSchedulePayload = {\n scheduleId: string\n tenantId?: string | null\n organizationId?: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n triggerType?: 'scheduled' | 'manual'\n triggeredByUserId?: string | null\n}\n\ntype HandlerContext = { resolve: <T = unknown>(name: string) => T }\ntype RbacServiceLike = {\n tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean>\n userHasAllFeatures(\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean>\n}\n\n/**\n * Worker that executes scheduled jobs.\n * \n * This worker is triggered by BullMQ repeatable jobs at the scheduled times.\n * It loads the fresh schedule configuration from the database, validates\n * conditions, and enqueues the target job or executes the command.\n * \n * BullMQ handles:\n * - Timing (exact cron/interval execution)\n * - Distributed locking (prevents duplicate execution)\n * - Retries (if worker fails)\n * - Execution history (via job state, logs, timestamps)\n * \n * This worker handles:\n * - Loading fresh schedule config\n * - Checking feature flags and conditions\n * - Enqueuing target job or executing command\n * - Updating last run time\n */\nexport default async function executeScheduleWorker(\n job: QueuedJob<ExecuteSchedulePayload>,\n ctx: JobContext & HandlerContext,\n): Promise<void> {\n logger.debug('Processing job', {\n jobId: ctx.jobId,\n attemptNumber: ctx.attemptNumber,\n })\n \n // Defensive: handle both data and payload for BullMQ compatibility\n const payload = (job.payload || (job as unknown as { data?: ExecuteSchedulePayload }).data) as ExecuteSchedulePayload | undefined\n \n if (!payload || !payload.scheduleId) {\n logger.error('Invalid job payload: scheduleId missing', { jobId: ctx.jobId })\n throw new Error('scheduleId is required in job payload')\n }\n\n const { scheduleId } = payload\n\n const em = ctx.resolve<EntityManager>('em')\n const rbacService = ctx.resolve<RbacServiceLike>('rbacService')\n\n // Load fresh schedule from database\n const schedule = await em.findOne(ScheduledJob, { \n id: scheduleId,\n deletedAt: null,\n })\n\n if (!schedule) {\n logger.info('Schedule not found or deleted', { scheduleId })\n return\n }\n\n // CRITICAL: Verify scope integrity - ensure payload scope matches database\n // This prevents scope tampering and ensures proper multi-tenant isolation\n if (payload.scopeType !== schedule.scopeType) {\n logger.error('Scope type mismatch for schedule', {\n scheduleId,\n payloadScope: payload.scopeType,\n dbScope: schedule.scopeType,\n })\n throw new Error('Schedule scope type mismatch - potential security issue')\n }\n\n if (payload.tenantId !== schedule.tenantId) {\n logger.error('Tenant ID mismatch for schedule', {\n scheduleId,\n payloadTenant: payload.tenantId,\n dbTenant: schedule.tenantId,\n })\n throw new Error('Schedule tenant ID mismatch - potential security issue')\n }\n\n if (payload.organizationId !== schedule.organizationId) {\n logger.error('Organization ID mismatch for schedule', {\n scheduleId,\n payloadOrg: payload.organizationId,\n dbOrg: schedule.organizationId,\n })\n throw new Error('Schedule organization ID mismatch - potential security issue')\n }\n\n // Check if schedule is still enabled\n if (!schedule.isEnabled) {\n logger.debug('Schedule is disabled', { scheduleId })\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: 'Schedule is disabled',\n })\n return\n }\n\n // Emit started event\n await emitSchedulerEvent('scheduler.job.started', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scheduleName: schedule.name,\n attemptNumber: ctx.attemptNumber || 1,\n })\n\n // Check feature flag if required\n if (schedule.requireFeature) {\n const hasFeature = await rbacService.tenantHasFeature(\n schedule.tenantId,\n schedule.requireFeature,\n { organizationId: schedule.organizationId },\n )\n \n if (!hasFeature) {\n await emitSchedulerEvent('scheduler.job.skipped', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n reason: `Feature not enabled: ${schedule.requireFeature}`,\n })\n\n logger.debug('Schedule skipped: feature not enabled', { scheduleId, requireFeature: schedule.requireFeature })\n return\n }\n }\n\n // Enqueue target job or execute command\n if (schedule.targetType === 'queue' && schedule.targetQueue) {\n // Determine queue strategy from environment\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n const targetQueue = createQueue(schedule.targetQueue, queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n \n let targetJobId: string | undefined\n try {\n // The execute-schedule job id is stable across BullMQ retries, so if\n // this worker crashes between enqueue and DB flush the retried attempt\n // reuses the same idempotency key and downstream workers can dedupe.\n const idempotencyKey = buildSchedulerIdempotencyKey(schedule.id, ctx.jobId ?? Date.now())\n\n targetJobId = await targetQueue.enqueue(buildQueueTargetPayload({\n targetPayload: schedule.targetPayload,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n idempotencyKey,\n }))\n } finally {\n // Always close the queue instance to free Redis connections\n await targetQueue.close()\n }\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n\n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n queueJobId: targetJobId,\n queueName: schedule.targetQueue,\n })\n\n logger.debug('Successfully enqueued job', {\n scheduleId: schedule.id,\n targetQueue: schedule.targetQueue,\n queueJobId: targetJobId,\n })\n\n } else if (schedule.targetType === 'command' && schedule.targetCommand) {\n const commandBus = new CommandBus()\n const actorUserId = typeof schedule.createdByUserId === 'string' ? schedule.createdByUserId.trim() : ''\n await assertSchedulerSafeCommandAuthorized({\n commandId: schedule.targetCommand,\n actorUserId,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n rbacService,\n })\n \n const commandInput = {\n ...((schedule.targetPayload as Record<string, unknown>) || {}),\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n }\n \n // Build the schedule-scoped command context after the allowlist/RBAC gate.\n const commandCtx = buildScheduledCommandContext(schedule, ctx as unknown as AppContainer)\n \n const commandResult = await commandBus.execute(schedule.targetCommand, {\n input: commandInput,\n ctx: commandCtx,\n })\n \n // Update schedule's last run time\n schedule.lastRunAt = new Date()\n await em.flush()\n \n await emitSchedulerEvent('scheduler.job.completed', {\n id: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n commandId: schedule.targetCommand,\n commandResult: commandResult.result,\n })\n \n logger.debug('Successfully executed command', {\n scheduleId: schedule.id,\n commandId: schedule.targetCommand,\n })\n\n } else {\n throw new Error('Invalid target configuration')\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAE3B,SAAS,0BAA0B;AACnC,SAAS,4CAA4C;AACrD,SAAS,oCAAoC;AAC7C,SAAS,yBAAyB,oCAAoC;AACtE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAG/D,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,aAAa;AAAA;AACf;AA4CA,eAAO,sBACL,KACA,KACe;AACf,SAAO,MAAM,kBAAkB;AAAA,IAC7B,OAAO,IAAI;AAAA,IACX,eAAe,IAAI;AAAA,EACrB,CAAC;AAGD,QAAM,UAAW,IAAI,WAAY,IAAqD;AAEtF,MAAI,CAAC,WAAW,CAAC,QAAQ,YAAY;AACnC,WAAO,MAAM,2CAA2C,EAAE,OAAO,IAAI,MAAM,CAAC;AAC5E,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AAEA,QAAM,EAAE,WAAW,IAAI;AAEvB,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,cAAc,IAAI,QAAyB,aAAa;AAG9D,QAAM,WAAW,MAAM,GAAG,QAAQ,cAAc;AAAA,IAC9C,IAAI;AAAA,IACJ,WAAW;AAAA,EACb,CAAC;AAED,MAAI,CAAC,UAAU;AACb,WAAO,KAAK,iCAAiC,EAAE,WAAW,CAAC;AAC3D;AAAA,EACF;AAIA,MAAI,QAAQ,cAAc,SAAS,WAAW;AAC5C,WAAO,MAAM,oCAAoC;AAAA,MAC/C;AAAA,MACA,cAAc,QAAQ;AAAA,MACtB,SAAS,SAAS;AAAA,IACpB,CAAC;AACD,UAAM,I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AAGA,UAAM,aAAa,6BAA6B,UAAU,GAA8B;AAExF,UAAM,gBAAgB,MAAM,WAAW,QAAQ,SAAS,eAAe;AAAA,MACrE,OAAO;AAAA,MACP,KAAK;AAAA,IACP,CAAC;AAGD,aAAS,YAAY,oBAAI,KAAK;AAC9B,UAAM,GAAG,MAAM;AAEf,UAAM,mBAAmB,2BAA2B;AAAA,MAClD,IAAI,SAAS;AAAA,MACb,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,WAAW,SAAS;AAAA,MACpB,eAAe,cAAc;AAAA,IAC/B,CAAC;AAED,WAAO,MAAM,iCAAiC;AAAA,MAC5C,YAAY,SAAS;AAAA,MACrB,WAAW,SAAS;AAAA,IACtB,CAAC;AAAA,EAEH,OAAO;AACL,UAAM,IAAI,MAAM,8BAA8B;AAAA,EAChD;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.6.7-develop.6751.1.ac823a3d26",
3
+ "version": "0.6.7-develop.6758.1.697eade236",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.6.7-develop.6751.1.ac823a3d26",
63
- "@open-mercato/queue": "0.6.7-develop.6751.1.ac823a3d26",
62
+ "@open-mercato/events": "0.6.7-develop.6758.1.697eade236",
63
+ "@open-mercato/queue": "0.6.7-develop.6758.1.697eade236",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.6.7-develop.6751.1.ac823a3d26",
68
+ "@open-mercato/shared": "0.6.7-develop.6758.1.697eade236",
69
69
  "bullmq": "^5.0.0",
70
70
  "ioredis": "^5.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.6.7-develop.6751.1.ac823a3d26",
82
+ "@open-mercato/shared": "0.6.7-develop.6758.1.697eade236",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.0.1",
85
85
  "jest": "^30.4.2",
@@ -0,0 +1,76 @@
1
+ import { NextRequest } from 'next/server'
2
+ import { GET } from '../route'
3
+ import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
4
+ import { getModules } from '@open-mercato/shared/lib/modules/registry'
5
+ import { registerCommand, unregisterCommand } from '@open-mercato/shared/lib/commands/registry'
6
+ import type { CommandHandler } from '@open-mercato/shared/lib/commands/types'
7
+ import {
8
+ clearSchedulerSafeCommandsForTests,
9
+ registerSchedulerSafeCommands,
10
+ } from '../../../lib/scheduler-safe-commands'
11
+
12
+ jest.mock('@open-mercato/shared/lib/auth/server', () => ({
13
+ getAuthFromRequest: jest.fn(),
14
+ }))
15
+
16
+ jest.mock('@open-mercato/shared/lib/modules/registry', () => ({
17
+ getModules: jest.fn(),
18
+ }))
19
+
20
+ const safeCommand: CommandHandler<unknown, { ok: boolean }> = {
21
+ id: 'test.scheduler.safe.route',
22
+ async execute() {
23
+ return { ok: true }
24
+ },
25
+ }
26
+
27
+ const unsafeCommand: CommandHandler<unknown, { ok: boolean }> = {
28
+ id: 'test.scheduler.unsafe.route',
29
+ async execute() {
30
+ return { ok: true }
31
+ },
32
+ }
33
+
34
+ describe('GET /api/scheduler/targets', () => {
35
+ beforeEach(() => {
36
+ clearSchedulerSafeCommandsForTests()
37
+ unregisterCommand(safeCommand.id)
38
+ unregisterCommand(unsafeCommand.id)
39
+ registerCommand(safeCommand)
40
+ registerCommand(unsafeCommand)
41
+ registerSchedulerSafeCommands([
42
+ {
43
+ commandId: safeCommand.id,
44
+ requiredFeatures: ['scheduler.jobs.manage'],
45
+ },
46
+ ])
47
+ ;(getAuthFromRequest as jest.Mock).mockResolvedValue({
48
+ sub: 'user-1',
49
+ tenantId: 'tenant-1',
50
+ orgId: 'org-1',
51
+ })
52
+ ;(getModules as jest.Mock).mockReturnValue([
53
+ { workers: [{ queue: 'z-queue' }] },
54
+ { workers: [{ queue: 'a-queue' }] },
55
+ ])
56
+ })
57
+
58
+ afterEach(() => {
59
+ unregisterCommand(safeCommand.id)
60
+ unregisterCommand(unsafeCommand.id)
61
+ })
62
+
63
+ it('lists only scheduler-safe commands', async () => {
64
+ const response = await GET(new NextRequest('http://localhost/api/scheduler/targets'))
65
+ const body = await response.json()
66
+
67
+ expect(response.status).toBe(200)
68
+ expect(body.queues).toEqual([
69
+ { value: 'a-queue', label: 'a-queue' },
70
+ { value: 'z-queue', label: 'z-queue' },
71
+ ])
72
+ expect(body.commands).toEqual([
73
+ { value: safeCommand.id, label: safeCommand.id },
74
+ ])
75
+ })
76
+ })
@@ -2,8 +2,9 @@ import { NextRequest, NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
4
4
  import { getModules } from '@open-mercato/shared/lib/modules/registry'
5
- import { commandRegistry } from '@open-mercato/shared/lib/commands'
5
+ import { commandRegistry } from '@open-mercato/shared/lib/commands/registry'
6
6
  import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'
7
+ import { listSchedulerSafeCommands } from '../../lib/scheduler-safe-commands'
7
8
 
8
9
  export const metadata = {
9
10
  requireAuth: true,
@@ -35,10 +36,9 @@ export async function GET(req: NextRequest) {
35
36
  .sort((a, b) => a.localeCompare(b))
36
37
  .map((queue) => ({ value: queue, label: queue }))
37
38
 
38
- const commands = commandRegistry
39
- .list()
40
- .sort((a, b) => a.localeCompare(b))
41
- .map((id) => ({ value: id, label: id }))
39
+ const commands = listSchedulerSafeCommands()
40
+ .filter((command) => commandRegistry.has(command.commandId))
41
+ .map((command) => ({ value: command.commandId, label: command.commandId }))
42
42
 
43
43
  return NextResponse.json({ queues, commands })
44
44
  }
@@ -61,12 +61,12 @@ const errorResponseSchema = z.object({
61
61
  export const openApi: OpenApiRouteDoc = {
62
62
  tag: 'Scheduler',
63
63
  summary: 'List available schedule targets',
64
- description: 'Returns available queue names and registered command IDs for schedule target selection.',
64
+ description: 'Returns available queue names and scheduler-safe command IDs for schedule target selection.',
65
65
  methods: {
66
66
  GET: {
67
67
  operationId: 'listScheduleTargets',
68
68
  summary: 'List available queues and commands',
69
- description: 'Returns all registered queue names (from module workers) and command IDs (from the command registry) that can be used as schedule targets.',
69
+ description: 'Returns all registered queue names (from module workers) and explicitly scheduler-safe command IDs that can be used as schedule targets.',
70
70
  responses: [
71
71
  {
72
72
  status: 200,
@@ -83,6 +83,14 @@ function toDate(value: Date | string | null | undefined): Date | null {
83
83
  return value instanceof Date ? value : new Date(value)
84
84
  }
85
85
 
86
+ function resolveCommandActorUserId(ctx: CommandRuntimeContext): string | null {
87
+ const auth = ctx.auth
88
+ if (!auth) return null
89
+ if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId.trim()
90
+ if (auth.isApiKey) return null
91
+ return typeof auth.sub === 'string' && auth.sub.trim().length > 0 ? auth.sub.trim() : null
92
+ }
93
+
86
94
  /**
87
95
  * Build a full create seed (including the original id and Date-coerced timestamps)
88
96
  * from a snapshot. Shared by `materializeScheduleFromSnapshot` (delete-undo) and the
@@ -223,7 +231,7 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
223
231
  sourceType: input.sourceType ?? 'user',
224
232
  sourceModule: input.sourceModule ?? null,
225
233
  nextRunAt,
226
- createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,
234
+ createdByUserId: resolveCommandActorUserId(ctx),
227
235
  createdAt: new Date(),
228
236
  updatedAt: new Date(),
229
237
  })
@@ -353,7 +361,7 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
353
361
  }
354
362
 
355
363
  schedule.updatedAt = new Date()
356
- schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null
364
+ schedule.updatedByUserId = resolveCommandActorUserId(ctx)
357
365
 
358
366
  await em.flush()
359
367
 
@@ -444,7 +452,7 @@ const deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {
444
452
  // Soft delete
445
453
  schedule.deletedAt = new Date()
446
454
  schedule.updatedAt = new Date()
447
- schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null
455
+ schedule.updatedByUserId = resolveCommandActorUserId(ctx)
448
456
 
449
457
  await em.flush()
450
458
 
@@ -7,19 +7,38 @@ import {
7
7
  scheduleTriggerSchema,
8
8
  scheduleRunsQuerySchema,
9
9
  } from '../validators'
10
- import { registerCommand } from '@open-mercato/shared/lib/commands'
11
- import type { CommandHandler } from '@open-mercato/shared/lib/commands'
10
+ import { registerCommand } from '@open-mercato/shared/lib/commands/registry'
11
+ import type { CommandHandler } from '@open-mercato/shared/lib/commands/types'
12
+ import {
13
+ clearSchedulerSafeCommandsForTests,
14
+ registerSchedulerSafeCommands,
15
+ } from '../../lib/scheduler-safe-commands'
12
16
 
13
- // Register a test command for validation tests
14
- const testCommand: CommandHandler<any, any> = {
17
+ // Register test commands for validation tests
18
+ const testCommand: CommandHandler<unknown, { ok: boolean }> = {
15
19
  id: 'test.command.for.validators',
16
20
  async execute() {
17
21
  return { ok: true }
18
22
  },
19
23
  }
20
24
 
25
+ const schedulableTestCommand: CommandHandler<unknown, { ok: boolean }> = {
26
+ id: 'test.command.schedulable',
27
+ async execute() {
28
+ return { ok: true }
29
+ },
30
+ }
31
+
21
32
  beforeAll(() => {
33
+ clearSchedulerSafeCommandsForTests()
22
34
  registerCommand(testCommand)
35
+ registerCommand(schedulableTestCommand)
36
+ registerSchedulerSafeCommands([
37
+ {
38
+ commandId: 'test.command.schedulable',
39
+ requiredFeatures: ['scheduler.jobs.manage'],
40
+ },
41
+ ])
23
42
  })
24
43
 
25
44
  const tenantId = '123e4567-e89b-12d3-a456-426614174000'
@@ -56,7 +75,7 @@ describe('scheduleCreateSchema', () => {
56
75
  scheduleValue: '1h',
57
76
  timezone: 'America/New_York',
58
77
  targetType: 'command',
59
- targetCommand: 'test.command.for.validators',
78
+ targetCommand: 'test.command.schedulable',
60
79
  targetPayload: { foo: 'bar' },
61
80
  isEnabled: true,
62
81
  })
@@ -68,7 +87,7 @@ describe('scheduleCreateSchema', () => {
68
87
  expect(result.scheduleType).toBe('interval')
69
88
  expect(result.scheduleValue).toBe('1h')
70
89
  expect(result.targetType).toBe('command')
71
- expect(result.targetCommand).toBe('test.command.for.validators')
90
+ expect(result.targetCommand).toBe('test.command.schedulable')
72
91
  })
73
92
 
74
93
  it('should accept valid tenant-scoped schedule', () => {
@@ -271,6 +290,19 @@ describe('scheduleCreateSchema', () => {
271
290
  })
272
291
  ).toThrow(/Command does not exist/)
273
292
  })
293
+
294
+ it('should reject a registered command that did not opt into scheduler execution', () => {
295
+ expect(() =>
296
+ scheduleCreateSchema.parse({
297
+ name: 'Unsafe command',
298
+ scopeType: 'system',
299
+ scheduleType: 'cron',
300
+ scheduleValue: '0 0 * * *',
301
+ targetType: 'command',
302
+ targetCommand: 'test.command.for.validators',
303
+ })
304
+ ).toThrow(/Command is not schedulable/)
305
+ })
274
306
  })
275
307
 
276
308
  describe('schedule validation', () => {
@@ -486,11 +518,11 @@ describe('scheduleUpdateSchema', () => {
486
518
  const result = scheduleUpdateSchema.parse({
487
519
  id: scheduleId,
488
520
  targetType: 'command',
489
- targetCommand: 'test.command.for.validators',
521
+ targetCommand: 'test.command.schedulable',
490
522
  })
491
523
 
492
524
  expect(result.targetType).toBe('command')
493
- expect(result.targetCommand).toBe('test.command.for.validators')
525
+ expect(result.targetCommand).toBe('test.command.schedulable')
494
526
  })
495
527
 
496
528
  it('should reject non-existent command on update', () => {
@@ -1,8 +1,9 @@
1
1
  import { z } from 'zod'
2
2
  import { validateCron } from '../lib/cronParser'
3
3
  import { validateInterval } from '../lib/intervalParser'
4
- import { commandRegistry } from '@open-mercato/shared/lib/commands'
4
+ import { commandRegistry } from '@open-mercato/shared/lib/commands/registry'
5
5
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
6
+ import { isSchedulerSafeCommandId } from '../lib/scheduler-safe-commands'
6
7
 
7
8
  /**
8
9
  * Validate that a command exists in the command registry
@@ -11,6 +12,10 @@ function validateCommandExists(commandId: string): boolean {
11
12
  return commandRegistry.has(commandId)
12
13
  }
13
14
 
15
+ function validateCommandIsSchedulable(commandId: string): boolean {
16
+ return isSchedulerSafeCommandId(commandId)
17
+ }
18
+
14
19
  /**
15
20
  * Base schedule fields
16
21
  */
@@ -103,6 +108,18 @@ export const scheduleCreateSchema = scheduleBaseSchema
103
108
  path: ['targetCommand'],
104
109
  }
105
110
  )
111
+ .refine(
112
+ (data) => {
113
+ if (data.targetType === 'command' && data.targetCommand) {
114
+ return validateCommandIsSchedulable(data.targetCommand)
115
+ }
116
+ return true
117
+ },
118
+ {
119
+ message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',
120
+ path: ['targetCommand'],
121
+ }
122
+ )
106
123
 
107
124
  /**
108
125
  * Update schedule schema (all fields optional except id)
@@ -185,6 +202,18 @@ export const scheduleUpdateSchema = z.object({
185
202
  path: ['targetCommand'],
186
203
  }
187
204
  )
205
+ .refine(
206
+ (data) => {
207
+ if (data.targetCommand) {
208
+ return validateCommandIsSchedulable(data.targetCommand)
209
+ }
210
+ return true
211
+ },
212
+ {
213
+ message: 'Command is not schedulable. Only scheduler-safe commands can be used as schedule targets.',
214
+ path: ['targetCommand'],
215
+ }
216
+ )
188
217
 
189
218
  /**
190
219
  * Delete schedule schema
@@ -0,0 +1,98 @@
1
+ export type SchedulerSafeCommandDefinition = {
2
+ commandId: string
3
+ requiredFeatures: readonly [string, ...string[]]
4
+ }
5
+
6
+ export type SchedulerCommandRbacService = {
7
+ userHasAllFeatures?: (
8
+ userId: string,
9
+ required: readonly string[],
10
+ scope: { tenantId: string | null; organizationId: string | null }
11
+ ) => Promise<boolean>
12
+ }
13
+
14
+ const schedulerSafeCommands = new Map<string, SchedulerSafeCommandDefinition>()
15
+
16
+ function normalizeCommandId(commandId: unknown): string | null {
17
+ if (typeof commandId !== 'string') return null
18
+ const trimmed = commandId.trim()
19
+ return trimmed.length > 0 ? trimmed : null
20
+ }
21
+
22
+ function normalizeFeatures(features: readonly string[]): [string, ...string[]] | null {
23
+ const normalized = features
24
+ .map((feature) => feature.trim())
25
+ .filter((feature) => feature.length > 0)
26
+ return normalized.length > 0 ? (normalized as [string, ...string[]]) : null
27
+ }
28
+
29
+ export function registerSchedulerSafeCommands(commands: readonly SchedulerSafeCommandDefinition[]): void {
30
+ for (const command of commands) {
31
+ const commandId = normalizeCommandId(command.commandId)
32
+ const requiredFeatures = normalizeFeatures(command.requiredFeatures)
33
+ if (!commandId || !requiredFeatures) {
34
+ throw new Error('[internal] Scheduler-safe commands require a commandId and requiredFeatures')
35
+ }
36
+ schedulerSafeCommands.set(commandId, { commandId, requiredFeatures })
37
+ }
38
+ }
39
+
40
+ export function getSchedulerSafeCommand(commandId: unknown): SchedulerSafeCommandDefinition | null {
41
+ const normalized = normalizeCommandId(commandId)
42
+ if (!normalized) return null
43
+ return schedulerSafeCommands.get(normalized) ?? null
44
+ }
45
+
46
+ export function isSchedulerSafeCommandId(commandId: unknown): boolean {
47
+ return getSchedulerSafeCommand(commandId) !== null
48
+ }
49
+
50
+ export function listSchedulerSafeCommands(): SchedulerSafeCommandDefinition[] {
51
+ return Array.from(schedulerSafeCommands.values()).sort((a, b) => a.commandId.localeCompare(b.commandId))
52
+ }
53
+
54
+ export async function assertSchedulerSafeCommandAuthorized(params: {
55
+ commandId: unknown
56
+ actorUserId: string | null | undefined
57
+ tenantId: string | null | undefined
58
+ organizationId: string | null | undefined
59
+ rbacService: SchedulerCommandRbacService
60
+ }): Promise<SchedulerSafeCommandDefinition> {
61
+ const command = getSchedulerSafeCommand(params.commandId)
62
+ if (!command) {
63
+ throw new Error('Scheduled command is not allowed')
64
+ }
65
+
66
+ const actorUserId = normalizeCommandId(params.actorUserId)
67
+ if (!actorUserId) {
68
+ throw new Error('Scheduled command requires an authenticated creator')
69
+ }
70
+
71
+ if (typeof params.rbacService.userHasAllFeatures !== 'function') {
72
+ throw new Error('Scheduled command authorization is unavailable')
73
+ }
74
+
75
+ const authorized = await params.rbacService.userHasAllFeatures(actorUserId, command.requiredFeatures, {
76
+ tenantId: params.tenantId ?? null,
77
+ organizationId: params.organizationId ?? null,
78
+ })
79
+ if (!authorized) {
80
+ throw new Error('Scheduled command creator is not authorized')
81
+ }
82
+
83
+ return command
84
+ }
85
+
86
+ export function clearSchedulerSafeCommandsForTests(): void {
87
+ if (process.env.NODE_ENV !== 'test') {
88
+ throw new Error('[internal] clearSchedulerSafeCommandsForTests is test-only')
89
+ }
90
+ schedulerSafeCommands.clear()
91
+ }
92
+
93
+ registerSchedulerSafeCommands([
94
+ {
95
+ commandId: 'scheduler.test.echo',
96
+ requiredFeatures: ['scheduler.jobs.manage'],
97
+ },
98
+ ])
@@ -2,6 +2,10 @@ import { LocalSchedulerService } from '../localSchedulerService'
2
2
  import type { EntityManager } from '@mikro-orm/core'
3
3
  import type { Queue } from '@open-mercato/queue'
4
4
  import { ScheduledJob } from '../../data/entities.js'
5
+ import {
6
+ clearSchedulerSafeCommandsForTests,
7
+ registerSchedulerSafeCommands,
8
+ } from '../../lib/scheduler-safe-commands'
5
9
  import { createLogger } from '@open-mercato/shared/lib/logger'
6
10
 
7
11
  jest.mock('@open-mercato/shared/lib/logger', () => {
@@ -54,12 +58,19 @@ describe('LocalSchedulerService', () => {
54
58
  let mockForkedEm: jest.Mocked<EntityManager>
55
59
  let mockQueue: jest.Mocked<Queue>
56
60
  let mockQueueFactory: jest.Mock
57
- let mockRbacService: { tenantHasFeature: jest.Mock }
61
+ let mockRbacService: { tenantHasFeature: jest.Mock; userHasAllFeatures: jest.Mock }
58
62
  let mockLockStrategy: { runWithLock: jest.Mock }
59
63
 
60
64
  beforeEach(() => {
61
65
  jest.clearAllMocks()
62
66
  jest.useFakeTimers()
67
+ clearSchedulerSafeCommandsForTests()
68
+ registerSchedulerSafeCommands([
69
+ {
70
+ commandId: 'test:command',
71
+ requiredFeatures: ['scheduler.jobs.manage'],
72
+ },
73
+ ])
63
74
 
64
75
  // Create mock queue
65
76
  mockQueue = {
@@ -84,6 +95,7 @@ describe('LocalSchedulerService', () => {
84
95
  // Create mock RBAC service
85
96
  mockRbacService = {
86
97
  tenantHasFeature: jest.fn(),
98
+ userHasAllFeatures: jest.fn().mockResolvedValue(true),
87
99
  }
88
100
 
89
101
  // Create service
@@ -283,6 +295,7 @@ describe('LocalSchedulerService', () => {
283
295
  targetType: 'command',
284
296
  targetCommand: 'test:command',
285
297
  targetQueue: null,
298
+ createdByUserId: 'user-1',
286
299
  })
287
300
 
288
301
  mockForkedEm.find.mockResolvedValue([schedule])
@@ -302,8 +315,85 @@ describe('LocalSchedulerService', () => {
302
315
  tenantId: null,
303
316
  organizationId: null,
304
317
  }),
318
+ ctx: expect.objectContaining({
319
+ auth: expect.objectContaining({
320
+ sub: 'user-1',
321
+ userId: 'user-1',
322
+ tenantId: null,
323
+ orgId: null,
324
+ }),
325
+ }),
326
+ })
327
+ )
328
+ expect(mockRbacService.userHasAllFeatures).toHaveBeenCalledWith(
329
+ 'user-1',
330
+ ['scheduler.jobs.manage'],
331
+ { tenantId: null, organizationId: null }
332
+ )
333
+ })
334
+
335
+ it('should reject command target that is not scheduler safe', async () => {
336
+ const schedule = createSchedule({
337
+ targetType: 'command',
338
+ targetCommand: 'unsafe.command',
339
+ targetQueue: null,
340
+ createdByUserId: 'user-1',
341
+ })
342
+
343
+ mockForkedEm.find.mockResolvedValue([schedule])
344
+ mockForkedEm.findOne.mockResolvedValue({ ...schedule })
345
+ mockLockStrategy.runWithLock.mockImplementation(async (_key: string, fn: () => Promise<unknown>) => {
346
+ await fn()
347
+ return { acquired: true }
348
+ })
349
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation()
350
+
351
+ await service.start()
352
+
353
+ expect(mockCommandBusInstance.execute).not.toHaveBeenCalled()
354
+ expect(mockEmitSchedulerEvent).toHaveBeenCalledWith(
355
+ 'scheduler.job.failed',
356
+ expect.objectContaining({
357
+ id: 'test-1',
358
+ error: 'Scheduled command is not allowed',
359
+ })
360
+ )
361
+ consoleErrorSpy.mockRestore()
362
+ })
363
+
364
+ it('should reject command target when the schedule creator lacks required features', async () => {
365
+ const schedule = createSchedule({
366
+ targetType: 'command',
367
+ targetCommand: 'test:command',
368
+ targetQueue: null,
369
+ createdByUserId: 'user-1',
370
+ })
371
+
372
+ mockRbacService.userHasAllFeatures.mockResolvedValueOnce(false)
373
+ mockForkedEm.find.mockResolvedValue([schedule])
374
+ mockForkedEm.findOne.mockResolvedValue({ ...schedule })
375
+ mockLockStrategy.runWithLock.mockImplementation(async (_key: string, fn: () => Promise<unknown>) => {
376
+ await fn()
377
+ return { acquired: true }
378
+ })
379
+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation()
380
+
381
+ await service.start()
382
+
383
+ expect(mockCommandBusInstance.execute).not.toHaveBeenCalled()
384
+ expect(mockRbacService.userHasAllFeatures).toHaveBeenCalledWith(
385
+ 'user-1',
386
+ ['scheduler.jobs.manage'],
387
+ { tenantId: null, organizationId: null }
388
+ )
389
+ expect(mockEmitSchedulerEvent).toHaveBeenCalledWith(
390
+ 'scheduler.job.failed',
391
+ expect.objectContaining({
392
+ id: 'test-1',
393
+ error: 'Scheduled command creator is not authorized',
305
394
  })
306
395
  )
396
+ consoleErrorSpy.mockRestore()
307
397
  })
308
398
 
309
399
  it('should emit started event', async () => {
@@ -587,6 +677,7 @@ describe('LocalSchedulerService', () => {
587
677
  scopeType: 'organization',
588
678
  tenantId: 'tenant-1',
589
679
  organizationId: 'org-1',
680
+ createdByUserId: 'user-1',
590
681
  })
591
682
 
592
683
  mockForkedEm.find.mockResolvedValue([schedule])
@@ -608,6 +699,11 @@ describe('LocalSchedulerService', () => {
608
699
  organizationId: 'org-1',
609
700
  }),
610
701
  ctx: expect.objectContaining({
702
+ auth: expect.objectContaining({
703
+ sub: 'user-1',
704
+ tenantId: 'tenant-1',
705
+ orgId: 'org-1',
706
+ }),
611
707
  selectedOrganizationId: 'org-1',
612
708
  organizationIds: ['org-1'],
613
709
  }),