@open-mercato/core 0.10.1-develop.7961.1.d65694a8e6 → 0.10.1-develop.7972.1.03f813eaaf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/auth/api/logout.js +3 -3
  3. package/dist/modules/auth/api/logout.js.map +2 -2
  4. package/dist/modules/communication_channels/setup.js +49 -45
  5. package/dist/modules/communication_channels/setup.js.map +2 -2
  6. package/dist/modules/customer_accounts/services/domainMappingService.js +55 -29
  7. package/dist/modules/customer_accounts/services/domainMappingService.js.map +2 -2
  8. package/dist/modules/customers/components/detail/ActivitiesSection.js +8 -3
  9. package/dist/modules/customers/components/detail/ActivitiesSection.js.map +2 -2
  10. package/dist/modules/customers/components/detail/ActivityCard.js +3 -3
  11. package/dist/modules/customers/components/detail/ActivityCard.js.map +2 -2
  12. package/dist/modules/customers/components/detail/ActivityHistorySection.js +19 -7
  13. package/dist/modules/customers/components/detail/ActivityHistorySection.js.map +2 -2
  14. package/dist/modules/customers/components/detail/ActivityTimeline.js +5 -5
  15. package/dist/modules/customers/components/detail/ActivityTimeline.js.map +2 -2
  16. package/dist/modules/directory/subscribers/seedOrganizationDefaults.js +67 -0
  17. package/dist/modules/directory/subscribers/seedOrganizationDefaults.js.map +7 -0
  18. package/dist/modules/ecommerce/api/storefront/categories/[slug]/route.js +1 -1
  19. package/dist/modules/ecommerce/api/storefront/categories/[slug]/route.js.map +2 -2
  20. package/dist/modules/ecommerce/api/storefront/categories/route.js +1 -1
  21. package/dist/modules/ecommerce/api/storefront/categories/route.js.map +2 -2
  22. package/dist/modules/ecommerce/api/storefront/context/route.js +1 -1
  23. package/dist/modules/ecommerce/api/storefront/context/route.js.map +2 -2
  24. package/dist/modules/ecommerce/api/storefront/products/[idOrHandle]/route.js +1 -1
  25. package/dist/modules/ecommerce/api/storefront/products/[idOrHandle]/route.js.map +2 -2
  26. package/dist/modules/ecommerce/api/storefront/products/route.js +1 -1
  27. package/dist/modules/ecommerce/api/storefront/products/route.js.map +2 -2
  28. package/dist/modules/ecommerce/api/storefront/search/suggest/route.js +1 -1
  29. package/dist/modules/ecommerce/api/storefront/search/suggest/route.js.map +2 -2
  30. package/dist/modules/ecommerce/lib/cacheInvalidation.js +3 -0
  31. package/dist/modules/ecommerce/lib/cacheInvalidation.js.map +2 -2
  32. package/dist/modules/ecommerce/lib/cacheKeys.js +4 -0
  33. package/dist/modules/ecommerce/lib/cacheKeys.js.map +2 -2
  34. package/dist/modules/ecommerce/lib/storeContext.js +36 -12
  35. package/dist/modules/ecommerce/lib/storeContext.js.map +2 -2
  36. package/dist/modules/ecommerce/subscribers/sales-channel-cache-invalidation.js +14 -0
  37. package/dist/modules/ecommerce/subscribers/sales-channel-cache-invalidation.js.map +7 -0
  38. package/dist/modules/integrations/setup.js +34 -24
  39. package/dist/modules/integrations/setup.js.map +2 -2
  40. package/dist/modules/messages/components/MessagesInboxPageClient.js +1 -1
  41. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  42. package/dist/modules/messages/components/message-detail/panels/MainMessageHeader.js +3 -3
  43. package/dist/modules/messages/components/message-detail/panels/MainMessageHeader.js.map +2 -2
  44. package/dist/modules/messages/components/message-detail/panels/body-panel.js +2 -2
  45. package/dist/modules/messages/components/message-detail/panels/body-panel.js.map +2 -2
  46. package/dist/modules/payment_gateways/setup.js +3 -0
  47. package/dist/modules/payment_gateways/setup.js.map +2 -2
  48. package/dist/modules/warranty_claims/backend/warranty_claims/[id]/page.js +30 -11
  49. package/dist/modules/warranty_claims/backend/warranty_claims/[id]/page.js.map +3 -3
  50. package/dist/modules/warranty_claims/setup.js +34 -30
  51. package/dist/modules/warranty_claims/setup.js.map +2 -2
  52. package/dist/modules/workflows/setup.js +7 -0
  53. package/dist/modules/workflows/setup.js.map +2 -2
  54. package/package.json +7 -7
  55. package/src/modules/auth/api/logout.ts +3 -3
  56. package/src/modules/communication_channels/setup.ts +59 -53
  57. package/src/modules/customer_accounts/services/domainMappingService.ts +57 -29
  58. package/src/modules/customers/components/detail/ActivitiesSection.tsx +8 -3
  59. package/src/modules/customers/components/detail/ActivityCard.tsx +3 -3
  60. package/src/modules/customers/components/detail/ActivityHistorySection.tsx +20 -8
  61. package/src/modules/customers/components/detail/ActivityTimeline.tsx +7 -7
  62. package/src/modules/customers/i18n/de.json +1 -0
  63. package/src/modules/customers/i18n/en.json +1 -0
  64. package/src/modules/customers/i18n/es.json +1 -0
  65. package/src/modules/customers/i18n/ko.json +1 -0
  66. package/src/modules/customers/i18n/pl.json +1 -0
  67. package/src/modules/directory/subscribers/seedOrganizationDefaults.ts +84 -0
  68. package/src/modules/ecommerce/api/storefront/categories/[slug]/route.ts +1 -1
  69. package/src/modules/ecommerce/api/storefront/categories/route.ts +1 -1
  70. package/src/modules/ecommerce/api/storefront/context/route.ts +1 -1
  71. package/src/modules/ecommerce/api/storefront/products/[idOrHandle]/route.ts +1 -1
  72. package/src/modules/ecommerce/api/storefront/products/route.ts +1 -1
  73. package/src/modules/ecommerce/api/storefront/search/suggest/route.ts +1 -1
  74. package/src/modules/ecommerce/lib/cacheInvalidation.ts +4 -0
  75. package/src/modules/ecommerce/lib/cacheKeys.ts +4 -0
  76. package/src/modules/ecommerce/lib/storeContext.ts +56 -10
  77. package/src/modules/ecommerce/subscribers/sales-channel-cache-invalidation.ts +12 -0
  78. package/src/modules/integrations/setup.ts +41 -24
  79. package/src/modules/messages/components/MessagesInboxPageClient.tsx +1 -1
  80. package/src/modules/messages/components/message-detail/panels/MainMessageHeader.tsx +3 -3
  81. package/src/modules/messages/components/message-detail/panels/body-panel.tsx +2 -2
  82. package/src/modules/payment_gateways/setup.ts +4 -0
  83. package/src/modules/warranty_claims/backend/warranty_claims/[id]/page.tsx +55 -28
  84. package/src/modules/warranty_claims/setup.ts +40 -30
  85. package/src/modules/workflows/setup.ts +8 -0
@@ -1,4 +1,4 @@
1
- [build:core] found 6279 entry points
1
+ [build:core] found 6287 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 271 entry points
4
4
  [build:core:generated] built successfully
