@open-mercato/core 0.11.1-develop.8541.1.955f210e1d → 0.11.1-develop.8549.1.bd34c91190

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 (121) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js +10 -30
  3. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js.map +2 -2
  4. package/dist/modules/customer_accounts/api/admin/users/[id].js +10 -9
  5. package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
  6. package/dist/modules/customer_accounts/api/email/verify.js +11 -10
  7. package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
  8. package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
  9. package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
  10. package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
  11. package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
  12. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js +3 -2
  13. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js.map +2 -2
  14. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js +3 -2
  15. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js.map +2 -2
  16. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js +4 -0
  17. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js.map +2 -2
  18. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js +4 -0
  19. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js.map +2 -2
  20. package/dist/modules/customer_accounts/api/portal/notifications.js +4 -0
  21. package/dist/modules/customer_accounts/api/portal/notifications.js.map +2 -2
  22. package/dist/modules/customer_accounts/api/signup.js +33 -19
  23. package/dist/modules/customer_accounts/api/signup.js.map +3 -3
  24. package/dist/modules/customer_accounts/data/validators.js +3 -2
  25. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  26. package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
  27. package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
  28. package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
  29. package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
  30. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +12 -1
  31. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +2 -2
  32. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js +8 -0
  33. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js.map +7 -0
  34. package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
  35. package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
  36. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js +9 -0
  37. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js.map +7 -0
  38. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
  39. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
  40. package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
  41. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  42. package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
  43. package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
  44. package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
  45. package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
  46. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
  47. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
  48. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
  49. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
  50. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
  51. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  52. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
  53. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
  54. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
  55. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
  56. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
  57. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  58. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
  59. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  60. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
  61. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
  62. package/dist/modules/wms/index.js +1 -1
  63. package/dist/modules/wms/index.js.map +2 -2
  64. package/dist/modules/wms/setup.js +4 -1
  65. package/dist/modules/wms/setup.js.map +2 -2
  66. package/dist/modules/workflows/api/events/route.js +1 -1
  67. package/dist/modules/workflows/api/events/route.js.map +2 -2
  68. package/dist/modules/workflows/api/instances/[id]/events/route.js +1 -1
  69. package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
  70. package/dist/modules/workflows/api/instances/[id]/steps/route.js +1 -1
  71. package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +2 -2
  72. package/dist/modules/workflows/api/instances/failure-queue/route.js +1 -1
  73. package/dist/modules/workflows/api/instances/failure-queue/route.js.map +2 -2
  74. package/dist/modules/workflows/lib/event-logger.js +1 -1
  75. package/dist/modules/workflows/lib/event-logger.js.map +2 -2
  76. package/dist/modules/workflows/lib/work-inbox/user-task-source.js +1 -1
  77. package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +2 -2
  78. package/package.json +7 -7
  79. package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
  80. package/src/modules/customer_accounts/api/admin/users/[id].ts +10 -9
  81. package/src/modules/customer_accounts/api/email/verify.ts +15 -11
  82. package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
  83. package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
  84. package/src/modules/customer_accounts/api/portal/notifications/[id]/dismiss.ts +8 -5
  85. package/src/modules/customer_accounts/api/portal/notifications/[id]/read.ts +8 -5
  86. package/src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts +4 -0
  87. package/src/modules/customer_accounts/api/portal/notifications/unread-count.ts +4 -0
  88. package/src/modules/customer_accounts/api/portal/notifications.ts +4 -0
  89. package/src/modules/customer_accounts/api/signup.ts +36 -24
  90. package/src/modules/customer_accounts/data/validators.ts +2 -1
  91. package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
  92. package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
  93. package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +13 -1
  94. package/src/modules/customer_accounts/lib/moduleEntityRegistration.ts +12 -0
  95. package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
  96. package/src/modules/customer_accounts/lib/portalNotificationsAvailability.ts +7 -0
  97. package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
  98. package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
  99. package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
  100. package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
  101. package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
  102. package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
  103. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
  104. package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
  105. package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
  106. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
  107. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
  108. package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
  109. package/src/modules/portal/i18n/de.json +2 -1
  110. package/src/modules/portal/i18n/en.json +2 -1
  111. package/src/modules/portal/i18n/es.json +2 -1
  112. package/src/modules/portal/i18n/ko.json +2 -1
  113. package/src/modules/portal/i18n/pl.json +2 -1
  114. package/src/modules/wms/index.ts +1 -1
  115. package/src/modules/wms/setup.ts +4 -1
  116. package/src/modules/workflows/api/events/route.ts +1 -1
  117. package/src/modules/workflows/api/instances/[id]/events/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/[id]/steps/route.ts +3 -2
  119. package/src/modules/workflows/api/instances/failure-queue/route.ts +1 -1
  120. package/src/modules/workflows/lib/event-logger.ts +1 -1
  121. package/src/modules/workflows/lib/work-inbox/user-task-source.ts +3 -2
@@ -7,14 +7,13 @@ import { platformDomains } from "@open-mercato/core/modules/customer_accounts/li
7
7
  import { validateUserState } from "./customerAuth.js";
8
8
  import { createLogger } from "@open-mercato/shared/lib/logger";
9
9
  const logger = createLogger("customer_accounts").child({ component: "customer-auth-server" });
