@open-mercato/core 0.11.1-develop.8545.1.dd603570fd → 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 (70) 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/email/verify.js +11 -10
  5. package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
  6. package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
  7. package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
  8. package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
  9. package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
  10. package/dist/modules/customer_accounts/api/signup.js +33 -19
  11. package/dist/modules/customer_accounts/api/signup.js.map +3 -3
  12. package/dist/modules/customer_accounts/data/validators.js +3 -2
  13. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  14. package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
  15. package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
  16. package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
  17. package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
  18. package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
  19. package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
  20. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
  21. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
  22. package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
  23. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  24. package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
  25. package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
  26. package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
  27. package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
  28. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
  29. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
  30. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
  31. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
  32. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
  33. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  34. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
  35. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
  36. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
  37. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
  38. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
  39. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  40. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
  41. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  42. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
  43. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
  44. package/package.json +7 -7
  45. package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
  46. package/src/modules/customer_accounts/api/email/verify.ts +15 -11
  47. package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
  48. package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
  49. package/src/modules/customer_accounts/api/signup.ts +36 -24
  50. package/src/modules/customer_accounts/data/validators.ts +2 -1
  51. package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
  52. package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
  53. package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
  54. package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
  55. package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
  56. package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
  57. package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
  58. package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
  59. package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
  60. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
  61. package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
  62. package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
  63. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
  64. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
  65. package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
  66. package/src/modules/portal/i18n/de.json +2 -1
  67. package/src/modules/portal/i18n/en.json +2 -1
  68. package/src/modules/portal/i18n/es.json +2 -1
  69. package/src/modules/portal/i18n/ko.json +2 -1
  70. package/src/modules/portal/i18n/pl.json +2 -1
@@ -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,
@@ -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
 
@@ -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,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, {
@@ -7,30 +7,30 @@ import {
7
7
  } from '@open-mercato/core/modules/customer_accounts/data/entities'
8
8
  import { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'
9
9
  import { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'
10
+ import { EMAIL_VERIFICATION_TTL_MS } from '../lib/pendingSignup'
10
11
 
11
12
  function getKysely(em: EntityManager): Kysely<any> {
12
13
  return (em as unknown as { getKysely: () => Kysely<any> }).getKysely()
13
14
  }
14
15
 
15
- const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000 // 24 hours
16
16
  const MAGIC_LINK_TTL_MS = 15 * 60 * 1000 // 15 minutes
17
17
  const PASSWORD_RESET_TTL_MS = 60 * 60 * 1000 // 60 minutes
18
18
 
19
19
  export class CustomerTokenService {
20
20
  constructor(private em: EntityManager) {}
21
21
 
22
- async createEmailVerification(userId: string, tenantId: string): Promise<string> {
22
+ async createEmailVerification(userId: string, tenantId: string, createdAt = new Date(), em = this.em): Promise<string> {
23
23
  const rawToken = generateSecureToken()
24
24
  const tokenHashed = hashToken(rawToken)
25
- const expiresAt = new Date(Date.now() + EMAIL_VERIFICATION_TTL_MS)
26
- const record = this.em.create(CustomerUserEmailVerification, {
25
+ const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS)
26
+ const record = em.create(CustomerUserEmailVerification, {
27
27
  user: userId as any,
28
28
  token: tokenHashed,
29
29
  purpose: 'email_verification',
30
30
  expiresAt,
31
- createdAt: new Date(),
31
+ createdAt,
32
32
  } as any)
33
- await this.em.persist(record).flush()
33
+ await em.persist(record).flush()
34
34
  return rawToken
35
35
  }
36
36
 
@@ -63,9 +63,9 @@ export class CustomerTokenService {
63
63
  return rawToken
64
64
  }
65
65
 
66
- async verifyEmailToken(token: string, purpose: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {
66
+ async verifyEmailToken(token: string, purpose: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {
67
67
  const tokenHashed = hashToken(token)
68
- const record = await this.em.findOne(CustomerUserEmailVerification, {
68
+ const record = await em.findOne(CustomerUserEmailVerification, {
69
69
  token: tokenHashed,
70
70
  purpose,
71
71
  }, { populate: ['user'] })
@@ -75,9 +75,9 @@ export class CustomerTokenService {
75
75
 
76
76
  const user = record.user as CustomerUser
77
77
  if (tenantId && user?.tenantId !== tenantId) return null
78
- if (purpose === 'magic_link' && !(await isCustomerTenantActive(this.em, user?.tenantId))) return null
78
+ if (purpose === 'magic_link' && !(await isCustomerTenantActive(em, user?.tenantId))) return null
79
79
 
80
- const db = getKysely(this.em)
80
+ const db = getKysely(em)
81
81
  const updateResult = await db
82
82
  .updateTable('customer_user_email_verifications' as any)
83
83
  .set({ used_at: new Date() } as any)
@@ -93,9 +93,9 @@ export class CustomerTokenService {
93
93
  return { userId: resolvedUserId, tenantId: resolvedTenantId }
94
94
  }
95
95
 
96
- async verifyPasswordResetToken(token: string, tenantId?: string): Promise<{ userId: string; tenantId: string } | null> {
96
+ async verifyPasswordResetToken(token: string, tenantId?: string, em = this.em): Promise<{ userId: string; tenantId: string } | null> {
97
97
  const tokenHashed = hashToken(token)
98
- const record = await this.em.findOne(CustomerUserPasswordReset, {
98
+ const record = await em.findOne(CustomerUserPasswordReset, {
99
99
  token: tokenHashed,
100
100
  }, { populate: ['user'] })
101
101
  if (!record) return null
@@ -105,7 +105,7 @@ export class CustomerTokenService {
105
105
  const user = record.user as CustomerUser
106
106
  if (tenantId && user?.tenantId !== tenantId) return null
107
107
 
108
- const db = getKysely(this.em)
108
+ const db = getKysely(em)
109
109
  const updateResult = await db
110
110
  .updateTable('customer_user_password_resets' as any)
111
111
  .set({ used_at: new Date() } as any)
@@ -21,11 +21,11 @@ export class CustomerUserService {
21
21
 
22
22
  async createUser(
23
23
  email: string,
24
- password: string,
24
+ password: string | null,
25
25
  displayName: string,
26
26
  scope: { tenantId: string; organizationId: string },
27
27
  ): Promise<CustomerUser> {
28
- const passwordHash = await hash(password, BCRYPT_COST)
28
+ const passwordHash = password === null ? null : await hash(password, BCRYPT_COST)
29
29
  const emailHash = hashForLookup(email)
30
30
  const user = this.em.create(CustomerUser, {
31
31
  email: email.toLowerCase().trim(),