@@ -41,7 +41,7 @@ function extractAuthTokenClaims(token) {
41
41
  async function POST(req) {
42
42
  const sessToken = parseCookie(req, "session_token");
43
43
  const authToken = parseCookie(req, "auth_token");
44
- if (!sessToken && !authToken) return buildSafeRedirectResponse(req, "/login");
44
+ if (!sessToken && !authToken) return buildSafeRedirectResponse(req, "/login", 303);
45
45
  const claims = extractAuthTokenClaims(authToken);
46
46
  let sessionRevoked = false;
47
47
  if (sessToken || claims.sessionId) {
@@ -69,7 +69,7 @@ async function POST(req) {
69
69
  at: (/* @__PURE__ */ new Date()).toISOString()
70
70
  }, { persistent: true }).catch(() => void 0);
71
71
  }
72
- const res = buildSafeRedirectResponse(req, "/login");
72
+ const res = buildSafeRedirectResponse(req, "/login", 303);
73
73
  res.cookies.set("auth_token", "", { path: "/", maxAge: 0 });
74
74
  res.cookies.set("session_token", "", { path: "/", maxAge: 0 });
75
75
  res.cookies.set("om_selected_org", "", { path: "/", maxAge: 0 });
@@ -87,7 +87,7 @@ const openApi = {
87
87
  summary: "Invalidate session and redirect",
88
88
  description: "Revokes the session identified by the `auth_token` sid claim and the `session_token` cookie, clears both cookies together with the organization-scope cookies (`om_selected_org`, `om_selected_tenant`), and redirects the browser to the login page. A valid access token is not required, so a logout submitted after the access token expired still revokes the remember-me refresh session. A request that carries neither session cookie is only redirected.",
89
89
  responses: [
90
- { status: 307, description: "Redirect to login after successful logout", mediaType: "text/html" }
90
+ { status: 303, description: "See Other: navigate to login with GET after logout", mediaType: "text/html" }
91
91
  ]
92
92
  }
93
93
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/api/logout.ts"],
4
- "sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { buildSafeRedirectResponse } from '@open-mercato/core/modules/auth/lib/requestRedirect'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\ntype AuthTokenClaims = {\n userId: string | null\n sessionId: string | null\n tenantId: string | null\n organizationId: string | null\n}\n\nconst emptyAuthTokenClaims: AuthTokenClaims = Object.freeze({\n userId: null,\n sessionId: null,\n tenantId: null,\n organizationId: null,\n})\n\nfunction parseCookie(req: Request, name: string): string | null {\n const cookie = req.headers.get('cookie') || ''\n const m = cookie.match(new RegExp('(?:^|;\\\\s*)' + name + '=([^;]+)'))\n if (!m) return null\n try {\n return decodeURIComponent(m[1])\n } catch {\n return null\n }\n}\n\nfunction readStringClaim(payload: Record<string, unknown>, key: string): string | null {\n const value = payload[key]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction extractAuthTokenClaims(token: string | null): AuthTokenClaims {\n if (!token) return emptyAuthTokenClaims\n try {\n const payload = verifyJwt(token) as Record<string, unknown> | null\n if (!payload || payload.type === 'customer') return emptyAuthTokenClaims\n return {\n userId: readStringClaim(payload, 'sub'),\n sessionId: readStringClaim(payload, 'sid'),\n tenantId: readStringClaim(payload, 'tenantId'),\n organizationId: readStringClaim(payload, 'orgId'),\n }\n } catch {\n return emptyAuthTokenClaims\n }\n}\n\nexport async function POST(req: Request) {\n const sessToken = parseCookie(req, 'session_token')\n const authToken = parseCookie(req, 'auth_token')\n if (!sessToken && !authToken) return buildSafeRedirectResponse(req, '/login')\n const claims = extractAuthTokenClaims(authToken)\n let sessionRevoked = false\n if (sessToken || claims.sessionId) {\n try {\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n if (claims.sessionId) {\n await auth.deleteSessionById(claims.sessionId)\n }\n if (sessToken) {\n await auth.deleteSessionByToken(sessToken)\n }\n sessionRevoked = true\n } catch (error) {\n getTelemetryRuntime()?.reportError(error, { module: 'auth', code: 'auth.logout_revoke_failed' })\n }\n }\n if (claims.userId) {\n void emitAuthEvent('auth.logout', {\n id: claims.userId,\n tenantId: claims.tenantId,\n organizationId: claims.organizationId,\n sessionId: claims.sessionId,\n sessionRevoked,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n const res = buildSafeRedirectResponse(req, '/login')\n res.cookies.set('auth_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('session_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('om_selected_org', '', { path: '/', maxAge: 0 })\n res.cookies.set('om_selected_tenant', '', { path: '/', maxAge: 0 })\n return res\n}\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Log out current session',\n methods: {\n POST: {\n summary: 'Invalidate session and redirect',\n description: 'Revokes the session identified by the `auth_token` sid claim and the `session_token` cookie, clears both cookies together with the organization-scope cookies (`om_selected_org`, `om_selected_tenant`), and redirects the browser to the login page. A valid access token is not required, so a logout submitted after the access token expired still revokes the remember-me refresh session. A request that carries neither session cookie is only redirected.',\n responses: [\n { status: 307, description: 'Redirect to login after successful logout', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
5
- "mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,SAAS,iCAAiC;AAC1C,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AASpC,MAAM,uBAAwC,OAAO,OAAO;AAAA,EAC1D,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,gBAAgB;AAClB,CAAC;AAED,SAAS,YAAY,KAAc,MAA6B;AAC9D,QAAM,SAAS,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAC5C,QAAM,IAAI,OAAO,MAAM,IAAI,OAAO,gBAAgB,OAAO,UAAU,CAAC;AACpE,MAAI,CAAC,EAAG,QAAO;AACf,MAAI;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;AAAA,MAChC,IAAI,OAAO;AAAA,MACX,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC7B,GAAG,EAAE,YAAY,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,EAChD;AACA,QAAM,MAAM,0BAA0B,KAAK,QAAQ;AACnD,MAAI,QAAQ,IAAI,cAAc,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC1D,MAAI,QAAQ,IAAI,iBAAiB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC7D,MAAI,QAAQ,IAAI,mBAAmB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC/D,MAAI,QAAQ,IAAI,sBAAsB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAClE,SAAO;AACT;AAEO,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM;AAC7B;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,6CAA6C,WAAW,YAAY;AAAA,MAClG;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { buildSafeRedirectResponse } from '@open-mercato/core/modules/auth/lib/requestRedirect'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\ntype AuthTokenClaims = {\n userId: string | null\n sessionId: string | null\n tenantId: string | null\n organizationId: string | null\n}\n\nconst emptyAuthTokenClaims: AuthTokenClaims = Object.freeze({\n userId: null,\n sessionId: null,\n tenantId: null,\n organizationId: null,\n})\n\nfunction parseCookie(req: Request, name: string): string | null {\n const cookie = req.headers.get('cookie') || ''\n const m = cookie.match(new RegExp('(?:^|;\\\\s*)' + name + '=([^;]+)'))\n if (!m) return null\n try {\n return decodeURIComponent(m[1])\n } catch {\n return null\n }\n}\n\nfunction readStringClaim(payload: Record<string, unknown>, key: string): string | null {\n const value = payload[key]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction extractAuthTokenClaims(token: string | null): AuthTokenClaims {\n if (!token) return emptyAuthTokenClaims\n try {\n const payload = verifyJwt(token) as Record<string, unknown> | null\n if (!payload || payload.type === 'customer') return emptyAuthTokenClaims\n return {\n userId: readStringClaim(payload, 'sub'),\n sessionId: readStringClaim(payload, 'sid'),\n tenantId: readStringClaim(payload, 'tenantId'),\n organizationId: readStringClaim(payload, 'orgId'),\n }\n } catch {\n return emptyAuthTokenClaims\n }\n}\n\nexport async function POST(req: Request) {\n const sessToken = parseCookie(req, 'session_token')\n const authToken = parseCookie(req, 'auth_token')\n if (!sessToken && !authToken) return buildSafeRedirectResponse(req, '/login', 303)\n const claims = extractAuthTokenClaims(authToken)\n let sessionRevoked = false\n if (sessToken || claims.sessionId) {\n try {\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n if (claims.sessionId) {\n await auth.deleteSessionById(claims.sessionId)\n }\n if (sessToken) {\n await auth.deleteSessionByToken(sessToken)\n }\n sessionRevoked = true\n } catch (error) {\n getTelemetryRuntime()?.reportError(error, { module: 'auth', code: 'auth.logout_revoke_failed' })\n }\n }\n if (claims.userId) {\n void emitAuthEvent('auth.logout', {\n id: claims.userId,\n tenantId: claims.tenantId,\n organizationId: claims.organizationId,\n sessionId: claims.sessionId,\n sessionRevoked,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n const res = buildSafeRedirectResponse(req, '/login', 303)\n res.cookies.set('auth_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('session_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('om_selected_org', '', { path: '/', maxAge: 0 })\n res.cookies.set('om_selected_tenant', '', { path: '/', maxAge: 0 })\n return res\n}\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Log out current session',\n methods: {\n POST: {\n summary: 'Invalidate session and redirect',\n description: 'Revokes the session identified by the `auth_token` sid claim and the `session_token` cookie, clears both cookies together with the organization-scope cookies (`om_selected_org`, `om_selected_tenant`), and redirects the browser to the login page. A valid access token is not required, so a logout submitted after the access token expired still revokes the remember-me refresh session. A request that carries neither session cookie is only redirected.',\n responses: [\n { status: 303, description: 'See Other: navigate to login with GET after logout', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,SAAS,iCAAiC;AAC1C,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AASpC,MAAM,uBAAwC,OAAO,OAAO;AAAA,EAC1D,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,gBAAgB;AAClB,CAAC;AAED,SAAS,YAAY,KAAc,MAA6B;AAC9D,QAAM,SAAS,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAC5C,QAAM,IAAI,OAAO,MAAM,IAAI,OAAO,gBAAgB,OAAO,UAAU,CAAC;AACpE,MAAI,CAAC,EAAG,QAAO;AACf,MAAI;AACF,WAAO,mBAAmB,EAAE,CAAC,CAAC;AAAA,EAChC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,gBAAgB,SAAkC,KAA4B;AACrF,QAAM,QAAQ,QAAQ,GAAG;AACzB,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;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MAAM,MAAM,MAAS;AAAA,EAChD;AACA,QAAM,MAAM,0BAA0B,KAAK,UAAU,GAAG;AACxD,MAAI,QAAQ,IAAI,cAAc,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC1D,MAAI,QAAQ,IAAI,iBAAiB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC7D,MAAI,QAAQ,IAAI,mBAAmB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC/D,MAAI,QAAQ,IAAI,sBAAsB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAClE,SAAO;AACT;AAEO,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM;AAC7B;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,sDAAsD,WAAW,YAAY;AAAA,MAC3G;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -17,6 +17,51 @@ function stableScheduleUuid(stableKey) {
17
17
  function stablePollTickScheduleId(organizationId) {
18
18
  return stableScheduleUuid(`communication_channels:poll-tick:${organizationId}`);
19
19
  }
20
+ async function ensureCommunicationChannelSchedules(ctx) {
21
+ const cradle = ctx.container;
22
+ if (typeof cradle.hasRegistration !== "function" || !cradle.hasRegistration("schedulerService")) return;
23
+ const schedulerService = ctx.container.resolve("schedulerService");
24
+ try {
25
+ await schedulerService.register({
26
+ id: stablePollTickScheduleId(ctx.organizationId),
27
+ name: "Communication channels poll tick",
28
+ description: `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,
29
+ scopeType: "organization",
30
+ organizationId: ctx.organizationId,
31
+ tenantId: ctx.tenantId,
32
+ scheduleType: "interval",
33
+ scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,
34
+ timezone: "UTC",
35
+ targetType: "queue",
36
+ targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,
37
+ targetPayload: {
38
+ scope: { tenantId: ctx.tenantId, organizationId: ctx.organizationId }
39
+ },
40
+ sourceType: "module",
41
+ sourceModule: "communication_channels",
42
+ isEnabled: true
43
+ });
44
+ await schedulerService.register({
45
+ id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${ctx.organizationId}`),
46
+ name: "Gmail watch renewal",
47
+ description: "Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.",
48
+ scopeType: "organization",
49
+ organizationId: ctx.organizationId,
50
+ tenantId: ctx.tenantId,
51
+ scheduleType: "cron",
52
+ scheduleValue: "0 4 * * *",
53
+ timezone: "UTC",
54
+ targetType: "queue",
55
+ targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,
56
+ targetPayload: { scope: { tenantId: ctx.tenantId, organizationId: ctx.organizationId } },
57
+ sourceType: "module",
58
+ sourceModule: "communication_channels",
59
+ isEnabled: true
60
+ });
61
+ } catch (error) {
62
+ logger.warn("Failed to register module schedules", { err: error });
63
+ }
64
+ }
20
65
  const setup = {
21
66
  defaultRoleFeatures: {
22
67
  superadmin: [
@@ -110,51 +155,10 @@ const setup = {
110
155
  });
111
156
  }
112
157
  }
113
- const cradle = container;
114
- if (typeof cradle.hasRegistration !== "function" || !cradle.hasRegistration("schedulerService")) {
115
- return;
116
- }
117
- const schedulerService = container.resolve("schedulerService");
118
- try {
119
- await schedulerService.register({
120
- id: stablePollTickScheduleId(organizationId),
121
- name: "Communication channels poll tick",
122
- description: `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,
123
- scopeType: "organization",
124
- organizationId,
125
- tenantId,
126
- scheduleType: "interval",
127
- scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,
128
- timezone: "UTC",
129
- targetType: "queue",
130
- targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,
131
- targetPayload: {
132
- scope: { tenantId, organizationId }
133
- },
134
- sourceType: "module",
135
- sourceModule: "communication_channels",
136
- isEnabled: true
137
- });
138
- await schedulerService.register({
139
- id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${organizationId}`),
140
- name: "Gmail watch renewal",
141
- description: "Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.",
142
- scopeType: "organization",
143
- organizationId,
144
- tenantId,
145
- scheduleType: "cron",
146
- scheduleValue: "0 4 * * *",
147
- timezone: "UTC",
148
- targetType: "queue",
149
- targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,
150
- targetPayload: { scope: { tenantId, organizationId } },
151
- sourceType: "module",
152
- sourceModule: "communication_channels",
153
- isEnabled: true
154
- });
155
- } catch (error) {
156
- logger.warn("Failed to register module schedules", { err: error });
157
- }
158
+ await ensureCommunicationChannelSchedules({ container, tenantId, organizationId });
159
+ },
160
+ async onOrganizationCreated({ container, tenantId, organizationId }) {
161
+ await ensureCommunicationChannelSchedules({ container, tenantId, organizationId });
158
162
  }
