@open-mercato/scheduler 0.10.1-develop.7728.1.6b52eb2849 → 0.10.1-develop.7736.1.88e07906bf

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.
@@ -82,7 +82,7 @@ function collectQueueConsumers() {
82
82
  for (const worker of mod.workers ?? []) {
83
83
  if (!worker.queue) continue;
84
84
  const consumers = byQueue.get(worker.queue) ?? [];
85
- consumers.push(worker);
85
+ consumers.push({ moduleId: mod.id, worker });
86
86
  byQueue.set(worker.queue, consumers);
87
87
  }
88
88
  }
@@ -92,10 +92,10 @@ function collectQueueConsumers() {
92
92
  function listSchedulerSafeQueueTargets() {
93
93
  const targets = [];
94
94
  for (const [queue, consumers] of collectQueueConsumers()) {
95
- const optedIn = consumers.filter((worker) => worker.schedulerSafe === true);
95
+ const optedIn = consumers.filter((consumer) => consumer.worker.schedulerSafe === true);
96
96
  if (optedIn.length === 0 || optedIn.length !== consumers.length) continue;
97
- const requiredFeatures = [...new Set(optedIn.flatMap((worker) => Array.isArray(worker.schedulerRequiredFeatures) ? worker.schedulerRequiredFeatures : []))];
98
- const ownerModuleIds = [...new Set(consumers.map((worker) => typeof worker.id === "string" ? worker.id.split(":")[0] ?? "" : ""))];
97
+ const requiredFeatures = [...new Set(optedIn.flatMap((consumer) => Array.isArray(consumer.worker.schedulerRequiredFeatures) ? consumer.worker.schedulerRequiredFeatures : []))];
98
+ const ownerModuleIds = [...new Set(consumers.map((consumer) => consumer.moduleId))];
99
99
  targets.push({ queue, moduleId: ownerModuleIds[0] ?? "", requiredFeatures });
100
100
  }
101
101
  targets.sort((a, b) => a.queue.localeCompare(b.queue));
@@ -110,11 +110,8 @@ function getSchedulerQueueRequiredFeatures(queue) {
110
110
  }
111
111
  function findQueueOwnerModuleIds(queue) {
112
112
  const owners = /* @__PURE__ */ new Set();
113
- for (const [candidate, consumers] of collectQueueConsumers()) {
114
- if (candidate !== queue) continue;
115
- for (const worker of consumers) {
116
- if (typeof worker.id === "string") owners.add(worker.id.split(":")[0] ?? "");
117
- }
113
+ for (const consumer of collectQueueConsumers().get(queue) ?? []) {
114
+ owners.add(consumer.moduleId);
118
115
  }
119
116
  return owners;
120
117
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/scheduler/lib/safeQueueTargets.ts"],
4
- "sourcesContent": ["import { getModules } from '@open-mercato/shared/lib/modules/registry'\nimport type { ModuleWorker } from '@open-mercato/shared/modules/registry'\nimport { z, type ZodTypeAny } from 'zod'\n\nexport type SchedulerSafeQueueTarget = {\n queue: string\n /**\n * Indicative primary owner \u2014 the first registry module found among the\n * queue's consumers. A queue may legitimately have consumers from more than\n * one module; ownership for provenance checks is always resolved per module.\n */\n moduleId: string\n /** Extra creator features a principal must hold to schedule onto this queue. */\n requiredFeatures: string[]\n}\n\nexport type TrustedScheduleScope = {\n tenantId: string | null\n organizationId: string | null\n}\n\n/**\n * Runtime payload schemas for opted-in scheduler targets.\n *\n * Worker metadata cannot carry a Zod schema through static registry generation,\n * so the module that owns a schedulable worker registers its target payload\n * schema here at bootstrap. Targets without a registered schema accept\n * arbitrary JSON payloads (documented escape hatch, mirroring scheduler-safe\n * commands which also carry no payload schema).\n */\nconst registeredPayloadSchemas = new Map<string, ZodTypeAny>()\n\nexport function registerSchedulerQueuePayloadSchema(queue: string, schema: ZodTypeAny): void {\n registeredPayloadSchemas.set(queue, schema)\n}\n\nexport function getSchedulerQueuePayloadSchema(queue: string): ZodTypeAny | null {\n return registeredPayloadSchemas.get(queue) ?? null\n}\n\nexport type SchedulerTargetRbacService = {\n userHasAllFeatures?: (\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n}\n\n/**\n * Creator-side authorization for an opted-in queue target (#5213): a principal\n * must hold every feature the target declares beyond `scheduler.jobs.manage`.\n * Super administrators bypass target-specific checks, mirroring the rest of\n * the scheduler's authorization model. Returns null when authorized,\n * otherwise a short reason string.\n */\nexport async function assertSchedulerQueueTargetAuthorized(params: {\n queue: string\n actorUserId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n isSuperAdmin?: boolean\n rbacService?: SchedulerTargetRbacService | null\n}): Promise<string | null> {\n const requiredFeatures = getSchedulerQueueRequiredFeatures(params.queue)\n if (requiredFeatures.length === 0) return null\n if (params.isSuperAdmin === true) return null\n\n const actorUserId = typeof params.actorUserId === 'string' ? params.actorUserId.trim() : ''\n if (!actorUserId) return 'Scheduler queue target requires an authenticated creator'\n if (typeof params.rbacService?.userHasAllFeatures !== 'function') {\n return 'Scheduler queue target authorization is unavailable'\n }\n\n const authorized = await params.rbacService.userHasAllFeatures(actorUserId, requiredFeatures, {\n tenantId: params.tenantId ?? null,\n organizationId: params.organizationId ?? null,\n })\n if (!authorized) {\n return `Scheduler queue target requires features the creator lacks: ${requiredFeatures.join(', ')}`\n }\n return null\n}\n\n/**\n * Validates an author-supplied target payload against the target's registered\n * schema, when one exists. Returns null when the payload is acceptable,\n * otherwise a short reason string.\n */\nexport function validateSchedulerTargetPayload(\n queue: string,\n targetPayload: Record<string, unknown> | null | undefined,\n): string | null {\n const schema = getSchedulerQueuePayloadSchema(queue)\n if (!schema) return null\n const result = schema.safeParse(targetPayload ?? {})\n if (result.success) return null\n const firstIssue = result.error.issues[0]\n return [\n firstIssue?.path?.length ? `${firstIssue.path.join('.')}: ` : '',\n firstIssue?.message ?? 'Invalid payload',\n ].join('')\n}\n\n/**\n * Keys a schedule author may never control on a dispatched target payload:\n * tenant/organization authority context and the reserved `_`-prefixed envelope\n * namespace (idempotency keys, dispatch-origin markers, \u2026).\n */\nconst RESERVED_PAYLOAD_KEYS = new Set(['tenantId', 'organizationId', 'scope'])\n\nfunction isReservedPayloadKey(key: string): boolean {\n return RESERVED_PAYLOAD_KEYS.has(key) || key.startsWith('_')\n}\n\nfunction stripReservedKeys(payload: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(payload)) {\n if (isReservedPayloadKey(key)) continue\n if (key === 'payload' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = stripReservedKeys(value as Record<string, unknown>)\n continue\n }\n result[key] = value\n }\n return result\n}\n\n/**\n * Rebuild the trusted scope for a dispatched schedule payload from the stored\n * schedule row. Callers must never trust scope-shaped data from the schedule\n * author's `targetPayload`.\n */\nexport function buildTrustedScheduleScope(schedule: {\n tenantId?: string | null\n organizationId?: string | null\n}): TrustedScheduleScope {\n return {\n tenantId: schedule.tenantId ?? null,\n organizationId: schedule.organizationId ?? null,\n }\n}\n\n/**\n * Sanitize an author-supplied schedule target payload before dispatch:\n * deep-copies it, strips reserved authority and `_`-prefixed envelope keys at\n * the payload root and inside the local-strategy `payload` wrapper level, then\n * injects the trusted scope derived from the schedule row.\n */\nexport function sanitizeSchedulerTargetPayload(\n targetPayload: Record<string, unknown> | null | undefined,\n schedule: Parameters<typeof buildTrustedScheduleScope>[0],\n): Record<string, unknown> {\n const source = targetPayload ?? {}\n const cloned = structuredClone(source)\n const stripped = stripReservedKeys(cloned)\n return {\n ...stripped,\n scope: buildTrustedScheduleScope(schedule),\n }\n}\n\nconst queueConsumerCache = new WeakMap<object, Map<string, ModuleWorker[]>>()\n\nfunction collectQueueConsumers(): Map<string, ModuleWorker[]> {\n let modules: ReturnType<typeof getModules>\n try {\n modules = getModules()\n } catch {\n return new Map()\n }\n // The registry returns the same array instance between registrations, so the\n // grouped map can be memoized per instance instead of rebuilt per lookup.\n const cached = queueConsumerCache.get(modules)\n if (cached) return cached\n\n const byQueue = new Map<string, ModuleWorker[]>()\n for (const mod of modules) {\n for (const worker of mod.workers ?? []) {\n if (!worker.queue) continue\n const consumers = byQueue.get(worker.queue) ?? []\n consumers.push(worker)\n byQueue.set(worker.queue, consumers)\n }\n }\n queueConsumerCache.set(modules, byQueue)\n return byQueue\n}\n\n/**\n * Enumerate queue targets that are safe for user-facing scheduling (#5213):\n * every worker consuming the queue must explicitly opt in \u2014 queue consumers\n * compete for the same jobs, so a single non-opted-in consumer would otherwise\n * receive scheduler-controlled payloads it never agreed to accept.\n */\nexport function listSchedulerSafeQueueTargets(): SchedulerSafeQueueTarget[] {\n const targets: SchedulerSafeQueueTarget[] = []\n for (const [queue, consumers] of collectQueueConsumers()) {\n const optedIn = consumers.filter((worker) => worker.schedulerSafe === true)\n if (optedIn.length === 0 || optedIn.length !== consumers.length) continue\n\n const requiredFeatures = [...new Set(optedIn.flatMap((worker) => (\n Array.isArray(worker.schedulerRequiredFeatures) ? worker.schedulerRequiredFeatures : []\n )))]\n const ownerModuleIds = [...new Set(consumers.map((worker) => (\n typeof worker.id === 'string' ? (worker.id.split(':')[0] ?? '') : ''\n )))]\n targets.push({ queue, moduleId: ownerModuleIds[0] ?? '', requiredFeatures })\n }\n targets.sort((a, b) => a.queue.localeCompare(b.queue))\n return targets\n}\n\nexport function isSchedulerSafeQueue(queue: string | null | undefined): boolean {\n if (!queue) return false\n return listSchedulerSafeQueueTargets().some((target) => target.queue === queue)\n}\n\n/**\n * Extra creator features required by the target queue beyond\n * `scheduler.jobs.manage` (#5213). Empty when the target declares none.\n */\nexport function getSchedulerQueueRequiredFeatures(queue: string): string[] {\n return listSchedulerSafeQueueTargets().find((target) => target.queue === queue)?.requiredFeatures ?? []\n}\n\n/**\n * The module ids that own workers on this queue, from the live registry.\n */\nfunction findQueueOwnerModuleIds(queue: string): Set<string> {\n const owners = new Set<string>()\n for (const [candidate, consumers] of collectQueueConsumers()) {\n if (candidate !== queue) continue\n for (const worker of consumers) {\n if (typeof worker.id === 'string') owners.add(worker.id.split(':')[0] ?? '')\n }\n }\n return owners\n}\n\n/**\n * Operator-facing audit for persisted module-authored queue rows (#5213).\n *\n * Provenance on pre-upgrade rows is not fully verifiable at rest: a row created\n * by a non-user-bound API key carries no acting-user stamp, making it\n * indistinguishable from a genuine module registration. This helper surfaces\n * every module-authored queue-target row with its current dispatch verdict so\n * operators can review the allowed ones against their known integrations\n * (`mercato scheduler audit-queue-targets`).\n */\nexport type SchedulerModuleQueueRowAudit = {\n scheduleId: string\n name?: string\n sourceModule: string | null\n targetQueue: string | null\n isEnabled: boolean\n /** Whether the dispatch guard currently lets this row fire. */\n dispatchAllowed: boolean\n}\n\nexport function auditSchedulerModuleQueueRows(\n rows: ReadonlyArray<{\n id: string\n name?: string | null\n targetQueue?: string | null\n sourceType?: string | null\n sourceModule?: string | null\n createdByUserId?: string | null\n isEnabled?: boolean\n }>,\n): SchedulerModuleQueueRowAudit[] {\n return rows\n .filter((row) => row.sourceType === 'module' && row.targetQueue)\n .map((row) => ({\n scheduleId: row.id,\n name: row.name ?? undefined,\n sourceModule: row.sourceModule ?? null,\n targetQueue: row.targetQueue ?? null,\n isEnabled: row.isEnabled !== false,\n dispatchAllowed: canDispatchScheduleQueueTarget(row),\n }))\n}\n\n/**\n * Dispatch-time authorization for queue-targeted schedules (#5213).\n *\n * Provenance is server-owned and verified, never trusted from the stored row:\n * - API-authored schedules (`sourceType: 'user'`) may only target queues whose\n * workers all opted into scheduling.\n * - Module-authored schedules are accepted only when the recorded\n * `sourceModule` owns the queue in the live registry AND the row carries no\n * acting-user stamp (`createdByUserId == null`) \u2014 `schedulerService.register()`\n * never stamps one while every interactive API write does. Residual limit: a\n * pre-upgrade row authored by a non-user-bound API key also lacks the stamp;\n * surface those with `auditSchedulerModuleQueueRows` /\n * `mercato scheduler audit-queue-targets`.\n */\nexport function canDispatchScheduleQueueTarget(schedule: {\n targetQueue?: string | null\n sourceType?: string | null\n sourceModule?: string | null\n /** Server-stamped actor on API-authored rows; module registration never sets it. */\n createdByUserId?: string | null\n}): boolean {\n if (!schedule.targetQueue) return false\n if (schedule.sourceType === 'module') {\n // Provenance must be server-owned, and both stored fields were client-\n // writable before #5213. A matching sourceModule alone is forgeable public\n // knowledge, so a persisted module row is only trusted when it also carries\n // no acting-user stamp: `schedulerService.register()` never sets one, while\n // every API write does. Forged pre-upgrade rows fail closed here.\n if (!schedule.sourceModule) return false\n if (schedule.createdByUserId) return false\n return findQueueOwnerModuleIds(schedule.targetQueue).has(schedule.sourceModule)\n }\n return isSchedulerSafeQueue(schedule.targetQueue)\n}\n\n// Built-in opted-in target owned by this module: the side-effect-free QA echo\n// queue. The strict shape keeps scheduler-controlled payloads predictable and\n// gives deployments a working reference for registering their own schemas.\nregisterSchedulerQueuePayloadSchema(\n 'scheduler-test',\n z.object({ message: z.string().max(200).optional() }).passthrough(),\n)\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,SAA0B;AA4BnC,MAAM,2BAA2B,oBAAI,IAAwB;AAEtD,SAAS,oCAAoC,OAAe,QAA0B;AAC3F,2BAAyB,IAAI,OAAO,MAAM;AAC5C;AAEO,SAAS,+BAA+B,OAAkC;AAC/E,SAAO,yBAAyB,IAAI,KAAK,KAAK;AAChD;AAiBA,eAAsB,qCAAqC,QAOhC;AACzB,QAAM,mBAAmB,kCAAkC,OAAO,KAAK;AACvE,MAAI,iBAAiB,WAAW,EAAG,QAAO;AAC1C,MAAI,OAAO,iBAAiB,KAAM,QAAO;AAEzC,QAAM,cAAc,OAAO,OAAO,gBAAgB,WAAW,OAAO,YAAY,KAAK,IAAI;AACzF,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI,OAAO,OAAO,aAAa,uBAAuB,YAAY;AAChE,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,MAAM,OAAO,YAAY,mBAAmB,aAAa,kBAAkB;AAAA,IAC5F,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,EAC3C,CAAC;AACD,MAAI,CAAC,YAAY;AACf,WAAO,+DAA+D,iBAAiB,KAAK,IAAI,CAAC;AAAA,EACnG;AACA,SAAO;AACT;AAOO,SAAS,+BACd,OACA,eACe;AACf,QAAM,SAAS,+BAA+B,KAAK;AACnD,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,SAAS,OAAO,UAAU,iBAAiB,CAAC,CAAC;AACnD,MAAI,OAAO,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W,OAAO,UAAU,KAAK,GAAG,oBAAoB,CAAC;AACxG;AAKA,SAAS,wBAAwB,OAA4B;AAC3D,QAAM,SAAS,oBAAI,IAAY;AAC/B,aAAW,CAAC,WAAW,SAAS,KAAK,sBAAsB,GAAG;AAC5D,QAAI,cAAc,MAAO;AACzB,eAAW,UAAU,WAAW;AAC9B,UAAI,OAAO,OAAO,OAAO,SAAU,QAAO,IAAI,OAAO,GAAG,MAAM,GAAG,EAAE,CAAC,KAAK,EAAE;AAAA,IAC7E;AAAA,EACF;AACA,SAAO;AACT;AAsBO,SAAS,8BACd,MASgC;AAChC,SAAO,KACJ,OAAO,CAAC,QAAQ,IAAI,eAAe,YAAY,IAAI,WAAW,EAC9D,IAAI,CAAC,SAAS;AAAA,IACb,YAAY,IAAI;AAAA,IAChB,MAAM,IAAI,QAAQ;AAAA,IAClB,cAAc,IAAI,gBAAgB;AAAA,IAClC,aAAa,IAAI,eAAe;AAAA,IAChC,WAAW,IAAI,cAAc;AAAA,IAC7B,iBAAiB,+BAA+B,GAAG;AAAA,EACrD,EAAE;AACN;AAgBO,SAAS,+BAA+B,UAMnC;AACV,MAAI,CAAC,SAAS,YAAa,QAAO;AAClC,MAAI,SAAS,eAAe,UAAU;AAMpC,QAAI,CAAC,SAAS,aAAc,QAAO;AACnC,QAAI,SAAS,gBAAiB,QAAO;AACrC,WAAO,wBAAwB,SAAS,WAAW,EAAE,IAAI,SAAS,YAAY;AAAA,EAChF;AACA,SAAO,qBAAqB,SAAS,WAAW;AAClD;AAKA;AAAA,EACE;AAAA,EACA,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,CAAC,EAAE,YAAY;AACpE;",
4
+ "sourcesContent": ["import { getModules } from '@open-mercato/shared/lib/modules/registry'\nimport type { ModuleWorker } from '@open-mercato/shared/modules/registry'\nimport { z, type ZodTypeAny } from 'zod'\n\nexport type SchedulerSafeQueueTarget = {\n queue: string\n /**\n * Indicative primary owner \u2014 the first registry module found among the\n * queue's consumers. A queue may legitimately have consumers from more than\n * one module; ownership for provenance checks is always resolved per module.\n */\n moduleId: string\n /** Extra creator features a principal must hold to schedule onto this queue. */\n requiredFeatures: string[]\n}\n\nexport type TrustedScheduleScope = {\n tenantId: string | null\n organizationId: string | null\n}\n\n/**\n * Runtime payload schemas for opted-in scheduler targets.\n *\n * Worker metadata cannot carry a Zod schema through static registry generation,\n * so the module that owns a schedulable worker registers its target payload\n * schema here at bootstrap. Targets without a registered schema accept\n * arbitrary JSON payloads (documented escape hatch, mirroring scheduler-safe\n * commands which also carry no payload schema).\n */\nconst registeredPayloadSchemas = new Map<string, ZodTypeAny>()\n\nexport function registerSchedulerQueuePayloadSchema(queue: string, schema: ZodTypeAny): void {\n registeredPayloadSchemas.set(queue, schema)\n}\n\nexport function getSchedulerQueuePayloadSchema(queue: string): ZodTypeAny | null {\n return registeredPayloadSchemas.get(queue) ?? null\n}\n\nexport type SchedulerTargetRbacService = {\n userHasAllFeatures?: (\n userId: string,\n required: readonly string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<boolean>\n}\n\n/**\n * Creator-side authorization for an opted-in queue target (#5213): a principal\n * must hold every feature the target declares beyond `scheduler.jobs.manage`.\n * Super administrators bypass target-specific checks, mirroring the rest of\n * the scheduler's authorization model. Returns null when authorized,\n * otherwise a short reason string.\n */\nexport async function assertSchedulerQueueTargetAuthorized(params: {\n queue: string\n actorUserId?: string | null\n tenantId?: string | null\n organizationId?: string | null\n isSuperAdmin?: boolean\n rbacService?: SchedulerTargetRbacService | null\n}): Promise<string | null> {\n const requiredFeatures = getSchedulerQueueRequiredFeatures(params.queue)\n if (requiredFeatures.length === 0) return null\n if (params.isSuperAdmin === true) return null\n\n const actorUserId = typeof params.actorUserId === 'string' ? params.actorUserId.trim() : ''\n if (!actorUserId) return 'Scheduler queue target requires an authenticated creator'\n if (typeof params.rbacService?.userHasAllFeatures !== 'function') {\n return 'Scheduler queue target authorization is unavailable'\n }\n\n const authorized = await params.rbacService.userHasAllFeatures(actorUserId, requiredFeatures, {\n tenantId: params.tenantId ?? null,\n organizationId: params.organizationId ?? null,\n })\n if (!authorized) {\n return `Scheduler queue target requires features the creator lacks: ${requiredFeatures.join(', ')}`\n }\n return null\n}\n\n/**\n * Validates an author-supplied target payload against the target's registered\n * schema, when one exists. Returns null when the payload is acceptable,\n * otherwise a short reason string.\n */\nexport function validateSchedulerTargetPayload(\n queue: string,\n targetPayload: Record<string, unknown> | null | undefined,\n): string | null {\n const schema = getSchedulerQueuePayloadSchema(queue)\n if (!schema) return null\n const result = schema.safeParse(targetPayload ?? {})\n if (result.success) return null\n const firstIssue = result.error.issues[0]\n return [\n firstIssue?.path?.length ? `${firstIssue.path.join('.')}: ` : '',\n firstIssue?.message ?? 'Invalid payload',\n ].join('')\n}\n\n/**\n * Keys a schedule author may never control on a dispatched target payload:\n * tenant/organization authority context and the reserved `_`-prefixed envelope\n * namespace (idempotency keys, dispatch-origin markers, \u2026).\n */\nconst RESERVED_PAYLOAD_KEYS = new Set(['tenantId', 'organizationId', 'scope'])\n\nfunction isReservedPayloadKey(key: string): boolean {\n return RESERVED_PAYLOAD_KEYS.has(key) || key.startsWith('_')\n}\n\nfunction stripReservedKeys(payload: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(payload)) {\n if (isReservedPayloadKey(key)) continue\n if (key === 'payload' && value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result[key] = stripReservedKeys(value as Record<string, unknown>)\n continue\n }\n result[key] = value\n }\n return result\n}\n\n/**\n * Rebuild the trusted scope for a dispatched schedule payload from the stored\n * schedule row. Callers must never trust scope-shaped data from the schedule\n * author's `targetPayload`.\n */\nexport function buildTrustedScheduleScope(schedule: {\n tenantId?: string | null\n organizationId?: string | null\n}): TrustedScheduleScope {\n return {\n tenantId: schedule.tenantId ?? null,\n organizationId: schedule.organizationId ?? null,\n }\n}\n\n/**\n * Sanitize an author-supplied schedule target payload before dispatch:\n * deep-copies it, strips reserved authority and `_`-prefixed envelope keys at\n * the payload root and inside the local-strategy `payload` wrapper level, then\n * injects the trusted scope derived from the schedule row.\n */\nexport function sanitizeSchedulerTargetPayload(\n targetPayload: Record<string, unknown> | null | undefined,\n schedule: Parameters<typeof buildTrustedScheduleScope>[0],\n): Record<string, unknown> {\n const source = targetPayload ?? {}\n const cloned = structuredClone(source)\n const stripped = stripReservedKeys(cloned)\n return {\n ...stripped,\n scope: buildTrustedScheduleScope(schedule),\n }\n}\n\n/**\n * A queue consumer paired with the registry module that declared it.\n *\n * The owning module is carried explicitly because a worker id is free-form\n * metadata: nothing constrains its prefix to match the id of the module that\n * registers it, and several modules whose id contains `_` spell their worker\n * ids with `-` (`data_sync` \u2192 `data-sync:scheduled`). Ownership must come from\n * the registry, never from parsing the worker id.\n */\ntype QueueConsumer = {\n moduleId: string\n worker: ModuleWorker\n}\n\nconst queueConsumerCache = new WeakMap<object, Map<string, QueueConsumer[]>>()\n\nfunction collectQueueConsumers(): Map<string, QueueConsumer[]> {\n let modules: ReturnType<typeof getModules>\n try {\n modules = getModules()\n } catch {\n return new Map()\n }\n // The registry returns the same array instance between registrations, so the\n // grouped map can be memoized per instance instead of rebuilt per lookup.\n const cached = queueConsumerCache.get(modules)\n if (cached) return cached\n\n const byQueue = new Map<string, QueueConsumer[]>()\n for (const mod of modules) {\n for (const worker of mod.workers ?? []) {\n if (!worker.queue) continue\n const consumers = byQueue.get(worker.queue) ?? []\n consumers.push({ moduleId: mod.id, worker })\n byQueue.set(worker.queue, consumers)\n }\n }\n queueConsumerCache.set(modules, byQueue)\n return byQueue\n}\n\n/**\n * Enumerate queue targets that are safe for user-facing scheduling (#5213):\n * every worker consuming the queue must explicitly opt in \u2014 queue consumers\n * compete for the same jobs, so a single non-opted-in consumer would otherwise\n * receive scheduler-controlled payloads it never agreed to accept.\n */\nexport function listSchedulerSafeQueueTargets(): SchedulerSafeQueueTarget[] {\n const targets: SchedulerSafeQueueTarget[] = []\n for (const [queue, consumers] of collectQueueConsumers()) {\n const optedIn = consumers.filter((consumer) => consumer.worker.schedulerSafe === true)\n if (optedIn.length === 0 || optedIn.length !== consumers.length) continue\n\n const requiredFeatures = [...new Set(optedIn.flatMap((consumer) => (\n Array.isArray(consumer.worker.schedulerRequiredFeatures) ? consumer.worker.schedulerRequiredFeatures : []\n )))]\n const ownerModuleIds = [...new Set(consumers.map((consumer) => consumer.moduleId))]\n targets.push({ queue, moduleId: ownerModuleIds[0] ?? '', requiredFeatures })\n }\n targets.sort((a, b) => a.queue.localeCompare(b.queue))\n return targets\n}\n\nexport function isSchedulerSafeQueue(queue: string | null | undefined): boolean {\n if (!queue) return false\n return listSchedulerSafeQueueTargets().some((target) => target.queue === queue)\n}\n\n/**\n * Extra creator features required by the target queue beyond\n * `scheduler.jobs.manage` (#5213). Empty when the target declares none.\n */\nexport function getSchedulerQueueRequiredFeatures(queue: string): string[] {\n return listSchedulerSafeQueueTargets().find((target) => target.queue === queue)?.requiredFeatures ?? []\n}\n\n/**\n * The module ids that own workers on this queue, as recorded by the live\n * registry \u2014 not as spelled in the workers' own ids (see `QueueConsumer`).\n */\nfunction findQueueOwnerModuleIds(queue: string): Set<string> {\n const owners = new Set<string>()\n for (const consumer of collectQueueConsumers().get(queue) ?? []) {\n owners.add(consumer.moduleId)\n }\n return owners\n}\n\n/**\n * Operator-facing audit for persisted module-authored queue rows (#5213).\n *\n * Provenance on pre-upgrade rows is not fully verifiable at rest: a row created\n * by a non-user-bound API key carries no acting-user stamp, making it\n * indistinguishable from a genuine module registration. This helper surfaces\n * every module-authored queue-target row with its current dispatch verdict so\n * operators can review the allowed ones against their known integrations\n * (`mercato scheduler audit-queue-targets`).\n */\nexport type SchedulerModuleQueueRowAudit = {\n scheduleId: string\n name?: string\n sourceModule: string | null\n targetQueue: string | null\n isEnabled: boolean\n /** Whether the dispatch guard currently lets this row fire. */\n dispatchAllowed: boolean\n}\n\nexport function auditSchedulerModuleQueueRows(\n rows: ReadonlyArray<{\n id: string\n name?: string | null\n targetQueue?: string | null\n sourceType?: string | null\n sourceModule?: string | null\n createdByUserId?: string | null\n isEnabled?: boolean\n }>,\n): SchedulerModuleQueueRowAudit[] {\n return rows\n .filter((row) => row.sourceType === 'module' && row.targetQueue)\n .map((row) => ({\n scheduleId: row.id,\n name: row.name ?? undefined,\n sourceModule: row.sourceModule ?? null,\n targetQueue: row.targetQueue ?? null,\n isEnabled: row.isEnabled !== false,\n dispatchAllowed: canDispatchScheduleQueueTarget(row),\n }))\n}\n\n/**\n * Dispatch-time authorization for queue-targeted schedules (#5213).\n *\n * Provenance is server-owned and verified, never trusted from the stored row:\n * - API-authored schedules (`sourceType: 'user'`) may only target queues whose\n * workers all opted into scheduling.\n * - Module-authored schedules are accepted only when the recorded\n * `sourceModule` owns the queue in the live registry AND the row carries no\n * acting-user stamp (`createdByUserId == null`) \u2014 `schedulerService.register()`\n * never stamps one while every interactive API write does. Residual limit: a\n * pre-upgrade row authored by a non-user-bound API key also lacks the stamp;\n * surface those with `auditSchedulerModuleQueueRows` /\n * `mercato scheduler audit-queue-targets`.\n */\nexport function canDispatchScheduleQueueTarget(schedule: {\n targetQueue?: string | null\n sourceType?: string | null\n sourceModule?: string | null\n /** Server-stamped actor on API-authored rows; module registration never sets it. */\n createdByUserId?: string | null\n}): boolean {\n if (!schedule.targetQueue) return false\n if (schedule.sourceType === 'module') {\n // Provenance must be server-owned, and both stored fields were client-\n // writable before #5213. A matching sourceModule alone is forgeable public\n // knowledge, so a persisted module row is only trusted when it also carries\n // no acting-user stamp: `schedulerService.register()` never sets one, while\n // every API write does. Forged pre-upgrade rows fail closed here.\n if (!schedule.sourceModule) return false\n if (schedule.createdByUserId) return false\n return findQueueOwnerModuleIds(schedule.targetQueue).has(schedule.sourceModule)\n }\n return isSchedulerSafeQueue(schedule.targetQueue)\n}\n\n// Built-in opted-in target owned by this module: the side-effect-free QA echo\n// queue. The strict shape keeps scheduler-controlled payloads predictable and\n// gives deployments a working reference for registering their own schemas.\nregisterSchedulerQueuePayloadSchema(\n 'scheduler-test',\n z.object({ message: z.string().max(200).optional() }).passthrough(),\n)\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,SAA0B;AA4BnC,MAAM,2BAA2B,oBAAI,IAAwB;AAEtD,SAAS,oCAAoC,OAAe,QAA0B;AAC3F,2BAAyB,IAAI,OAAO,MAAM;AAC5C;AAEO,SAAS,+BAA+B,OAAkC;AAC/E,SAAO,yBAAyB,IAAI,KAAK,KAAK;AAChD;AAiBA,eAAsB,qCAAqC,QAOhC;AACzB,QAAM,mBAAmB,kCAAkC,OAAO,KAAK;AACvE,MAAI,iBAAiB,WAAW,EAAG,QAAO;AAC1C,MAAI,OAAO,iBAAiB,KAAM,QAAO;AAEzC,QAAM,cAAc,OAAO,OAAO,gBAAgB,WAAW,OAAO,YAAY,KAAK,IAAI;AACzF,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI,OAAO,OAAO,aAAa,uBAAuB,YAAY;AAChE,WAAO;AAAA,EACT;AAEA,QAAM,aAAa,MAAM,OAAO,YAAY,mBAAmB,aAAa,kBAAkB;AAAA,IAC5F,UAAU,OAAO,YAAY;AAAA,IAC7B,gBAAgB,OAAO,kBAAkB;AAAA,EAC3C,CAAC;AACD,MAAI,CAAC,YAAY;AACf,WAAO,+DAA+D,iBAAiB,KAAK,IAAI,CAAC;AAAA,EACnG;AACA,SAAO;AACT;AAOO,SAAS,+BACd,OACA,eACe;AACf,QAAM,SAAS,+BAA+B,KAAK;AACnD,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,SAAS,OAAO,UAAU,iBAAiB,CAAC,CAAC;AACnD,MAAI,OAAO,QAAS,QAAO;AAC3B,QAAM,aAAa,OAAO,MAAM,OAAO,CAAC;AACxC,SAAO;AAAA,IACL,YAAY,MAAM,SAAS,GAAG,WAAW,KAAK,KAAK,GAAG,CAAC,OAAO;AAAA,IAC9D,YAAY,WAAW;AAAA,EACzB,EAAE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,QAAQ;AAAA,EAC9B;AACA,SAAO;AACT;AAsBO,SAAS,8BACd,MASgC;AAChC,SAAO,KACJ,OAAO,CAAC,QAAQ,IAAI,eAAe,YAAY,IAAI,WAAW,EAC9D,IAAI,CAAC,SAAS;AAAA,IACb,YAAY,IAAI;AAAA,IAChB,MAAM,IAAI,QAAQ;AAAA,IAClB,cAAc,IAAI,gBAAgB;AAAA,IAClC,aAAa,IAAI,eAAe;AAAA,IAChC,WAAW,IAAI,cAAc;AAAA,IAC7B,iBAAiB,+BAA+B,GAAG;AAAA,EACrD,EAAE;AACN;AAgBO,SAAS,+BAA+B,UAMnC;AACV,MAAI,CAAC,SAAS,YAAa,QAAO;AAClC,MAAI,SAAS,eAAe,UAAU;AAMpC,QAAI,CAAC,SAAS,aAAc,QAAO;AACnC,QAAI,SAAS,gBAAiB,QAAO;AACrC,WAAO,wBAAwB,SAAS,WAAW,EAAE,IAAI,SAAS,YAAY;AAAA,EAChF;AACA,SAAO,qBAAqB,SAAS,WAAW;AAClD;AAKA;AAAA,EACE;AAAA,EACA,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,CAAC,EAAE,YAAY;AACpE;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/scheduler",
3
- "version": "0.10.1-develop.7728.1.6b52eb2849",
3
+ "version": "0.10.1-develop.7736.1.88e07906bf",
4
4
  "license": "MIT",
5
5
  "description": "Database-managed scheduled jobs with admin UI",
6
6
  "type": "module",
@@ -59,13 +59,13 @@
59
59
  "./*/*/*/*/*/*.json": "./src/*/*/*/*/*/*.json"
60
60
  },
61
61
  "dependencies": {
62
- "@open-mercato/events": "0.10.1-develop.7728.1.6b52eb2849",
63
- "@open-mercato/queue": "0.10.1-develop.7728.1.6b52eb2849",
62
+ "@open-mercato/events": "0.10.1-develop.7736.1.88e07906bf",
63
+ "@open-mercato/queue": "0.10.1-develop.7736.1.88e07906bf",
64
64
  "cron-parser": "^5.6.2"
65
65
  },
66
66
  "peerDependencies": {
67
67
  "@mikro-orm/core": "^7.0.14",
68
- "@open-mercato/shared": "0.10.1-develop.7728.1.6b52eb2849",
68
+ "@open-mercato/shared": "0.10.1-develop.7736.1.88e07906bf",
69
69
  "bullmq": "^5.0.0 || ^6.0.0",
70
70
  "ioredis": "^5.0.0 || ^6.0.0",
71
71
  "zod": ">=3.23.0"
@@ -79,7 +79,7 @@
79
79
  }
80
80
  },
81
81
  "devDependencies": {
82
- "@open-mercato/shared": "0.10.1-develop.7728.1.6b52eb2849",
82
+ "@open-mercato/shared": "0.10.1-develop.7736.1.88e07906bf",
83
83
  "@types/jest": "^30.0.0",
84
84
  "@types/node": "^26.4.0",
85
85
  "jest": "^30.4.2",
@@ -67,6 +67,24 @@ beforeAll(() => {
67
67
  },
68
68
  ],
69
69
  },
70
+ {
71
+ id: 'gamma_module',
72
+ workers: [
73
+ {
74
+ id: 'gamma-module:workers:scheduled',
75
+ queue: 'gamma-module-scheduled',
76
+ concurrency: 1,
77
+ handler: async () => {},
78
+ },
79
+ {
80
+ id: 'gamma-module:workers:safe',
81
+ queue: 'gamma-module-safe',
82
+ concurrency: 1,
83
+ schedulerSafe: true,
84
+ handler: async () => {},
85
+ },
86
+ ],
87
+ },
70
88
  ] as never)
71
89
  })
