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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js +10 -30
  3. package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js.map +2 -2
  4. package/dist/modules/customer_accounts/api/admin/users/[id].js +10 -9
  5. package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
  6. package/dist/modules/customer_accounts/api/email/verify.js +11 -10
  7. package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
  8. package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
  9. package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
  10. package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
  11. package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
  12. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js +3 -2
  13. package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js.map +2 -2
  14. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js +3 -2
  15. package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js.map +2 -2
  16. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js +4 -0
  17. package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js.map +2 -2
  18. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js +4 -0
  19. package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js.map +2 -2
  20. package/dist/modules/customer_accounts/api/portal/notifications.js +4 -0
  21. package/dist/modules/customer_accounts/api/portal/notifications.js.map +2 -2
  22. package/dist/modules/customer_accounts/api/signup.js +33 -19
  23. package/dist/modules/customer_accounts/api/signup.js.map +3 -3
  24. package/dist/modules/customer_accounts/data/validators.js +3 -2
  25. package/dist/modules/customer_accounts/data/validators.js.map +2 -2
  26. package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
  27. package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
  28. package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
  29. package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
  30. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +12 -1
  31. package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +2 -2
  32. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js +8 -0
  33. package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js.map +7 -0
  34. package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
  35. package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
  36. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js +9 -0
  37. package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js.map +7 -0
  38. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
  39. package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
  40. package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
  41. package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
  42. package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
  43. package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
  44. package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
  45. package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
  46. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
  47. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
  48. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
  49. package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
  50. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
  51. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  52. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
  53. package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
  54. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
  55. package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
  56. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
  57. package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
  58. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
  59. package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
  60. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
  61. package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
  62. package/dist/modules/wms/index.js +1 -1
  63. package/dist/modules/wms/index.js.map +2 -2
  64. package/dist/modules/wms/setup.js +4 -1
  65. package/dist/modules/wms/setup.js.map +2 -2
  66. package/dist/modules/workflows/api/events/route.js +1 -1
  67. package/dist/modules/workflows/api/events/route.js.map +2 -2
  68. package/dist/modules/workflows/api/instances/[id]/events/route.js +1 -1
  69. package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
  70. package/dist/modules/workflows/api/instances/[id]/steps/route.js +1 -1
  71. package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +2 -2
  72. package/dist/modules/workflows/api/instances/failure-queue/route.js +1 -1
  73. package/dist/modules/workflows/api/instances/failure-queue/route.js.map +2 -2
  74. package/dist/modules/workflows/lib/event-logger.js +1 -1
  75. package/dist/modules/workflows/lib/event-logger.js.map +2 -2
  76. package/dist/modules/workflows/lib/work-inbox/user-task-source.js +1 -1
  77. package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +2 -2
  78. package/package.json +7 -7
  79. package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
  80. package/src/modules/customer_accounts/api/admin/users/[id].ts +10 -9
  81. package/src/modules/customer_accounts/api/email/verify.ts +15 -11
  82. package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
  83. package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
  84. package/src/modules/customer_accounts/api/portal/notifications/[id]/dismiss.ts +8 -5
  85. package/src/modules/customer_accounts/api/portal/notifications/[id]/read.ts +8 -5
  86. package/src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts +4 -0
  87. package/src/modules/customer_accounts/api/portal/notifications/unread-count.ts +4 -0
  88. package/src/modules/customer_accounts/api/portal/notifications.ts +4 -0
  89. package/src/modules/customer_accounts/api/signup.ts +36 -24
  90. package/src/modules/customer_accounts/data/validators.ts +2 -1
  91. package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
  92. package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
  93. package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +13 -1
  94. package/src/modules/customer_accounts/lib/moduleEntityRegistration.ts +12 -0
  95. package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
  96. package/src/modules/customer_accounts/lib/portalNotificationsAvailability.ts +7 -0
  97. package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
  98. package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
  99. package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
  100. package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
  101. package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
  102. package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
  103. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
  104. package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
  105. package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
  106. package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
  107. package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
  108. package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
  109. package/src/modules/portal/i18n/de.json +2 -1
  110. package/src/modules/portal/i18n/en.json +2 -1
  111. package/src/modules/portal/i18n/es.json +2 -1
  112. package/src/modules/portal/i18n/ko.json +2 -1
  113. package/src/modules/portal/i18n/pl.json +2 -1
  114. package/src/modules/wms/index.ts +1 -1
  115. package/src/modules/wms/setup.ts +4 -1
  116. package/src/modules/workflows/api/events/route.ts +1 -1
  117. package/src/modules/workflows/api/instances/[id]/events/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/[id]/steps/route.ts +3 -2
  119. package/src/modules/workflows/api/instances/failure-queue/route.ts +1 -1
  120. package/src/modules/workflows/lib/event-logger.ts +1 -1
  121. package/src/modules/workflows/lib/work-inbox/user-task-source.ts +3 -2
@@ -1,4 +1,4 @@
1
- [build:core] found 6670 entry points
1
+ [build:core] found 6677 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 276 entry points
4
4
  [build:core:generated] built successfully
@@ -2,9 +2,7 @@ import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
- import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
6
- import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
7
- import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
5
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from "../../../../lib/verifyCustomerEmail.js";
8
6
  const metadata = {};
