@open-mercato/core 0.11.1-develop.8545.1.dd603570fd → 0.11.1-develop.8556.1.d944a8493f
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/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/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/pendingSignup.js +16 -0
- package/dist/modules/customer_accounts/lib/pendingSignup.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/customers/commands/companies.js +8 -6
- package/dist/modules/customers/commands/companies.js.map +2 -2
- package/dist/modules/customers/commands/deals.js +24 -13
- package/dist/modules/customers/commands/deals.js.map +2 -2
- package/dist/modules/customers/commands/people.js +8 -6
- package/dist/modules/customers/commands/people.js.map +2 -2
- package/dist/modules/entities/lib/helpers.js +6 -2
- package/dist/modules/entities/lib/helpers.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/package.json +8 -8
- package/src/modules/customer_accounts/api/admin/users/[id]/verify-email.ts +11 -33
- 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/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/pendingSignup.ts +12 -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/customers/commands/companies.ts +7 -5
- package/src/modules/customers/commands/deals.ts +22 -12
- package/src/modules/customers/commands/people.ts +7 -4
- package/src/modules/entities/lib/helpers.ts +8 -2
- 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
|
@@ -1,66 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { jsx
|
|
3
|
-
import {
|
|
4
|
-
import Link from "next/link";
|
|
5
|
-
import { useSearchParams } from "next/navigation";
|
|
6
|
-
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
7
|
-
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
|
|
8
|
-
import { Button } from "@open-mercato/ui/primitives/button";
|
|
9
|
-
import { Alert, AlertDescription } from "@open-mercato/ui/primitives/alert";
|
|
10
|
-
import { Spinner } from "@open-mercato/ui/primitives/spinner";
|
|
2
|
+
import { jsx } from "react/jsx-runtime";
|
|
3
|
+
import { PortalPasswordForm } from "../PasswordForm.js";
|
|
11
4
|
function PortalVerifyPage({ params }) {
|
|
12
|
-
|
|
13
|
-
const searchParams = useSearchParams();
|
|
14
|
-
const token = searchParams.get("token") ?? "";
|
|
15
|
-
const [state, setState] = useState(token ? "verifying" : "error");
|
|
16
|
-
const [error, setError] = useState(token ? null : t("portal.verify.error.invalidToken", "Verification token is missing."));
|
|
17
|
-
useEffect(() => {
|
|
18
|
-
if (!token) return;
|
|
19
|
-
let active = true;
|
|
20
|
-
void apiCall("/api/customer_accounts/email/verify", {
|
|
21
|
-
method: "POST",
|
|
22
|
-
headers: { "Content-Type": "application/json" },
|
|
23
|
-
body: JSON.stringify({ token })
|
|
24
|
-
}).then((result) => {
|
|
25
|
-
if (!active) return;
|
|
26
|
-
if (result.ok && result.result?.ok) {
|
|
27
|
-
setState("success");
|
|
28
|
-
return;
|
|
29
|
-
}
|
|
30
|
-
setState("error");
|
|
31
|
-
setError(result.result?.error || t("portal.verify.error.generic", "Email verification failed. Please try again."));
|
|
32
|
-
}).catch(() => {
|
|
33
|
-
if (!active) return;
|
|
34
|
-
setState("error");
|
|
35
|
-
setError(t("portal.verify.error.generic", "Email verification failed. Please try again."));
|
|
36
|
-
});
|
|
37
|
-
return () => {
|
|
38
|
-
active = false;
|
|
39
|
-
};
|
|
40
|
-
}, [token, t]);
|
|
41
|
-
if (state === "verifying") {
|
|
42
|
-
return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex max-w-sm flex-col items-center gap-4 py-12 text-center", children: [
|
|
43
|
-
/* @__PURE__ */ jsx(Spinner, {}),
|
|
44
|
-
/* @__PURE__ */ jsxs("div", { children: [
|
|
45
|
-
/* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.verify.title", "Verifying email") }),
|
|
46
|
-
/* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.verify.description", "Please wait while we verify your email address.") })
|
|
47
|
-
] })
|
|
48
|
-
] });
|
|
49
|
-
}
|
|
50
|
-
if (state === "success") {
|
|
51
|
-
return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex max-w-sm flex-col items-center gap-4 py-12 text-center", children: [
|
|
52
|
-
/* @__PURE__ */ jsx("div", { className: "mx-auto flex size-12 items-center justify-center rounded-full bg-foreground text-background", children: /* @__PURE__ */ jsx("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", className: "size-6", children: /* @__PURE__ */ jsx("polyline", { points: "20 6 9 17 4 12" }) }) }),
|
|
53
|
-
/* @__PURE__ */ jsxs("div", { children: [
|
|
54
|
-
/* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold tracking-tight", children: t("portal.verify.success.title", "Email verified") }),
|
|
55
|
-
/* @__PURE__ */ jsx("p", { className: "mt-1.5 text-sm text-muted-foreground", children: t("portal.verify.success.description", "Your email has been verified. You can now sign in to the portal.") })
|
|
56
|
-
] }),
|
|
57
|
-
/* @__PURE__ */ jsx(Button, { asChild: true, className: "w-full rounded-lg", children: /* @__PURE__ */ jsx(Link, { href: `/${params.orgSlug}/portal/login`, children: t("portal.verify.success.loginLink", "Sign In") }) })
|
|
58
|
-
] });
|
|
59
|
-
}
|
|
60
|
-
return /* @__PURE__ */ jsxs("div", { className: "mx-auto flex max-w-sm flex-col gap-4 py-12", children: [
|
|
61
|
-
/* @__PURE__ */ jsx(Alert, { status: "error", children: /* @__PURE__ */ jsx(AlertDescription, { children: error || t("portal.verify.error.generic", "Email verification failed. Please try again.") }) }),
|
|
62
|
-
/* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", className: "rounded-lg", children: /* @__PURE__ */ jsx(Link, { href: `/${params.orgSlug}/portal/login`, children: t("portal.verify.error.backToLogin", "Back to sign in") }) })
|
|
63
|
-
] });
|
|
5
|
+
return /* @__PURE__ */ jsx(PortalPasswordForm, { params, verify: true });
|
|
64
6
|
}
|
|
65
7
|
export {
|
|
66
8
|
PortalVerifyPage as default
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/portal/frontend/%5BorgSlug%5D/portal/verify/page.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\nimport {
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\nimport { PortalPasswordForm } from '../PasswordForm'\n\nexport default function PortalVerifyPage({ params }: { params: { orgSlug: string } }) {\n return <PortalPasswordForm params={params} verify />\n}\n"],
|
|
5
|
+
"mappings": ";AAIS;AAHT,SAAS,0BAA0B;AAEpB,SAAR,iBAAkC,EAAE,OAAO,GAAoC;AACpF,SAAO,oBAAC,sBAAmB,QAAgB,QAAM,MAAC;AACpD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/core",
|
|
3
|
-
"version": "0.11.1-develop.
|
|
3
|
+
"version": "0.11.1-develop.8556.1.d944a8493f",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"build": "node build.mjs",
|
|
9
9
|
"watch": "node watch.mjs",
|
|
10
10
|
"test": "jest --config jest.config.cjs",
|
|
11
|
-
"test:pg-integration": "cross-env OM_PG_INTEGRATION=1 jest --config jest.config.cjs --runInBand 'src/(modules/((availability|catalog|communication_channels|customer_accounts|eudr|integrations|notifications|progress|staff)/.+\\.integration|workflows/.+\\.pg|customers/migrations/.+\\.integration|entities/__tests__/cli-rehash-lookups\\.integration|payment_gateways/lib/__tests__/gateway-service\\.status-race\\.pg|devices/.+\\.pg)|__tests__/money-numeric-widening-migrations\\.integration)\\.test\\.ts$'",
|
|
11
|
+
"test:pg-integration": "cross-env OM_PG_INTEGRATION=1 jest --config jest.config.cjs --runInBand 'src/(modules/((availability|catalog|communication_channels|customer_accounts|eudr|integrations|notifications|progress|staff)/.+\\.integration|workflows/.+\\.pg|customers/(migrations/.+\\.integration|api/people/__tests__/encrypted-custom-fields\\.pg)|entities/__tests__/cli-rehash-lookups\\.integration|payment_gateways/lib/__tests__/gateway-service\\.status-race\\.pg|devices/.+\\.pg)|__tests__/money-numeric-widening-migrations\\.integration)\\.test\\.ts$'",
|
|
12
12
|
"test:tz": "cross-env TZ=Pacific/Auckland jest --config jest.config.cjs",
|
|
13
13
|
"typecheck": "tsc --noEmit"
|
|
14
14
|
},
|
|
@@ -268,16 +268,16 @@
|
|
|
268
268
|
"zod": "^4.6.6"
|
|
269
269
|
},
|
|
270
270
|
"peerDependencies": {
|
|
271
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8556.1.d944a8493f",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8556.1.d944a8493f",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8556.1.d944a8493f",
|
|
274
274
|
"react": "^19.0.0",
|
|
275
275
|
"react-dom": "^19.0.0"
|
|
276
276
|
},
|
|
277
277
|
"devDependencies": {
|
|
278
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8556.1.d944a8493f",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8556.1.d944a8493f",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8556.1.d944a8493f",
|
|
281
281
|
"@testing-library/dom": "^10.4.1",
|
|
282
282
|
"@testing-library/jest-dom": "^7.0.1",
|
|
283
283
|
"@testing-library/react": "^16.3.3",
|
|
@@ -4,9 +4,8 @@ import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib
|
|
|
4
4
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
5
5
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
6
6
|
import { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'
|
|
7
|
+
import type { CustomerSessionService } from '../../../../services/customerSessionService'
|
|
8
|
+
import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../../../lib/verifyCustomerEmail'
|
|
10
9
|
|
|
11
10
|
export const metadata = {}
|
|
12
11
|
|
|
@@ -25,40 +24,19 @@ export async function POST(req: Request, { params }: { params: { id: string } })
|
|
|
25
24
|
|
|
26
25
|
const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
|
|
27
26
|
|
|
28
|
-
|
|
29
|
-
em,
|
|
30
|
-
CustomerUser,
|
|
31
|
-
{
|
|
32
|
-
id: params.id,
|
|
33
|
-
tenantId: auth.tenantId,
|
|
34
|
-
organizationId: auth.orgId,
|
|
35
|
-
deletedAt: null,
|
|
36
|
-
} as any,
|
|
37
|
-
undefined,
|
|
38
|
-
{ tenantId: auth.tenantId, organizationId: auth.orgId },
|
|
39
|
-
)
|
|
40
|
-
if (!user) {
|
|
27
|
+
if (!auth.tenantId || !auth.orgId) {
|
|
41
28
|
return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })
|
|
42
29
|
}
|
|
43
|
-
|
|
44
|
-
|
|
30
|
+
const scope = { userId: params.id, tenantId: auth.tenantId, organizationId: auth.orgId }
|
|
31
|
+
const sessions = container.resolve<CustomerSessionService>('customerSessionService')
|
|
32
|
+
const result = await em.transactional((tx) => verifyCustomerEmail(tx, scope, sessions))
|
|
33
|
+
if (!result) {
|
|
34
|
+
return NextResponse.json({ ok: false, error: 'User not found' }, { status: 404 })
|
|
35
|
+
}
|
|
36
|
+
if (!result.newlyVerified) {
|
|
45
37
|
return NextResponse.json({ ok: true, alreadyVerified: true })
|
|
46
38
|
}
|
|
47
|
-
|
|
48
|
-
await em.nativeUpdate(CustomerUser, {
|
|
49
|
-
id: user.id,
|
|
50
|
-
tenantId: user.tenantId,
|
|
51
|
-
organizationId: user.organizationId,
|
|
52
|
-
}, { emailVerifiedAt: new Date() })
|
|
53
|
-
|
|
54
|
-
void emitCustomerAccountsEvent('customer_accounts.email.verified', {
|
|
55
|
-
id: user.id,
|
|
56
|
-
recipientUserId: user.id,
|
|
57
|
-
email: user.email,
|
|
58
|
-
tenantId: user.tenantId,
|
|
59
|
-
organizationId: user.organizationId,
|
|
60
|
-
verifiedBy: auth.sub,
|
|
61
|
-
}).catch(() => undefined)
|
|
39
|
+
emitCustomerEmailVerified(result.user, auth.sub)
|
|
62
40
|
|
|
63
41
|
return NextResponse.json({ ok: true })
|
|
64
42
|
}
|
|
@@ -4,8 +4,9 @@ import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib
|
|
|
4
4
|
import { emailVerifySchema } from '@open-mercato/core/modules/customer_accounts/data/validators'
|
|
5
5
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
6
6
|
import { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import type { CustomerSessionService } from '../../services/customerSessionService'
|
|
8
|
+
import type { CustomerUserService } from '../../services/customerUserService'
|
|
9
|
+
import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'
|
|
9
10
|
|
|
10
11
|
export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
|
|
11
12
|
|
|
@@ -26,18 +27,21 @@ export async function POST(req: Request) {
|
|
|
26
27
|
const customerTokenService = container.resolve('customerTokenService') as CustomerTokenService
|
|
27
28
|
const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
|
|
28
29
|
|
|
29
|
-
const
|
|
30
|
+
const sessions = container.resolve<CustomerSessionService>('customerSessionService')
|
|
31
|
+
const { token, password } = parsed.data
|
|
32
|
+
const result = await em.transactional(async (tx) => {
|
|
33
|
+
const identity = await customerTokenService.verifyEmailToken(token, 'email_verification', undefined, tx)
|
|
34
|
+
if (!identity) return null
|
|
35
|
+
const credentials = password === undefined
|
|
36
|
+
? undefined
|
|
37
|
+
: { password, users: container.resolve<CustomerUserService>('customerUserService') }
|
|
38
|
+
return verifyCustomerEmail(tx, identity, sessions, credentials)
|
|
39
|
+
})
|
|
30
40
|
if (!result) {
|
|
31
41
|
return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
|
|
32
42
|
}
|
|
33
43
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
void emitCustomerAccountsEvent('customer_accounts.email.verified', {
|
|
37
|
-
userId: result.userId,
|
|
38
|
-
recipientUserId: result.userId,
|
|
39
|
-
tenantId: result.tenantId,
|
|
40
|
-
}).catch(() => undefined)
|
|
44
|
+
if (result.newlyVerified) emitCustomerEmailVerified(result.user)
|
|
41
45
|
|
|
42
46
|
return NextResponse.json({ ok: true })
|
|
43
47
|
}
|
|
@@ -47,7 +51,7 @@ const errorSchema = z.object({ ok: z.literal(false), error: z.string() })
|
|
|
47
51
|
|
|
48
52
|
const methodDoc: OpenApiMethodDoc = {
|
|
49
53
|
summary: 'Verify customer email address',
|
|
50
|
-
description: '
|
|
54
|
+
description: 'Verifies the email and optionally sets a password chosen by the email recipient.',
|
|
51
55
|
tags: ['Customer Authentication'],
|
|
52
56
|
requestBody: {
|
|
53
57
|
schema: emailVerifySchema,
|
|
@@ -7,8 +7,8 @@ import { CustomerTokenService } from '@open-mercato/core/modules/customer_accoun
|
|
|
7
7
|
import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
|
|
8
8
|
import { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'
|
|
9
9
|
import { CustomerRbacService } from '@open-mercato/core/modules/customer_accounts/services/customerRbacService'
|
|
10
|
-
import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
11
10
|
import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
|
|
11
|
+
import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'
|
|
12
12
|
import { getClientIp } from '@open-mercato/shared/lib/ratelimit/helpers'
|
|
13
13
|
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
14
14
|
import { isCrossSiteBrowserRequest } from '@open-mercato/shared/lib/url'
|
|
@@ -39,21 +39,21 @@ export async function POST(req: Request) {
|
|
|
39
39
|
const customerRbacService = container.resolve('customerRbacService') as CustomerRbacService
|
|
40
40
|
const em = container.resolve('em') as import('@mikro-orm/postgresql').EntityManager
|
|
41
41
|
|
|
42
|
-
const result = await
|
|
42
|
+
const result = await em.transactional(async (tx) => {
|
|
43
|
+
const identity = await customerTokenService.verifyEmailToken(parsed.data.token, 'magic_link', undefined, tx)
|
|
44
|
+
if (!identity) return null
|
|
45
|
+
return { account: await verifyCustomerEmail(tx, identity, customerSessionService) }
|
|
46
|
+
})
|
|
43
47
|
if (!result) {
|
|
44
48
|
return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
|
|
45
49
|
}
|
|
46
50
|
|
|
47
|
-
|
|
48
|
-
if (!user || !user.isActive) {
|
|
51
|
+
if (!result.account) {
|
|
49
52
|
return NextResponse.json({ ok: false, error: 'Account not found or deactivated' }, { status: 401 })
|
|
50
53
|
}
|
|
51
54
|
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
await em.nativeUpdate(CustomerUser, { id: user.id }, { emailVerifiedAt: new Date() })
|
|
55
|
-
user.emailVerifiedAt = new Date()
|
|
56
|
-
}
|
|
55
|
+
const { user, newlyVerified } = result.account
|
|
56
|
+
if (newlyVerified) emitCustomerEmailVerified(user)
|
|
57
57
|
|
|
58
58
|
await customerUserService.resetFailedAttempts(user)
|
|
59
59
|
await customerUserService.updateLastLoginAt(user)
|
|
@@ -6,9 +6,9 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
|
6
6
|
import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
|
|
7
7
|
import { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'
|
|
8
8
|
import { CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'
|
|
9
|
-
import { CustomerUser } from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
10
9
|
import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
|
|
11
10
|
import type { EntityManager } from '@mikro-orm/postgresql'
|
|
11
|
+
import { emitCustomerEmailVerified, verifyCustomerEmail } from '../../lib/verifyCustomerEmail'
|
|
12
12
|
|
|
13
13
|
export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
|
|
14
14
|
|
|
@@ -30,26 +30,21 @@ export async function POST(req: Request) {
|
|
|
30
30
|
const customerUserService = container.resolve('customerUserService') as CustomerUserService
|
|
31
31
|
const customerSessionService = container.resolve('customerSessionService') as CustomerSessionService
|
|
32
32
|
|
|
33
|
-
const
|
|
33
|
+
const em = container.resolve('em') as EntityManager
|
|
34
|
+
const result = await em.transactional(async (tx) => {
|
|
35
|
+
const identity = await customerTokenService.verifyPasswordResetToken(parsed.data.token, undefined, tx)
|
|
36
|
+
if (!identity) return null
|
|
37
|
+
return verifyCustomerEmail(tx, identity, customerSessionService, {
|
|
38
|
+
password: parsed.data.password,
|
|
39
|
+
users: customerUserService,
|
|
40
|
+
reset: true,
|
|
41
|
+
})
|
|
42
|
+
})
|
|
34
43
|
if (!result) {
|
|
35
44
|
return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
|
|
36
45
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if (!user) {
|
|
40
|
-
return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const em = container.resolve('em') as EntityManager
|
|
44
|
-
await em.transactional(async (trx) => {
|
|
45
|
-
await customerUserService.updatePassword(user, parsed.data.password, trx)
|
|
46
|
-
await customerSessionService.revokeAllUserSessions(user.id, trx)
|
|
47
|
-
await trx.nativeUpdate(
|
|
48
|
-
CustomerUser,
|
|
49
|
-
{ id: user.id, emailVerifiedAt: null },
|
|
50
|
-
{ emailVerifiedAt: new Date() },
|
|
51
|
-
)
|
|
52
|
-
})
|
|
46
|
+
const { user, newlyVerified } = result
|
|
47
|
+
if (newlyVerified) emitCustomerEmailVerified(user)
|
|
53
48
|
|
|
54
49
|
void emitCustomerAccountsEvent('customer_accounts.password.changed', {
|
|
55
50
|
userId: user.id,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { NextResponse } from 'next/server'
|
|
2
2
|
import { compare as bcryptCompare } from 'bcryptjs'
|
|
3
|
+
import { UniqueConstraintViolationException } from '@mikro-orm/core'
|
|
3
4
|
import { z } from 'zod'
|
|
4
5
|
import type { OpenApiRouteDoc, OpenApiMethodDoc } from '@open-mercato/shared/lib/openapi'
|
|
5
6
|
import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
|
|
@@ -8,7 +9,7 @@ import { signupSchema } from '@open-mercato/core/modules/customer_accounts/data/
|
|
|
8
9
|
import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
9
10
|
import { CustomerUserService } from '@open-mercato/core/modules/customer_accounts/services/customerUserService'
|
|
10
11
|
import { CustomerTokenService } from '@open-mercato/core/modules/customer_accounts/services/customerTokenService'
|
|
11
|
-
import { CustomerRole, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
12
|
+
import { CustomerRole, CustomerUser, CustomerUserRole } from '@open-mercato/core/modules/customer_accounts/data/entities'
|
|
12
13
|
import { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'
|
|
13
14
|
import CustomerSignupVerificationEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerSignupVerificationEmail'
|
|
14
15
|
import CustomerExistingAccountEmail from '@open-mercato/core/modules/customer_accounts/emails/CustomerExistingAccountEmail'
|
|
@@ -27,14 +28,14 @@ import {
|
|
|
27
28
|
} from '@open-mercato/core/modules/customer_accounts/lib/resolveTenantContext'
|
|
28
29
|
import { urlForCustomerOrg } from '@open-mercato/core/modules/customer_accounts/lib/customerUrl'
|
|
29
30
|
import { createLogger } from '@open-mercato/shared/lib/logger'
|
|
31
|
+
import { pendingSignup, signupExpiryCutoff } from '../lib/pendingSignup'
|
|
30
32
|
|
|
31
33
|
const logger = createLogger('customer_accounts').child({ component: 'signup' })
|
|
32
34
|
|
|
33
35
|
export const metadata: { path?: string; requireAuth?: boolean } = { requireAuth: false }
|
|
34
36
|
|
|
35
37
|
// Precomputed bcrypt cost-10 hash of an unknowable random 32-byte input; used to equalize
|
|
36
|
-
// response latency between
|
|
37
|
-
// 202-for-both contract is not undone by a timing side channel.
|
|
38
|
+
// response latency between new and existing registrations.
|
|
38
39
|
const TIMING_EQUALIZATION_HASH = '$2b$10$.F2A6UHFzk.d8trNdfqt4OLz05Nf3IOuMmN6VJKflhD4.rz.prR8i'
|
|
39
40
|
function resolvePortalLoginUrl(baseUrl: string, organizationSlug?: string | null): string {
|
|
40
41
|
return organizationSlug
|
|
@@ -114,9 +115,22 @@ export async function POST(req: Request) {
|
|
|
114
115
|
return NextResponse.json({ ok: false, error: 'Registration could not be completed' }, { status: 400 })
|
|
115
116
|
}
|
|
116
117
|
|
|
117
|
-
|
|
118
|
+
let existing = await customerUserService.findByEmail(email, tenantId)
|
|
119
|
+
await bcryptCompare(password ?? '', TIMING_EQUALIZATION_HASH)
|
|
120
|
+
const now = new Date()
|
|
121
|
+
const cutoff = signupExpiryCutoff(now)
|
|
122
|
+
if (existing?.isActive && !existing.emailVerifiedAt
|
|
123
|
+
&& !existing.lastLoginAt && existing.createdAt <= cutoff) {
|
|
124
|
+
const retired = await em.nativeUpdate(CustomerUser, {
|
|
125
|
+
id: existing.id,
|
|
126
|
+
tenantId,
|
|
127
|
+
organizationId: existing.organizationId,
|
|
128
|
+
...pendingSignup,
|
|
129
|
+
createdAt: { $lte: cutoff },
|
|
130
|
+
}, { deletedAt: now, isActive: false, passwordHash: null, sessionsRevokedAt: now })
|
|
131
|
+
existing = retired === 1 ? null : await customerUserService.findByEmail(email, tenantId)
|
|
132
|
+
}
|
|
118
133
|
if (existing) {
|
|
119
|
-
await bcryptCompare(password, TIMING_EQUALIZATION_HASH)
|
|
120
134
|
const existingOrg = await findOrganizationInTenant(em, existing.organizationId, tenantId)
|
|
121
135
|
// Prefer the org's active custom domain when available; fall back to the
|
|
122
136
|
// platform login URL preserved by `resolvePortalLoginUrl`.
|
|
@@ -154,25 +168,23 @@ export async function POST(req: Request) {
|
|
|
154
168
|
return NextResponse.json({ ok: true }, { status: 202 })
|
|
155
169
|
}
|
|
156
170
|
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
171
|
+
const signupScope = { tenantId, organizationId }
|
|
172
|
+
const signup = await em.transactional(async (tx) => {
|
|
173
|
+
const defaultRole = await tx.findOne(CustomerRole, { tenantId, isDefault: true, deletedAt: null })
|
|
174
|
+
const user = await customerUserService.createUser(email, null, displayName, signupScope)
|
|
175
|
+
if (defaultRole) tx.persist(tx.create(CustomerUserRole, { user, role: defaultRole, createdAt: new Date() }))
|
|
176
|
+
await tx.persist(user).flush()
|
|
177
|
+
const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId, user.createdAt, tx)
|
|
178
|
+
return { user, verificationToken }
|
|
179
|
+
}).catch(async (error: unknown) => {
|
|
180
|
+
if (error instanceof UniqueConstraintViolationException
|
|
181
|
+
&& (await customerUserService.findByEmail(email, tenantId))) {
|
|
182
|
+
return null
|
|
183
|
+
}
|
|
184
|
+
throw error
|
|
163
185
|
})
|
|
164
|
-
if (
|
|
165
|
-
|
|
166
|
-
user,
|
|
167
|
-
role: defaultRole,
|
|
168
|
-
createdAt: new Date(),
|
|
169
|
-
} as any)
|
|
170
|
-
em.persist(userRole)
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
await em.persist(user).flush()
|
|
174
|
-
|
|
175
|
-
const verificationToken = await customerTokenService.createEmailVerification(user.id, tenantId)
|
|
186
|
+
if (!signup) return NextResponse.json({ ok: true }, { status: 202 })
|
|
187
|
+
const { user, verificationToken } = signup
|
|
176
188
|
let verifyUrl = resolvePortalVerifyUrl(baseUrl, verificationToken, orgRow.slug)
|
|
177
189
|
try {
|
|
178
190
|
verifyUrl = await urlForCustomerOrg(organizationId, `/verify?token=${encodeURIComponent(verificationToken)}`, {
|
|
@@ -229,7 +241,7 @@ const methodDoc: OpenApiMethodDoc = {
|
|
|
229
241
|
tags: ['Customer Authentication'],
|
|
230
242
|
requestBody: {
|
|
231
243
|
schema: signupSchema,
|
|
232
|
-
description: 'Signup payload with email
|
|
244
|
+
description: 'Signup payload with email and display name. Passwords are set during email verification.',
|
|
233
245
|
},
|
|
234
246
|
responses: [
|
|
235
247
|
{ status: 202, description: 'Signup accepted', schema: signupAcceptedSchema },
|
|
@@ -7,7 +7,7 @@ const displayNameField = z.string().min(1).max(255)
|
|
|
7
7
|
|
|
8
8
|
export const signupSchema = z.object({
|
|
9
9
|
email: emailField,
|
|
10
|
-
password: passwordField,
|
|
10
|
+
password: passwordField.optional(),
|
|
11
11
|
displayName: displayNameField,
|
|
12
12
|
tenantId: z.string().uuid().optional(),
|
|
13
13
|
organizationId: z.string().uuid().optional(),
|
|
@@ -22,6 +22,7 @@ export const loginSchema = z.object({
|
|
|
22
22
|
|
|
23
23
|
export const emailVerifySchema = z.object({
|
|
24
24
|
token: z.string().min(1).max(512),
|
|
25
|
+
password: passwordField.optional(),
|
|
25
26
|
})
|
|
26
27
|
|
|
27
28
|
export const passwordResetRequestSchema = z.object({
|
|
@@ -30,20 +30,19 @@ async function resolveSessionService(): Promise<
|
|
|
30
30
|
return container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
async function
|
|
33
|
+
async function findSessionStillActive(input: {
|
|
34
34
|
sessionId: string
|
|
35
35
|
userId: string
|
|
36
36
|
tenantId: string
|
|
37
37
|
organizationId: string
|
|
38
|
-
})
|
|
38
|
+
}) {
|
|
39
39
|
try {
|
|
40
40
|
const service = await resolveSessionService()
|
|
41
|
-
|
|
42
|
-
return session !== null
|
|
41
|
+
return await service.findActiveSessionForClaims(input)
|
|
43
42
|
} catch {
|
|
44
43
|
// Fail closed: if we cannot verify the session, treat the token as revoked to prevent
|
|
45
44
|
// replay of leaked JWTs when the backend is partially degraded.
|
|
46
|
-
return
|
|
45
|
+
return null
|
|
47
46
|
}
|
|
48
47
|
}
|
|
49
48
|
|
|
@@ -96,6 +95,7 @@ export async function validateUserState(
|
|
|
96
95
|
tenantId: string,
|
|
97
96
|
orgId: string,
|
|
98
97
|
iat: unknown,
|
|
98
|
+
sessionCreatedAt?: Date,
|
|
99
99
|
): Promise<UserValidationResult> {
|
|
100
100
|
const [{ createRequestContainer }, { CustomerUser }] = await Promise.all([
|
|
101
101
|
import('@open-mercato/shared/lib/di/container'),
|
|
@@ -109,7 +109,8 @@ export async function validateUserState(
|
|
|
109
109
|
if (!user) return { valid: false }
|
|
110
110
|
if (user.deletedAt) return { valid: false }
|
|
111
111
|
if (!user.isActive) return { valid: false }
|
|
112
|
-
|
|
112
|
+
const issuedAt = sessionCreatedAt?.getTime() ?? (typeof iat === 'number' ? iat * 1000 : undefined)
|
|
113
|
+
if (user.sessionsRevokedAt && issuedAt !== undefined && issuedAt < user.sessionsRevokedAt.getTime()) {
|
|
113
114
|
return { valid: false }
|
|
114
115
|
}
|
|
115
116
|
if (!(await isCustomerTenantActive(em, tenantId))) return { valid: false }
|
|
@@ -185,21 +186,22 @@ export async function getCustomerAuthFromRequest(req: Request): Promise<Customer
|
|
|
185
186
|
// Every accepted token is re-checked for liveness, exactly like the SSR path does — a token
|
|
186
187
|
// without a `sid` is checked against the customer's remaining sessions rather than skipped,
|
|
187
188
|
// so session revocation is never structurally unreachable on the API path.
|
|
188
|
-
const
|
|
189
|
-
? await
|
|
189
|
+
const session = sid
|
|
190
|
+
? await findSessionStillActive({
|
|
190
191
|
sessionId: sid,
|
|
191
192
|
userId,
|
|
192
193
|
tenantId,
|
|
193
194
|
organizationId,
|
|
194
195
|
})
|
|
195
|
-
:
|
|
196
|
-
if (!
|
|
196
|
+
: null
|
|
197
|
+
if (sid ? !session : !(await assertUserStillHasActiveSession({ userId, tenantId, organizationId }))) return null
|
|
197
198
|
|
|
198
199
|
const userState = await validateUserState(
|
|
199
200
|
userId,
|
|
200
201
|
tenantId,
|
|
201
202
|
organizationId,
|
|
202
203
|
payload.iat,
|
|
204
|
+
session?.createdAt,
|
|
203
205
|
)
|
|
204
206
|
if (!userState.valid || !userState.tenantId || !userState.organizationId) return null
|
|
205
207
|
|
|
@@ -20,19 +20,18 @@ const logger = createLogger('customer_accounts').child({ component: 'customer-au
|
|
|
20
20
|
|
|
21
21
|
export type { CustomerAuthContext }
|
|
22
22
|
|
|
23
|
-
async function
|
|
23
|
+
async function findSessionStillActive(input: {
|
|
24
24
|
sessionId: string
|
|
25
25
|
userId: string
|
|
26
26
|
tenantId: string
|
|
27
27
|
organizationId: string
|
|
28
|
-
})
|
|
28
|
+
}) {
|
|
29
29
|
try {
|
|
30
30
|
const container = await createRequestContainer()
|
|
31
31
|
const service = container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>
|
|
32
|
-
|
|
33
|
-
return session !== null
|
|
32
|
+
return await service.findActiveSessionForClaims(input)
|
|
34
33
|
} catch {
|
|
35
|
-
return
|
|
34
|
+
return null
|
|
36
35
|
}
|
|
37
36
|
}
|
|
38
37
|
|
|
@@ -73,19 +72,20 @@ export async function getCustomerAuthFromCookies(
|
|
|
73
72
|
// JWTs are rejected as if unauthenticated.
|
|
74
73
|
return null
|
|
75
74
|
}
|
|
76
|
-
const
|
|
75
|
+
const session = await findSessionStillActive({
|
|
77
76
|
sessionId: sid,
|
|
78
77
|
userId,
|
|
79
78
|
tenantId,
|
|
80
79
|
organizationId,
|
|
81
80
|
})
|
|
82
|
-
if (!
|
|
81
|
+
if (!session) return null
|
|
83
82
|
|
|
84
83
|
const userState = await validateUserState(
|
|
85
84
|
userId,
|
|
86
85
|
tenantId,
|
|
87
86
|
organizationId,
|
|
88
87
|
payload.iat,
|
|
88
|
+
session.createdAt,
|
|
89
89
|
)
|
|
90
90
|
if (!userState.valid || !userState.tenantId || !userState.organizationId) return null
|
|
91
91
|
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000
|
|
2
|
+
|
|
3
|
+
export const pendingSignup = {
|
|
4
|
+
isActive: true,
|
|
5
|
+
emailVerifiedAt: null,
|
|
6
|
+
lastLoginAt: null,
|
|
7
|
+
deletedAt: null,
|
|
8
|
+
} as const
|
|
9
|
+
|
|
10
|
+
export function signupExpiryCutoff(now: Date): Date {
|
|
11
|
+
return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS)
|
|
12
|
+
}
|