@open-mercato/core 0.6.7-develop.6825.1.85bbf320ad → 0.6.7-develop.6826.1.3f6d307d01

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.
@@ -13,6 +13,8 @@ import {
13
13
  } from "@open-mercato/core/modules/customer_accounts/lib/rateLimiter";
14
14
  import { readNormalizedEmailFromJsonRequest } from "@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier";
15
15
  import { sendCustomerInvitationEmail } from "@open-mercato/core/modules/customer_accounts/lib/invitationEmail";
16
+ import { createLogger } from "@open-mercato/shared/lib/logger";
17
+ const logger = createLogger("customer_accounts").child({ component: "admin-users-invite" });
16
18
  const metadata = {};
17
19
  function resolveInvitedByUserId(auth) {
18
20
  if (auth.isApiKey) return auth.userId ?? null;
@@ -94,11 +96,11 @@ async function POST(req) {
94
96
  rawToken
95
97
  });
96
98
  } catch (error) {
97
- console.error("[customer_accounts.admin.users-invite] invitation email failed", error);
99
+ logger.error("Invitation email failed", { err: error });
98
100
  try {
99
101
  await customerInvitationService.rollbackInvitation(invitation, rollbackState);
100
102
  } catch (rollbackError) {
101
- console.error("[customer_accounts.admin.users-invite] invitation rollback failed", rollbackError);
103
+ logger.error("Invitation rollback failed", { err: rollbackError });
102
104
  }
103
105
  return NextResponse.json({ ok: false, error: "Invitation email could not be sent" }, { status: 502 });
104
106
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/admin/users-invite.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity, resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\n\nexport const metadata = {}\n\nfunction resolveInvitedByUserId(auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>): string | null {\n if (auth.isApiKey) return auth.userId ?? null\n return auth.sub\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.invite'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n // Reject a customerEntityId the caller does not own. customerEntityId is the\n // CRM company FK; without this check a non-company (e.g. a person) entity id\n // or a company from another org poisons the invitation and every later user\n // edit fails with \"Company not found\" (#4362, #2693).\n if (parsed.data.customerEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK: it is copied onto the customer user on accept\n // and makes `autoLinkCrm` short-circuit, so an unowned id would permanently\n // cross-link the portal user to another org's CRM person.\n let resolvedCustomerEntityId = parsed.data.customerEntityId || null\n if (parsed.data.personEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n\n // An invitation raised from a person card carries only the person FK, and the\n // accepted user then short-circuits `autoLinkCrm`. Resolve the person's company\n // here so the user lands with a company scope key: the portal Users page, portal\n // invitations, and the company detail \"Portal users\" group all filter on it.\n if (!resolvedCustomerEntityId) {\n resolvedCustomerEntityId = await resolveOwnedCompanyForPerson(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId!, organizationId: auth.orgId! },\n {\n customerEntityId: resolvedCustomerEntityId,\n personEntityId: parsed.data.personEntityId || null,\n roleIds: parsed.data.roleIds,\n invitedByUserId: resolveInvitedByUserId(auth),\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId!,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n console.error('[customer_accounts.admin.users-invite] invitation email failed', error)\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n console.error('[customer_accounts.admin.users-invite] invitation rollback failed', rollbackError)\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'staff',\n tenantId: auth.tenantId!,\n organizationId: auth.orgId!,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n // Echo the stored CRM links so the caller can see which company the person\n // invite resolved to. The token stays unexposed.\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite customer user (admin)',\n description: 'Creates a staff-initiated invitation for a new customer user. The invitedByUserId is set from the staff auth context.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite customer user (admin)',\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,sBAAsB,qBAAqB,oCAAoC;AACxF,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAErC,MAAM,WAAW,CAAC;AAEzB,SAAS,uBAAuB,MAAkF;AAChH,MAAI,KAAK,SAAU,QAAO,KAAK,UAAU;AACzC,SAAO,KAAK;AACd;AAEA,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,iBAAiB,MAAM,mCAAmC,GAAG;AACnE,QAAM,EAAE,OAAO,eAAe,IAAI,MAAM,mBAAmB;AAAA,IACzD;AAAA,IACA,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,EACtB,CAAC;AACD,MAAI,eAAgB,QAAO;AAE3B,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KAAK,CAAC,0BAA0B,GAAG,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM,CAAC;AACtJ,MAAI,CAAC,WAAW;AACd,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE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, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity, resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'admin-users-invite' })\n\nexport const metadata = {}\n\nfunction resolveInvitedByUserId(auth: NonNullable<Awaited<ReturnType<typeof getAuthFromRequest>>>): string | null {\n if (auth.isApiKey) return auth.userId ?? null\n return auth.sub\n}\n\nexport async function POST(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.invite'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n // Reject a customerEntityId the caller does not own. customerEntityId is the\n // CRM company FK; without this check a non-company (e.g. a person) entity id\n // or a company from another org poisons the invitation and every later user\n // edit fails with \"Company not found\" (#4362, #2693).\n if (parsed.data.customerEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK: it is copied onto the customer user on accept\n // and makes `autoLinkCrm` short-circuit, so an unowned id would permanently\n // cross-link the portal user to another org's CRM person.\n let resolvedCustomerEntityId = parsed.data.customerEntityId || null\n if (parsed.data.personEntityId) {\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n\n // An invitation raised from a person card carries only the person FK, and the\n // accepted user then short-circuits `autoLinkCrm`. Resolve the person's company\n // here so the user lands with a company scope key: the portal Users page, portal\n // invitations, and the company detail \"Portal users\" group all filter on it.\n if (!resolvedCustomerEntityId) {\n resolvedCustomerEntityId = await resolveOwnedCompanyForPerson(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId!, organizationId: auth.orgId! },\n {\n customerEntityId: resolvedCustomerEntityId,\n personEntityId: parsed.data.personEntityId || null,\n roleIds: parsed.data.roleIds,\n invitedByUserId: resolveInvitedByUserId(auth),\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId!,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'staff',\n tenantId: auth.tenantId!,\n organizationId: auth.orgId!,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n // Echo the stored CRM links so the caller can see which company the person\n // invite resolved to. The token stays unexposed.\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite customer user (admin)',\n description: 'Creates a staff-initiated invitation for a new customer user. The invitedByUserId is set from the staff auth context.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite customer user (admin)',\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,iCAAiC;AAC1C,SAAS,wBAAwB;AACjC,SAAS,sBAAsB,qBAAqB,oCAAoC;AACxF,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAEnF,MAAM,WAAW,CAAC;AAEzB,SAAS,uBAAuB,MAAkF;AAChH,MAAI,KAAK,SAAU,QAAO,KAAK,UAAU;AACzC,SAAO,KAAK;AACd;AAEA,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,iBAAiB,MAAM,mCAAmC,GAAG;AACnE,QAAM,EAAE,OAAO,eAAe,IAAI,MAAM,mBAAmB;AAAA,IACzD;AAAA,IACA,UAAU;AAAA,IACV,gBAAg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KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,qBAAqB;AAAA,IACzF,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -14,6 +14,8 @@ import {
14
14
  } from "@open-mercato/core/modules/customer_accounts/lib/rateLimiter";
15
15
  import { readNormalizedEmailFromJsonRequest } from "@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier";
16
16
  import { sendCustomerInvitationEmail } from "@open-mercato/core/modules/customer_accounts/lib/invitationEmail";
17
+ import { createLogger } from "@open-mercato/shared/lib/logger";
18
+ const logger = createLogger("customer_accounts").child({ component: "portal-users-invite" });
17
19
  const metadata = { requireAuth: false };
18
20
  async function POST(req) {
19
21
  const auth = await getCustomerAuthFromRequest(req);
@@ -91,11 +93,11 @@ async function POST(req) {
91
93
  rawToken
92
94
  });
93
95
  } catch (error) {
94
- console.error("[customer_accounts.portal.users-invite] invitation email failed", error);
96
+ logger.error("Invitation email failed", { err: error });
95
97
  try {
96
98
  await customerInvitationService.rollbackInvitation(invitation, rollbackState);
97
99
  } catch (rollbackError) {
98
- console.error("[customer_accounts.portal.users-invite] invitation rollback failed", rollbackError);
100
+ logger.error("Invitation rollback failed", { err: rollbackError });
99
101
  }
100
102
  return NextResponse.json({ ok: false, error: "Invitation email could not be sent" }, { status: 502 });
101
103
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/portal/users-invite.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n const rolesById = new Map(roles.map((role) => [role.id, role]))\n for (const roleId of requestedRoleIds) {\n const role = rolesById.get(roleId)\n if (!role) {\n return NextResponse.json({ ok: false, error: `Role ${roleId} not found` }, { status: 400 })\n }\n if (!role.customerAssignable) {\n return NextResponse.json({ ok: false, error: `Role \"${role.name}\" cannot be assigned by portal users` }, { status: 403 })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n {\n customerEntityId: auth.customerEntityId,\n roleIds: parsed.data.roleIds,\n invitedByCustomerUserId: auth.sub,\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n console.error('[customer_accounts.portal.users-invite] invitation email failed', error)\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n console.error('[customer_accounts.portal.users-invite] invitation rollback failed', rollbackError)\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'portal',\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite a user to the company portal',\n description: 'Creates an invitation for a new user to join the company portal.',\n tags: ['Customer Portal'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions or non-assignable role', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite portal user',\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAErC,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eA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BAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,YAAY;AAAA,IACnG,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,qBAAqB;AAAA,IACzF,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest, requireCustomerFeature } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerInvitationService } from '@open-mercato/core/modules/customer_accounts/services/customerInvitationService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { inviteUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerInviteRateLimitConfig,\n customerInviteIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'portal-users-invite' })\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerInviteIpRateLimitConfig,\n compoundConfig: customerInviteRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n })\n if (rateLimitError) return rateLimitError\n\n const container = await createRequestContainer()\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n\n try {\n await requireCustomerFeature(auth, ['portal.users.manage'], customerRbacService)\n } catch (response) {\n return response as NextResponse\n }\n\n if (!auth.customerEntityId) {\n return NextResponse.json({ ok: false, error: 'No company association' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = inviteUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n // Validate all roles are customer_assignable\n const requestedRoleIds = parsed.data.roleIds\n const roles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds },\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n const rolesById = new Map(roles.map((role) => [role.id, role]))\n for (const roleId of requestedRoleIds) {\n const role = rolesById.get(roleId)\n if (!role) {\n return NextResponse.json({ ok: false, error: `Role ${roleId} not found` }, { status: 400 })\n }\n if (!role.customerAssignable) {\n return NextResponse.json({ ok: false, error: `Role \"${role.name}\" cannot be assigned by portal users` }, { status: 403 })\n }\n }\n\n const customerInvitationService = container.resolve('customerInvitationService') as CustomerInvitationService\n\n const { invitation, rawToken, rollbackState } = await customerInvitationService.createInvitation(\n parsed.data.email,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n {\n customerEntityId: auth.customerEntityId,\n roleIds: parsed.data.roleIds,\n invitedByCustomerUserId: auth.sub,\n displayName: parsed.data.displayName || null,\n },\n )\n\n try {\n await sendCustomerInvitationEmail({\n container,\n organizationId: auth.orgId,\n email: invitation.email,\n rawToken,\n })\n } catch (error) {\n logger.error('Invitation email failed', { err: error })\n try {\n await customerInvitationService.rollbackInvitation(invitation, rollbackState)\n } catch (rollbackError) {\n logger.error('Invitation rollback failed', { err: rollbackError })\n }\n return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })\n }\n\n // Emit only after the email is sent, so a subscriber observing \"invited\" can\n // assume the recipient was actually notified (no event fires on the 502 path).\n void emitCustomerAccountsEvent('customer_accounts.user.invited', {\n invitationId: invitation.id,\n email: invitation.email,\n customerEntityId: invitation.customerEntityId || null,\n invitedByType: 'portal',\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n }).catch(() => undefined)\n\n return NextResponse.json({\n ok: true,\n invitation: {\n id: invitation.id,\n email: invitation.email,\n expiresAt: invitation.expiresAt,\n },\n }, { status: 201 })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n invitation: z.object({\n id: z.string().uuid(),\n email: z.string(),\n expiresAt: z.string().datetime(),\n }),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Invite a user to the company portal',\n description: 'Creates an invitation for a new user to join the company portal.',\n tags: ['Customer Portal'],\n requestBody: { schema: inviteUserSchema },\n responses: [{ status: 201, description: 'Invitation created', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions or non-assignable role', schema: errorSchema },\n { status: 429, description: 'Too many invitation requests', schema: rateLimitErrorSchema },\n { status: 502, description: 'Invitation email could not be sent', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Invite portal user',\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,4BAA4B,8BAA8B;AACnE,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAE1C,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,mCAAmC;AAC5C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,sBAAsB,CAAC;AAEpF,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,iBAAiB,MAAM,mCAAmC,GAAG;AACnE,QAAM,EAAE,OAAO,eAAe,IAAI,MAAM,mBAAmB;AAAA,IACzD;AAAA,IACA,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,oBAAoB;AAAA,EACtB,CAAC;AACD,MAAI,eAAgB,QAAO;AAE3B,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,sBAAsB,UAAU,QAAQ,qBAAqB;AAEnE,MAAI;AACF,UAAM,uBAAuB,MAAM,CAAC,qBAAqB,GAAG,mBAAmB;AAAA,EACjF,SAAS,UAAU;AACjB,WAAO;AAAA,EACT;AAEA,MAAI,CAAC,KAAK,kBAAkB;AAC1B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;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Y,EAAE,OAAO;AAAA,IACnB,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,IACpB,OAAO,EAAE,OAAO;AAAA,IAChB,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,CAAC;AACH,CAAC;AACD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,aAAa,EAAE,QAAQ,iBAAiB;AAAA,EACxC,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,sBAAsB,QAAQ,cAAc,CAAC;AAAA,EACrF,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,mDAAmD,QAAQ,YAAY;AAAA,IACnG,EAAE,QAAQ,KAAK,aAAa,gCAAgC,QAAQ,qBAAqB;AAAA,IACzF,EAAE,QAAQ,KAAK,aAAa,sCAAsC,QAAQ,YAAY;AAAA,EACxF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -167,7 +167,7 @@ async function executeActivity(em, container, activity, context) {
167
167
  const startTime = Date.now();
168
168
  const timeoutMs = resolveActivityTimeoutMs(activity);
169
169
  const result = timeoutMs ? await executeWithTimeout(
170
- () => executeActivityByType(em, container, activity, context),
170
+ (signal) => executeActivityByType(em, container, activity, context, signal),
171
171
  timeoutMs
172
172
  ) : await executeActivityByType(em, container, activity, context);
173
173
  const executionTimeMs = Date.now() - startTime;
@@ -258,19 +258,19 @@ async function executeActivities(em, container, activities, context) {
258
258
  }
259
259
  return results;
260
260
  }
261
- async function executeActivityByType(em, container, activity, context) {
261
+ async function executeActivityByType(em, container, activity, context, signal) {
262
262
  const interpolatedConfig = interpolateVariables(activity.config, context.workflowContext, context.workflowInstance);
263
263
  switch (activity.activityType) {
264
264
  case "SEND_EMAIL":
265
265
  return await executeSendEmail(interpolatedConfig, context, container);
266
266
  case "CALL_API":
267
- return await executeCallApi(em, interpolatedConfig, context, container);
267
+ return await executeCallApi(em, interpolatedConfig, context, container, signal);
268
268
  case "EMIT_EVENT":
269
269
  return await executeEmitEvent(interpolatedConfig, context, container);
270
270
  case "UPDATE_ENTITY":
271
271
  return await executeUpdateEntity(em, interpolatedConfig, context, container);
272
272
  case "CALL_WEBHOOK":
273
- return await executeCallWebhook(interpolatedConfig, context);
273
+ return await executeCallWebhook(interpolatedConfig, context, { signal });
274
274
  case "EXECUTE_FUNCTION":
275
275
  return await executeFunction(interpolatedConfig, context, container);
276
276
  case "WAIT":
@@ -793,13 +793,15 @@ function sleep(ms) {
793
793
  }
794
794
  async function executeWithTimeout(executor, timeoutMs) {
795
795
  let timeoutId;
796
+ const abortController = new AbortController();
796
797
  const timeoutPromise = new Promise((_, reject) => {
797
798
  timeoutId = setTimeout(() => {
799
+ abortController.abort();
798
800
  reject(new Error(`Activity execution timeout after ${timeoutMs}ms`));
799
801
  }, timeoutMs);
800
802
  });
801
803
  try {
802
- return await Promise.race([executor(), timeoutPromise]);
804
+ return await Promise.race([executor(abortController.signal), timeoutPromise]);
803
805
  } finally {
804
806
  clearTimeout(timeoutId);
805
807
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/workflows/lib/activity-executor.ts"],
4
- "sourcesContent": ["/**\n * Workflows Module - Activity Executor Service\n *\n * Executes workflow activities (send email, call API, emit events, etc.)\n * - Supports multiple activity types\n * - Implements retry logic with exponential backoff\n * - Handles timeouts\n * - Variable interpolation from workflow context\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { WorkflowInstance } from '../data/entities'\nimport { createModuleQueue, Queue } from '@open-mercato/queue'\nimport { getRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport {\n safeOutboundFetch,\n UnsafeOutboundUrlError,\n type HostLookup,\n} from '@open-mercato/shared/lib/url-safety'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { callWebhookConfigSchema } from '../data/validators'\nimport { WorkflowActivityJob, WORKFLOW_ACTIVITIES_QUEUE_NAME } from './activity-queue-types'\nimport { logWorkflowEvent } from './event-logger'\nimport { parseDuration } from './duration'\nimport { getWorkflowSafeCommand } from './workflow-safe-commands'\n\nexport { isPrivateUrl } from '@open-mercato/shared/lib/network'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nfunction isAllowPrivateWorkflowWebhookUrlsEnabled(): boolean {\n if (parseBooleanWithDefault(process.env.OM_WORKFLOWS_ALLOW_PRIVATE_URLS, false)) {\n if (process.env.NODE_ENV === 'production') {\n logger.warn('OM_WORKFLOWS_ALLOW_PRIVATE_URLS is set but ignored in production. SSRF protection remains enabled.', { component: 'CALL_WEBHOOK' })\n return false\n }\n\n logger.warn('OM_WORKFLOWS_ALLOW_PRIVATE_URLS is enabled. SSRF protection is bypassed for workflow webhooks; use only in development.', { component: 'CALL_WEBHOOK' })\n return true\n }\n\n if (parseBooleanWithDefault(process.env.WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS, false)) {\n if (process.env.NODE_ENV === 'production') {\n logger.warn('WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS is deprecated and ignored in production. Use OM_WORKFLOWS_ALLOW_PRIVATE_URLS for development only. SSRF protection remains enabled.', { component: 'CALL_WEBHOOK' })\n return false\n }\n\n logger.warn('WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS is deprecated. Use OM_WORKFLOWS_ALLOW_PRIVATE_URLS instead. SSRF protection is bypassed.', { component: 'CALL_WEBHOOK' })\n return true\n }\n\n return false\n}\n\nconst DEFAULT_WORKFLOW_ENV_INTERPOLATION_ALLOWLIST = new Set(['APP_URL'])\nconst WORKFLOW_ENV_INTERPOLATION_ALLOWLIST_KEY = 'OM_WORKFLOWS_ENV_INTERPOLATION_ALLOWLIST'\n\nfunction getWorkflowEnvInterpolationAllowlist(): Set<string> {\n const allowlist = new Set(DEFAULT_WORKFLOW_ENV_INTERPOLATION_ALLOWLIST)\n const configuredKeys = process.env[WORKFLOW_ENV_INTERPOLATION_ALLOWLIST_KEY]\n if (!configuredKeys) {\n return allowlist\n }\n\n for (const key of configuredKeys.split(',')) {\n const trimmedKey = key.trim()\n if (trimmedKey) {\n allowlist.add(trimmedKey)\n }\n }\n\n return allowlist\n}\n\nfunction resolveWorkflowEnvInterpolation(envKey: string): string {\n if (!getWorkflowEnvInterpolationAllowlist().has(envKey)) {\n return ''\n }\n\n return process.env[envKey] ?? ''\n}\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport type ActivityType =\n | 'SEND_EMAIL'\n | 'CALL_API'\n | 'EMIT_EVENT'\n | 'UPDATE_ENTITY'\n | 'CALL_WEBHOOK'\n | 'EXECUTE_FUNCTION'\n | 'WAIT'\n\nexport interface ActivityDefinition {\n activityId: string // Unique identifier for activity\n activityName?: string // Optional, for debugging/logging\n activityType: ActivityType\n config: any\n async?: boolean // Flag to execute activity asynchronously via queue\n retryPolicy?: RetryPolicy\n timeoutMs?: number\n /**\n * @deprecated Use `timeoutMs`. Legacy ISO 8601 duration string accepted by\n * the definition schema before #4424; normalized by `resolveActivityTimeoutMs`.\n */\n timeout?: string\n compensate?: boolean // Flag to execute compensation on failure\n}\n\n/**\n * Effective timeout for an activity, in milliseconds.\n *\n * The editor and this executor both speak `timeoutMs`, but the definition\n * schema historically accepted only an ISO 8601 `timeout` string \u2014 so stored\n * definitions can carry either. Prefer `timeoutMs`; fall back to parsing\n * `timeout`, ignoring a malformed value rather than throwing mid-execution\n * (an unparseable timeout must not fail an activity that would otherwise\n * succeed). Returns undefined when no usable timeout is configured (#4424).\n */\nexport function resolveActivityTimeoutMs(activity: {\n timeoutMs?: number\n timeout?: string\n}): number | undefined {\n if (typeof activity.timeoutMs === 'number' && activity.timeoutMs > 0) {\n return activity.timeoutMs\n }\n if (typeof activity.timeout === 'string' && activity.timeout.trim().length > 0) {\n try {\n const parsed = parseDuration(activity.timeout.trim())\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nexport interface RetryPolicy {\n maxAttempts: number\n initialIntervalMs: number\n backoffCoefficient: number\n maxIntervalMs: number\n}\n\nexport interface ActivityContext {\n workflowInstance: WorkflowInstance\n workflowContext: Record<string, any>\n stepContext?: Record<string, any>\n stepInstanceId?: string\n // Set when the activity runs inside a parallel branch; carried on the queue\n // payload so async resume targets the branch rather than the instance.\n branchInstanceId?: string | null\n transitionId?: string\n userId?: string\n}\n\ntype RbacFeatureResolver = {\n userHasAllFeatures: (\n userId: string,\n required: string[],\n opts: { tenantId: string | null; organizationId: string | null }\n ) => Promise<boolean>\n}\n\nasync function workflowUserHasAllFeatures(\n container: AwilixContainer,\n userId: string,\n required: readonly string[],\n tenantId: string | null,\n organizationId: string | null\n): Promise<boolean> {\n try {\n const rbac = container.resolve('rbacService') as RbacFeatureResolver | undefined\n if (rbac?.userHasAllFeatures) {\n return await rbac.userHasAllFeatures(userId, [...required], { tenantId, organizationId })\n }\n } catch {\n // Fail closed below when the workflow executor cannot prove the actor's grants.\n }\n return false\n}\n\nexport interface ActivityExecutionResult {\n activityId: string\n activityName?: string\n activityType: ActivityType\n success: boolean\n output?: any\n error?: string\n retryCount: number\n executionTimeMs: number\n async?: boolean // Marks activity as async (queued)\n jobId?: string // Queue job ID for async activities\n}\n\nexport class ActivityExecutionError extends Error {\n constructor(\n message: string,\n public activityType: ActivityType,\n public activityName?: string,\n public details?: any\n ) {\n super(message)\n this.name = 'ActivityExecutionError'\n }\n}\n\n// ============================================================================\n// Queue Integration for Async Activities\n// ============================================================================\n\nlet activityQueue: Queue<WorkflowActivityJob> | null = null\n\n/**\n * Get or create the activity queue (lazy initialization)\n */\nfunction getActivityQueue(): Queue<WorkflowActivityJob> {\n if (!activityQueue) {\n activityQueue = createModuleQueue<WorkflowActivityJob>(\n WORKFLOW_ACTIVITIES_QUEUE_NAME,\n { concurrency: parseInt(process.env.WORKFLOW_WORKER_CONCURRENCY || '5') },\n )\n }\n\n return activityQueue\n}\n\n/**\n * Enqueue an activity for background execution\n *\n * @param em - Entity manager\n * @param activity - Activity definition\n * @param context - Execution context\n * @returns Job ID\n */\nexport async function enqueueActivity(\n em: EntityManager,\n activity: ActivityDefinition,\n context: ActivityContext\n): Promise<string> {\n const { workflowInstance, workflowContext, stepContext, transitionId, stepInstanceId, branchInstanceId } =\n context\n\n // Interpolate config variables NOW (before queuing)\n const interpolatedConfig = interpolateVariables(activity.config, workflowContext, workflowInstance)\n\n // Create job payload\n const job: WorkflowActivityJob = {\n workflowInstanceId: workflowInstance.id,\n stepInstanceId,\n branchInstanceId: branchInstanceId ?? undefined,\n transitionId,\n activityId: activity.activityId,\n activityName: activity.activityName || activity.activityType,\n activityType: activity.activityType,\n activityConfig: interpolatedConfig,\n workflowContext,\n stepContext,\n retryPolicy: activity.retryPolicy,\n timeoutMs: activity.timeoutMs,\n tenantId: workflowInstance.tenantId,\n organizationId: workflowInstance.organizationId,\n userId: context.userId,\n }\n\n // Enqueue to queue (WAIT activities use delayMs for the actual delay)\n const queue = getActivityQueue()\n const enqueueOptions = activity.activityType === 'WAIT' && (interpolatedConfig.duration || interpolatedConfig.until)\n ? { delayMs: calculateWaitDelayMs(interpolatedConfig) }\n : undefined\n const jobId = await queue.enqueue(job, enqueueOptions)\n\n // Log event\n await logWorkflowEvent(em, {\n workflowInstanceId: workflowInstance.id,\n stepInstanceId,\n eventType: 'ACTIVITY_QUEUED',\n eventData: {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n async: true,\n jobId,\n },\n tenantId: workflowInstance.tenantId,\n organizationId: workflowInstance.organizationId,\n })\n\n return jobId\n}\n\n/**\n * Enqueue a delayed timer job for a WAIT_FOR_TIMER step.\n *\n * The activity worker handles `kind: 'timer'` jobs by calling\n * `timerHandler.fireTimer`, which resumes the paused workflow instance.\n */\nexport async function enqueueTimerJob(params: {\n workflowInstanceId: string\n stepInstanceId: string\n branchInstanceId?: string | null\n tenantId: string\n organizationId: string\n userId?: string\n fireAt: string\n delayMs: number\n}): Promise<string> {\n const { workflowInstanceId, stepInstanceId, branchInstanceId, tenantId, organizationId, userId, fireAt, delayMs } =\n params\n\n const queue = getActivityQueue()\n const jobId = await queue.enqueue(\n {\n kind: 'timer',\n workflowInstanceId,\n stepInstanceId,\n branchInstanceId: branchInstanceId ?? undefined,\n tenantId,\n organizationId,\n userId,\n fireAt,\n },\n { delayMs: delayMs > 0 ? delayMs : undefined }\n )\n\n return jobId\n}\n\n// ============================================================================\n// Main Activity Execution Functions\n// ============================================================================\n\n/**\n * Execute a single activity with retry logic and timeout\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param activity - Activity definition\n * @param context - Execution context\n * @returns Execution result\n */\nexport async function executeActivity(\n em: EntityManager,\n container: AwilixContainer,\n activity: ActivityDefinition,\n context: ActivityContext\n): Promise<ActivityExecutionResult> {\n const retryPolicy = activity.retryPolicy || {\n maxAttempts: 1,\n initialIntervalMs: 0,\n backoffCoefficient: 1,\n maxIntervalMs: 0,\n }\n\n let lastError: any\n let retryCount = 0\n\n for (let attempt = 0; attempt < retryPolicy.maxAttempts; attempt++) {\n try {\n const startTime = Date.now()\n\n // Execute with timeout if specified (timeoutMs, or a legacy ISO 8601\n // `timeout` string normalized to ms \u2014 see resolveActivityTimeoutMs).\n const timeoutMs = resolveActivityTimeoutMs(activity)\n const result = timeoutMs\n ? await executeWithTimeout(\n () => executeActivityByType(em, container, activity, context),\n timeoutMs\n )\n : await executeActivityByType(em, container, activity, context)\n\n const executionTimeMs = Date.now() - startTime\n\n return {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: true,\n output: result,\n retryCount: attempt,\n executionTimeMs,\n async: activity.async || false,\n }\n } catch (error) {\n lastError = error\n retryCount = attempt + 1\n\n // Log activity retry attempt with context\n if (attempt < retryPolicy.maxAttempts - 1) {\n logger.error('Activity failed; will retry', {\n activityId: activity.activityId,\n activityType: activity.activityType,\n attempt: attempt + 1,\n maxAttempts: retryPolicy.maxAttempts,\n instanceId: context.workflowInstance.id,\n err: error,\n })\n }\n\n // If not the last attempt, apply backoff and retry\n if (attempt < retryPolicy.maxAttempts - 1) {\n const backoff = calculateBackoff(\n retryPolicy.initialIntervalMs,\n retryPolicy.backoffCoefficient,\n attempt,\n retryPolicy.maxIntervalMs\n )\n\n await sleep(backoff)\n }\n }\n }\n\n // All retries exhausted\n const errorMessage = lastError instanceof Error ? lastError.message : String(lastError)\n logger.error('Activity failed after all attempts', {\n activityId: activity.activityId,\n activityType: activity.activityType,\n attempts: retryCount,\n instanceId: context.workflowInstance.id,\n err: lastError,\n })\n\n return {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: false,\n error: `Activity failed after ${retryCount} attempts: ${errorMessage}`,\n retryCount,\n executionTimeMs: 0,\n async: activity.async || false,\n }\n}\n\n/**\n * Execute multiple activities in sequence\n * Supports both synchronous and asynchronous (queued) execution\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param activities - Array of activity definitions\n * @param context - Execution context\n * @returns Array of execution results\n */\nexport async function executeActivities(\n em: EntityManager,\n container: AwilixContainer,\n activities: ActivityDefinition[],\n context: ActivityContext\n): Promise<ActivityExecutionResult[]> {\n const results: ActivityExecutionResult[] = []\n\n for (let i = 0; i < activities.length; i++) {\n const activity = activities[i]\n\n // Check if activity should run async\n if (activity.async) {\n // Enqueue for background execution\n const jobId = await enqueueActivity(em, activity, context)\n\n results.push({\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: true, // Queued successfully\n async: true,\n jobId,\n retryCount: 0,\n executionTimeMs: 0,\n })\n } else {\n // Execute synchronously (existing logic)\n const result = await executeActivity(em, container, activity, context)\n results.push(result)\n\n // Stop execution if activity fails (fail-fast)\n if (!result.success) {\n break\n }\n\n // Update workflow context with activity output\n if (result.output && typeof result.output === 'object') {\n const key = activity.activityName || activity.activityType\n context.workflowContext = {\n ...context.workflowContext,\n [key]: result.output,\n }\n }\n }\n }\n\n return results\n}\n\n// ============================================================================\n// Activity Type Handlers\n// ============================================================================\n\n/**\n * Execute activity based on its type\n */\nasync function executeActivityByType(\n em: EntityManager,\n container: AwilixContainer,\n activity: ActivityDefinition,\n context: ActivityContext\n): Promise<any> {\n // Interpolate config variables from context (including workflow metadata)\n const interpolatedConfig = interpolateVariables(activity.config, context.workflowContext, context.workflowInstance)\n\n switch (activity.activityType) {\n case 'SEND_EMAIL':\n return await executeSendEmail(interpolatedConfig, context, container)\n\n case 'CALL_API':\n return await executeCallApi(em, interpolatedConfig, context, container)\n\n case 'EMIT_EVENT':\n return await executeEmitEvent(interpolatedConfig, context, container)\n\n case 'UPDATE_ENTITY':\n return await executeUpdateEntity(em, interpolatedConfig, context, container)\n\n case 'CALL_WEBHOOK':\n return await executeCallWebhook(interpolatedConfig, context)\n\n case 'EXECUTE_FUNCTION':\n return await executeFunction(interpolatedConfig, context, container)\n\n case 'WAIT':\n return await executeWait(interpolatedConfig)\n\n default:\n throw new ActivityExecutionError(\n `Unknown activity type: ${activity.activityType}`,\n activity.activityType,\n activity.activityName\n )\n }\n}\n\n/**\n * SEND_EMAIL activity handler\n *\n * For MVP, this logs the email (actual email sending can be added later)\n */\nexport async function executeSendEmail(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { to, subject, template, templateData, body } = config\n\n if (!to || !subject) {\n throw new Error('SEND_EMAIL requires \"to\" and \"subject\" fields')\n }\n\n // For MVP: Log the email (actual email service integration can be added later)\n logger.info('Send email activity invoked', { component: 'SEND_EMAIL', subject })\n\n // Check if email service is available in container\n try {\n const emailService = container.resolve<{ send: (input: unknown) => Promise<unknown> | unknown }>('emailService')\n if (emailService && typeof emailService.send === 'function') {\n await emailService.send({\n to,\n subject,\n template,\n templateData,\n body,\n })\n return { sent: true, to, subject, via: 'emailService' }\n }\n } catch (error) {\n // Email service not available, just log\n }\n\n return { sent: true, to, subject, via: 'console' }\n}\n\n/**\n * EMIT_EVENT activity handler\n *\n * Publishes a domain event to the event bus\n */\nexport async function executeEmitEvent(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { eventName, payload } = config\n\n if (!eventName) {\n throw new Error('EMIT_EVENT requires \"eventName\" field')\n }\n\n // Get event bus from container\n const eventBus = container.resolve<{ emitEvent: (event: string, payload: unknown, options?: unknown) => Promise<unknown> | unknown }>('eventBus')\n\n if (!eventBus || typeof eventBus.emitEvent !== 'function') {\n throw new Error('Event bus not available in container')\n }\n\n // Publish event with workflow metadata\n const enrichedPayload = {\n ...payload,\n _workflow: {\n workflowInstanceId: context.workflowInstance.id,\n workflowId: context.workflowInstance.workflowId,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n },\n }\n\n await eventBus.emitEvent(eventName, enrichedPayload, {\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n })\n\n return { emitted: true, eventName, payload: enrichedPayload }\n}\n\n/**\n * UPDATE_ENTITY activity handler\n *\n * Updates an entity via CommandBus for proper audit logging, undo support, and side effects.\n *\n * Config format:\n * ```json\n * {\n * \"commandId\": \"sales.documents.update\",\n * \"input\": {\n * \"id\": \"{{context.orderId}}\",\n * \"statusEntryId\": \"{{context.approvedStatusId}}\"\n * }\n * }\n * ```\n *\n * Alternative format with statusValue (auto-resolves to statusEntryId):\n * ```json\n * {\n * \"commandId\": \"sales.orders.update\",\n * \"statusDictionary\": \"sales.order_status\",\n * \"input\": {\n * \"id\": \"{{context.id}}\",\n * \"statusValue\": \"pending_approval\"\n * }\n * }\n * ```\n */\nexport async function executeUpdateEntity(\n em: EntityManager,\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { commandId, input, statusDictionary } = config\n\n if (!commandId) {\n throw new Error('UPDATE_ENTITY requires \"commandId\" field (e.g., \"sales.documents.update\")')\n }\n\n const workflowSafeCommand = getWorkflowSafeCommand(commandId)\n if (!workflowSafeCommand) {\n throw new Error('UPDATE_ENTITY command is not allowed')\n }\n\n if (!input || typeof input !== 'object') {\n throw new Error('UPDATE_ENTITY requires \"input\" object with entity data')\n }\n\n const actorUserId = typeof context.userId === 'string' ? context.userId.trim() : ''\n if (!actorUserId) {\n throw new Error('UPDATE_ENTITY requires an authenticated workflow user')\n }\n\n const authorized = await workflowUserHasAllFeatures(\n container,\n actorUserId,\n workflowSafeCommand.requiredFeatures,\n context.workflowInstance.tenantId,\n context.workflowInstance.organizationId\n )\n if (!authorized) {\n throw new Error('UPDATE_ENTITY command is not authorized')\n }\n\n // Resolve CommandBus from container\n const commandBus = container.resolve('commandBus') as any\n\n if (!commandBus || typeof commandBus.execute !== 'function') {\n throw new Error('CommandBus not available in container')\n }\n\n // Prepare final input, resolving statusValue if provided\n let finalInput = { ...input }\n\n // If statusValue is provided with a statusDictionary, resolve it to statusEntryId\n if (finalInput.statusValue && statusDictionary) {\n const statusEntryId = await resolveDictionaryEntryId(\n em,\n statusDictionary,\n finalInput.statusValue,\n context.workflowInstance.tenantId,\n context.workflowInstance.organizationId\n )\n if (statusEntryId) {\n finalInput.statusEntryId = statusEntryId\n }\n delete finalInput.statusValue\n }\n\n // Build synthetic CommandRuntimeContext for workflow execution\n const ctx = {\n container,\n auth: {\n sub: actorUserId,\n tenantId: context.workflowInstance.tenantId,\n orgId: context.workflowInstance.organizationId,\n isSuperAdmin: false,\n },\n organizationScope: null,\n selectedOrganizationId: context.workflowInstance.organizationId,\n organizationIds: context.workflowInstance.organizationId\n ? [context.workflowInstance.organizationId]\n : null,\n }\n\n // Execute the command\n const { result, logEntry } = await commandBus.execute(commandId, {\n input: finalInput,\n ctx,\n })\n\n return {\n executed: true,\n commandId,\n result,\n logEntryId: logEntry?.id,\n }\n}\n\n/**\n * Helper to resolve dictionary entry ID by value\n */\nasync function resolveDictionaryEntryId(\n em: EntityManager,\n dictionaryKey: string,\n value: string,\n tenantId: string,\n organizationId: string\n): Promise<string | null> {\n try {\n // Import here to avoid circular dependencies\n const { Dictionary, DictionaryEntry } = await import('@open-mercato/core/modules/dictionaries/data/entities')\n\n // Find the dictionary\n const dictionary = await em.findOne(Dictionary, {\n key: dictionaryKey,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n\n if (!dictionary) {\n logger.warn('Dictionary not found', { component: 'UPDATE_ENTITY', dictionaryKey })\n return null\n }\n\n // Find the entry by normalized value\n const normalizedValue = value.toLowerCase().trim()\n const entry = await em.findOne(DictionaryEntry, {\n dictionary: dictionary.id,\n tenantId,\n organizationId,\n normalizedValue,\n })\n\n if (!entry) {\n logger.warn('Dictionary entry not found', { component: 'UPDATE_ENTITY', dictionaryKey, value })\n return null\n }\n\n return entry.id\n } catch (error) {\n logger.error('Error resolving dictionary entry', { component: 'UPDATE_ENTITY', err: error })\n return null\n }\n}\n\n/**\n * CALL_WEBHOOK activity handler\n *\n * Makes HTTP request to an external URL. Applies shared SSRF guard\n * (protocol / credentials / blocked host / private IP literal / DNS rebinding)\n * before issuing the request and rejects any 3xx redirect rather than following.\n */\nexport type CallWebhookDeps = {\n lookupHost?: HostLookup\n allowPrivate?: boolean\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\nexport async function executeCallWebhook(\n config: unknown,\n context: ActivityContext,\n deps: CallWebhookDeps = {}\n): Promise<any> {\n const parsed = callWebhookConfigSchema.safeParse(config)\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || 'config'}: ${issue.message}`)\n .join('; ')\n throw new Error(`CALL_WEBHOOK config invalid: ${issues}`)\n }\n const { url, method, headers: rawHeaders, body } = parsed.data\n const headers = rawHeaders ?? {}\n\n const allowPrivate = deps.allowPrivate ?? isAllowPrivateWorkflowWebhookUrlsEnabled()\n\n let response: Response\n try {\n response = await safeOutboundFetch(\n url,\n {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,\n redirect: 'manual',\n signal: deps.signal,\n },\n {\n subject: 'Workflow webhook URL',\n allowPrivate,\n lookupHost: deps.lookupHost,\n fetchImpl: deps.fetchImpl,\n },\n )\n } catch (error) {\n if (error instanceof UnsafeOutboundUrlError) {\n throw new Error(\n `CALL_WEBHOOK rejected unsafe URL (reason=${error.reason}): ${error.message}`\n )\n }\n throw error\n }\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location')\n throw new Error(\n `CALL_WEBHOOK refused to follow redirect ${response.status} to ${\n location ?? '(no Location header)'\n }`\n )\n }\n\n // Parse response\n let result: any\n const contentType = response.headers.get('content-type')\n\n if (contentType && contentType.includes('application/json')) {\n result = await response.json()\n } else {\n result = await response.text()\n }\n\n // Check for HTTP errors\n if (!response.ok) {\n throw new Error(\n `Webhook request failed with status ${response.status}: ${JSON.stringify(result)}`\n )\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n result,\n }\n}\n\n/**\n * EXECUTE_FUNCTION activity handler\n *\n * Calls a registered function from DI container\n */\nexport async function executeFunction(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { functionName, args = {} } = config\n\n if (!functionName) {\n throw new Error('EXECUTE_FUNCTION requires \"functionName\" field')\n }\n\n // Look up function in container\n const fnKey = `workflowFunction:${functionName}`\n\n try {\n const fn = container.resolve(fnKey)\n\n if (typeof fn !== 'function') {\n throw new Error(`Registered workflow function \"${functionName}\" is not a function`)\n }\n\n // Call function with args and context\n const result = await fn(args, context)\n\n return { executed: true, functionName, result }\n } catch (error) {\n if (error instanceof Error && error.message.includes('not registered')) {\n throw new Error(\n `Workflow function \"${functionName}\" not registered in DI container (key: ${fnKey})`\n )\n }\n throw error\n }\n}\n\n/**\n * Calculate delay in milliseconds from a WAIT activity config.\n * Supports either `duration` (relative, e.g. \"PT5M\") or `until` (absolute ISO 8601 datetime).\n */\nfunction calculateWaitDelayMs(config: { duration?: string; until?: string }): number {\n if (config.until) {\n const targetDate = new Date(config.until)\n if (isNaN(targetDate.getTime())) {\n throw new Error(`WAIT activity: invalid \"until\" datetime: ${config.until}`)\n }\n const delayMs = targetDate.getTime() - Date.now()\n return Math.max(0, delayMs)\n }\n\n if (config.duration) {\n return parseDuration(config.duration)\n }\n\n throw new Error('WAIT activity requires \"duration\" (e.g., \"PT5M\", \"1h\") or \"until\" (ISO 8601 datetime)')\n}\n\n/**\n * WAIT activity handler\n *\n * Delays workflow execution for a configured duration or until a specific datetime.\n * - `duration`: relative delay (e.g. \"PT5M\", \"1h\", \"30s\")\n * - `until`: absolute datetime (e.g. \"2026-04-15T10:00:00Z\")\n * - Sync mode: blocks via sleep (suitable for short delays)\n * - Async mode: delay is handled by the queue's delayMs option;\n * this handler returns immediately when called from the worker\n */\nasync function executeWait(config: any): Promise<any> {\n const durationMs = calculateWaitDelayMs(config)\n\n // In sync mode, actually sleep for the duration\n // In async mode (called from worker), the delay already happened via queue scheduling\n await sleep(durationMs)\n\n return { waited: true, durationMs }\n}\n\n/**\n * CALL_API activity handler\n *\n * Makes authenticated HTTP request to internal Open Mercato APIs\n * - Automatically creates one-time API key for authentication\n * - Injects tenant/organization context headers\n * - Validates URL security (SSRF prevention)\n * - Classifies errors (retriable vs non-retriable)\n * - Deletes API key after request (no stored credentials!)\n */\nexport async function executeCallApi(\n em: EntityManager,\n config: any,\n context: ActivityContext,\n container: AwilixContainer,\n signal?: AbortSignal\n): Promise<any> {\n // 1. Interpolate variables in config (including {{workflow.*}}, {{context.*}}, allowlisted {{env.*}}, {{now}})\n const interpolatedConfig = interpolateVariables(config, context.workflowContext, context.workflowInstance)\n\n const {\n endpoint,\n method = 'GET',\n headers = {},\n body,\n validateTenantMatch = true,\n } = interpolatedConfig\n\n\n if (!endpoint) {\n throw new Error('CALL_API requires \"endpoint\" field')\n }\n\n // 2. Build full URL (prepend APP_URL for relative paths)\n const fullUrl = buildApiUrl(endpoint)\n\n // 3. Import the one-time API key helper\n const { withOnetimeApiKey } = await import('../../api_keys/services/apiKeyService')\n\n // 4. Create the one-time API key on an EntityManager that is fully detached\n // from the surrounding request/transaction context.\n //\n // CALL_API runs inside `workflowExecutor.executeWorkflow()`, which wraps\n // the whole execution in `em.transactional(...)`. The request EM is forked\n // with `useContext: true`, so while that transaction is open, EVERY\n // operation on the container's `em` \u2014 including this API key's\n // persist/flush \u2014 is transparently redirected to the uncommitted\n // transaction fork (MikroORM `getContext()` \u2192 `TransactionContext`). The\n // key would therefore stay invisible until the transaction commits, but\n // the commit cannot happen until this activity returns. The outbound\n // self-authenticated `fetch` below opens a SEPARATE DB connection that\n // cannot see the uncommitted row, so the internal API responds `401` and\n // the activity fails (issue #4202).\n //\n // Forking with `useContext: false` (matching the query_index/webhooks\n // isolated-EM convention) gives the key its own pooled connection with\n // autocommit, so it is committed and visible to the internal request\n // immediately.\n const apiKeyEm = container\n .resolve<PostgreSqlEntityManager>('em')\n .fork({ clear: true, freshEventManager: true, useContext: false }) as PostgreSqlEntityManager\n\n // 5. Resolve the roles that the one-time API key will inherit.\n //\n // SECURITY: The key must never exceed the permissions of the human who\n // triggered (or authored) this workflow. Previously this code looked up\n // a role named \"admin\"/\"superadmin\" for the tenant and assigned it to\n // the key \u2014 which allowed any non-admin workflow author with\n // `workflows.definitions.edit` + `workflows.instances.create` to issue\n // arbitrary administrative API calls via a CALL_API activity. See the\n // SECURITY.md changelog entry for this fix.\n //\n // The resolution strategy is:\n // 1. Use the workflow instance's `metadata.initiatedBy` user (whoever\n // manually started the instance), when available. Only this user's\n // current active roles are used \u2014 we never fall back to the author\n // when the initiator is known, because that would escalate the\n // initiator's privileges.\n // 2. Fall back to the workflow definition's `createdBy` (author) only\n // when the instance was started by an event trigger with no user.\n // 3. If no traceable principal exists, the activity refuses to run \u2014\n // there is no \"system\" fallback that bypasses RBAC.\n const resolvedRoleIds = await resolveCallApiRoleIds(apiKeyEm, context.workflowInstance)\n\n if (resolvedRoleIds.length === 0) {\n throw new Error(\n `[CALL_API] Refusing to execute CALL_API for workflow instance ${context.workflowInstance.id}: ` +\n `no traceable user roles could be resolved from the workflow instance or definition. ` +\n `CALL_API activities must run under the identity of the user who triggered them.`\n )\n }\n\n // 6. Execute request with one-time API key scoped to the resolved user's roles\n return await withOnetimeApiKey(\n apiKeyEm,\n {\n name: `__workflow_${context.workflowInstance.id}__`,\n description: `One-time key for workflow ${context.workflowInstance.workflowId} instance ${context.workflowInstance.id}`,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n roles: resolvedRoleIds,\n expiresAt: null,\n },\n async (apiKeySecret) => {\n // Build request headers (auth + context + custom)\n const requestHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Authorization': `apikey ${apiKeySecret}`,\n 'X-Tenant-Id': context.workflowInstance.tenantId,\n 'X-Organization-Id': context.workflowInstance.organizationId,\n 'X-Workflow-Instance-Id': context.workflowInstance.id,\n ...headers,\n }\n\n // Make HTTP request\n const response = await fetch(fullUrl, {\n method,\n headers: requestHeaders,\n body: body ? JSON.stringify(body) : undefined,\n signal,\n })\n\n // Parse response body (JSON-safe)\n let responseBody: any\n const contentType = response.headers.get('content-type')\n\n try {\n if (contentType && contentType.includes('application/json')) {\n responseBody = await response.json()\n } else {\n responseBody = await response.text()\n }\n } catch (error) {\n responseBody = null\n }\n\n // Check for HTTP errors and classify\n if (!response.ok) {\n classifyAndThrowError(response.status, responseBody, fullUrl)\n }\n\n // Validate tenant match (security check)\n if (validateTenantMatch && responseBody && typeof responseBody === 'object') {\n if (responseBody.tenantId && responseBody.tenantId !== context.workflowInstance.tenantId) {\n throw new Error(\n `Tenant ID mismatch: workflow expects ${context.workflowInstance.tenantId} but API returned ${responseBody.tenantId}`\n )\n }\n }\n\n // Return structured result\n return {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n body: responseBody,\n authenticated: true,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n }\n }\n )\n}\n\n// ============================================================================\n// CALL_API Helper Functions\n// ============================================================================\n\nexport type CallApiInstanceLike = {\n id: string\n tenantId: string\n organizationId: string\n definitionId: string\n metadata?: { initiatedBy?: string | null } | null\n}\n\nasync function resolveActiveRoleIdsForUser(\n em: any,\n userId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<string[]> {\n const { findOneWithDecryption, findWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const { User, UserRole, Role } = await import('../../auth/data/entities')\n\n const user = await findOneWithDecryption(em, User, {\n id: userId,\n tenantId: scope.tenantId,\n deletedAt: null,\n }, {}, scope)\n if (!user) return []\n\n const userRoles = await findWithDecryption(\n em,\n UserRole,\n { user: user.id, deletedAt: null },\n { populate: ['role'] },\n scope,\n )\n const roleIds = userRoles\n .map((ur: any) => (typeof ur.role === 'string' ? ur.role : ur.role?.id))\n .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0)\n\n if (roleIds.length === 0) return []\n\n const scopedRoles = await findWithDecryption(em, Role, {\n id: { $in: roleIds },\n tenantId: scope.tenantId,\n deletedAt: null,\n }, {}, scope)\n return scopedRoles.map((r: any) => r.id as string)\n}\n\nexport async function resolveCallApiRoleIds(\n em: any,\n instance: CallApiInstanceLike\n): Promise<string[]> {\n if (!instance.definitionId) return []\n\n const { findOneWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const { WorkflowDefinition } = await import('../data/entities')\n\n const scope = { tenantId: instance.tenantId, organizationId: instance.organizationId }\n\n // 1. Prefer the triggering user (whoever manually started this instance).\n // WorkflowInstance.metadata.initiatedBy is the canonical record of that\n // principal for user-started instances; use their current role set so\n // CALL_API never exceeds the initiator's permissions. Refuse if the\n // initiator has no active scoped roles \u2014 do not fall back to the\n // definition author, which would escalate the initiator's privileges.\n const initiatorUserId = instance.metadata?.initiatedBy ?? null\n if (initiatorUserId) {\n return resolveActiveRoleIdsForUser(em, initiatorUserId, scope)\n }\n\n // 2. Event-triggered instance with no human initiator: fall back to the\n // definition author. Soft-deleted definitions must not mint keys.\n const definition = await findOneWithDecryption(em, WorkflowDefinition, {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n deletedAt: null,\n }, {}, scope)\n const authorUserId = definition?.createdBy\n if (!authorUserId) return []\n\n return resolveActiveRoleIdsForUser(em, authorUserId, scope)\n}\n\n/**\n * Build full API URL from endpoint\n * - Relative paths (/api/...) \u2192 prepend APP_URL\n * - Absolute URLs \u2192 validate domain matches APP_URL (SSRF prevention)\n */\nfunction buildApiUrl(endpoint: string): string {\n const appUrl = process.env.APP_URL || 'http://localhost:3000'\n\n // Relative path - prepend APP_URL\n if (endpoint.startsWith('/')) {\n // Security: Only allow /api/* paths\n if (!endpoint.startsWith('/api/')) {\n throw new Error(`CALL_API only supports /api/* paths, got: ${endpoint}`)\n }\n return `${appUrl}${endpoint}`\n }\n\n // Absolute URL - validate domain matches APP_URL (SSRF prevention)\n try {\n const endpointUrl = new URL(endpoint)\n const appUrlObj = new URL(appUrl)\n\n if (endpointUrl.host !== appUrlObj.host) {\n throw new Error(\n `SSRF Prevention: CALL_API endpoint domain (${endpointUrl.host}) does not match APP_URL (${appUrlObj.host})`\n )\n }\n\n return endpoint\n } catch (error) {\n if (error instanceof TypeError) {\n throw new Error(`Invalid endpoint URL: ${endpoint}`)\n }\n throw error\n }\n}\n\n/**\n * Classify HTTP error and throw appropriate error\n * - 400-499: Non-retriable (client error - validation/auth)\n * - 500-599: Retriable (server error)\n */\nfunction classifyAndThrowError(status: number, body: any, url: string): never {\n const bodyStr = typeof body === 'string' ? body : JSON.stringify(body)\n\n if (status >= 400 && status < 500) {\n // Client errors - non-retriable\n throw new Error(\n `CALL_API request failed with status ${status} (non-retriable): ${bodyStr}`\n )\n }\n\n if (status >= 500) {\n // Server errors - retriable\n const error: any = new Error(\n `CALL_API request failed with status ${status} (retriable): ${bodyStr}`\n )\n error.retriable = true\n throw error\n }\n\n // Other errors\n throw new Error(`CALL_API request failed with status ${status}: ${bodyStr}`)\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Interpolate variables in config from workflow context\n *\n * Supports syntax:\n * - {{context.field}} or {{context.nested.field}} - from workflow context\n * - {{workflow.instanceId}} - workflow instance ID\n * - {{workflow.tenantId}} - tenant ID\n * - {{workflow.organizationId}} - organization ID\n * - {{workflow.currentStepId}} - current step ID\n * - {{env.VAR_NAME}} - server-allowlisted environment variables\n * - {{now}} - current ISO timestamp\n */\nfunction interpolateVariables(\n config: any,\n context: Record<string, any>,\n workflowInstance?: WorkflowInstance\n): any {\n if (typeof config === 'string') {\n // Check if this is a single variable reference (e.g., \"{{context.cart.items}}\")\n // This preserves the original type (array, object, number, boolean)\n const singleVarMatch = config.match(/^\\{\\{([^}]+)\\}\\}$/)\n\n if (singleVarMatch) {\n const trimmedPath = singleVarMatch[1].trim()\n\n // Handle {{workflow.*}} variables\n if (trimmedPath.startsWith('workflow.') && workflowInstance) {\n const workflowKey = trimmedPath.substring('workflow.'.length)\n switch (workflowKey) {\n case 'instanceId':\n return workflowInstance.id\n case 'tenantId':\n return workflowInstance.tenantId\n case 'organizationId':\n return workflowInstance.organizationId\n case 'currentStepId':\n return workflowInstance.currentStepId\n case 'workflowId':\n return workflowInstance.workflowId\n case 'version':\n return workflowInstance.version // Return as number\n default:\n return config // Return original if unknown\n }\n }\n\n // Handle {{env.*}} variables\n if (trimmedPath.startsWith('env.')) {\n const envKey = trimmedPath.substring('env.'.length)\n return resolveWorkflowEnvInterpolation(envKey)\n }\n\n // Handle {{now}} - current timestamp\n if (trimmedPath === 'now') {\n return new Date().toISOString()\n }\n\n // Handle {{context.*}} variables (default behavior)\n const contextPath = trimmedPath.startsWith('context.')\n ? trimmedPath.substring('context.'.length)\n : trimmedPath\n\n const value = getNestedValue(context, contextPath)\n return value !== undefined ? value : config // Return raw value to preserve type\n }\n\n // Multiple interpolations or mixed text - return string\n return config.replace(/\\{\\{([^}]+)\\}\\}/g, (match, path) => {\n const trimmedPath = path.trim()\n\n // Handle {{workflow.*}} variables\n if (trimmedPath.startsWith('workflow.') && workflowInstance) {\n const workflowKey = trimmedPath.substring('workflow.'.length)\n switch (workflowKey) {\n case 'instanceId':\n return workflowInstance.id\n case 'tenantId':\n return workflowInstance.tenantId\n case 'organizationId':\n return workflowInstance.organizationId\n case 'currentStepId':\n return workflowInstance.currentStepId\n case 'workflowId':\n return workflowInstance.workflowId\n case 'version':\n return String(workflowInstance.version)\n default:\n return match // Unknown workflow key\n }\n }\n\n // Handle {{env.*}} variables\n if (trimmedPath.startsWith('env.')) {\n const envKey = trimmedPath.substring('env.'.length)\n return resolveWorkflowEnvInterpolation(envKey)\n }\n\n // Handle {{now}} - current timestamp\n if (trimmedPath === 'now') {\n return new Date().toISOString()\n }\n\n // Handle {{context.*}} variables (default behavior)\n const contextPath = trimmedPath.startsWith('context.')\n ? trimmedPath.substring('context.'.length)\n : trimmedPath\n\n const value = getNestedValue(context, contextPath)\n return value !== undefined ? String(value) : match\n })\n }\n\n if (Array.isArray(config)) {\n return config.map((item) => interpolateVariables(item, context, workflowInstance))\n }\n\n if (config && typeof config === 'object') {\n const result: Record<string, any> = {}\n for (const [key, value] of Object.entries(config)) {\n result[key] = interpolateVariables(value, context, workflowInstance)\n }\n return result\n }\n\n return config\n}\n\n/**\n * Get nested value from object by path (e.g., \"user.email\")\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split('.')\n let value = obj\n\n for (const part of parts) {\n if (value && typeof value === 'object' && part in value) {\n value = value[part]\n } else {\n return undefined\n }\n }\n\n return value\n}\n\n/**\n * Calculate exponential backoff delay\n */\nfunction calculateBackoff(\n initialIntervalMs: number,\n backoffCoefficient: number,\n attempt: number,\n maxIntervalMs: number\n): number {\n const backoff = initialIntervalMs * Math.pow(backoffCoefficient, attempt)\n return Math.min(backoff, maxIntervalMs || Infinity)\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Execute a promise with timeout\n */\nasync function executeWithTimeout<T>(\n executor: () => Promise<T>,\n timeoutMs: number\n): Promise<T> {\n let timeoutId: NodeJS.Timeout\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n reject(new Error(`Activity execution timeout after ${timeoutMs}ms`))\n }, timeoutMs)\n })\n\n try {\n return await Promise.race([executor(), timeoutPromise])\n } finally {\n clearTimeout(timeoutId!)\n }\n}\n"],
5
- "mappings": "AAgBA,SAAS,yBAAgC;AAEzC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,+BAA+B;AACxC,SAAS,+BAA+B;AACxC,SAA8B,sCAAsC;AACpE,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEvC,SAAS,2CAAoD;AAC3D,MAAI,wBAAwB,QAAQ,IAAI,iCAAiC,KAAK,GAAG;AAC/E,QAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,aAAO,KAAK,sGAAsG,EAAE,WAAW,eAAe,CAAC;AAC/I,aAAO;AAAA,IACT;AAEA,WAAO,KAAK,2HAA2H,EAAE,WAAW,eAAe,CAAC;AACpK,WAAO;AAAA,EACT;AAEA,MAAI,wBAAwB,QAAQ,IAAI,qCAAqC,KAAK,GAAG;AACnF,QAAI,QAAQ,IAAI,aAAa,cAAc;AACzC,aAAO,KAAK,2KAA2K,EAAE,WAAW,eAAe,CAAC;AACpN,aAAO;AAAA,IACT;AAEA,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WAAW,SAAS,EAAE,CAAC;AACzD;AAKA,eAAe,mBACb,UACA,WACY;AACZ,MAAI;AAEJ,QAAM,iBAAiB,IAAI,QAAe,CAAC,GAAG,WAAW;AACvD,gBAAY,WAAW,MAAM;AAC3B,aAAO,IAAI,MAAM,oCAAoC,SAAS,IAAI,CAAC;AAAA,IACrE,GAAG,SAAS;AAAA,EACd,CAAC;AAED,MAAI;AACF,WAAO,MAAM,QAAQ,KAAK,CAAC,SAAS,GAAG,cAAc,CAAC;AAAA,EACxD,UAAE;AACA,iBAAa,SAAU;AAAA,EACzB;AACF;",
4
+ "sourcesContent": ["/**\n * Workflows Module - Activity Executor Service\n *\n * Executes workflow activities (send email, call API, emit events, etc.)\n * - Supports multiple activity types\n * - Implements retry logic with exponential backoff\n * - Handles timeouts\n * - Variable interpolation from workflow context\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { WorkflowInstance } from '../data/entities'\nimport { createModuleQueue, Queue } from '@open-mercato/queue'\nimport { getRedisUrl } from '@open-mercato/shared/lib/redis/connection'\nimport {\n safeOutboundFetch,\n UnsafeOutboundUrlError,\n type HostLookup,\n} from '@open-mercato/shared/lib/url-safety'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { callWebhookConfigSchema } from '../data/validators'\nimport { WorkflowActivityJob, WORKFLOW_ACTIVITIES_QUEUE_NAME } from './activity-queue-types'\nimport { logWorkflowEvent } from './event-logger'\nimport { parseDuration } from './duration'\nimport { getWorkflowSafeCommand } from './workflow-safe-commands'\n\nexport { isPrivateUrl } from '@open-mercato/shared/lib/network'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\nfunction isAllowPrivateWorkflowWebhookUrlsEnabled(): boolean {\n if (parseBooleanWithDefault(process.env.OM_WORKFLOWS_ALLOW_PRIVATE_URLS, false)) {\n if (process.env.NODE_ENV === 'production') {\n logger.warn('OM_WORKFLOWS_ALLOW_PRIVATE_URLS is set but ignored in production. SSRF protection remains enabled.', { component: 'CALL_WEBHOOK' })\n return false\n }\n\n logger.warn('OM_WORKFLOWS_ALLOW_PRIVATE_URLS is enabled. SSRF protection is bypassed for workflow webhooks; use only in development.', { component: 'CALL_WEBHOOK' })\n return true\n }\n\n if (parseBooleanWithDefault(process.env.WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS, false)) {\n if (process.env.NODE_ENV === 'production') {\n logger.warn('WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS is deprecated and ignored in production. Use OM_WORKFLOWS_ALLOW_PRIVATE_URLS for development only. SSRF protection remains enabled.', { component: 'CALL_WEBHOOK' })\n return false\n }\n\n logger.warn('WORKFLOW_WEBHOOK_ALLOW_PRIVATE_URLS is deprecated. Use OM_WORKFLOWS_ALLOW_PRIVATE_URLS instead. SSRF protection is bypassed.', { component: 'CALL_WEBHOOK' })\n return true\n }\n\n return false\n}\n\nconst DEFAULT_WORKFLOW_ENV_INTERPOLATION_ALLOWLIST = new Set(['APP_URL'])\nconst WORKFLOW_ENV_INTERPOLATION_ALLOWLIST_KEY = 'OM_WORKFLOWS_ENV_INTERPOLATION_ALLOWLIST'\n\nfunction getWorkflowEnvInterpolationAllowlist(): Set<string> {\n const allowlist = new Set(DEFAULT_WORKFLOW_ENV_INTERPOLATION_ALLOWLIST)\n const configuredKeys = process.env[WORKFLOW_ENV_INTERPOLATION_ALLOWLIST_KEY]\n if (!configuredKeys) {\n return allowlist\n }\n\n for (const key of configuredKeys.split(',')) {\n const trimmedKey = key.trim()\n if (trimmedKey) {\n allowlist.add(trimmedKey)\n }\n }\n\n return allowlist\n}\n\nfunction resolveWorkflowEnvInterpolation(envKey: string): string {\n if (!getWorkflowEnvInterpolationAllowlist().has(envKey)) {\n return ''\n }\n\n return process.env[envKey] ?? ''\n}\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport type ActivityType =\n | 'SEND_EMAIL'\n | 'CALL_API'\n | 'EMIT_EVENT'\n | 'UPDATE_ENTITY'\n | 'CALL_WEBHOOK'\n | 'EXECUTE_FUNCTION'\n | 'WAIT'\n\nexport interface ActivityDefinition {\n activityId: string // Unique identifier for activity\n activityName?: string // Optional, for debugging/logging\n activityType: ActivityType\n config: any\n async?: boolean // Flag to execute activity asynchronously via queue\n retryPolicy?: RetryPolicy\n timeoutMs?: number\n /**\n * @deprecated Use `timeoutMs`. Legacy ISO 8601 duration string accepted by\n * the definition schema before #4424; normalized by `resolveActivityTimeoutMs`.\n */\n timeout?: string\n compensate?: boolean // Flag to execute compensation on failure\n}\n\n/**\n * Effective timeout for an activity, in milliseconds.\n *\n * The editor and this executor both speak `timeoutMs`, but the definition\n * schema historically accepted only an ISO 8601 `timeout` string \u2014 so stored\n * definitions can carry either. Prefer `timeoutMs`; fall back to parsing\n * `timeout`, ignoring a malformed value rather than throwing mid-execution\n * (an unparseable timeout must not fail an activity that would otherwise\n * succeed). Returns undefined when no usable timeout is configured (#4424).\n */\nexport function resolveActivityTimeoutMs(activity: {\n timeoutMs?: number\n timeout?: string\n}): number | undefined {\n if (typeof activity.timeoutMs === 'number' && activity.timeoutMs > 0) {\n return activity.timeoutMs\n }\n if (typeof activity.timeout === 'string' && activity.timeout.trim().length > 0) {\n try {\n const parsed = parseDuration(activity.timeout.trim())\n if (Number.isFinite(parsed) && parsed > 0) return parsed\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nexport interface RetryPolicy {\n maxAttempts: number\n initialIntervalMs: number\n backoffCoefficient: number\n maxIntervalMs: number\n}\n\nexport interface ActivityContext {\n workflowInstance: WorkflowInstance\n workflowContext: Record<string, any>\n stepContext?: Record<string, any>\n stepInstanceId?: string\n // Set when the activity runs inside a parallel branch; carried on the queue\n // payload so async resume targets the branch rather than the instance.\n branchInstanceId?: string | null\n transitionId?: string\n userId?: string\n}\n\ntype RbacFeatureResolver = {\n userHasAllFeatures: (\n userId: string,\n required: string[],\n opts: { tenantId: string | null; organizationId: string | null }\n ) => Promise<boolean>\n}\n\nasync function workflowUserHasAllFeatures(\n container: AwilixContainer,\n userId: string,\n required: readonly string[],\n tenantId: string | null,\n organizationId: string | null\n): Promise<boolean> {\n try {\n const rbac = container.resolve('rbacService') as RbacFeatureResolver | undefined\n if (rbac?.userHasAllFeatures) {\n return await rbac.userHasAllFeatures(userId, [...required], { tenantId, organizationId })\n }\n } catch {\n // Fail closed below when the workflow executor cannot prove the actor's grants.\n }\n return false\n}\n\nexport interface ActivityExecutionResult {\n activityId: string\n activityName?: string\n activityType: ActivityType\n success: boolean\n output?: any\n error?: string\n retryCount: number\n executionTimeMs: number\n async?: boolean // Marks activity as async (queued)\n jobId?: string // Queue job ID for async activities\n}\n\nexport class ActivityExecutionError extends Error {\n constructor(\n message: string,\n public activityType: ActivityType,\n public activityName?: string,\n public details?: any\n ) {\n super(message)\n this.name = 'ActivityExecutionError'\n }\n}\n\n// ============================================================================\n// Queue Integration for Async Activities\n// ============================================================================\n\nlet activityQueue: Queue<WorkflowActivityJob> | null = null\n\n/**\n * Get or create the activity queue (lazy initialization)\n */\nfunction getActivityQueue(): Queue<WorkflowActivityJob> {\n if (!activityQueue) {\n activityQueue = createModuleQueue<WorkflowActivityJob>(\n WORKFLOW_ACTIVITIES_QUEUE_NAME,\n { concurrency: parseInt(process.env.WORKFLOW_WORKER_CONCURRENCY || '5') },\n )\n }\n\n return activityQueue\n}\n\n/**\n * Enqueue an activity for background execution\n *\n * @param em - Entity manager\n * @param activity - Activity definition\n * @param context - Execution context\n * @returns Job ID\n */\nexport async function enqueueActivity(\n em: EntityManager,\n activity: ActivityDefinition,\n context: ActivityContext\n): Promise<string> {\n const { workflowInstance, workflowContext, stepContext, transitionId, stepInstanceId, branchInstanceId } =\n context\n\n // Interpolate config variables NOW (before queuing)\n const interpolatedConfig = interpolateVariables(activity.config, workflowContext, workflowInstance)\n\n // Create job payload\n const job: WorkflowActivityJob = {\n workflowInstanceId: workflowInstance.id,\n stepInstanceId,\n branchInstanceId: branchInstanceId ?? undefined,\n transitionId,\n activityId: activity.activityId,\n activityName: activity.activityName || activity.activityType,\n activityType: activity.activityType,\n activityConfig: interpolatedConfig,\n workflowContext,\n stepContext,\n retryPolicy: activity.retryPolicy,\n timeoutMs: activity.timeoutMs,\n tenantId: workflowInstance.tenantId,\n organizationId: workflowInstance.organizationId,\n userId: context.userId,\n }\n\n // Enqueue to queue (WAIT activities use delayMs for the actual delay)\n const queue = getActivityQueue()\n const enqueueOptions = activity.activityType === 'WAIT' && (interpolatedConfig.duration || interpolatedConfig.until)\n ? { delayMs: calculateWaitDelayMs(interpolatedConfig) }\n : undefined\n const jobId = await queue.enqueue(job, enqueueOptions)\n\n // Log event\n await logWorkflowEvent(em, {\n workflowInstanceId: workflowInstance.id,\n stepInstanceId,\n eventType: 'ACTIVITY_QUEUED',\n eventData: {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n async: true,\n jobId,\n },\n tenantId: workflowInstance.tenantId,\n organizationId: workflowInstance.organizationId,\n })\n\n return jobId\n}\n\n/**\n * Enqueue a delayed timer job for a WAIT_FOR_TIMER step.\n *\n * The activity worker handles `kind: 'timer'` jobs by calling\n * `timerHandler.fireTimer`, which resumes the paused workflow instance.\n */\nexport async function enqueueTimerJob(params: {\n workflowInstanceId: string\n stepInstanceId: string\n branchInstanceId?: string | null\n tenantId: string\n organizationId: string\n userId?: string\n fireAt: string\n delayMs: number\n}): Promise<string> {\n const { workflowInstanceId, stepInstanceId, branchInstanceId, tenantId, organizationId, userId, fireAt, delayMs } =\n params\n\n const queue = getActivityQueue()\n const jobId = await queue.enqueue(\n {\n kind: 'timer',\n workflowInstanceId,\n stepInstanceId,\n branchInstanceId: branchInstanceId ?? undefined,\n tenantId,\n organizationId,\n userId,\n fireAt,\n },\n { delayMs: delayMs > 0 ? delayMs : undefined }\n )\n\n return jobId\n}\n\n// ============================================================================\n// Main Activity Execution Functions\n// ============================================================================\n\n/**\n * Execute a single activity with retry logic and timeout\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param activity - Activity definition\n * @param context - Execution context\n * @returns Execution result\n */\nexport async function executeActivity(\n em: EntityManager,\n container: AwilixContainer,\n activity: ActivityDefinition,\n context: ActivityContext\n): Promise<ActivityExecutionResult> {\n const retryPolicy = activity.retryPolicy || {\n maxAttempts: 1,\n initialIntervalMs: 0,\n backoffCoefficient: 1,\n maxIntervalMs: 0,\n }\n\n let lastError: any\n let retryCount = 0\n\n for (let attempt = 0; attempt < retryPolicy.maxAttempts; attempt++) {\n try {\n const startTime = Date.now()\n\n // Execute with timeout if specified (timeoutMs, or a legacy ISO 8601\n // `timeout` string normalized to ms \u2014 see resolveActivityTimeoutMs).\n const timeoutMs = resolveActivityTimeoutMs(activity)\n const result = timeoutMs\n ? await executeWithTimeout(\n (signal) => executeActivityByType(em, container, activity, context, signal),\n timeoutMs\n )\n : await executeActivityByType(em, container, activity, context)\n\n const executionTimeMs = Date.now() - startTime\n\n return {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: true,\n output: result,\n retryCount: attempt,\n executionTimeMs,\n async: activity.async || false,\n }\n } catch (error) {\n lastError = error\n retryCount = attempt + 1\n\n // Log activity retry attempt with context\n if (attempt < retryPolicy.maxAttempts - 1) {\n logger.error('Activity failed; will retry', {\n activityId: activity.activityId,\n activityType: activity.activityType,\n attempt: attempt + 1,\n maxAttempts: retryPolicy.maxAttempts,\n instanceId: context.workflowInstance.id,\n err: error,\n })\n }\n\n // If not the last attempt, apply backoff and retry\n if (attempt < retryPolicy.maxAttempts - 1) {\n const backoff = calculateBackoff(\n retryPolicy.initialIntervalMs,\n retryPolicy.backoffCoefficient,\n attempt,\n retryPolicy.maxIntervalMs\n )\n\n await sleep(backoff)\n }\n }\n }\n\n // All retries exhausted\n const errorMessage = lastError instanceof Error ? lastError.message : String(lastError)\n logger.error('Activity failed after all attempts', {\n activityId: activity.activityId,\n activityType: activity.activityType,\n attempts: retryCount,\n instanceId: context.workflowInstance.id,\n err: lastError,\n })\n\n return {\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: false,\n error: `Activity failed after ${retryCount} attempts: ${errorMessage}`,\n retryCount,\n executionTimeMs: 0,\n async: activity.async || false,\n }\n}\n\n/**\n * Execute multiple activities in sequence\n * Supports both synchronous and asynchronous (queued) execution\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param activities - Array of activity definitions\n * @param context - Execution context\n * @returns Array of execution results\n */\nexport async function executeActivities(\n em: EntityManager,\n container: AwilixContainer,\n activities: ActivityDefinition[],\n context: ActivityContext\n): Promise<ActivityExecutionResult[]> {\n const results: ActivityExecutionResult[] = []\n\n for (let i = 0; i < activities.length; i++) {\n const activity = activities[i]\n\n // Check if activity should run async\n if (activity.async) {\n // Enqueue for background execution\n const jobId = await enqueueActivity(em, activity, context)\n\n results.push({\n activityId: activity.activityId,\n activityName: activity.activityName,\n activityType: activity.activityType,\n success: true, // Queued successfully\n async: true,\n jobId,\n retryCount: 0,\n executionTimeMs: 0,\n })\n } else {\n // Execute synchronously (existing logic)\n const result = await executeActivity(em, container, activity, context)\n results.push(result)\n\n // Stop execution if activity fails (fail-fast)\n if (!result.success) {\n break\n }\n\n // Update workflow context with activity output\n if (result.output && typeof result.output === 'object') {\n const key = activity.activityName || activity.activityType\n context.workflowContext = {\n ...context.workflowContext,\n [key]: result.output,\n }\n }\n }\n }\n\n return results\n}\n\n// ============================================================================\n// Activity Type Handlers\n// ============================================================================\n\n/**\n * Execute activity based on its type\n */\nasync function executeActivityByType(\n em: EntityManager,\n container: AwilixContainer,\n activity: ActivityDefinition,\n context: ActivityContext,\n signal?: AbortSignal\n): Promise<any> {\n // Interpolate config variables from context (including workflow metadata)\n const interpolatedConfig = interpolateVariables(activity.config, context.workflowContext, context.workflowInstance)\n\n switch (activity.activityType) {\n case 'SEND_EMAIL':\n return await executeSendEmail(interpolatedConfig, context, container)\n\n case 'CALL_API':\n return await executeCallApi(em, interpolatedConfig, context, container, signal)\n\n case 'EMIT_EVENT':\n return await executeEmitEvent(interpolatedConfig, context, container)\n\n case 'UPDATE_ENTITY':\n return await executeUpdateEntity(em, interpolatedConfig, context, container)\n\n case 'CALL_WEBHOOK':\n return await executeCallWebhook(interpolatedConfig, context, { signal })\n\n case 'EXECUTE_FUNCTION':\n return await executeFunction(interpolatedConfig, context, container)\n\n case 'WAIT':\n return await executeWait(interpolatedConfig)\n\n default:\n throw new ActivityExecutionError(\n `Unknown activity type: ${activity.activityType}`,\n activity.activityType,\n activity.activityName\n )\n }\n}\n\n/**\n * SEND_EMAIL activity handler\n *\n * For MVP, this logs the email (actual email sending can be added later)\n */\nexport async function executeSendEmail(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { to, subject, template, templateData, body } = config\n\n if (!to || !subject) {\n throw new Error('SEND_EMAIL requires \"to\" and \"subject\" fields')\n }\n\n // For MVP: Log the email (actual email service integration can be added later)\n logger.info('Send email activity invoked', { component: 'SEND_EMAIL', subject })\n\n // Check if email service is available in container\n try {\n const emailService = container.resolve<{ send: (input: unknown) => Promise<unknown> | unknown }>('emailService')\n if (emailService && typeof emailService.send === 'function') {\n await emailService.send({\n to,\n subject,\n template,\n templateData,\n body,\n })\n return { sent: true, to, subject, via: 'emailService' }\n }\n } catch (error) {\n // Email service not available, just log\n }\n\n return { sent: true, to, subject, via: 'console' }\n}\n\n/**\n * EMIT_EVENT activity handler\n *\n * Publishes a domain event to the event bus\n */\nexport async function executeEmitEvent(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { eventName, payload } = config\n\n if (!eventName) {\n throw new Error('EMIT_EVENT requires \"eventName\" field')\n }\n\n // Get event bus from container\n const eventBus = container.resolve<{ emitEvent: (event: string, payload: unknown, options?: unknown) => Promise<unknown> | unknown }>('eventBus')\n\n if (!eventBus || typeof eventBus.emitEvent !== 'function') {\n throw new Error('Event bus not available in container')\n }\n\n // Publish event with workflow metadata\n const enrichedPayload = {\n ...payload,\n _workflow: {\n workflowInstanceId: context.workflowInstance.id,\n workflowId: context.workflowInstance.workflowId,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n },\n }\n\n await eventBus.emitEvent(eventName, enrichedPayload, {\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n })\n\n return { emitted: true, eventName, payload: enrichedPayload }\n}\n\n/**\n * UPDATE_ENTITY activity handler\n *\n * Updates an entity via CommandBus for proper audit logging, undo support, and side effects.\n *\n * Config format:\n * ```json\n * {\n * \"commandId\": \"sales.documents.update\",\n * \"input\": {\n * \"id\": \"{{context.orderId}}\",\n * \"statusEntryId\": \"{{context.approvedStatusId}}\"\n * }\n * }\n * ```\n *\n * Alternative format with statusValue (auto-resolves to statusEntryId):\n * ```json\n * {\n * \"commandId\": \"sales.orders.update\",\n * \"statusDictionary\": \"sales.order_status\",\n * \"input\": {\n * \"id\": \"{{context.id}}\",\n * \"statusValue\": \"pending_approval\"\n * }\n * }\n * ```\n */\nexport async function executeUpdateEntity(\n em: EntityManager,\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { commandId, input, statusDictionary } = config\n\n if (!commandId) {\n throw new Error('UPDATE_ENTITY requires \"commandId\" field (e.g., \"sales.documents.update\")')\n }\n\n const workflowSafeCommand = getWorkflowSafeCommand(commandId)\n if (!workflowSafeCommand) {\n throw new Error('UPDATE_ENTITY command is not allowed')\n }\n\n if (!input || typeof input !== 'object') {\n throw new Error('UPDATE_ENTITY requires \"input\" object with entity data')\n }\n\n const actorUserId = typeof context.userId === 'string' ? context.userId.trim() : ''\n if (!actorUserId) {\n throw new Error('UPDATE_ENTITY requires an authenticated workflow user')\n }\n\n const authorized = await workflowUserHasAllFeatures(\n container,\n actorUserId,\n workflowSafeCommand.requiredFeatures,\n context.workflowInstance.tenantId,\n context.workflowInstance.organizationId\n )\n if (!authorized) {\n throw new Error('UPDATE_ENTITY command is not authorized')\n }\n\n // Resolve CommandBus from container\n const commandBus = container.resolve('commandBus') as any\n\n if (!commandBus || typeof commandBus.execute !== 'function') {\n throw new Error('CommandBus not available in container')\n }\n\n // Prepare final input, resolving statusValue if provided\n let finalInput = { ...input }\n\n // If statusValue is provided with a statusDictionary, resolve it to statusEntryId\n if (finalInput.statusValue && statusDictionary) {\n const statusEntryId = await resolveDictionaryEntryId(\n em,\n statusDictionary,\n finalInput.statusValue,\n context.workflowInstance.tenantId,\n context.workflowInstance.organizationId\n )\n if (statusEntryId) {\n finalInput.statusEntryId = statusEntryId\n }\n delete finalInput.statusValue\n }\n\n // Build synthetic CommandRuntimeContext for workflow execution\n const ctx = {\n container,\n auth: {\n sub: actorUserId,\n tenantId: context.workflowInstance.tenantId,\n orgId: context.workflowInstance.organizationId,\n isSuperAdmin: false,\n },\n organizationScope: null,\n selectedOrganizationId: context.workflowInstance.organizationId,\n organizationIds: context.workflowInstance.organizationId\n ? [context.workflowInstance.organizationId]\n : null,\n }\n\n // Execute the command\n const { result, logEntry } = await commandBus.execute(commandId, {\n input: finalInput,\n ctx,\n })\n\n return {\n executed: true,\n commandId,\n result,\n logEntryId: logEntry?.id,\n }\n}\n\n/**\n * Helper to resolve dictionary entry ID by value\n */\nasync function resolveDictionaryEntryId(\n em: EntityManager,\n dictionaryKey: string,\n value: string,\n tenantId: string,\n organizationId: string\n): Promise<string | null> {\n try {\n // Import here to avoid circular dependencies\n const { Dictionary, DictionaryEntry } = await import('@open-mercato/core/modules/dictionaries/data/entities')\n\n // Find the dictionary\n const dictionary = await em.findOne(Dictionary, {\n key: dictionaryKey,\n tenantId,\n organizationId,\n deletedAt: null,\n })\n\n if (!dictionary) {\n logger.warn('Dictionary not found', { component: 'UPDATE_ENTITY', dictionaryKey })\n return null\n }\n\n // Find the entry by normalized value\n const normalizedValue = value.toLowerCase().trim()\n const entry = await em.findOne(DictionaryEntry, {\n dictionary: dictionary.id,\n tenantId,\n organizationId,\n normalizedValue,\n })\n\n if (!entry) {\n logger.warn('Dictionary entry not found', { component: 'UPDATE_ENTITY', dictionaryKey, value })\n return null\n }\n\n return entry.id\n } catch (error) {\n logger.error('Error resolving dictionary entry', { component: 'UPDATE_ENTITY', err: error })\n return null\n }\n}\n\n/**\n * CALL_WEBHOOK activity handler\n *\n * Makes HTTP request to an external URL. Applies shared SSRF guard\n * (protocol / credentials / blocked host / private IP literal / DNS rebinding)\n * before issuing the request and rejects any 3xx redirect rather than following.\n */\nexport type CallWebhookDeps = {\n lookupHost?: HostLookup\n allowPrivate?: boolean\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}\n\nexport async function executeCallWebhook(\n config: unknown,\n context: ActivityContext,\n deps: CallWebhookDeps = {}\n): Promise<any> {\n const parsed = callWebhookConfigSchema.safeParse(config)\n if (!parsed.success) {\n const issues = parsed.error.issues\n .map((issue) => `${issue.path.join('.') || 'config'}: ${issue.message}`)\n .join('; ')\n throw new Error(`CALL_WEBHOOK config invalid: ${issues}`)\n }\n const { url, method, headers: rawHeaders, body } = parsed.data\n const headers = rawHeaders ?? {}\n\n const allowPrivate = deps.allowPrivate ?? isAllowPrivateWorkflowWebhookUrlsEnabled()\n\n let response: Response\n try {\n response = await safeOutboundFetch(\n url,\n {\n method,\n headers: {\n 'Content-Type': 'application/json',\n ...headers,\n },\n body: body !== undefined && body !== null ? JSON.stringify(body) : undefined,\n redirect: 'manual',\n signal: deps.signal,\n },\n {\n subject: 'Workflow webhook URL',\n allowPrivate,\n lookupHost: deps.lookupHost,\n fetchImpl: deps.fetchImpl,\n },\n )\n } catch (error) {\n if (error instanceof UnsafeOutboundUrlError) {\n throw new Error(\n `CALL_WEBHOOK rejected unsafe URL (reason=${error.reason}): ${error.message}`\n )\n }\n throw error\n }\n\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location')\n throw new Error(\n `CALL_WEBHOOK refused to follow redirect ${response.status} to ${\n location ?? '(no Location header)'\n }`\n )\n }\n\n // Parse response\n let result: any\n const contentType = response.headers.get('content-type')\n\n if (contentType && contentType.includes('application/json')) {\n result = await response.json()\n } else {\n result = await response.text()\n }\n\n // Check for HTTP errors\n if (!response.ok) {\n throw new Error(\n `Webhook request failed with status ${response.status}: ${JSON.stringify(result)}`\n )\n }\n\n return {\n status: response.status,\n statusText: response.statusText,\n result,\n }\n}\n\n/**\n * EXECUTE_FUNCTION activity handler\n *\n * Calls a registered function from DI container\n */\nexport async function executeFunction(\n config: any,\n context: ActivityContext,\n container: AwilixContainer\n): Promise<any> {\n const { functionName, args = {} } = config\n\n if (!functionName) {\n throw new Error('EXECUTE_FUNCTION requires \"functionName\" field')\n }\n\n // Look up function in container\n const fnKey = `workflowFunction:${functionName}`\n\n try {\n const fn = container.resolve(fnKey)\n\n if (typeof fn !== 'function') {\n throw new Error(`Registered workflow function \"${functionName}\" is not a function`)\n }\n\n // Call function with args and context\n const result = await fn(args, context)\n\n return { executed: true, functionName, result }\n } catch (error) {\n if (error instanceof Error && error.message.includes('not registered')) {\n throw new Error(\n `Workflow function \"${functionName}\" not registered in DI container (key: ${fnKey})`\n )\n }\n throw error\n }\n}\n\n/**\n * Calculate delay in milliseconds from a WAIT activity config.\n * Supports either `duration` (relative, e.g. \"PT5M\") or `until` (absolute ISO 8601 datetime).\n */\nfunction calculateWaitDelayMs(config: { duration?: string; until?: string }): number {\n if (config.until) {\n const targetDate = new Date(config.until)\n if (isNaN(targetDate.getTime())) {\n throw new Error(`WAIT activity: invalid \"until\" datetime: ${config.until}`)\n }\n const delayMs = targetDate.getTime() - Date.now()\n return Math.max(0, delayMs)\n }\n\n if (config.duration) {\n return parseDuration(config.duration)\n }\n\n throw new Error('WAIT activity requires \"duration\" (e.g., \"PT5M\", \"1h\") or \"until\" (ISO 8601 datetime)')\n}\n\n/**\n * WAIT activity handler\n *\n * Delays workflow execution for a configured duration or until a specific datetime.\n * - `duration`: relative delay (e.g. \"PT5M\", \"1h\", \"30s\")\n * - `until`: absolute datetime (e.g. \"2026-04-15T10:00:00Z\")\n * - Sync mode: blocks via sleep (suitable for short delays)\n * - Async mode: delay is handled by the queue's delayMs option;\n * this handler returns immediately when called from the worker\n */\nasync function executeWait(config: any): Promise<any> {\n const durationMs = calculateWaitDelayMs(config)\n\n // In sync mode, actually sleep for the duration\n // In async mode (called from worker), the delay already happened via queue scheduling\n await sleep(durationMs)\n\n return { waited: true, durationMs }\n}\n\n/**\n * CALL_API activity handler\n *\n * Makes authenticated HTTP request to internal Open Mercato APIs\n * - Automatically creates one-time API key for authentication\n * - Injects tenant/organization context headers\n * - Validates URL security (SSRF prevention)\n * - Classifies errors (retriable vs non-retriable)\n * - Deletes API key after request (no stored credentials!)\n */\nexport async function executeCallApi(\n em: EntityManager,\n config: any,\n context: ActivityContext,\n container: AwilixContainer,\n signal?: AbortSignal\n): Promise<any> {\n // 1. Interpolate variables in config (including {{workflow.*}}, {{context.*}}, allowlisted {{env.*}}, {{now}})\n const interpolatedConfig = interpolateVariables(config, context.workflowContext, context.workflowInstance)\n\n const {\n endpoint,\n method = 'GET',\n headers = {},\n body,\n validateTenantMatch = true,\n } = interpolatedConfig\n\n\n if (!endpoint) {\n throw new Error('CALL_API requires \"endpoint\" field')\n }\n\n // 2. Build full URL (prepend APP_URL for relative paths)\n const fullUrl = buildApiUrl(endpoint)\n\n // 3. Import the one-time API key helper\n const { withOnetimeApiKey } = await import('../../api_keys/services/apiKeyService')\n\n // 4. Create the one-time API key on an EntityManager that is fully detached\n // from the surrounding request/transaction context.\n //\n // CALL_API runs inside `workflowExecutor.executeWorkflow()`, which wraps\n // the whole execution in `em.transactional(...)`. The request EM is forked\n // with `useContext: true`, so while that transaction is open, EVERY\n // operation on the container's `em` \u2014 including this API key's\n // persist/flush \u2014 is transparently redirected to the uncommitted\n // transaction fork (MikroORM `getContext()` \u2192 `TransactionContext`). The\n // key would therefore stay invisible until the transaction commits, but\n // the commit cannot happen until this activity returns. The outbound\n // self-authenticated `fetch` below opens a SEPARATE DB connection that\n // cannot see the uncommitted row, so the internal API responds `401` and\n // the activity fails (issue #4202).\n //\n // Forking with `useContext: false` (matching the query_index/webhooks\n // isolated-EM convention) gives the key its own pooled connection with\n // autocommit, so it is committed and visible to the internal request\n // immediately.\n const apiKeyEm = container\n .resolve<PostgreSqlEntityManager>('em')\n .fork({ clear: true, freshEventManager: true, useContext: false }) as PostgreSqlEntityManager\n\n // 5. Resolve the roles that the one-time API key will inherit.\n //\n // SECURITY: The key must never exceed the permissions of the human who\n // triggered (or authored) this workflow. Previously this code looked up\n // a role named \"admin\"/\"superadmin\" for the tenant and assigned it to\n // the key \u2014 which allowed any non-admin workflow author with\n // `workflows.definitions.edit` + `workflows.instances.create` to issue\n // arbitrary administrative API calls via a CALL_API activity. See the\n // SECURITY.md changelog entry for this fix.\n //\n // The resolution strategy is:\n // 1. Use the workflow instance's `metadata.initiatedBy` user (whoever\n // manually started the instance), when available. Only this user's\n // current active roles are used \u2014 we never fall back to the author\n // when the initiator is known, because that would escalate the\n // initiator's privileges.\n // 2. Fall back to the workflow definition's `createdBy` (author) only\n // when the instance was started by an event trigger with no user.\n // 3. If no traceable principal exists, the activity refuses to run \u2014\n // there is no \"system\" fallback that bypasses RBAC.\n const resolvedRoleIds = await resolveCallApiRoleIds(apiKeyEm, context.workflowInstance)\n\n if (resolvedRoleIds.length === 0) {\n throw new Error(\n `[CALL_API] Refusing to execute CALL_API for workflow instance ${context.workflowInstance.id}: ` +\n `no traceable user roles could be resolved from the workflow instance or definition. ` +\n `CALL_API activities must run under the identity of the user who triggered them.`\n )\n }\n\n // 6. Execute request with one-time API key scoped to the resolved user's roles\n return await withOnetimeApiKey(\n apiKeyEm,\n {\n name: `__workflow_${context.workflowInstance.id}__`,\n description: `One-time key for workflow ${context.workflowInstance.workflowId} instance ${context.workflowInstance.id}`,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n roles: resolvedRoleIds,\n expiresAt: null,\n },\n async (apiKeySecret) => {\n // Build request headers (auth + context + custom)\n const requestHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'Authorization': `apikey ${apiKeySecret}`,\n 'X-Tenant-Id': context.workflowInstance.tenantId,\n 'X-Organization-Id': context.workflowInstance.organizationId,\n 'X-Workflow-Instance-Id': context.workflowInstance.id,\n ...headers,\n }\n\n // Make HTTP request\n const response = await fetch(fullUrl, {\n method,\n headers: requestHeaders,\n body: body ? JSON.stringify(body) : undefined,\n signal,\n })\n\n // Parse response body (JSON-safe)\n let responseBody: any\n const contentType = response.headers.get('content-type')\n\n try {\n if (contentType && contentType.includes('application/json')) {\n responseBody = await response.json()\n } else {\n responseBody = await response.text()\n }\n } catch (error) {\n responseBody = null\n }\n\n // Check for HTTP errors and classify\n if (!response.ok) {\n classifyAndThrowError(response.status, responseBody, fullUrl)\n }\n\n // Validate tenant match (security check)\n if (validateTenantMatch && responseBody && typeof responseBody === 'object') {\n if (responseBody.tenantId && responseBody.tenantId !== context.workflowInstance.tenantId) {\n throw new Error(\n `Tenant ID mismatch: workflow expects ${context.workflowInstance.tenantId} but API returned ${responseBody.tenantId}`\n )\n }\n }\n\n // Return structured result\n return {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n body: responseBody,\n authenticated: true,\n tenantId: context.workflowInstance.tenantId,\n organizationId: context.workflowInstance.organizationId,\n }\n }\n )\n}\n\n// ============================================================================\n// CALL_API Helper Functions\n// ============================================================================\n\nexport type CallApiInstanceLike = {\n id: string\n tenantId: string\n organizationId: string\n definitionId: string\n metadata?: { initiatedBy?: string | null } | null\n}\n\nasync function resolveActiveRoleIdsForUser(\n em: any,\n userId: string,\n scope: { tenantId: string; organizationId: string },\n): Promise<string[]> {\n const { findOneWithDecryption, findWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const { User, UserRole, Role } = await import('../../auth/data/entities')\n\n const user = await findOneWithDecryption(em, User, {\n id: userId,\n tenantId: scope.tenantId,\n deletedAt: null,\n }, {}, scope)\n if (!user) return []\n\n const userRoles = await findWithDecryption(\n em,\n UserRole,\n { user: user.id, deletedAt: null },\n { populate: ['role'] },\n scope,\n )\n const roleIds = userRoles\n .map((ur: any) => (typeof ur.role === 'string' ? ur.role : ur.role?.id))\n .filter((id: unknown): id is string => typeof id === 'string' && id.length > 0)\n\n if (roleIds.length === 0) return []\n\n const scopedRoles = await findWithDecryption(em, Role, {\n id: { $in: roleIds },\n tenantId: scope.tenantId,\n deletedAt: null,\n }, {}, scope)\n return scopedRoles.map((r: any) => r.id as string)\n}\n\nexport async function resolveCallApiRoleIds(\n em: any,\n instance: CallApiInstanceLike\n): Promise<string[]> {\n if (!instance.definitionId) return []\n\n const { findOneWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const { WorkflowDefinition } = await import('../data/entities')\n\n const scope = { tenantId: instance.tenantId, organizationId: instance.organizationId }\n\n // 1. Prefer the triggering user (whoever manually started this instance).\n // WorkflowInstance.metadata.initiatedBy is the canonical record of that\n // principal for user-started instances; use their current role set so\n // CALL_API never exceeds the initiator's permissions. Refuse if the\n // initiator has no active scoped roles \u2014 do not fall back to the\n // definition author, which would escalate the initiator's privileges.\n const initiatorUserId = instance.metadata?.initiatedBy ?? null\n if (initiatorUserId) {\n return resolveActiveRoleIdsForUser(em, initiatorUserId, scope)\n }\n\n // 2. Event-triggered instance with no human initiator: fall back to the\n // definition author. Soft-deleted definitions must not mint keys.\n const definition = await findOneWithDecryption(em, WorkflowDefinition, {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n deletedAt: null,\n }, {}, scope)\n const authorUserId = definition?.createdBy\n if (!authorUserId) return []\n\n return resolveActiveRoleIdsForUser(em, authorUserId, scope)\n}\n\n/**\n * Build full API URL from endpoint\n * - Relative paths (/api/...) \u2192 prepend APP_URL\n * - Absolute URLs \u2192 validate domain matches APP_URL (SSRF prevention)\n */\nfunction buildApiUrl(endpoint: string): string {\n const appUrl = process.env.APP_URL || 'http://localhost:3000'\n\n // Relative path - prepend APP_URL\n if (endpoint.startsWith('/')) {\n // Security: Only allow /api/* paths\n if (!endpoint.startsWith('/api/')) {\n throw new Error(`CALL_API only supports /api/* paths, got: ${endpoint}`)\n }\n return `${appUrl}${endpoint}`\n }\n\n // Absolute URL - validate domain matches APP_URL (SSRF prevention)\n try {\n const endpointUrl = new URL(endpoint)\n const appUrlObj = new URL(appUrl)\n\n if (endpointUrl.host !== appUrlObj.host) {\n throw new Error(\n `SSRF Prevention: CALL_API endpoint domain (${endpointUrl.host}) does not match APP_URL (${appUrlObj.host})`\n )\n }\n\n return endpoint\n } catch (error) {\n if (error instanceof TypeError) {\n throw new Error(`Invalid endpoint URL: ${endpoint}`)\n }\n throw error\n }\n}\n\n/**\n * Classify HTTP error and throw appropriate error\n * - 400-499: Non-retriable (client error - validation/auth)\n * - 500-599: Retriable (server error)\n */\nfunction classifyAndThrowError(status: number, body: any, url: string): never {\n const bodyStr = typeof body === 'string' ? body : JSON.stringify(body)\n\n if (status >= 400 && status < 500) {\n // Client errors - non-retriable\n throw new Error(\n `CALL_API request failed with status ${status} (non-retriable): ${bodyStr}`\n )\n }\n\n if (status >= 500) {\n // Server errors - retriable\n const error: any = new Error(\n `CALL_API request failed with status ${status} (retriable): ${bodyStr}`\n )\n error.retriable = true\n throw error\n }\n\n // Other errors\n throw new Error(`CALL_API request failed with status ${status}: ${bodyStr}`)\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Interpolate variables in config from workflow context\n *\n * Supports syntax:\n * - {{context.field}} or {{context.nested.field}} - from workflow context\n * - {{workflow.instanceId}} - workflow instance ID\n * - {{workflow.tenantId}} - tenant ID\n * - {{workflow.organizationId}} - organization ID\n * - {{workflow.currentStepId}} - current step ID\n * - {{env.VAR_NAME}} - server-allowlisted environment variables\n * - {{now}} - current ISO timestamp\n */\nfunction interpolateVariables(\n config: any,\n context: Record<string, any>,\n workflowInstance?: WorkflowInstance\n): any {\n if (typeof config === 'string') {\n // Check if this is a single variable reference (e.g., \"{{context.cart.items}}\")\n // This preserves the original type (array, object, number, boolean)\n const singleVarMatch = config.match(/^\\{\\{([^}]+)\\}\\}$/)\n\n if (singleVarMatch) {\n const trimmedPath = singleVarMatch[1].trim()\n\n // Handle {{workflow.*}} variables\n if (trimmedPath.startsWith('workflow.') && workflowInstance) {\n const workflowKey = trimmedPath.substring('workflow.'.length)\n switch (workflowKey) {\n case 'instanceId':\n return workflowInstance.id\n case 'tenantId':\n return workflowInstance.tenantId\n case 'organizationId':\n return workflowInstance.organizationId\n case 'currentStepId':\n return workflowInstance.currentStepId\n case 'workflowId':\n return workflowInstance.workflowId\n case 'version':\n return workflowInstance.version // Return as number\n default:\n return config // Return original if unknown\n }\n }\n\n // Handle {{env.*}} variables\n if (trimmedPath.startsWith('env.')) {\n const envKey = trimmedPath.substring('env.'.length)\n return resolveWorkflowEnvInterpolation(envKey)\n }\n\n // Handle {{now}} - current timestamp\n if (trimmedPath === 'now') {\n return new Date().toISOString()\n }\n\n // Handle {{context.*}} variables (default behavior)\n const contextPath = trimmedPath.startsWith('context.')\n ? trimmedPath.substring('context.'.length)\n : trimmedPath\n\n const value = getNestedValue(context, contextPath)\n return value !== undefined ? value : config // Return raw value to preserve type\n }\n\n // Multiple interpolations or mixed text - return string\n return config.replace(/\\{\\{([^}]+)\\}\\}/g, (match, path) => {\n const trimmedPath = path.trim()\n\n // Handle {{workflow.*}} variables\n if (trimmedPath.startsWith('workflow.') && workflowInstance) {\n const workflowKey = trimmedPath.substring('workflow.'.length)\n switch (workflowKey) {\n case 'instanceId':\n return workflowInstance.id\n case 'tenantId':\n return workflowInstance.tenantId\n case 'organizationId':\n return workflowInstance.organizationId\n case 'currentStepId':\n return workflowInstance.currentStepId\n case 'workflowId':\n return workflowInstance.workflowId\n case 'version':\n return String(workflowInstance.version)\n default:\n return match // Unknown workflow key\n }\n }\n\n // Handle {{env.*}} variables\n if (trimmedPath.startsWith('env.')) {\n const envKey = trimmedPath.substring('env.'.length)\n return resolveWorkflowEnvInterpolation(envKey)\n }\n\n // Handle {{now}} - current timestamp\n if (trimmedPath === 'now') {\n return new Date().toISOString()\n }\n\n // Handle {{context.*}} variables (default behavior)\n const contextPath = trimmedPath.startsWith('context.')\n ? trimmedPath.substring('context.'.length)\n : trimmedPath\n\n const value = getNestedValue(context, contextPath)\n return value !== undefined ? String(value) : match\n })\n }\n\n if (Array.isArray(config)) {\n return config.map((item) => interpolateVariables(item, context, workflowInstance))\n }\n\n if (config && typeof config === 'object') {\n const result: Record<string, any> = {}\n for (const [key, value] of Object.entries(config)) {\n result[key] = interpolateVariables(value, context, workflowInstance)\n }\n return result\n }\n\n return config\n}\n\n/**\n * Get nested value from object by path (e.g., \"user.email\")\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split('.')\n let value = obj\n\n for (const part of parts) {\n if (value && typeof value === 'object' && part in value) {\n value = value[part]\n } else {\n return undefined\n }\n }\n\n return value\n}\n\n/**\n * Calculate exponential backoff delay\n */\nfunction calculateBackoff(\n initialIntervalMs: number,\n backoffCoefficient: number,\n attempt: number,\n maxIntervalMs: number\n): number {\n const backoff = initialIntervalMs * Math.pow(backoffCoefficient, attempt)\n return Math.min(backoff, maxIntervalMs || Infinity)\n}\n\n/**\n * Sleep for specified milliseconds\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Execute a promise with timeout\n */\nasync function executeWithTimeout<T>(\n executor: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number\n): Promise<T> {\n let timeoutId: NodeJS.Timeout\n const abortController = new AbortController()\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => {\n abortController.abort()\n reject(new Error(`Activity execution timeout after ${timeoutMs}ms`))\n }, timeoutMs)\n })\n\n try {\n return await Promise.race([executor(abortController.signal), timeoutPromise])\n } finally {\n clearTimeout(timeoutId!)\n }\n}\n"],
5
+ "mappings": "AAgBA,SAAS,yBAAgC;AAEzC;AAAA,EACE;AAAA,EACA;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.85bbf320ad",
3
+ "version": "0.6.7-develop.6826.1.3f6d307d01",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -254,16 +254,16 @@
254
254
  "zod": "^4.4.3"
255
255
  },
256
256
  "peerDependencies": {
257
- "@open-mercato/ai-assistant": "0.6.7-develop.6825.1.85bbf320ad",
258
- "@open-mercato/shared": "0.6.7-develop.6825.1.85bbf320ad",
259
- "@open-mercato/ui": "0.6.7-develop.6825.1.85bbf320ad",
257
+ "@open-mercato/ai-assistant": "0.6.7-develop.6826.1.3f6d307d01",
258
+ "@open-mercato/shared": "0.6.7-develop.6826.1.3f6d307d01",
259
+ "@open-mercato/ui": "0.6.7-develop.6826.1.3f6d307d01",
260
260
  "react": "^19.0.0",
261
261
  "react-dom": "^19.0.0"
262
262
  },
263
263
  "devDependencies": {
264
- "@open-mercato/ai-assistant": "0.6.7-develop.6825.1.85bbf320ad",
265
- "@open-mercato/shared": "0.6.7-develop.6825.1.85bbf320ad",
266
- "@open-mercato/ui": "0.6.7-develop.6825.1.85bbf320ad",
264
+ "@open-mercato/ai-assistant": "0.6.7-develop.6826.1.3f6d307d01",
265
+ "@open-mercato/shared": "0.6.7-develop.6826.1.3f6d307d01",
266
+ "@open-mercato/ui": "0.6.7-develop.6826.1.3f6d307d01",
267
267
  "@testing-library/dom": "^10.4.1",
268
268
  "@testing-library/jest-dom": "^6.9.1",
269
269
  "@testing-library/react": "^16.3.1",
@@ -16,6 +16,9 @@ import {
16
16
  } from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'
17
17
  import { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'
18
18
  import { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'
19
+ import { createLogger } from '@open-mercato/shared/lib/logger'
20
+
21
+ const logger = createLogger('customer_accounts').child({ component: 'admin-users-invite' })
19
22
 
20
23
  export const metadata = {}
21
24
 
@@ -121,11 +124,11 @@ export async function POST(req: Request) {
121
124
  rawToken,
122
125
  })
123
126
  } catch (error) {
124
- console.error('[customer_accounts.admin.users-invite] invitation email failed', error)
127
+ logger.error('Invitation email failed', { err: error })
125
128
  try {
126
129
  await customerInvitationService.rollbackInvitation(invitation, rollbackState)
127
130
  } catch (rollbackError) {
128
- console.error('[customer_accounts.admin.users-invite] invitation rollback failed', rollbackError)
131
+ logger.error('Invitation rollback failed', { err: rollbackError })
129
132
  }
130
133
  return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })
131
134
  }
@@ -17,6 +17,9 @@ import {
17
17
  } from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'
18
18
  import { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'
19
19
  import { sendCustomerInvitationEmail } from '@open-mercato/core/modules/customer_accounts/lib/invitationEmail'
20
+ import { createLogger } from '@open-mercato/shared/lib/logger'
21
+
22
+ const logger = createLogger('customer_accounts').child({ component: 'portal-users-invite' })
20
23
 
21
24
  export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
22
25
 
@@ -110,11 +113,11 @@ export async function POST(req: Request) {
110
113
  rawToken,
111
114
  })
112
115
  } catch (error) {
113
- console.error('[customer_accounts.portal.users-invite] invitation email failed', error)
116
+ logger.error('Invitation email failed', { err: error })
114
117
  try {
115
118
  await customerInvitationService.rollbackInvitation(invitation, rollbackState)
116
119
  } catch (rollbackError) {
117
- console.error('[customer_accounts.portal.users-invite] invitation rollback failed', rollbackError)
120
+ logger.error('Invitation rollback failed', { err: rollbackError })
118
121
  }
119
122
  return NextResponse.json({ ok: false, error: 'Invitation email could not be sent' }, { status: 502 })
120
123
  }
@@ -371,7 +371,7 @@ export async function executeActivity(
371
371
  const timeoutMs = resolveActivityTimeoutMs(activity)
372
372
  const result = timeoutMs
373
373
  ? await executeWithTimeout(
374
- () => executeActivityByType(em, container, activity, context),
374
+ (signal) => executeActivityByType(em, container, activity, context, signal),
375
375
  timeoutMs
376
376
  )
377
377
  : await executeActivityByType(em, container, activity, context)
@@ -511,7 +511,8 @@ async function executeActivityByType(
511
511
  em: EntityManager,
512
512
  container: AwilixContainer,
513
513
  activity: ActivityDefinition,
514
- context: ActivityContext
514
+ context: ActivityContext,
515
+ signal?: AbortSignal
515
516
  ): Promise<any> {
516
517
  // Interpolate config variables from context (including workflow metadata)
517
518
  const interpolatedConfig = interpolateVariables(activity.config, context.workflowContext, context.workflowInstance)
@@ -521,7 +522,7 @@ async function executeActivityByType(
521
522
  return await executeSendEmail(interpolatedConfig, context, container)
522
523
 
523
524
  case 'CALL_API':
524
- return await executeCallApi(em, interpolatedConfig, context, container)
525
+ return await executeCallApi(em, interpolatedConfig, context, container, signal)
525
526
 
526
527
  case 'EMIT_EVENT':
527
528
  return await executeEmitEvent(interpolatedConfig, context, container)
@@ -530,7 +531,7 @@ async function executeActivityByType(
530
531
  return await executeUpdateEntity(em, interpolatedConfig, context, container)
531
532
 
532
533
  case 'CALL_WEBHOOK':
533
- return await executeCallWebhook(interpolatedConfig, context)
534
+ return await executeCallWebhook(interpolatedConfig, context, { signal })
534
535
 
535
536
  case 'EXECUTE_FUNCTION':
536
537
  return await executeFunction(interpolatedConfig, context, container)
@@ -1456,19 +1457,21 @@ function sleep(ms: number): Promise<void> {
1456
1457
  * Execute a promise with timeout
1457
1458
  */
1458
1459
  async function executeWithTimeout<T>(
1459
- executor: () => Promise<T>,
1460
+ executor: (signal: AbortSignal) => Promise<T>,
1460
1461
  timeoutMs: number
1461
1462
  ): Promise<T> {
1462
1463
  let timeoutId: NodeJS.Timeout
1464
+ const abortController = new AbortController()
1463
1465
 
1464
1466
  const timeoutPromise = new Promise<never>((_, reject) => {
1465
1467
  timeoutId = setTimeout(() => {
1468
+ abortController.abort()
1466
1469
  reject(new Error(`Activity execution timeout after ${timeoutMs}ms`))
1467
1470
  }, timeoutMs)
1468
1471
  })
1469
1472
 
1470
1473
  try {
1471
- return await Promise.race([executor(), timeoutPromise])
1474
+ return await Promise.race([executor(abortController.signal), timeoutPromise])
1472
1475
  } finally {
1473
1476
  clearTimeout(timeoutId!)
1474
1477
  }