72
90
 
@@ -78,6 +96,7 @@ describe('listSchedulerSafeQueueTargets', () => {
78
96
  it('returns only queues whose workers ALL opted into scheduling, deduplicated and sorted', () => {
79
97
  expect(listSchedulerSafeQueueTargets()).toEqual([
80
98
  { queue: 'alpha-safe', moduleId: 'alpha', requiredFeatures: [] },
99
+ { queue: 'gamma-module-safe', moduleId: 'gamma_module', requiredFeatures: [] },
81
100
  { queue: 'gated-queue', moduleId: 'alpha', requiredFeatures: ['orders.export'] },
82
101
  ])
83
102
  })
@@ -160,6 +179,22 @@ describe('canDispatchScheduleQueueTarget', () => {
160
179
  })).toBe(true)
161
180
  })
162
181
 
182
+ it('resolves ownership from the registry when the worker id is spelled differently', () => {
183
+ expect(canDispatchScheduleQueueTarget({
184
+ targetQueue: 'gamma-module-scheduled',
185
+ sourceType: 'module',
186
+ sourceModule: 'gamma_module',
187
+ })).toBe(true)
188
+ })
189
+
190
+ it('does not accept the worker id prefix as a module id', () => {
191
+ expect(canDispatchScheduleQueueTarget({
192
+ targetQueue: 'gamma-module-scheduled',
193
+ sourceType: 'module',
194
+ sourceModule: 'gamma-module',
195
+ })).toBe(false)
196
+ })
197
+
163
198
  it('fails closed on pre-upgrade/forged module rows (#5213 B1)', () => {
164
199
  // legacy row without any recorded owner
165
200
  expect(canDispatchScheduleQueueTarget({ targetQueue: 'alpha-internal', sourceType: 'module' })).toBe(false)
@@ -159,9 +159,23 @@ export function sanitizeSchedulerTargetPayload(
159
159
  }
160
160
  }
161
161
 
162
- const queueConsumerCache = new WeakMap<object, Map<string, ModuleWorker[]>>()
162
+ /**
163
+ * A queue consumer paired with the registry module that declared it.
164
+ *
165
+ * The owning module is carried explicitly because a worker id is free-form
166
+ * metadata: nothing constrains its prefix to match the id of the module that
167
+ * registers it, and several modules whose id contains `_` spell their worker
168
+ * ids with `-` (`data_sync` → `data-sync:scheduled`). Ownership must come from
169
+ * the registry, never from parsing the worker id.
170
+ */
171
+ type QueueConsumer = {
172
+ moduleId: string
173
+ worker: ModuleWorker
174
+ }
175
+
176
+ const queueConsumerCache = new WeakMap<object, Map<string, QueueConsumer[]>>()
163
177
 
164
- function collectQueueConsumers(): Map<string, ModuleWorker[]> {
178
+ function collectQueueConsumers(): Map<string, QueueConsumer[]> {
165
179
  let modules: ReturnType<typeof getModules>
166
180
  try {
167
181
  modules = getModules()
@@ -173,12 +187,12 @@ function collectQueueConsumers(): Map<string, ModuleWorker[]> {
173
187
  const cached = queueConsumerCache.get(modules)
174
188
  if (cached) return cached
175
189
 
176
- const byQueue = new Map<string, ModuleWorker[]>()
190
+ const byQueue = new Map<string, QueueConsumer[]>()
177
191
  for (const mod of modules) {
178
192
  for (const worker of mod.workers ?? []) {
179
193
  if (!worker.queue) continue
180
194
  const consumers = byQueue.get(worker.queue) ?? []
181
- consumers.push(worker)
195
+ consumers.push({ moduleId: mod.id, worker })
182
196
  byQueue.set(worker.queue, consumers)
183
197
  }
184
198
  }
@@ -195,15 +209,13 @@ function collectQueueConsumers(): Map<string, ModuleWorker[]> {
195
209
  export function listSchedulerSafeQueueTargets(): SchedulerSafeQueueTarget[] {
196
210
  const targets: SchedulerSafeQueueTarget[] = []
197
211
  for (const [queue, consumers] of collectQueueConsumers()) {
198
- const optedIn = consumers.filter((worker) => worker.schedulerSafe === true)
212
+ const optedIn = consumers.filter((consumer) => consumer.worker.schedulerSafe === true)
199
213
  if (optedIn.length === 0 || optedIn.length !== consumers.length) continue
200
214
 
201
- const requiredFeatures = [...new Set(optedIn.flatMap((worker) => (
202
- Array.isArray(worker.schedulerRequiredFeatures) ? worker.schedulerRequiredFeatures : []
203
- )))]
204
- const ownerModuleIds = [...new Set(consumers.map((worker) => (
205
- typeof worker.id === 'string' ? (worker.id.split(':')[0] ?? '') : ''
215
+ const requiredFeatures = [...new Set(optedIn.flatMap((consumer) => (
216
+ Array.isArray(consumer.worker.schedulerRequiredFeatures) ? consumer.worker.schedulerRequiredFeatures : []
206
217
  )))]
218
+ const ownerModuleIds = [...new Set(consumers.map((consumer) => consumer.moduleId))]
207
219
  targets.push({ queue, moduleId: ownerModuleIds[0] ?? '', requiredFeatures })
208
220
  }
209
221
  targets.sort((a, b) => a.queue.localeCompare(b.queue))
@@ -224,15 +236,13 @@ export function getSchedulerQueueRequiredFeatures(queue: string): string[] {
224
236
  }
225
237
 
226
238
  /**
227
- * The module ids that own workers on this queue, from the live registry.
239
+ * The module ids that own workers on this queue, as recorded by the live
240
+ * registry — not as spelled in the workers' own ids (see `QueueConsumer`).
228
241
  */
229
242
  function findQueueOwnerModuleIds(queue: string): Set<string> {
230
243
  const owners = new Set<string>()
231
- for (const [candidate, consumers] of collectQueueConsumers()) {
232
- if (candidate !== queue) continue
233
- for (const worker of consumers) {
234
- if (typeof worker.id === 'string') owners.add(worker.id.split(':')[0] ?? '')
235
- }
244
+ for (const consumer of collectQueueConsumers().get(queue) ?? []) {
245
+ owners.add(consumer.moduleId)
236
246
  }
237
247
  return owners
238
248
  }