9
7
  async function POST(req, { params }) {
10
8
  const auth = await getAuthFromRequest(req);
@@ -18,37 +16,19 @@ async function POST(req, { params }) {
18
16
  return NextResponse.json({ ok: false, error: "Insufficient permissions" }, { status: 403 });
19
17
  }
20
18
  const em = container.resolve("em");
21
- const user = await findOneWithDecryption(
22
- em,
23
- CustomerUser,
24
- {
25
- id: params.id,
26
- tenantId: auth.tenantId,
27
- organizationId: auth.orgId,
28
- deletedAt: null
29
- },
30
- void 0,
31
- { tenantId: auth.tenantId, organizationId: auth.orgId }
32
- );
33
- if (!user) {
19
+ if (!auth.tenantId || !auth.orgId) {
34
20
  return NextResponse.json({ ok: false, error: "User not found" }, { status: 404 });
35
21
  }
36
- if (user.emailVerifiedAt) {
22
+ const scope = { userId: params.id, tenantId: auth.tenantId, organizationId: auth.orgId };
23
+ const sessions = container.resolve("customerSessionService");
24
+ const result = await em.transactional((tx) => verifyCustomerEmail(tx, scope, sessions));
25
+ if (!result) {
26
+ return NextResponse.json({ ok: false, error: "User not found" }, { status: 404 });
27
+ }
28
+ if (!result.newlyVerified) {
37
29
  return NextResponse.json({ ok: true, alreadyVerified: true });
38
30
  }
39
- await em.nativeUpdate(CustomerUser, {
40
- id: user.id,
41
- tenantId: user.tenantId,
42
- organizationId: user.organizationId
43
- }, { emailVerifiedAt: /* @__PURE__ */ new Date() });
44
- void emitCustomerAccountsEvent("customer_accounts.email.verified", {
45
- id: user.id,
46
- recipientUserId: user.id,
47
- email: user.email,
48
- tenantId: user.tenantId,
49
- organizationId: user.organizationId,
50
- verifiedBy: auth.sub
51
- }).catch(() => void 0);
31
+ emitCustomerEmailVerified(result.user, auth.sub);
52
32
  return NextResponse.json({ ok: true });
53
33
  }
54
34
  const successSchema = z.object({ ok: z.literal(true), alreadyVerified: z.boolean().optional() });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customer_accounts/api/admin/users/%5Bid%5D/verify-email.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport const metadata = {}\n\nexport async function POST(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n {\n id: params.id,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n if (user.emailVerifiedAt) {\n return NextResponse.json({ ok: true, alreadyVerified: true })\n }\n\n await em.nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, { emailVerifiedAt: new Date() })\n\n void emitCustomerAccountsEvent('customer_accounts.email.verified', {\n id: user.id,\n recipientUserId: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n verifiedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true), alreadyVerified: z.boolean().optional() })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify customer user email (admin)',\n description: 'Allows staff to manually mark a customer user email as verified.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'Email verified', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer user email (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AAE/B,MAAM,WAAW,CAAC;AAEzB,eAAsB,KAAK,KAAc,EAAE,OAAO,GAA+B;AAC/E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KAAK,CAAC,0BAA0B,GAAG,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM,CAAC;AACtJ,MAAI,CAAC,WAAW;AACd,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AAEA,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI,OAAO;AAAA,MACX,UAAU,KAAK;AAAA,MACf,gBAAgB,KAAK;AAAA,MACrB,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM;AAAA,EACxD;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A,EACpE;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,MAAM,UAAU;AAC7B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { CustomerSessionService } from '../../../../services/customerSessionService'\nimport { emitCustomerEmailVerified, verifyCustomerEmail } from '../../../../lib/verifyCustomerEmail'\n\nexport const metadata = {}\n\nexport async function POST(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n if (!auth.tenantId || !auth.orgId) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n const scope = { userId: params.id, tenantId: auth.tenantId, organizationId: auth.orgId }\n const sessions = container.resolve<CustomerSessionService>('customerSessionService')\n const result = await em.transactional((tx) => verifyCustomerEmail(tx, scope, sessions))\n if (!result) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n if (!result.newlyVerified) {\n return NextResponse.json({ ok: true, alreadyVerified: true })\n }\n emitCustomerEmailVerified(result.user, auth.sub)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true), alreadyVerified: z.boolean().optional() })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify customer user email (admin)',\n description: 'Allows staff to manually mark a customer user email as verified.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'Email verified', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer user email (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAGvC,SAAS,2BAA2B,2BAA2B;AAExD,MAAM,WAAW,CAAC;AAEzB,eAAsB,KAAK,KAAc,EAAE,OAAO,GAA+B;AAC/E,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KAAK,CAAC,0BAA0B,GAAG,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM,CAAC;AACtJ,MAAI,CAAC,WAAW;AACd,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AAEA,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,MAAI,CAAC,KAAK,YAAY,CAAC,KAAK,OAAO;AACj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AA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,7 @@ import { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } fro
6
6
  import { adminUpdateUserSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
7
7
  import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
8
8
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
9
- import { isOwnedCompanyEntity, isOwnedPersonEntity } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
9
+ import { isCustomerEntityRegistered, isOwnedCompanyEntity, isOwnedPersonEntity } from "@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership";
10
10
  import { enforceCommandOptimisticLockWithGuards } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
11
11
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
12
12
  const metadata = {};
@@ -127,21 +127,22 @@ async function PUT(req, { params }) {
127
127
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
128
128
  throw err;
129
129
  }
130
- if (parsed.data.customerEntityId) {
131
- const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {
130
+ const { customerEntityId, personEntityId } = parsed.data;
131
+ if (customerEntityId) {
132
+ const owned = await isOwnedCompanyEntity(em, customerEntityId, {
132
133
  tenantId: auth.tenantId,
133
134
  organizationId: auth.orgId
134
135
  });
135
- if (!owned) {
136
+ if (!owned && (customerEntityId !== user.customerEntityId || await isCustomerEntityRegistered(em))) {
136
137
  return NextResponse.json({ ok: false, error: "Company not found" }, { status: 400 });
137
138
  }
138
139
  }
139
- if (parsed.data.personEntityId) {
140
- const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {
140
+ if (personEntityId) {
141
+ const owned = await isOwnedPersonEntity(em, personEntityId, {
141
142
  tenantId: auth.tenantId,
142
143
  organizationId: auth.orgId
143
144
  });
144
- if (!owned) {
145
+ if (!owned && (personEntityId !== user.personEntityId || await isCustomerEntityRegistered(em))) {
145
146
  return NextResponse.json({ ok: false, error: "Person not found" }, { status: 400 });
146
147
  }
147
148
  }
@@ -153,8 +154,8 @@ async function PUT(req, { params }) {
153
154
  const updates = { updatedAt: nextUpdatedAt };
154
155
  if (parsed.data.isActive !== void 0) updates.isActive = parsed.data.isActive;
155
156
  if (parsed.data.lockedUntil !== void 0) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null;
156
- if (parsed.data.personEntityId !== void 0) updates.personEntityId = parsed.data.personEntityId;
157
- if (parsed.data.customerEntityId !== void 0) updates.customerEntityId = parsed.data.customerEntityId;
157
+ if (personEntityId !== void 0 && personEntityId !== user.personEntityId) updates.personEntityId = personEntityId;
158
+ if (customerEntityId !== void 0 && customerEntityId !== user.customerEntityId) updates.customerEntityId = customerEntityId;
158
159
  await em.nativeUpdate(CustomerUser, {
159
160
  id: user.id,
160
161
  tenantId: user.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customer_accounts/api/admin/users/%5Bid%5D.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { adminUpdateUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\n\nexport const metadata = {}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n if (!UUID_RE.test(params.id)) {\n return NextResponse.json({ ok: false, error: 'Invalid user ID' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n const userRoles = await findWithDecryption(\n em,\n CustomerUserRole,\n { user: user.id as any, deletedAt: null } as any,\n { populate: ['role'] },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n const roles = userRoles.map((ur) => ({\n id: (ur.role as any).id,\n name: (ur.role as any).name,\n slug: (ur.role as any).slug,\n }))\n\n const activeSessions = await findWithDecryption(\n em,\n CustomerUserSession,\n {\n user: user.id as any,\n deletedAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n { orderBy: { lastUsedAt: 'DESC' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const sessions = activeSessions.map((session) => ({\n id: session.id,\n ipAddress: (session as any).ipAddress || null,\n userAgent: (session as any).userAgent || null,\n lastUsedAt: (session as any).lastUsedAt || null,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n }))\n\n return NextResponse.json({\n ok: true,\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerifiedAt: user.emailVerifiedAt || null,\n isActive: user.isActive,\n lockedUntil: user.lockedUntil || null,\n lastLoginAt: user.lastLoginAt || null,\n customerEntityId: user.customerEntityId || null,\n personEntityId: user.personEntityId || null,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt || null,\n roles,\n sessions,\n })\n}\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = adminUpdateUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same\n // customer user in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 a no-op when the client sends no expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Reject a customerEntityId the caller does not own before persisting it.\n // Without this check a mislinked company FK cross-links the user into another\n // org/company's portal context and persists indefinitely (#2693). A null value\n // (unlink) needs no ownership check.\n if (parsed.data.customerEntityId) {\n const owned = await isOwnedCompanyEntity(em, parsed.data.customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK. Without it the invite-side check is trivially\n // bypassable: create the user normally, then PUT an unowned personEntityId.\n // It persists (autoLinkCrm short-circuits on any non-null value) and leaks\n // account status into the other org's people list via the account-status\n // enricher. A null value (unlink) needs no ownership check.\n if (parsed.data.personEntityId) {\n const owned = await isOwnedPersonEntity(em, parsed.data.personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n }\n\n // `display_name` is encrypted at rest, and `nativeUpdate` skips the flush hooks the\n // tenant-encryption subscriber relies on, so persisting it below would write plaintext PII\n // into a ciphertext column (#3837). Route it through the service, which writes it via the\n // managed entity. Runs before the `nativeUpdate` so the explicit `updated_at` below stays\n // the value this response reports back as the optimistic-lock version.\n if (parsed.data.displayName !== undefined) {\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n await customerUserService.updateProfile(user, { displayName: parsed.data.displayName })\n }\n\n // Always bump updated_at so the optimistic-lock version advances on every save.\n // `nativeUpdate` bypasses MikroORM's `onUpdate` hook, so set it explicitly \u2014 without\n // this the version never changes and concurrent edits cannot be detected (#2055).\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.isActive !== undefined) updates.isActive = parsed.data.isActive\n if (parsed.data.lockedUntil !== undefined) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null\n if (parsed.data.personEntityId !== undefined) updates.personEntityId = parsed.data.personEntityId\n if (parsed.data.customerEntityId !== undefined) updates.customerEntityId = parsed.data.customerEntityId\n\n await em.nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, updates)\n\n let rolesChanged = false\n if (parsed.data.roleIds !== undefined) {\n const requestedRoleIds = parsed.data.roleIds\n // Scope role resolution to the caller's organization too \u2014 CustomerRole is\n // org-scoped, so a tenant-only filter would let an admin link roles from\n // another org in the same tenant (#2693).\n const validRoles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds } as any,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n if (validRoles.length !== requestedRoleIds.length) {\n const foundIds = new Set(validRoles.map((role) => role.id))\n const missingId = requestedRoleIds.find((roleId) => !foundIds.has(roleId))\n return NextResponse.json({ ok: false, error: `Role ${missingId} not found` }, { status: 400 })\n }\n\n await em.nativeDelete(CustomerUserRole, { user: user.id } as Record<string, unknown>)\n\n for (const role of validRoles) {\n const userRole = em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n em.persist(userRole)\n }\n await em.flush()\n rolesChanged = true\n }\n\n if (rolesChanged) {\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateUserCache(user.id)\n }\n\n void emitCustomerAccountsEvent('customer_accounts.user.updated', {\n id: user.id,\n recipientUserId: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n updatedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale delete (e.g. deleting a record another admin\n // already modified). Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n await customerUserService.softDelete(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n await customerSessionService.revokeAllUserSessions(user.id)\n\n void emitCustomerAccountsEvent('customer_accounts.user.deleted', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n deletedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst roleSchema = z.object({ id: z.string().uuid(), name: z.string(), slug: z.string() })\nconst userDetailSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n isActive: z.boolean(),\n lockedUntil: z.string().datetime().nullable(),\n lastLoginAt: z.string().datetime().nullable(),\n failedLoginAttempts: z.number(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n roles: z.array(roleSchema),\n activeSessionCount: z.number(),\n})\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst getMethodDoc: OpenApiMethodDoc = {\n summary: 'Get customer user detail (admin)',\n description: 'Returns full customer user details including CRM links, roles, and active session count.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'User detail',\n schema: z.object({ ok: z.literal(true), user: userDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer user (admin)',\n description: 'Updates a customer user. Staff can update status, lock, CRM links, and roles. Role assignment bypasses customer_assignable check.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: adminUpdateUserSchema },\n responses: [{ status: 200, description: 'User updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or role not found', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer user (admin)',\n description: 'Soft deletes a customer user and revokes all their active sessions.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'User deleted', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer user detail management (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: getMethodDoc,\n PUT: putMethodDoc,\n DELETE: deleteMethodDoc,\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,cAAc,kBAAkB,cAAc,2BAA2B;AAIlF,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,sBAAsB,2BAA2B;AAC1D,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAEzB,MAAM,WAAW,CAAC;AAEzB,MAAM,UAAU;AAEhB,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,MAAI,CAAC,QAAQ,KAAK,OAAO,EAAE,GAAG;AAC5B,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,kBAAkB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACnF;AAEA,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,cAAc,UAAU,QAAQ,aAAa;AACnD,QAAM,YAAY,MAAM,YAAY,mBAAmB,KAAK,KA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AC5E,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,YAAY;AAAA,EACpE;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS;AAAA,IACP,KAAK;AAAA,IACL,KAAK;AAAA,IACL,QAAQ;AAAA,EACV;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { CustomerUser, CustomerUserRole, CustomerRole, CustomerUserSession } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { adminUpdateUserSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerEntityRegistered, isOwnedCompanyEntity, isOwnedPersonEntity } from '@open-mercato/core/modules/customer_accounts/lib/customerEntityOwnership'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\n\nexport const metadata = {}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport async function GET(req: Request, { params }: { params: { id: string } }) {\n if (!UUID_RE.test(params.id)) {\n return NextResponse.json({ ok: false, error: 'Invalid user ID' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.view'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n const userRoles = await findWithDecryption(\n em,\n CustomerUserRole,\n { user: user.id as any, deletedAt: null } as any,\n { populate: ['role'] },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n const roles = userRoles.map((ur) => ({\n id: (ur.role as any).id,\n name: (ur.role as any).name,\n slug: (ur.role as any).slug,\n }))\n\n const activeSessions = await findWithDecryption(\n em,\n CustomerUserSession,\n {\n user: user.id as any,\n deletedAt: null,\n expiresAt: { $gt: new Date() },\n } as any,\n { orderBy: { lastUsedAt: 'DESC' } },\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n\n const sessions = activeSessions.map((session) => ({\n id: session.id,\n ipAddress: (session as any).ipAddress || null,\n userAgent: (session as any).userAgent || null,\n lastUsedAt: (session as any).lastUsedAt || null,\n createdAt: session.createdAt,\n expiresAt: session.expiresAt,\n }))\n\n return NextResponse.json({\n ok: true,\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerifiedAt: user.emailVerifiedAt || null,\n isActive: user.isActive,\n lockedUntil: user.lockedUntil || null,\n lastLoginAt: user.lastLoginAt || null,\n customerEntityId: user.customerEntityId || null,\n personEntityId: user.personEntityId || null,\n createdAt: user.createdAt,\n updatedAt: user.updatedAt || null,\n roles,\n sessions,\n })\n}\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = adminUpdateUserSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed', details: parsed.error.flatten().fieldErrors }, { status: 400 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite so two admins editing the same\n // customer user in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 a no-op when the client sends no expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Reject a customerEntityId the caller does not own before persisting it.\n // Without this check a mislinked company FK cross-links the user into another\n // org/company's portal context and persists indefinitely (#2693). A null value\n // (unlink) needs no ownership check.\n const { customerEntityId, personEntityId } = parsed.data\n if (customerEntityId) {\n const owned = await isOwnedCompanyEntity(em, customerEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned && (customerEntityId !== user.customerEntityId || await isCustomerEntityRegistered(em))) {\n return NextResponse.json({ ok: false, error: 'Company not found' }, { status: 400 })\n }\n }\n\n // Same guard for the person FK. Without it the invite-side check is trivially\n // bypassable: create the user normally, then PUT an unowned personEntityId.\n // It persists (autoLinkCrm short-circuits on any non-null value) and leaks\n // account status into the other org's people list via the account-status\n // enricher. A null value (unlink) needs no ownership check.\n if (personEntityId) {\n const owned = await isOwnedPersonEntity(em, personEntityId, {\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n })\n if (!owned && (personEntityId !== user.personEntityId || await isCustomerEntityRegistered(em))) {\n return NextResponse.json({ ok: false, error: 'Person not found' }, { status: 400 })\n }\n }\n\n // `display_name` is encrypted at rest, and `nativeUpdate` skips the flush hooks the\n // tenant-encryption subscriber relies on, so persisting it below would write plaintext PII\n // into a ciphertext column (#3837). Route it through the service, which writes it via the\n // managed entity. Runs before the `nativeUpdate` so the explicit `updated_at` below stays\n // the value this response reports back as the optimistic-lock version.\n if (parsed.data.displayName !== undefined) {\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n await customerUserService.updateProfile(user, { displayName: parsed.data.displayName })\n }\n\n // Always bump updated_at so the optimistic-lock version advances on every save.\n // `nativeUpdate` bypasses MikroORM's `onUpdate` hook, so set it explicitly \u2014 without\n // this the version never changes and concurrent edits cannot be detected (#2055).\n const nextUpdatedAt = new Date()\n const updates: Record<string, unknown> = { updatedAt: nextUpdatedAt }\n if (parsed.data.isActive !== undefined) updates.isActive = parsed.data.isActive\n if (parsed.data.lockedUntil !== undefined) updates.lockedUntil = parsed.data.lockedUntil ? new Date(parsed.data.lockedUntil) : null\n if (personEntityId !== undefined && personEntityId !== user.personEntityId) updates.personEntityId = personEntityId\n if (customerEntityId !== undefined && customerEntityId !== user.customerEntityId) updates.customerEntityId = customerEntityId\n\n await em.nativeUpdate(CustomerUser, {\n id: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }, updates)\n\n let rolesChanged = false\n if (parsed.data.roleIds !== undefined) {\n const requestedRoleIds = parsed.data.roleIds\n // Scope role resolution to the caller's organization too \u2014 CustomerRole is\n // org-scoped, so a tenant-only filter would let an admin link roles from\n // another org in the same tenant (#2693).\n const validRoles = requestedRoleIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerRole,\n {\n id: { $in: requestedRoleIds } as any,\n tenantId: auth.tenantId,\n organizationId: auth.orgId,\n deletedAt: null,\n } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n : []\n if (validRoles.length !== requestedRoleIds.length) {\n const foundIds = new Set(validRoles.map((role) => role.id))\n const missingId = requestedRoleIds.find((roleId) => !foundIds.has(roleId))\n return NextResponse.json({ ok: false, error: `Role ${missingId} not found` }, { status: 400 })\n }\n\n await em.nativeDelete(CustomerUserRole, { user: user.id } as Record<string, unknown>)\n\n for (const role of validRoles) {\n const userRole = em.create(CustomerUserRole, {\n user,\n role,\n createdAt: new Date(),\n } as any)\n em.persist(userRole)\n }\n await em.flush()\n rolesChanged = true\n }\n\n if (rolesChanged) {\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n await customerRbacService.invalidateUserCache(user.id)\n }\n\n void emitCustomerAccountsEvent('customer_accounts.user.updated', {\n id: user.id,\n recipientUserId: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n updatedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true, updatedAt: nextUpdatedAt.toISOString() })\n}\n\nexport async function DELETE(req: Request, { params }: { params: { id: string } }) {\n const auth = await getAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const rbacService = container.resolve('rbacService') as RbacService\n const hasAccess = await rbacService.userHasAllFeatures(auth.sub, ['customer_accounts.manage'], { tenantId: auth.tenantId, organizationId: auth.orgId })\n if (!hasAccess) {\n return NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: params.id, tenantId: auth.tenantId, organizationId: auth.orgId, deletedAt: null } as any,\n undefined,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!user) {\n return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale delete (e.g. deleting a record another admin\n // already modified). Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'customer_accounts.user',\n resourceId: user.id,\n current: user.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n await customerUserService.softDelete(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n await customerSessionService.revokeAllUserSessions(user.id)\n\n void emitCustomerAccountsEvent('customer_accounts.user.deleted', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n deletedBy: auth.sub,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst roleSchema = z.object({ id: z.string().uuid(), name: z.string(), slug: z.string() })\nconst userDetailSchema = z.object({\n id: z.string().uuid(),\n email: z.string(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n isActive: z.boolean(),\n lockedUntil: z.string().datetime().nullable(),\n lastLoginAt: z.string().datetime().nullable(),\n failedLoginAttempts: z.number(),\n customerEntityId: z.string().uuid().nullable(),\n personEntityId: z.string().uuid().nullable(),\n createdAt: z.string().datetime(),\n updatedAt: z.string().datetime().nullable(),\n roles: z.array(roleSchema),\n activeSessionCount: z.number(),\n})\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst getMethodDoc: OpenApiMethodDoc = {\n summary: 'Get customer user detail (admin)',\n description: 'Returns full customer user details including CRM links, roles, and active session count.',\n tags: ['Customer Accounts Admin'],\n responses: [{\n status: 200,\n description: 'User detail',\n schema: z.object({ ok: z.literal(true), user: userDetailSchema }),\n }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst putMethodDoc: OpenApiMethodDoc = {\n summary: 'Update customer user (admin)',\n description: 'Updates a customer user. Staff can update status, lock, CRM links, and roles. Role assignment bypasses customer_assignable check.',\n tags: ['Customer Accounts Admin'],\n requestBody: { schema: adminUpdateUserSchema },\n responses: [{ status: 200, description: 'User updated', schema: successSchema }],\n errors: [\n { status: 400, description: 'Validation failed or role not found', schema: errorSchema },\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nconst deleteMethodDoc: OpenApiMethodDoc = {\n summary: 'Delete customer user (admin)',\n description: 'Soft deletes a customer user and revokes all their active sessions.',\n tags: ['Customer Accounts Admin'],\n responses: [{ status: 200, description: 'User deleted', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 403, description: 'Insufficient permissions', schema: errorSchema },\n { status: 404, description: 'User not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer user detail management (admin)',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: {\n GET: getMethodDoc,\n PUT: putMethodDoc,\n DELETE: deleteMethodDoc,\n },\n}\n"],
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server";
2
2
  import { z } from "zod";
3
3
  import { emailVerifySchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
- import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
6
- import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
5
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from "../../lib/verifyCustomerEmail.js";
7
6
  const metadata = { requireAuth: false };
8
7
  async function POST(req) {
9
8
  let body;
@@ -19,23 +18,25 @@ async function POST(req) {
19
18
  const container = await createRequestContainer();
20
19
  const customerTokenService = container.resolve("customerTokenService");
21
20
  const em = container.resolve("em");
22
- const result = await customerTokenService.verifyEmailToken(parsed.data.token, "email_verification");
21
+ const sessions = container.resolve("customerSessionService");
22
+ const { token, password } = parsed.data;
23
+ const result = await em.transactional(async (tx) => {
24
+ const identity = await customerTokenService.verifyEmailToken(token, "email_verification", void 0, tx);
25
+ if (!identity) return null;
26
+ const credentials = password === void 0 ? void 0 : { password, users: container.resolve("customerUserService") };
27
+ return verifyCustomerEmail(tx, identity, sessions, credentials);
28
+ });
23
29
  if (!result) {
24
30
  return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
25
31
  }
26
- await em.nativeUpdate(CustomerUser, { id: result.userId, tenantId: result.tenantId }, { emailVerifiedAt: /* @__PURE__ */ new Date() });
27
- void emitCustomerAccountsEvent("customer_accounts.email.verified", {
28
- userId: result.userId,
29
- recipientUserId: result.userId,
30
- tenantId: result.tenantId
31
- }).catch(() => void 0);
32
+ if (result.newlyVerified) emitCustomerEmailVerified(result.user);
32
33
  return NextResponse.json({ ok: true });
33
34
  }
34
35
  const successSchema = z.object({ ok: z.literal(true) });
35
36
  const errorSchema = z.object({ ok: z.literal(false), error: z.string() });
36
37
  const methodDoc = {
37
38
  summary: "Verify customer email address",
38
- description: "Validates the email verification token and marks the email as verified.",
39
+ description: "Verifies the email and optionally sets a password chosen by the email recipient.",
39
40
  tags: ["Customer Authentication"],
40
41
  requestBody: {
41
42
  schema: emailVerifySchema,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/email/verify.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { emailVerifySchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = emailVerifySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Invalid token' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const result = await customerTokenService.verifyEmailToken(parsed.data.token, 'email_verification')\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n await em.nativeUpdate(CustomerUser, { id: result.userId, tenantId: result.tenantId }, { emailVerifiedAt: new Date() })\n\n void emitCustomerAccountsEvent('customer_accounts.email.verified', {\n userId: result.userId,\n recipientUserId: result.userId,\n tenantId: result.tenantId,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify customer email address',\n description: 'Validates the email verification token and marks the email as verified.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: emailVerifySchema,\n description: 'Email verification token.',\n },\n responses: [\n { status: 200, description: 'Email verified', schema: successSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer email',\n description: 'Handles email verification for customer accounts.',\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,yBAAyB;AAClC,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAEnC,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,uBAAuB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACxF;AAEA,QAAM,SAAS,kBAAkB,UAAU,IAAI;AAC/C,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,gBAAgB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACjF;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,uBAAuB,UAAU,QAAQ,sBAAsB;AACrE,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,SAAS,MAAM,qBAAqB,iBAAiB,OAAO,KAAK,OAAO,oBAAoB;AAClG,MAAI,CAAC,QAAQ;AACX,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AAEA,QAAM,GAAG,aAAa,cAAc,EAAE,IAAI,OAAO,QAAQ,UAAU,OAAO,SAAS,GAAG,EAAE,iBAAiB,oBAAI,KAAK,EAAE,CAAC;AAErH,OAAK,0BAA0B,oCAAoC;AAAA,IACjE,QAAQ,OAAO;AAAA,IACf,iBAAiB,OAAO;AAAA,IACxB,UAAU,OAAO;AAAA,EACnB,CAAC,EAAE,MAAM,MAAM,MAAS;AAExB,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AACtD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,cAAc;AAAA,EACtE;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { emailVerifySchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport type { CustomerSessionService } from '../../services/customerSessionService'\nimport type { CustomerUserService } from '../../services/customerUserService'\nimport { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = emailVerifySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Invalid token' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const sessions = container.resolve<CustomerSessionService>('customerSessionService')\n const { token, password } = parsed.data\n const result = await em.transactional(async (tx) => {\n const identity = await customerTokenService.verifyEmailToken(token, 'email_verification', undefined, tx)\n if (!identity) return null\n const credentials = password === undefined\n ? undefined\n : { password, users: container.resolve<CustomerUserService>('customerUserService') }\n return verifyCustomerEmail(tx, identity, sessions, credentials)\n })\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n if (result.newlyVerified) emitCustomerEmailVerified(result.user)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify customer email address',\n description: 'Verifies the email and optionally sets a password chosen by the email recipient.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: emailVerifySchema,\n description: 'Email verification token.',\n },\n responses: [\n { status: 200, description: 'Email verified', schema: successSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer email',\n description: 'Handles email verification for customer accounts.',\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,yBAAyB;AAClC,SAAS,8BAA8B;AAIvC,SAAS,2BAA2B,2BAA2B;AAExD,MAAM,WA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AAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,cAAc;AAAA,EACtE;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -2,8 +2,8 @@ import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { magicLinkVerifySchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
- import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
6
5
  import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
6
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from "../../lib/verifyCustomerEmail.js";
7
7
  import { getClientIp } from "@open-mercato/shared/lib/ratelimit/helpers";
8
8
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
9
9
  import { isCrossSiteBrowserRequest } from "@open-mercato/shared/lib/url";
@@ -29,18 +29,19 @@ async function POST(req) {
29
29
  const customerSessionService = container.resolve("customerSessionService");
30
30
  const customerRbacService = container.resolve("customerRbacService");
31
31
  const em = container.resolve("em");
32
- const result = await customerTokenService.verifyEmailToken(parsed.data.token, "magic_link");
32
+ const result = await em.transactional(async (tx) => {
33
+ const identity = await customerTokenService.verifyEmailToken(parsed.data.token, "magic_link", void 0, tx);
34
+ if (!identity) return null;
35
+ return { account: await verifyCustomerEmail(tx, identity, customerSessionService) };
36
+ });
33
37
  if (!result) {
34
38
  return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
35
39
  }
36
- const user = await customerUserService.findById(result.userId, result.tenantId);
37
- if (!user || !user.isActive) {
40
+ if (!result.account) {
38
41
  return NextResponse.json({ ok: false, error: "Account not found or deactivated" }, { status: 401 });
39
42
  }
40
- if (!user.emailVerifiedAt) {
41
- await em.nativeUpdate(CustomerUser, { id: user.id }, { emailVerifiedAt: /* @__PURE__ */ new Date() });
42
- user.emailVerifiedAt = /* @__PURE__ */ new Date();
43
- }
43
+ const { user, newlyVerified } = result.account;
44
+ if (newlyVerified) emitCustomerEmailVerified(user);
44
45
  await customerUserService.resetFailedAttempts(user);
45
46
  await customerUserService.updateLastLoginAt(user);
46
47
  const resolvedFeatures = await customerRbacService.getEffectiveFeatures(user.id, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/magic-link/verify.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { magicLinkVerifySchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { getClientIp } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n if (isCrossSiteBrowserRequest(req)) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ ok: false, error: translate('customer_accounts.errors.crossSiteRequest', 'This sign-in request did not come from this application. Open the sign-in page and try again.') }, { status: 403 })\n }\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = magicLinkVerifySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Invalid token' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const result = await customerTokenService.verifyEmailToken(parsed.data.token, 'magic_link')\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n const user = await customerUserService.findById(result.userId, result.tenantId)\n if (!user || !user.isActive) {\n return NextResponse.json({ ok: false, error: 'Account not found or deactivated' }, { status: 401 })\n }\n\n // Auto-verify email on magic link login\n if (!user.emailVerifiedAt) {\n await em.nativeUpdate(CustomerUser, { id: user.id }, { emailVerifiedAt: new Date() })\n user.emailVerifiedAt = new Date()\n }\n\n await customerUserService.resetFailedAttempts(user)\n await customerUserService.updateLastLoginAt(user)\n\n const resolvedFeatures = await customerRbacService.getEffectiveFeatures(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n\n const ip = getClientIp(req, 0)\n const userAgent = req.headers.get('user-agent') || null\n const { rawToken, jwt } = await customerSessionService.createSession(user, resolvedFeatures, ip, userAgent)\n\n void emitCustomerAccountsEvent('customer_accounts.login.success', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }).catch(() => undefined)\n\n const res = NextResponse.json({\n ok: true,\n user: {\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerified: true,\n },\n resolvedFeatures,\n })\n\n res.cookies.set('customer_auth_token', jwt, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 8,\n })\n res.cookies.set('customer_session_token', rawToken, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 24 * 30,\n })\n\n return res\n}\n\nconst loginSuccessSchema = z.object({\n ok: z.literal(true),\n user: z.object({\n id: z.string().uuid(),\n email: z.string().email(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n }),\n resolvedFeatures: z.array(z.string()),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify magic link token',\n description: 'Validates the magic link token, auto-verifies email, and creates a session.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: magicLinkVerifySchema,\n description: 'Magic link verification token.',\n },\n responses: [\n { status: 200, description: 'Login successful', schema: loginSuccessSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n { status: 401, description: 'Account not found', schema: errorSchema },\n { status: 403, description: 'Request was submitted cross-site', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer magic link',\n description: 'Handles magic link verification and auto-login.',\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAKvC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,mBAAmB;AAC5B,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAEnC,MAAM,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K,KAAK,KAAK;AAAA,EACzB,CAAC;AAED,SAAO;AACT;AAEA,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,MAAM,EAAE,OAAO;AAAA,IACb,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,IACpB,OAAO,EAAE,OAAO,EAAE,MAAM;AAAA,IACxB,aAAa,EAAE,OAAO;AAAA,IACtB,eAAe,EAAE,QAAQ;AAAA,EAC3B,CAAC;AAAA,EACD,kBAAkB,EAAE,MAAM,EAAE,OAAO,CAAC;AACtC,CAAC;AAED,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,mBAAmB;AAAA,EAC7E;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,IAC5E,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,oCAAoC,QAAQ,YAAY;AAAA,EACtF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { magicLinkVerifySchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'\nimport { getClientIp } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n if (isCrossSiteBrowserRequest(req)) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({ ok: false, error: translate('customer_accounts.errors.crossSiteRequest', 'This sign-in request did not come from this application. Open the sign-in page and try again.') }, { status: 403 })\n }\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = magicLinkVerifySchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Invalid token' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const result = await em.transactional(async (tx) => {\n const identity = await customerTokenService.verifyEmailToken(parsed.data.token, 'magic_link', undefined, tx)\n if (!identity) return null\n return { account: await verifyCustomerEmail(tx, identity, customerSessionService) }\n })\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n if (!result.account) {\n return NextResponse.json({ ok: false, error: 'Account not found or deactivated' }, { status: 401 })\n }\n\n const { user, newlyVerified } = result.account\n if (newlyVerified) emitCustomerEmailVerified(user)\n\n await customerUserService.resetFailedAttempts(user)\n await customerUserService.updateLastLoginAt(user)\n\n const resolvedFeatures = await customerRbacService.getEffectiveFeatures(user.id, {\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n })\n\n const ip = getClientIp(req, 0)\n const userAgent = req.headers.get('user-agent') || null\n const { rawToken, jwt } = await customerSessionService.createSession(user, resolvedFeatures, ip, userAgent)\n\n void emitCustomerAccountsEvent('customer_accounts.login.success', {\n id: user.id,\n email: user.email,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n }).catch(() => undefined)\n\n const res = NextResponse.json({\n ok: true,\n user: {\n id: user.id,\n email: user.email,\n displayName: user.displayName,\n emailVerified: true,\n },\n resolvedFeatures,\n })\n\n res.cookies.set('customer_auth_token', jwt, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 8,\n })\n res.cookies.set('customer_session_token', rawToken, {\n httpOnly: true,\n path: '/',\n sameSite: 'lax',\n secure: process.env.NODE_ENV === 'production',\n maxAge: 60 * 60 * 24 * 30,\n })\n\n return res\n}\n\nconst loginSuccessSchema = z.object({\n ok: z.literal(true),\n user: z.object({\n id: z.string().uuid(),\n email: z.string().email(),\n displayName: z.string(),\n emailVerified: z.boolean(),\n }),\n resolvedFeatures: z.array(z.string()),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Verify magic link token',\n description: 'Validates the magic link token, auto-verifies email, and creates a session.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: magicLinkVerifySchema,\n description: 'Magic link verification token.',\n },\n responses: [\n { status: 200, description: 'Login successful', schema: loginSuccessSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n { status: 401, description: 'Account not found', schema: errorSchema },\n { status: 403, description: 'Request was submitted cross-site', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Verify customer magic link',\n description: 'Handles magic link verification and auto-login.',\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAKvC,SAAS,iCAAiC;AAC1C,SAAS,2BAA2B,2BAA2B;AAC/D,SAAS,mBAAmB;AAC5B,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAEnC,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,MAAI,0BAA0B,GAAG,GAAG;AAClC,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,UAAU,6CAA6C,+FAA+F,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACzN;AACA,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,uBAAuB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACxF;AAEA,QAAM,SAAS,sBAAsB,UAAU,IAAI;AACnD,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,gBAAgB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACjF;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,uBAAuB,UAAU,QAAQ,sBAAsB;AACrE,QAAM,sBAAsB,UAAU,QAAQ,qBAAqB;AACnE,QAAM,yBAAyB,UAAU,QAAQ,wBAAwB;AACzE,QAAM,sBAAsB,UAAU,QAAQ,qBAAqB;AACnE,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,Q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AAA,IACrE,EAAE,QAAQ,KAAK,aAAa,oCAAoC,QAAQ,YAAY;AAAA,EACtF;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -2,8 +2,8 @@ import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { passwordResetConfirmSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
4
4
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
- import { CustomerUser } from "@open-mercato/core/modules/customer_accounts/data/entities";
6
5
  import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
6
+ import { emitCustomerEmailVerified, verifyCustomerEmail } from "../../lib/verifyCustomerEmail.js";
7
7
  const metadata = { requireAuth: false };
8
8
  async function POST(req) {
9
9
  let body;
@@ -20,24 +20,21 @@ async function POST(req) {
20
20
  const customerTokenService = container.resolve("customerTokenService");
21
21
  const customerUserService = container.resolve("customerUserService");
22
22
  const customerSessionService = container.resolve("customerSessionService");
23
- const result = await customerTokenService.verifyPasswordResetToken(parsed.data.token);
23
+ const em = container.resolve("em");
24
+ const result = await em.transactional(async (tx) => {
25
+ const identity = await customerTokenService.verifyPasswordResetToken(parsed.data.token, void 0, tx);
26
+ if (!identity) return null;
27
+ return verifyCustomerEmail(tx, identity, customerSessionService, {
28
+ password: parsed.data.password,
29
+ users: customerUserService,
30
+ reset: true
31
+ });
32
+ });
24
33
  if (!result) {
25
34
  return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
26
35
  }
27
- const user = await customerUserService.findById(result.userId, result.tenantId);
28
- if (!user) {
29
- return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
30
- }
31
- const em = container.resolve("em");
32
- await em.transactional(async (trx) => {
33
- await customerUserService.updatePassword(user, parsed.data.password, trx);
34
- await customerSessionService.revokeAllUserSessions(user.id, trx);
35
- await trx.nativeUpdate(
36
- CustomerUser,
37
- { id: user.id, emailVerifiedAt: null },
38
- { emailVerifiedAt: /* @__PURE__ */ new Date() }
39
- );
40
- });
36
+ const { user, newlyVerified } = result;
37
+ if (newlyVerified) emitCustomerEmailVerified(user);
41
38
  void emitCustomerAccountsEvent("customer_accounts.password.changed", {
42
39
  userId: user.id,
43
40
  tenantId: user.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customer_accounts/api/password/reset-confirm.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { passwordResetConfirmSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = passwordResetConfirmSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n const result = await customerTokenService.verifyPasswordResetToken(parsed.data.token)\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n const user = await customerUserService.findById(result.userId, result.tenantId)\n if (!user) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n\n const em = container.resolve('em') as EntityManager\n await em.transactional(async (trx) => {\n await customerUserService.updatePassword(user, parsed.data.password, trx)\n await customerSessionService.revokeAllUserSessions(user.id, trx)\n await trx.nativeUpdate(\n CustomerUser,\n { id: user.id, emailVerifiedAt: null },\n { emailVerifiedAt: new Date() },\n )\n })\n\n void emitCustomerAccountsEvent('customer_accounts.password.changed', {\n userId: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n changedBy: 'reset',\n changedById: null,\n at: new Date().toISOString(),\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Confirm customer password reset',\n description: 'Validates the reset token and sets a new password. Revokes all existing sessions.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: passwordResetConfirmSchema,\n description: 'Password reset confirmation with token and new password.',\n },\n responses: [\n { status: 200, description: 'Password reset successful', schema: successSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Confirm customer password reset',\n description: 'Handles password reset confirmation for customer accounts.',\n methods: { POST: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AAIvC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAGnC,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,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AgB,KAAK,kBAAkB;AAAA,IACvC,WAAW;AAAA,IACX,aAAa;AAAA,IACb,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,EAC7B,CAAC,EAAE,MAAM,MAAM,MAAS;AAExB,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AACtD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,cAAc;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { passwordResetConfirmSchema } from '@open-mercato/core/modules/customer_accounts/data/validators'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'\nimport { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'\nimport { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function POST(req: Request) {\n let body: unknown\n try {\n body = await req.json()\n } catch {\n return NextResponse.json({ ok: false, error: 'Invalid request body' }, { status: 400 })\n }\n\n const parsed = passwordResetConfirmSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ ok: false, error: 'Validation failed' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService\n\n const em = container.resolve('em') as EntityManager\n const result = await em.transactional(async (tx) => {\n const identity = await customerTokenService.verifyPasswordResetToken(parsed.data.token, undefined, tx)\n if (!identity) return null\n return verifyCustomerEmail(tx, identity, customerSessionService, {\n password: parsed.data.password,\n users: customerUserService,\n reset: true,\n })\n })\n if (!result) {\n return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n }\n const { user, newlyVerified } = result\n if (newlyVerified) emitCustomerEmailVerified(user)\n\n void emitCustomerAccountsEvent('customer_accounts.password.changed', {\n userId: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId ?? null,\n changedBy: 'reset',\n changedById: null,\n at: new Date().toISOString(),\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Confirm customer password reset',\n description: 'Validates the reset token and sets a new password. Revokes all existing sessions.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: passwordResetConfirmSchema,\n description: 'Password reset confirmation with token and new password.',\n },\n responses: [\n { status: 200, description: 'Password reset successful', schema: successSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid or expired token', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Confirm customer password reset',\n description: 'Handles password reset confirmation for customer accounts.',\n methods: { POST: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AAIvC,SAAS,iCAAiC;AAE1C,SAAS,2BAA2B,2BAA2B;AAExD,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,KAAK,KAAc;AACvC,MAAI;AACJ,MAAI;AACF,WAAO,MAAM,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,uBAAuB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACxF;AAEA,QAAM,SAAS,2BAA2B,UAAU,IAAI;AACxD,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,oBAAoB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrF;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,uBAAuB,UAAU,QAAQ,sBAAsB;AACrE,QAAM,sBAAsB,UAAU,QAAQ,qBAAqB;AACnE,QAAM,yBAAyB,UAAU,QAAQ,wBAAwB;AAEzE,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,QAAM,SAAS,MAAM,GAAG,cAAc,OAAO,OAAO;AAClD,UAAM,WAAW,MAAM,qBAAqB,yBAAyB,OAAO,KAAK,OAAO,QAAW,EAAE;AACrG,QAAI,CAAC,SAAU,QAAO;AACtB,WAAO,oBAAoB,IAAI,UAAU,wBAAwB;AAAA,MAC/D,UAAU,OAAO,KAAK;AAAA,MACtB,OAAO;AAAA,MACP,OAAO;AAAA,IACT,CAAC;AAAA,EACH,CAAC;AACD,MAAI,CAAC,QAAQ;AACX,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5F;AACA,QAAM,EAAE,MAAM,cAAc,IAAI;AAChC,MAAI,cAAe,2BAA0B,IAAI;AAEjD,OAAK,0BAA0B,sCAAsC;AAAA,IACnE,QAAQ,KAAK;AAAA,IACb,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK,kBAAkB;AAAA,IACvC,WAAW;AAAA,IACX,aAAa;AAAA,IACb,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,EAC7B,CAAC,EAAE,MAAM,MAAM,MAAS;AAExB,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AACtD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,yBAAyB;AAAA,EAChC,aAAa;AAAA,IACX,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AAAA,EACA,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,6BAA6B,QAAQ,cAAc;AAAA,EACjF;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,YAAY;AAAA,EAC9E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getCustomerAuthFromRequest } from "@open-mercato/core/modules/customer_accounts/lib/customerAuth";
4
+ import { arePortalNotificationsAvailable } from "@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { Notification } from "@open-mercato/core/modules/notifications/data/entities";
6
7
  const metadata = { requireAuth: false };
@@ -11,11 +12,11 @@ async function PUT(req, { params }) {
11
12
  }
12
13
  const container = await createRequestContainer();
13
14
  const em = container.resolve("em");
14
- const notification = await em.findOne(Notification, {
15
+ const notification = arePortalNotificationsAvailable(em) ? await em.findOne(Notification, {
15
16
  id: params.id,
16
17
  recipientUserId: auth.sub,
17
18
  tenantId: auth.tenantId
18
- });
19
+ }) : null;
19
20
  if (!notification) {
20
21
  return NextResponse.json({ ok: false, error: "Notification not found" }, { status: 404 });
21
22
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customer_accounts/api/portal/notifications/%5Bid%5D/dismiss.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Dismiss notification',\n description: 'Dismisses a single notification for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification dismissed', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Dismiss customer notification',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,eAAe,MAAM,GAAG,QAAQ,cAAc;AAAA,IAClD,IAAI,OAAO;AAAA,IACX,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,EACjB,CAAC;AAED,MAAI,CAAC,cAAc;AACjB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,yBAAyB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1F;AAEA,eAAa,SAAS;AACtB,eAAa,cAAc,oBAAI,KAAK;AACpC,QAAM,GAAG,MAAM;AAEf,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,CAAC;AACvC;AAEA,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AACtD,MAAM,cAAc,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,KAAK,GAAG,OAAO,EAAE,OAAO,EAAE,CAAC;AAExE,MAAM,YAA8B;AAAA,EAClC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,MAAM,CAAC,iBAAiB;AAAA,EACxB,WAAW,CAAC,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,cAAc,CAAC;AAAA,EACzF,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY;AAAA,IACrE,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,YAAY;AAAA,EAC5E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,EAC9C,SAAS,EAAE,KAAK,UAAU;AAC5B;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { getCustomerAuthFromRequest } from '@open-mercato/core/modules/customer_accounts/lib/customerAuth'\nimport { arePortalNotificationsAvailable } from '@open-mercato/core/modules/customer_accounts/lib/portalNotificationsAvailability'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { Notification } from '@open-mercato/core/modules/notifications/data/entities'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function PUT(req: Request, { params }: { params: { id: string } }) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const notification = arePortalNotificationsAvailable(em)\n ? await em.findOne(Notification, {\n id: params.id,\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n })\n : null\n\n if (!notification) {\n return NextResponse.json({ ok: false, error: 'Notification not found' }, { status: 404 })\n }\n\n notification.status = 'dismissed'\n notification.dismissedAt = new Date()\n await em.flush()\n\n return NextResponse.json({ ok: true })\n}\n\nconst successSchema = z.object({ ok: z.literal(true) })\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Dismiss notification',\n description: 'Dismisses a single notification for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification dismissed', schema: successSchema }],\n errors: [\n { status: 401, description: 'Not authenticated', schema: errorSchema },\n { status: 404, description: 'Notification not found', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Dismiss customer notification',\n pathParams: z.object({ id: z.string().uuid() }),\n methods: { PUT: methodDoc },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAEtB,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc,EAAE,OAAO,GAA+B;AAC9E,QAAM,OAAO,MAAM,2BAA2B,GAAG;AACjD,MAAI,CAAC,MAAM;AACT,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AAEjC,QAAM,eAAe,gCAAgC,EAAE,IACnD,MAAM,GAAG,QAAQ,cAAc;AAAA,IAC7B,IAAI,OAAO;AAAA,IACX,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,EACjB,CAAC,IACD;AAEJ,MAAI,CAAC,cAAc;AACjB,WAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,yBAAyB,GA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