159
163
  };
160
164
  var setup_default = setup;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/communication_channels/setup.ts"],
4
- "sourcesContent": ["import { createHash } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { CommunicationChannel } from './data/entities'\nimport { COMMUNICATION_CHANNELS_QUEUES } from './lib/queue'\nimport { isTestChannelSeedingEnabled, TEST_SEED_PROVIDER_KEY } from './lib/test-seed'\n\nconst logger = createLogger('communication_channels')\n\ntype SchedulerServiceLike = {\n register: (registration: {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetPayload?: unknown\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n }) => Promise<void>\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\n/**\n * Sender the test-seed channel presents. Shared by the channel row's\n * `externalIdentifier` and its seeded credentials so both describe one address.\n */\nconst TEST_SEED_FROM_ADDRESS = 'system@test-seed.local'\n\n/**\n * Tick interval in seconds. Default 60s per email integration spec\n * \u00A7 Hub Deltas \u2192 Delta 6 (scheduler mechanism).\n */\nconst POLL_TICK_INTERVAL_SECONDS = Math.max(\n 10,\n Number.parseInt(process.env.OM_HUB_POLL_SCHEDULER_TICK_SECONDS ?? '60', 10) || 60,\n)\n\n/**\n * `scheduled_jobs.id` is a uuid column, so a module-owned schedule's stable\n * registration key must be hashed into a uuid rather than used verbatim \u2014 this\n * keeps `schedulerService.register()` an idempotent upsert across re-runs of\n * seedDefaults instead of trying to insert a raw string into the uuid PK.\n */\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction stablePollTickScheduleId(organizationId: string): string {\n return stableScheduleUuid(`communication_channels:poll-tick:${organizationId}`)\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n admin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n manager: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n ],\n employee: [\n 'communication_channels.view',\n 'communication_channels.react',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n ],\n },\n\n async seedDefaults({ container, organizationId, tenantId }) {\n if (isTestChannelSeedingEnabled() && process.env.SYSTEM_EMAIL_PROVIDER === TEST_SEED_PROVIDER_KEY) {\n const em = (container.resolve('em') as EntityManager).fork()\n const existing = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n tenantId,\n organizationId,\n userId: null,\n deletedAt: null,\n },\n undefined,\n { tenantId, organizationId },\n )\n if (!existing) {\n em.persist(em.create(CommunicationChannel, {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n displayName: 'Test Seed System Email',\n externalIdentifier: TEST_SEED_FROM_ADDRESS,\n userId: null,\n isPrimary: false,\n isActive: true,\n status: 'connected',\n tenantId,\n organizationId,\n }))\n await em.flush()\n }\n\n /**\n * Seeding the channel row without credentials is not a neutral state \u2014 it is a\n * fail-closed one. Once a tenant owns a Hub channel, `resolveTenantCredentials`\n * deliberately refuses to fall back to instance-wide env credentials, so every\n * tenant-scoped send throws `SYSTEM_EMAIL_CREDENTIALS_NOT_CONFIGURED`. Callers that\n * treat a failed send as a failed write (customer invitations roll back and return\n * 502) then fail outright rather than merely losing the email.\n *\n * Seeding credentials alongside the row makes the harness model a tenant that\n * finished configuring its provider, which is also the only one of the three\n * credential cases the integration suite would otherwise never exercise.\n */\n // Best-effort, like the scheduler registration below: credential storage needs the\n // integrations module and a usable encryption key, and neither is guaranteed in every\n // harness. A failure here must not abort tenant initialization for every other module.\n try {\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n const testSeedIntegrationId = `channel_${TEST_SEED_PROVIDER_KEY}`\n const credentialScope = { tenantId, organizationId, userId: null }\n const existingCredentials = await credentialsService.resolve(testSeedIntegrationId, credentialScope)\n if (!existingCredentials) {\n await credentialsService.save(\n testSeedIntegrationId,\n { testSeed: true, fromAddress: TEST_SEED_FROM_ADDRESS },\n credentialScope,\n )\n }\n } catch (error) {\n logger.warn('Test-seed email credentials could not be stored; tenant-scoped sends will fail closed', {\n err: error,\n tenantId,\n organizationId,\n })\n }\n }\n\n /**\n * Register the per-channel polling tick with `@open-mercato/scheduler`.\n *\n * Per email integration spec \u00A7 Hub Deltas \u2192 Delta 6: every\n * `POLL_TICK_INTERVAL_SECONDS` (default 60s), enqueue a single\n * `communication-channels-poll-tick` job that enumerates due channels and\n * fans out to the `communication-channels-poll` queue.\n *\n * The registration is per-organization (one tick row per org/tenant pair)\n * so multi-tenant deploys schedule independently. Skipped silently when the\n * scheduler module isn't enabled \u2014 keeps the hub usable in scheduler-less\n * test harnesses.\n */\n const cradle = container as { hasRegistration?: (name: string) => boolean }\n if (typeof cradle.hasRegistration !== 'function' || !cradle.hasRegistration('schedulerService')) {\n return\n }\n const schedulerService = container.resolve('schedulerService') as SchedulerServiceLike\n // Best-effort: a scheduler failure must not abort tenant initialization for\n // every other module (mirrors the ai_assistant setup pattern). The schedule\n // ids are deterministic uuids so re-runs upsert idempotently.\n try {\n await schedulerService.register({\n id: stablePollTickScheduleId(organizationId),\n name: 'Communication channels poll tick',\n description:\n `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'interval',\n scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,\n targetPayload: {\n scope: { tenantId, organizationId },\n },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n\n // Spec C \u00A7 Phase C4 \u2014 Gmail watch renewal cron, per-org so multi-tenant\n // deploys schedule independently.\n await schedulerService.register({\n id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${organizationId}`),\n name: 'Gmail watch renewal',\n description:\n 'Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.',\n scopeType: 'organization',\n organizationId,\n tenantId,\n scheduleType: 'cron',\n scheduleValue: '0 4 * * *',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,\n targetPayload: { scope: { tenantId, organizationId } },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register module schedules', { err: error })\n }\n },\n}\n\nexport default setup\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAE7B,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B,8BAA8B;AAEpE,MAAM,SAAS,aAAa,wBAAwB;AAsCpD,MAAM,yBAAyB;AAM/B,MAAM,6BAA6B,KAAK;AAAA,EACtC;AAAA,EACA,OAAO,SAAS,QAAQ,IAAI,sCAAsC,MAAM,EAAE,KAAK;AACjF;AAQA,SAAS,mBAAmB,WAA2B;AACrD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC/D,SAAO,GAAG,I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B,IAAI,mBAAmB,4CAA4C,cAAc,EAAE;AAAA,QACnF,MAAM;AAAA,QACN,aACE;AAAA,QACF,WAAW;AAAA,QACX;AAAA,QACA;AAAA,QACA,cAAc;AAAA,QACd,eAAe;AAAA,QACf,UAAU;AAAA,QACV,YAAY;AAAA,QACZ,aAAa,8BAA8B;AAAA,QAC3C,eAAe,EAAE,OAAO,EAAE,UAAU,eAAe,EAAE;AAAA,QACrD,YAAY;AAAA,QACZ,cAAc;AAAA,QACd,WAAW;AAAA,MACb,CAAC;AAAA,IACH,SAAS,OAAO;AACd,aAAO,KAAK,uCAAuC,EAAE,KAAK,MAAM,CAAC;AAAA,IACnE;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["import { createHash } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { CommunicationChannel } from './data/entities'\nimport { COMMUNICATION_CHANNELS_QUEUES } from './lib/queue'\nimport { isTestChannelSeedingEnabled, TEST_SEED_PROVIDER_KEY } from './lib/test-seed'\n\nconst logger = createLogger('communication_channels')\n\ntype SchedulerServiceLike = {\n register: (registration: {\n id: string\n name: string\n scopeType: 'system' | 'organization' | 'tenant'\n organizationId?: string\n tenantId?: string\n scheduleType: 'cron' | 'interval'\n scheduleValue: string\n timezone?: string\n targetType: 'queue' | 'command'\n targetQueue?: string\n targetPayload?: unknown\n sourceType?: 'user' | 'module'\n sourceModule?: string\n isEnabled?: boolean\n description?: string\n }) => Promise<void>\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\n/**\n * Sender the test-seed channel presents. Shared by the channel row's\n * `externalIdentifier` and its seeded credentials so both describe one address.\n */\nconst TEST_SEED_FROM_ADDRESS = 'system@test-seed.local'\n\n/**\n * Tick interval in seconds. Default 60s per email integration spec\n * \u00A7 Hub Deltas \u2192 Delta 6 (scheduler mechanism).\n */\nconst POLL_TICK_INTERVAL_SECONDS = Math.max(\n 10,\n Number.parseInt(process.env.OM_HUB_POLL_SCHEDULER_TICK_SECONDS ?? '60', 10) || 60,\n)\n\n/**\n * `scheduled_jobs.id` is a uuid column, so a module-owned schedule's stable\n * registration key must be hashed into a uuid rather than used verbatim \u2014 this\n * keeps `schedulerService.register()` an idempotent upsert across re-runs of\n * seedDefaults instead of trying to insert a raw string into the uuid PK.\n */\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nfunction stablePollTickScheduleId(organizationId: string): string {\n return stableScheduleUuid(`communication_channels:poll-tick:${organizationId}`)\n}\n\nasync function ensureCommunicationChannelSchedules(ctx: {\n container: import('awilix').AwilixContainer\n tenantId: string\n organizationId: string\n}): Promise<void> {\n const cradle = ctx.container as { hasRegistration?: (name: string) => boolean }\n if (typeof cradle.hasRegistration !== 'function' || !cradle.hasRegistration('schedulerService')) return\n\n const schedulerService = ctx.container.resolve('schedulerService') as SchedulerServiceLike\n try {\n await schedulerService.register({\n id: stablePollTickScheduleId(ctx.organizationId),\n name: 'Communication channels poll tick',\n description:\n `Enumerates active polling channels every ${POLL_TICK_INTERVAL_SECONDS}s and enqueues per-channel poll jobs.`,\n scopeType: 'organization',\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n scheduleType: 'interval',\n scheduleValue: `${POLL_TICK_INTERVAL_SECONDS}s`,\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.pollTick,\n targetPayload: {\n scope: { tenantId: ctx.tenantId, organizationId: ctx.organizationId },\n },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n\n await schedulerService.register({\n id: stableScheduleUuid(`communication_channels:gmail-renew-watch:${ctx.organizationId}`),\n name: 'Gmail watch renewal',\n description:\n 'Daily 04:00 UTC. Re-issues gmail.users.watch for channels within OM_PUSH_RENEWAL_GMAIL_LEAD_HOURS of expiry.',\n scopeType: 'organization',\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n scheduleType: 'cron',\n scheduleValue: '0 4 * * *',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: COMMUNICATION_CHANNELS_QUEUES.gmailRenewWatch,\n targetPayload: { scope: { tenantId: ctx.tenantId, organizationId: ctx.organizationId } },\n sourceType: 'module',\n sourceModule: 'communication_channels',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register module schedules', { err: error })\n }\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n admin: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n 'communication_channels.connect_tenant_channel',\n 'communication_channels.admin',\n 'communication_channels.channel.import_history',\n 'communication_channels.channel.push.manage',\n ],\n manager: [\n 'communication_channels.view',\n 'communication_channels.manage',\n 'communication_channels.react',\n 'communication_channels.assign',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n ],\n employee: [\n 'communication_channels.view',\n 'communication_channels.react',\n 'communication_channels.connect_user_channel',\n 'communication_channels.share_own_channel',\n ],\n },\n\n async seedDefaults({ container, organizationId, tenantId }) {\n if (isTestChannelSeedingEnabled() && process.env.SYSTEM_EMAIL_PROVIDER === TEST_SEED_PROVIDER_KEY) {\n const em = (container.resolve('em') as EntityManager).fork()\n const existing = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n tenantId,\n organizationId,\n userId: null,\n deletedAt: null,\n },\n undefined,\n { tenantId, organizationId },\n )\n if (!existing) {\n em.persist(em.create(CommunicationChannel, {\n providerKey: TEST_SEED_PROVIDER_KEY,\n channelType: 'email',\n displayName: 'Test Seed System Email',\n externalIdentifier: TEST_SEED_FROM_ADDRESS,\n userId: null,\n isPrimary: false,\n isActive: true,\n status: 'connected',\n tenantId,\n organizationId,\n }))\n await em.flush()\n }\n\n /**\n * Seeding the channel row without credentials is not a neutral state \u2014 it is a\n * fail-closed one. Once a tenant owns a Hub channel, `resolveTenantCredentials`\n * deliberately refuses to fall back to instance-wide env credentials, so every\n * tenant-scoped send throws `SYSTEM_EMAIL_CREDENTIALS_NOT_CONFIGURED`. Callers that\n * treat a failed send as a failed write (customer invitations roll back and return\n * 502) then fail outright rather than merely losing the email.\n *\n * Seeding credentials alongside the row makes the harness model a tenant that\n * finished configuring its provider, which is also the only one of the three\n * credential cases the integration suite would otherwise never exercise.\n */\n // Best-effort, like the scheduler registration below: credential storage needs the\n // integrations module and a usable encryption key, and neither is guaranteed in every\n // harness. A failure here must not abort tenant initialization for every other module.\n try {\n const credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n const testSeedIntegrationId = `channel_${TEST_SEED_PROVIDER_KEY}`\n const credentialScope = { tenantId, organizationId, userId: null }\n const existingCredentials = await credentialsService.resolve(testSeedIntegrationId, credentialScope)\n if (!existingCredentials) {\n await credentialsService.save(\n testSeedIntegrationId,\n { testSeed: true, fromAddress: TEST_SEED_FROM_ADDRESS },\n credentialScope,\n )\n }\n } catch (error) {\n logger.warn('Test-seed email credentials could not be stored; tenant-scoped sends will fail closed', {\n err: error,\n tenantId,\n organizationId,\n })\n }\n }\n\n /**\n * Register the per-channel polling tick with `@open-mercato/scheduler`.\n *\n * Per email integration spec \u00A7 Hub Deltas \u2192 Delta 6: every\n * `POLL_TICK_INTERVAL_SECONDS` (default 60s), enqueue a single\n * `communication-channels-poll-tick` job that enumerates due channels and\n * fans out to the `communication-channels-poll` queue.\n *\n * The registration is per-organization (one tick row per org/tenant pair)\n * so multi-tenant deploys schedule independently. Skipped silently when the\n * scheduler module isn't enabled \u2014 keeps the hub usable in scheduler-less\n * test harnesses.\n */\n await ensureCommunicationChannelSchedules({ container, tenantId, organizationId })\n },\n\n async onOrganizationCreated({ container, tenantId, organizationId }) {\n await ensureCommunicationChannelSchedules({ container, tenantId, organizationId })\n },\n}\n\nexport default setup\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAE3B,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAE7B,SAAS,4BAA4B;AACrC,SAAS,qCAAqC;AAC9C,SAAS,6BAA6B,8BAA8B;AAEpE,MAAM,SAAS,aAAa,wBAAwB;AAsCpD,MAAM,yBAAyB;AAM/B,MAAM,6BAA6B,KAAK;AAAA,EACtC;AAAA,EACA,OAAO,SAAS,QAAQ,IAAI,sCAAsC,MAAM,EAAE,KAAK;AACjF;AAQA,SAAS,mBAAmB,WAA2B;AACrD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC/D,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC;AAC9G;AAEA,SAAS,yBAAyB,gBAAgC;AAChE,SAAO,mBAAmB,oCAAoC,cAAc,EAAE;AAChF;AAEA,eAAe,oCAAoC,KAIjC;AACh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AuB,eAAe;AACnG,YAAI,CAAC,qBAAqB;AACxB,gBAAM,mBAAmB;AAAA,YACvB;AAAA,YACA,EAAE,UAAU,MAAM,aAAa,uBAAuB;AAAA,YACtD;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,eAAO,KAAK,yFAAyF;AAAA,UACnG,KAAK;AAAA,UACL;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAeA,UAAM,oCAAoC,EAAE,WAAW,UAAU,eAAe,CAAC;AAAA,EACnF;AAAA,EAEA,MAAM,sBAAsB,EAAE,WAAW,UAAU,eAAe,GAAG;AACnE,UAAM,oCAAoC,EAAE,WAAW,UAAU,eAAe,CAAC;AAAA,EACnF;AACF;AAEA,IAAO,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,7 @@
1
1
  import { Resolver, promises as dnsPromises } from "node:dns";
2
2
  import { request as httpsRequest } from "node:https";
3
+ import { resolveSafeHostAddress } from "@open-mercato/shared/lib/host-pinning";
4
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
3
5
  import { setTimeout as delay } from "node:timers/promises";
4
6
  import { runWithCacheTenant } from "@open-mercato/cache";
5
7
  import {
@@ -46,36 +48,60 @@ const defaultDnsResolver = {
46
48
  }
47
49
  };
48
50
  const defaultHealthCheck = (hostname, timeoutMs) => new Promise((resolve) => {
49
- const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? "X-Open-Mercato-Origin").toLowerCase();
50
- const req = httpsRequest(
51
- {
52
- host: hostname,
53
- port: 443,
54
- path: "/api/customer_accounts/domain-check",
55
- method: "GET",
56
- headers: { "X-Domain-Check-Secret": process.env.DOMAIN_CHECK_SECRET ?? "" },
57
- timeout: timeoutMs
58
- },
59
- (res) => {
60
- const headerValue = res.headers[headerName];
61
- const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue;
62
- const originHeaderPresent = typeof originHeader === "string" && originHeader === "1";
63
- const status = res.statusCode ?? 0;
64
- res.resume();
65
- resolve({
66
- ok: status >= 200 && status < 400,
67
- originHeaderPresent,
68
- reason: status >= 200 && status < 400 ? void 0 : `HTTP ${status}`
69
- });
70
- }
71
- );
72
- req.on("timeout", () => {
73
- req.destroy(new Error("TLS health check timed out"));
74
- });
75
- req.on("error", (err) => {
76
- resolve({ ok: false, originHeaderPresent: false, reason: err.message });
51
+ let req;
52
+ let settled = false;
53
+ const failure = { ok: false, originHeaderPresent: false, reason: "TLS health check failed" };
54
+ const finish = (result) => {
55
+ if (settled) return;
56
+ settled = true;
57
+ clearTimeout(deadline);
58
+ resolve(result);
59
+ };
60
+ const deadline = setTimeout(() => {
61
+ finish(failure);
62
+ req?.destroy();
63
+ }, timeoutMs);
64
+ void resolveSafeHostAddress(hostname).then(({ host }) => {
65
+ if (settled) return;
66
+ const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? "X-Open-Mercato-Origin").toLowerCase();
67
+ req = httpsRequest(
68
+ {
69
+ host,
70
+ servername: hostname,
71
+ rejectUnauthorized: true,
72
+ agent: false,
73
+ port: 443,
74
+ path: "/api/customer_accounts/domain-check",
75
+ method: "GET",
76
+ headers: { Host: hostname, "X-Domain-Check-Secret": process.env.DOMAIN_CHECK_SECRET ?? "" },
77
+ timeout: timeoutMs
78
+ },
79
+ (res) => {
80
+ const headerValue = res.headers[headerName];
81
+ const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue;
82
+ const originHeaderPresent = typeof originHeader === "string" && originHeader === "1";
83
+ const status = res.statusCode ?? 0;
84
+ res.resume();
85
+ finish({
86
+ ok: status >= 200 && status < 400,
87
+ originHeaderPresent,
88
+ reason: status >= 200 && status < 400 ? void 0 : `HTTP ${status}`
89
+ });
90
+ }
91
+ );
92
+ req.on("timeout", () => {
93
+ finish(failure);
94
+ req?.destroy();
95
+ });
96
+ req.on("error", () => finish(failure));
97
+ req.end();
98
+ }).catch(() => {
99
+ getTelemetryRuntime()?.reportError(new Error("[internal] Domain TLS health check failed"), {
100
+ module: "customer_accounts",
101
+ code: "customer_accounts.domain_health_check_failed"
102
+ });
103
+ finish(failure);
77
104
  });
78
- req.end();
79
105
  });
80
106
  class DomainMappingService {
81
107
  constructor(em, deps) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/services/domainMappingService.ts"],
4
- "sourcesContent": ["import { Resolver, promises as dnsPromises } from 'node:dns'\nimport { request as httpsRequest } from 'node:https'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport {\n DomainMapping,\n type DomainStatus,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { normalizeHostname, tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { findOrganizationInTenant } from '@open-mercato/core/modules/customer_accounts/lib/organizationLookup'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { detectProxy, isInKnownProxyRange } from '@open-mercato/core/modules/customer_accounts/lib/proxyRanges'\n\nexport class DomainMappingOrgScopeError extends Error {\n constructor(organizationId: string) {\n super(`[internal] organizationId ${organizationId} does not belong to the caller's tenant`)\n this.name = 'DomainMappingOrgScopeError'\n }\n}\n\nconst DOMAIN_ROUTING_TAG = 'domain_routing'\nconst RESOLVE_KEY_PREFIX = 'domain_routing:resolve'\nconst ACTIVE_BY_ORG_KEY_PREFIX = 'domain_routing:active-by-org'\nconst RESOLVE_TTL_MS = 5 * 60_000\nconst TLS_HEALTH_CHECK_TIMEOUT_MS = 10_000\nconst TLS_HEALTH_CHECK_RETRY_DELAYS_MS = [1_000, 4_000, 16_000]\nconst DEFAULT_DNS_RECHECK_THRESHOLD_MS = 5 * 60_000\nconst DEFAULT_TLS_MAX_RETRIES = 6\n\nexport type ResolveResult = {\n domainMappingId: string\n hostname: string\n tenantId: string\n organizationId: string\n orgSlug: string | null\n status: DomainStatus\n}\n\nexport type DnsDiagnostics = {\n expectedCnameTarget: string\n expectedARecordTarget: string | null\n detectedRecords: Array<{ type: 'CNAME' | 'A'; value: string; proxy?: string }>\n reverseResolve?: { attempted: boolean; originHeaderPresent: boolean }\n suggestion: string\n}\n\nexport type VerifyResult = {\n domainMapping: DomainMapping\n diagnostics?: DnsDiagnostics\n}\n\nexport type RegisterInput = {\n hostname: string\n organizationId: string\n tenantId: string\n replacesDomainId?: string\n}\n\ntype CacheService = {\n get(key: string, options?: unknown): Promise<unknown>\n set(key: string, value: unknown, options?: { ttl?: number; tags?: string[] }): Promise<void>\n deleteByTags(tags: string[]): Promise<number>\n}\n\ntype DnsResolverContract = {\n resolveCname(hostname: string): Promise<string[]>\n resolve4(hostname: string): Promise<string[]>\n}\n\ntype HealthCheckContract = (hostname: string, timeoutMs: number) => Promise<{\n ok: boolean\n originHeaderPresent: boolean\n reason?: string\n}>\n\nconst defaultDnsResolver: DnsResolverContract = {\n async resolveCname(hostname) {\n try {\n return await dnsPromises.resolveCname(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n async resolve4(hostname) {\n try {\n return await dnsPromises.resolve4(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n}\n\nconst defaultHealthCheck: HealthCheckContract = (hostname, timeoutMs) =>\n new Promise((resolve) => {\n const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? 'X-Open-Mercato-Origin').toLowerCase()\n const req = httpsRequest(\n {\n host: hostname,\n port: 443,\n path: '/api/customer_accounts/domain-check',\n method: 'GET',\n headers: { 'X-Domain-Check-Secret': process.env.DOMAIN_CHECK_SECRET ?? '' },\n timeout: timeoutMs,\n },\n (res) => {\n const headerValue = res.headers[headerName]\n const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue\n const originHeaderPresent = typeof originHeader === 'string' && originHeader === '1'\n const status = res.statusCode ?? 0\n res.resume() // discard body\n resolve({\n ok: status >= 200 && status < 400,\n originHeaderPresent,\n reason: status >= 200 && status < 400 ? undefined : `HTTP ${status}`,\n })\n },\n )\n req.on('timeout', () => {\n req.destroy(new Error('TLS health check timed out'))\n })\n req.on('error', (err) => {\n resolve({ ok: false, originHeaderPresent: false, reason: (err as Error).message })\n })\n req.end()\n })\n\nexport class DomainMappingService {\n private cache: CacheService | null\n private dns: DnsResolverContract\n private healthCheckImpl: HealthCheckContract\n\n constructor(\n private em: EntityManager,\n deps?: {\n cacheService?: CacheService\n dnsResolver?: DnsResolverContract\n healthCheck?: HealthCheckContract\n },\n ) {\n this.cache = deps?.cacheService ?? null\n this.dns = deps?.dnsResolver ?? defaultDnsResolver\n this.healthCheckImpl = deps?.healthCheck ?? defaultHealthCheck\n }\n\n // -------------------------------------------------------------------------\n // Read paths\n // -------------------------------------------------------------------------\n\n async findById(id: string, scope?: { tenantId?: string }): Promise<DomainMapping | null> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.findOne(DomainMapping, where as never)\n }\n\n async findByOrganization(\n organizationId: string,\n scope?: { tenantId?: string },\n ): Promise<DomainMapping[]> {\n const where: Record<string, unknown> = { organizationId }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.find(DomainMapping, where as never, { orderBy: { createdAt: 'asc' } })\n }\n\n async resolveByHostname(input: string): Promise<ResolveResult | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n\n const cacheKey = `${RESOLVE_KEY_PREFIX}:${hostname}`\n const cache = this.cache\n if (cache) {\n const cached = (await runWithCacheTenant(null, () => cache.get(cacheKey))) as ResolveResult | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const result = await this.lookupResolveResult(hostname)\n if (cache) {\n await runWithCacheTenant(null, () => cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`],\n }))\n }\n return result\n }\n\n async isAllowedForTls(input: string): Promise<{ organizationId: string; status: DomainStatus } | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n const row = await this.em.findOne(DomainMapping, {\n hostname,\n status: { $in: ['active', 'verified'] },\n } as never)\n if (!row) return null\n return { organizationId: row.organizationId, status: row.status }\n }\n\n async resolveActiveByOrg(organizationId: string): Promise<{ hostname: string; status: DomainStatus } | null> {\n const cacheKey = `${ACTIVE_BY_ORG_KEY_PREFIX}:${organizationId}`\n if (this.cache) {\n const cached = (await this.cache.get(cacheKey)) as { hostname: string; status: DomainStatus } | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const row = await this.em.findOne(DomainMapping, {\n organizationId,\n status: 'active',\n } as never)\n const result = row ? { hostname: row.hostname, status: row.status } : null\n\n if (this.cache) {\n await this.cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:org:${organizationId}`],\n })\n }\n return result\n }\n\n async resolveAll(): Promise<ResolveResult[]> {\n const rows = await this.em.find(DomainMapping, { status: 'active' } as never)\n if (rows.length === 0) return []\n const orgIds = Array.from(new Set(rows.map((r) => r.organizationId)))\n const orgs = await this.em.find(Organization, { id: { $in: orgIds } } as never)\n const slugByOrg = new Map<string, string | null>(orgs.map((o) => [o.id, o.slug ?? null]))\n\n return rows.map<ResolveResult>((row) => ({\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: slugByOrg.get(row.organizationId) ?? null,\n status: row.status,\n }))\n }\n\n // -------------------------------------------------------------------------\n // Worker queries\n // -------------------------------------------------------------------------\n\n async findPendingVerification(threshold?: { olderThanMs?: number }): Promise<DomainMapping[]> {\n const olderThan = threshold?.olderThanMs ?? DEFAULT_DNS_RECHECK_THRESHOLD_MS\n const cutoff = new Date(Date.now() - olderThan)\n return this.em.find(\n DomainMapping,\n {\n status: { $in: ['pending', 'dns_failed'] },\n $or: [{ lastDnsCheckAt: null }, { lastDnsCheckAt: { $lt: cutoff } }],\n } as never,\n { orderBy: { lastDnsCheckAt: 'asc' } },\n )\n }\n\n async findPendingTls(options?: { maxRetries?: number; batchSize?: number }): Promise<DomainMapping[]> {\n const maxRetries = options?.maxRetries ?? DEFAULT_TLS_MAX_RETRIES\n const limit = options?.batchSize ?? 50\n return this.em.find(\n DomainMapping,\n {\n $or: [\n { status: 'verified' },\n { status: 'tls_failed', tlsRetryCount: { $lt: maxRetries } },\n ],\n } as never,\n { orderBy: { updatedAt: 'asc' }, limit },\n )\n }\n\n // -------------------------------------------------------------------------\n // Write paths\n // -------------------------------------------------------------------------\n\n async register(input: RegisterInput): Promise<DomainMapping> {\n const hostname = normalizeHostname(input.hostname)\n const organization = await findOrganizationInTenant(this.em, input.organizationId, input.tenantId)\n if (!organization) throw new DomainMappingOrgScopeError(input.organizationId)\n\n let replacesDomain: DomainMapping | null = null\n if (input.replacesDomainId) {\n replacesDomain = await this.em.findOne(DomainMapping, {\n id: input.replacesDomainId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n } as never)\n }\n\n const entity = this.em.create(DomainMapping, {\n hostname,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n replacesDomain: replacesDomain ?? null,\n provider: 'traefik',\n status: 'pending',\n tlsRetryCount: 0,\n createdAt: new Date(),\n } as never)\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.created', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n status: entity.status,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n\n return entity\n }\n\n async verify(id: string): Promise<VerifyResult> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n\n const expectedCname = process.env.CUSTOM_DOMAIN_CNAME_TARGET ?? ''\n const expectedARecord = process.env.CUSTOM_DOMAIN_A_RECORD_TARGET ?? null\n const now = new Date()\n entity.lastDnsCheckAt = now\n\n const verification = await this.runDnsVerification(entity.hostname, {\n expectedCname,\n expectedARecord,\n })\n\n if (verification.ok) {\n entity.status = 'verified'\n entity.verifiedAt = now\n entity.dnsFailureReason = null\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.verified', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity }\n }\n\n entity.status = 'dns_failed'\n entity.dnsFailureReason = verification.reason\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.dns_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: verification.reason,\n detectedRecords: verification.diagnostics.detectedRecords,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity, diagnostics: verification.diagnostics }\n }\n\n async activate(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot transition to active from ${entity.status}`)\n }\n\n entity.status = 'active'\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.activated', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n\n if (entity.replacesDomain) {\n const replaced = await this.em.findOne(DomainMapping, {\n id: (entity.replacesDomain as unknown as { id: string }).id,\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n } as never)\n if (replaced) {\n const replacedHostname = replaced.hostname\n const replacedOrg = replaced.organizationId\n this.em.remove(replaced)\n await this.em.flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.replaced', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n replacedDomainId: replaced.id,\n replacedHostname,\n } as never)\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id: replaced.id,\n hostname: replacedHostname,\n organizationId: replacedOrg,\n tenantId: replaced.tenantId,\n } as never)\n await this.invalidateCacheFor(replacedHostname, replacedOrg)\n }\n }\n\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n async remove(id: string, scope?: { tenantId?: string }): Promise<void> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n const entity = await this.em.findOne(DomainMapping, where as never)\n if (!entity) return\n\n const hostname = entity.hostname\n const organizationId = entity.organizationId\n const tenantId = entity.tenantId\n\n this.em.remove(entity)\n await this.em.flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id,\n hostname,\n organizationId,\n tenantId,\n } as never)\n await this.invalidateCacheFor(hostname, organizationId)\n }\n\n async healthCheck(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot run health check from status ${entity.status}`)\n }\n\n let lastReason: string | null = null\n for (let attempt = 0; attempt < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length; attempt++) {\n const result = await this.healthCheckImpl(entity.hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (result.ok) {\n return this.activate(entity.id)\n }\n lastReason = result.reason ?? 'TLS health check failed'\n if (attempt + 1 < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length) {\n await delay(TLS_HEALTH_CHECK_RETRY_DELAYS_MS[attempt])\n }\n }\n\n entity.status = 'tls_failed'\n entity.tlsFailureReason = lastReason ?? 'TLS health check failed'\n entity.tlsRetryCount = (entity.tlsRetryCount ?? 0) + 1\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.tls_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: entity.tlsFailureReason,\n retryCount: entity.tlsRetryCount,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async lookupResolveResult(hostname: string): Promise<ResolveResult | null> {\n const row = await this.em.findOne(DomainMapping, { hostname, status: 'active' } as never)\n if (!row) return null\n const org = await this.em.findOne(Organization, { id: row.organizationId } as never)\n return {\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: org?.slug ?? null,\n status: row.status,\n }\n }\n\n private async invalidateCacheFor(hostname: string, organizationId: string | null): Promise<void> {\n const cache = this.cache\n if (!cache) return\n const tags = [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`]\n if (organizationId) tags.push(`${DOMAIN_ROUTING_TAG}:org:${organizationId}`)\n await Promise.allSettled([\n cache.deleteByTags(tags),\n runWithCacheTenant(null, () => cache.deleteByTags([`${DOMAIN_ROUTING_TAG}:${hostname}`])),\n ])\n }\n\n private async runDnsVerification(\n hostname: string,\n expected: { expectedCname: string; expectedARecord: string | null },\n ): Promise<\n | {\n ok: true\n method: 'cname' | 'a-record' | 'reverse-resolve'\n diagnostics: DnsDiagnostics\n }\n | { ok: false; reason: string; diagnostics: DnsDiagnostics }\n > {\n const detectedRecords: DnsDiagnostics['detectedRecords'] = []\n const baseDiag = (overrides?: Partial<DnsDiagnostics>): DnsDiagnostics => ({\n expectedCnameTarget: expected.expectedCname,\n expectedARecordTarget: expected.expectedARecord,\n detectedRecords,\n suggestion: overrides?.suggestion ?? '',\n reverseResolve: overrides?.reverseResolve,\n })\n\n // Phase 1: CNAME\n let cnameRecords: string[] = []\n try {\n cnameRecords = await this.dns.resolveCname(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (CNAME): ${(err as Error).message}`,\n diagnostics: baseDiag({\n suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.',\n }),\n }\n }\n for (const cname of cnameRecords) detectedRecords.push({ type: 'CNAME', value: cname })\n\n if (expected.expectedCname && cnameRecords.length > 0) {\n const expectedCname = tryNormalizeHostname(expected.expectedCname) ?? expected.expectedCname.toLowerCase()\n const match = cnameRecords.some((c) => (tryNormalizeHostname(c) ?? c.toLowerCase()) === expectedCname)\n if (match) {\n return {\n ok: true,\n method: 'cname',\n diagnostics: baseDiag({\n suggestion: 'CNAME record matches the expected target.',\n }),\n }\n }\n return {\n ok: false,\n reason: `CNAME points to ${cnameRecords.join(', ')} instead of ${expected.expectedCname}`,\n diagnostics: baseDiag({\n suggestion: `Update your CNAME record to point to ${expected.expectedCname}.`,\n }),\n }\n }\n\n // Phase 2: A record\n let aRecords: string[] = []\n try {\n aRecords = await this.dns.resolve4(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (A): ${(err as Error).message}`,\n diagnostics: baseDiag({ suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.' }),\n }\n }\n for (const a of aRecords) {\n const proxy = detectProxy(a)\n detectedRecords.push({ type: 'A', value: a, ...(proxy ? { proxy } : {}) })\n }\n\n if (aRecords.length === 0) {\n return {\n ok: false,\n reason: `No CNAME or A record found for ${hostname}`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `For a subdomain, add a CNAME record pointing to ${expected.expectedCname}. For an apex domain, add an A record pointing to ${expected.expectedARecord}. DNS propagation can take up to 48 hours.`\n : `Add a CNAME record pointing to ${expected.expectedCname}. DNS propagation can take up to 48 hours.`,\n }),\n }\n }\n\n if (expected.expectedARecord && aRecords.includes(expected.expectedARecord)) {\n return {\n ok: true,\n method: 'a-record',\n diagnostics: baseDiag({ suggestion: 'A record matches the expected target.' }),\n }\n }\n\n // Phase 3: reverse-resolve through proxy\n const proxiedRecords = aRecords.filter((ip) => isInKnownProxyRange(ip))\n if (proxiedRecords.length > 0) {\n const probe = await this.healthCheckImpl(hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (probe.ok && probe.originHeaderPresent) {\n return {\n ok: true,\n method: 'reverse-resolve',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: true },\n suggestion: 'Domain is proxied \u2014 reverse-resolve confirmed traffic reaches our origin.',\n }),\n }\n }\n return {\n ok: false,\n reason: 'A record points to a known proxy IP, but reverse-resolve over HTTPS did not reach our server',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: false },\n suggestion: expected.expectedCname\n ? `Your DNS uses a proxy. Either disable the proxy and add a CNAME \u2192 ${expected.expectedCname}, or configure your proxy to forward traffic to ${expected.expectedCname}.`\n : 'Disable the DNS proxy or configure it to forward traffic to our platform.',\n }),\n }\n }\n\n return {\n ok: false,\n reason: expected.expectedARecord\n ? `A record points to ${aRecords.join(', ')} instead of ${expected.expectedARecord}`\n : `A record points to ${aRecords.join(', ')} but apex-domain registration is not enabled on this deployment`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `Update your A record to point to ${expected.expectedARecord}.`\n : `Apex-domain registration is not enabled on this deployment. Use a subdomain (e.g., shop.${hostname}) and add a CNAME pointing to ${expected.expectedCname}.`,\n }),\n }\n }\n}\n\n// Re-exported for tests; allow injection of fakes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,SAAS,EAAE,YAAY,wCAAwC,CAAC;AAAA,MAC/E;AAAA,IACF;AAGA,UAAM,iBAAiB,SAAS,OAAO,CAAC,OAAO,oBAAoB,EAAE,CAAC;AACtE,QAAI,eAAe,SAAS,GAAG;AAC7B,YAAM,QAAQ,MAAM,KAAK,gBAAgB,UAAU,2BAA2B;AAC9E,UAAI,MAAM,MAAM,MAAM,qBAAqB;AACzC,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,QAAQ;AAAA,UACR,aAAa,SAAS;AAAA,YACpB,gBAAgB,EAAE,WAAW,MAAM,qBAAqB,KAAK;AAAA,YAC7D,YAAY;AAAA,UACd,CAAC;AAAA,QACH;AAAA,MACF;AACA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ;AAAA,QACR,aAAa,SAAS;AAAA,UACpB,gBAAgB,EAAE,WAAW,MAAM,qBAAqB,MAAM;AAAA,UAC9D,YAAY,SAAS,gBACjB,0EAAqE,SAAS,aAAa,mDAAmD,SAAS,aAAa,MACpK;AAAA,QACN,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,SAAS,kBACb,sBAAsB,SAAS,KAAK,IAAI,CAAC,eAAe,SAAS,eAAe,KAChF,sBAAsB,SAAS,KAAK,IAAI,CAAC;AAAA,MAC7C,aAAa,SAAS;AAAA,QACpB,YAAY,SAAS,kBACjB,oCAAoC,SAAS,eAAe,MAC5D,2FAA2F,QAAQ,iCAAiC,SAAS,aAAa;AAAA,MAChK,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAGO,MAAM,cAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
4
+ "sourcesContent": ["import { Resolver, promises as dnsPromises } from 'node:dns'\nimport { request as httpsRequest } from 'node:https'\nimport type { ClientRequest } from 'node:http'\nimport { resolveSafeHostAddress } from '@open-mercato/shared/lib/host-pinning'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { setTimeout as delay } from 'node:timers/promises'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport {\n DomainMapping,\n type DomainStatus,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { normalizeHostname, tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { findOrganizationInTenant } from '@open-mercato/core/modules/customer_accounts/lib/organizationLookup'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { detectProxy, isInKnownProxyRange } from '@open-mercato/core/modules/customer_accounts/lib/proxyRanges'\n\nexport class DomainMappingOrgScopeError extends Error {\n constructor(organizationId: string) {\n super(`[internal] organizationId ${organizationId} does not belong to the caller's tenant`)\n this.name = 'DomainMappingOrgScopeError'\n }\n}\n\nconst DOMAIN_ROUTING_TAG = 'domain_routing'\nconst RESOLVE_KEY_PREFIX = 'domain_routing:resolve'\nconst ACTIVE_BY_ORG_KEY_PREFIX = 'domain_routing:active-by-org'\nconst RESOLVE_TTL_MS = 5 * 60_000\nconst TLS_HEALTH_CHECK_TIMEOUT_MS = 10_000\nconst TLS_HEALTH_CHECK_RETRY_DELAYS_MS = [1_000, 4_000, 16_000]\nconst DEFAULT_DNS_RECHECK_THRESHOLD_MS = 5 * 60_000\nconst DEFAULT_TLS_MAX_RETRIES = 6\n\nexport type ResolveResult = {\n domainMappingId: string\n hostname: string\n tenantId: string\n organizationId: string\n orgSlug: string | null\n status: DomainStatus\n}\n\nexport type DnsDiagnostics = {\n expectedCnameTarget: string\n expectedARecordTarget: string | null\n detectedRecords: Array<{ type: 'CNAME' | 'A'; value: string; proxy?: string }>\n reverseResolve?: { attempted: boolean; originHeaderPresent: boolean }\n suggestion: string\n}\n\nexport type VerifyResult = {\n domainMapping: DomainMapping\n diagnostics?: DnsDiagnostics\n}\n\nexport type RegisterInput = {\n hostname: string\n organizationId: string\n tenantId: string\n replacesDomainId?: string\n}\n\ntype CacheService = {\n get(key: string, options?: unknown): Promise<unknown>\n set(key: string, value: unknown, options?: { ttl?: number; tags?: string[] }): Promise<void>\n deleteByTags(tags: string[]): Promise<number>\n}\n\ntype DnsResolverContract = {\n resolveCname(hostname: string): Promise<string[]>\n resolve4(hostname: string): Promise<string[]>\n}\n\ntype HealthCheckContract = (hostname: string, timeoutMs: number) => Promise<{\n ok: boolean\n originHeaderPresent: boolean\n reason?: string\n}>\n\nconst defaultDnsResolver: DnsResolverContract = {\n async resolveCname(hostname) {\n try {\n return await dnsPromises.resolveCname(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n async resolve4(hostname) {\n try {\n return await dnsPromises.resolve4(hostname)\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENODATA' || code === 'ENOTFOUND') return []\n throw err\n }\n },\n}\n\nconst defaultHealthCheck: HealthCheckContract = (hostname, timeoutMs) =>\n new Promise((resolve) => {\n let req: ClientRequest | undefined\n let settled = false\n const failure = { ok: false, originHeaderPresent: false, reason: 'TLS health check failed' }\n const finish = (result: Awaited<ReturnType<HealthCheckContract>>) => {\n if (settled) return\n settled = true\n clearTimeout(deadline)\n resolve(result)\n }\n const deadline = setTimeout(() => {\n finish(failure)\n req?.destroy()\n }, timeoutMs)\n\n void resolveSafeHostAddress(hostname).then(({ host }) => {\n if (settled) return\n const headerName = (process.env.CUSTOMER_DOMAIN_ORIGIN_HEADER ?? 'X-Open-Mercato-Origin').toLowerCase()\n req = httpsRequest(\n {\n host,\n servername: hostname,\n rejectUnauthorized: true,\n agent: false,\n port: 443,\n path: '/api/customer_accounts/domain-check',\n method: 'GET',\n headers: { Host: hostname, 'X-Domain-Check-Secret': process.env.DOMAIN_CHECK_SECRET ?? '' },\n timeout: timeoutMs,\n },\n (res) => {\n const headerValue = res.headers[headerName]\n const originHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue\n const originHeaderPresent = typeof originHeader === 'string' && originHeader === '1'\n const status = res.statusCode ?? 0\n res.resume()\n finish({\n ok: status >= 200 && status < 400,\n originHeaderPresent,\n reason: status >= 200 && status < 400 ? undefined : `HTTP ${status}`,\n })\n },\n )\n req.on('timeout', () => {\n finish(failure)\n req?.destroy()\n })\n req.on('error', () => finish(failure))\n req.end()\n }).catch(() => {\n getTelemetryRuntime()?.reportError(new Error('[internal] Domain TLS health check failed'), {\n module: 'customer_accounts',\n code: 'customer_accounts.domain_health_check_failed',\n })\n finish(failure)\n })\n })\n\nexport class DomainMappingService {\n private cache: CacheService | null\n private dns: DnsResolverContract\n private healthCheckImpl: HealthCheckContract\n\n constructor(\n private em: EntityManager,\n deps?: {\n cacheService?: CacheService\n dnsResolver?: DnsResolverContract\n healthCheck?: HealthCheckContract\n },\n ) {\n this.cache = deps?.cacheService ?? null\n this.dns = deps?.dnsResolver ?? defaultDnsResolver\n this.healthCheckImpl = deps?.healthCheck ?? defaultHealthCheck\n }\n\n // -------------------------------------------------------------------------\n // Read paths\n // -------------------------------------------------------------------------\n\n async findById(id: string, scope?: { tenantId?: string }): Promise<DomainMapping | null> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.findOne(DomainMapping, where as never)\n }\n\n async findByOrganization(\n organizationId: string,\n scope?: { tenantId?: string },\n ): Promise<DomainMapping[]> {\n const where: Record<string, unknown> = { organizationId }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n return this.em.find(DomainMapping, where as never, { orderBy: { createdAt: 'asc' } })\n }\n\n async resolveByHostname(input: string): Promise<ResolveResult | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n\n const cacheKey = `${RESOLVE_KEY_PREFIX}:${hostname}`\n const cache = this.cache\n if (cache) {\n const cached = (await runWithCacheTenant(null, () => cache.get(cacheKey))) as ResolveResult | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const result = await this.lookupResolveResult(hostname)\n if (cache) {\n await runWithCacheTenant(null, () => cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`],\n }))\n }\n return result\n }\n\n async isAllowedForTls(input: string): Promise<{ organizationId: string; status: DomainStatus } | null> {\n const hostname = tryNormalizeHostname(input)\n if (!hostname) return null\n if (platformDomains().includes(hostname)) return null\n const row = await this.em.findOne(DomainMapping, {\n hostname,\n status: { $in: ['active', 'verified'] },\n } as never)\n if (!row) return null\n return { organizationId: row.organizationId, status: row.status }\n }\n\n async resolveActiveByOrg(organizationId: string): Promise<{ hostname: string; status: DomainStatus } | null> {\n const cacheKey = `${ACTIVE_BY_ORG_KEY_PREFIX}:${organizationId}`\n if (this.cache) {\n const cached = (await this.cache.get(cacheKey)) as { hostname: string; status: DomainStatus } | null | undefined\n if (cached !== undefined && cached !== null) return cached\n }\n\n const row = await this.em.findOne(DomainMapping, {\n organizationId,\n status: 'active',\n } as never)\n const result = row ? { hostname: row.hostname, status: row.status } : null\n\n if (this.cache) {\n await this.cache.set(cacheKey, result, {\n ttl: RESOLVE_TTL_MS,\n tags: [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:org:${organizationId}`],\n })\n }\n return result\n }\n\n async resolveAll(): Promise<ResolveResult[]> {\n const rows = await this.em.find(DomainMapping, { status: 'active' } as never)\n if (rows.length === 0) return []\n const orgIds = Array.from(new Set(rows.map((r) => r.organizationId)))\n const orgs = await this.em.find(Organization, { id: { $in: orgIds } } as never)\n const slugByOrg = new Map<string, string | null>(orgs.map((o) => [o.id, o.slug ?? null]))\n\n return rows.map<ResolveResult>((row) => ({\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: slugByOrg.get(row.organizationId) ?? null,\n status: row.status,\n }))\n }\n\n // -------------------------------------------------------------------------\n // Worker queries\n // -------------------------------------------------------------------------\n\n async findPendingVerification(threshold?: { olderThanMs?: number }): Promise<DomainMapping[]> {\n const olderThan = threshold?.olderThanMs ?? DEFAULT_DNS_RECHECK_THRESHOLD_MS\n const cutoff = new Date(Date.now() - olderThan)\n return this.em.find(\n DomainMapping,\n {\n status: { $in: ['pending', 'dns_failed'] },\n $or: [{ lastDnsCheckAt: null }, { lastDnsCheckAt: { $lt: cutoff } }],\n } as never,\n { orderBy: { lastDnsCheckAt: 'asc' } },\n )\n }\n\n async findPendingTls(options?: { maxRetries?: number; batchSize?: number }): Promise<DomainMapping[]> {\n const maxRetries = options?.maxRetries ?? DEFAULT_TLS_MAX_RETRIES\n const limit = options?.batchSize ?? 50\n return this.em.find(\n DomainMapping,\n {\n $or: [\n { status: 'verified' },\n { status: 'tls_failed', tlsRetryCount: { $lt: maxRetries } },\n ],\n } as never,\n { orderBy: { updatedAt: 'asc' }, limit },\n )\n }\n\n // -------------------------------------------------------------------------\n // Write paths\n // -------------------------------------------------------------------------\n\n async register(input: RegisterInput): Promise<DomainMapping> {\n const hostname = normalizeHostname(input.hostname)\n const organization = await findOrganizationInTenant(this.em, input.organizationId, input.tenantId)\n if (!organization) throw new DomainMappingOrgScopeError(input.organizationId)\n\n let replacesDomain: DomainMapping | null = null\n if (input.replacesDomainId) {\n replacesDomain = await this.em.findOne(DomainMapping, {\n id: input.replacesDomainId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n } as never)\n }\n\n const entity = this.em.create(DomainMapping, {\n hostname,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n replacesDomain: replacesDomain ?? null,\n provider: 'traefik',\n status: 'pending',\n tlsRetryCount: 0,\n createdAt: new Date(),\n } as never)\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.created', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n status: entity.status,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n\n return entity\n }\n\n async verify(id: string): Promise<VerifyResult> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n\n const expectedCname = process.env.CUSTOM_DOMAIN_CNAME_TARGET ?? ''\n const expectedARecord = process.env.CUSTOM_DOMAIN_A_RECORD_TARGET ?? null\n const now = new Date()\n entity.lastDnsCheckAt = now\n\n const verification = await this.runDnsVerification(entity.hostname, {\n expectedCname,\n expectedARecord,\n })\n\n if (verification.ok) {\n entity.status = 'verified'\n entity.verifiedAt = now\n entity.dnsFailureReason = null\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.verified', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity }\n }\n\n entity.status = 'dns_failed'\n entity.dnsFailureReason = verification.reason\n await this.em.persist(entity).flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.dns_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: verification.reason,\n detectedRecords: verification.diagnostics.detectedRecords,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return { domainMapping: entity, diagnostics: verification.diagnostics }\n }\n\n async activate(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot transition to active from ${entity.status}`)\n }\n\n entity.status = 'active'\n entity.tlsRetryCount = 0\n entity.tlsFailureReason = null\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.activated', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n } as never)\n\n if (entity.replacesDomain) {\n const replaced = await this.em.findOne(DomainMapping, {\n id: (entity.replacesDomain as unknown as { id: string }).id,\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n } as never)\n if (replaced) {\n const replacedHostname = replaced.hostname\n const replacedOrg = replaced.organizationId\n this.em.remove(replaced)\n await this.em.flush()\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.replaced', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n replacedDomainId: replaced.id,\n replacedHostname,\n } as never)\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id: replaced.id,\n hostname: replacedHostname,\n organizationId: replacedOrg,\n tenantId: replaced.tenantId,\n } as never)\n await this.invalidateCacheFor(replacedHostname, replacedOrg)\n }\n }\n\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n async remove(id: string, scope?: { tenantId?: string }): Promise<void> {\n const where: Record<string, unknown> = { id }\n if (scope?.tenantId) where.tenantId = scope.tenantId\n const entity = await this.em.findOne(DomainMapping, where as never)\n if (!entity) return\n\n const hostname = entity.hostname\n const organizationId = entity.organizationId\n const tenantId = entity.tenantId\n\n this.em.remove(entity)\n await this.em.flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.deleted', {\n id,\n hostname,\n organizationId,\n tenantId,\n } as never)\n await this.invalidateCacheFor(hostname, organizationId)\n }\n\n async healthCheck(id: string): Promise<DomainMapping> {\n const entity = await this.em.findOne(DomainMapping, { id } as never)\n if (!entity) throw new Error(`DomainMapping ${id} not found`)\n if (entity.status === 'active') return entity\n if (entity.status !== 'verified' && entity.status !== 'tls_failed') {\n throw new Error(`DomainMapping ${id} cannot run health check from status ${entity.status}`)\n }\n\n let lastReason: string | null = null\n for (let attempt = 0; attempt < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length; attempt++) {\n const result = await this.healthCheckImpl(entity.hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (result.ok) {\n return this.activate(entity.id)\n }\n lastReason = result.reason ?? 'TLS health check failed'\n if (attempt + 1 < TLS_HEALTH_CHECK_RETRY_DELAYS_MS.length) {\n await delay(TLS_HEALTH_CHECK_RETRY_DELAYS_MS[attempt])\n }\n }\n\n entity.status = 'tls_failed'\n entity.tlsFailureReason = lastReason ?? 'TLS health check failed'\n entity.tlsRetryCount = (entity.tlsRetryCount ?? 0) + 1\n await this.em.persist(entity).flush()\n\n await emitCustomerAccountsEvent('customer_accounts.domain_mapping.tls_failed', {\n id: entity.id,\n hostname: entity.hostname,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n reason: entity.tlsFailureReason,\n retryCount: entity.tlsRetryCount,\n } as never)\n await this.invalidateCacheFor(entity.hostname, entity.organizationId)\n return entity\n }\n\n // -------------------------------------------------------------------------\n // Internals\n // -------------------------------------------------------------------------\n\n private async lookupResolveResult(hostname: string): Promise<ResolveResult | null> {\n const row = await this.em.findOne(DomainMapping, { hostname, status: 'active' } as never)\n if (!row) return null\n const org = await this.em.findOne(Organization, { id: row.organizationId } as never)\n return {\n domainMappingId: row.id,\n hostname: row.hostname,\n tenantId: row.tenantId,\n organizationId: row.organizationId,\n orgSlug: org?.slug ?? null,\n status: row.status,\n }\n }\n\n private async invalidateCacheFor(hostname: string, organizationId: string | null): Promise<void> {\n const cache = this.cache\n if (!cache) return\n const tags = [DOMAIN_ROUTING_TAG, `${DOMAIN_ROUTING_TAG}:${hostname}`]\n if (organizationId) tags.push(`${DOMAIN_ROUTING_TAG}:org:${organizationId}`)\n await Promise.allSettled([\n cache.deleteByTags(tags),\n runWithCacheTenant(null, () => cache.deleteByTags([`${DOMAIN_ROUTING_TAG}:${hostname}`])),\n ])\n }\n\n private async runDnsVerification(\n hostname: string,\n expected: { expectedCname: string; expectedARecord: string | null },\n ): Promise<\n | {\n ok: true\n method: 'cname' | 'a-record' | 'reverse-resolve'\n diagnostics: DnsDiagnostics\n }\n | { ok: false; reason: string; diagnostics: DnsDiagnostics }\n > {\n const detectedRecords: DnsDiagnostics['detectedRecords'] = []\n const baseDiag = (overrides?: Partial<DnsDiagnostics>): DnsDiagnostics => ({\n expectedCnameTarget: expected.expectedCname,\n expectedARecordTarget: expected.expectedARecord,\n detectedRecords,\n suggestion: overrides?.suggestion ?? '',\n reverseResolve: overrides?.reverseResolve,\n })\n\n // Phase 1: CNAME\n let cnameRecords: string[] = []\n try {\n cnameRecords = await this.dns.resolveCname(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (CNAME): ${(err as Error).message}`,\n diagnostics: baseDiag({\n suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.',\n }),\n }\n }\n for (const cname of cnameRecords) detectedRecords.push({ type: 'CNAME', value: cname })\n\n if (expected.expectedCname && cnameRecords.length > 0) {\n const expectedCname = tryNormalizeHostname(expected.expectedCname) ?? expected.expectedCname.toLowerCase()\n const match = cnameRecords.some((c) => (tryNormalizeHostname(c) ?? c.toLowerCase()) === expectedCname)\n if (match) {\n return {\n ok: true,\n method: 'cname',\n diagnostics: baseDiag({\n suggestion: 'CNAME record matches the expected target.',\n }),\n }\n }\n return {\n ok: false,\n reason: `CNAME points to ${cnameRecords.join(', ')} instead of ${expected.expectedCname}`,\n diagnostics: baseDiag({\n suggestion: `Update your CNAME record to point to ${expected.expectedCname}.`,\n }),\n }\n }\n\n // Phase 2: A record\n let aRecords: string[] = []\n try {\n aRecords = await this.dns.resolve4(hostname)\n } catch (err) {\n return {\n ok: false,\n reason: `DNS lookup error (A): ${(err as Error).message}`,\n diagnostics: baseDiag({ suggestion: 'DNS lookup failed unexpectedly. Try again in a few minutes.' }),\n }\n }\n for (const a of aRecords) {\n const proxy = detectProxy(a)\n detectedRecords.push({ type: 'A', value: a, ...(proxy ? { proxy } : {}) })\n }\n\n if (aRecords.length === 0) {\n return {\n ok: false,\n reason: `No CNAME or A record found for ${hostname}`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `For a subdomain, add a CNAME record pointing to ${expected.expectedCname}. For an apex domain, add an A record pointing to ${expected.expectedARecord}. DNS propagation can take up to 48 hours.`\n : `Add a CNAME record pointing to ${expected.expectedCname}. DNS propagation can take up to 48 hours.`,\n }),\n }\n }\n\n if (expected.expectedARecord && aRecords.includes(expected.expectedARecord)) {\n return {\n ok: true,\n method: 'a-record',\n diagnostics: baseDiag({ suggestion: 'A record matches the expected target.' }),\n }\n }\n\n // Phase 3: reverse-resolve through proxy\n const proxiedRecords = aRecords.filter((ip) => isInKnownProxyRange(ip))\n if (proxiedRecords.length > 0) {\n const probe = await this.healthCheckImpl(hostname, TLS_HEALTH_CHECK_TIMEOUT_MS)\n if (probe.ok && probe.originHeaderPresent) {\n return {\n ok: true,\n method: 'reverse-resolve',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: true },\n suggestion: 'Domain is proxied \u2014 reverse-resolve confirmed traffic reaches our origin.',\n }),\n }\n }\n return {\n ok: false,\n reason: 'A record points to a known proxy IP, but reverse-resolve over HTTPS did not reach our server',\n diagnostics: baseDiag({\n reverseResolve: { attempted: true, originHeaderPresent: false },\n suggestion: expected.expectedCname\n ? `Your DNS uses a proxy. Either disable the proxy and add a CNAME \u2192 ${expected.expectedCname}, or configure your proxy to forward traffic to ${expected.expectedCname}.`\n : 'Disable the DNS proxy or configure it to forward traffic to our platform.',\n }),\n }\n }\n\n return {\n ok: false,\n reason: expected.expectedARecord\n ? `A record points to ${aRecords.join(', ')} instead of ${expected.expectedARecord}`\n : `A record points to ${aRecords.join(', ')} but apex-domain registration is not enabled on this deployment`,\n diagnostics: baseDiag({\n suggestion: expected.expectedARecord\n ? `Update your A record to point to ${expected.expectedARecord}.`\n : `Apex-domain registration is not enabled on this deployment. Use a subdomain (e.g., shop.${hostname}) and add a CNAME pointing to ${expected.expectedCname}.`,\n }),\n }\n }\n}\n\n// Re-exported for tests; allow injection of fakes.\nexport const __testing__ = {\n DEFAULT_DNS_RECHECK_THRESHOLD_MS,\n DEFAULT_TLS_MAX_RETRIES,\n TLS_HEALTH_CHECK_RETRY_DELAYS_MS,\n RESOLVE_TTL_MS,\n DOMAIN_ROUTING_TAG,\n defaultHealthCheck,\n defaultDnsResolver,\n Resolver,\n}\n"],
5
+ "mappings": "AAAA,SAAS,UAAU,YAAY,mBAAmB;AAClD,SAAS,WAAW,oBAAoB;AAExC,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,cAAc,aAAa;AAEpC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,mBAAmB,4BAA4B;AACxD,SAAS,gCAAgC;AACzC,SAAS,uBAAuB;AAChC,SAAS,aAAa,2BAA2B;AAE1C,MAAM,mCAAmC,MAAM;AAAA,EACpD,YAAY,gBAAwB;AAClC,UAAM,6BAA6B,cAAc,yCAAyC;AAC1F,SAAK,OAAO;AAAA,EACd;AACF;AAEA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,2BAA2B;AACjC,MAAM,iBAAiB,IAAI;AAC3B,MAAM,8BAA8B;AACpC,MAAM,mCAAmC,CAAC,KAAO,KAAO,IAAM;AAC9D,MAAM,mCAAmC,IAAI;AAC7C,MAAM,0BAA0B;AAgDhC,MAAM,qBAA0C;AAAA,EAC9C,MAAM,aAAa,UAAU;AAC3B,QAAI;AACF,aAAO,MAAM,YAAY,aAAa,QAAQ;AAAA,IAChD,SAAS,KAAK;AACZ,YAAM,OAAQ,IAA8B;AAC5C,UAAI,SAAS,aAAa,SAAS,YAAa,QAAO,CAAC;AACxD,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EACA,MAAM,SAAS,UAAU;AACvB,QA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AS,gBACjB,0EAAqE,SAAS,aAAa,mDAAmD,SAAS,aAAa,MACpK;AAAA,QACN,CAAC;AAAA,MACH;AAAA,IACF;AAEA,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,QAAQ,SAAS,kBACb,sBAAsB,SAAS,KAAK,IAAI,CAAC,eAAe,SAAS,eAAe,KAChF,sBAAsB,SAAS,KAAK,IAAI,CAAC;AAAA,MAC7C,aAAa,SAAS;AAAA,QACpB,YAAY,SAAS,kBACjB,oCAAoC,SAAS,eAAe,MAC5D,2FAA2F,QAAQ,iCAAiC,SAAS,aAAa;AAAA,MAChK,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAGO,MAAM,cAAc;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
6
  "names": []
7
7
  }
@@ -60,8 +60,12 @@ function sortTimelineActivities(items) {
60
60
  if (leftScheduled === rightScheduled) return left.id.localeCompare(right.id);
61
61
  return leftScheduled - rightScheduled;
62
62
  }
63
- const leftTime = left.occurredAt ?? left.createdAt;
64
- const rightTime = right.occurredAt ?? right.createdAt;
63
+ const leftTime = left.occurredAt ?? left.scheduledAt ?? null;
64
+ const rightTime = right.occurredAt ?? right.scheduledAt ?? null;
65
+ if (!leftTime || !rightTime) {
66
+ if (leftTime !== rightTime) return leftTime ? -1 : 1;
67
+ return right.id.localeCompare(left.id);
68
+ }
65
69
  const compare = rightTime.localeCompare(leftTime);
66
70
  if (compare !== 0) return compare;
67
71
  return right.id.localeCompare(left.id);
@@ -185,7 +189,8 @@ function ActivitiesSection({
185
189
  }
186
190
  const legacyFiltered = legacyItems.filter((entry) => {
187
191
  if (filterTypes.length > 0 && !filterTypes.includes(entry.interactionType)) return false;
188
- const dateOnly = toDateOnly(entry.occurredAt ?? entry.createdAt);
192
+ const dateOnly = toDateOnly(entry.occurredAt ?? entry.scheduledAt);
193
+ if ((filterDateFrom || filterDateTo) && !dateOnly) return false;
189
194
  if (filterDateFrom && dateOnly < filterDateFrom) return false;
190
195
  if (filterDateTo && dateOnly > filterDateTo) return false;
191
196
  return true;