@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
@@ -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,YA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I,EAAG,QAAO;AAEpD,UAAM,OAAO,OAAO;AACpB,QAAI,YAAY,MAAM,aAAa,SAAU,QAAO;AAEpD,UAAM,KAAK,UAAU,KAAK,EAAE;AAC5B,UAAM,eAAe,MAAM,GACxB,YAAY,+BAAsC,EAClD,IAAI,EAAE,SAAS,oBAAI,KAAK,EAAE,CAAQ,EAClC,MAAM,MAAa,KAAK,OAAO,EAAE,EACjC,MAAM,WAAkB,MAAM,IAAI,EAClC,MAAM,cAAqB,KAAK,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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MAAM,IAAI,EAClC,MAAM,cAAqB,KAAK,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;",
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(),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/services/customerUserService.ts"],
4
- "sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst MAX_FAILED_ATTEMPTS = 5\nconst LOCKOUT_DURATION_MS = 15 * 60 * 1000 // 15 minutes\n\ntype CustomerUserLockoutDatabase = {\n customer_users: {\n id: string\n failed_login_attempts: number\n locked_until: Date | null\n }\n}\n\nexport class CustomerUserService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n email: string,\n password: string,\n displayName: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerUser> {\n const passwordHash = await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(email)\n const user = this.em.create(CustomerUser, {\n email: email.toLowerCase().trim(),\n emailHash,\n passwordHash,\n displayName,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isActive: true,\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any)\n return user as CustomerUser\n }\n\n async findByEmail(email: string, tenantId: string): Promise<CustomerUser | null> {\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n {\n emailHash: { $in: lookupHashCandidates(email) },\n tenantId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async findById(\n id: string,\n tenantId: string,\n organizationId?: string | null,\n ): Promise<CustomerUser | null> {\n const where: Record<string, unknown> = { id, tenantId, deletedAt: null }\n if (organizationId !== undefined) where.organizationId = organizationId\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n where as any,\n undefined,\n { tenantId, organizationId },\n )\n }\n\n async verifyPassword(user: CustomerUser, password: string): Promise<boolean> {\n if (!user.passwordHash) return false\n return compare(password, user.passwordHash)\n }\n\n async updateLastLoginAt(user: CustomerUser): Promise<void> {\n const now = new Date()\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n checkLockout(user: CustomerUser): boolean {\n if (!user.lockedUntil) return false\n if (user.lockedUntil.getTime() > Date.now()) return true\n return false\n }\n\n async incrementFailedAttempts(user: CustomerUser): Promise<void> {\n const lockedUntil = new Date(Date.now() + LOCKOUT_DURATION_MS)\n await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set((eb) => ({\n failed_login_attempts: eb('failed_login_attempts', '+', 1),\n locked_until: eb\n .case()\n .when('failed_login_attempts', '>=', MAX_FAILED_ATTEMPTS - 1)\n .then(eb.fn<Date>('greatest', [eb.ref('locked_until'), eb.val(lockedUntil)]))\n .else(eb.ref('locked_until'))\n .end(),\n }))\n .where('id', '=', user.id)\n .execute()\n }\n\n async resetFailedAttemptsUnlessLocked(user: CustomerUser): Promise<boolean> {\n const now = new Date()\n const row = await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set({ failed_login_attempts: 0, locked_until: null })\n .where('id', '=', user.id)\n .where((eb) => eb.or([eb('locked_until', 'is', null), eb('locked_until', '<=', now)]))\n .returning('id')\n .executeTakeFirst()\n return row !== undefined\n }\n\n async resetFailedAttempts(user: CustomerUser): Promise<void> {\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, {\n failedLoginAttempts: 0,\n lockedUntil: null,\n })\n }\n\n async updatePassword(user: CustomerUser, newPassword: string, em?: EntityManager): Promise<void> {\n const passwordHash = await hash(newPassword, BCRYPT_COST)\n await (em ?? this.em).nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, { passwordHash })\n user.passwordHash = passwordHash\n }\n\n // `display_name` is encrypted at rest. `nativeUpdate` issues raw SQL and fires none of the\n // flush hooks the tenant-encryption subscriber depends on, so writing it that way persists\n // plaintext PII into a ciphertext column (#3837). Assign it on the managed entity and flush\n // so `beforeUpdate` encrypts the value on its way to the database.\n async updateProfile(user: CustomerUser, data: { displayName?: string }): Promise<void> {\n if (data.displayName === undefined) return\n const managed = await findOneWithDecryption(\n this.em,\n CustomerUser,\n { id: user.id, tenantId: user.tenantId, organizationId: user.organizationId, deletedAt: null } as any,\n undefined,\n { tenantId: user.tenantId, organizationId: user.organizationId },\n )\n if (!managed) return\n managed.displayName = data.displayName\n await this.em.flush()\n user.displayName = data.displayName\n }\n\n async softDelete(\n userId: string,\n scope?: { tenantId: string; organizationId: string | null },\n ): Promise<void> {\n const where: Record<string, unknown> = { id: userId }\n if (scope) {\n where.tenantId = scope.tenantId\n where.organizationId = scope.organizationId\n }\n await this.em.nativeUpdate(CustomerUser, where, {\n deletedAt: new Date(),\n isActive: false,\n })\n }\n}\n"],
5
- "mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe,4BAA4B;AACpD,SAAS,6BAA6B;AAEtC,M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,KAAK,GAAG,GAAG;AAAA,MACxD,qBAAqB;AAAA,MACrB,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,eAAe,MAAoB,aAAqB,IAAmC;AAC/F,UAAM,eAAe,MAAM,KAAK,aAAa,WAAW;AACxD,WAAO,MAAM,KAAK,IAAI,aAAa,cAAc;AAAA,MAC/C,IAAI,KAAK;AAAA,MACT,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK;AAAA,IACvB,GAAG,EAAE,aAAa,CAAC;AACnB,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,MAAM,cAAc,MAAoB,MAA+C;AACrF,QAAI,KAAK,gBAAgB,OAAW;AACpC,UAAM,UAAU,MAAM;AAAA,MACpB,KAAK;AAAA,MACL;AAAA,MACA,EAAE,IAAI,KAAK,IAAI,UAAU,KAAK,UAAU,gBAAgB,KAAK,gBAAgB,WAAW,KAAK;AAAA,MAC7F;AAAA,MACA,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,eAAe;AAAA,IACjE;AACA,QAAI,CAAC,QAAS;AACd,YAAQ,cAAc,KAAK;AAC3B,UAAM,KAAK,GAAG,MAAM;AACpB,SAAK,cAAc,KAAK;AAAA,EAC1B;AAAA,EAEA,MAAM,WACJ,QACA,OACe;AACf,UAAM,QAAiC,EAAE,IAAI,OAAO;AACpD,QAAI,OAAO;AACT,YAAM,WAAW,MAAM;AACvB,YAAM,iBAAiB,MAAM;AAAA,IAC/B;AACA,UAAM,KAAK,GAAG,aAAa,cAAc,OAAO;AAAA,MAC9C,WAAW,oBAAI,KAAK;AAAA,MACpB,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACF;",
4
+ "sourcesContent": ["import { EntityManager } from '@mikro-orm/postgresql'\nimport { hash, compare } from 'bcryptjs'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst BCRYPT_COST = 10\nconst MAX_FAILED_ATTEMPTS = 5\nconst LOCKOUT_DURATION_MS = 15 * 60 * 1000 // 15 minutes\n\ntype CustomerUserLockoutDatabase = {\n customer_users: {\n id: string\n failed_login_attempts: number\n locked_until: Date | null\n }\n}\n\nexport class CustomerUserService {\n constructor(private em: EntityManager) {}\n\n async createUser(\n email: string,\n password: string | null,\n displayName: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<CustomerUser> {\n const passwordHash = password === null ? null : await hash(password, BCRYPT_COST)\n const emailHash = hashForLookup(email)\n const user = this.em.create(CustomerUser, {\n email: email.toLowerCase().trim(),\n emailHash,\n passwordHash,\n displayName,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n isActive: true,\n failedLoginAttempts: 0,\n createdAt: new Date(),\n } as any)\n return user as CustomerUser\n }\n\n async findByEmail(email: string, tenantId: string): Promise<CustomerUser | null> {\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n {\n emailHash: { $in: lookupHashCandidates(email) },\n tenantId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId },\n )\n }\n\n async findById(\n id: string,\n tenantId: string,\n organizationId?: string | null,\n ): Promise<CustomerUser | null> {\n const where: Record<string, unknown> = { id, tenantId, deletedAt: null }\n if (organizationId !== undefined) where.organizationId = organizationId\n return findOneWithDecryption(\n this.em,\n CustomerUser,\n where as any,\n undefined,\n { tenantId, organizationId },\n )\n }\n\n async verifyPassword(user: CustomerUser, password: string): Promise<boolean> {\n if (!user.passwordHash) return false\n return compare(password, user.passwordHash)\n }\n\n async updateLastLoginAt(user: CustomerUser): Promise<void> {\n const now = new Date()\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, { lastLoginAt: now })\n user.lastLoginAt = now\n }\n\n checkLockout(user: CustomerUser): boolean {\n if (!user.lockedUntil) return false\n if (user.lockedUntil.getTime() > Date.now()) return true\n return false\n }\n\n async incrementFailedAttempts(user: CustomerUser): Promise<void> {\n const lockedUntil = new Date(Date.now() + LOCKOUT_DURATION_MS)\n await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set((eb) => ({\n failed_login_attempts: eb('failed_login_attempts', '+', 1),\n locked_until: eb\n .case()\n .when('failed_login_attempts', '>=', MAX_FAILED_ATTEMPTS - 1)\n .then(eb.fn<Date>('greatest', [eb.ref('locked_until'), eb.val(lockedUntil)]))\n .else(eb.ref('locked_until'))\n .end(),\n }))\n .where('id', '=', user.id)\n .execute()\n }\n\n async resetFailedAttemptsUnlessLocked(user: CustomerUser): Promise<boolean> {\n const now = new Date()\n const row = await this.em.getKysely<CustomerUserLockoutDatabase>()\n .updateTable('customer_users')\n .set({ failed_login_attempts: 0, locked_until: null })\n .where('id', '=', user.id)\n .where((eb) => eb.or([eb('locked_until', 'is', null), eb('locked_until', '<=', now)]))\n .returning('id')\n .executeTakeFirst()\n return row !== undefined\n }\n\n async resetFailedAttempts(user: CustomerUser): Promise<void> {\n await this.em.nativeUpdate(CustomerUser, { id: user.id }, {\n failedLoginAttempts: 0,\n lockedUntil: null,\n })\n }\n\n async updatePassword(user: CustomerUser, newPassword: string, em?: EntityManager): Promise<void> {\n const passwordHash = await hash(newPassword, BCRYPT_COST)\n await (em ?? this.em).nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, { passwordHash })\n user.passwordHash = passwordHash\n }\n\n // `display_name` is encrypted at rest. `nativeUpdate` issues raw SQL and fires none of the\n // flush hooks the tenant-encryption subscriber depends on, so writing it that way persists\n // plaintext PII into a ciphertext column (#3837). Assign it on the managed entity and flush\n // so `beforeUpdate` encrypts the value on its way to the database.\n async updateProfile(user: CustomerUser, data: { displayName?: string }): Promise<void> {\n if (data.displayName === undefined) return\n const managed = await findOneWithDecryption(\n this.em,\n CustomerUser,\n { id: user.id, tenantId: user.tenantId, organizationId: user.organizationId, deletedAt: null } as any,\n undefined,\n { tenantId: user.tenantId, organizationId: user.organizationId },\n )\n if (!managed) return\n managed.displayName = data.displayName\n await this.em.flush()\n user.displayName = data.displayName\n }\n\n async softDelete(\n userId: string,\n scope?: { tenantId: string; organizationId: string | null },\n ): Promise<void> {\n const where: Record<string, unknown> = { id: userId }\n if (scope) {\n where.tenantId = scope.tenantId\n where.organizationId = scope.organizationId\n }\n await this.em.nativeUpdate(CustomerUser, where, {\n deletedAt: new Date(),\n isActive: false,\n })\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,MAAM,eAAe;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,eAAe,4BAA4B;AACpD,SAAS,6BAA6B;AAEtC,MAAM,cAAc;AACpB,MAAM,sBAAsB;AAC5B,MAAM,sBAAsB,KAAK,KAAK;AAU/B,MAAM,oBAAoB;AAAA,EAC/B,YAAoB,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAExC,MAAM,WACJ,OACA,UACA,aACA,OACuB;AACvB,UAAM,eAAe,aAAa,OAAO,OAAO,MAAM,KAAK,UAAU,WAAW;AAChF,UAAM,YAAY,cAAc,KAAK;AACrC,UAAM,OAAO,KAAK,GAAG,OAAO,cAAc;AAAA,MACxC,OAAO,MAAM,YAAY,EAAE,KAAK;AAAA,MAChC;AAAA,MACA;AAAA,MACA;AAAA,MACA,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,UAAU;AAAA,MACV,qBAAqB;AAAA,MACrB,WAAW,oBAAI,KAAK;AAAA,IACtB,CAAQ;AACR,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,YAAY,OAAe,UAAgD;AAC/E,WAAO;AAAA,MACL,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,WAAW,EAAE,KAAK,qBAAqB,KAAK,EAAE;AAAA,QAC9C;AAAA,QACA,WAAW;AAAA,MACb;AAAA,MACA;AAAA,MACA,EAAE,SAAS;AAAA,IACb;AAAA,EACF;AAAA,EAEA,MAAM,SACJ,IACA,UACA,gBA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MAAM,WACJ,QACA,OACe;AACf,UAAM,QAAiC,EAAE,IAAI,OAAO;AACpD,QAAI,OAAO;AACT,YAAM,WAAW,MAAM;AACvB,YAAM,iBAAiB,MAAM;AAAA,IAC/B;AACA,UAAM,KAAK,GAAG,aAAa,cAAc,OAAO;AAAA,MAC9C,WAAW,oBAAI,KAAK;AAAA,MACpB,UAAU;AAAA,IACZ,CAAC;AAAA,EACH;AACF;",
6
6
  "names": []
7
7
  }
