@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,8 +7,8 @@ import { CustomerTokenService } from '@open-mercato/core/modules/customer_accoun
7
7
  import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
8
8
  import { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'
9
9
  import { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'
10
- import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'
11
10
  import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
11
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'
12
12
  import { getClientIp } from '@open-mercato/shared/lib/ratelimit/helpers'
13
13
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
14
14
  import { isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'
@@ -39,21 +39,21 @@ export async function POST(req: Request) {
39
39
  const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService
40
40
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
41
41
 
42
- const result = await customerTokenService.verifyEmailToken(parsed.data.token, 'magic_link')
42
+ const result = await em.transactional(async (tx) => {
43
+ const identity = await customerTokenService.verifyEmailToken(parsed.data.token, 'magic_link', undefined, tx)
44
+ if (!identity) return null
45
+ return { account: await verifyCustomerEmail(tx, identity, customerSessionService) }
46
+ })
43
47
  if (!result) {
44
48
  return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
45
49
  }
46
50
 
47
- const user = await customerUserService.findById(result.userId, result.tenantId)
48
- if (!user || !user.isActive) {
51
+ if (!result.account) {
49
52
  return NextResponse.json({ ok: false, error: 'Account not found or deactivated' }, { status: 401 })
50
53
  }
51
54
 
52
- // Auto-verify email on magic link login
53
- if (!user.emailVerifiedAt) {
54
- await em.nativeUpdate(CustomerUser, { id: user.id }, { emailVerifiedAt: new Date() })
55
- user.emailVerifiedAt = new Date()
56
- }
55
+ const { user, newlyVerified } = result.account
56
+ if (newlyVerified) emitCustomerEmailVerified(user)
57
57
 
58
58
  await customerUserService.resetFailedAttempts(user)
59
59
  await customerUserService.updateLastLoginAt(user)
@@ -6,9 +6,9 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
6
  import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
7
7
  import { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'
8
8
  import { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'
9
- import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'
10
9
  import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
11
10
  import type { EntityManager } from '@mikro-orm/postgresql'
11
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'
12
12
 
13
13
  export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
14
14
 
@@ -30,26 +30,21 @@ export async function POST(req: Request) {
30
30
  const customerUserService = container.resolve('customerUserService') as CustomerUserService
31
31
  const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService
32
32
 
33
- const result = await customerTokenService.verifyPasswordResetToken(parsed.data.token)
33
+ const em = container.resolve('em') as EntityManager
34
+ const result = await em.transactional(async (tx) => {
35
+ const identity = await customerTokenService.verifyPasswordResetToken(parsed.data.token, undefined, tx)
36
+ if (!identity) return null
37
+ return verifyCustomerEmail(tx, identity, customerSessionService, {
38
+ password: parsed.data.password,
39
+ users: customerUserService,
40
+ reset: true,
41
+ })
42
+ })
34
43
  if (!result) {
35
44
  return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
36
45
  }
37
-
38
- const user = await customerUserService.findById(result.userId, result.tenantId)
39
- if (!user) {
40
- return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
41
- }
42
-
43
- const em = container.resolve('em') as EntityManager
44
- await em.transactional(async (trx) => {
45
- await customerUserService.updatePassword(user, parsed.data.password, trx)
46
- await customerSessionService.revokeAllUserSessions(user.id, trx)
47
- await trx.nativeUpdate(
48
- CustomerUser,
49
- { id: user.id, emailVerifiedAt: null },
50
- { emailVerifiedAt: new Date() },
51
- )
52
- })
46
+ const { user, newlyVerified } = result
47
+ if (newlyVerified) emitCustomerEmailVerified(user)
53
48
 
54
49
  void emitCustomerAccountsEvent('customer_accounts.password.changed', {
55
50
  userId: user.id,
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
4
4
  import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
5
+ import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
5
6
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
7
  import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
7
8
 
@@ -16,11 +17,13 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
16
17
  const container = await createRequestContainer()
17
18
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
18
19
 
19
- const notification = await em.findOne(Notification, {
20
- id: params.id,
21
- recipientUserId: auth.sub,
22
- tenantId: auth.tenantId,
23
- })
20
+ const notification = arePortalNotificationsAvailable(em)
21
+ ? await em.findOne(Notification, {
22
+ id: params.id,
23
+ recipientUserId: auth.sub,
24
+ tenantId: auth.tenantId,
25
+ })
26
+ : null
24
27
 
25
28
  if (!notification) {
26
29
  return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
4
4
  import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
5
+ import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
5
6
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
7
  import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
7
8
 
@@ -16,11 +17,13 @@ export async function PUT(req: Request, { params }: { params: { id: string } })
16
17
  const container = await createRequestContainer()
17
18
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
18
19
 
19
- const notification = await em.findOne(Notification, {
20
- id: params.id,
21
- recipientUserId: auth.sub,
22
- tenantId: auth.tenantId,
23
- })
20
+ const notification = arePortalNotificationsAvailable(em)
21
+ ? await em.findOne(Notification, {
22
+ id: params.id,
23
+ recipientUserId: auth.sub,
24
+ tenantId: auth.tenantId,
25
+ })
26
+ : null
24
27
 
25
28
  if (!notification) {
26
29
  return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
4
4
  import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
5
+ import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
5
6
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
7
  import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
7
8
 
@@ -15,6 +16,9 @@ export async function PUT(req: Request) {
15
16
 
16
17
  const container = await createRequestContainer()
17
18
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
19
+ if (!arePortalNotificationsAvailable(em)) {
20
+ return NextResponse.json({ ok: true, count: 0 })
21
+ }
18
22
 
19
23
  const now = new Date()
20
24
  const count = await em.nativeUpdate(Notification, {
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
4
4
  import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
5
+ import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
5
6
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
7
  import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
7
8
 
@@ -15,6 +16,9 @@ export async function GET(req: Request) {
15
16
 
16
17
  const container = await createRequestContainer()
17
18
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
19
+ if (!arePortalNotificationsAvailable(em)) {
20
+ return NextResponse.json({ ok: true, unreadCount: 0 })
21
+ }
18
22
 
19
23
  const unreadCount = await em.count(Notification, {
20
24
  recipientUserId: auth.sub,
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
2
2
  import { z } from 'zod'
3
3
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
4
4
  import { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'
5
+ import { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'
5
6
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
6
7
  import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
7
8
  import { toNotificationDto } from '@open-mercato/core/modules/notifications/lib/notificationMapper'
@@ -23,6 +24,9 @@ export async function GET(req: Request) {
23
24
 
24
25
  const container = await createRequestContainer()
25
26
  const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
27
+ if (!arePortalNotificationsAvailable(em)) {
28
+ return NextResponse.json({ ok: true, items: [], total: 0, page, pageSize })
29
+ }
26
30
 
27
31
  const where: Record<string, unknown> = {
28
32
  recipientUserId: auth.sub,
@@ -1,5 +1,6 @@
1
1
  import { NextResponse } from 'next/server'
2
2
  import { compare as bcryptCompare } from 'bcryptjs'
3
+ import { UniqueConstraintViolationException } from '@mikro-orm/core'
3
4
  import { z } from 'zod'
4
5
  import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
5
6
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
@@ -8,7 +9,7 @@ import { signupSchema } from '@open-mercato/core/modules/customer_accounts/data/
8
9
  import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
9
10
  import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
10
11
  import { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'
11
- import { CustomerRole, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'
12
+ import { CustomerRole, CustomerUser, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'
12
13
  import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
13
14
  import CustomerSignupVerificationEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerSignupVerificationEmail'
14
15
  import CustomerExistingAccountEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerExistingAccountEmail'
@@ -27,14 +28,14 @@ import {
27
28
  } from '@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext'
28
29
  import { urlForCustomerOrg } from '@open-mercato/core/modules/customer_accounts/lib/customerUrl'
29
30
  import { createLogger } from '@open-mercato/shared/lib/logger'
31
+ import { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'
30
32
 
31
33
  const logger = createLogger('customer_accounts').child({ component: 'signup' })
32
34
 
33
35
  export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
34
36
 
35
37
  // Precomputed bcrypt cost-10 hash of an unknowable random 32-byte input; used to equalize
36
- // response latency between the existing-user and new-user signup branches so the endpoint's
37
- // 202-for-both contract is not undone by a timing side channel.
38
+ // response latency between new and existing registrations.
38
39
  const TIMING_EQUALIZATION_HASH = '$2b$10$.F2A6UHFzk.d8trNdfqt4OLz05Nf3IOuMmN6VJKflhD4.rz.prR8i'
39
40
  function resolvePortalLoginUrl(baseUrl: string, organizationSlug?: string | null): string {
40
41
  return organizationSlug
@@ -114,9 +115,22 @@ export async function POST(req: Request) {
114
115
  return NextResponse.json({ ok: false, error: 'Registration could not be completed' }, { status: 400 })
115
116
  }
116
117
 
117
- const existing = await customerUserService.findByEmail(email, tenantId)
118
+ let existing = await customerUserService.findByEmail(email, tenantId)
119
+ await bcryptCompare(password ?? '', TIMING_EQUALIZATION_HASH)
120
+ const now = new Date()
121
+ const cutoff = signupExpiryCutoff(now)
122
+ if (existing?.isActive && !existing.emailVerifiedAt
123
+ && !existing.lastLoginAt && existing.createdAt <= cutoff) {
124
+ const retired = await em.nativeUpdate(CustomerUser, {
125
+ id: existing.id,
126
+ tenantId,
127
+ organizationId: existing.organizationId,
128
+ ...pendingSignup,
129
+ createdAt: { $lte: cutoff },
130
+ }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })
131
+ existing = retired === 1 ? null : await customerUserService.findByEmail(email, tenantId)
132
+ }
118
133
  if (existing) {
119
- await bcryptCompare(password, TIMING_EQUALIZATION_HASH)
120
134
  const existingOrg = await findOrganizationInTenant(em, existing.organizationId, tenantId)
121
135
  // Prefer the org's active custom domain when available; fall back to the
122
136
  // platform login URL preserved by `resolvePortalLoginUrl`.
@@ -154,25 +168,23 @@ export async function POST(req: Request) {
154
168
  return NextResponse.json({ ok: true }, { status: 202 })
155
169
  }
156
170
 
157
- const user = await customerUserService.createUser(email, password, displayName, { tenantId, organizationId })
158
-
159
- const defaultRole = await em.findOne(CustomerRole, {
160
- tenantId,
161
- isDefault: true,
162
- deletedAt: null,
171
+ const signupScope = { tenantId, organizationId }
172
+ const signup = await em.transactional(async (tx) => {
173
+ const defaultRole = await tx.findOne(CustomerRole, { tenantId, isDefault: true, deletedAt: null })
174
+ const user = await customerUserService.createUser(email, null, displayName, signupScope)
175
+ if (defaultRole) tx.persist(tx.create(CustomerUserRole, { user, role: defaultRole, createdAt: new Date() }))
176
+ await tx.persist(user).flush()
177
+ const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId, user.createdAt, tx)
178
+ return { user, verificationToken }
179
+ }).catch(async (error: unknown) => {
180
+ if (error instanceof UniqueConstraintViolationException
181
+ && (await customerUserService.findByEmail(email, tenantId))) {
182
+ return null
183
+ }
184
+ throw error
163
185
  })
164
- if (defaultRole) {
165
- const userRole = em.create(CustomerUserRole, {
166
- user,
167
- role: defaultRole,
168
- createdAt: new Date(),
169
- } as any)
170
- em.persist(userRole)
171
- }
172
-
173
- await em.persist(user).flush()
174
-
175
- const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId)
186
+ if (!signup) return NextResponse.json({ ok: true }, { status: 202 })
187
+ const { user, verificationToken } = signup
176
188
  let verifyUrl = resolvePortalVerifyUrl(baseUrl, verificationToken, orgRow.slug)
177
189
  try {
178
190
  verifyUrl = await urlForCustomerOrg(organizationId, `/verify?token=${encodeURIComponent(verificationToken)}`, {
@@ -229,7 +241,7 @@ const methodDoc: OpenApiMethodDoc = {
229
241
  tags: ['Customer Authentication'],
230
242
  requestBody: {
231
243
  schema: signupSchema,
232
- description: 'Signup payload with email, password, and display name.',
244
+ description: 'Signup payload with email and display name. Passwords are set during email verification.',
233
245
  },
234
246
  responses: [
235
247
  { status: 202, description: 'Signup accepted', schema: signupAcceptedSchema },
@@ -7,7 +7,7 @@ const displayNameField = z.string().min(1).max(255)
7
7
 
8
8
  export const signupSchema = z.object({
9
9
  email: emailField,
10
- password: passwordField,
10
+ password: passwordField.optional(),
11
11
  displayName: displayNameField,
12
12
  tenantId: z.string().uuid().optional(),
13
13
  organizationId: z.string().uuid().optional(),
@@ -22,6 +22,7 @@ export const loginSchema = z.object({
22
22
 
23
23
  export const emailVerifySchema = z.object({
24
24
  token: z.string().min(1).max(512),
25
+ password: passwordField.optional(),
25
26
  })
26
27
 
27
28
  export const passwordResetRequestSchema = z.object({
@@ -30,20 +30,19 @@ async function resolveSessionService(): Promise<
30
30
  return container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>
31
31
  }
32
32
 
33
- async function assertSessionStillActive(input: {
33
+ async function findSessionStillActive(input: {
34
34
  sessionId: string
35
35
  userId: string
36
36
  tenantId: string
37
37
  organizationId: string
38
- }): Promise<boolean> {
38
+ }) {
39
39
  try {
40
40
  const service = await resolveSessionService()
41
- const session = await service.findActiveSessionForClaims(input)
42
- return session !== null
41
+ return await service.findActiveSessionForClaims(input)
43
42
  } catch {
44
43
  // Fail closed: if we cannot verify the session, treat the token as revoked to prevent
45
44
  // replay of leaked JWTs when the backend is partially degraded.
46
- return false
45
+ return null
47
46
  }
48
47
  }
49
48
 
@@ -96,6 +95,7 @@ export async function validateUserState(
96
95
  tenantId: string,
97
96
  orgId: string,
98
97
  iat: unknown,
98
+ sessionCreatedAt?: Date,
99
99
  ): Promise<UserValidationResult> {
100
100
  const [{ createRequestContainer }, { CustomerUser }] = await Promise.all([
101
101
  import('@open-mercato/shared/lib/di/container'),
@@ -109,7 +109,8 @@ export async function validateUserState(
109
109
  if (!user) return { valid: false }
110
110
  if (user.deletedAt) return { valid: false }
111
111
  if (!user.isActive) return { valid: false }
112
- if (user.sessionsRevokedAt && typeof iat === 'number' && iat * 1000 < user.sessionsRevokedAt.getTime()) {
112
+ const issuedAt = sessionCreatedAt?.getTime() ?? (typeof iat === 'number' ? iat * 1000 : undefined)
113
+ if (user.sessionsRevokedAt && issuedAt !== undefined && issuedAt < user.sessionsRevokedAt.getTime()) {
113
114
  return { valid: false }
114
115
  }
115
116
  if (!(await isCustomerTenantActive(em, tenantId))) return { valid: false }
@@ -185,21 +186,22 @@ export async function getCustomerAuthFromRequest(req: Request): Promise<Customer
185
186
  // Every accepted token is re-checked for liveness, exactly like the SSR path does — a token
186
187
  // without a `sid` is checked against the customer's remaining sessions rather than skipped,
187
188
  // so session revocation is never structurally unreachable on the API path.
188
- const stillActive = sid
189
- ? await assertSessionStillActive({
189
+ const session = sid
190
+ ? await findSessionStillActive({
190
191
  sessionId: sid,
191
192
  userId,
192
193
  tenantId,
193
194
  organizationId,
194
195
  })
195
- : await assertUserStillHasActiveSession({ userId, tenantId, organizationId })
196
- if (!stillActive) return null
196
+ : null
197
+ if (sid ? !session : !(await assertUserStillHasActiveSession({ userId, tenantId, organizationId }))) return null
197
198
 
198
199
  const userState = await validateUserState(
199
200
  userId,
200
201
  tenantId,
201
202
  organizationId,
202
203
  payload.iat,
204
+ session?.createdAt,
203
205
  )
204
206
  if (!userState.valid || !userState.tenantId || !userState.organizationId) return null
205
207
 
@@ -20,19 +20,18 @@ const logger = createLogger('customer_accounts').child({ component: 'customer-au
20
20
 
21
21
  export type { CustomerAuthContext }
22
22
 
23
- async function assertSessionStillActive(input: {
23
+ async function findSessionStillActive(input: {
24
24
  sessionId: string
25
25
  userId: string
26
26
  tenantId: string
27
27
  organizationId: string
28
- }): Promise<boolean> {
28
+ }) {
29
29
  try {
30
30
  const container = await createRequestContainer()
31
31
  const service = container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>
32
- const session = await service.findActiveSessionForClaims(input)
33
- return session !== null
32
+ return await service.findActiveSessionForClaims(input)
34
33
  } catch {
35
- return false
34
+ return null
36
35
  }
37
36
  }
38
37
 
@@ -73,19 +72,20 @@ export async function getCustomerAuthFromCookies(
73
72
  // JWTs are rejected as if unauthenticated.
74
73
  return null
75
74
  }
76
- const stillActive = await assertSessionStillActive({
75
+ const session = await findSessionStillActive({
77
76
  sessionId: sid,
78
77
  userId,
79
78
  tenantId,
80
79
  organizationId,
81
80
  })
82
- if (!stillActive) return null
81
+ if (!session) return null
83
82
 
84
83
  const userState = await validateUserState(
85
84
  userId,
86
85
  tenantId,
87
86
  organizationId,
88
87
  payload.iat,
88
+ session.createdAt,
89
89
  )
90
90
  if (!userState.valid || !userState.tenantId || !userState.organizationId) return null
91
91
 
@@ -1,11 +1,21 @@
1
1
  import type { EntityManager } from '@mikro-orm/postgresql'
2
2
  import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
3
+ import { isRegisteredModuleEntity } from './moduleEntityRegistration'
3
4
 
4
5
  export type CustomerEntityScope = {
5
6
  tenantId: string | null | undefined
6
7
  organizationId: string | null | undefined
7
8
  }
8
9
 
10
+ async function getRegisteredCustomerEntity(em: EntityManager) {
11
+ const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')
12
+ return isRegisteredModuleEntity(em, CustomerEntity, 'customers.CustomerEntity') ? CustomerEntity : null
13
+ }
14
+
15
+ export async function isCustomerEntityRegistered(em: EntityManager): Promise<boolean> {
16
+ return (await getRegisteredCustomerEntity(em)) !== null
17
+ }
18
+
9
19
  /**
10
20
  * Confirms that a caller-supplied `customerEntityId` (the CRM company FK linked
11
21
  * onto a customer user) exists, is a company, is not soft-deleted, and belongs
@@ -57,6 +67,7 @@ export async function resolveOwnedCompanyForPerson(
57
67
  scope: CustomerEntityScope,
58
68
  ): Promise<string | null> {
59
69
  const { CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')
70
+ if (!isRegisteredModuleEntity(em, CustomerPersonProfile, 'customers.CustomerPersonProfile')) return null
60
71
  const profile = await em.findOne(CustomerPersonProfile as any, {
61
72
  entity: personEntityId,
62
73
  tenantId: scope.tenantId,
@@ -87,7 +98,8 @@ async function isOwnedEntityOfKind(
87
98
  kind: 'company' | 'person',
88
99
  scope: CustomerEntityScope,
89
100
  ): Promise<boolean> {
90
- const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')
101
+ const CustomerEntity = await getRegisteredCustomerEntity(em)
102
+ if (!CustomerEntity) return false
91
103
  const entity = await findOneWithDecryption(
92
104
  em,
93
105
  CustomerEntity,
@@ -0,0 +1,12 @@
1
+ import type { EntityCtor } from '@mikro-orm/core'
2
+ import type { EntityManager } from '@mikro-orm/postgresql'
3
+
4
+ export function isRegisteredModuleEntity<Entity>(
5
+ em: EntityManager,
6
+ entity: EntityCtor<Entity>,
7
+ qualifiedName: string,
8
+ ): boolean {
9
+ const registeredClass: (EntityCtor<Entity> & { entityName?: string }) | undefined =
10
+ em.getMetadata().find(entity)?.class
11
+ return registeredClass === entity || registeredClass?.entityName === qualifiedName
12
+ }
@@ -0,0 +1,12 @@
1
+ export const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000
2
+
3
+ export const pendingSignup = {
4
+ isActive: true,
5
+ emailVerifiedAt: null,
6
+ lastLoginAt: null,
7
+ deletedAt: null,
8
+ } as const
9
+
10
+ export function signupExpiryCutoff(now: Date): Date {
11
+ return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS)
12
+ }
@@ -0,0 +1,7 @@
1
+ import type { EntityManager } from '@mikro-orm/postgresql'
2
+ import { Notification } from '@open-mercato/core/modules/notifications/data/entities'
3
+ import { isRegisteredModuleEntity } from './moduleEntityRegistration'
4
+
5
+ export function arePortalNotificationsAvailable(em: EntityManager): boolean {
6
+ return isRegisteredModuleEntity(em, Notification, 'notifications.Notification')
7
+ }
@@ -0,0 +1,57 @@
1
+ import { LockMode } from '@mikro-orm/core'
2
+ import type { EntityManager } from '@mikro-orm/postgresql'
3
+ import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
4
+ import { CustomerUser } from '../data/entities'
5
+ import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
6
+ import type { CustomerSessionService } from '../services/customerSessionService'
7
+ import type { CustomerUserService } from '../services/customerUserService'
8
+ import { signupExpiryCutoff } from './pendingSignup'
9
+
10
+ export async function verifyCustomerEmail(
11
+ em: EntityManager,
12
+ identity: { userId: string; tenantId: string; organizationId?: string },
13
+ sessions: CustomerSessionService,
14
+ options?: { password: string; users: CustomerUserService; reset?: boolean },
15
+ ): Promise<{ user: CustomerUser; newlyVerified: boolean } | null> {
16
+ const { userId, tenantId, organizationId } = identity
17
+ const user = await findOneWithDecryption(
18
+ em,
19
+ CustomerUser,
20
+ { id: userId, tenantId, ...(organizationId ? { organizationId } : {}), deletedAt: null },
21
+ { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
22
+ { tenantId, organizationId },
23
+ )
24
+ if (!user?.isActive) return null
25
+
26
+ const now = new Date()
27
+ const newlyVerified = !user.emailVerifiedAt
28
+ if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null
29
+ if (!newlyVerified && !options) return { user, newlyVerified }
30
+ if (!newlyVerified && !options?.reset && user.passwordHash) {
31
+ return null
32
+ }
33
+
34
+ const scope = { id: user.id, tenantId, organizationId: user.organizationId }
35
+ if (options) {
36
+ await options.users.updatePassword(user, options.password, em)
37
+ }
38
+ if (newlyVerified) {
39
+ await em.nativeUpdate(CustomerUser, scope, {
40
+ emailVerifiedAt: now,
41
+ ...(options ? {} : { passwordHash: null }),
42
+ })
43
+ }
44
+ await sessions.revokeAllUserSessions(user.id, em)
45
+ return { user, newlyVerified }
46
+ }
47
+
48
+ export function emitCustomerEmailVerified(user: CustomerUser, verifiedBy?: string): void {
49
+ void emitCustomerAccountsEvent('customer_accounts.email.verified', {
50
+ id: user.id,
51
+ userId: user.id,
52
+ recipientUserId: user.id,
53
+ tenantId: user.tenantId,
54
+ organizationId: user.organizationId,
55
+ ...(verifiedBy ? { email: user.email, verifiedBy } : {}),
56
+ }).catch(() => undefined)
57
+ }
@@ -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'
14
16
 
15
17
  const BCRYPT_COST = 10
16
18
  const INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours
@@ -270,7 +272,20 @@ export class CustomerInvitationService {
270
272
  scope,
271
273
  )
272
274
  if (existingActiveUser) {
273
- throw new CustomerInvitationEmailConflictError(invitation.email)
275
+ if (existingActiveUser.organizationId !== scope.organizationId
276
+ || !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {
277
+ throw new CustomerInvitationEmailConflictError(invitation.email)
278
+ }
279
+ const retired = await transactionEm.nativeUpdate(CustomerUser, {
280
+ id: existingActiveUser.id,
281
+ ...scope,
282
+ ...pendingSignup,
283
+ }, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt })
284
+ if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email)
285
+ await transactionEm.nativeUpdate(CustomerUserSession, {
286
+ user: existingActiveUser.id,
287
+ deletedAt: null,
288
+ }, { deletedAt: acceptedAt })
274
289
  }
275
290
 
276
291
  const user = transactionEm.create(CustomerUser, {