@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.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js +10 -30
- package/dist/modules/customer_accounts/api/admin/users/[id]/verify-email.js.map +2 -2
- package/dist/modules/customer_accounts/api/admin/users/[id].js +10 -9
- package/dist/modules/customer_accounts/api/admin/users/[id].js.map +2 -2
- package/dist/modules/customer_accounts/api/email/verify.js +11 -10
- package/dist/modules/customer_accounts/api/email/verify.js.map +2 -2
- package/dist/modules/customer_accounts/api/magic-link/verify.js +9 -8
- package/dist/modules/customer_accounts/api/magic-link/verify.js.map +2 -2
- package/dist/modules/customer_accounts/api/password/reset-confirm.js +13 -16
- package/dist/modules/customer_accounts/api/password/reset-confirm.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js +3 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/dismiss.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js +3 -2
- package/dist/modules/customer_accounts/api/portal/notifications/[id]/read.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications/mark-all-read.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications/unread-count.js.map +2 -2
- package/dist/modules/customer_accounts/api/portal/notifications.js +4 -0
- package/dist/modules/customer_accounts/api/portal/notifications.js.map +2 -2
- package/dist/modules/customer_accounts/api/signup.js +33 -19
- package/dist/modules/customer_accounts/api/signup.js.map +3 -3
- package/dist/modules/customer_accounts/data/validators.js +3 -2
- package/dist/modules/customer_accounts/data/validators.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuth.js +11 -10
- package/dist/modules/customer_accounts/lib/customerAuth.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerAuthServer.js +7 -7
- package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
- package/dist/modules/customer_accounts/lib/customerEntityOwnership.js +12 -1
- package/dist/modules/customer_accounts/lib/customerEntityOwnership.js.map +2 -2
- package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js +8 -0
- package/dist/modules/customer_accounts/lib/moduleEntityRegistration.js.map +7 -0
- package/dist/modules/customer_accounts/lib/pendingSignup.js +16 -0
- package/dist/modules/customer_accounts/lib/pendingSignup.js.map +7 -0
- package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js +9 -0
- package/dist/modules/customer_accounts/lib/portalNotificationsAvailability.js.map +7 -0
- package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js +50 -0
- package/dist/modules/customer_accounts/lib/verifyCustomerEmail.js.map +7 -0
- package/dist/modules/customer_accounts/services/customerInvitationService.js +15 -1
- package/dist/modules/customer_accounts/services/customerInvitationService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerTokenService.js +13 -13
- package/dist/modules/customer_accounts/services/customerTokenService.js.map +2 -2
- package/dist/modules/customer_accounts/services/customerUserService.js +1 -1
- package/dist/modules/customer_accounts/services/customerUserService.js.map +2 -2
- package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +44 -51
- package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js +12 -0
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.js.map +7 -0
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
- package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
- package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js +6 -0
- package/dist/modules/customer_accounts/workers/cleanupExpiredTokens.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js +127 -0
- package/dist/modules/portal/frontend/[orgSlug]/portal/PasswordForm.js.map +7 -0
- package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js +10 -122
- package/dist/modules/portal/frontend/[orgSlug]/portal/reset-password/page.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js +2 -11
- package/dist/modules/portal/frontend/[orgSlug]/portal/signup/page.js.map +2 -2
- package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js +3 -61
- package/dist/modules/portal/frontend/[orgSlug]/portal/verify/page.js.map +2 -2
- package/dist/modules/wms/index.js +1 -1
- package/dist/modules/wms/index.js.map +2 -2
- package/dist/modules/wms/setup.js +4 -1
- package/dist/modules/wms/setup.js.map +2 -2
- package/dist/modules/workflows/api/events/route.js +1 -1
- package/dist/modules/workflows/api/events/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/events/route.js +1 -1
- package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/steps/route.js +1 -1
- package/dist/modules/workflows/api/instances/[id]/steps/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/failure-queue/route.js +1 -1
- package/dist/modules/workflows/api/instances/failure-queue/route.js.map +2 -2
- package/dist/modules/workflows/lib/event-logger.js +1 -1
- package/dist/modules/workflows/lib/event-logger.js.map +2 -2
- package/dist/modules/workflows/lib/work-inbox/user-task-source.js +1 -1
- package/dist/modules/workflows/lib/work-inbox/user-task-source.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
- package/src/modules/customer_accounts/api/admin/users/[id].ts +10 -9
- package/src/modules/customer_accounts/api/email/verify.ts +15 -11
- package/src/modules/customer_accounts/api/magic-link/verify.ts +9 -9
- package/src/modules/customer_accounts/api/password/reset-confirm.ts +13 -18
- package/src/modules/customer_accounts/api/portal/notifications/[id]/dismiss.ts +8 -5
- package/src/modules/customer_accounts/api/portal/notifications/[id]/read.ts +8 -5
- package/src/modules/customer_accounts/api/portal/notifications/mark-all-read.ts +4 -0
- package/src/modules/customer_accounts/api/portal/notifications/unread-count.ts +4 -0
- package/src/modules/customer_accounts/api/portal/notifications.ts +4 -0
- package/src/modules/customer_accounts/api/signup.ts +36 -24
- package/src/modules/customer_accounts/data/validators.ts +2 -1
- package/src/modules/customer_accounts/lib/customerAuth.ts +12 -10
- package/src/modules/customer_accounts/lib/customerAuthServer.ts +7 -7
- package/src/modules/customer_accounts/lib/customerEntityOwnership.ts +13 -1
- package/src/modules/customer_accounts/lib/moduleEntityRegistration.ts +12 -0
- package/src/modules/customer_accounts/lib/pendingSignup.ts +12 -0
- package/src/modules/customer_accounts/lib/portalNotificationsAvailability.ts +7 -0
- package/src/modules/customer_accounts/lib/verifyCustomerEmail.ts +57 -0
- package/src/modules/customer_accounts/services/customerInvitationService.ts +16 -1
- package/src/modules/customer_accounts/services/customerTokenService.ts +13 -13
- package/src/modules/customer_accounts/services/customerUserService.ts +2 -2
- package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +46 -78
- package/src/modules/customer_accounts/subscribers/autoLinkCrmOnVerification.ts +9 -0
- package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +3 -1
- package/src/modules/customer_accounts/workers/cleanupExpiredTokens.ts +7 -0
- package/src/modules/portal/frontend/[orgSlug]/portal/PasswordForm.tsx +182 -0
- package/src/modules/portal/frontend/[orgSlug]/portal/reset-password/page.tsx +9 -165
- package/src/modules/portal/frontend/[orgSlug]/portal/signup/page.tsx +2 -12
- package/src/modules/portal/frontend/[orgSlug]/portal/verify/page.tsx +3 -89
- package/src/modules/portal/i18n/de.json +2 -1
- package/src/modules/portal/i18n/en.json +2 -1
- package/src/modules/portal/i18n/es.json +2 -1
- package/src/modules/portal/i18n/ko.json +2 -1
- package/src/modules/portal/i18n/pl.json +2 -1
- package/src/modules/wms/index.ts +1 -1
- package/src/modules/wms/setup.ts +4 -1
- package/src/modules/workflows/api/events/route.ts +1 -1
- package/src/modules/workflows/api/instances/[id]/events/route.ts +1 -1
- package/src/modules/workflows/api/instances/[id]/steps/route.ts +3 -2
- package/src/modules/workflows/api/instances/failure-queue/route.ts +1 -1
- package/src/modules/workflows/lib/event-logger.ts +1 -1
- package/src/modules/workflows/lib/work-inbox/user-task-source.ts +3 -2
|
@@ -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/read.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
|
|
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,
|
|
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 = 'read'\n notification.readAt = 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: 'Mark notification as read',\n description: 'Marks a single notification as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification marked as read', 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: 'Mark notification as read',\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,QA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AuthFromRequest } 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,6 +12,9 @@ async function PUT(req) {
|
|
|
11
12
|
}
|
|
12
13
|
const container = await createRequestContainer();
|
|
13
14
|
const em = container.resolve("em");
|
|
15
|
+
if (!arePortalNotificationsAvailable(em)) {
|
|
16
|
+
return NextResponse.json({ ok: true, count: 0 });
|
|
17
|
+
}
|
|
14
18
|
const now = /* @__PURE__ */ new Date();
|
|
15
19
|
const count = await em.nativeUpdate(Notification, {
|
|
16
20
|
recipientUserId: auth.sub,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/customer_accounts/api/portal/notifications/mark-all-read.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) {\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 now = new Date()\n const count = await em.nativeUpdate(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n }, {\n status: 'read',\n readAt: now,\n })\n\n return NextResponse.json({ ok: true, count })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n count: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark all notifications as read',\n description: 'Marks all unread notifications as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'All notifications marked as read', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark all customer notifications as read',\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;AACtC,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;
|
|
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) {\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 if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, count: 0 })\n }\n\n const now = new Date()\n const count = await em.nativeUpdate(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n }, {\n status: 'read',\n readAt: now,\n })\n\n return NextResponse.json({ ok: true, count })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n count: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Mark all notifications as read',\n description: 'Marks all unread notifications as read for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'All notifications marked as read', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Mark all customer notifications as read',\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;AACtC,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;AACjC,MAAI,CAAC,gCAAgC,EAAE,GAAG;AACxC,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,OAAO,EAAE,CAAC;AAAA,EACjD;AAEA,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,QAAQ,MAAM,GAAG,aAAa,cAAc;AAAA,IAChD,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,GAAG;AAAA,IACD,QAAQ;AAAA,IACR,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,MAAM,CAAC;AAC9C;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,OAAO,EAAE,OAAO;AAClB,CAAC;AACD,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,oCAAoC,QAAQ,cAAc,CAAC;AAAA,EACnG,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
|
|
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,6 +12,9 @@ async function GET(req) {
|
|
|
11
12
|
}
|
|
12
13
|
const container = await createRequestContainer();
|
|
13
14
|
const em = container.resolve("em");
|
|
15
|
+
if (!arePortalNotificationsAvailable(em)) {
|
|
16
|
+
return NextResponse.json({ ok: true, unreadCount: 0 });
|
|
17
|
+
}
|
|
14
18
|
const unreadCount = await em.count(Notification, {
|
|
15
19
|
recipientUserId: auth.sub,
|
|
16
20
|
tenantId: auth.tenantId,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/modules/customer_accounts/api/portal/notifications/unread-count.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 GET(req: Request) {\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 unreadCount = await em.count(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n })\n\n return NextResponse.json({ ok: true, unreadCount })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n unreadCount: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Get unread notification count',\n description: 'Returns the number of unread notifications for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Unread count', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer unread notification count',\n methods: { GET: 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;AACtC,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;
|
|
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 GET(req: Request) {\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 if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, unreadCount: 0 })\n }\n\n const unreadCount = await em.count(Notification, {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n status: 'unread',\n })\n\n return NextResponse.json({ ok: true, unreadCount })\n}\n\nconst successSchema = z.object({\n ok: z.literal(true),\n unreadCount: z.number(),\n})\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Get unread notification count',\n description: 'Returns the number of unread notifications for the authenticated customer user.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Unread count', schema: successSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer unread notification count',\n methods: { GET: 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;AACtC,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;AACjC,MAAI,CAAC,gCAAgC,EAAE,GAAG;AACxC,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,aAAa,EAAE,CAAC;AAAA,EACvD;AAEA,QAAM,cAAc,MAAM,GAAG,MAAM,cAAc;AAAA,IAC/C,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,QAAQ;AAAA,EACV,CAAC;AAED,SAAO,aAAa,KAAK,EAAE,IAAI,MAAM,YAAY,CAAC;AACpD;AAEA,MAAM,gBAAgB,EAAE,OAAO;AAAA,EAC7B,IAAI,EAAE,QAAQ,IAAI;AAAA,EAClB,aAAa,EAAE,OAAO;AACxB,CAAC;AACD,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,gBAAgB,QAAQ,cAAc,CAAC;AAAA,EAC/E,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
|
|
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
|
import { toNotificationDto } from "@open-mercato/core/modules/notifications/lib/notificationMapper";
|
|
@@ -18,6 +19,9 @@ async function GET(req) {
|
|
|
18
19
|
const since = url.searchParams.get("since") || void 0;
|
|
19
20
|
const container = await createRequestContainer();
|
|
20
21
|
const em = container.resolve("em");
|
|
22
|
+
if (!arePortalNotificationsAvailable(em)) {
|
|
23
|
+
return NextResponse.json({ ok: true, items: [], total: 0, page, pageSize });
|
|
24
|
+
}
|
|
21
25
|
const where = {
|
|
22
26
|
recipientUserId: auth.sub,
|
|
23
27
|
tenantId: auth.tenantId
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/customer_accounts/api/portal/notifications.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'\nimport { toNotificationDto } from '@open-mercato/core/modules/notifications/lib/notificationMapper'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const page = Math.max(1, parseInt(url.searchParams.get('page') || '1', 10) || 1)\n const rawPageSize = parseInt(url.searchParams.get('pageSize') || '50', 10) || 50\n const pageSize = Math.min(Math.max(1, rawPageSize), 100)\n const status = url.searchParams.get('status') || undefined\n const since = url.searchParams.get('since') || undefined\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n\n const where: Record<string, unknown> = {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n }\n\n if (status) {\n where.status = status\n } else {\n where.status = { $ne: 'dismissed' }\n }\n\n if (since) {\n const sinceDate = new Date(since)\n if (!isNaN(sinceDate.getTime())) {\n where.createdAt = { $gte: sinceDate }\n }\n }\n\n const offset = (page - 1) * pageSize\n\n const [items, total] = await Promise.all([\n em.find(Notification, where, {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset,\n }),\n em.count(Notification, where),\n ])\n\n return NextResponse.json({\n ok: true,\n items: items.map(toNotificationDto),\n total,\n page,\n pageSize,\n })\n}\n\nconst notificationDtoSchema = z.object({\n id: z.string().uuid(),\n type: z.string(),\n title: z.string(),\n body: z.string().nullable().optional(),\n titleKey: z.string().nullable().optional(),\n bodyKey: z.string().nullable().optional(),\n titleVariables: z.record(z.string(), z.string()).nullable().optional(),\n bodyVariables: z.record(z.string(), z.string()).nullable().optional(),\n icon: z.string().nullable().optional(),\n severity: z.enum(['info', 'warning', 'success', 'error']),\n status: z.enum(['unread', 'read', 'actioned', 'dismissed']),\n actions: z.array(z.object({\n id: z.string(),\n label: z.string(),\n labelKey: z.string().optional(),\n variant: z.string().optional(),\n icon: z.string().optional(),\n })),\n primaryActionId: z.string().optional(),\n sourceModule: z.string().nullable().optional(),\n sourceEntityType: z.string().nullable().optional(),\n sourceEntityId: z.string().nullable().optional(),\n linkHref: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n readAt: z.string().datetime().nullable(),\n actionTaken: z.string().nullable().optional(),\n})\n\nconst listResponseSchema = z.object({\n ok: z.literal(true),\n items: z.array(notificationDtoSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'List customer notifications',\n description: 'Returns paginated notifications for the authenticated customer user. Dismissed notifications are excluded by default unless ?status=dismissed is specified.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification list', schema: listResponseSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer notifications',\n methods: { GET: methodDoc },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAE3B,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,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,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,OAAO,KAAK,IAAI,GAAG,SAAS,IAAI,aAAa,IAAI,MAAM,KAAK,KAAK,EAAE,KAAK,CAAC;AAC/E,QAAM,cAAc,SAAS,IAAI,aAAa,IAAI,UAAU,KAAK,MAAM,EAAE,KAAK;AAC9E,QAAM,WAAW,KAAK,IAAI,KAAK,IAAI,GAAG,WAAW,GAAG,GAAG;AACvD,QAAM,SAAS,IAAI,aAAa,IAAI,QAAQ,KAAK;AACjD,QAAM,QAAQ,IAAI,aAAa,IAAI,OAAO,KAAK;AAE/C,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;
|
|
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'\nimport { toNotificationDto } from '@open-mercato/core/modules/notifications/lib/notificationMapper'\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\nexport async function GET(req: Request) {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const page = Math.max(1, parseInt(url.searchParams.get('page') || '1', 10) || 1)\n const rawPageSize = parseInt(url.searchParams.get('pageSize') || '50', 10) || 50\n const pageSize = Math.min(Math.max(1, rawPageSize), 100)\n const status = url.searchParams.get('status') || undefined\n const since = url.searchParams.get('since') || undefined\n\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n if (!arePortalNotificationsAvailable(em)) {\n return NextResponse.json({ ok: true, items: [], total: 0, page, pageSize })\n }\n\n const where: Record<string, unknown> = {\n recipientUserId: auth.sub,\n tenantId: auth.tenantId,\n }\n\n if (status) {\n where.status = status\n } else {\n where.status = { $ne: 'dismissed' }\n }\n\n if (since) {\n const sinceDate = new Date(since)\n if (!isNaN(sinceDate.getTime())) {\n where.createdAt = { $gte: sinceDate }\n }\n }\n\n const offset = (page - 1) * pageSize\n\n const [items, total] = await Promise.all([\n em.find(Notification, where, {\n orderBy: { createdAt: 'DESC' },\n limit: pageSize,\n offset,\n }),\n em.count(Notification, where),\n ])\n\n return NextResponse.json({\n ok: true,\n items: items.map(toNotificationDto),\n total,\n page,\n pageSize,\n })\n}\n\nconst notificationDtoSchema = z.object({\n id: z.string().uuid(),\n type: z.string(),\n title: z.string(),\n body: z.string().nullable().optional(),\n titleKey: z.string().nullable().optional(),\n bodyKey: z.string().nullable().optional(),\n titleVariables: z.record(z.string(), z.string()).nullable().optional(),\n bodyVariables: z.record(z.string(), z.string()).nullable().optional(),\n icon: z.string().nullable().optional(),\n severity: z.enum(['info', 'warning', 'success', 'error']),\n status: z.enum(['unread', 'read', 'actioned', 'dismissed']),\n actions: z.array(z.object({\n id: z.string(),\n label: z.string(),\n labelKey: z.string().optional(),\n variant: z.string().optional(),\n icon: z.string().optional(),\n })),\n primaryActionId: z.string().optional(),\n sourceModule: z.string().nullable().optional(),\n sourceEntityType: z.string().nullable().optional(),\n sourceEntityId: z.string().nullable().optional(),\n linkHref: z.string().nullable().optional(),\n createdAt: z.string().datetime(),\n readAt: z.string().datetime().nullable(),\n actionTaken: z.string().nullable().optional(),\n})\n\nconst listResponseSchema = z.object({\n ok: z.literal(true),\n items: z.array(notificationDtoSchema),\n total: z.number(),\n page: z.number(),\n pageSize: z.number(),\n})\n\nconst errorSchema = z.object({ ok: z.literal(false), error: z.string() })\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'List customer notifications',\n description: 'Returns paginated notifications for the authenticated customer user. Dismissed notifications are excluded by default unless ?status=dismissed is specified.',\n tags: ['Customer Portal'],\n responses: [{ status: 200, description: 'Notification list', schema: listResponseSchema }],\n errors: [{ status: 401, description: 'Not authenticated', schema: errorSchema }],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer notifications',\n methods: { GET: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,kCAAkC;AAC3C,SAAS,uCAAuC;AAChD,SAAS,8BAA8B;AACvC,SAAS,oBAAoB;AAC7B,SAAS,yBAAyB;AAE3B,MAAM,WAAqD,EAAE,aAAa,MAAM;AAEvF,eAAsB,IAAI,KAAc;AACtC,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,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,OAAO,KAAK,IAAI,GAAG,SAAS,IAAI,aAAa,IAAI,MAAM,KAAK,KAAK,EAAE,KAAK,CAAC;AAC/E,QAAM,cAAc,SAAS,IAAI,aAAa,IAAI,UAAU,KAAK,MAAM,EAAE,KAAK;AAC9E,QAAM,WAAW,KAAK,IAAI,KAAK,IAAI,GAAG,WAAW,GAAG,GAAG;AACvD,QAAM,SAAS,IAAI,aAAa,IAAI,QAAQ,KAAK;AACjD,QAAM,QAAQ,IAAI,aAAa,IAAI,OAAO,KAAK;AAE/C,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAK,UAAU,QAAQ,IAAI;AACjC,MAAI,CAAC,gCAAgC,EAAE,GAAG;AACxC,WAAO,aAAa,KAAK,EAAE,IAAI,MAAM,OAAO,CAAC,GAAG,OAAO,GAAG,MAAM,SAAS,CAAC;AAAA,EAC5E;AAEA,QAAM,QAAiC;AAAA,IACrC,iBAAiB,K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W,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,mBAAmB,CAAC;AAAA,EACzF,QAAQ,CAAC,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,YAAY,CAAC;AACjF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,SAAS,EAAE,KAAK,UAAU;AAC5B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { NextResponse } from "next/server";
|
|
2
2
|
import { compare as bcryptCompare } from "bcryptjs";
|
|
3
|
+
import { UniqueConstraintViolationException } from "@mikro-orm/core";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
|
|
5
6
|
import { sendEmail } from "@open-mercato/shared/lib/email/send";
|
|
6
7
|
import { signupSchema } from "@open-mercato/core/modules/customer_accounts/data/validators";
|
|
7
8
|
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
8
|
-
import { CustomerRole, CustomerUserRole } from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
9
|
+
import { CustomerRole, CustomerUser, CustomerUserRole } from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
9
10
|
import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
|
|
10
11
|
import CustomerSignupVerificationEmail from "@open-mercato/core/modules/customer_accounts/emails/CustomerSignupVerificationEmail";
|
|
11
12
|
import CustomerExistingAccountEmail from "@open-mercato/core/modules/customer_accounts/emails/CustomerExistingAccountEmail";
|
|
@@ -24,6 +25,7 @@ import {
|
|
|
24
25
|
} from "@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext";
|
|
25
26
|
import { urlForCustomerOrg } from "@open-mercato/core/modules/customer_accounts/lib/customerUrl";
|
|
26
27
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
28
|
+
import { pendingSignup, signupExpiryCutoff } from "../lib/pendingSignup.js";
|
|
27
29
|
const logger = createLogger("customer_accounts").child({ component: "signup" });
|
|
28
30
|
const metadata = { requireAuth: false };
|
|
29
31
|
const TIMING_EQUALIZATION_HASH = "$2b$10$.F2A6UHFzk.d8trNdfqt4OLz05Nf3IOuMmN6VJKflhD4.rz.prR8i";
|
|
@@ -92,9 +94,21 @@ async function POST(req) {
|
|
|
92
94
|
if (!orgRow) {
|
|
93
95
|
return NextResponse.json({ ok: false, error: "Registration could not be completed" }, { status: 400 });
|
|
94
96
|
}
|
|
95
|
-
|
|
97
|
+
let existing = await customerUserService.findByEmail(email, tenantId);
|
|
98
|
+
await bcryptCompare(password ?? "", TIMING_EQUALIZATION_HASH);
|
|
99
|
+
const now = /* @__PURE__ */ new Date();
|
|
100
|
+
const cutoff = signupExpiryCutoff(now);
|
|
101
|
+
if (existing?.isActive && !existing.emailVerifiedAt && !existing.lastLoginAt && existing.createdAt <= cutoff) {
|
|
102
|
+
const retired = await em.nativeUpdate(CustomerUser, {
|
|
103
|
+
id: existing.id,
|
|
104
|
+
tenantId,
|
|
105
|
+
organizationId: existing.organizationId,
|
|
106
|
+
...pendingSignup,
|
|
107
|
+
createdAt: { $lte: cutoff }
|
|
108
|
+
}, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now });
|
|
109
|
+
existing = retired === 1 ? null : await customerUserService.findByEmail(email, tenantId);
|
|
110
|
+
}
|
|
96
111
|
if (existing) {
|
|
97
|
-
await bcryptCompare(password, TIMING_EQUALIZATION_HASH);
|
|
98
112
|
const existingOrg = await findOrganizationInTenant(em, existing.organizationId, tenantId);
|
|
99
113
|
let loginUrl = resolvePortalLoginUrl(baseUrl, existingOrg?.slug ?? null);
|
|
100
114
|
try {
|
|
@@ -126,22 +140,22 @@ async function POST(req) {
|
|
|
126
140
|
});
|
|
127
141
|
return NextResponse.json({ ok: true }, { status: 202 });
|
|
128
142
|
}
|
|
129
|
-
const
|
|
130
|
-
const
|
|
131
|
-
tenantId,
|
|
132
|
-
|
|
133
|
-
|
|
143
|
+
const signupScope = { tenantId, organizationId };
|
|
144
|
+
const signup = await em.transactional(async (tx) => {
|
|
145
|
+
const defaultRole = await tx.findOne(CustomerRole, { tenantId, isDefault: true, deletedAt: null });
|
|
146
|
+
const user2 = await customerUserService.createUser(email, null, displayName, signupScope);
|
|
147
|
+
if (defaultRole) tx.persist(tx.create(CustomerUserRole, { user: user2, role: defaultRole, createdAt: /* @__PURE__ */ new Date() }));
|
|
148
|
+
await tx.persist(user2).flush();
|
|
149
|
+
const verificationToken2 = await customerTokenService.createEmailVerification(user2.id, tenantId, user2.createdAt, tx);
|
|
150
|
+
return { user: user2, verificationToken: verificationToken2 };
|
|
151
|
+
}).catch(async (error) => {
|
|
152
|
+
if (error instanceof UniqueConstraintViolationException && await customerUserService.findByEmail(email, tenantId)) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
134
156
|
});
|
|
135
|
-
if (
|
|
136
|
-
|
|
137
|
-
user,
|
|
138
|
-
role: defaultRole,
|
|
139
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
140
|
-
});
|
|
141
|
-
em.persist(userRole);
|
|
142
|
-
}
|
|
143
|
-
await em.persist(user).flush();
|
|
144
|
-
const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId);
|
|
157
|
+
if (!signup) return NextResponse.json({ ok: true }, { status: 202 });
|
|
158
|
+
const { user, verificationToken } = signup;
|
|
145
159
|
let verifyUrl = resolvePortalVerifyUrl(baseUrl, verificationToken, orgRow.slug);
|
|
146
160
|
try {
|
|
147
161
|
verifyUrl = await urlForCustomerOrg(organizationId, `/verify?token=${encodeURIComponent(verificationToken)}`, {
|
|
@@ -191,7 +205,7 @@ const methodDoc = {
|
|
|
191
205
|
tags: ["Customer Authentication"],
|
|
192
206
|
requestBody: {
|
|
193
207
|
schema: signupSchema,
|
|
194
|
-
description: "Signup payload with email
|
|
208
|
+
description: "Signup payload with email and display name. Passwords are set during email verification."
|
|
195
209
|
},
|
|
196
210
|
responses: [
|
|
197
211
|
{ status: 202, description: "Signup accepted", schema: signupAcceptedSchema }
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/api/signup.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { compare as bcryptCompare } from 'bcryptjs'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport { signupSchema } 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 { CustomerRole, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport CustomerSignupVerificationEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerSignupVerificationEmail'\nimport CustomerExistingAccountEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerExistingAccountEmail'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerSignupRateLimitConfig,\n customerSignupIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { findOrganizationInTenant } from '@open-mercato/core/modules/customer_accounts/lib/organizationLookup'\nimport { getSecurityEmailBaseUrl, mapSecurityEmailUrlError } from '@open-mercato/shared/lib/url'\nimport {\n resolveTenantContext,\n TenantResolutionError,\n} from '@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext'\nimport { urlForCustomerOrg } from '@open-mercato/core/modules/customer_accounts/lib/customerUrl'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'signup' })\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\n// Precomputed bcrypt cost-10 hash of an unknowable random 32-byte input; used to equalize\n// response latency between the existing-user and new-user signup branches so the endpoint's\n// 202-for-both contract is not undone by a timing side channel.\nconst TIMING_EQUALIZATION_HASH = '$2b$10$.F2A6UHFzk.d8trNdfqt4OLz05Nf3IOuMmN6VJKflhD4.rz.prR8i'\nfunction resolvePortalLoginUrl(baseUrl: string, organizationSlug?: string | null): string {\n return organizationSlug\n ? `${baseUrl}/${organizationSlug}/portal/login`\n : `${baseUrl}/portal/login`\n}\n\nfunction resolvePortalVerifyUrl(baseUrl: string, token: string, organizationSlug?: string | null): string {\n const route = organizationSlug\n ? `${baseUrl}/${organizationSlug}/portal/verify`\n : `${baseUrl}/portal/verify`\n return `${route}?token=${encodeURIComponent(token)}`\n}\n\nexport async function POST(req: Request) {\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerSignupIpRateLimitConfig,\n compoundConfig: customerSignupRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n isolateByIdentifierWithoutTrustedIp: true,\n })\n if (rateLimitError) return rateLimitError\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 = signupSchema.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 { email, password, displayName } = parsed.data\n let tenantId: string\n let organizationId: string | null\n try {\n const context = await resolveTenantContext(req, parsed.data.tenantId, {\n organizationId: parsed.data.organizationId ?? null,\n })\n tenantId = context.tenantId\n organizationId = context.organizationId ?? parsed.data.organizationId ?? null\n } catch (err) {\n if (err instanceof TenantResolutionError) {\n return NextResponse.json({ ok: false, error: err.message }, { status: err.status })\n }\n throw err\n }\n if (!organizationId) {\n return NextResponse.json({ ok: false, error: 'organizationId is required' }, { status: 400 })\n }\n\n let baseUrl: string\n try {\n baseUrl = getSecurityEmailBaseUrl(req)\n } catch (error) {\n const mapped = mapSecurityEmailUrlError(error, {\n scope: 'customer_accounts.signup',\n configMessage: 'Customer signup is not configured',\n })\n if (mapped) return NextResponse.json(mapped.body, { status: mapped.status })\n throw error\n }\n\n const container = await createRequestContainer()\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const { translate } = await resolveTranslations()\n\n const orgRow = await findOrganizationInTenant(em, organizationId, tenantId)\n if (!orgRow) {\n return NextResponse.json({ ok: false, error: 'Registration could not be completed' }, { status: 400 })\n }\n\n const existing = await customerUserService.findByEmail(email, tenantId)\n if (existing) {\n await bcryptCompare(password, TIMING_EQUALIZATION_HASH)\n const existingOrg = await findOrganizationInTenant(em, existing.organizationId, tenantId)\n // Prefer the org's active custom domain when available; fall back to the\n // platform login URL preserved by `resolvePortalLoginUrl`.\n let loginUrl = resolvePortalLoginUrl(baseUrl, existingOrg?.slug ?? null)\n try {\n loginUrl = await urlForCustomerOrg(existing.organizationId, '/login', { container })\n } catch {\n // Fall back to platform URL on any resolution issue.\n }\n const subject = translate('customer_accounts.signup.existing.subject', 'You already have a portal account')\n const copy = {\n preview: translate('customer_accounts.signup.existing.preview', 'A sign-up attempt was made for an email that already has a portal account.'),\n title: translate('customer_accounts.signup.existing.title', 'You already have a portal account'),\n body: translate(\n 'customer_accounts.signup.existing.body',\n 'A sign-up request was made for this email address. You can sign in with your existing account. If you forgot your password, use the password reset option on the sign-in page.',\n ),\n cta: translate('customer_accounts.signup.existing.cta', 'Open sign-in page'),\n hint: translate(\n 'customer_accounts.signup.existing.hint',\n 'If this was not you, you can ignore this message. No new portal account was created.',\n ),\n }\n\n await sendEmail({\n to: existing.email,\n subject,\n react: CustomerExistingAccountEmail({ loginUrl, copy }),\n tenantId,\n organizationId,\n }).catch((error) => {\n logger.error('Existing-account email failed', { err: error })\n })\n\n return NextResponse.json({ ok: true }, { status: 202 })\n }\n\n const user = await customerUserService.createUser(email, password, displayName, { tenantId, organizationId })\n\n const defaultRole = await em.findOne(CustomerRole, {\n tenantId,\n isDefault: true,\n deletedAt: null,\n })\n if (defaultRole) {\n const userRole = em.create(CustomerUserRole, {\n user,\n role: defaultRole,\n createdAt: new Date(),\n } as any)\n em.persist(userRole)\n }\n\n await em.persist(user).flush()\n\n const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId)\n let verifyUrl = resolvePortalVerifyUrl(baseUrl, verificationToken, orgRow.slug)\n try {\n verifyUrl = await urlForCustomerOrg(organizationId, `/verify?token=${encodeURIComponent(verificationToken)}`, {\n container,\n })\n } catch {\n // Fall back to the platform-derived URL on any resolution issue.\n }\n const subject = translate('customer_accounts.signup.created.subject', 'Verify your portal account')\n const copy = {\n preview: translate('customer_accounts.signup.created.preview', 'Verify your portal account to finish sign-up.'),\n title: translate('customer_accounts.signup.created.title', 'Verify your portal account'),\n body: translate(\n 'customer_accounts.signup.created.body',\n 'Your account request was accepted. Confirm your email address to finish setting up portal access.',\n ),\n cta: translate('customer_accounts.signup.created.cta', 'Verify email address'),\n hint: translate(\n 'customer_accounts.signup.created.hint',\n 'This verification link expires in 24 hours. If you did not request this, you can ignore this email.',\n ),\n }\n\n await sendEmail({\n to: user.email,\n subject,\n react: CustomerSignupVerificationEmail({ verifyUrl, copy }),\n tenantId,\n organizationId,\n }).catch((error) => {\n logger.error('Verification email failed', { err: error })\n })\n\n void emitCustomerAccountsEvent('customer_accounts.user.created', {\n id: user.id,\n email: user.email,\n tenantId,\n organizationId,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true }, { status: 202 })\n}\n\nconst signupAcceptedSchema = z.object({ ok: z.literal(true) })\n\nconst errorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Register a new customer account',\n description: 'Accepts a signup request and always returns 202 to prevent account enumeration.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: signupSchema,\n description: 'Signup payload with email, password, and display name.',\n },\n responses: [\n { status: 202, description: 'Signup accepted', schema: signupAcceptedSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed or invalid request origin', schema: errorSchema },\n { status: 429, description: 'Too many signup attempts', schema: rateLimitErrorSchema },\n { status: 500, description: 'Signup email origin is not configured', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer account registration',\n description: 'Handles customer self-registration without revealing whether the email already exists.',\n methods: { POST: methodDoc },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,WAAW,qBAAqB;AACzC,SAAS,SAAS;AAElB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAC1B,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AAGvC,SAAS,cAAc,wBAAwB;
|
|
6
|
-
"names": ["subject", "copy"]
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { compare as bcryptCompare } from 'bcryptjs'\nimport { UniqueConstraintViolationException } from '@mikro-orm/core'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport { signupSchema } 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 { CustomerRole, CustomerUser, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport CustomerSignupVerificationEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerSignupVerificationEmail'\nimport CustomerExistingAccountEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerExistingAccountEmail'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport {\n checkAuthRateLimit,\n customerSignupRateLimitConfig,\n customerSignupIpRateLimitConfig,\n} from '@open-mercato/core/modules/customer_accounts/lib/rateLimiter'\nimport { readNormalizedEmailFromJsonRequest } from '@open-mercato/core/modules/customer_accounts/lib/rateLimitIdentifier'\nimport { findOrganizationInTenant } from '@open-mercato/core/modules/customer_accounts/lib/organizationLookup'\nimport { getSecurityEmailBaseUrl, mapSecurityEmailUrlError } from '@open-mercato/shared/lib/url'\nimport {\n resolveTenantContext,\n TenantResolutionError,\n} from '@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext'\nimport { urlForCustomerOrg } from '@open-mercato/core/modules/customer_accounts/lib/customerUrl'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'\n\nconst logger = createLogger('customer_accounts').child({ component: 'signup' })\n\nexport const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }\n\n// Precomputed bcrypt cost-10 hash of an unknowable random 32-byte input; used to equalize\n// response latency between new and existing registrations.\nconst TIMING_EQUALIZATION_HASH = '$2b$10$.F2A6UHFzk.d8trNdfqt4OLz05Nf3IOuMmN6VJKflhD4.rz.prR8i'\nfunction resolvePortalLoginUrl(baseUrl: string, organizationSlug?: string | null): string {\n return organizationSlug\n ? `${baseUrl}/${organizationSlug}/portal/login`\n : `${baseUrl}/portal/login`\n}\n\nfunction resolvePortalVerifyUrl(baseUrl: string, token: string, organizationSlug?: string | null): string {\n const route = organizationSlug\n ? `${baseUrl}/${organizationSlug}/portal/verify`\n : `${baseUrl}/portal/verify`\n return `${route}?token=${encodeURIComponent(token)}`\n}\n\nexport async function POST(req: Request) {\n const rateLimitEmail = await readNormalizedEmailFromJsonRequest(req)\n const { error: rateLimitError } = await checkAuthRateLimit({\n req,\n ipConfig: customerSignupIpRateLimitConfig,\n compoundConfig: customerSignupRateLimitConfig,\n compoundIdentifier: rateLimitEmail,\n isolateByIdentifierWithoutTrustedIp: true,\n })\n if (rateLimitError) return rateLimitError\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 = signupSchema.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 { email, password, displayName } = parsed.data\n let tenantId: string\n let organizationId: string | null\n try {\n const context = await resolveTenantContext(req, parsed.data.tenantId, {\n organizationId: parsed.data.organizationId ?? null,\n })\n tenantId = context.tenantId\n organizationId = context.organizationId ?? parsed.data.organizationId ?? null\n } catch (err) {\n if (err instanceof TenantResolutionError) {\n return NextResponse.json({ ok: false, error: err.message }, { status: err.status })\n }\n throw err\n }\n if (!organizationId) {\n return NextResponse.json({ ok: false, error: 'organizationId is required' }, { status: 400 })\n }\n\n let baseUrl: string\n try {\n baseUrl = getSecurityEmailBaseUrl(req)\n } catch (error) {\n const mapped = mapSecurityEmailUrlError(error, {\n scope: 'customer_accounts.signup',\n configMessage: 'Customer signup is not configured',\n })\n if (mapped) return NextResponse.json(mapped.body, { status: mapped.status })\n throw error\n }\n\n const container = await createRequestContainer()\n const customerUserService = container.resolve('customerUserService') as CustomerUserService\n const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const { translate } = await resolveTranslations()\n\n const orgRow = await findOrganizationInTenant(em, organizationId, tenantId)\n if (!orgRow) {\n return NextResponse.json({ ok: false, error: 'Registration could not be completed' }, { status: 400 })\n }\n\n let existing = await customerUserService.findByEmail(email, tenantId)\n await bcryptCompare(password ?? '', TIMING_EQUALIZATION_HASH)\n const now = new Date()\n const cutoff = signupExpiryCutoff(now)\n if (existing?.isActive && !existing.emailVerifiedAt\n && !existing.lastLoginAt && existing.createdAt <= cutoff) {\n const retired = await em.nativeUpdate(CustomerUser, {\n id: existing.id,\n tenantId,\n organizationId: existing.organizationId,\n ...pendingSignup,\n createdAt: { $lte: cutoff },\n }, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })\n existing = retired === 1 ? null : await customerUserService.findByEmail(email, tenantId)\n }\n if (existing) {\n const existingOrg = await findOrganizationInTenant(em, existing.organizationId, tenantId)\n // Prefer the org's active custom domain when available; fall back to the\n // platform login URL preserved by `resolvePortalLoginUrl`.\n let loginUrl = resolvePortalLoginUrl(baseUrl, existingOrg?.slug ?? null)\n try {\n loginUrl = await urlForCustomerOrg(existing.organizationId, '/login', { container })\n } catch {\n // Fall back to platform URL on any resolution issue.\n }\n const subject = translate('customer_accounts.signup.existing.subject', 'You already have a portal account')\n const copy = {\n preview: translate('customer_accounts.signup.existing.preview', 'A sign-up attempt was made for an email that already has a portal account.'),\n title: translate('customer_accounts.signup.existing.title', 'You already have a portal account'),\n body: translate(\n 'customer_accounts.signup.existing.body',\n 'A sign-up request was made for this email address. You can sign in with your existing account. If you forgot your password, use the password reset option on the sign-in page.',\n ),\n cta: translate('customer_accounts.signup.existing.cta', 'Open sign-in page'),\n hint: translate(\n 'customer_accounts.signup.existing.hint',\n 'If this was not you, you can ignore this message. No new portal account was created.',\n ),\n }\n\n await sendEmail({\n to: existing.email,\n subject,\n react: CustomerExistingAccountEmail({ loginUrl, copy }),\n tenantId,\n organizationId,\n }).catch((error) => {\n logger.error('Existing-account email failed', { err: error })\n })\n\n return NextResponse.json({ ok: true }, { status: 202 })\n }\n\n const signupScope = { tenantId, organizationId }\n const signup = await em.transactional(async (tx) => {\n const defaultRole = await tx.findOne(CustomerRole, { tenantId, isDefault: true, deletedAt: null })\n const user = await customerUserService.createUser(email, null, displayName, signupScope)\n if (defaultRole) tx.persist(tx.create(CustomerUserRole, { user, role: defaultRole, createdAt: new Date() }))\n await tx.persist(user).flush()\n const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId, user.createdAt, tx)\n return { user, verificationToken }\n }).catch(async (error: unknown) => {\n if (error instanceof UniqueConstraintViolationException\n && (await customerUserService.findByEmail(email, tenantId))) {\n return null\n }\n throw error\n })\n if (!signup) return NextResponse.json({ ok: true }, { status: 202 })\n const { user, verificationToken } = signup\n let verifyUrl = resolvePortalVerifyUrl(baseUrl, verificationToken, orgRow.slug)\n try {\n verifyUrl = await urlForCustomerOrg(organizationId, `/verify?token=${encodeURIComponent(verificationToken)}`, {\n container,\n })\n } catch {\n // Fall back to the platform-derived URL on any resolution issue.\n }\n const subject = translate('customer_accounts.signup.created.subject', 'Verify your portal account')\n const copy = {\n preview: translate('customer_accounts.signup.created.preview', 'Verify your portal account to finish sign-up.'),\n title: translate('customer_accounts.signup.created.title', 'Verify your portal account'),\n body: translate(\n 'customer_accounts.signup.created.body',\n 'Your account request was accepted. Confirm your email address to finish setting up portal access.',\n ),\n cta: translate('customer_accounts.signup.created.cta', 'Verify email address'),\n hint: translate(\n 'customer_accounts.signup.created.hint',\n 'This verification link expires in 24 hours. If you did not request this, you can ignore this email.',\n ),\n }\n\n await sendEmail({\n to: user.email,\n subject,\n react: CustomerSignupVerificationEmail({ verifyUrl, copy }),\n tenantId,\n organizationId,\n }).catch((error) => {\n logger.error('Verification email failed', { err: error })\n })\n\n void emitCustomerAccountsEvent('customer_accounts.user.created', {\n id: user.id,\n email: user.email,\n tenantId,\n organizationId,\n }).catch(() => undefined)\n\n return NextResponse.json({ ok: true }, { status: 202 })\n}\n\nconst signupAcceptedSchema = z.object({ ok: z.literal(true) })\n\nconst errorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nconst methodDoc: OpenApiMethodDoc = {\n summary: 'Register a new customer account',\n description: 'Accepts a signup request and always returns 202 to prevent account enumeration.',\n tags: ['Customer Authentication'],\n requestBody: {\n schema: signupSchema,\n description: 'Signup payload with email and display name. Passwords are set during email verification.',\n },\n responses: [\n { status: 202, description: 'Signup accepted', schema: signupAcceptedSchema },\n ],\n errors: [\n { status: 400, description: 'Validation failed or invalid request origin', schema: errorSchema },\n { status: 429, description: 'Too many signup attempts', schema: rateLimitErrorSchema },\n { status: 500, description: 'Signup email origin is not configured', schema: errorSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n summary: 'Customer account registration',\n description: 'Handles customer self-registration without revealing whether the email already exists.',\n methods: { POST: methodDoc },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,WAAW,qBAAqB;AACzC,SAAS,0CAA0C;AACnD,SAAS,SAAS;AAElB,SAAS,2BAA2B;AACpC,SAAS,iBAAiB;AAC1B,SAAS,oBAAoB;AAC7B,SAAS,8BAA8B;AAGvC,SAAS,cAAc,cAAc,wBAAwB;AAC7D,SAAS,iCAAiC;AAC1C,OAAO,qCAAqC;AAC5C,OAAO,kCAAkC;AACzC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0CAA0C;AACnD,SAAS,gCAAgC;AACzC,SAAS,yBAAyB,gCAAgC;AAClE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,eAAe,0BAA0B;AAElD,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,SAAS,CAAC;AAEvE,MAAM,WAAqD,EAAE,aAAa,MAAM;AAIvF,MAAM,2BAA2B;AACjC,SAAS,sBAAsB,SAAiB,kBAA0C;AACxF,SAAO,mBACH,GAAG,OAAO,IAAI,gBAAgB,kBAC9B,GAAG,OAAO;AAChB;AAEA,SAAS,uBAAuB,SAA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K,MAAM,CAAC;AAAA,EAC1D,CAAC;AAED,OAAK,0BAA0B,kCAAkC;AAAA,IAC/D,IAAI,KAAK;AAAA,IACT,OAAO,KAAK;AAAA,IACZ;AAAA,IACA;AAAA,EACF,CAAC,EAAE,MAAM,MAAM,MAAS;AAExB,SAAO,aAAa,KAAK,EAAE,IAAI,KAAK,GAAG,EAAE,QAAQ,IAAI,CAAC;AACxD;AAEA,MAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,IAAI,EAAE,CAAC;AAE7D,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,IAAI,EAAE,QAAQ,KAAK;AAAA,EACnB,OAAO,EAAE,OAAO;AAClB,CAAC;AAED,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,mBAAmB,QAAQ,qBAAqB;AAAA,EAC9E;AAAA,EACA,QAAQ;AAAA,IACN,EAAE,QAAQ,KAAK,aAAa,+CAA+C,QAAQ,YAAY;AAAA,IAC/F,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,qBAAqB;AAAA,IACrF,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,YAAY;AAAA,EAC3F;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,SAAS;AAAA,EACT,aAAa;AAAA,EACb,SAAS,EAAE,MAAM,UAAU;AAC7B;",
|
|
6
|
+
"names": ["subject", "copy", "user", "verificationToken"]
|
|
7
7
|
}
|
|
@@ -5,7 +5,7 @@ const passwordField = z.string().min(8).max(128);
|
|
|
5
5
|
const displayNameField = z.string().min(1).max(255);
|
|
6
6
|
const signupSchema = z.object({
|
|
7
7
|
email: emailField,
|
|
8
|
-
password: passwordField,
|
|
8
|
+
password: passwordField.optional(),
|
|
9
9
|
displayName: displayNameField,
|
|
10
10
|
tenantId: z.string().uuid().optional(),
|
|
11
11
|
organizationId: z.string().uuid().optional()
|
|
@@ -17,7 +17,8 @@ const loginSchema = z.object({
|
|
|
17
17
|
organizationId: z.string().uuid().optional()
|
|
18
18
|
});
|
|
19
19
|
const emailVerifySchema = z.object({
|
|
20
|
-
token: z.string().min(1).max(512)
|
|
20
|
+
token: z.string().min(1).max(512),
|
|
21
|
+
password: passwordField.optional()
|
|
21
22
|
});
|
|
22
23
|
const passwordResetRequestSchema = z.object({
|
|
23
24
|
email: emailField,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/data/validators.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport { normalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\n\nconst emailField = z.string().email().max(255)\nconst passwordField = z.string().min(8).max(128)\nconst displayNameField = z.string().min(1).max(255)\n\nexport const signupSchema = z.object({\n email: emailField,\n password: passwordField,\n displayName: displayNameField,\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const loginSchema = z.object({\n email: emailField,\n password: z.string().min(1).max(128),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const emailVerifySchema = z.object({\n token: z.string().min(1).max(512),\n})\n\nexport const passwordResetRequestSchema = z.object({\n email: emailField,\n tenantId: z.string().uuid().optional(),\n})\n\nexport const passwordResetConfirmSchema = z.object({\n token: z.string().min(1).max(512),\n password: passwordField,\n})\n\nexport const magicLinkRequestSchema = z.object({\n email: emailField,\n tenantId: z.string().uuid().optional(),\n})\n\nexport const magicLinkVerifySchema = z.object({\n token: z.string().min(1).max(512),\n})\n\nexport const invitationAcceptSchema = z.object({\n token: z.string().min(1).max(512),\n password: passwordField,\n displayName: displayNameField,\n})\n\nexport const profileUpdateSchema = z.object({\n displayName: displayNameField.optional(),\n})\n\nexport const passwordChangeSchema = z.object({\n currentPassword: z.string().min(1).max(128),\n newPassword: passwordField,\n})\n\nexport const createRoleSchema = z.object({\n name: z.string().min(1).max(255),\n slug: z.string().min(1).max(255).regex(/^[a-z0-9_-]+$/),\n description: z.string().max(1000).optional(),\n isDefault: z.boolean().optional(),\n customerAssignable: z.boolean().optional(),\n})\n\nexport const updateRoleSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n description: z.string().max(1000).optional(),\n isDefault: z.boolean().optional(),\n customerAssignable: z.boolean().optional(),\n})\n\nexport const updateRoleAclSchema = z.object({\n features: z.array(z.string().min(1).max(255)),\n isPortalAdmin: z.boolean().optional(),\n})\n\nexport const inviteUserSchema = z.object({\n email: emailField,\n customerEntityId: z.string().uuid().optional(),\n personEntityId: z.string().uuid().optional(),\n roleIds: z.array(z.string().uuid()).min(1),\n displayName: displayNameField.optional(),\n})\n\nexport const cancelInvitationSchema = z.object({\n id: z.string().uuid(),\n})\n\nexport type CancelInvitationInput = z.infer<typeof cancelInvitationSchema>\n\nexport const assignRolesSchema = z.object({\n roleIds: z.array(z.string().uuid()).min(1),\n})\n\nexport const adminCreateUserSchema = z.object({\n email: emailField,\n password: passwordField,\n displayName: displayNameField,\n roleIds: z.array(z.string().uuid()).optional(),\n customerEntityId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const adminUpdateUserSchema = z.object({\n displayName: displayNameField.optional(),\n isActive: z.boolean().optional(),\n lockedUntil: z.string().datetime().nullable().optional(),\n personEntityId: z.string().uuid().nullable().optional(),\n customerEntityId: z.string().uuid().nullable().optional(),\n roleIds: z.array(z.string().uuid()).optional(),\n})\n\nexport const adminResetPasswordSchema = z.object({\n newPassword: passwordField,\n})\n\nexport type AdminCreateUserInput = z.infer<typeof adminCreateUserSchema>\nexport type AdminResetPasswordInput = z.infer<typeof adminResetPasswordSchema>\nexport type SignupInput = z.infer<typeof signupSchema>\nexport type LoginInput = z.infer<typeof loginSchema>\nexport type EmailVerifyInput = z.infer<typeof emailVerifySchema>\nexport type PasswordResetRequestInput = z.infer<typeof passwordResetRequestSchema>\nexport type PasswordResetConfirmInput = z.infer<typeof passwordResetConfirmSchema>\nexport type MagicLinkRequestInput = z.infer<typeof magicLinkRequestSchema>\nexport type MagicLinkVerifyInput = z.infer<typeof magicLinkVerifySchema>\nexport type InvitationAcceptInput = z.infer<typeof invitationAcceptSchema>\nexport type ProfileUpdateInput = z.infer<typeof profileUpdateSchema>\nexport type PasswordChangeInput = z.infer<typeof passwordChangeSchema>\nexport type CreateRoleInput = z.infer<typeof createRoleSchema>\nexport type UpdateRoleInput = z.infer<typeof updateRoleSchema>\nexport type UpdateRoleAclInput = z.infer<typeof updateRoleAclSchema>\nexport type InviteUserInput = z.infer<typeof inviteUserSchema>\nexport type AssignRolesInput = z.infer<typeof assignRolesSchema>\nexport type AdminUpdateUserInput = z.infer<typeof adminUpdateUserSchema>\n\n// Custom domain mapping\nexport const hostnameSchema = z\n .string()\n .min(1, 'Hostname is required')\n .max(512, 'Hostname is too long')\n .transform((value, ctx) => {\n try {\n return normalizeHostname(value)\n } catch (err) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: err instanceof Error ? err.message : 'Invalid hostname',\n })\n return z.NEVER\n }\n })\n\nexport const registerDomainSchema = z.object({\n hostname: hostnameSchema,\n organizationId: z.string().uuid(),\n replacesDomainId: z.string().uuid().optional(),\n})\n\nexport type RegisterDomainInput = z.infer<typeof registerDomainSchema>\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,yBAAyB;AAElC,MAAM,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,GAAG;AAC7C,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAC/C,MAAM,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAE3C,MAAM,eAAe,EAAE,OAAO;AAAA,EACnC,OAAO;AAAA,EACP,UAAU;AAAA,
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport { normalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\n\nconst emailField = z.string().email().max(255)\nconst passwordField = z.string().min(8).max(128)\nconst displayNameField = z.string().min(1).max(255)\n\nexport const signupSchema = z.object({\n email: emailField,\n password: passwordField.optional(),\n displayName: displayNameField,\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const loginSchema = z.object({\n email: emailField,\n password: z.string().min(1).max(128),\n tenantId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const emailVerifySchema = z.object({\n token: z.string().min(1).max(512),\n password: passwordField.optional(),\n})\n\nexport const passwordResetRequestSchema = z.object({\n email: emailField,\n tenantId: z.string().uuid().optional(),\n})\n\nexport const passwordResetConfirmSchema = z.object({\n token: z.string().min(1).max(512),\n password: passwordField,\n})\n\nexport const magicLinkRequestSchema = z.object({\n email: emailField,\n tenantId: z.string().uuid().optional(),\n})\n\nexport const magicLinkVerifySchema = z.object({\n token: z.string().min(1).max(512),\n})\n\nexport const invitationAcceptSchema = z.object({\n token: z.string().min(1).max(512),\n password: passwordField,\n displayName: displayNameField,\n})\n\nexport const profileUpdateSchema = z.object({\n displayName: displayNameField.optional(),\n})\n\nexport const passwordChangeSchema = z.object({\n currentPassword: z.string().min(1).max(128),\n newPassword: passwordField,\n})\n\nexport const createRoleSchema = z.object({\n name: z.string().min(1).max(255),\n slug: z.string().min(1).max(255).regex(/^[a-z0-9_-]+$/),\n description: z.string().max(1000).optional(),\n isDefault: z.boolean().optional(),\n customerAssignable: z.boolean().optional(),\n})\n\nexport const updateRoleSchema = z.object({\n name: z.string().min(1).max(255).optional(),\n description: z.string().max(1000).optional(),\n isDefault: z.boolean().optional(),\n customerAssignable: z.boolean().optional(),\n})\n\nexport const updateRoleAclSchema = z.object({\n features: z.array(z.string().min(1).max(255)),\n isPortalAdmin: z.boolean().optional(),\n})\n\nexport const inviteUserSchema = z.object({\n email: emailField,\n customerEntityId: z.string().uuid().optional(),\n personEntityId: z.string().uuid().optional(),\n roleIds: z.array(z.string().uuid()).min(1),\n displayName: displayNameField.optional(),\n})\n\nexport const cancelInvitationSchema = z.object({\n id: z.string().uuid(),\n})\n\nexport type CancelInvitationInput = z.infer<typeof cancelInvitationSchema>\n\nexport const assignRolesSchema = z.object({\n roleIds: z.array(z.string().uuid()).min(1),\n})\n\nexport const adminCreateUserSchema = z.object({\n email: emailField,\n password: passwordField,\n displayName: displayNameField,\n roleIds: z.array(z.string().uuid()).optional(),\n customerEntityId: z.string().uuid().optional(),\n organizationId: z.string().uuid().optional(),\n})\n\nexport const adminUpdateUserSchema = z.object({\n displayName: displayNameField.optional(),\n isActive: z.boolean().optional(),\n lockedUntil: z.string().datetime().nullable().optional(),\n personEntityId: z.string().uuid().nullable().optional(),\n customerEntityId: z.string().uuid().nullable().optional(),\n roleIds: z.array(z.string().uuid()).optional(),\n})\n\nexport const adminResetPasswordSchema = z.object({\n newPassword: passwordField,\n})\n\nexport type AdminCreateUserInput = z.infer<typeof adminCreateUserSchema>\nexport type AdminResetPasswordInput = z.infer<typeof adminResetPasswordSchema>\nexport type SignupInput = z.infer<typeof signupSchema>\nexport type LoginInput = z.infer<typeof loginSchema>\nexport type EmailVerifyInput = z.infer<typeof emailVerifySchema>\nexport type PasswordResetRequestInput = z.infer<typeof passwordResetRequestSchema>\nexport type PasswordResetConfirmInput = z.infer<typeof passwordResetConfirmSchema>\nexport type MagicLinkRequestInput = z.infer<typeof magicLinkRequestSchema>\nexport type MagicLinkVerifyInput = z.infer<typeof magicLinkVerifySchema>\nexport type InvitationAcceptInput = z.infer<typeof invitationAcceptSchema>\nexport type ProfileUpdateInput = z.infer<typeof profileUpdateSchema>\nexport type PasswordChangeInput = z.infer<typeof passwordChangeSchema>\nexport type CreateRoleInput = z.infer<typeof createRoleSchema>\nexport type UpdateRoleInput = z.infer<typeof updateRoleSchema>\nexport type UpdateRoleAclInput = z.infer<typeof updateRoleAclSchema>\nexport type InviteUserInput = z.infer<typeof inviteUserSchema>\nexport type AssignRolesInput = z.infer<typeof assignRolesSchema>\nexport type AdminUpdateUserInput = z.infer<typeof adminUpdateUserSchema>\n\n// Custom domain mapping\nexport const hostnameSchema = z\n .string()\n .min(1, 'Hostname is required')\n .max(512, 'Hostname is too long')\n .transform((value, ctx) => {\n try {\n return normalizeHostname(value)\n } catch (err) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: err instanceof Error ? err.message : 'Invalid hostname',\n })\n return z.NEVER\n }\n })\n\nexport const registerDomainSchema = z.object({\n hostname: hostnameSchema,\n organizationId: z.string().uuid(),\n replacesDomainId: z.string().uuid().optional(),\n})\n\nexport type RegisterDomainInput = z.infer<typeof registerDomainSchema>\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,yBAAyB;AAElC,MAAM,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,GAAG;AAC7C,MAAM,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAC/C,MAAM,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAE3C,MAAM,eAAe,EAAE,OAAO;AAAA,EACnC,OAAO;AAAA,EACP,UAAU,cAAc,SAAS;AAAA,EACjC,aAAa;AAAA,EACb,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACrC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAC7C,CAAC;AAEM,MAAM,cAAc,EAAE,OAAO;AAAA,EAClC,OAAO;AAAA,EACP,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EACnC,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EACrC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAC7C,CAAC;A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AK,EAAE,SAAS;AAAA,EAC7C,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAC7C,CAAC;AAEM,MAAM,wBAAwB,EAAE,OAAO;AAAA,EAC5C,aAAa,iBAAiB,SAAS;AAAA,EACvC,UAAU,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC/B,aAAa,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS;AAAA,EACvD,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AAAA,EACtD,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AAAA,EACxD,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,SAAS;AAC/C,CAAC;AAEM,MAAM,2BAA2B,EAAE,OAAO;AAAA,EAC/C,aAAa;AACf,CAAC;AAsBM,MAAM,iBAAiB,EAC3B,OAAO,EACP,IAAI,GAAG,sBAAsB,EAC7B,IAAI,KAAK,sBAAsB,EAC/B,UAAU,CAAC,OAAO,QAAQ;AACzB,MAAI;AACF,WAAO,kBAAkB,KAAK;AAAA,EAChC,SAAS,KAAK;AACZ,QAAI,SAAS;AAAA,MACX,MAAM,EAAE,aAAa;AAAA,MACrB,SAAS,eAAe,QAAQ,IAAI,UAAU;AAAA,IAChD,CAAC;AACD,WAAO,EAAE;AAAA,EACX;AACF,CAAC;AAEI,MAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,UAAU;AAAA,EACV,gBAAgB,EAAE,OAAO,EAAE,KAAK;AAAA,EAChC,kBAAkB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAC/C,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -11,13 +11,12 @@ async function resolveSessionService() {
|
|
|
11
11
|
const container = await createRequestContainer();
|
|
12
12
|
return container.resolve("customerSessionService");
|
|
13
13
|
}
|
|
14
|
-
async function
|
|
14
|
+
async function findSessionStillActive(input) {
|
|
15
15
|
try {
|
|
16
16
|
const service = await resolveSessionService();
|
|
17
|
-
|
|
18
|
-
return session !== null;
|
|
17
|
+
return await service.findActiveSessionForClaims(input);
|
|
19
18
|
} catch {
|
|
20
|
-
return
|
|
19
|
+
return null;
|
|
21
20
|
}
|
|
22
21
|
}
|
|
23
22
|
async function assertUserStillHasActiveSession(input) {
|
|
@@ -39,7 +38,7 @@ function readCookieFromHeader(header, name) {
|
|
|
39
38
|
}
|
|
40
39
|
return void 0;
|
|
41
40
|
}
|
|
42
|
-
async function validateUserState(sub, tenantId, orgId, iat) {
|
|
41
|
+
async function validateUserState(sub, tenantId, orgId, iat, sessionCreatedAt) {
|
|
43
42
|
const [{ createRequestContainer }, { CustomerUser }] = await Promise.all([
|
|
44
43
|
import("@open-mercato/shared/lib/di/container"),
|
|
45
44
|
import("@open-mercato/core/modules/customer_accounts/data/entities")
|
|
@@ -52,7 +51,8 @@ async function validateUserState(sub, tenantId, orgId, iat) {
|
|
|
52
51
|
if (!user) return { valid: false };
|
|
53
52
|
if (user.deletedAt) return { valid: false };
|
|
54
53
|
if (!user.isActive) return { valid: false };
|
|
55
|
-
|
|
54
|
+
const issuedAt = sessionCreatedAt?.getTime() ?? (typeof iat === "number" ? iat * 1e3 : void 0);
|
|
55
|
+
if (user.sessionsRevokedAt && issuedAt !== void 0 && issuedAt < user.sessionsRevokedAt.getTime()) {
|
|
56
56
|
return { valid: false };
|
|
57
57
|
}
|
|
58
58
|
if (!await isCustomerTenantActive(em, tenantId)) return { valid: false };
|
|
@@ -109,18 +109,19 @@ async function getCustomerAuthFromRequest(req) {
|
|
|
109
109
|
const userId = String(payload.sub);
|
|
110
110
|
const tenantId = String(payload.tenantId);
|
|
111
111
|
const organizationId = String(payload.orgId);
|
|
112
|
-
const
|
|
112
|
+
const session = sid ? await findSessionStillActive({
|
|
113
113
|
sessionId: sid,
|
|
114
114
|
userId,
|
|
115
115
|
tenantId,
|
|
116
116
|
organizationId
|
|
117
|
-
}) :
|
|
118
|
-
if (!
|
|
117
|
+
}) : null;
|
|
118
|
+
if (sid ? !session : !await assertUserStillHasActiveSession({ userId, tenantId, organizationId })) return null;
|
|
119
119
|
const userState = await validateUserState(
|
|
120
120
|
userId,
|
|
121
121
|
tenantId,
|
|
122
122
|
organizationId,
|
|
123
|
-
payload.iat
|
|
123
|
+
payload.iat,
|
|
124
|
+
session?.createdAt
|
|
124
125
|
);
|
|
125
126
|
if (!userState.valid || !userState.tenantId || !userState.organizationId) return null;
|
|
126
127
|
return {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/lib/customerAuth.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { verifyAudienceJwt, verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport type { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CUSTOMER_JWT_AUDIENCE } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { isCustomerTenantActive } from './tenantEligibility'\n\nexport interface CustomerAuthContext {\n sub: string\n sid: string\n type: 'customer'\n tenantId: string\n orgId: string\n email: string\n displayName: string\n customerEntityId?: string | null\n personEntityId?: string | null\n resolvedFeatures: string[]\n isPortalAdmin?: boolean\n}\n\nasync function resolveSessionService(): Promise<\n InstanceType<typeof import('@open-mercato/core/modules/customer_accounts/services/customerSessionService').CustomerSessionService>\n> {\n const [{ createRequestContainer }, { CustomerSessionService }] = await Promise.all([\n import('@open-mercato/shared/lib/di/container'),\n import('@open-mercato/core/modules/customer_accounts/services/customerSessionService'),\n ])\n const container = await createRequestContainer()\n return container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>\n}\n\nasync function assertSessionStillActive(input: {\n sessionId: string\n userId: string\n tenantId: string\n organizationId: string\n}): Promise<boolean> {\n try {\n const service = await resolveSessionService()\n const session = await service.findActiveSessionForClaims(input)\n return session !== null\n } catch {\n // Fail closed: if we cannot verify the session, treat the token as revoked to prevent\n // replay of leaked JWTs when the backend is partially degraded.\n return false\n }\n}\n\n/**\n * Liveness re-check for a legacy token that carries no `sid` claim. It cannot name the session it\n * was issued for, so the check falls back to the strongest available statement: the customer must\n * still be signed in somewhere. Once every session is revoked \u2014 logout, per-device revoke, admin\n * action \u2014 the token stops authenticating instead of surviving until its own expiry.\n */\nasync function assertUserStillHasActiveSession(input: {\n userId: string\n tenantId: string\n organizationId: string\n}): Promise<boolean> {\n try {\n const service = await resolveSessionService()\n return await service.hasActiveSessionForUser(input)\n } catch {\n // Same fail-closed contract as the sid-bound check above.\n return false\n }\n}\n\nexport function readCookieFromHeader(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined\n const parts = header.split(';')\n for (const part of parts) {\n const trimmed = part.trim()\n if (trimmed.startsWith(`${name}=`)) {\n return trimmed.slice(name.length + 1)\n }\n }\n return undefined\n}\n\nexport type UserValidationResult =\n | { valid: false }\n | {\n valid: true\n resolvedFeatures: string[]\n isPortalAdmin: boolean\n tenantId?: string\n organizationId?: string\n customerEntityId?: string | null\n personEntityId?: string | null\n }\n\nexport async function validateUserState(\n sub: string,\n tenantId: string,\n orgId: string,\n iat: unknown,\n): Promise<UserValidationResult> {\n const [{ createRequestContainer }, { CustomerUser }] = await Promise.all([\n import('@open-mercato/shared/lib/di/container'),\n import('@open-mercato/core/modules/customer_accounts/data/entities'),\n ])\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const user = await findOneWithDecryption(em, CustomerUser, { id: sub }, {\n fields: ['tenantId', 'organizationId', 'customerEntityId', 'personEntityId', 'sessionsRevokedAt', 'deletedAt', 'isActive'],\n })\n if (!user) return { valid: false }\n if (user.deletedAt) return { valid: false }\n if (!user.isActive) return { valid: false }\n if (user.sessionsRevokedAt && typeof iat === 'number' && iat * 1000 < user.sessionsRevokedAt.getTime()) {\n return { valid: false }\n }\n if (!(await isCustomerTenantActive(em, tenantId))) return { valid: false }\n\n // Trusted scope (#2244): the JWT's tenantId/orgId are a hint only, same as the staff auth\n // contract (resolveCanonicalStaffAuthContext). A token issued before a tenant/org change \u2014\n // or carrying a forged claim \u2014 is rejected outright rather than trusted for authorization.\n const currentTenantId = String(user.tenantId)\n const currentOrganizationId = String(user.organizationId)\n if (currentTenantId !== tenantId || currentOrganizationId !== orgId) {\n return { valid: false }\n }\n\n const { CustomerRbacService } = await import(\n '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\n )\n const rbac = container.resolve('customerRbacService') as InstanceType<typeof CustomerRbacService>\n const acl = await rbac.loadAcl(sub, { tenantId: currentTenantId, organizationId: currentOrganizationId })\n const resolvedFeatures = await rbac.getEffectiveFeatures(sub, {\n tenantId: currentTenantId,\n organizationId: currentOrganizationId,\n })\n return {\n valid: true,\n resolvedFeatures,\n isPortalAdmin: acl.isPortalAdmin,\n tenantId: currentTenantId,\n organizationId: currentOrganizationId,\n customerEntityId: user.customerEntityId ? String(user.customerEntityId) : null,\n personEntityId: user.personEntityId ? String(user.personEntityId) : null,\n }\n}\n\nexport async function getCustomerAuthFromRequest(req: Request): Promise<CustomerAuthContext | null> {\n const cookieHeader = req.headers.get('cookie') || ''\n const authHeader = (req.headers.get('authorization') || '').trim()\n\n let token: string | undefined\n if (authHeader.toLowerCase().startsWith('bearer ')) {\n token = authHeader.slice(7).trim()\n }\n if (!token) {\n const cookieValue = readCookieFromHeader(cookieHeader, 'customer_auth_token')\n if (cookieValue) {\n try {\n token = decodeURIComponent(cookieValue)\n } catch {\n // Malformed percent-encoding; use raw value\n token = cookieValue\n }\n }\n }\n if (!token) return null\n\n try {\n let payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token) as Record<string, unknown> | null\n // Legacy fallback: accept a pre-migration customer token signed with the raw JWT_SECRET, but\n // only while `verifyJwt` itself still considers it legacy \u2014 it owns the grace window (token\n // `iat` vs JWT_LEGACY_GRACE_MINUTES / JWT_LEGACY_CUTOVER_AT) and marks the payload. Trusting\n // the bare return value would also let a staff-audience token through this branch, because\n // the default `verifyJwt` path verifies against the staff-derived key.\n if (!payload) {\n const legacyPayload = verifyJwt(token) as Record<string, unknown> | null\n if (legacyPayload && legacyPayload._legacyToken === true) payload = legacyPayload\n }\n if (!payload) return null\n if (payload.type !== 'customer') return null\n const sid = typeof payload.sid === 'string' ? payload.sid : ''\n if (!sid && payload._legacyToken !== true) return null\n const userId = String(payload.sub)\n const tenantId = String(payload.tenantId)\n const organizationId = String(payload.orgId)\n // Every accepted token is re-checked for liveness, exactly like the SSR path does \u2014 a token\n // without a `sid` is checked against the customer's remaining sessions rather than skipped,\n // so session revocation is never structurally unreachable on the API path.\n const stillActive = sid\n ? await assertSessionStillActive({\n sessionId: sid,\n userId,\n tenantId,\n organizationId,\n })\n : await assertUserStillHasActiveSession({ userId, tenantId, organizationId })\n if (!stillActive) return null\n\n const userState = await validateUserState(\n userId,\n tenantId,\n organizationId,\n payload.iat,\n )\n if (!userState.valid || !userState.tenantId || !userState.organizationId) return null\n\n return {\n sub: userId,\n sid,\n type: 'customer',\n // Authorization scope comes from userState (re-derived from the DB in validateUserState),\n // not from the JWT's own tenantId/orgId/customerEntityId/personEntityId claims (#2244).\n tenantId: userState.tenantId,\n orgId: userState.organizationId,\n email: String(payload.email || ''),\n displayName: String(payload.displayName || ''),\n customerEntityId: userState.customerEntityId ?? null,\n personEntityId: userState.personEntityId ?? null,\n resolvedFeatures: userState.resolvedFeatures,\n isPortalAdmin: userState.isPortalAdmin,\n }\n } catch {\n // Invalid or expired JWT \u2014 treat as unauthenticated\n return null\n }\n}\n\nexport async function requireCustomerAuth(req: Request): Promise<CustomerAuthContext> {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n throw NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n return auth\n}\n\nexport async function requireCustomerFeature(\n auth: CustomerAuthContext,\n features: string[],\n rbac: CustomerRbacService,\n): Promise<void> {\n if (!features.length) return\n const ok = await rbac.userHasAllFeatures(\n auth.sub,\n features,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!ok) {\n throw NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB,iBAAiB;AAE7C,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAgBvC,eAAe,wBAEb;AACA,QAAM,CAAC,EAAE,uBAAuB,GAAG,EAAE,uBAAuB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,IACjF,OAAO,uCAAuC;AAAA,IAC9C,OAAO,8EAA8E;AAAA,EACvF,CAAC;AACD,QAAM,YAAY,MAAM,uBAAuB;AAC/C,SAAO,UAAU,QAAQ,wBAAwB;AACnD;AAEA,eAAe,
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { verifyAudienceJwt, verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport type { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CUSTOMER_JWT_AUDIENCE } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { isCustomerTenantActive } from './tenantEligibility'\n\nexport interface CustomerAuthContext {\n sub: string\n sid: string\n type: 'customer'\n tenantId: string\n orgId: string\n email: string\n displayName: string\n customerEntityId?: string | null\n personEntityId?: string | null\n resolvedFeatures: string[]\n isPortalAdmin?: boolean\n}\n\nasync function resolveSessionService(): Promise<\n InstanceType<typeof import('@open-mercato/core/modules/customer_accounts/services/customerSessionService').CustomerSessionService>\n> {\n const [{ createRequestContainer }, { CustomerSessionService }] = await Promise.all([\n import('@open-mercato/shared/lib/di/container'),\n import('@open-mercato/core/modules/customer_accounts/services/customerSessionService'),\n ])\n const container = await createRequestContainer()\n return container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>\n}\n\nasync function findSessionStillActive(input: {\n sessionId: string\n userId: string\n tenantId: string\n organizationId: string\n}) {\n try {\n const service = await resolveSessionService()\n return await service.findActiveSessionForClaims(input)\n } catch {\n // Fail closed: if we cannot verify the session, treat the token as revoked to prevent\n // replay of leaked JWTs when the backend is partially degraded.\n return null\n }\n}\n\n/**\n * Liveness re-check for a legacy token that carries no `sid` claim. It cannot name the session it\n * was issued for, so the check falls back to the strongest available statement: the customer must\n * still be signed in somewhere. Once every session is revoked \u2014 logout, per-device revoke, admin\n * action \u2014 the token stops authenticating instead of surviving until its own expiry.\n */\nasync function assertUserStillHasActiveSession(input: {\n userId: string\n tenantId: string\n organizationId: string\n}): Promise<boolean> {\n try {\n const service = await resolveSessionService()\n return await service.hasActiveSessionForUser(input)\n } catch {\n // Same fail-closed contract as the sid-bound check above.\n return false\n }\n}\n\nexport function readCookieFromHeader(header: string | null | undefined, name: string): string | undefined {\n if (!header) return undefined\n const parts = header.split(';')\n for (const part of parts) {\n const trimmed = part.trim()\n if (trimmed.startsWith(`${name}=`)) {\n return trimmed.slice(name.length + 1)\n }\n }\n return undefined\n}\n\nexport type UserValidationResult =\n | { valid: false }\n | {\n valid: true\n resolvedFeatures: string[]\n isPortalAdmin: boolean\n tenantId?: string\n organizationId?: string\n customerEntityId?: string | null\n personEntityId?: string | null\n }\n\nexport async function validateUserState(\n sub: string,\n tenantId: string,\n orgId: string,\n iat: unknown,\n sessionCreatedAt?: Date,\n): Promise<UserValidationResult> {\n const [{ createRequestContainer }, { CustomerUser }] = await Promise.all([\n import('@open-mercato/shared/lib/di/container'),\n import('@open-mercato/core/modules/customer_accounts/data/entities'),\n ])\n const container = await createRequestContainer()\n const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager\n const user = await findOneWithDecryption(em, CustomerUser, { id: sub }, {\n fields: ['tenantId', 'organizationId', 'customerEntityId', 'personEntityId', 'sessionsRevokedAt', 'deletedAt', 'isActive'],\n })\n if (!user) return { valid: false }\n if (user.deletedAt) return { valid: false }\n if (!user.isActive) return { valid: false }\n const issuedAt = sessionCreatedAt?.getTime() ?? (typeof iat === 'number' ? iat * 1000 : undefined)\n if (user.sessionsRevokedAt && issuedAt !== undefined && issuedAt < user.sessionsRevokedAt.getTime()) {\n return { valid: false }\n }\n if (!(await isCustomerTenantActive(em, tenantId))) return { valid: false }\n\n // Trusted scope (#2244): the JWT's tenantId/orgId are a hint only, same as the staff auth\n // contract (resolveCanonicalStaffAuthContext). A token issued before a tenant/org change \u2014\n // or carrying a forged claim \u2014 is rejected outright rather than trusted for authorization.\n const currentTenantId = String(user.tenantId)\n const currentOrganizationId = String(user.organizationId)\n if (currentTenantId !== tenantId || currentOrganizationId !== orgId) {\n return { valid: false }\n }\n\n const { CustomerRbacService } = await import(\n '@open-mercato/core/modules/customer_accounts/services/customerRbacService'\n )\n const rbac = container.resolve('customerRbacService') as InstanceType<typeof CustomerRbacService>\n const acl = await rbac.loadAcl(sub, { tenantId: currentTenantId, organizationId: currentOrganizationId })\n const resolvedFeatures = await rbac.getEffectiveFeatures(sub, {\n tenantId: currentTenantId,\n organizationId: currentOrganizationId,\n })\n return {\n valid: true,\n resolvedFeatures,\n isPortalAdmin: acl.isPortalAdmin,\n tenantId: currentTenantId,\n organizationId: currentOrganizationId,\n customerEntityId: user.customerEntityId ? String(user.customerEntityId) : null,\n personEntityId: user.personEntityId ? String(user.personEntityId) : null,\n }\n}\n\nexport async function getCustomerAuthFromRequest(req: Request): Promise<CustomerAuthContext | null> {\n const cookieHeader = req.headers.get('cookie') || ''\n const authHeader = (req.headers.get('authorization') || '').trim()\n\n let token: string | undefined\n if (authHeader.toLowerCase().startsWith('bearer ')) {\n token = authHeader.slice(7).trim()\n }\n if (!token) {\n const cookieValue = readCookieFromHeader(cookieHeader, 'customer_auth_token')\n if (cookieValue) {\n try {\n token = decodeURIComponent(cookieValue)\n } catch {\n // Malformed percent-encoding; use raw value\n token = cookieValue\n }\n }\n }\n if (!token) return null\n\n try {\n let payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token) as Record<string, unknown> | null\n // Legacy fallback: accept a pre-migration customer token signed with the raw JWT_SECRET, but\n // only while `verifyJwt` itself still considers it legacy \u2014 it owns the grace window (token\n // `iat` vs JWT_LEGACY_GRACE_MINUTES / JWT_LEGACY_CUTOVER_AT) and marks the payload. Trusting\n // the bare return value would also let a staff-audience token through this branch, because\n // the default `verifyJwt` path verifies against the staff-derived key.\n if (!payload) {\n const legacyPayload = verifyJwt(token) as Record<string, unknown> | null\n if (legacyPayload && legacyPayload._legacyToken === true) payload = legacyPayload\n }\n if (!payload) return null\n if (payload.type !== 'customer') return null\n const sid = typeof payload.sid === 'string' ? payload.sid : ''\n if (!sid && payload._legacyToken !== true) return null\n const userId = String(payload.sub)\n const tenantId = String(payload.tenantId)\n const organizationId = String(payload.orgId)\n // Every accepted token is re-checked for liveness, exactly like the SSR path does \u2014 a token\n // without a `sid` is checked against the customer's remaining sessions rather than skipped,\n // so session revocation is never structurally unreachable on the API path.\n const session = sid\n ? await findSessionStillActive({\n sessionId: sid,\n userId,\n tenantId,\n organizationId,\n })\n : null\n if (sid ? !session : !(await assertUserStillHasActiveSession({ userId, tenantId, organizationId }))) return null\n\n const userState = await validateUserState(\n userId,\n tenantId,\n organizationId,\n payload.iat,\n session?.createdAt,\n )\n if (!userState.valid || !userState.tenantId || !userState.organizationId) return null\n\n return {\n sub: userId,\n sid,\n type: 'customer',\n // Authorization scope comes from userState (re-derived from the DB in validateUserState),\n // not from the JWT's own tenantId/orgId/customerEntityId/personEntityId claims (#2244).\n tenantId: userState.tenantId,\n orgId: userState.organizationId,\n email: String(payload.email || ''),\n displayName: String(payload.displayName || ''),\n customerEntityId: userState.customerEntityId ?? null,\n personEntityId: userState.personEntityId ?? null,\n resolvedFeatures: userState.resolvedFeatures,\n isPortalAdmin: userState.isPortalAdmin,\n }\n } catch {\n // Invalid or expired JWT \u2014 treat as unauthenticated\n return null\n }\n}\n\nexport async function requireCustomerAuth(req: Request): Promise<CustomerAuthContext> {\n const auth = await getCustomerAuthFromRequest(req)\n if (!auth) {\n throw NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 })\n }\n return auth\n}\n\nexport async function requireCustomerFeature(\n auth: CustomerAuthContext,\n features: string[],\n rbac: CustomerRbacService,\n): Promise<void> {\n if (!features.length) return\n const ok = await rbac.userHasAllFeatures(\n auth.sub,\n features,\n { tenantId: auth.tenantId, organizationId: auth.orgId },\n )\n if (!ok) {\n throw NextResponse.json({ ok: false, error: 'Insufficient permissions' }, { status: 403 })\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,mBAAmB,iBAAiB;AAE7C,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,8BAA8B;AAgBvC,eAAe,wBAEb;AACA,QAAM,CAAC,EAAE,uBAAuB,GAAG,EAAE,uBAAuB,CAAC,IAAI,MAAM,QAAQ,IAAI;AAAA,IACjF,OAAO,uCAAuC;AAAA,IAC9C,OAAO,8EAA8E;AAAA,EACvF,CAAC;AACD,QAAM,YAAY,MAAM,uBAAuB;AAC/C,SAAO,UAAU,QAAQ,wBAAwB;AACnD;AAEA,eAAe,uBAAuB,OAKnC;AACD,MAAI;AACF,UAAM,UAAU,MAAM,sBAAsB;AAC5C,WAAO,MAAM,QAAQ,2BAA2B,KAAK;AAAA,EACvD,QAAQ;AAGN,WAAO;AAAA,EACT;AACF;AAQA,eAAe,gCAAgC,OAI1B;AACnB,MAAI;AACF,UAAM,UAAU,MAAM,sBAAsB;AAC5C,WAAO,MAAM,QAAQ,wBAAwB,KAAK;AAAA,EACpD,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,qBAAqB,QAAmC,MAAkC;AACxG,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,QAAQ,OAAO,MAAM,GAAG;AAC9B,aAAW,QAAQ,OAAO;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