@@ -2,6 +2,7 @@ import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/
2
2
  import { findWithDecryption, findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
3
3
  import { resolveOwnedCompanyForPerson } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
4
4
  import { createLogger } from "@open-mercato/shared/lib/logger";
5
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
5
6
  const logger = createLogger("customer_accounts").child({ component: "auto-link-crm" });
6
7
  const metadata = {
7
8
  event: "customer_accounts.user.created",
@@ -10,78 +11,70 @@ const metadata = {
10
11
  };
11
12
  async function handle(payload, ctx) {
12
13
  const data = payload;
13
- const userId = data?.id;
14
+ const userId = data?.userId ?? data?.id;
14
15
  const tenantId = data?.tenantId;
15
16
  const organizationId = data?.organizationId;
16
17
  if (!userId || !tenantId) return;
17
18
  const em = ctx.resolve("em");
18
19
  try {
19
- const user = await findOneWithDecryption(em, CustomerUser, { id: userId, tenantId, deletedAt: null }, void 0, { tenantId, organizationId });
20
+ const user = await findOneWithDecryption(em, CustomerUser, {
21
+ id: userId,
22
+ tenantId,
23
+ ...organizationId ? { organizationId } : {},
24
+ deletedAt: null
25
+ }, void 0, { tenantId, organizationId });
20
26
  if (!user) return;
27
+ if (!user.emailVerifiedAt || !user.isActive) return;
21
28
  const { CustomerEntity } = await import("@open-mercato/core/modules/customers/data/entities");
22
29
  const ownScope = { tenantId, organizationId: user.organizationId };
23
- if (user.customerEntityId) {
30
+ let personEntityId = user.personEntityId ?? null;
31
+ let customerEntityId = user.customerEntityId ?? null;
32
+ if (customerEntityId) {
24
33
  const linked = await findOneWithDecryption(
25
34
  em,
26
35
  CustomerEntity,
27
- { id: user.customerEntityId, tenantId, organizationId: user.organizationId, deletedAt: null },
36
+ { id: customerEntityId, ...ownScope, deletedAt: null },
28
37
  void 0,
29
- { tenantId, organizationId }
38
+ ownScope
30
39
  );
31
- if (!linked) {
32
- await em.nativeUpdate(
33
- CustomerUser,
34
- { id: userId, tenantId, organizationId: user.organizationId },
35
- { customerEntityId: null }
36
- );
37
- user.customerEntityId = null;
38
- } else if (linked.kind === "person") {
39
- const replacement = await resolveOwnedCompanyForPerson(em, user.customerEntityId, ownScope);
40
- await em.nativeUpdate(
41
- CustomerUser,
42
- { id: userId, tenantId, organizationId: user.organizationId },
43
- { customerEntityId: replacement }
44
- );
45
- user.customerEntityId = replacement;
40
+ if (!linked) customerEntityId = null;
41
+ else if (linked.kind === "person") {
42
+ customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope);
46
43
  }
47
44
  }
48
- if (user.personEntityId) {
49
- if (user.customerEntityId) return;
50
- const recovered = await resolveOwnedCompanyForPerson(em, user.personEntityId, ownScope);
51
- if (recovered) {
52
- await em.nativeUpdate(
53
- CustomerUser,
54
- { id: userId, tenantId, organizationId: user.organizationId },
55
- { customerEntityId: recovered }
45
+ if (!personEntityId) {
46
+ const email = user.email?.toLowerCase().trim();
47
+ if (email) {
48
+ const personEntities = await findWithDecryption(
49
+ em,
50
+ CustomerEntity,
51
+ { ...ownScope, kind: "person", deletedAt: null },
52
+ { limit: 500 },
53
+ ownScope
56
54
  );
55
+ personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null;
57
56
  }
58
- return;
59
57
  }
60
- const email = (data?.email ? data.email : user.email)?.toLowerCase().trim();
61
- if (!email) return;
62
- const personEntities = await findWithDecryption(
63
- em,
64
- CustomerEntity,
65
- { tenantId, organizationId: user.organizationId, kind: "person", deletedAt: null },
66
- { limit: 500 },
67
- { tenantId, organizationId }
68
- );
69
- const matchingEntity = personEntities.find(
70
- (e) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email
71
- );
72
- if (!matchingEntity) return;
73
- const companyEntityId = await resolveOwnedCompanyForPerson(em, matchingEntity.id, ownScope);
74
- const updates = { personEntityId: matchingEntity.id };
75
- if (companyEntityId) {
76
- updates.customerEntityId = companyEntityId;
58
+ if (personEntityId && !customerEntityId) {
59
+ customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope);
77
60
  }
78
- await em.nativeUpdate(
79
- CustomerUser,
80
- { id: userId, tenantId, organizationId: user.organizationId },
81
- updates
82
- );
61
+ const updates = {};
62
+ if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId;
63
+ if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId;
64
+ if (!Object.keys(updates).length) return;
65
+ await em.nativeUpdate(CustomerUser, {
66
+ id: userId,
67
+ ...ownScope,
68
+ emailHash: user.emailHash,
69
+ emailVerifiedAt: { $ne: null },
70
+ deletedAt: null,
71
+ isActive: true,
72
+ personEntityId: user.personEntityId ?? null,
73
+ customerEntityId: user.customerEntityId ?? null
74
+ }, updates);
83
75
  } catch (err) {
84
76
  logger.error("Failed to link customer user to CRM person", { err });
77
+ getTelemetryRuntime()?.reportError(err, { module: "customer_accounts", code: "customer_accounts.crm_link_failed" });
85
78
  }
86
79
  }
87
80
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrm.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })\n\nexport const metadata = {\n event: 'customer_accounts.user.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n const data = payload as Record<string, unknown>\n const userId = data?.id as string\n const tenantId = data?.tenantId as string\n const organizationId = data?.organizationId as string | undefined\n if (!userId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const user = await findOneWithDecryption(em, CustomerUser, { id: userId, tenantId, deletedAt: null }, undefined, { tenantId, organizationId })\n if (!user) return\n\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n\n // Every lookup and write below normalizes against the user's OWN org, not just\n // the tenant: customerEntityId is the portal's company scope key (portal user\n // and invite routes filter on it), so adopting an entity from another org would\n // widen the user's portal access instead of repairing it.\n const ownScope = { tenantId, organizationId: user.organizationId }\n\n // Defensive normalization for NEW users only \u2014 this subscriber runs on\n // `customer_accounts.user.created`, which is never re-emitted for an existing\n // row. customerEntityId is the CRM company FK, and earlier invite flows (#4362)\n // could poison it with a person entity id, which then breaks every later user\n // edit (\"Company not found\"). If the linked entity is a person (not a company)\n // or sits outside the user's org, drop it \u2014 or recover the person's real company\n // from their profile. Correct company links are left untouched. Rows created\n // before this change keep their bad FK; see #4473 for the backfill.\n if (user.customerEntityId) {\n const linked = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: user.customerEntityId, tenantId, organizationId: user.organizationId, deletedAt: null } as any,\n undefined,\n { tenantId, organizationId },\n ) as any\n if (!linked) {\n // Not resolvable inside the user's own org \u2014 a cross-org (or deleted)\n // entity. Clear it rather than leave it: this FK is the portal scope key.\n await em.nativeUpdate(\n CustomerUser,\n { id: userId, tenantId, organizationId: user.organizationId },\n { customerEntityId: null },\n )\n user.customerEntityId = null\n } else if (linked.kind === 'person') {\n // Only adopt a recovered company that is itself in the user's org.\n const replacement = await resolveOwnedCompanyForPerson(em, user.customerEntityId, ownScope)\n await em.nativeUpdate(\n CustomerUser,\n { id: userId, tenantId, organizationId: user.organizationId },\n { customerEntityId: replacement },\n )\n user.customerEntityId = replacement\n }\n }\n\n // A user invited from a CRM person card arrives with personEntityId already\n // set, so the email-matching path below never runs for it. Derive the company\n // FK from that person's own profile instead of leaving it null forever \u2014 the\n // portal Users page, portal invitations, and the company detail \"Portal users\"\n // group all key off customerEntityId (#4362).\n if (user.personEntityId) {\n if (user.customerEntityId) return\n const recovered = await resolveOwnedCompanyForPerson(em, user.personEntityId, ownScope)\n if (recovered) {\n await em.nativeUpdate(\n CustomerUser,\n { id: userId, tenantId, organizationId: user.organizationId },\n { customerEntityId: recovered },\n )\n }\n return\n }\n\n const email = (data?.email ? (data.email as string) : user.email)?.toLowerCase().trim()\n if (!email) return\n\n // Scope the candidate lookup to the user's own org. The fifth argument is a\n // decryption scope, not a filter, so without organizationId in the `where`\n // this matches people across every org in the tenant and writes a cross-org\n // link that the normalization block above just cleared.\n const personEntities = await findWithDecryption(\n em,\n CustomerEntity,\n { tenantId, organizationId: user.organizationId, kind: 'person', deletedAt: null } as any,\n { limit: 500 } as any,\n { tenantId, organizationId },\n )\n\n const matchingEntity = personEntities.find(\n (e: any) => e.primaryEmail && e.primaryEmail.toLowerCase().trim() === email,\n ) as any\n\n if (!matchingEntity) return\n\n const companyEntityId = await resolveOwnedCompanyForPerson(em, matchingEntity.id, ownScope)\n\n const updates: Record<string, unknown> = { personEntityId: matchingEntity.id }\n if (companyEntityId) {\n updates.customerEntityId = companyEntityId\n }\n\n await em.nativeUpdate(\n CustomerUser,\n { id: userId, tenantId, organizationId: user.organizationId },\n updates,\n )\n } catch (err) {\n logger.error('Failed to link customer user to CRM person', { err })\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,oCAAoC;AAC7C,SAA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AK,mBAAmB;AAAA,MAC1B;AAAA,IACF;AAOA,QAAI,KAAK,gBAAgB;AACvB,UAAI,KAAK,iBAAkB;AAC3B,YAAM,YAAY,MAAM,6BAA6B,IAAI,KAAK,gBAAgB,QAAQ;AACtF,UAAI,WAAW;AACb,cAAM,GAAG;AAAA,UACP;AAAA,UACA,EAAE,IAAI,QAAQ,UAAU,gBAAgB,KAAK,eAAe;AAAA,UAC5D,EAAE,kBAAkB,UAAU;AAAA,QAChC;AAAA,MACF;AACA;AAAA,IACF;AAEA,UAAM,SAAS,MAAM,QAAS,KAAK,QAAmB,KAAK,QAAQ,YAAY,EAAE,KAAK;AACtF,QAAI,CAAC,MAAO;AAMZ,UAAM,iBAAiB,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,EAAE,UAAU,gBAAgB,KAAK,gBAAgB,MAAM,UAAU,WAAW,KAAK;AAAA,MACjF,EAAE,OAAO,IAAI;AAAA,MACb,EAAE,UAAU,eAAe;AAAA,IAC7B;AAEA,UAAM,iBAAiB,eAAe;AAAA,MACpC,CAAC,MAAW,EAAE,gBAAgB,EAAE,aAAa,YAAY,EAAE,KAAK,MAAM;AAAA,IACxE;AAEA,QAAI,CAAC,eAAgB;AAErB,UAAM,kBAAkB,MAAM,6BAA6B,IAAI,eAAe,IAAI,QAAQ;AAE1F,UAAM,UAAmC,EAAE,gBAAgB,eAAe,GAAG;AAC7E,QAAI,iBAAiB;AACnB,cAAQ,mBAAmB;AAAA,IAC7B;AAEA,UAAM,GAAG;AAAA,MACP;AAAA,MACA,EAAE,IAAI,QAAQ,UAAU,gBAAgB,KAAK,eAAe;AAAA,MAC5D;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAAA,EACpE;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm' })\n\nexport const metadata = {\n event: 'customer_accounts.user.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n const data = payload as Record<string, unknown>\n const userId = (data?.userId ?? data?.id) as string\n const tenantId = data?.tenantId as string\n const organizationId = data?.organizationId as string | undefined\n if (!userId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const user = await findOneWithDecryption(em, CustomerUser, {\n id: userId,\n tenantId,\n ...(organizationId ? { organizationId } : {}),\n deletedAt: null,\n }, undefined, { tenantId, organizationId })\n if (!user) return\n if (!user.emailVerifiedAt || !user.isActive) return\n\n const { CustomerEntity } = await import('@open-mercato/core/modules/customers/data/entities')\n\n // Every lookup and write below normalizes against the user's OWN org, not just\n // the tenant: customerEntityId is the portal's company scope key (portal user\n // and invite routes filter on it), so adopting an entity from another org would\n // widen the user's portal access instead of repairing it.\n const ownScope = { tenantId, organizationId: user.organizationId }\n\n let personEntityId = user.personEntityId ?? null\n let customerEntityId = user.customerEntityId ?? null\n if (customerEntityId) {\n const linked = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: customerEntityId, ...ownScope, deletedAt: null },\n undefined,\n ownScope,\n )\n if (!linked) customerEntityId = null\n else if (linked.kind === 'person') {\n customerEntityId = await resolveOwnedCompanyForPerson(em, linked.id, ownScope)\n }\n }\n\n if (!personEntityId) {\n const email = user.email?.toLowerCase().trim()\n if (email) {\n const personEntities = await findWithDecryption(\n em,\n CustomerEntity,\n { ...ownScope, kind: 'person', deletedAt: null },\n { limit: 500 },\n ownScope,\n )\n personEntityId = personEntities.find((person) => person.primaryEmail?.toLowerCase().trim() === email)?.id ?? null\n }\n }\n if (personEntityId && !customerEntityId) {\n customerEntityId = await resolveOwnedCompanyForPerson(em, personEntityId, ownScope)\n }\n\n const updates: Partial<CustomerUser> = {}\n if (personEntityId !== (user.personEntityId ?? null)) updates.personEntityId = personEntityId\n if (customerEntityId !== (user.customerEntityId ?? null)) updates.customerEntityId = customerEntityId\n if (!Object.keys(updates).length) return\n\n await em.nativeUpdate(CustomerUser, {\n id: userId,\n ...ownScope,\n emailHash: user.emailHash,\n emailVerifiedAt: { $ne: null },\n deletedAt: null,\n isActive: true,\n personEntityId: user.personEntityId ?? null,\n customerEntityId: user.customerEntityId ?? null,\n }, updates)\n } catch (err) {\n logger.error('Failed to link customer user to CRM person', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.crm_link_failed' })\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,oCAAoC;AAC7C,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAE9E,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,eAAO,OACL,SACA,KACe;AACf,QAAM,OAAO;AACb,QAAM,SAAU,MAAM,UAAU,MAAM;AACtC,QAAM,WAAW,MAAM;AACvB,QAAM,iBAAiB,MAAM;AAC7B,MAAI,CAAC,UAAU,CAAC,SAAU;AAE1B,QAAM,KAAK,IAAI,QAAuB,IAAI;AAE1C,MAAI;AACF,UAAM,OAAO,MAAM,sBAAsB,IAAI,cAAc;AAAA,MACzD,IAAI;AAAA,MACJ;AAAA,MACA,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC;AAAA,MAC3C,WAAW;AAAA,IACb,G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;AAElC,UAAM,GAAG,aAAa,cAAc;AAAA,MAClC,IAAI;AAAA,MACJ,GAAG;AAAA,MACH,WAAW,KAAK;AAAA,MAChB,iBAAiB,EAAE,KAAK,KAAK;AAAA,MAC7B,WAAW;AAAA,MACX,UAAU;AAAA,MACV,gBAAgB,KAAK,kBAAkB;AAAA,MACvC,kBAAkB,KAAK,oBAAoB;AAAA,IAC7C,GAAG,OAAO;AAAA,EACZ,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAClE,wBAAoB,GAAG,YAAY,KAAK,EAAE,QAAQ,qBAAqB,MAAM,oCAAoC,CAAC;AAAA,EACpH;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,12 @@
1
+ import autoLinkCrm from "./autoLinkCrm.js";
2
+ const metadata = {
3
+ event: "customer_accounts.email.verified",
4
+ persistent: true,
5
+ id: "customer_accounts:auto-link-crm-on-verification"
6
+ };
7
+ var autoLinkCrmOnVerification_default = autoLinkCrm;
8
+ export {
9
+ autoLinkCrmOnVerification_default as default,
10
+ metadata
11
+ };
12
+ //# sourceMappingURL=autoLinkCrmOnVerification.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts"],
4
+ "sourcesContent": ["import autoLinkCrm from './autoLinkCrm'\n\nexport const metadata = {\n event: 'customer_accounts.email.verified',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-on-verification',\n}\n\nexport default autoLinkCrm\n"],
5
+ "mappings": "AAAA,OAAO,iBAAiB;AAEjB,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,IAAO,oCAAQ;",
6
+ "names": []
7
+ }
@@ -58,10 +58,12 @@ async function handle(payload, ctx) {
58
58
  emailHash: { $in: emailHashes },
59
59
  ...ownScope,
60
60
  deletedAt: null,
61
+ emailVerifiedAt: { $ne: null },
62
+ isActive: true,
61
63
  personEntityId: null
62
64
  };
63
65
  const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, void 0, ownScope);
64
- if (customerUser) {
66
+ if (customerUser?.emailVerifiedAt && customerUser.isActive) {
65
67
  const updates = { personEntityId: entity.id, updatedAt: /* @__PURE__ */ new Date() };
66
68
  if (!customerUser.customerEntityId) {
67
69
  const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm-reverse' })\n\nexport const metadata = {\n event: 'customers.person.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-reverse',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n if (!payload || typeof payload !== 'object') return\n const data = payload as Record<string, unknown>\n const eventId = typeof data.id === 'string' ? data.id : undefined\n const tenantId = typeof data.tenantId === 'string' ? data.tenantId : undefined\n const organizationId = typeof data.organizationId === 'string' ? data.organizationId : undefined\n if (!eventId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const { CustomerEntity, CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const eventScope = { tenantId, ...(organizationId ? { organizationId } : {}) }\n\n let entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: eventId, ...eventScope, kind: 'person', deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!entity) {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { id: eventId, ...eventScope },\n undefined,\n eventScope,\n )\n const profileEntity: unknown = profile?.entity\n const personEntityId = typeof profileEntity === 'string' ? profileEntity : profile?.entity?.id\n if (personEntityId && profile?.organizationId) {\n const profileScope = { tenantId, organizationId: profile.organizationId }\n entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: personEntityId, ...profileScope, kind: 'person', deletedAt: null },\n undefined,\n profileScope,\n )\n }\n }\n\n if (!entity?.organizationId) return\n const ownScope = { tenantId, organizationId: entity.organizationId }\n const email = entity.primaryEmail\n if (!email) return\n\n const emailHashes = lookupHashCandidates(email.toLowerCase().trim())\n\n const userWhere = {\n emailHash: { $in: emailHashes },\n ...ownScope,\n deletedAt: null,\n personEntityId: null,\n }\n const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)\n\n if (customerUser) {\n const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }\n if (!customerUser.customerEntityId) {\n const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)\n if (companyEntityId) updates.customerEntityId = companyEntityId\n }\n const affected = await em.nativeUpdate(CustomerUser, {\n id: customerUser.id,\n ...userWhere,\n customerEntityId: customerUser.customerEntityId ?? null,\n }, updates)\n if (affected === 0) return\n }\n } catch (err) {\n logger.error('Failed to link CRM person to customer user', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.reverse_crm_link_failed' })\n }\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AACrC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,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IACF;AAEA,QAAI,CAAC,QAAQ,eAAgB;AAC7B,UAAM,WAAW,EAAE,UAAU,gBAAgB,OAAO,eAAe;AACnE,UAAM,QAAQ,OAAO;AACrB,QAAI,CAAC,MAAO;AAEZ,UAAM,cAAc,qBAAqB,MAAM,YAAY,EAAE,KAAK,CAAC;AAEnE,UAAM,YAAY;AAAA,MAChB,WAAW,EAAE,KAAK,YAAY;AAAA,MAC9B,GAAG;AAAA,MACH,WAAW;AAAA,MACX,gBAAgB;AAAA,IAClB;AACA,UAAM,eAAe,MAAM,sBAAsB,IAAI,cAAc,WAAW,QAAW,QAAQ;AAEjG,QAAI,cAAc;AAChB,YAAM,UAAiC,EAAE,gBAAgB,OAAO,IAAI,WAAW,oBAAI,KAAK,EAAE;AAC1F,UAAI,CAAC,aAAa,kBAAkB;AAClC,cAAM,kBAAkB,MAAM,6BAA6B,IAAI,OAAO,IAAI,QAAQ;AAClF,YAAI,gBAAiB,SAAQ,mBAAmB;AAAA,MAClD;AACA,YAAM,WAAW,MAAM,GAAG,aAAa,cAAc;AAAA,QACnD,IAAI,aAAa;AAAA,QACjB,GAAG;AAAA,QACH,kBAAkB,aAAa,oBAAoB;AAAA,MACrD,GAAG,OAAO;AACV,UAAI,aAAa,EAAG;AAAA,IACtB;AAAA,EACF,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAClE,wBAAoB,GAAG,YAAY,KAAK,EAAE,QAAQ,qBAAqB,MAAM,4CAA4C,CAAC;AAAA,EAC5H;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { resolveOwnedCompanyForPerson } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('customer_accounts').child({ component: 'auto-link-crm-reverse' })\n\nexport const metadata = {\n event: 'customers.person.created',\n persistent: true,\n id: 'customer_accounts:auto-link-crm-reverse',\n}\n\nexport default async function handle(\n payload: unknown,\n ctx: { resolve: <T = unknown>(name: string) => T; eventName?: string },\n): Promise<void> {\n if (!payload || typeof payload !== 'object') return\n const data = payload as Record<string, unknown>\n const eventId = typeof data.id === 'string' ? data.id : undefined\n const tenantId = typeof data.tenantId === 'string' ? data.tenantId : undefined\n const organizationId = typeof data.organizationId === 'string' ? data.organizationId : undefined\n if (!eventId || !tenantId) return\n\n const em = ctx.resolve<EntityManager>('em')\n\n try {\n const { CustomerEntity, CustomerPersonProfile } = await import('@open-mercato/core/modules/customers/data/entities')\n const eventScope = { tenantId, ...(organizationId ? { organizationId } : {}) }\n\n let entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: eventId, ...eventScope, kind: 'person', deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!entity) {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { id: eventId, ...eventScope },\n undefined,\n eventScope,\n )\n const profileEntity: unknown = profile?.entity\n const personEntityId = typeof profileEntity === 'string' ? profileEntity : profile?.entity?.id\n if (personEntityId && profile?.organizationId) {\n const profileScope = { tenantId, organizationId: profile.organizationId }\n entity = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: personEntityId, ...profileScope, kind: 'person', deletedAt: null },\n undefined,\n profileScope,\n )\n }\n }\n\n if (!entity?.organizationId) return\n const ownScope = { tenantId, organizationId: entity.organizationId }\n const email = entity.primaryEmail\n if (!email) return\n\n const emailHashes = lookupHashCandidates(email.toLowerCase().trim())\n\n const userWhere = {\n emailHash: { $in: emailHashes },\n ...ownScope,\n deletedAt: null,\n emailVerifiedAt: { $ne: null },\n isActive: true,\n personEntityId: null,\n }\n const customerUser = await findOneWithDecryption(em, CustomerUser, userWhere, undefined, ownScope)\n\n if (customerUser?.emailVerifiedAt && customerUser.isActive) {\n const updates: Partial<CustomerUser> = { personEntityId: entity.id, updatedAt: new Date() }\n if (!customerUser.customerEntityId) {\n const companyEntityId = await resolveOwnedCompanyForPerson(em, entity.id, ownScope)\n if (companyEntityId) updates.customerEntityId = companyEntityId\n }\n const affected = await em.nativeUpdate(CustomerUser, {\n id: customerUser.id,\n ...userWhere,\n customerEntityId: customerUser.customerEntityId ?? null,\n }, updates)\n if (affected === 0) return\n }\n } catch (err) {\n logger.error('Failed to link CRM person to customer user', { err })\n getTelemetryRuntime()?.reportError(err, { module: 'customer_accounts', code: 'customer_accounts.reverse_crm_link_failed' })\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,4BAA4B;AACrC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,wBAAwB,CAAC;AAEtF,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAEA,eAAO,OACL,SACA,KACe;AACf,MAAI,CAAC,WAAW,OAAO,YAAY,SAAU;AAC7C,QAAM,OAAO;AACb,QAAM,UAAU,OAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AACxD,QAAM,WAAW,OAAO,KAAK,aAAa,WAAW,KAAK,WAAW;AACrE,QAAM,iBAAiB,OAAO,KAAK,mBAAmB,WAAW,KAAK,iBAAiB;AACvF,MAAI,CAAC,WAAW,CAAC,SAAU;AAE3B,QAAM,KAAK,IAAI,QAAuB,IAAI;AAE1C,MAAI;AACF,UAAM,EAAE,gBAAgB,sBAAsB,IAAI,MAAM,OAAO,oDAAoD;AACnH,UAAM,aAAa,EAAE,UAAU,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC,EAAG;AAE7E,QAAI,SAAS,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kB,MAAM,6BAA6B,IAAI,OAAO,IAAI,QAAQ;AAClF,YAAI,gBAAiB,SAAQ,mBAAmB;AAAA,MAClD;AACA,YAAM,WAAW,MAAM,GAAG,aAAa,cAAc;AAAA,QACnD,IAAI,aAAa;AAAA,QACjB,GAAG;AAAA,QACH,kBAAkB,aAAa,oBAAoB;AAAA,MACrD,GAAG,OAAO;AACV,UAAI,aAAa,EAAG;AAAA,IACtB;AAAA,EACF,SAAS,KAAK;AACZ,WAAO,MAAM,8CAA8C,EAAE,IAAI,CAAC;AAClE,wBAAoB,GAAG,YAAY,KAAK,EAAE,QAAQ,qBAAqB,MAAM,4CAA4C,CAAC;AAAA,EAC5H;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,8 +1,10 @@
1
1
  import {
2
+ CustomerUser,
2
3
  CustomerUserEmailVerification,
3
4
  CustomerUserPasswordReset,
4
5
  CustomerUserInvitation
5
6
  } from "@open-mercato/core/modules/customer_accounts/data/entities";
7
+ import { pendingSignup, signupExpiryCutoff } from "../lib/pendingSignup.js";
6
8
  const metadata = {
7
9
  queue: "customer-accounts-cleanup-tokens",
8
10
  id: "customer_accounts:cleanup-expired-tokens",
@@ -11,6 +13,10 @@ const metadata = {
11
13
  async function handle(job, ctx) {
12
14
  const em = ctx.resolve("em");
13
15
  const now = /* @__PURE__ */ new Date();
16
+ await em.nativeUpdate(CustomerUser, {
17
+ ...pendingSignup,
18
+ createdAt: { $lte: signupExpiryCutoff(now) }
19
+ }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now });
14
20
  await em.nativeDelete(CustomerUserEmailVerification, {
15
21
  $or: [
16
22
  { expiresAt: { $lt: now }, usedAt: null },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customer_accounts/workers/cleanupExpiredTokens.ts"],
4
- "sourcesContent": ["import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n CustomerUserInvitation,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\n\nexport const metadata: WorkerMeta = {\n queue: 'customer-accounts-cleanup-tokens',\n id: 'customer_accounts:cleanup-expired-tokens',\n concurrency: 1,\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(job: QueuedJob, ctx: HandlerContext): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n const now = new Date()\n\n // Cleanup expired email verifications\n await em.nativeDelete(CustomerUserEmailVerification, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired password resets\n await em.nativeDelete(CustomerUserPasswordReset, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired/accepted/cancelled invitations\n await em.nativeDelete(CustomerUserInvitation, {\n $or: [\n { expiresAt: { $lt: now }, acceptedAt: null, cancelledAt: null },\n { acceptedAt: { $ne: null } },\n { cancelledAt: { $ne: null } },\n ],\n } as any)\n}\n"],
5
- "mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAMA,eAAO,OAA8B,KAAgB,KAAoC;AACvF,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,MAAM,oBAAI,KAAK;AAGrB,QAAM,GAAG,aAAa,+BAA+B;AAAA,IACnD,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,2BAA2B;AAAA,IAC/C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,wBAAwB;AAAA,IAC5C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,YAAY,MAAM,aAAa,KAAK;AAAA,MAC/D,EAAE,YAAY,EAAE,KAAK,KAAK,EAAE;AAAA,MAC5B,EAAE,aAAa,EAAE,KAAK,KAAK,EAAE;AAAA,IAC/B;AAAA,EACF,CAAQ;AACV;",
4
+ "sourcesContent": ["import type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerUser,\n CustomerUserEmailVerification,\n CustomerUserPasswordReset,\n CustomerUserInvitation,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'\n\nexport const metadata: WorkerMeta = {\n queue: 'customer-accounts-cleanup-tokens',\n id: 'customer_accounts:cleanup-expired-tokens',\n concurrency: 1,\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(job: QueuedJob, ctx: HandlerContext): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n const now = new Date()\n\n await em.nativeUpdate(CustomerUser, {\n ...pendingSignup,\n createdAt: { $lte: signupExpiryCutoff(now) },\n }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })\n\n // Cleanup expired email verifications\n await em.nativeDelete(CustomerUserEmailVerification, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired password resets\n await em.nativeDelete(CustomerUserPasswordReset, {\n $or: [\n { expiresAt: { $lt: now }, usedAt: null },\n { usedAt: { $ne: null } },\n ],\n } as any)\n\n // Cleanup expired/accepted/cancelled invitations\n await em.nativeDelete(CustomerUserInvitation, {\n $or: [\n { expiresAt: { $lt: now }, acceptedAt: null, cancelledAt: null },\n { acceptedAt: { $ne: null } },\n { cancelledAt: { $ne: null } },\n ],\n } as any)\n}\n"],
5
+ "mappings": "AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe,0BAA0B;AAE3C,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAMA,eAAO,OAA8B,KAAgB,KAAoC;AACvF,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,MAAM,oBAAI,KAAK;AAErB,QAAM,GAAG,aAAa,cAAc;AAAA,IAClC,GAAG;AAAA,IACH,WAAW,EAAE,MAAM,mBAAmB,GAAG,EAAE;AAAA,EAC7C,GAAG,EAAE,WAAW,KAAK,UAAU,OAAO,cAAc,MAAM,mBAAmB,IAAI,CAAC;AAGlF,QAAM,GAAG,aAAa,+BAA+B;AAAA,IACnD,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,2BAA2B;AAAA,IAC/C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,QAAQ,KAAK;AAAA,MACxC,EAAE,QAAQ,EAAE,KAAK,KAAK,EAAE;AAAA,IAC1B;AAAA,EACF,CAAQ;AAGR,QAAM,GAAG,aAAa,wBAAwB;AAAA,IAC5C,KAAK;AAAA,MACH,EAAE,WAAW,EAAE,KAAK,IAAI,GAAG,YAAY,MAAM,aAAa,KAAK;AAAA,MAC/D,EAAE,YAAY,EAAE,KAAK,KAAK,EAAE;AAAA,MAC5B,EAAE,aAAa,EAAE,KAAK,KAAK,EAAE;AAAA,IAC/B;AAAA,EACF,CAAQ;AACV;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,127 @@
1
+ "use client";
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ import { useCallback, useState, useEffect } from "react";
4
+ import { useSearchParams } from "next/navigation";
5
+ import Link from "next/link";
6
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
7
+ import { PasswordInput } from "@open-mercato/ui/primitives/password-input";
8
+ import { Label } from "@open-mercato/ui/primitives/label";
9
+ import { Button } from "@open-mercato/ui/primitives/button";
10
+ import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
11
+ import { EmptyState } from "@open-mercato/ui/primitives/empty-state";
12
+ import { SearchX } from "lucide-react";
13
+ import { Spinner } from "@open-mercato/ui/primitives/spinner";
14
+ import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
15
+ import { usePortalContext } from "@open-mercato/ui/portal/PortalContext";
16
+ function PortalPasswordForm({ params, verify = false, beforeForm, afterForm }) {
17
+ const t = useT();
18
+ const orgSlug = params.orgSlug;
19
+ const { tenant } = usePortalContext();
20
+ const searchParams = useSearchParams();
21
+ const [password, setPassword] = useState("");
22
+ const [confirmPassword, setConfirmPassword] = useState("");
23
+ const [error, setError] = useState(null);
24
+ const [success, setSuccess] = useState(false);
25
+ const [submitting, setSubmitting] = useState(false);
26
+ const token = searchParams.get("token");
27
+ const noTokenMessage = verify ? t("portal.verify.error.invalidToken", "Verification token is missing.") : t("portal.resetPassword.error.noToken", "Invalid or missing reset token.");
28
+ useEffect(() => {
29
+ if (!token) setError(noTokenMessage);
30
+ }, [token, noTokenMessage]);
31
+ const handleSubmit = useCallback(
32
+ async (event) => {
33
+ event.preventDefault();
34
+ setError(null);
35
+ if (!token) {
36
+ setError(noTokenMessage);
37
+ return;
38
+ }
39
+ if (password !== confirmPassword) {
40
+ setError(t("portal.resetPassword.error.passwordMismatch", "Passwords do not match."));
41
+ return;
42
+ }
43
+ if (password.length < 8) {
44
+ setError(t("portal.resetPassword.error.passwordTooShort", "Password must be at least 8 characters long."));
45
+ return;
46
+ }
47
+ setSubmitting(true);
48
+ try {
49
+ const endpoint = verify ? "/api/customer_accounts/email/verify" : "/api/customer_accounts/password/reset-confirm";
50
+ const result = await apiCall(endpoint, {
51
+ method: "POST",
52
+ headers: { "Content-Type": "application/json" },
53
+ body: JSON.stringify({ token, password })
54
+ });
55
+ if (result.ok && result.result?.ok) {
56
+ setSuccess(true);
57
+ return;
58
+ }
59
+ if (verify) {
60
+ setError(t("portal.verify.error.generic", "Email verification failed. Please try again."));
61
+ } else if (result.status === 400) {
62
+ setError(t("portal.resetPassword.error.invalidToken", "Invalid or expired reset token."));
63
+ } else {
64
+ setError(result.result?.error || t("portal.resetPassword.error.generic", "Password reset failed. Please try again."));
65
+ }
66
+ } catch {
67
+ setError(verify ? t("portal.verify.error.generic", "Email verification failed. Please try again.") : t("portal.resetPassword.error.generic", "Password reset failed. Please try again."));
68
+ } finally {
69
+ setSubmitting(false);
70
+ }
71
+ },
72
+ [token, password, confirmPassword, t, verify, noTokenMessage]
73
+ );
74
+ if (tenant.loading) {
75
+ return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center py-20", children: /* @__PURE__ */ jsx(Spinner, {}) });
76
+ }
77
+ if (tenant.error) {
78
+ return /* @__PURE__ */ jsx("div", { className: "mx-auto w-full max-w-md py-12", children: /* @__PURE__ */ jsx(
79
+ EmptyState,
80
+ {
81
+ variant: "subtle",
82
+ size: "lg",
83
+ icon: /* @__PURE__ */ jsx(SearchX, { className: "h-6 w-6", "aria-hidden": true }),
84
+ title: t("portal.org.invalid", "Organization not found.")
85
+ }
86
+ ) });
87
+ }
88
+ if (success) {
89
+ return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm", children: [
90
+ /* @__PURE__ */ jsxs("div", { className: "mb-8 text-center", children: [
91
+ /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: verify ? t("portal.verify.success.title", "Email verified") : t("portal.resetPassword.success.title", "Password Reset Complete") }),
92
+ /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: verify ? t("portal.verify.success.description", "Your email has been verified. You can now sign in to the portal.") : t("portal.resetPassword.success.description", "Your password has been successfully reset.") })
93
+ ] }),
94
+ /* @__PURE__ */ jsx(Alert, { children: /* @__PURE__ */ jsx(AlertDescription, { children: t("portal.resetPassword.success.message", "You can now sign in with your new password.") }) }),
95
+ /* @__PURE__ */ jsx("div", { className: "mt-6 text-center", children: /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.resetPassword.success.loginLink", "Go to Sign In") }) })
96
+ ] });
97
+ }
98
+ return /* @__PURE__ */ jsxs("div", { className: "mx-auto w-full max-w-sm", children: [
99
+ /* @__PURE__ */ jsxs("div", { className: "mb-8 text-center", children: [
100
+ /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: verify ? t("portal.verify.title", "Verify email") : t("portal.resetPassword.title", "Reset Password") }),
101
+ /* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.resetPassword.description", "Enter your new password below.") })
102
+ ] }),
103
+ beforeForm,
104
+ /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "flex flex-col gap-4", children: [
105
+ error ? /* @__PURE__ */ jsx(Alert, { status: "error", children: /* @__PURE__ */ jsx(AlertDescription, { children: error }) }) : null,
106
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
107
+ /* @__PURE__ */ jsx(Label, { htmlFor: "reset-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.resetPassword.password", "New Password") }),
108
+ /* @__PURE__ */ jsx(PasswordInput, { id: "reset-password", autoComplete: "new-password", required: true, placeholder: t("portal.resetPassword.password.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: password, onChange: (e) => setPassword(e.target.value), disabled: submitting || !token, className: "rounded-lg" })
109
+ ] }),
110
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1.5", children: [
111
+ /* @__PURE__ */ jsx(Label, { htmlFor: "confirm-password", className: "text-overline font-semibold uppercase tracking-wider text-muted-foreground/70", children: t("portal.resetPassword.confirmPassword", "Confirm New Password") }),
112
+ /* @__PURE__ */ jsx(PasswordInput, { id: "confirm-password", autoComplete: "new-password", required: true, placeholder: t("portal.resetPassword.confirmPassword.placeholder", "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"), value: confirmPassword, onChange: (e) => setConfirmPassword(e.target.value), disabled: submitting || !token, className: "rounded-lg" })
113
+ ] }),
114
+ /* @__PURE__ */ jsx(Button, { type: "submit", disabled: submitting || !token, className: "mt-1 w-full rounded-lg", children: verify ? t("portal.verify.submit", "Verify email and set password") : submitting ? t("portal.resetPassword.submitting", "Resetting password...") : t("portal.resetPassword.submit", "Reset Password") }),
115
+ /* @__PURE__ */ jsxs("p", { className: "text-center text-sm text-muted-foreground", children: [
116
+ verify ? null : t("portal.resetPassword.backToLogin", "Remember your password?"),
117
+ " ",
118
+ /* @__PURE__ */ jsx(Link, { href: `/${orgSlug}/portal/login`, className: "font-medium text-foreground underline underline-offset-4 hover:opacity-80", children: t("portal.resetPassword.loginLink", "Sign in") })
119
+ ] })
120
+ ] }),
121
+ afterForm
122
+ ] });
123
+ }
124
+ export {
125
+ PortalPasswordForm
126
+ };
127
+ //# sourceMappingURL=PasswordForm.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/modules/portal/frontend/%5BorgSlug%5D/portal/PasswordForm.tsx"],
4
+ "sourcesContent": ["\"use client\"\nimport { useCallback, useState, useEffect, type ReactNode } from 'react'\nimport { useSearchParams } from 'next/navigation'\nimport Link from 'next/link'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { PasswordInput } from '@open-mercato/ui/primitives/password-input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport { EmptyState } from '@open-mercato/ui/primitives/empty-state'\nimport { SearchX } from 'lucide-react'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\nimport { usePortalContext } from '@open-mercato/ui/portal/PortalContext'\n\ntype Props = {\n params: { orgSlug: string }\n verify?: boolean\n beforeForm?: ReactNode\n afterForm?: ReactNode\n}\n\nexport function PortalPasswordForm({ params, verify = false, beforeForm, afterForm }: Props) {\n const t = useT()\n const orgSlug = params.orgSlug\n const { tenant } = usePortalContext()\n const searchParams = useSearchParams()\n\n const [password, setPassword] = useState('')\n const [confirmPassword, setConfirmPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [success, setSuccess] = useState(false)\n const [submitting, setSubmitting] = useState(false)\n const token = searchParams.get('token')\n const noTokenMessage = verify\n ? t('portal.verify.error.invalidToken', 'Verification token is missing.')\n : t('portal.resetPassword.error.noToken', 'Invalid or missing reset token.')\n\n useEffect(() => {\n if (!token) setError(noTokenMessage)\n }, [token, noTokenMessage])\n\n const handleSubmit = useCallback(\n async (event: React.FormEvent) => {\n event.preventDefault()\n setError(null)\n\n if (!token) {\n setError(noTokenMessage)\n return\n }\n\n if (password !== confirmPassword) {\n setError(t('portal.resetPassword.error.passwordMismatch', 'Passwords do not match.'))\n return\n }\n\n if (password.length < 8) {\n setError(t('portal.resetPassword.error.passwordTooShort', 'Password must be at least 8 characters long.'))\n return\n }\n\n setSubmitting(true)\n try {\n const endpoint = verify ? '/api/customer_accounts/email/verify' : '/api/customer_accounts/password/reset-confirm'\n const result = await apiCall<{ ok: boolean; error?: string }>(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ token, password }),\n })\n\n if (result.ok && result.result?.ok) {\n setSuccess(true)\n return\n }\n\n if (verify) {\n setError(t('portal.verify.error.generic', 'Email verification failed. Please try again.'))\n } else if (result.status === 400) {\n setError(t('portal.resetPassword.error.invalidToken', 'Invalid or expired reset token.'))\n } else {\n setError(result.result?.error || t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))\n }\n } catch {\n setError(verify\n ? t('portal.verify.error.generic', 'Email verification failed. Please try again.')\n : t('portal.resetPassword.error.generic', 'Password reset failed. Please try again.'))\n } finally {\n setSubmitting(false)\n }\n },\n [token, password, confirmPassword, t, verify, noTokenMessage],\n )\n\n if (tenant.loading) {\n return <div className=\"flex items-center justify-center py-20\"><Spinner /></div>\n }\n\n if (tenant.error) {\n return (\n <div className=\"mx-auto w-full max-w-md py-12\">\n <EmptyState\n variant=\"subtle\"\n size=\"lg\"\n icon={<SearchX className=\"h-6 w-6\" aria-hidden />}\n title={t('portal.org.invalid', 'Organization not found.')}\n />\n </div>\n )\n }\n\n if (success) {\n return (\n <div className=\"mx-auto w-full max-w-sm\">\n <div className=\"mb-8 text-center\">\n <h1 className=\"text-2xl font-bold tracking-tight\">{verify\n ? t('portal.verify.success.title', 'Email verified')\n : t('portal.resetPassword.success.title', 'Password Reset Complete')}</h1>\n <p className=\"mt-1.5 text-sm text-muted-foreground\">{verify\n ? t('portal.verify.success.description', 'Your email has been verified. You can now sign in to the portal.')\n : t('portal.resetPassword.success.description', 'Your password has been successfully reset.')}</p>\n </div>\n\n <Alert>\n <AlertDescription>{t('portal.resetPassword.success.message', 'You can now sign in with your new password.')}</AlertDescription>\n </Alert>\n\n <div className=\"mt-6 text-center\">\n <Link href={`/${orgSlug}/portal/login`} className=\"font-medium text-foreground underline underline-offset-4 hover:opacity-80\">\n {t('portal.resetPassword.success.loginLink', 'Go to Sign In')}\n </Link>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"mx-auto w-full max-w-sm\">\n <div className=\"mb-8 text-center\">\n <h1 className=\"text-2xl font-bold tracking-tight\">{verify\n ? t('portal.verify.title', 'Verify email')\n : t('portal.resetPassword.title', 'Reset Password')}</h1>\n <p className=\"mt-1.5 text-sm text-muted-foreground\">{t('portal.resetPassword.description', 'Enter your new password below.')}</p>\n </div>\n\n {beforeForm}\n\n <form onSubmit={handleSubmit} className=\"flex flex-col gap-4\">\n {error ? (\n <Alert status=\"error\">\n <AlertDescription>{error}</AlertDescription>\n </Alert>\n ) : null}\n\n <div className=\"flex flex-col gap-1.5\">\n <Label htmlFor=\"reset-password\" className=\"text-overline font-semibold uppercase tracking-wider text-muted-foreground/70\">{t('portal.resetPassword.password', 'New Password')}</Label>\n <PasswordInput id=\"reset-password\" autoComplete=\"new-password\" required placeholder={t('portal.resetPassword.password.placeholder', '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022')} value={password} onChange={(e) => setPassword(e.target.value)} disabled={submitting || !token} className=\"rounded-lg\" />\n </div>\n\n <div className=\"flex flex-col gap-1.5\">\n <Label htmlFor=\"confirm-password\" className=\"text-overline font-semibold uppercase tracking-wider text-muted-foreground/70\">{t('portal.resetPassword.confirmPassword', 'Confirm New Password')}</Label>\n <PasswordInput id=\"confirm-password\" autoComplete=\"new-password\" required placeholder={t('portal.resetPassword.confirmPassword.placeholder', '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022')} value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} disabled={submitting || !token} className=\"rounded-lg\" />\n </div>\n\n <Button type=\"submit\" disabled={submitting || !token} className=\"mt-1 w-full rounded-lg\">\n {verify\n ? t('portal.verify.submit', 'Verify email and set password')\n : submitting ? t('portal.resetPassword.submitting', 'Resetting password...') : t('portal.resetPassword.submit', 'Reset Password')}\n </Button>\n\n <p className=\"text-center text-sm text-muted-foreground\">\n {verify ? null : t('portal.resetPassword.backToLogin', 'Remember your password?')}{' '}\n <Link href={`/${orgSlug}/portal/login`} className=\"font-medium text-foreground underline underline-offset-4 hover:opacity-80\">\n {t('portal.resetPassword.loginLink', 'Sign in')}\n </Link>\n </p>\n </form>\n\n {afterForm}\n </div>\n )\n}\n"],
5
+ "mappings": ";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