10
- async function assertSessionStillActive(input) {
10
+ async function findSessionStillActive(input) {
11
11
  try {
12
12
  const container = await createRequestContainer();
13
13
  const service = container.resolve("customerSessionService");
14
- const session = await service.findActiveSessionForClaims(input);
15
- return session !== null;
14
+ return await service.findActiveSessionForClaims(input);
16
15
  } catch {
17
- return false;
16
+ return null;
18
17
  }
19
18
  }
20
19
  async function getCustomerAuthFromCookies(options) {
@@ -33,18 +32,19 @@ async function getCustomerAuthFromCookies(options) {
33
32
  if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {
34
33
  return null;
35
34
  }
36
- const stillActive = await assertSessionStillActive({
35
+ const session = await findSessionStillActive({
37
36
  sessionId: sid,
38
37
  userId,
39
38
  tenantId,
40
39
  organizationId
41
40
  });
42
- if (!stillActive) return null;
41
+ if (!session) return null;
43
42
  const userState = await validateUserState(
44
43
  userId,
45
44
  tenantId,
46
45
  organizationId,
47
- payload.iat
46
+ payload.iat,
47
+ session.createdAt
48
48
  );
49
49
  if (!userState.valid || !userState.tenantId || !userState.organizationId) return null;
50
50
  return {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/lib/customerAuthServer.ts"],
4
- "sourcesContent": ["/**\n * Server-side customer auth helpers for Next.js server components.\n *\n * Uses the `cookies()` API from `next/headers` to read the customer auth token\n * from cookies \u2014 analogous to `getAuthFromCookies()` for staff auth.\n */\n\nimport { cookies } from 'next/headers'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { verifyAudienceJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { CUSTOMER_JWT_AUDIENCE, CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\nimport { tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { validateUserState } from './customerAuth'\nimport type { CustomerAuthContext } from './customerAuth'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'customer-auth-server' })\n\nexport type { CustomerAuthContext }\n\nasync function assertSessionStillActive(input: {\n sessionId: string\n userId: string\n tenantId: string\n organizationId: string\n}): Promise<boolean> {\n try {\n const container = await createRequestContainer()\n const service = container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>\n const session = await service.findActiveSessionForClaims(input)\n return session !== null\n } catch {\n return false\n }\n}\n\n/**\n * Read and verify customer auth from cookies in server components.\n *\n * Returns the customer auth context if a valid customer JWT is found,\n * or null if not authenticated.\n *\n * @example\n * ```tsx\n * // In a server component or catch-all route\n * import { getCustomerAuthFromCookies } from '@open-mercato/core/modules/customer_accounts/lib/customerAuthServer'\n *\n * const customerAuth = await getCustomerAuthFromCookies()\n * if (!customerAuth) redirect('/login')\n * ```\n */\nexport async function getCustomerAuthFromCookies(\n options?: { expectedTenantId?: string },\n): Promise<CustomerAuthContext | null> {\n const cookieStore = await cookies()\n const token = cookieStore.get('customer_auth_token')?.value\n if (!token) return null\n\n try {\n const payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token) as Record<string, unknown> | null\n if (!payload) return null\n if (payload.type !== 'customer') return null\n const sid = typeof payload.sid === 'string' ? payload.sid : ''\n if (!sid) return null\n const tenantId = String(payload.tenantId)\n const userId = String(payload.sub)\n const organizationId = String(payload.orgId)\n if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {\n // Cross-host JWT replay defense. See spec rev 5 Customer Authentication\n // section: the host-resolved tenant is the authoritative scope; mismatched\n // JWTs are rejected as if unauthenticated.\n return null\n }\n const stillActive = await assertSessionStillActive({\n sessionId: sid,\n userId,\n tenantId,\n organizationId,\n })\n if (!stillActive) return null\n\n const userState = await validateUserState(\n userId,\n tenantId,\n organizationId,\n payload.iat,\n )\n if (!userState.valid || !userState.tenantId || !userState.organizationId) return null\n\n return {\n sub: userId,\n sid,\n type: 'customer',\n // Authorization scope comes from userState (re-derived from the DB in validateUserState),\n // not from the JWT's own tenantId/orgId/customerEntityId/personEntityId claims (#2244).\n tenantId: userState.tenantId,\n orgId: userState.organizationId,\n email: String(payload.email || ''),\n displayName: String(payload.displayName || ''),\n customerEntityId: userState.customerEntityId ?? null,\n personEntityId: userState.personEntityId ?? null,\n resolvedFeatures: userState.resolvedFeatures,\n isPortalAdmin: userState.isPortalAdmin,\n }\n } catch {\n // Invalid or expired JWT \u2014 treat as unauthenticated\n return null\n }\n}\n\n/**\n * Convenience wrapper for custom-domain pages: resolves the host, calls\n * getCustomerAuthFromCookies with the host-resolved tenant as expectedTenantId.\n *\n * Use from server components rendered under custom domains.\n */\nexport async function getCustomerAuthForHost(\n host: string | null | undefined,\n): Promise<CustomerAuthContext | null> {\n if (!host) return getCustomerAuthFromCookies()\n\n try {\n const hostname = tryNormalizeHostname(host)\n if (!hostname) return getCustomerAuthFromCookies()\n if (platformDomains().includes(hostname)) return getCustomerAuthFromCookies()\n\n const container = await createRequestContainer()\n const service = container.resolve('domainMappingService') as InstanceType<typeof DomainMappingService>\n const resolved = await service.resolveByHostname(hostname)\n if (!resolved || resolved.status !== 'active') return null\n return getCustomerAuthFromCookies({ expectedTenantId: resolved.tenantId })\n } catch (err) {\n logger.warn('Domain resolve failed; falling back to platform cookie', { err })\n return getCustomerAuthFromCookies()\n }\n}\n"],
5
- "mappings": "AAOA,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC,SAAS,6BAAqD;AAE9D,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAI5F,eAAe,yBAAyB,OAKnB;AACnB,MAAI;AACF,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,UAAU,UAAU,QAAQ,wBAAwB;AAC1D,UAAM,UAAU,MAAM,QAAQ,2BAA2B,KAAK;AAC9D,WAAO,YAAY;AAAA,EACrB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAiBA,eAAsB,2BACpB,SACqC;AACrC,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,QAAQ,YAAY,IAAI,qBAAqB,GAAG;AACtD,MAAI,CAAC,MAAO,QAAO;AAEnB,MAAI;AACF,UAAM,UAAU,kBAAkB,uBAAuB,KAAK;AAC9D,QAAI,CAAC,QAAS,QAAO;AACrB,QAAI,QAAQ,SAAS,WAAY,QAAO;AACxC,UAAM,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,MAAM;AAC5D,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,WAAW,OAAO,QAAQ,QAAQ;AACxC,UAAM,SAAS,OAAO,QAAQ,GAAG;AACjC,UAAM,iBAAiB,OAAO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AAK,0DAA0D,EAAE,IAAI,CAAC;AAC7E,WAAO,2BAA2B;AAAA,EACpC;AACF;",
4
+ "sourcesContent": ["/**\n * Server-side customer auth helpers for Next.js server components.\n *\n * Uses the `cookies()` API from `next/headers` to read the customer auth token\n * from cookies \u2014 analogous to `getAuthFromCookies()` for staff auth.\n */\n\nimport { cookies } from 'next/headers'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { verifyAudienceJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { CUSTOMER_JWT_AUDIENCE, CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\nimport { tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { validateUserState } from './customerAuth'\nimport type { CustomerAuthContext } from './customerAuth'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'customer-auth-server' })\n\nexport type { CustomerAuthContext }\n\nasync function findSessionStillActive(input: {\n sessionId: string\n userId: string\n tenantId: string\n organizationId: string\n}) {\n try {\n const container = await createRequestContainer()\n const service = container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>\n return await service.findActiveSessionForClaims(input)\n } catch {\n return null\n }\n}\n\n/**\n * Read and verify customer auth from cookies in server components.\n *\n * Returns the customer auth context if a valid customer JWT is found,\n * or null if not authenticated.\n *\n * @example\n * ```tsx\n * // In a server component or catch-all route\n * import { getCustomerAuthFromCookies } from '@open-mercato/core/modules/customer_accounts/lib/customerAuthServer'\n *\n * const customerAuth = await getCustomerAuthFromCookies()\n * if (!customerAuth) redirect('/login')\n * ```\n */\nexport async function getCustomerAuthFromCookies(\n options?: { expectedTenantId?: string },\n): Promise<CustomerAuthContext | null> {\n const cookieStore = await cookies()\n const token = cookieStore.get('customer_auth_token')?.value\n if (!token) return null\n\n try {\n const payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token) as Record<string, unknown> | null\n if (!payload) return null\n if (payload.type !== 'customer') return null\n const sid = typeof payload.sid === 'string' ? payload.sid : ''\n if (!sid) return null\n const tenantId = String(payload.tenantId)\n const userId = String(payload.sub)\n const organizationId = String(payload.orgId)\n if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {\n // Cross-host JWT replay defense. See spec rev 5 Customer Authentication\n // section: the host-resolved tenant is the authoritative scope; mismatched\n // JWTs are rejected as if unauthenticated.\n return null\n }\n const session = await findSessionStillActive({\n sessionId: sid,\n userId,\n tenantId,\n organizationId,\n })\n if (!session) return null\n\n const userState = await validateUserState(\n userId,\n tenantId,\n organizationId,\n payload.iat,\n session.createdAt,\n )\n if (!userState.valid || !userState.tenantId || !userState.organizationId) return null\n\n return {\n sub: userId,\n sid,\n type: 'customer',\n // Authorization scope comes from userState (re-derived from the DB in validateUserState),\n // not from the JWT's own tenantId/orgId/customerEntityId/personEntityId claims (#2244).\n tenantId: userState.tenantId,\n orgId: userState.organizationId,\n email: String(payload.email || ''),\n displayName: String(payload.displayName || ''),\n customerEntityId: userState.customerEntityId ?? null,\n personEntityId: userState.personEntityId ?? null,\n resolvedFeatures: userState.resolvedFeatures,\n isPortalAdmin: userState.isPortalAdmin,\n }\n } catch {\n // Invalid or expired JWT \u2014 treat as unauthenticated\n return null\n }\n}\n\n/**\n * Convenience wrapper for custom-domain pages: resolves the host, calls\n * getCustomerAuthFromCookies with the host-resolved tenant as expectedTenantId.\n *\n * Use from server components rendered under custom domains.\n */\nexport async function getCustomerAuthForHost(\n host: string | null | undefined,\n): Promise<CustomerAuthContext | null> {\n if (!host) return getCustomerAuthFromCookies()\n\n try {\n const hostname = tryNormalizeHostname(host)\n if (!hostname) return getCustomerAuthFromCookies()\n if (platformDomains().includes(hostname)) return getCustomerAuthFromCookies()\n\n const container = await createRequestContainer()\n const service = container.resolve('domainMappingService') as InstanceType<typeof DomainMappingService>\n const resolved = await service.resolveByHostname(hostname)\n if (!resolved || resolved.status !== 'active') return null\n return getCustomerAuthFromCookies({ expectedTenantId: resolved.tenantId })\n } catch (err) {\n logger.warn('Domain resolve failed; falling back to platform cookie', { err })\n return getCustomerAuthFromCookies()\n }\n}\n"],
5
+ "mappings": "AAOA,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC,SAAS,6BAAqD;AAE9D,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAI5F,eAAe,uBAAuB,OAKnC;AACD,MAAI;AACF,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,UAAU,UAAU,QAAQ,wBAAwB;AAC1D,WAAO,MAAM,QAAQ,2BAA2B,KAAK;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAiBA,eAAsB,2BACpB,SACqC;AACrC,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,QAAQ,YAAY,IAAI,qBAAqB,GAAG;AACtD,MAAI,CAAC,MAAO,QAAO;AAEnB,MAAI;AACF,UAAM,UAAU,kBAAkB,uBAAuB,KAAK;AAC9D,QAAI,CAAC,QAAS,QAAO;AACrB,QAAI,QAAQ,SAAS,WAAY,QAAO;AACxC,UAAM,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,MAAM;AAC5D,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,WAAW,OAAO,QAAQ,QAAQ;AACxC,UAAM,SAAS,OAAO,QAAQ,GAAG;AACjC,UAAM,iBAAiB,OAAO,QAAQ,KAAK;AAC3C,QAAI,SAAS,oBAAoB,QAAQ,qBAAqB,UAAU;AAItE,aAAO;AAAA,IACT;AACA,UAAM,UAAU,MAAM,uBAAuB;AAAA,MAC3C,WAAW;AAAA,MACX;AAAA,MACA;AAAA,M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ib/encryption/find";
2
+ import { isRegisteredModuleEntity } from "./moduleEntityRegistration.js";
3
+ async function getRegisteredCustomerEntity(em) {
4
+ const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
5
+ return isRegisteredModuleEntity(em, CustomerEntity, "customers.CustomerEntity") ? CustomerEntity : null;
6
+ }
7
+ async function isCustomerEntityRegistered(em) {
8
+ return await getRegisteredCustomerEntity(em) !== null;
9
+ }
2
10
  async function isOwnedCompanyEntity(em, customerEntityId, scope) {
3
11
  return isOwnedEntityOfKind(em, customerEntityId, "company", scope);
4
12
  }
@@ -7,6 +15,7 @@ async function isOwnedPersonEntity(em, personEntityId, scope) {
7
15
  }
8
16
  async function resolveOwnedCompanyForPerson(em, personEntityId, scope) {
9
17
  const { CustomerPersonProfile } = await import("@open-mercato/core/modules/customers/data/entities");
18
+ if (!isRegisteredModuleEntity(em, CustomerPersonProfile, "customers.CustomerPersonProfile")) return null;
10
19
  const profile = await em.findOne(CustomerPersonProfile, {
11
20
  entity: personEntityId,
12
21
  tenantId: scope.tenantId,
@@ -24,7 +33,8 @@ function readCompanyEntityId(profile) {
24
33
  return typeof id === "string" ? id : null;
25
34
  }
26
35
  async function isOwnedEntityOfKind(em, entityId, kind, scope) {
27
- const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
36
+ const CustomerEntity = await getRegisteredCustomerEntity(em);
37
+ if (!CustomerEntity) return false;
28
38
  const entity = await findOneWithDecryption(
29
39
  em,
30
40
  CustomerEntity,
@@ -41,6 +51,7 @@ async function isOwnedEntityOfKind(em, entityId, kind, scope) {
41
51
  return !!entity;
42
52
  }
43
53
  export {
54
+ isCustomerEntityRegistered,
44
55
  isOwnedCompanyEntity,
45
56
  isOwnedPersonEntity,
46
57
  resolveOwnedCompanyForPerson
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/lib/customerEntityOwnership.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport type CustomerEntityScope = {\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n}\n\n/**\n * Confirms that a caller-supplied `customerEntityId` (the CRM company FK linked\n * onto a customer user) exists, is a company, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * Without this check an admin in org A could pass a company UUID from org B in\n * the same tenant and cross-link a customer user into another org's portal\n * context (#2693). The lookup is org-scoped to match how `CustomerEntity` rows\n * are created and listed.\n */\nexport async function isOwnedCompanyEntity(\n em: EntityManager,\n customerEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, customerEntityId, 'company', scope)\n}\n\n/**\n * Confirms that a caller-supplied `personEntityId` (the CRM person FK linked\n * onto a customer user) exists, is a person, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * This is the symmetric guard to {@link isOwnedCompanyEntity}: the person FK is\n * copied onto the customer user on accept and short-circuits CRM auto-linking,\n * so an unvalidated id would permanently cross-link a portal user to another\n * org's person (the #4362/#2693 class of bug, on the person side).\n */\nexport async function isOwnedPersonEntity(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, personEntityId, 'person', scope)\n}\n\n/**\n * Resolves the CRM company a person belongs to, but only when both the profile\n * lookup and the company itself stay inside the given tenant/organization scope.\n * Returns null when the person has no company or that company is out of scope.\n *\n * Both the invite route and the CRM auto-link subscriber need this answer, and\n * both write the result into `customerEntityId` \u2014 the portal company scope key \u2014\n * so they must agree on what counts as an in-scope company.\n */\nexport async function resolveOwnedCompanyForPerson(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<string | null> {\n const { CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const profile = await em.findOne(CustomerPersonProfile as any, {\n entity: personEntityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as any)\n const candidate = readCompanyEntityId(profile)\n if (!candidate) return null\n return (await isOwnedCompanyEntity(em, candidate, scope)) ? candidate : null\n}\n\n/**\n * `CustomerPersonProfile.company` is a relation on `company_entity_id`, not a\n * scalar \u2014 MikroORM hands back either the raw id or an entity reference, never a\n * `companyEntityId` property. Reading the wrong one silently yields undefined and\n * turns every company recovery into a clear.\n */\nfunction readCompanyEntityId(profile: unknown): string | null {\n const company = (profile as { company?: unknown } | null | undefined)?.company\n if (!company) return null\n if (typeof company === 'string') return company\n const id = (company as { id?: unknown }).id\n return typeof id === 'string' ? id : null\n}\n\nasync function isOwnedEntityOfKind(\n em: EntityManager,\n entityId: string,\n kind: 'company' | 'person',\n scope: CustomerEntityScope,\n): Promise<boolean> {\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n kind,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return !!entity\n}\n"],
5
- "mappings": "AACA,SAAS,6BAA6B;AAiBtC,eAAsB,qBACpB,IACA,kBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,kBAAkB,WAAW,KAAK;AACnE;AAYA,eAAsB,oBACpB,IACA,gBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,gBAAgB,UAAU,KAAK;AAChE;AAWA,eAAsB,6BACpB,IACA,gBACA,OACwB;AACxB,QAAM,EAAE,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnG,QAAM,UAAU,MAAM,GAAG,QAAQ,uBAA8B;AAAA,IAC7D,QAAQ;AAAA,IACR,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB,CAAQ;AACR,QAAM,YAAY,oBAAoB,OAAO;AAC7C,MAAI,CAAC,UAAW,QAAO;AACvB,SAAQ,MAAM,qBAAqB,IAAI,WAAW,KAAK,IAAK,YAAY;AAC1E;AAQA,SAAS,oBAAoB,SAAiC;AAC5D,QAAM,UAAW,SAAsD;AACvE,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAM,KAAM,QAA6B;AACzC,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEA,eAAe,oBACb,IACA,UACA,MACA,OACkB;AAClB,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,oDAAoD;AAC5F,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,SAAO,CAAC,CAAC;AACX;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isRegisteredModuleEntity } from './moduleEntityRegistration'\n\nexport type CustomerEntityScope = {\n tenantId: string | null | undefined\n organizationId: string | null | undefined\n}\n\nasync function getRegisteredCustomerEntity(em: EntityManager) {\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n return isRegisteredModuleEntity(em, CustomerEntity, 'customers.CustomerEntity') ? CustomerEntity : null\n}\n\nexport async function isCustomerEntityRegistered(em: EntityManager): Promise<boolean> {\n return (await getRegisteredCustomerEntity(em)) !== null\n}\n\n/**\n * Confirms that a caller-supplied `customerEntityId` (the CRM company FK linked\n * onto a customer user) exists, is a company, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * Without this check an admin in org A could pass a company UUID from org B in\n * the same tenant and cross-link a customer user into another org's portal\n * context (#2693). The lookup is org-scoped to match how `CustomerEntity` rows\n * are created and listed.\n */\nexport async function isOwnedCompanyEntity(\n em: EntityManager,\n customerEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, customerEntityId, 'company', scope)\n}\n\n/**\n * Confirms that a caller-supplied `personEntityId` (the CRM person FK linked\n * onto a customer user) exists, is a person, is not soft-deleted, and belongs\n * to the caller's tenant and organization.\n *\n * This is the symmetric guard to {@link isOwnedCompanyEntity}: the person FK is\n * copied onto the customer user on accept and short-circuits CRM auto-linking,\n * so an unvalidated id would permanently cross-link a portal user to another\n * org's person (the #4362/#2693 class of bug, on the person side).\n */\nexport async function isOwnedPersonEntity(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<boolean> {\n return isOwnedEntityOfKind(em, personEntityId, 'person', scope)\n}\n\n/**\n * Resolves the CRM company a person belongs to, but only when both the profile\n * lookup and the company itself stay inside the given tenant/organization scope.\n * Returns null when the person has no company or that company is out of scope.\n *\n * Both the invite route and the CRM auto-link subscriber need this answer, and\n * both write the result into `customerEntityId` \u2014 the portal company scope key \u2014\n * so they must agree on what counts as an in-scope company.\n */\nexport async function resolveOwnedCompanyForPerson(\n em: EntityManager,\n personEntityId: string,\n scope: CustomerEntityScope,\n): Promise<string | null> {\n const { CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n if (!isRegisteredModuleEntity(em, CustomerPersonProfile, 'customers.CustomerPersonProfile')) return null\n const profile = await em.findOne(CustomerPersonProfile as any, {\n entity: personEntityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n } as any)\n const candidate = readCompanyEntityId(profile)\n if (!candidate) return null\n return (await isOwnedCompanyEntity(em, candidate, scope)) ? candidate : null\n}\n\n/**\n * `CustomerPersonProfile.company` is a relation on `company_entity_id`, not a\n * scalar \u2014 MikroORM hands back either the raw id or an entity reference, never a\n * `companyEntityId` property. Reading the wrong one silently yields undefined and\n * turns every company recovery into a clear.\n */\nfunction readCompanyEntityId(profile: unknown): string | null {\n const company = (profile as { company?: unknown } | null | undefined)?.company\n if (!company) return null\n if (typeof company === 'string') return company\n const id = (company as { id?: unknown }).id\n return typeof id === 'string' ? id : null\n}\n\nasync function isOwnedEntityOfKind(\n em: EntityManager,\n entityId: string,\n kind: 'company' | 'person',\n scope: CustomerEntityScope,\n): Promise<boolean> {\n const CustomerEntity = await getRegisteredCustomerEntity(em)\n if (!CustomerEntity) return false\n const entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n {\n id: entityId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n kind,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n return !!entity\n}\n"],
5
+ "mappings": "AACA,SAAS,6BAA6B;AACtC,SAAS,gCAAgC;AAOzC,eAAe,4BAA4B,IAAmB;AAC5D,QAAM,EAAE,eAAe,IAAI,MAAM,OAAO,oDAAoD;AAC5F,SAAO,yBAAyB,IAAI,gBAAgB,0BAA0B,IAAI,iBAAiB;AACrG;AAEA,eAAsB,2BAA2B,IAAqC;AACpF,SAAQ,MAAM,4BAA4B,EAAE,MAAO;AACrD;AAYA,eAAsB,qBACpB,IACA,kBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,kBAAkB,WAAW,KAAK;AACnE;AAYA,eAAsB,oBACpB,IACA,gBACA,OACkB;AAClB,SAAO,oBAAoB,IAAI,gBAAgB,UAAU,KAAK;AAChE;AAWA,eAAsB,6BACpB,IACA,gBACA,OACwB;AACxB,QAAM,EAAE,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnG,MAAI,CAAC,yBAAyB,IAAI,uBAAuB,iCAAiC,EAAG,QAAO;AACpG,QAAM,UAAU,MAAM,GAAG,QAAQ,uBAA8B;AAAA,IAC7D,QAAQ;AAAA,IACR,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB,CAAQ;AACR,QAAM,YAAY,oBAAoB,OAAO;AAC7C,MAAI,CAAC,UAAW,QAAO;AACvB,SAAQ,MAAM,qBAAqB,IAAI,WAAW,KAAK,IAAK,YAAY;AAC1E;AAQA,SAAS,oBAAoB,SAAiC;AAC5D,QAAM,UAAW,SAAsD;AACvE,MAAI,CAAC,QAAS,QAAO;AACrB,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAM,KAAM,QAA6B;AACzC,SAAO,OAAO,OAAO,WAAW,KAAK;AACvC;AAEA,eAAe,oBACb,IACA,UACA,MACA,OACkB;AAClB,QAAM,iBAAiB,MAAM,4BAA4B,EAAE;AAC3D,MAAI,CAAC,eAAgB,QAAO;AAC5B,QAAM,SAAS,MAAM;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI;AAAA,MACJ,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB;AAAA,MACA,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,EACnE;AACA,SAAO,CAAC,CAAC;AACX;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,8 @@
1
+ function isRegisteredModuleEntity(em, entity, qualifiedName) {
2
+ const registeredClass = em.getMetadata().find(entity)?.class;
3
+ return registeredClass === entity || registeredClass?.entityName === qualifiedName;
4
+ }
5
+ export {
6
+ isRegisteredModuleEntity
7
+ };
8
+ //# sourceMappingURL=moduleEntityRegistration.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/moduleEntityRegistration.ts"],
4
+ "sourcesContent": ["import type { EntityCtor } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\nexport function isRegisteredModuleEntity<Entity>(\n em: EntityManager,\n entity: EntityCtor<Entity>,\n qualifiedName: string,\n): boolean {\n const registeredClass: (EntityCtor<Entity> & { entityName?: string }) | undefined =\n em.getMetadata().find(entity)?.class\n return registeredClass === entity || registeredClass?.entityName === qualifiedName\n}\n"],
5
+ "mappings": "AAGO,SAAS,yBACd,IACA,QACA,eACS;AACT,QAAM,kBACJ,GAAG,YAAY,EAAE,KAAK,MAAM,GAAG;AACjC,SAAO,oBAAoB,UAAU,iBAAiB,eAAe;AACvE;",
6
+ "names": []
7
+ }
@@ -0,0 +1,16 @@
1
+ const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1e3;
2
+ const pendingSignup = {
3
+ isActive: true,
4
+ emailVerifiedAt: null,
5
+ lastLoginAt: null,
6
+ deletedAt: null
7
+ };
8
+ function signupExpiryCutoff(now) {
9
+ return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS);
10
+ }
11
+ export {
12
+ EMAIL_VERIFICATION_TTL_MS,
13
+ pendingSignup,
14
+ signupExpiryCutoff
15
+ };
16
+ //# sourceMappingURL=pendingSignup.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/pendingSignup.ts"],
4
+ "sourcesContent": ["export const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000\n\nexport const pendingSignup = {\n isActive: true,\n emailVerifiedAt: null,\n lastLoginAt: null,\n deletedAt: null,\n} as const\n\nexport function signupExpiryCutoff(now: Date): Date {\n return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS)\n}\n"],
5
+ "mappings": "AAAO,MAAM,4BAA4B,KAAK,KAAK,KAAK;AAEjD,MAAM,gBAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,WAAW;AACb;AAEO,SAAS,mBAAmB,KAAiB;AAClD,SAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,yBAAyB;AAC3D;",
6
+ "names": []
7
+ }
@@ -0,0 +1,9 @@
1
+ import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
2
+ import { isRegisteredModuleEntity } from "./moduleEntityRegistration.js";
3
+ function arePortalNotificationsAvailable(em) {
4
+ return isRegisteredModuleEntity(em, Notification, "notifications.Notification");
5
+ }
6
+ export {
7
+ arePortalNotificationsAvailable
8
+ };
9
+ //# sourceMappingURL=portalNotificationsAvailability.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/portalNotificationsAvailability.ts"],
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\nimport { isRegisteredModuleEntity } from './moduleEntityRegistration'\n\nexport function arePortalNotificationsAvailable(em: EntityManager): boolean {\n return isRegisteredModuleEntity(em, Notification, 'notifications.Notification')\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AAElC,SAAS,gCAAgC,IAA4B;AAC1E,SAAO,yBAAyB,IAAI,cAAc,4BAA4B;AAChF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,50 @@
1
+ import { LockMode } from "@mikro-orm/core";
2
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
3
+ import { CustomerUser } from "../data/entities.js";
4
+ import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
5
+ import { signupExpiryCutoff } from "./pendingSignup.js";
6
+ async function verifyCustomerEmail(em, identity, sessions, options) {
7
+ const { userId, tenantId, organizationId } = identity;
8
+ const user = await findOneWithDecryption(
9
+ em,
10
+ CustomerUser,
11
+ { id: userId, tenantId, ...organizationId ? { organizationId } : {}, deletedAt: null },
12
+ { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
13
+ { tenantId, organizationId }
14
+ );
15
+ if (!user?.isActive) return null;
16
+ const now = /* @__PURE__ */ new Date();
17
+ const newlyVerified = !user.emailVerifiedAt;
18
+ if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null;
19
+ if (!newlyVerified && !options) return { user, newlyVerified };
20
+ if (!newlyVerified && !options?.reset && user.passwordHash) {
21
+ return null;
22
+ }
23
+ const scope = { id: user.id, tenantId, organizationId: user.organizationId };
24
+ if (options) {
25
+ await options.users.updatePassword(user, options.password, em);
26
+ }
27
+ if (newlyVerified) {
28
+ await em.nativeUpdate(CustomerUser, scope, {
29
+ emailVerifiedAt: now,
30
+ ...options ? {} : { passwordHash: null }
31
+ });
32
+ }
33
+ await sessions.revokeAllUserSessions(user.id, em);
34
+ return { user, newlyVerified };
35
+ }
36
+ function emitCustomerEmailVerified(user, verifiedBy) {
37
+ void emitCustomerAccountsEvent("customer_accounts.email.verified", {
38
+ id: user.id,
39
+ userId: user.id,
40
+ recipientUserId: user.id,
41
+ tenantId: user.tenantId,
42
+ organizationId: user.organizationId,
43
+ ...verifiedBy ? { email: user.email, verifiedBy } : {}
44
+ }).catch(() => void 0);
45
+ }
46
+ export {
47
+ emitCustomerEmailVerified,
48
+ verifyCustomerEmail
49
+ };
50
+ //# sourceMappingURL=verifyCustomerEmail.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/lib/verifyCustomerEmail.ts"],
4
+ "sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerUser } from '../data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport type { CustomerSessionService } from '../services/customerSessionService'\nimport type { CustomerUserService } from '../services/customerUserService'\nimport { signupExpiryCutoff } from './pendingSignup'\n\nexport async function verifyCustomerEmail(\n em: EntityManager,\n identity: { userId: string; tenantId: string; organizationId?: string },\n sessions: CustomerSessionService,\n options?: { password: string; users: CustomerUserService; reset?: boolean },\n): Promise<{ user: CustomerUser; newlyVerified: boolean } | null> {\n const { userId, tenantId, organizationId } = identity\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: userId, tenantId, ...(organizationId ? { organizationId } : {}), deletedAt: null },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId, organizationId },\n )\n if (!user?.isActive) return null\n\n const now = new Date()\n const newlyVerified = !user.emailVerifiedAt\n if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null\n if (!newlyVerified && !options) return { user, newlyVerified }\n if (!newlyVerified && !options?.reset && user.passwordHash) {\n return null\n }\n\n const scope = { id: user.id, tenantId, organizationId: user.organizationId }\n if (options) {\n await options.users.updatePassword(user, options.password, em)\n }\n if (newlyVerified) {\n await em.nativeUpdate(CustomerUser, scope, {\n emailVerifiedAt: now,\n ...(options ? {} : { passwordHash: null }),\n })\n }\n await sessions.revokeAllUserSessions(user.id, em)\n return { user, newlyVerified }\n}\n\nexport function emitCustomerEmailVerified(user: CustomerUser, verifiedBy?: string): void {\n void emitCustomerAccountsEvent('customer_accounts.email.verified', {\n id: user.id,\n userId: user.id,\n recipientUserId: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n ...(verifiedBy ? { email: user.email, verifiedBy } : {}),\n }).catch(() => undefined)\n}\n"],
5
+ "mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAG1C,SAAS,0BAA0B;AAEnC,eAAsB,oBACpB,IACA,UACA,UACA,SACgE;AAChE,QAAM,EAAE,QAAQ,UAAU,eAAe,IAAI;AAC7C,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA;AAAA,IACA,EAAE,IAAI,QAAQ,UAAU,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC,GAAI,WAAW,KAAK;AAAA,IACvF,EAAE,UAAU,SAAS,mBAAmB,SAAS,KAAK;AAAA,IACtD,EAAE,UAAU,eAAe;AAAA,EAC7B;AACA,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,gBAAgB,CAAC,KAAK;AAC5B,MAAI,iBAAiB,CAAC,KAAK,eAAe,KAAK,aAAa,mBAAmB,GAAG,EAAG,QAAO;AAC5F,MAAI,CAAC,iBAAiB,CAAC,QAAS,QAAO,EAAE,MAAM,cAAc;AAC7D,MAAI,CAAC,iBAAiB,CAAC,SAAS,SAAS,KAAK,cAAc;AAC1D,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,EAAE,IAAI,KAAK,IAAI,UAAU,gBAAgB,KAAK,eAAe;AAC3E,MAAI,SAAS;AACX,UAAM,QAAQ,MAAM,eAAe,MAAM,QAAQ,UAAU,EAAE;AAAA,EAC/D;AACA,MAAI,eAAe;AACjB,UAAM,GAAG,aAAa,cAAc,OAAO;AAAA,MACzC,iBAAiB;AAAA,MACjB,GAAI,UAAU,CAAC,IAAI,EAAE,cAAc,KAAK;AAAA,IAC1C,CAAC;AAAA,EACH;AACA,QAAM,SAAS,sBAAsB,KAAK,IAAI,EAAE;AAChD,SAAO,EAAE,MAAM,cAAc;AAC/B;AAEO,SAAS,0BAA0B,MAAoB,YAA2B;AACvF,OAAK,0BAA0B,oCAAoC;AAAA,IACjE,IAAI,KAAK;AAAA,IACT,QAAQ,KAAK;AAAA,IACb,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,GAAI,aAAa,EAAE,OAAO,KAAK,OAAO,WAAW,IAAI,CAAC;AAAA,EACxD,CAAC,EAAE,MAAM,MAAM,MAAS;AAC1B;",
6
+ "names": []
7
+ }
@@ -5,12 +5,14 @@ import {
5
5
  CustomerUser,
6
6
  CustomerUserInvitation,
7
7
  CustomerUserRole,
8
+ CustomerUserSession,
8
9
  CustomerRole
9
10
  } from "@open-mercato/core/modules/customer_accounts/data/entities";
10
11
  import { generateSecureToken, hashToken } from "@open-mercato/core/modules/customer_accounts/lib/tokenGenerator";
11
12
  import { hashForLookup, lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
12
13
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
13
14
  import { isCustomerTenantActive } from "@open-mercato/core/modules/customer_accounts/lib/tenantEligibility";
15
+ import { pendingSignup } from "../lib/pendingSignup.js";
14
16
  const BCRYPT_COST = 10;
15
17
  const INVITATION_TTL_MS = 72 * 60 * 60 * 1e3;
16
18
  const CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/CustomerInvitationEmailConflictError");
@@ -189,7 +191,19 @@ class CustomerInvitationService {
189
191
  scope
190
192
  );
191
193
  if (existingActiveUser) {
192
- throw new CustomerInvitationEmailConflictError(invitation.email);
194
+ if (existingActiveUser.organizationId !== scope.organizationId || !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {
195
+ throw new CustomerInvitationEmailConflictError(invitation.email);
196
+ }
197
+ const retired = await transactionEm.nativeUpdate(CustomerUser, {
198
+ id: existingActiveUser.id,
199
+ ...scope,
200
+ ...pendingSignup
201
+ }, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt });
202
+ if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email);
203
+ await transactionEm.nativeUpdate(CustomerUserSession, {
204
+ user: existingActiveUser.id,
205
+ deletedAt: null
206
+ }, { deletedAt: acceptedAt });
193
207
  }
194
208
  const user = transactionEm.create(CustomerUser, {
195
209
  email: invitation.email,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/services/customerInvitationService.ts"],
4
- "sourcesContent": ["import { LockMode, UniqueConstraintViolationException, type RequiredEntityData } from '@mikro-orm/core'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the accept route and this service are bundled into separate\n// chunks, so `instanceof` between them is false and the 409 mapping would\n// silently degrade back into the raw 500 this error exists to prevent.\nconst CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = Symbol.for('@open-mercato/CustomerInvitationEmailConflictError')\n\nexport class CustomerInvitationEmailConflictError extends Error {\n readonly [CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] = true\n\n constructor(public readonly email: string) {\n super('[internal] An account with this email address already exists')\n this.name = 'CustomerInvitationEmailConflictError'\n }\n}\n\n/**\n * Bundle-safe check for {@link CustomerInvitationEmailConflictError}. Always prefer\n * this over `instanceof` \u2014 API routes reach this service through DI and resolve a\n * different copy of this module.\n */\nexport function isCustomerInvitationEmailConflictError(\n error: unknown,\n): error is CustomerInvitationEmailConflictError {\n return !!error\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] === true\n}\n\nconst POSTGRES_UNIQUE_VIOLATION = '23505'\n\n/**\n * Unique-constraint detection that does not depend on `instanceof`: the MikroORM\n * copy this module is bundled with is not necessarily the one the driver throws\n * from, so fall back to the exception name and the Postgres SQLSTATE.\n */\nfunction isUniqueConstraintViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const candidate = error as { name?: unknown; code?: unknown; cause?: unknown }\n if (candidate.name === 'UniqueConstraintViolationException') return true\n if (candidate.code === POSTGRES_UNIQUE_VIOLATION) return true\n const cause = candidate.cause as { code?: unknown } | undefined\n return !!cause && typeof cause === 'object' && cause.code === POSTGRES_UNIQUE_VIOLATION\n}\n\nexport type CustomerInvitationRollbackState = {\n email: string\n token: string\n customerEntityId: string | null\n personEntityId: string | null\n roleIdsJson: string[]\n invitedByUserId: string | null\n invitedByCustomerUserId: string | null\n displayName: string | null\n expiresAt: Date\n}\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n personEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{\n invitation: CustomerUserInvitation\n rawToken: string\n reused: boolean\n rollbackState: CustomerInvitationRollbackState | null\n }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n return this.em.transactional(async (transactionEm) => {\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n transactionEm,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing && !existing.acceptedAt && !existing.cancelledAt && existing.expiresAt.getTime() > Date.now()) {\n const rollbackState: CustomerInvitationRollbackState = {\n email: existing.email,\n token: existing.token,\n customerEntityId: existing.customerEntityId ?? null,\n personEntityId: existing.personEntityId ?? null,\n roleIdsJson: [...(existing.roleIdsJson ?? [])],\n invitedByUserId: existing.invitedByUserId ?? null,\n invitedByCustomerUserId: existing.invitedByCustomerUserId ?? null,\n displayName: existing.displayName ?? null,\n expiresAt: new Date(existing.expiresAt),\n }\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n // Keep the CRM person link and the recipient's display name when the\n // re-invite does not carry them: the portal invite route and the admin users\n // page only ever know the company, so overwriting with null would strip an\n // invitation raised from a person card off that person's account-status card\n // and drop the personalization from the invitation email (#5499).\n existing.personEntityId = options.personEntityId || existing.personEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || existing.displayName || null\n existing.expiresAt = expiresAt\n await transactionEm.flush()\n return { invitation: existing, rawToken: token, reused: true, rollbackState }\n }\n\n const invitation = transactionEm.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n personEntityId: options.personEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as RequiredEntityData<CustomerUserInvitation>)\n await transactionEm.persist(invitation).flush()\n return { invitation, rawToken: token, reused: false, rollbackState: null }\n })\n }\n\n async rollbackInvitation(\n invitation: CustomerUserInvitation,\n rollbackState: CustomerInvitationRollbackState | null,\n expectedToken: string = invitation.token,\n ): Promise<void> {\n if (!invitation.tenantId || !invitation.organizationId || !expectedToken) return\n await this.em.transactional(async (transactionEm) => {\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const pending = await findOneWithDecryption(transactionEm, CustomerUserInvitation, {\n id: invitation.id,\n ...scope,\n token: expectedToken,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }, { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true }, scope)\n if (!pending) return\n if (!rollbackState) {\n await transactionEm.remove(pending).flush()\n return\n }\n pending.email = rollbackState.email\n pending.token = rollbackState.token\n pending.customerEntityId = rollbackState.customerEntityId\n pending.personEntityId = rollbackState.personEntityId\n pending.roleIdsJson = [...rollbackState.roleIdsJson]\n pending.invitedByUserId = rollbackState.invitedByUserId\n pending.invitedByCustomerUserId = rollbackState.invitedByCustomerUserId\n pending.displayName = rollbackState.displayName\n pending.expiresAt = new Date(rollbackState.expiresAt)\n await transactionEm.flush()\n })\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async cancelInvitation(\n invitationId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!scope.tenantId || !scope.organizationId) return false\n const cancelledAt = new Date()\n const changed = await this.em.nativeUpdate(CustomerUserInvitation, {\n id: invitationId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: cancelledAt },\n }, { cancelledAt })\n return changed === 1\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n if (!(await isCustomerTenantActive(this.em, invitation.tenantId))) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n try {\n const result = await this.em.transactional(async (transactionEm) => {\n const acceptedAt = new Date()\n const changed = await transactionEm.nativeUpdate(CustomerUserInvitation, {\n id: invitation.id,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n token: hashToken(token),\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: acceptedAt },\n }, { acceptedAt })\n if (changed !== 1) return null\n\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const existingActiveUser = await findOneWithDecryption(\n transactionEm,\n CustomerUser,\n {\n tenantId: invitation.tenantId,\n emailHash: { $in: lookupHashCandidates(invitation.email) },\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (existingActiveUser) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n\n const user = transactionEm.create(CustomerUser, {\n email: invitation.email,\n emailHash: hashForLookup(invitation.email),\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n isActive: true,\n emailVerifiedAt: acceptedAt,\n failedLoginAttempts: 0,\n createdAt: acceptedAt,\n })\n transactionEm.persist(user)\n\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n transactionEm,\n CustomerRole,\n {\n id: { $in: roleIds },\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n : []\n for (const role of roles) {\n transactionEm.persist(transactionEm.create(CustomerUserRole, {\n user,\n role,\n createdAt: acceptedAt,\n }))\n }\n await transactionEm.flush()\n return { user, acceptedAt }\n })\n if (!result) return null\n invitation.acceptedAt = result.acceptedAt\n return { user: result.user, invitation }\n } catch (error) {\n if (isUniqueConstraintViolation(error)) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n throw error\n }\n }\n}\n"],
5
- "mappings": "AAAA;AAAA,SAAS,UAAU,0CAAmE;AAEtF,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,eAAe,4BAA4B;AACpD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,8BAA8B;AAEvC,MAAM,cAAc;AACpB,MAAM,oBAAoB,KAAK,KAAK,KAAK;AAMzC,MAAM,4CAA4C,uBAAO,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AI,CAAC,OAAQ,QAAO;AACpB,iBAAW,aAAa,OAAO;AAC/B,aAAO,EAAE,MAAM,OAAO,MAAM,WAAW;AAAA,IACzC,SAAS,OAAO;AACd,UAAI,4BAA4B,KAAK,GAAG;AACtC,cAAM,IAAI,qCAAqC,WAAW,KAAK;AAAA,MACjE;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { LockMode, UniqueConstraintViolationException, type RequiredEntityData } from '@mikro-orm/core'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerUserSession,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\nimport { pendingSignup } from '../lib/pendingSignup'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the accept route and this service are bundled into separate\n// chunks, so `instanceof` between them is false and the 409 mapping would\n// silently degrade back into the raw 500 this error exists to prevent.\nconst CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = Symbol.for('@open-mercato/CustomerInvitationEmailConflictError')\n\nexport class CustomerInvitationEmailConflictError extends Error {\n readonly [CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] = true\n\n constructor(public readonly email: string) {\n super('[internal] An account with this email address already exists')\n this.name = 'CustomerInvitationEmailConflictError'\n }\n}\n\n/**\n * Bundle-safe check for {@link CustomerInvitationEmailConflictError}. Always prefer\n * this over `instanceof` \u2014 API routes reach this service through DI and resolve a\n * different copy of this module.\n */\nexport function isCustomerInvitationEmailConflictError(\n error: unknown,\n): error is CustomerInvitationEmailConflictError {\n return !!error\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] === true\n}\n\nconst POSTGRES_UNIQUE_VIOLATION = '23505'\n\n/**\n * Unique-constraint detection that does not depend on `instanceof`: the MikroORM\n * copy this module is bundled with is not necessarily the one the driver throws\n * from, so fall back to the exception name and the Postgres SQLSTATE.\n */\nfunction isUniqueConstraintViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const candidate = error as { name?: unknown; code?: unknown; cause?: unknown }\n if (candidate.name === 'UniqueConstraintViolationException') return true\n if (candidate.code === POSTGRES_UNIQUE_VIOLATION) return true\n const cause = candidate.cause as { code?: unknown } | undefined\n return !!cause && typeof cause === 'object' && cause.code === POSTGRES_UNIQUE_VIOLATION\n}\n\nexport type CustomerInvitationRollbackState = {\n email: string\n token: string\n customerEntityId: string | null\n personEntityId: string | null\n roleIdsJson: string[]\n invitedByUserId: string | null\n invitedByCustomerUserId: string | null\n displayName: string | null\n expiresAt: Date\n}\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n personEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{\n invitation: CustomerUserInvitation\n rawToken: string\n reused: boolean\n rollbackState: CustomerInvitationRollbackState | null\n }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n return this.em.transactional(async (transactionEm) => {\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n transactionEm,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing && !existing.acceptedAt && !existing.cancelledAt && existing.expiresAt.getTime() > Date.now()) {\n const rollbackState: CustomerInvitationRollbackState = {\n email: existing.email,\n token: existing.token,\n customerEntityId: existing.customerEntityId ?? null,\n personEntityId: existing.personEntityId ?? null,\n roleIdsJson: [...(existing.roleIdsJson ?? [])],\n invitedByUserId: existing.invitedByUserId ?? null,\n invitedByCustomerUserId: existing.invitedByCustomerUserId ?? null,\n displayName: existing.displayName ?? null,\n expiresAt: new Date(existing.expiresAt),\n }\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n // Keep the CRM person link and the recipient's display name when the\n // re-invite does not carry them: the portal invite route and the admin users\n // page only ever know the company, so overwriting with null would strip an\n // invitation raised from a person card off that person's account-status card\n // and drop the personalization from the invitation email (#5499).\n existing.personEntityId = options.personEntityId || existing.personEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || existing.displayName || null\n existing.expiresAt = expiresAt\n await transactionEm.flush()\n return { invitation: existing, rawToken: token, reused: true, rollbackState }\n }\n\n const invitation = transactionEm.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n personEntityId: options.personEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as RequiredEntityData<CustomerUserInvitation>)\n await transactionEm.persist(invitation).flush()\n return { invitation, rawToken: token, reused: false, rollbackState: null }\n })\n }\n\n async rollbackInvitation(\n invitation: CustomerUserInvitation,\n rollbackState: CustomerInvitationRollbackState | null,\n expectedToken: string = invitation.token,\n ): Promise<void> {\n if (!invitation.tenantId || !invitation.organizationId || !expectedToken) return\n await this.em.transactional(async (transactionEm) => {\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const pending = await findOneWithDecryption(transactionEm, CustomerUserInvitation, {\n id: invitation.id,\n ...scope,\n token: expectedToken,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }, { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true }, scope)\n if (!pending) return\n if (!rollbackState) {\n await transactionEm.remove(pending).flush()\n return\n }\n pending.email = rollbackState.email\n pending.token = rollbackState.token\n pending.customerEntityId = rollbackState.customerEntityId\n pending.personEntityId = rollbackState.personEntityId\n pending.roleIdsJson = [...rollbackState.roleIdsJson]\n pending.invitedByUserId = rollbackState.invitedByUserId\n pending.invitedByCustomerUserId = rollbackState.invitedByCustomerUserId\n pending.displayName = rollbackState.displayName\n pending.expiresAt = new Date(rollbackState.expiresAt)\n await transactionEm.flush()\n })\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async cancelInvitation(\n invitationId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!scope.tenantId || !scope.organizationId) return false\n const cancelledAt = new Date()\n const changed = await this.em.nativeUpdate(CustomerUserInvitation, {\n id: invitationId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: cancelledAt },\n }, { cancelledAt })\n return changed === 1\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n if (!(await isCustomerTenantActive(this.em, invitation.tenantId))) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n try {\n const result = await this.em.transactional(async (transactionEm) => {\n const acceptedAt = new Date()\n const changed = await transactionEm.nativeUpdate(CustomerUserInvitation, {\n id: invitation.id,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n token: hashToken(token),\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: acceptedAt },\n }, { acceptedAt })\n if (changed !== 1) return null\n\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const existingActiveUser = await findOneWithDecryption(\n transactionEm,\n CustomerUser,\n {\n tenantId: invitation.tenantId,\n emailHash: { $in: lookupHashCandidates(invitation.email) },\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (existingActiveUser) {\n if (existingActiveUser.organizationId !== scope.organizationId\n || !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n const retired = await transactionEm.nativeUpdate(CustomerUser, {\n id: existingActiveUser.id,\n ...scope,\n ...pendingSignup,\n }, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt })\n if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email)\n await transactionEm.nativeUpdate(CustomerUserSession, {\n user: existingActiveUser.id,\n deletedAt: null,\n }, { deletedAt: acceptedAt })\n }\n\n const user = transactionEm.create(CustomerUser, {\n email: invitation.email,\n emailHash: hashForLookup(invitation.email),\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n isActive: true,\n emailVerifiedAt: acceptedAt,\n failedLoginAttempts: 0,\n createdAt: acceptedAt,\n })\n transactionEm.persist(user)\n\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n transactionEm,\n CustomerRole,\n {\n id: { $in: roleIds },\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n : []\n for (const role of roles) {\n transactionEm.persist(transactionEm.create(CustomerUserRole, {\n user,\n role,\n createdAt: acceptedAt,\n }))\n }\n await transactionEm.flush()\n return { user, acceptedAt }\n })\n if (!result) return null\n invitation.acceptedAt = result.acceptedAt\n return { user: result.user, invitation }\n } catch (error) {\n if (isUniqueConstraintViolation(error)) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n throw error\n }\n }\n}\n"],
5
+ "mappings": "AAAA;AAAA,SAAS,UAAU,0CAAmE;AAEtF,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,eAAe,4BAA4B;AACpD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAE9B,MAAM,cAAc;AACpB,MAAM,oBAAoB,KAAK,KAAK,KAAK;AAMzC,MAAM,4CAA4C,uBAAO,IAAI,oDAAoD;AAE1G,MAAM,8CAA6C,YAC9C,gDAD8C,IAAM;AAAA,EAG9D,YAA4B,OAAe;AACzC,UAAM,8DAA8D;AAD1C;AAF5B,SAAU,MAA6C;AAIrD,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,uCACd,OAC+C;AAC/C,SAAO,CAAC,CAAC,SACJ,OAAO,UAAU,YACh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CAAC;AACL,mBAAW,QAAQ,OAAO;AACxB,wBAAc,QAAQ,cAAc,OAAO,kBAAkB;AAAA,YAC3D;AAAA,YACA;AAAA,YACA,WAAW;AAAA,UACb,CAAC,CAAC;AAAA,QACJ;AACA,cAAM,cAAc,MAAM;AAC1B,eAAO,EAAE,MAAM,WAAW;AAAA,MAC5B,CAAC;AACD,UAAI,CAAC,OAAQ,QAAO;AACpB,iBAAW,aAAa,OAAO;AAC/B,aAAO,EAAE,MAAM,OAAO,MAAM,WAAW;AAAA,IACzC,SAAS,OAAO;AACd,UAAI,4BAA4B,KAAK,GAAG;AACtC,cAAM,IAAI,qCAAqC,WAAW,KAAK;AAAA,MACjE;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -4,28 +4,28 @@ import {
4
4
  } from "@open-mercato/core/modules/customer_accounts/data/entities";
5
5
  import { generateSecureToken, hashToken } from "@open-mercato/core/modules/customer_accounts/lib/tokenGenerator";
6
6
  import { isCustomerTenantActive } from "@open-mercato/core/modules/customer_accounts/lib/tenantEligibility";
7
+ import { EMAIL_VERIFICATION_TTL_MS } from "../lib/pendingSignup.js";
7
8
  function getKysely(em) {
8
9
  return em.getKysely();
9
10
  }
10
- const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1e3;
11
11
  const MAGIC_LINK_TTL_MS = 15 * 60 * 1e3;
12
12
  const PASSWORD_RESET_TTL_MS = 60 * 60 * 1e3;
13
13
  class CustomerTokenService {
14
14
  constructor(em) {
15
15
  this.em = em;
16
16
  }
17
- async createEmailVerification(userId, tenantId) {
17
+ async createEmailVerification(userId, tenantId, createdAt = /* @__PURE__ */ new Date(), em = this.em) {
18
18
  const rawToken = generateSecureToken();
19
19
  const tokenHashed = hashToken(rawToken);
20
- const expiresAt = new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS);
21
- const record = this.em.create(CustomerUserEmailVerification, {
20
+ const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS);
21
+ const record = em.create(CustomerUserEmailVerification, {
22
22
  user: userId,
23
23
  token: tokenHashed,
24
24
  purpose: "email_verification",
25
25
  expiresAt,
26
- createdAt: /* @__PURE__ */ new Date()
26
+ createdAt
27
27
  });
28
- await this.em.persist(record).flush();
28
+ await em.persist(record).flush();
29
29
  return rawToken;
30
30
  }
31
31
  async createMagicLink(userId, tenantId) {
@@ -55,9 +55,9 @@ class CustomerTokenService {
55
55
  await this.em.persist(record).flush();
56
56
  return rawToken;
57
57
  }
58
- async verifyEmailToken(token, purpose, tenantId) {
58
+ async verifyEmailToken(token, purpose, tenantId, em = this.em) {
59
59
  const tokenHashed = hashToken(token);
60
- const record = await this.em.findOne(CustomerUserEmailVerification, {
60
+ const record = await em.findOne(CustomerUserEmailVerification, {
61
61
  token: tokenHashed,
62
62
  purpose
63
63
  }, { populate: ["user"] });
@@ -66,8 +66,8 @@ class CustomerTokenService {
66
66
  if (record.expiresAt.getTime() < Date.now()) return null;
67
67
  const user = record.user;
68
68
  if (tenantId && user?.tenantId !== tenantId) return null;
69
- if (purpose === "magic_link" && !await isCustomerTenantActive(this.em, user?.tenantId)) return null;
70
- const db = getKysely(this.em);
69
+ if (purpose === "magic_link" && !await isCustomerTenantActive(em, user?.tenantId)) return null;
70
+ const db = getKysely(em);
71
71
  const updateResult = await db.updateTable("customer_user_email_verifications").set({ used_at: /* @__PURE__ */ new Date() }).where("id", "=", record.id).where("used_at", "is", null).where("expires_at", ">", /* @__PURE__ */ new Date()).executeTakeFirst();
72
72
  const consumed = Number(updateResult?.numUpdatedRows ?? 0);
73
73
  if (consumed === 0) return null;
@@ -75,9 +75,9 @@ class CustomerTokenService {
75
75
  const resolvedTenantId = typeof user === "string" ? "" : user.tenantId;
76
76
  return { userId: resolvedUserId, tenantId: resolvedTenantId };
77
77
  }
78
- async verifyPasswordResetToken(token, tenantId) {
78
+ async verifyPasswordResetToken(token, tenantId, em = this.em) {
79
79
  const tokenHashed = hashToken(token);
80
- const record = await this.em.findOne(CustomerUserPasswordReset, {
80
+ const record = await em.findOne(CustomerUserPasswordReset, {
81
81
  token: tokenHashed
82
82
  }, { populate: ["user"] });
83
83
  if (!record) return null;
@@ -85,7 +85,7 @@ class CustomerTokenService {
85
85
  if (record.expiresAt.getTime() < Date.now()) return null;
86
86
  const user = record.user;
87
87
  if (tenantId && user?.tenantId !== tenantId) return null;
88
- const db = getKysely(this.em);
88
+ const db = getKysely(em);
89
89
  const updateResult = await db.updateTable("customer_user_password_resets").set({ used_at: /* @__PURE__ */ new Date() }).where("id", "=", record.id).where("used_at", "is", null).where("expires_at", ">", /* @__PURE__ */ new Date()).executeTakeFirst();
90
90
  const consumed = Number(updateResult?.numUpdatedRows ?? 0);
91
91
  if (consumed === 0) return null;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/services/customerTokenService.ts"],
4
- "sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { Kysely } from 'kysely'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\n\nfunction getKysely(em: EntityManager): Kysely<any> {\n return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()\n}\n\nconst EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours\nconst MAGIC_LINK_TTL_MS = 15 * 60 * 1000 // 15 minutes\nconst PASSWORD_RESET_TTL_MS = 60 * 60 * 1000 // 60 minutes\n\nexport class CustomerTokenService {\n constructor(private em: EntityManager) {}\n\n async createEmailVerification(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS)\n const record = this.em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'email_verification',\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async createMagicLink(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + MAGIC_LINK_TTL_MS)\n const record = this.em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'magic_link',\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async createPasswordReset(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + PASSWORD_RESET_TTL_MS)\n const record = this.em.create(CustomerUserPasswordReset, {\n user: userId as any,\n token: tokenHashed,\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async verifyEmailToken(token: string, purpose: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await this.em.findOne(CustomerUserEmailVerification, {\n token: tokenHashed,\n purpose,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n if (purpose === 'magic_link' && !(await isCustomerTenantActive(this.em, user?.tenantId))) return null\n\n const db = getKysely(this.em)\n const updateResult = await db\n .updateTable('customer_user_email_verifications' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n\n async verifyPasswordResetToken(token: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await this.em.findOne(CustomerUserPasswordReset, {\n token: tokenHashed,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n\n const db = getKysely(this.em)\n const updateResult = await db\n .updateTable('customer_user_password_resets' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n}\n"],
5
- "mappings": "AAEA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,8BAA8B;AAEvC,SAAS,UAAU,IAAgC;AACjD,SAAQ,GAAmD,UAAU;AACvE;AAEA,MAAM,4BAA4B,KAAK,KAAK,KAAK;AACjD,MAAM,oBAAoB,KAAK,KAAK;AACpC,MAAM,wBAAwB,KAAK,KAAK;AAEjC,MAAM,qBAAqB;AAAA,EAChC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,wBAAwB,QAAgB,UAAmC;AAC/E,UAAM,WAAW,oBAAoB;AACrC,UAAM,cAAc,UAAU,QAAQ;AACtC,UAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,yBAAyB;AACjE,UAAM,SAAS,KAAK,GAAG,OAAO,+BAA+B;AAAA,MAC3D,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,MACT;AAAA,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AAK,oBAAI,KAAK,CAAC,EAC1C,iBAAiB;AACpB,UAAM,WAAW,OAAO,cAAc,kBAAkB,CAAC;AACzD,QAAI,aAAa,EAAG,QAAO;AAE3B,UAAM,iBAAiB,OAAO,SAAS,WAAW,OAAO,KAAK;AAC9D,UAAM,mBAAmB,OAAO,SAAS,WAAW,KAAK,KAAK;AAC9D,WAAO,EAAE,QAAQ,gBAAgB,UAAU,iBAAiB;AAAA,EAC9D;AACF;",
4
+ "sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport type { Kysely } from 'kysely'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\nimport { EMAIL_VERIFICATION_TTL_MS } from '../lib/pendingSignup'\n\nfunction getKysely(em: EntityManager): Kysely<any> {\n return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()\n}\n\nconst MAGIC_LINK_TTL_MS = 15 * 60 * 1000 // 15 minutes\nconst PASSWORD_RESET_TTL_MS = 60 * 60 * 1000 // 60 minutes\n\nexport class CustomerTokenService {\n constructor(private em: EntityManager) {}\n\n async createEmailVerification(userId: string, tenantId: string, createdAt = new Date(), em = this.em): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS)\n const record = em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'email_verification',\n expiresAt,\n createdAt,\n } as any)\n await em.persist(record).flush()\n return rawToken\n }\n\n async createMagicLink(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + MAGIC_LINK_TTL_MS)\n const record = this.em.create(CustomerUserEmailVerification, {\n user: userId as any,\n token: tokenHashed,\n purpose: 'magic_link',\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async createPasswordReset(userId: string, tenantId: string): Promise<string> {\n const rawToken = generateSecureToken()\n const tokenHashed = hashToken(rawToken)\n const expiresAt = new Date(Date.now() + PASSWORD_RESET_TTL_MS)\n const record = this.em.create(CustomerUserPasswordReset, {\n user: userId as any,\n token: tokenHashed,\n expiresAt,\n createdAt: new Date(),\n } as any)\n await this.em.persist(record).flush()\n return rawToken\n }\n\n async verifyEmailToken(token: string, purpose: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await em.findOne(CustomerUserEmailVerification, {\n token: tokenHashed,\n purpose,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n if (purpose === 'magic_link' && !(await isCustomerTenantActive(em, user?.tenantId))) return null\n\n const db = getKysely(em)\n const updateResult = await db\n .updateTable('customer_user_email_verifications' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n\n async verifyPasswordResetToken(token: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {\n const tokenHashed = hashToken(token)\n const record = await em.findOne(CustomerUserPasswordReset, {\n token: tokenHashed,\n }, { populate: ['user'] })\n if (!record) return null\n if (record.usedAt) return null\n if (record.expiresAt.getTime() < Date.now()) return null\n\n const user = record.user as CustomerUser\n if (tenantId && user?.tenantId !== tenantId) return null\n\n const db = getKysely(em)\n const updateResult = await db\n .updateTable('customer_user_password_resets' as any)\n .set({ used_at: new Date() } as any)\n .where('id' as any, '=', record.id)\n .where('used_at' as any, 'is', null)\n .where('expires_at' as any, '>', new Date())\n .executeTakeFirst()\n const consumed = Number(updateResult?.numUpdatedRows ?? 0)\n if (consumed === 0) return null\n\n const resolvedUserId = typeof user === 'string' ? user : user.id\n const resolvedTenantId = typeof user === 'string' ? '' : user.tenantId\n return { userId: resolvedUserId, tenantId: resolvedTenantId }\n }\n}\n"],
5
+ "mappings": "AAEA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,8BAA8B;AACvC,SAAS,iCAAiC;AAE1C,SAAS,UAAU,IAAgC;AACjD,SAAQ,GAAmD,UAAU;AACvE;AAEA,MAAM,oBAAoB,KAAK,KAAK;AACpC,MAAM,wBAAwB,KAAK,KAAK;AAEjC,MAAM,qBAAqB;AAAA,EAChC,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,wBAAwB,QAAgB,UAAkB,YAAY,oBAAI,KAAK,GAAG,KAAK,KAAK,IAAqB;AACrH,UAAM,WAAW,oBAAoB;AACrC,UAAM,cAAc,UAAU,QAAQ;AACtC,UAAM,YAAY,IAAI,KAAK,UAAU,QAAQ,IAAI,yBAAyB;AAC1E,UAAM,SAAS,GAAG,OAAO,+BAA+B;AAAA,MACtD,MAAM;AAAA,MACN,OAAO;AAAA,MACP,SAAS;AAAA,MACT;AAAA,MACA;AAAA,IACF,CAAQ;AACR,UAAM,GAAG,QAAQ,MAAM,EAAE,MAAM;AAC/B,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,gBAAgB,QAAgB,UAAmC;AACvE,UAAM,WAAW,oBAAoB;AACrC,UAAM,cAAc,UAAU,QAAQ;AACtC,UAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,iBAAiB;AACzD,U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A,EAC9D;AACF;",
6
6
  "names": []
7
7
  }
@@ -10,7 +10,7 @@ class CustomerUserService {
10
10
  this.em = em;
11
11
  }
12
12
  async createUser(email, password, displayName, scope) {
13
- const passwordHash = await hash(password, BCRYPT_COST);
13
+ const passwordHash = password === null ? null : await hash(password, BCRYPT_COST);
14
14
  const emailHash = hashForLookup(email);
15
15
  const user = this.em.create(CustomerUser, {
16
16
  email: email.toLowerCase().trim(),