@open-mercato/scheduler 0.6.4-develop.4299.1.af24e08431 → 0.6.4-develop.4305.1.efaf0ebab1
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.
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js +1 -3
- package/dist/modules/scheduler/api/jobs/[id]/executions/route.js.map +2 -2
- package/dist/modules/scheduler/api/jobs/buildFilters.js +1 -1
- package/dist/modules/scheduler/api/jobs/buildFilters.js.map +2 -2
- package/dist/modules/scheduler/api/jobs/route.js +1 -4
- package/dist/modules/scheduler/api/jobs/route.js.map +2 -2
- package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js +1 -3
- package/dist/modules/scheduler/api/queue-jobs/[jobId]/route.js.map +2 -2
- package/dist/modules/scheduler/api/trigger/route.js +1 -3
- package/dist/modules/scheduler/api/trigger/route.js.map +2 -2
- package/dist/modules/scheduler/commands/jobs.js +15 -0
- package/dist/modules/scheduler/commands/jobs.js.map +2 -2
- package/package.json +5 -5
- package/src/modules/scheduler/api/jobs/[id]/executions/route.ts +3 -4
- package/src/modules/scheduler/api/jobs/__tests__/scope-filter.test.ts +17 -5
- package/src/modules/scheduler/api/jobs/buildFilters.ts +2 -4
- package/src/modules/scheduler/api/jobs/route.ts +4 -5
- package/src/modules/scheduler/api/queue-jobs/[jobId]/route.ts +3 -4
- package/src/modules/scheduler/api/trigger/route.ts +3 -4
- package/src/modules/scheduler/commands/__tests__/jobs.system-scope.test.ts +122 -0
- package/src/modules/scheduler/commands/jobs.ts +27 -0
|
@@ -33,9 +33,7 @@ async function GET(req, { params }) {
|
|
|
33
33
|
if (!schedule) {
|
|
34
34
|
return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
|
|
35
35
|
}
|
|
36
|
-
const isSuperAdmin =
|
|
37
|
-
(role) => typeof role === "string" && role.trim().toLowerCase() === "superadmin"
|
|
38
|
-
);
|
|
36
|
+
const isSuperAdmin = auth.isSuperAdmin === true;
|
|
39
37
|
if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
|
|
40
38
|
return NextResponse.json({ error: translate("scheduler.error.access_denied", "Access denied") }, { status: 403 });
|
|
41
39
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/scheduler/api/jobs/%5Bid%5D/executions/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Verify schedule exists and user has access (with tenant/org scope filter)\n const findFilter: Record<string, unknown> = {\n id: scheduleId,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require
|
|
5
|
-
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAG7B,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AASA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAuB,IAAI;AAEhD,QAAM,aAAa,OAAO;AAE1B,MAAI;AAEF,UAAM,aAAsC;AAAA,MAC1C,IAAI;AAAA,MACJ,WAAW;AAAA,IACb;AAGA,QAAI,KAAK,UAAU;AACjB,iBAAW,WAAW,KAAK;AAAA,IAC7B;AACA,QAAI,KAAK,OAAO;AACd,iBAAW,iBAAiB,KAAK;AAAA,IACnC;AAEA,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,UAAU;AAE1D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,oBAAoB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACnH;
|
|
4
|
+
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { ScheduledJob } from '../../../../data/entities.js'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/jobs/[id]/executions\n * Fetch execution history for a schedule from BullMQ\n * \n * Returns jobs from the scheduler-execution queue filtered by scheduleId.\n * This replaces the old /api/scheduler/runs endpoint that used the database table.\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { id: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n const scheduleId = params.id\n\n try {\n // Verify schedule exists and user has access (with tenant/org scope filter)\n const findFilter: Record<string, unknown> = {\n id: scheduleId,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require super-admin. Use the\n // immutable `isSuperAdmin` flag \u2014 never compare mutable/spoofable role names.\n const isSuperAdmin = auth.isSuperAdmin === true\n if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.async_strategy_required', 'Execution history requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.async_strategy_hint', 'Please set QUEUE_STRATEGY=async to view execution history'),\n items: [],\n }, { status: 400 })\n }\n\n // Fetch jobs from BullMQ scheduler-execution queue\n const { Queue } = await import('bullmq')\n const queue = new Queue('scheduler-execution', { connection: { url: getRedisUrlOrThrow('QUEUE') } })\n\n try {\n // Validate query params with Zod schema\n const queryResult = executionsQuerySchema.safeParse({\n pageSize: req.nextUrl.searchParams.get('pageSize') ?? undefined,\n })\n const limit = queryResult.success ? queryResult.data.pageSize : 20\n\n const [completed, failed, active, waiting, delayed] = await Promise.all([\n queue.getCompleted(0, limit - 1),\n queue.getFailed(0, limit - 1),\n queue.getActive(0, limit - 1),\n queue.getWaiting(0, limit - 1),\n queue.getDelayed(0, limit - 1),\n ])\n\n // Combine all jobs and filter by scheduleId\n const allJobs = [...completed, ...failed, ...active, ...waiting, ...delayed]\n type BullJobData = { payload?: { scheduleId?: string; triggerType?: string; triggeredByUserId?: string }; scheduleId?: string; triggerType?: string; triggeredByUserId?: string }\n\n const filteredJobs = allJobs\n .filter(job => {\n const data = job.data as BullJobData | undefined\n return data?.payload?.scheduleId === scheduleId || data?.scheduleId === scheduleId\n })\n .slice(0, limit)\n\n // Get state for each job (parallel)\n const jobsWithState = await Promise.all(\n filteredJobs.map(async (job) => {\n const state = await job.getState()\n const data = job.data as BullJobData | undefined\n \n return {\n id: job.id,\n scheduleId: data?.payload?.scheduleId || data?.scheduleId,\n startedAt: job.processedOn ? new Date(job.processedOn).toISOString() : new Date(job.timestamp).toISOString(),\n finishedAt: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n status: state === 'completed' ? 'completed' : state === 'failed' ? 'failed' : state === 'active' ? 'running' : 'waiting',\n triggerType: data?.payload?.triggerType || data?.triggerType || 'scheduled',\n triggeredByUserId: data?.payload?.triggeredByUserId || data?.triggeredByUserId || null,\n errorMessage: job.failedReason || null,\n errorStack: job.stacktrace ? job.stacktrace.join('\\n') : null,\n durationMs: (job.finishedOn && job.processedOn) ? (job.finishedOn - job.processedOn) : null,\n queueJobId: job.id,\n queueName: 'scheduler-execution',\n attemptsMade: job.attemptsMade,\n result: job.returnvalue,\n }\n })\n )\n\n // Sort by startedAt descending (most recent first)\n jobsWithState.sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime())\n\n return NextResponse.json({\n items: jobsWithState,\n total: jobsWithState.length,\n page: 1,\n pageSize: limit,\n })\n } finally {\n await queue.close()\n }\n\n } catch (error: unknown) {\n console.error('[scheduler:executions] Error fetching execution history:', error)\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_executions_failed', 'Failed to fetch execution history') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst executionsQuerySchema = z.object({\n pageSize: z.coerce.number().int().min(1).max(100).default(20),\n})\n\n// Response schemas\nconst executionItemSchema = z.object({\n id: z.string(),\n scheduleId: z.string().uuid(),\n startedAt: z.string(),\n finishedAt: z.string().nullable(),\n status: z.enum(['running', 'completed', 'failed', 'waiting']),\n triggerType: z.enum(['scheduled', 'manual']),\n triggeredByUserId: z.string().uuid().nullable(),\n errorMessage: z.string().nullable(),\n errorStack: z.string().nullable(),\n durationMs: z.number().nullable(),\n queueJobId: z.string(),\n queueName: z.string(),\n attemptsMade: z.number(),\n result: z.unknown().nullable(),\n})\n\nconst executionsResponseSchema = z.object({\n items: z.array(executionItemSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n items: z.array(z.any()).optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Get execution history',\n description: 'Fetches recent execution history for a scheduled job from BullMQ.',\n methods: {\n GET: {\n operationId: 'getScheduleExecutions',\n summary: 'Get execution history for a schedule',\n description: 'Fetch recent executions from BullMQ for a scheduled job. Requires QUEUE_STRATEGY=async.',\n query: executionsQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Execution history',\n schema: executionsResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Schedule not found', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAG7B,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AASA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAuB,IAAI;AAEhD,QAAM,aAAa,OAAO;AAE1B,MAAI;AAEF,UAAM,aAAsC;AAAA,MAC1C,IAAI;AAAA,MACJ,WAAW;AAAA,IACb;AAGA,QAAI,KAAK,UAAU;AACjB,iBAAW,WAAW,KAAK;AAAA,IAC7B;AACA,QAAI,KAAK,OAAO;AACd,iBAAW,iBAAiB,KAAK;AAAA,IACnC;AAEA,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,UAAU;AAE1D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,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ACf,UAAU,EAAE,OAAO;AACrB,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAAA,EAChB,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,SAAS;AACnC,CAAC;AAGM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS;AAAA,IACP,KAAK;AAAA,MACH,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,oBAAoB;AAAA,QACxF,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -6,7 +6,7 @@ async function buildSchedulerJobsFilters(query, ctx) {
|
|
|
6
6
|
filters.id = { $eq: "00000000-0000-0000-0000-000000000000" };
|
|
7
7
|
return filters;
|
|
8
8
|
}
|
|
9
|
-
const isSuperAdmin =
|
|
9
|
+
const isSuperAdmin = ctx.auth?.isSuperAdmin === true;
|
|
10
10
|
const rawOrgIds = Array.isArray(ctx.organizationIds) ? ctx.organizationIds.filter((id) => typeof id === "string" && id.trim().length > 0) : [];
|
|
11
11
|
const orgIdsForVisibility = rawOrgIds.length > 0 ? rawOrgIds : ctx.auth?.orgId ? [ctx.auth.orgId] : [];
|
|
12
12
|
const visibilityBranches = [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/scheduler/api/jobs/buildFilters.ts"],
|
|
4
|
-
"sourcesContent": ["import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\n\nexport type SchedulerJobsFilterContext = {\n auth?: {\n tenantId?: string | null\n orgId?: string | null\n
|
|
5
|
-
"mappings": "AAAA,SAAS,yBAAyB;AAoBlC,eAAsB,0BACpB,OACA,KACkC;AAClC,QAAM,UAAmC,CAAC;AAC1C,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,UAAU;AACb,YAAQ,KAAK,EAAE,KAAK,uCAAuC;AAC3D,WAAO;AAAA,EACT;AAEA,QAAM,
|
|
4
|
+
"sourcesContent": ["import { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\n\nexport type SchedulerJobsFilterContext = {\n auth?: {\n tenantId?: string | null\n orgId?: string | null\n isSuperAdmin?: boolean\n } | null\n organizationIds?: string[] | null\n}\n\nexport type SchedulerJobsFilterQuery = {\n id?: string\n scopeType?: string\n isEnabled?: boolean\n sourceType?: string\n sourceModule?: string\n search?: string\n}\n\nexport async function buildSchedulerJobsFilters(\n query: SchedulerJobsFilterQuery,\n ctx: SchedulerJobsFilterContext,\n): Promise<Record<string, unknown>> {\n const filters: Record<string, unknown> = {}\n const tenantId = ctx.auth?.tenantId\n if (!tenantId) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n return filters\n }\n\n const isSuperAdmin = ctx.auth?.isSuperAdmin === true\n\n const rawOrgIds = Array.isArray(ctx.organizationIds)\n ? ctx.organizationIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)\n : []\n const orgIdsForVisibility =\n rawOrgIds.length > 0 ? rawOrgIds : ctx.auth?.orgId ? [ctx.auth.orgId] : []\n\n const visibilityBranches: Record<string, unknown>[] = []\n if (orgIdsForVisibility.length === 1) {\n visibilityBranches.push({\n organization_id: { $eq: orgIdsForVisibility[0] },\n tenant_id: { $eq: tenantId },\n })\n } else if (orgIdsForVisibility.length > 1) {\n visibilityBranches.push({\n organization_id: { $in: orgIdsForVisibility },\n tenant_id: { $eq: tenantId },\n })\n }\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: tenantId },\n scope_type: { $eq: 'tenant' },\n })\n if (isSuperAdmin) {\n visibilityBranches.push({\n organization_id: { $eq: null },\n tenant_id: { $eq: null },\n scope_type: { $eq: 'system' },\n })\n }\n\n const searchNeedle = query.search?.trim()\n ? `%${escapeLikePattern(query.search.trim())}%`\n : null\n\n const visibilityOr: Record<string, unknown>[] = searchNeedle\n ? visibilityBranches.flatMap((branch) => [\n { ...branch, name: { $ilike: searchNeedle } },\n { ...branch, description: { $ilike: searchNeedle } },\n ])\n : visibilityBranches\n\n filters.$or = visibilityOr\n\n if (query.id) {\n filters.id = { $eq: query.id }\n }\n\n if (query.scopeType) {\n filters.scope_type = { $eq: query.scopeType }\n }\n\n if (query.isEnabled !== undefined) {\n filters.is_enabled = { $eq: query.isEnabled }\n }\n\n if (query.sourceType) {\n filters.source_type = { $eq: query.sourceType }\n }\n\n if (query.sourceModule) {\n filters.source_module = { $eq: query.sourceModule }\n }\n\n return filters\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAoBlC,eAAsB,0BACpB,OACA,KACkC;AAClC,QAAM,UAAmC,CAAC;AAC1C,QAAM,WAAW,IAAI,MAAM;AAC3B,MAAI,CAAC,UAAU;AACb,YAAQ,KAAK,EAAE,KAAK,uCAAuC;AAC3D,WAAO;AAAA,EACT;AAEA,QAAM,eAAe,IAAI,MAAM,iBAAiB;AAEhD,QAAM,YAAY,MAAM,QAAQ,IAAI,eAAe,IAC/C,IAAI,gBAAgB,OAAO,CAAC,OAAqB,OAAO,OAAO,YAAY,GAAG,KAAK,EAAE,SAAS,CAAC,IAC/F,CAAC;AACL,QAAM,sBACJ,UAAU,S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,EAC9C;AAEA,MAAI,MAAM,cAAc,QAAW;AACjC,YAAQ,aAAa,EAAE,KAAK,MAAM,UAAU;AAAA,EAC9C;AAEA,MAAI,MAAM,YAAY;AACpB,YAAQ,cAAc,EAAE,KAAK,MAAM,WAAW;AAAA,EAChD;AAEA,MAAI,MAAM,cAAc;AACtB,YAAQ,gBAAgB,EAAE,KAAK,MAAM,aAAa;AAAA,EACpD;AAEA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -103,10 +103,7 @@ const crud = makeCrudRoute({
|
|
|
103
103
|
let organizationId = raw.organizationId;
|
|
104
104
|
let tenantId = raw.tenantId;
|
|
105
105
|
if (scopeType === "system") {
|
|
106
|
-
|
|
107
|
-
(role) => typeof role === "string" && role.trim().toLowerCase() === "superadmin"
|
|
108
|
-
);
|
|
109
|
-
if (!isSuperAdmin) {
|
|
106
|
+
if (ctx.auth?.isSuperAdmin !== true) {
|
|
110
107
|
throw new CrudHttpError(403, { error: "System-scoped schedules require superadmin privileges" });
|
|
111
108
|
}
|
|
112
109
|
organizationId = null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/scheduler/api/jobs/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveCrudRecordId } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../../data/entities.js'\nimport {\n scheduleCreateSchema,\n scheduleUpdateSchema,\n scheduleDeleteSchema,\n scheduleListQuerySchema,\n} from '../../data/validators.js'\nimport { buildSchedulerJobsFilters } from './buildFilters.js'\nimport {\n createSchedulerCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi.js'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['scheduler.jobs.view'] },\n POST: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: ScheduledJob,\n idField: 'id',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n indexer: { entityType: 'scheduler:scheduled_job' },\n list: {\n entityId: 'scheduler:scheduled_job',\n schema: scheduleListQuerySchema,\n fields: [\n 'id',\n 'name',\n 'description',\n 'scope_type',\n 'organization_id',\n 'tenant_id',\n 'schedule_type',\n 'schedule_value',\n 'timezone',\n 'target_type',\n 'target_queue',\n 'target_command',\n 'target_payload',\n 'require_feature',\n 'is_enabled',\n 'last_run_at',\n 'next_run_at',\n 'source_type',\n 'source_module',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'name',\n nextRunAt: 'next_run_at',\n lastRunAt: 'last_run_at',\n createdAt: 'created_at',\n },\n omitAutomaticTenantOrgScope: true,\n transformItem: (item: Record<string, unknown>) => {\n if (!item) return item\n return {\n id: item.id,\n name: item.name,\n description: item.description,\n scopeType: item.scope_type,\n organizationId: item.organization_id,\n tenantId: item.tenant_id,\n scheduleType: item.schedule_type,\n scheduleValue: item.schedule_value,\n timezone: item.timezone,\n targetType: item.target_type,\n targetQueue: item.target_queue,\n targetCommand: item.target_command,\n targetPayload: item.target_payload,\n requireFeature: item.require_feature,\n isEnabled: item.is_enabled,\n lastRunAt: item.last_run_at,\n nextRunAt: item.next_run_at,\n sourceType: item.source_type,\n sourceModule: item.source_module,\n createdAt: item.created_at,\n updatedAt: item.updated_at,\n }\n },\n buildFilters: buildSchedulerJobsFilters,\n },\n actions: {\n create: {\n commandId: 'scheduler.jobs.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n // Auto-populate organizationId and tenantId based on scopeType\n const scopeType = raw.scopeType\n let organizationId = raw.organizationId\n let tenantId = raw.tenantId\n \n if (scopeType === 'system') {\n // System scope requires
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,gBAAgB;AAAA,EACpB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,qBAAqB,EAAE;AAAA,EACnE,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAAA,EACtE,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAAA,EACrE,QAAQ,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AAC1E;AAEO,MAAM,WAAW;AAExB,MAAM,OAAO,cAAc;AAAA,EACzB,UAAU;AAAA,EACV,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,aAAa;AAAA,IACb,iBAAiB;AAAA,EACnB;AAAA,EACA,SAAS,EAAE,YAAY,0BAA0B;AAAA,EACjD,MAAM;AAAA,IACJ,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,cAAc;AAAA,MACZ,MAAM;AAAA,MACN,WAAW;AAAA,MACX,WAAW;AAAA,MACX,WAAW;AAAA,IACb;AAAA,IACA,6BAA6B;AAAA,IAC7B,eAAe,CAAC,SAAkC;AAChD,UAAI,CAAC,KAAM,QAAO;AAClB,aAAO;AAAA,QACL,IAAI,KAAK;AAAA,QACT,MAAM,KAAK;AAAA,QACX,aAAa,KAAK;AAAA,QAClB,WAAW,KAAK;AAAA,QAChB,gBAAgB,KAAK;AAAA,QACrB,UAAU,KAAK;AAAA,QACf,cAAc,KAAK;AAAA,QACnB,eAAe,KAAK;AAAA,QACpB,UAAU,KAAK;AAAA,QACf,YAAY,KAAK;AAAA,QACjB,aAAa,KAAK;AAAA,QAClB,eAAe,KAAK;AAAA,QACpB,eAAe,KAAK;AAAA,QACpB,gBAAgB,KAAK;AAAA,QACrB,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK;AAAA,QAChB,YAAY,KAAK;AAAA,QACjB,cAAc,KAAK;AAAA,QACnB,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK;AAAA,MAClB;AAAA,IACF;AAAA,IACA,cAAc;AAAA,EAChB;AAAA,EACA,SAAS;AAAA,IACP,QAAQ;AAAA,MACN,WAAW;AAAA,MACX,QAAQ;AAAA,MACR,UAAU,OAAO,EAAE,KAAK,IAAI,MAAM;AAEhC,cAAM,YAAY,IAAI;AACtB,YAAI,iBAAiB,IAAI;AACzB,YAAI,WAAW,IAAI;AAEnB,YAAI,cAAc,UAAU;
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { resolveCrudRecordId } from '@open-mercato/shared/lib/api/scoped'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { ScheduledJob } from '../../data/entities.js'\nimport {\n scheduleCreateSchema,\n scheduleUpdateSchema,\n scheduleDeleteSchema,\n scheduleListQuerySchema,\n} from '../../data/validators.js'\nimport { buildSchedulerJobsFilters } from './buildFilters.js'\nimport {\n createSchedulerCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi.js'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['scheduler.jobs.view'] },\n POST: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['scheduler.jobs.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: ScheduledJob,\n idField: 'id',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n indexer: { entityType: 'scheduler:scheduled_job' },\n list: {\n entityId: 'scheduler:scheduled_job',\n schema: scheduleListQuerySchema,\n fields: [\n 'id',\n 'name',\n 'description',\n 'scope_type',\n 'organization_id',\n 'tenant_id',\n 'schedule_type',\n 'schedule_value',\n 'timezone',\n 'target_type',\n 'target_queue',\n 'target_command',\n 'target_payload',\n 'require_feature',\n 'is_enabled',\n 'last_run_at',\n 'next_run_at',\n 'source_type',\n 'source_module',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'name',\n nextRunAt: 'next_run_at',\n lastRunAt: 'last_run_at',\n createdAt: 'created_at',\n },\n omitAutomaticTenantOrgScope: true,\n transformItem: (item: Record<string, unknown>) => {\n if (!item) return item\n return {\n id: item.id,\n name: item.name,\n description: item.description,\n scopeType: item.scope_type,\n organizationId: item.organization_id,\n tenantId: item.tenant_id,\n scheduleType: item.schedule_type,\n scheduleValue: item.schedule_value,\n timezone: item.timezone,\n targetType: item.target_type,\n targetQueue: item.target_queue,\n targetCommand: item.target_command,\n targetPayload: item.target_payload,\n requireFeature: item.require_feature,\n isEnabled: item.is_enabled,\n lastRunAt: item.last_run_at,\n nextRunAt: item.next_run_at,\n sourceType: item.source_type,\n sourceModule: item.source_module,\n createdAt: item.created_at,\n updatedAt: item.updated_at,\n }\n },\n buildFilters: buildSchedulerJobsFilters,\n },\n actions: {\n create: {\n commandId: 'scheduler.jobs.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n // Auto-populate organizationId and tenantId based on scopeType\n const scopeType = raw.scopeType\n let organizationId = raw.organizationId\n let tenantId = raw.tenantId\n \n if (scopeType === 'system') {\n // System scope requires super-admin. Use the immutable `isSuperAdmin`\n // flag (derived from RoleAcl/UserAcl) \u2014 never compare role names, which\n // are tenant-mutable and spoofable.\n if (ctx.auth?.isSuperAdmin !== true) {\n throw new CrudHttpError(403, { error: 'System-scoped schedules require superadmin privileges' })\n }\n // System scope: no org/tenant\n organizationId = null\n tenantId = null\n } else if (scopeType === 'organization') {\n // Organization scope: use auth context (orgId and tenantId)\n organizationId = ctx.auth?.orgId ?? null\n tenantId = ctx.auth?.tenantId ?? null\n } else if (scopeType === 'tenant') {\n // Tenant scope: use auth context tenantId only\n organizationId = null\n tenantId = ctx.auth?.tenantId ?? null\n }\n \n const parsed = scheduleCreateSchema.parse({\n ...raw,\n organizationId,\n tenantId,\n })\n return parsed\n },\n response: ({ result }) => ({\n id: result?.id ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: 'scheduler.jobs.update',\n schema: rawBodySchema,\n mapInput: async ({ raw }) => {\n const parsed = scheduleUpdateSchema.parse(raw)\n return parsed\n },\n response: () => ({ ok: true }),\n },\n delete: {\n commandId: 'scheduler.jobs.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id = resolveCrudRecordId(parsed, ctx, translate)\n if (!id) {\n throw new CrudHttpError(400, { \n error: translate('scheduler.errors.id_required', 'Schedule id is required') \n })\n }\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n})\n\nexport const { GET, POST, PUT, DELETE } = crud\n\n// Response schemas\nconst scheduledJobListItemSchema = z.object({\n id: z.string().uuid(),\n name: z.string(),\n description: z.string().nullable(),\n scopeType: z.enum(['system', 'organization', 'tenant']),\n organizationId: z.string().uuid().nullable(),\n tenantId: z.string().uuid().nullable(),\n scheduleType: z.enum(['cron', 'interval']),\n scheduleValue: z.string(),\n timezone: z.string(),\n targetType: z.enum(['queue', 'command']),\n targetQueue: z.string().nullable(),\n targetCommand: z.string().nullable(),\n targetPayload: z.record(z.string(), z.unknown()).nullable(),\n requireFeature: z.string().nullable(),\n isEnabled: z.boolean(),\n lastRunAt: z.string().nullable(),\n nextRunAt: z.string().nullable(),\n sourceType: z.enum(['user', 'module']),\n sourceModule: z.string().nullable(),\n createdAt: z.string(),\n updatedAt: z.string(),\n})\n\n// OpenAPI specification\nexport const openApi = createSchedulerCrudOpenApi({\n resourceName: 'ScheduledJob',\n pluralName: 'ScheduledJobs',\n querySchema: scheduleListQuerySchema,\n listResponseSchema: createPagedListResponseSchema(scheduledJobListItemSchema),\n create: {\n schema: scheduleCreateSchema,\n description: 'Creates a new scheduled job with cron or interval-based scheduling.',\n },\n update: {\n schema: scheduleUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Updates an existing scheduled job by ID.',\n },\n del: {\n schema: scheduleDeleteSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Deletes a scheduled job by ID.',\n },\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EA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AAE,SAAS;AAAA,EACpC,WAAW,EAAE,QAAQ;AAAA,EACrB,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,YAAY,EAAE,KAAK,CAAC,QAAQ,QAAQ,CAAC;AAAA,EACrC,cAAc,EAAE,OAAO,EAAE,SAAS;AAAA,EAClC,WAAW,EAAE,OAAO;AAAA,EACpB,WAAW,EAAE,OAAO;AACtB,CAAC;AAGM,MAAM,UAAU,2BAA2B;AAAA,EAChD,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB,8BAA8B,0BAA0B;AAAA,EAC5E,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AACF,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -56,9 +56,7 @@ async function GET(req, { params }) {
|
|
|
56
56
|
const jobPayload = jobData?.payload;
|
|
57
57
|
const jobTenantId = jobData?.tenantId ?? jobPayload?.tenantId ?? null;
|
|
58
58
|
const jobOrgId = jobData?.organizationId ?? jobPayload?.organizationId ?? null;
|
|
59
|
-
const isSuperAdmin =
|
|
60
|
-
(role) => typeof role === "string" && role.trim().toLowerCase() === "superadmin"
|
|
61
|
-
);
|
|
59
|
+
const isSuperAdmin = auth.isSuperAdmin === true;
|
|
62
60
|
if (!jobTenantId && !jobOrgId && !isSuperAdmin) {
|
|
63
61
|
await queue.close();
|
|
64
62
|
return NextResponse.json({ error: translate("scheduler.error.forbidden", "Forbidden") }, { status: 403 });
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/scheduler/api/queue-jobs/%5BjobId%5D/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { getModules } from '@open-mercato/shared/lib/modules/registry'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/queue-jobs/[jobId]\n * Fetch BullMQ job details and logs\n * \n * Query params:\n * - queue: Queue name (required)\n * \n * Note: This endpoint returns job data from BullMQ directly.\n * Tenant/org isolation is enforced at the queue level (jobs contain tenant/org IDs in their data).\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { jobId: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const { jobId } = params\n\n // Validate query params with Zod schema\n const queryResult = queueJobQuerySchema.safeParse({\n queue: req.nextUrl.searchParams.get('queue') ?? undefined,\n })\n if (!queryResult.success) {\n return NextResponse.json(\n { error: translate('scheduler.error.queue_param_required', 'queue parameter required') },\n { status: 400 }\n )\n }\n const queueName = queryResult.data.queue\n\n // Validate queue name against registered module queues\n const registeredQueues = new Set(\n getModules().flatMap((m) => m.workers?.map((w) => w.queue) ?? [])\n )\n if (!registeredQueues.has(queueName)) {\n return NextResponse.json(\n { error: translate('scheduler.error.invalid_queue_name', 'Invalid queue name') },\n { status: 400 }\n )\n }\n\n try {\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.bullmq_required', 'BullMQ job logs are only available with QUEUE_STRATEGY=async'),\n available: false,\n }, { status: 400 })\n }\n\n // Fetch job from BullMQ\n const { Queue } = await import('bullmq')\n const queue = new Queue(queueName, { connection: { url: getRedisUrlOrThrow('QUEUE') } })\n\n const job = await queue.getJob(jobId)\n\n if (!job) {\n await queue.close()\n return NextResponse.json(\n { error: translate('scheduler.error.job_not_found', 'Job not found in BullMQ (may have been removed)') },\n { status: 404 }\n )\n }\n\n // Validate tenant/org access from job data\n const jobData = job.data as Record<string, unknown> | undefined\n const jobPayload = jobData?.payload as Record<string, unknown> | undefined\n\n // Resolve tenant/org IDs from job data (may be nested in payload)\n const jobTenantId = jobData?.tenantId ?? jobPayload?.tenantId ?? null\n const jobOrgId = jobData?.organizationId ?? jobPayload?.organizationId ?? null\n\n // System-scoped jobs (no tenantId/orgId) require
|
|
5
|
-
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AAEnC,SAAS,0BAA0B;AACnC,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AAG7B,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AAYA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,EAAE,MAAM,IAAI;AAGlB,QAAM,cAAc,oBAAoB,UAAU;AAAA,IAChD,OAAO,IAAI,QAAQ,aAAa,IAAI,OAAO,KAAK;AAAA,EAClD,CAAC;AACD,MAAI,CAAC,YAAY,SAAS;AACxB,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,UAAU,wCAAwC,0BAA0B,EAAE;AAAA,MACvF,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACA,QAAM,YAAY,YAAY,KAAK;AAGnC,QAAM,mBAAmB,IAAI;AAAA,IAC3B,WAAW,EAAE,QAAQ,CAAC,MAAM,EAAE,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,KAAK,CAAC,CAAC;AAAA,EAClE;AACA,MAAI,CAAC,iBAAiB,IAAI,SAAS,GAAG;AACpC,WAAO,aAAa;AAAA,MAClB,EAAE,OAAO,UAAU,sCAAsC,oBAAoB,EAAE;AAAA,MAC/E,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AAEA,MAAI;AAEF,UAAM,gBAAgB,QAAQ,IAAI,kBAAkB;AACpD,QAAI,kBAAkB,SAAS;AAC7B,aAAO,aAAa,KAAK;AAAA,QACvB,OAAO,UAAU,mCAAmC,8DAA8D;AAAA,QAClH,WAAW;AAAA,MACb,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACpB;AAGA,UAAM,EAAE,MAAM,IAAI,MAAM,OAAO,QAAQ;AACvC,UAAM,QAAQ,IAAI,MAAM,WAAW,EAAE,YAAY,EAAE,KAAK,mBAAmB,OAAO,EAAE,EAAE,CAAC;AAEvF,UAAM,MAAM,MAAM,MAAM,OAAO,KAAK;AAEpC,QAAI,CAAC,KAAK;AACR,YAAM,MAAM,MAAM;AAClB,aAAO,aAAa;AAAA,QAClB,EAAE,OAAO,UAAU,iCAAiC,iDAAiD,EAAE;AAAA,QACvG,EAAE,QAAQ,IAAI;AAAA,MAChB;AAAA,IACF;AAGA,UAAM,UAAU,IAAI;AACpB,UAAM,aAAa,SAAS;AAG5B,UAAM,cAAc,SAAS,YAAY,YAAY,YAAY;AACjE,UAAM,WAAW,SAAS,kBAAkB,YAAY,kBAAkB;
|
|
4
|
+
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { getModules } from '@open-mercato/shared/lib/modules/registry'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.view'],\n}\n\n/**\n * GET /api/scheduler/queue-jobs/[jobId]\n * Fetch BullMQ job details and logs\n * \n * Query params:\n * - queue: Queue name (required)\n * \n * Note: This endpoint returns job data from BullMQ directly.\n * Tenant/org isolation is enforced at the queue level (jobs contain tenant/org IDs in their data).\n */\nexport async function GET(\n req: NextRequest,\n { params }: { params: { jobId: string } }\n) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const { jobId } = params\n\n // Validate query params with Zod schema\n const queryResult = queueJobQuerySchema.safeParse({\n queue: req.nextUrl.searchParams.get('queue') ?? undefined,\n })\n if (!queryResult.success) {\n return NextResponse.json(\n { error: translate('scheduler.error.queue_param_required', 'queue parameter required') },\n { status: 400 }\n )\n }\n const queueName = queryResult.data.queue\n\n // Validate queue name against registered module queues\n const registeredQueues = new Set(\n getModules().flatMap((m) => m.workers?.map((w) => w.queue) ?? [])\n )\n if (!registeredQueues.has(queueName)) {\n return NextResponse.json(\n { error: translate('scheduler.error.invalid_queue_name', 'Invalid queue name') },\n { status: 400 }\n )\n }\n\n try {\n // Check if using async strategy\n const queueStrategy = process.env.QUEUE_STRATEGY || 'local'\n if (queueStrategy !== 'async') {\n return NextResponse.json({\n error: translate('scheduler.error.bullmq_required', 'BullMQ job logs are only available with QUEUE_STRATEGY=async'),\n available: false,\n }, { status: 400 })\n }\n\n // Fetch job from BullMQ\n const { Queue } = await import('bullmq')\n const queue = new Queue(queueName, { connection: { url: getRedisUrlOrThrow('QUEUE') } })\n\n const job = await queue.getJob(jobId)\n\n if (!job) {\n await queue.close()\n return NextResponse.json(\n { error: translate('scheduler.error.job_not_found', 'Job not found in BullMQ (may have been removed)') },\n { status: 404 }\n )\n }\n\n // Validate tenant/org access from job data\n const jobData = job.data as Record<string, unknown> | undefined\n const jobPayload = jobData?.payload as Record<string, unknown> | undefined\n\n // Resolve tenant/org IDs from job data (may be nested in payload)\n const jobTenantId = jobData?.tenantId ?? jobPayload?.tenantId ?? null\n const jobOrgId = jobData?.organizationId ?? jobPayload?.organizationId ?? null\n\n // System-scoped jobs (no tenantId/orgId) require super-admin. Use the\n // immutable `isSuperAdmin` flag \u2014 never compare mutable/spoofable role names.\n const isSuperAdmin = auth.isSuperAdmin === true\n if (!jobTenantId && !jobOrgId && !isSuperAdmin) {\n await queue.close()\n return NextResponse.json({ error: translate('scheduler.error.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n // Deny access to jobs belonging to a different tenant\n if (jobTenantId && auth.tenantId && jobTenantId !== auth.tenantId) {\n await queue.close()\n return NextResponse.json({ error: translate('scheduler.error.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n // Deny access to jobs belonging to a different organization\n if (jobOrgId && auth.orgId && jobOrgId !== auth.orgId) {\n await queue.close()\n return NextResponse.json({ error: translate('scheduler.error.forbidden', 'Forbidden') }, { status: 403 })\n }\n\n // Get job state and logs\n const state = await job.getState()\n const logs = await queue.getJobLogs(jobId)\n\n await queue.close()\n\n return NextResponse.json({\n id: job.id,\n name: job.name,\n data: job.data,\n state,\n progress: job.progress,\n returnvalue: job.returnvalue,\n failedReason: job.failedReason,\n stacktrace: job.stacktrace,\n attemptsMade: job.attemptsMade,\n processedOn: job.processedOn ? new Date(job.processedOn).toISOString() : null,\n finishedOn: job.finishedOn ? new Date(job.finishedOn).toISOString() : null,\n logs: logs.logs || [],\n })\n } catch (error: unknown) {\n console.error('[scheduler:queue-jobs] Error fetching job:', error)\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.fetch_job_failed', 'Failed to fetch job details') },\n { status: 500 }\n )\n }\n}\n\n// Query schemas\nconst queueJobQuerySchema = z.object({\n queue: z.string(),\n})\n\n// Response schemas\nconst queueJobResponseSchema = z.object({\n id: z.string(),\n name: z.string(),\n data: z.unknown(),\n state: z.enum(['waiting', 'active', 'completed', 'failed', 'delayed', 'waiting-children']),\n progress: z.number().nullable(),\n returnvalue: z.unknown().nullable(),\n failedReason: z.string().nullable(),\n stacktrace: z.array(z.string()).nullable(),\n attemptsMade: z.number(),\n processedOn: z.string().nullable(),\n finishedOn: z.string().nullable(),\n logs: z.array(z.string()),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n available: z.boolean().optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Get BullMQ job details',\n description: 'Fetches detailed information and logs for a queue job from BullMQ.',\n methods: {\n GET: {\n operationId: 'getQueueJobDetails',\n summary: 'Get BullMQ job details and logs',\n description: 'Fetch detailed information and logs for a queue job. Requires QUEUE_STRATEGY=async.',\n query: queueJobQuerySchema,\n responses: [\n {\n status: 200,\n description: 'Job details and logs',\n schema: queueJobResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request or local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: errorResponseSchema },\n { status: 404, description: 'Job not found', schema: errorResponseSchema },\n { status: 500, description: 'Internal server error', schema: errorResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AAEnC,SAAS,0BAA0B;AACnC,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AAG7B,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,qBAAqB;AACzC;AAYA,eAAsB,IACpB,KACA,EAAE,OAAO,GACT;AACA,QAAM,EAAE,UAAU,IAAI,MA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SAAS;AAAA,IACP,KAAK;AAAA,MACH,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,oBAAoB;AAAA,QAC3G,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,yBAAyB,QAAQ,oBAAoB;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -36,9 +36,7 @@ async function POST(req) {
|
|
|
36
36
|
if (!schedule) {
|
|
37
37
|
return NextResponse.json({ error: translate("scheduler.error.not_found", "Schedule not found") }, { status: 404 });
|
|
38
38
|
}
|
|
39
|
-
const isSuperAdmin =
|
|
40
|
-
(role) => typeof role === "string" && role.trim().toLowerCase() === "superadmin"
|
|
41
|
-
);
|
|
39
|
+
const isSuperAdmin = auth.isSuperAdmin === true;
|
|
42
40
|
if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
|
|
43
41
|
return NextResponse.json({ error: translate("scheduler.error.access_denied", "Access denied") }, { status: 403 });
|
|
44
42
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/scheduler/api/trigger/route.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { ScheduledJob } from '../../data/entities.js'\nimport { scheduleTriggerSchema } from '../../data/validators.js'\nimport type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.trigger'],\n}\n\n/**\n * POST /api/scheduler/trigger\n * Manually trigger a schedule\n * \n * This enqueues the schedule execution job in BullMQ.\n * Execution history is tracked in BullMQ job state.\n */\nexport async function POST(req: NextRequest) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n try {\n const body = await req.json()\n const input = scheduleTriggerSchema.parse(body)\n\n // Find the schedule with tenant/org scope filter\n const findFilter: Record<string, unknown> = {\n id: input.id,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require
|
|
5
|
-
"mappings": "AAAA,SAAsB,oBAAoB;AAC1C,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,6BAA6B;AAEtC,SAAS,2BAA2B;AAE7B,MAAM,WAAW;AAAA,EACtB,aAAa;AAAA,EACb,iBAAiB,CAAC,wBAAwB;AAC5C;AASA,eAAsB,KAAK,KAAkB;AAC3C,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,KAAK;AACd,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,gCAAgC,cAAc,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAChH;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAuB,IAAI;AAEhD,MAAI;AACF,UAAM,OAAO,MAAM,IAAI,KAAK;AAC5B,UAAM,QAAQ,sBAAsB,MAAM,IAAI;AAG9C,UAAM,aAAsC;AAAA,MAC1C,IAAI,MAAM;AAAA,MACV,WAAW;AAAA,IACb;AAGA,QAAI,KAAK,UAAU;AACjB,iBAAW,WAAW,KAAK;AAAA,IAC7B;AACA,QAAI,KAAK,OAAO;AACd,iBAAW,iBAAiB,KAAK;AAAA,IACnC;AAEA,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,UAAU;AAE1D,QAAI,CAAC,UAAU;AACb,aAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,oBAAoB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,IACnH;
|
|
4
|
+
"sourcesContent": ["import { NextRequest, NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/core'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createQueue } from '@open-mercato/queue'\nimport { getRedisUrlOrThrow } from '@open-mercato/shared/lib/redis/connection'\nimport { ScheduledJob } from '../../data/entities.js'\nimport { scheduleTriggerSchema } from '../../data/validators.js'\nimport type { ExecuteSchedulePayload } from '../../workers/execute-schedule.worker.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nexport const metadata = {\n requireAuth: true,\n requireFeatures: ['scheduler.jobs.trigger'],\n}\n\n/**\n * POST /api/scheduler/trigger\n * Manually trigger a schedule\n * \n * This enqueues the schedule execution job in BullMQ.\n * Execution history is tracked in BullMQ job state.\n */\nexport async function POST(req: NextRequest) {\n const { translate } = await resolveTranslations()\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub) {\n return NextResponse.json({ error: translate('scheduler.error.unauthorized', 'Unauthorized') }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n\n try {\n const body = await req.json()\n const input = scheduleTriggerSchema.parse(body)\n\n // Find the schedule with tenant/org scope filter\n const findFilter: Record<string, unknown> = {\n id: input.id,\n deletedAt: null,\n }\n\n // Apply tenant isolation: scope the query to the user's tenant/org\n if (auth.tenantId) {\n findFilter.tenantId = auth.tenantId\n }\n if (auth.orgId) {\n findFilter.organizationId = auth.orgId\n }\n\n const schedule = await em.findOne(ScheduledJob, findFilter)\n\n if (!schedule) {\n return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })\n }\n\n // System-scoped schedules (no tenantId/orgId) require super-admin. Use the\n // immutable `isSuperAdmin` flag \u2014 never compare mutable/spoofable role names.\n const isSuperAdmin = auth.isSuperAdmin === true\n if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {\n return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })\n }\n\n // Check if using async queue strategy\n const queueStrategy = (process.env.QUEUE_STRATEGY || 'local') as 'local' | 'async'\n \n if (queueStrategy !== 'async') {\n return NextResponse.json(\n { \n error: translate('scheduler.error.trigger_async_required', 'Manual trigger requires QUEUE_STRATEGY=async'),\n message: translate('scheduler.error.trigger_async_hint', 'Execution history and manual triggers are only available with BullMQ (async strategy)')\n },\n { status: 400 }\n )\n }\n\n // Enqueue execution job to scheduler-execution queue\n const executionQueue = createQueue<ExecuteSchedulePayload>('scheduler-execution', queueStrategy, {\n connection: { url: getRedisUrlOrThrow('QUEUE') },\n })\n\n const payload: ExecuteSchedulePayload = {\n scheduleId: schedule.id,\n tenantId: schedule.tenantId,\n organizationId: schedule.organizationId,\n scopeType: schedule.scopeType,\n triggerType: 'manual',\n triggeredByUserId: auth.sub,\n }\n\n const jobId = await executionQueue.enqueue(payload)\n await executionQueue.close()\n\n console.log('[scheduler:trigger] Manually triggered schedule:', {\n scheduleId: schedule.id,\n scheduleName: schedule.name,\n jobId,\n triggeredBy: auth.sub,\n })\n\n return NextResponse.json({\n ok: true,\n jobId, // BullMQ job ID\n message: translate('scheduler.success.triggered', 'Schedule queued for execution'),\n })\n\n } catch (error) {\n console.error('[scheduler:trigger] Error:', error)\n return NextResponse.json(\n { error: error instanceof Error ? error.message : translate('scheduler.error.trigger_failed', 'Failed to trigger schedule') },\n { status: 400 }\n )\n }\n}\n\n// Response schemas\nconst triggerResponseSchema = z.object({\n ok: z.boolean(),\n jobId: z.string(),\n message: z.string(),\n})\n\nconst errorResponseSchema = z.object({\n error: z.string(),\n message: z.string().optional(),\n})\n\n// OpenAPI specification\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Scheduler',\n summary: 'Manually trigger a schedule',\n description: 'Execute a schedule immediately by enqueueing it in the scheduler-execution queue. Requires QUEUE_STRATEGY=async.',\n methods: {\n POST: {\n operationId: 'triggerScheduledJob',\n summary: 'Manually trigger a schedule',\n description: 'Executes a scheduled job immediately, bypassing the scheduled time. Only works with async queue strategy.',\n requestBody: {\n schema: scheduleTriggerSchema,\n contentType: 'application/json',\n },\n responses: [\n {\n status: 200,\n description: 'Schedule triggered successfully',\n schema: triggerResponseSchema,\n },\n ],\n errors: [\n { status: 400, description: 'Invalid request or local strategy not supported', schema: errorResponseSchema },\n { status: 401, description: 'Unauthorized', schema: errorResponseSchema },\n { status: 403, description: 'Access denied', schema: error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;AAAA,EACd,OAAO,EAAE,OAAO;AAAA,EAChB,SAAS,EAAE,OAAO;AACpB,CAAC;AAED,MAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,OAAO,EAAE,OAAO;AAAA,EAChB,SAAS,EAAE,OAAO,EAAE,SAAS;AAC/B,CAAC;AAGM,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,aAAa;AAAA,MACb,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,QAAQ;AAAA,QACR,aAAa;AAAA,MACf;AAAA,MACA,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ;AAAA,QACV;AAAA,MACF;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,oBAAoB;AAAA,QAC3G,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,oBAAoB;AAAA,QACxE,EAAE,QAAQ,KAAK,aAAa,iBAAiB,QAAQ,oBAAoB;AAAA,QACzE,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,oBAAoB;AAAA,MAChF;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { registerCommand } from "@open-mercato/shared/lib/commands";
|
|
2
2
|
import { ensureOrganizationScope } from "@open-mercato/shared/lib/commands/scope";
|
|
3
|
+
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
3
4
|
import { ScheduledJob } from "../data/entities.js";
|
|
4
5
|
import { calculateNextRun } from "../lib/nextRunCalculator.js";
|
|
5
6
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
@@ -46,11 +47,23 @@ function ensureTenantScope(ctx, tenantId) {
|
|
|
46
47
|
throw new Error("Tenant mismatch");
|
|
47
48
|
}
|
|
48
49
|
}
|
|
50
|
+
function isSuperAdminActor(ctx) {
|
|
51
|
+
return ctx.auth?.isSuperAdmin === true;
|
|
52
|
+
}
|
|
53
|
+
function ensureCanManageSystemScopedJob(ctx, job) {
|
|
54
|
+
const isSystemScoped = job.scopeType === "system" || job.tenantId == null;
|
|
55
|
+
if (!isSystemScoped) return;
|
|
56
|
+
if (isSuperAdminActor(ctx)) return;
|
|
57
|
+
throw new CrudHttpError(403, {
|
|
58
|
+
error: "System-scoped scheduled jobs can only be managed by a super administrator."
|
|
59
|
+
});
|
|
60
|
+
}
|
|
49
61
|
const createScheduleCommand = {
|
|
50
62
|
id: "scheduler.jobs.create",
|
|
51
63
|
async execute(input, ctx) {
|
|
52
64
|
ensureTenantScope(ctx, input.tenantId);
|
|
53
65
|
if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId);
|
|
66
|
+
ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId });
|
|
54
67
|
const em = ctx.container.resolve("em").fork();
|
|
55
68
|
const nextRunAt = calculateNextRun(
|
|
56
69
|
input.scheduleType,
|
|
@@ -130,6 +143,7 @@ const updateScheduleCommand = {
|
|
|
130
143
|
}
|
|
131
144
|
ensureTenantScope(ctx, schedule.tenantId);
|
|
132
145
|
if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId);
|
|
146
|
+
ensureCanManageSystemScopedJob(ctx, schedule);
|
|
133
147
|
if (input.name !== void 0) schedule.name = input.name;
|
|
134
148
|
if (input.description !== void 0) schedule.description = input.description ?? null;
|
|
135
149
|
if (input.scheduleType !== void 0) schedule.scheduleType = input.scheduleType;
|
|
@@ -231,6 +245,7 @@ const deleteScheduleCommand = {
|
|
|
231
245
|
}
|
|
232
246
|
ensureTenantScope(ctx, schedule.tenantId);
|
|
233
247
|
if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId);
|
|
248
|
+
ensureCanManageSystemScopedJob(ctx, schedule);
|
|
234
249
|
schedule.deletedAt = /* @__PURE__ */ new Date();
|
|
235
250
|
schedule.updatedAt = /* @__PURE__ */ new Date();
|
|
236
251
|
schedule.updatedByUserId = ctx.auth?.userId ?? null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/scheduler/commands/jobs.ts"],
|
|
4
|
-
"sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\n\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n // Calculate next run time\n const nextRunAt = calculateNextRun(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: input.sourceType ?? 'user',\n sourceModule: input.sourceModule ?? null,\n nextRunAt,\n createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { after?: ScheduleSnapshot } }\n const after = undoPayload?.undo?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n // Recalculate next run if schedule changed\n if (input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot; after?: ScheduleSnapshot } }\n const before = undoPayload?.undo?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = before.nextRunAt\n schedule.lastRunAt = before.lastRunAt\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot } }\n const before = undoPayload?.undo?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore by clearing deletedAt\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand(deleteScheduleCommand)\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,+BAA+B;
|
|
4
|
+
"sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { EntityManager } from '@mikro-orm/core'\nimport { ScheduledJob } from '../data/entities.js'\nimport { calculateNextRun } from '../lib/nextRunCalculator.js'\nimport type {\n ScheduleCreateInput,\n ScheduleUpdateInput,\n} from '../data/validators.js'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { BullMQSchedulerService } from '../services/bullmqSchedulerService.js'\n\n/**\n * Snapshot of a schedule for undo/redo\n */\ntype ScheduleSnapshot = {\n id: string\n name: string\n description: string | null\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId: string | null\n tenantId: string | null\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone: string\n targetType: 'queue' | 'command'\n targetQueue: string | null\n targetCommand: string | null\n targetPayload: Record<string, unknown> | null\n requireFeature: string | null\n isEnabled: boolean\n sourceType: 'user' | 'module'\n sourceModule: string | null\n nextRunAt: Date | null\n lastRunAt: Date | null\n}\n\n/**\n * Load a schedule snapshot\n */\nasync function loadScheduleSnapshot(\n em: EntityManager,\n scheduleId: string\n): Promise<ScheduleSnapshot | null> {\n const schedule = await em.findOne(ScheduledJob, { id: scheduleId })\n if (!schedule) return null\n\n return {\n id: schedule.id,\n name: schedule.name,\n description: schedule.description ?? null,\n scopeType: schedule.scopeType,\n organizationId: schedule.organizationId ?? null,\n tenantId: schedule.tenantId ?? null,\n scheduleType: schedule.scheduleType,\n scheduleValue: schedule.scheduleValue,\n timezone: schedule.timezone,\n targetType: schedule.targetType,\n targetQueue: schedule.targetQueue ?? null,\n targetCommand: schedule.targetCommand ?? null,\n targetPayload: schedule.targetPayload ?? null,\n requireFeature: schedule.requireFeature ?? null,\n isEnabled: schedule.isEnabled,\n sourceType: schedule.sourceType,\n sourceModule: schedule.sourceModule ?? null,\n nextRunAt: schedule.nextRunAt ?? null,\n lastRunAt: schedule.lastRunAt ?? null,\n }\n}\n\n/**\n * Trigger BullMQ sync after undo operations.\n * Best-effort: if BullMQ service is unavailable (e.g. local strategy), this is a no-op.\n */\nasync function syncBullMQAfterUndo(ctx: CommandRuntimeContext, schedule: ScheduledJob | null): Promise<void> {\n try {\n if (!ctx.container?.resolve) return\n const bullmqService = ctx.container.resolve<BullMQSchedulerService>('bullmqSchedulerService')\n if (!bullmqService) return\n\n if (schedule && schedule.isEnabled && !schedule.deletedAt) {\n await bullmqService.register(schedule, { skipNextRunUpdate: true })\n } else if (schedule) {\n await bullmqService.unregister(schedule.id)\n }\n } catch {\n // Best-effort: BullMQ service may not be registered (local strategy)\n }\n}\n\n/**\n * Ensure tenant/org scope for security\n */\nfunction ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null | undefined) {\n if (tenantId && ctx.auth?.tenantId && ctx.auth.tenantId !== tenantId) {\n throw new Error('Tenant mismatch')\n }\n}\n\n// Super-admin status is the immutable `isSuperAdmin` flag derived from\n// RoleAcl/UserAcl at session resolution. Never compare role names to a string\n// like 'superadmin' \u2014 role names are tenant-mutable and trivially spoofable.\nfunction isSuperAdminActor(ctx: CommandRuntimeContext): boolean {\n return ctx.auth?.isSuperAdmin === true\n}\n\n// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a\n// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule\n// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,\n// mirroring the create route's system-scope gate.\nfunction ensureCanManageSystemScopedJob(\n ctx: CommandRuntimeContext,\n job: { scopeType?: string | null; tenantId?: string | null },\n): void {\n const isSystemScoped = job.scopeType === 'system' || job.tenantId == null\n if (!isSystemScoped) return\n if (isSuperAdminActor(ctx)) return\n throw new CrudHttpError(403, {\n error: 'System-scoped scheduled jobs can only be managed by a super administrator.',\n })\n}\n\n/**\n * CREATE SCHEDULE COMMAND\n */\nconst createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }> = {\n id: 'scheduler.jobs.create',\n\n async execute(input, ctx) {\n ensureTenantScope(ctx, input.tenantId)\n if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)\n ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n // Calculate next run time\n const nextRunAt = calculateNextRun(\n input.scheduleType,\n input.scheduleValue,\n input.timezone || 'UTC'\n )\n\n if (!nextRunAt) {\n throw new Error('Failed to calculate next run time')\n }\n\n // Create schedule\n const schedule = em.create(ScheduledJob, {\n name: input.name,\n description: input.description ?? null,\n scopeType: input.scopeType,\n organizationId: input.organizationId ?? null,\n tenantId: input.tenantId ?? null,\n scheduleType: input.scheduleType,\n scheduleValue: input.scheduleValue,\n timezone: input.timezone ?? 'UTC',\n targetType: input.targetType,\n targetQueue: input.targetQueue ?? null,\n targetCommand: input.targetCommand ?? null,\n targetPayload: input.targetPayload ?? null,\n requireFeature: input.requireFeature ?? null,\n isEnabled: input.isEnabled ?? true,\n sourceType: input.sourceType ?? 'user',\n sourceModule: input.sourceModule ?? null,\n nextRunAt,\n createdByUserId: (ctx.auth?.userId as string | undefined) ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n em.persist(schedule)\n await em.flush()\n\n return { id: schedule.id }\n },\n\n async captureAfter(_input, result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, result.id)\n },\n\n async buildLog({ result, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.create', 'Create schedule'),\n resourceKind: 'scheduler.job',\n resourceId: result.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotAfter: after,\n payload: { undo: { after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { after?: ScheduleSnapshot } }\n const after = undoPayload?.undo?.after\n if (!after) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: after.id })\n\n if (schedule) {\n await em.remove(schedule).flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * UPDATE SCHEDULE COMMAND\n */\nconst updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }> = {\n id: 'scheduler.jobs.update',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Update fields\n if (input.name !== undefined) schedule.name = input.name\n if (input.description !== undefined) schedule.description = input.description ?? null\n if (input.scheduleType !== undefined) schedule.scheduleType = input.scheduleType\n if (input.scheduleValue !== undefined) schedule.scheduleValue = input.scheduleValue\n if (input.timezone !== undefined) schedule.timezone = input.timezone\n if (input.targetPayload !== undefined) schedule.targetPayload = input.targetPayload ?? null\n if (input.requireFeature !== undefined) schedule.requireFeature = input.requireFeature || null\n if (input.isEnabled !== undefined) schedule.isEnabled = input.isEnabled\n \n // Handle target type changes - clear stale values when switching between queue and command\n if (input.targetType !== undefined) {\n schedule.targetType = input.targetType\n \n if (input.targetType === 'queue') {\n // Switching to queue: set new queue and clear command\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n schedule.targetCommand = null\n } else if (input.targetType === 'command') {\n // Switching to command: set new command and clear queue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n schedule.targetQueue = null\n }\n } else {\n // targetType not changing, but allow updating individual target fields\n if (input.targetQueue !== undefined) schedule.targetQueue = input.targetQueue\n if (input.targetCommand !== undefined) schedule.targetCommand = input.targetCommand\n }\n\n // Recalculate next run if schedule changed\n if (input.scheduleType !== undefined || input.scheduleValue !== undefined || input.timezone !== undefined) {\n const nextRunAt = calculateNextRun(\n schedule.scheduleType,\n schedule.scheduleValue,\n schedule.timezone\n )\n if (nextRunAt) {\n schedule.nextRunAt = nextRunAt\n }\n }\n\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async captureAfter(input, _result, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n return await loadScheduleSnapshot(em, input.id)\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n const after = snapshots.after as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.update', 'Update schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: after?.tenantId || null,\n organizationId: after?.organizationId || null,\n snapshotBefore: before,\n snapshotAfter: after,\n payload: { undo: { before, after } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot; after?: ScheduleSnapshot } }\n const before = undoPayload?.undo?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore all fields\n schedule.name = before.name\n schedule.description = before.description\n schedule.scopeType = before.scopeType\n schedule.organizationId = before.organizationId\n schedule.tenantId = before.tenantId\n schedule.scheduleType = before.scheduleType\n schedule.scheduleValue = before.scheduleValue\n schedule.timezone = before.timezone\n schedule.targetType = before.targetType\n schedule.targetQueue = before.targetQueue\n schedule.targetCommand = before.targetCommand\n schedule.targetPayload = before.targetPayload\n schedule.requireFeature = before.requireFeature\n schedule.isEnabled = before.isEnabled\n schedule.sourceType = before.sourceType\n schedule.sourceModule = before.sourceModule\n schedule.nextRunAt = before.nextRunAt\n schedule.lastRunAt = before.lastRunAt\n schedule.updatedAt = new Date()\n\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n/**\n * DELETE SCHEDULE COMMAND\n */\nconst deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {\n id: 'scheduler.jobs.delete',\n\n async prepare(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em')\n const before = await loadScheduleSnapshot(em, input.id)\n return { before }\n },\n\n async execute(input, ctx) {\n const em = ctx.container.resolve<EntityManager>('em').fork()\n\n const schedule = await em.findOne(ScheduledJob, { id: input.id, deletedAt: null })\n if (!schedule) {\n throw new Error('Schedule not found')\n }\n\n ensureTenantScope(ctx, schedule.tenantId)\n if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)\n ensureCanManageSystemScopedJob(ctx, schedule)\n\n // Soft delete\n schedule.deletedAt = new Date()\n schedule.updatedAt = new Date()\n schedule.updatedByUserId = (ctx.auth?.userId as string | undefined) ?? null\n\n await em.flush()\n\n return { ok: true }\n },\n\n async buildLog({ input, ctx, snapshots }) {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as ScheduleSnapshot | undefined\n\n return {\n actionLabel: translate('scheduler.audit.delete', 'Delete schedule'),\n resourceKind: 'scheduler.job',\n resourceId: input.id,\n tenantId: before?.tenantId || null,\n organizationId: before?.organizationId || null,\n snapshotBefore: before,\n payload: { undo: { before } },\n }\n },\n\n async undo({ logEntry, ctx }) {\n const undoPayload = logEntry.payload as { undo?: { before?: ScheduleSnapshot } }\n const before = undoPayload?.undo?.before\n if (!before) return\n\n const em = ctx.container.resolve<EntityManager>('em').fork()\n const schedule = await em.findOne(ScheduledJob, { id: before.id })\n\n if (schedule) {\n // Restore by clearing deletedAt\n schedule.deletedAt = null\n schedule.updatedAt = new Date()\n await em.flush()\n await syncBullMQAfterUndo(ctx, schedule)\n }\n },\n}\n\n// Register all commands\nregisterCommand(createScheduleCommand)\nregisterCommand(updateScheduleCommand)\nregisterCommand(deleteScheduleCommand)\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,+BAA+B;AACxC,SAAS,qBAAqB;AAE9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AAKjC,SAAS,2BAA2B;AA+BpC,eAAe,qBACb,IACA,Y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UAAiC;AAEvE,UAAM,GAAG,MAAM;AAEf,WAAO,EAAE,IAAI,KAAK;AAAA,EACpB;AAAA,EAEA,MAAM,SAAS,EAAE,OAAO,KAAK,UAAU,GAAG;AACxC,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,UAAM,SAAS,UAAU;AAEzB,WAAO;AAAA,MACL,aAAa,UAAU,0BAA0B,iBAAiB;AAAA,MAClE,cAAc;AAAA,MACd,YAAY,MAAM;AAAA,MAClB,UAAU,QAAQ,YAAY;AAAA,MAC9B,gBAAgB,QAAQ,kBAAkB;AAAA,MAC1C,gBAAgB;AAAA,MAChB,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE;AAAA,IAC9B;AAAA,EACF;AAAA,EAEA,MAAM,KAAK,EAAE,UAAU,IAAI,GAAG;AAC5B,UAAM,cAAc,SAAS;AAC7B,UAAM,SAAS,aAAa,MAAM;AAClC,QAAI,CAAC,OAAQ;AAEb,UAAM,KAAK,IAAI,UAAU,QAAuB,IAAI,EAAE,KAAK;AAC3D,UAAM,WAAW,MAAM,GAAG,QAAQ,cAAc,EAAE,IAAI,OAAO,GAAG,CAAC;AAEjE,QAAI,UAAU;AAEZ,eAAS,YAAY;AACrB,eAAS,YAAY,oBAAI,KAAK;AAC9B,YAAM,GAAG,MAAM;AACf,YAAM,oBAAoB,KAAK,QAAQ;AAAA,IACzC;AAAA,EACF;AACF;AAGA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
|
|
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.4-develop.
|
|
3
|
+
"version": "0.6.4-develop.4305.1.efaf0ebab1",
|
|
4
4
|
"description": "Database-managed scheduled jobs with admin UI",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -58,13 +58,13 @@
|
|
|
58
58
|
"./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@open-mercato/events": "0.6.4-develop.
|
|
62
|
-
"@open-mercato/queue": "0.6.4-develop.
|
|
61
|
+
"@open-mercato/events": "0.6.4-develop.4305.1.efaf0ebab1",
|
|
62
|
+
"@open-mercato/queue": "0.6.4-develop.4305.1.efaf0ebab1",
|
|
63
63
|
"cron-parser": "^5.5.0"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|
|
66
66
|
"@mikro-orm/core": "^7.0.14",
|
|
67
|
-
"@open-mercato/shared": "0.6.4-develop.
|
|
67
|
+
"@open-mercato/shared": "0.6.4-develop.4305.1.efaf0ebab1",
|
|
68
68
|
"bullmq": "^5.0.0",
|
|
69
69
|
"ioredis": "^5.0.0",
|
|
70
70
|
"zod": ">=3.23.0"
|
|
@@ -78,7 +78,7 @@
|
|
|
78
78
|
}
|
|
79
79
|
},
|
|
80
80
|
"devDependencies": {
|
|
81
|
-
"@open-mercato/shared": "0.6.4-develop.
|
|
81
|
+
"@open-mercato/shared": "0.6.4-develop.4305.1.efaf0ebab1",
|
|
82
82
|
"@types/jest": "^30.0.0",
|
|
83
83
|
"@types/node": "^25.9.1",
|
|
84
84
|
"jest": "^30.4.2",
|
|
@@ -57,10 +57,9 @@ export async function GET(
|
|
|
57
57
|
return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
// System-scoped schedules (no tenantId/orgId) require
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
)
|
|
60
|
+
// System-scoped schedules (no tenantId/orgId) require super-admin. Use the
|
|
61
|
+
// immutable `isSuperAdmin` flag — never compare mutable/spoofable role names.
|
|
62
|
+
const isSuperAdmin = auth.isSuperAdmin === true
|
|
64
63
|
if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
|
|
65
64
|
return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })
|
|
66
65
|
}
|
|
@@ -14,13 +14,13 @@ type Ctx = Parameters<typeof buildSchedulerJobsFilters>[1]
|
|
|
14
14
|
const makeCtx = (overrides: Partial<{
|
|
15
15
|
tenantId: string | null
|
|
16
16
|
orgId: string | null
|
|
17
|
-
|
|
17
|
+
isSuperAdmin: boolean
|
|
18
18
|
organizationIds: string[] | null
|
|
19
19
|
}> = {}): Ctx => ({
|
|
20
20
|
auth: {
|
|
21
21
|
tenantId: overrides.tenantId === undefined ? 't1' : overrides.tenantId,
|
|
22
22
|
orgId: overrides.orgId === undefined ? 'o1' : overrides.orgId,
|
|
23
|
-
|
|
23
|
+
isSuperAdmin: overrides.isSuperAdmin === undefined ? false : overrides.isSuperAdmin,
|
|
24
24
|
},
|
|
25
25
|
organizationIds: overrides.organizationIds === undefined ? ['o1'] : overrides.organizationIds,
|
|
26
26
|
})
|
|
@@ -42,7 +42,7 @@ describe('buildSchedulerJobsFilters — scope visibility (#815, #1587)', () => {
|
|
|
42
42
|
it('adds a system-scope branch only for superadmins', async () => {
|
|
43
43
|
const filters = await buildSchedulerJobsFilters(
|
|
44
44
|
{},
|
|
45
|
-
makeCtx({
|
|
45
|
+
makeCtx({ isSuperAdmin: true }),
|
|
46
46
|
)
|
|
47
47
|
const or = filters.$or as Record<string, unknown>[]
|
|
48
48
|
expect(or).toContainEqual({
|
|
@@ -55,7 +55,19 @@ describe('buildSchedulerJobsFilters — scope visibility (#815, #1587)', () => {
|
|
|
55
55
|
it('does NOT leak system-scope rows to non-superadmins', async () => {
|
|
56
56
|
const filters = await buildSchedulerJobsFilters(
|
|
57
57
|
{},
|
|
58
|
-
makeCtx({
|
|
58
|
+
makeCtx({ isSuperAdmin: false }),
|
|
59
|
+
)
|
|
60
|
+
const or = filters.$or as Record<string, unknown>[]
|
|
61
|
+
const systemBranch = or.find(
|
|
62
|
+
(branch) => (branch.scope_type as { $eq?: string } | undefined)?.$eq === 'system',
|
|
63
|
+
)
|
|
64
|
+
expect(systemBranch).toBeUndefined()
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('does NOT grant system-scope visibility to a spoofed role named "superadmin" without the isSuperAdmin flag', async () => {
|
|
68
|
+
const filters = await buildSchedulerJobsFilters(
|
|
69
|
+
{},
|
|
70
|
+
{ auth: { tenantId: 't1', orgId: 'o1', isSuperAdmin: false }, organizationIds: ['o1'] },
|
|
59
71
|
)
|
|
60
72
|
const or = filters.$or as Record<string, unknown>[]
|
|
61
73
|
const systemBranch = or.find(
|
|
@@ -82,7 +94,7 @@ describe('buildSchedulerJobsFilters — scope visibility (#815, #1587)', () => {
|
|
|
82
94
|
it('distributes search across every visibility branch (name + description)', async () => {
|
|
83
95
|
const filters = await buildSchedulerJobsFilters(
|
|
84
96
|
{ search: 'nightly' },
|
|
85
|
-
makeCtx({
|
|
97
|
+
makeCtx({ isSuperAdmin: true }),
|
|
86
98
|
)
|
|
87
99
|
const or = filters.$or as Record<string, unknown>[]
|
|
88
100
|
// 3 visibility branches (org, tenant, system) × 2 columns (name, description) = 6
|
|
@@ -4,7 +4,7 @@ export type SchedulerJobsFilterContext = {
|
|
|
4
4
|
auth?: {
|
|
5
5
|
tenantId?: string | null
|
|
6
6
|
orgId?: string | null
|
|
7
|
-
|
|
7
|
+
isSuperAdmin?: boolean
|
|
8
8
|
} | null
|
|
9
9
|
organizationIds?: string[] | null
|
|
10
10
|
}
|
|
@@ -29,9 +29,7 @@ export async function buildSchedulerJobsFilters(
|
|
|
29
29
|
return filters
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
const isSuperAdmin =
|
|
33
|
-
Array.isArray(ctx.auth?.roles) &&
|
|
34
|
-
ctx.auth.roles.some((role) => typeof role === 'string' && role.trim().toLowerCase() === 'superadmin')
|
|
32
|
+
const isSuperAdmin = ctx.auth?.isSuperAdmin === true
|
|
35
33
|
|
|
36
34
|
const rawOrgIds = Array.isArray(ctx.organizationIds)
|
|
37
35
|
? ctx.organizationIds.filter((id): id is string => typeof id === 'string' && id.trim().length > 0)
|
|
@@ -109,11 +109,10 @@ const crud = makeCrudRoute({
|
|
|
109
109
|
let tenantId = raw.tenantId
|
|
110
110
|
|
|
111
111
|
if (scopeType === 'system') {
|
|
112
|
-
// System scope requires
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
)
|
|
116
|
-
if (!isSuperAdmin) {
|
|
112
|
+
// System scope requires super-admin. Use the immutable `isSuperAdmin`
|
|
113
|
+
// flag (derived from RoleAcl/UserAcl) — never compare role names, which
|
|
114
|
+
// are tenant-mutable and spoofable.
|
|
115
|
+
if (ctx.auth?.isSuperAdmin !== true) {
|
|
117
116
|
throw new CrudHttpError(403, { error: 'System-scoped schedules require superadmin privileges' })
|
|
118
117
|
}
|
|
119
118
|
// System scope: no org/tenant
|
|
@@ -89,10 +89,9 @@ export async function GET(
|
|
|
89
89
|
const jobTenantId = jobData?.tenantId ?? jobPayload?.tenantId ?? null
|
|
90
90
|
const jobOrgId = jobData?.organizationId ?? jobPayload?.organizationId ?? null
|
|
91
91
|
|
|
92
|
-
// System-scoped jobs (no tenantId/orgId) require
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
)
|
|
92
|
+
// System-scoped jobs (no tenantId/orgId) require super-admin. Use the
|
|
93
|
+
// immutable `isSuperAdmin` flag — never compare mutable/spoofable role names.
|
|
94
|
+
const isSuperAdmin = auth.isSuperAdmin === true
|
|
96
95
|
if (!jobTenantId && !jobOrgId && !isSuperAdmin) {
|
|
97
96
|
await queue.close()
|
|
98
97
|
return NextResponse.json({ error: translate('scheduler.error.forbidden', 'Forbidden') }, { status: 403 })
|
|
@@ -57,10 +57,9 @@ export async function POST(req: NextRequest) {
|
|
|
57
57
|
return NextResponse.json({ error: translate('scheduler.error.not_found', 'Schedule not found') }, { status: 404 })
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
// System-scoped schedules (no tenantId/orgId) require
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
)
|
|
60
|
+
// System-scoped schedules (no tenantId/orgId) require super-admin. Use the
|
|
61
|
+
// immutable `isSuperAdmin` flag — never compare mutable/spoofable role names.
|
|
62
|
+
const isSuperAdmin = auth.isSuperAdmin === true
|
|
64
63
|
if (!schedule.tenantId && !schedule.organizationId && !isSuperAdmin) {
|
|
65
64
|
return NextResponse.json({ error: translate('scheduler.error.access_denied', 'Access denied') }, { status: 403 })
|
|
66
65
|
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
export {}
|
|
2
|
+
|
|
3
|
+
const registerCommand = jest.fn()
|
|
4
|
+
|
|
5
|
+
jest.mock('@open-mercato/shared/lib/commands', () => ({
|
|
6
|
+
registerCommand,
|
|
7
|
+
}))
|
|
8
|
+
|
|
9
|
+
jest.mock('@open-mercato/shared/lib/i18n/server', () => ({
|
|
10
|
+
resolveTranslations: jest.fn().mockResolvedValue({
|
|
11
|
+
translate: (_key: string, fallback?: string) => fallback ?? _key,
|
|
12
|
+
}),
|
|
13
|
+
}))
|
|
14
|
+
|
|
15
|
+
function loadCommands() {
|
|
16
|
+
let create: any
|
|
17
|
+
let update: any
|
|
18
|
+
let del: any
|
|
19
|
+
jest.isolateModules(() => {
|
|
20
|
+
require('../jobs')
|
|
21
|
+
create = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.create')?.[0]
|
|
22
|
+
update = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.update')?.[0]
|
|
23
|
+
del = registerCommand.mock.calls.find(([cmd]) => cmd.id === 'scheduler.jobs.delete')?.[0]
|
|
24
|
+
})
|
|
25
|
+
return { create, update, del }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function makeEm(schedule: Record<string, unknown> | null) {
|
|
29
|
+
return {
|
|
30
|
+
fork: jest.fn().mockReturnThis(),
|
|
31
|
+
findOne: jest.fn().mockResolvedValue(schedule),
|
|
32
|
+
persist: jest.fn(),
|
|
33
|
+
remove: jest.fn(),
|
|
34
|
+
flush: jest.fn().mockResolvedValue(undefined),
|
|
35
|
+
create: jest.fn(),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function makeCtx(auth: Record<string, unknown> | null, em: any) {
|
|
40
|
+
return {
|
|
41
|
+
auth,
|
|
42
|
+
container: { resolve: jest.fn(() => em) },
|
|
43
|
+
} as any
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe('scheduler.jobs system-scope authorization (issue #2267)', () => {
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
jest.clearAllMocks()
|
|
49
|
+
jest.resetModules()
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('blocks a non-super-admin from creating a system-scoped job', async () => {
|
|
53
|
+
const { create } = loadCommands()
|
|
54
|
+
expect(create).toBeDefined()
|
|
55
|
+
const em = makeEm(null)
|
|
56
|
+
const ctx = makeCtx({ isSuperAdmin: false, tenantId: 'tenant-a', roles: ['admin'] }, em)
|
|
57
|
+
|
|
58
|
+
await expect(
|
|
59
|
+
create.execute(
|
|
60
|
+
{ name: 'sys', scopeType: 'system', tenantId: null, scheduleType: 'cron', scheduleValue: '* * * * *', targetType: 'queue' },
|
|
61
|
+
ctx,
|
|
62
|
+
),
|
|
63
|
+
).rejects.toMatchObject({ status: 403 })
|
|
64
|
+
expect(em.persist).not.toHaveBeenCalled()
|
|
65
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('blocks a non-super-admin from updating a system-scoped job and performs no write', async () => {
|
|
69
|
+
const { update } = loadCommands()
|
|
70
|
+
const em = makeEm({ id: 'job-1', scopeType: 'system', tenantId: null, organizationId: null })
|
|
71
|
+
const ctx = makeCtx({ isSuperAdmin: false, tenantId: 'tenant-a', roles: ['admin'] }, em)
|
|
72
|
+
|
|
73
|
+
await expect(
|
|
74
|
+
update.execute({ id: 'job-1', name: 'hijacked' }, ctx),
|
|
75
|
+
).rejects.toMatchObject({ status: 403 })
|
|
76
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('blocks a non-super-admin from deleting a system-scoped job and performs no write', async () => {
|
|
80
|
+
const { del } = loadCommands()
|
|
81
|
+
const em = makeEm({ id: 'job-1', scopeType: 'system', tenantId: null, organizationId: null })
|
|
82
|
+
const ctx = makeCtx({ isSuperAdmin: false, tenantId: 'tenant-a', roles: ['admin'] }, em)
|
|
83
|
+
|
|
84
|
+
await expect(
|
|
85
|
+
del.execute({ id: 'job-1' }, ctx),
|
|
86
|
+
).rejects.toMatchObject({ status: 403 })
|
|
87
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
88
|
+
expect(em.remove).not.toHaveBeenCalled()
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
it('blocks an actor whose role is literally named "superadmin" but lacks the isSuperAdmin flag (no role-name spoofing)', async () => {
|
|
92
|
+
const { del } = loadCommands()
|
|
93
|
+
const em = makeEm({ id: 'job-1', scopeType: 'system', tenantId: null, organizationId: null })
|
|
94
|
+
const ctx = makeCtx({ isSuperAdmin: false, tenantId: 'tenant-a', roles: ['superadmin'] }, em)
|
|
95
|
+
|
|
96
|
+
await expect(
|
|
97
|
+
del.execute({ id: 'job-1' }, ctx),
|
|
98
|
+
).rejects.toMatchObject({ status: 403 })
|
|
99
|
+
expect(em.flush).not.toHaveBeenCalled()
|
|
100
|
+
expect(em.remove).not.toHaveBeenCalled()
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('allows a super-admin to delete a system-scoped job (not blocked by the guard)', async () => {
|
|
104
|
+
const { del } = loadCommands()
|
|
105
|
+
const em = makeEm({ id: 'job-1', scopeType: 'system', tenantId: null, organizationId: null })
|
|
106
|
+
const ctx = makeCtx({ isSuperAdmin: true, tenantId: null, roles: ['superadmin'] }, em)
|
|
107
|
+
|
|
108
|
+
const result = await del.execute({ id: 'job-1' }, ctx)
|
|
109
|
+
expect(result).toEqual({ ok: true })
|
|
110
|
+
expect(em.flush).toHaveBeenCalled()
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
it('does NOT block a same-tenant non-super-admin from deleting a tenant-scoped job', async () => {
|
|
114
|
+
const { del } = loadCommands()
|
|
115
|
+
const em = makeEm({ id: 'job-2', scopeType: 'tenant', tenantId: 'tenant-a', organizationId: null })
|
|
116
|
+
const ctx = makeCtx({ isSuperAdmin: false, tenantId: 'tenant-a', roles: ['admin'] }, em)
|
|
117
|
+
|
|
118
|
+
const result = await del.execute({ id: 'job-2' }, ctx)
|
|
119
|
+
expect(result).toEqual({ ok: true })
|
|
120
|
+
expect(em.flush).toHaveBeenCalled()
|
|
121
|
+
})
|
|
122
|
+
})
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { registerCommand } from '@open-mercato/shared/lib/commands'
|
|
2
2
|
import type { CommandHandler, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'
|
|
3
3
|
import { ensureOrganizationScope } from '@open-mercato/shared/lib/commands/scope'
|
|
4
|
+
import { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
4
5
|
import type { EntityManager } from '@mikro-orm/core'
|
|
5
6
|
import { ScheduledJob } from '../data/entities.js'
|
|
6
7
|
import { calculateNextRun } from '../lib/nextRunCalculator.js'
|
|
@@ -98,6 +99,29 @@ function ensureTenantScope(ctx: CommandRuntimeContext, tenantId: string | null |
|
|
|
98
99
|
}
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
// Super-admin status is the immutable `isSuperAdmin` flag derived from
|
|
103
|
+
// RoleAcl/UserAcl at session resolution. Never compare role names to a string
|
|
104
|
+
// like 'superadmin' — role names are tenant-mutable and trivially spoofable.
|
|
105
|
+
function isSuperAdminActor(ctx: CommandRuntimeContext): boolean {
|
|
106
|
+
return ctx.auth?.isSuperAdmin === true
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// `ensureTenantScope` is a no-op for system-scoped jobs (tenantId === null), so a
|
|
110
|
+
// `scheduler.jobs.manage` holder could otherwise update/delete a system schedule
|
|
111
|
+
// belonging to the whole deployment. System-scoped jobs MUST be super-admin only,
|
|
112
|
+
// mirroring the create route's system-scope gate.
|
|
113
|
+
function ensureCanManageSystemScopedJob(
|
|
114
|
+
ctx: CommandRuntimeContext,
|
|
115
|
+
job: { scopeType?: string | null; tenantId?: string | null },
|
|
116
|
+
): void {
|
|
117
|
+
const isSystemScoped = job.scopeType === 'system' || job.tenantId == null
|
|
118
|
+
if (!isSystemScoped) return
|
|
119
|
+
if (isSuperAdminActor(ctx)) return
|
|
120
|
+
throw new CrudHttpError(403, {
|
|
121
|
+
error: 'System-scoped scheduled jobs can only be managed by a super administrator.',
|
|
122
|
+
})
|
|
123
|
+
}
|
|
124
|
+
|
|
101
125
|
/**
|
|
102
126
|
* CREATE SCHEDULE COMMAND
|
|
103
127
|
*/
|
|
@@ -107,6 +131,7 @@ const createScheduleCommand: CommandHandler<ScheduleCreateInput, { id: string }>
|
|
|
107
131
|
async execute(input, ctx) {
|
|
108
132
|
ensureTenantScope(ctx, input.tenantId)
|
|
109
133
|
if (input.organizationId) ensureOrganizationScope(ctx, input.organizationId)
|
|
134
|
+
ensureCanManageSystemScopedJob(ctx, { scopeType: input.scopeType, tenantId: input.tenantId })
|
|
110
135
|
|
|
111
136
|
const em = ctx.container.resolve<EntityManager>('em').fork()
|
|
112
137
|
|
|
@@ -208,6 +233,7 @@ const updateScheduleCommand: CommandHandler<ScheduleUpdateInput, { ok: boolean }
|
|
|
208
233
|
|
|
209
234
|
ensureTenantScope(ctx, schedule.tenantId)
|
|
210
235
|
if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)
|
|
236
|
+
ensureCanManageSystemScopedJob(ctx, schedule)
|
|
211
237
|
|
|
212
238
|
// Update fields
|
|
213
239
|
if (input.name !== undefined) schedule.name = input.name
|
|
@@ -338,6 +364,7 @@ const deleteScheduleCommand: CommandHandler<{ id: string }, { ok: boolean }> = {
|
|
|
338
364
|
|
|
339
365
|
ensureTenantScope(ctx, schedule.tenantId)
|
|
340
366
|
if (schedule.organizationId) ensureOrganizationScope(ctx, schedule.organizationId)
|
|
367
|
+
ensureCanManageSystemScopedJob(ctx, schedule)
|
|
341
368
|
|
|
342
369
|
// Soft delete
|
|
343
370
|
schedule.deletedAt = new Date()
|