@open-mercato/core 0.11.1-develop.8545.1.dd603570fd → 0.11.1-develop.8549.1.bd34c91190
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/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 +7 -7
- 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/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,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;AA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E,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,UA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AAG;AACjD,MAAI,CAAC,MAAM;AACT,UAAM,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,0BAA0B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC1F;AACA,SAAO;AACT;AAEA,eAAsB,uBACpB,MACA,UACA,MACe;AACf,MAAI,CAAC,SAAS,OAAQ;AACtB,QAAM,KAAK,MAAM,KAAK;AAAA,IACpB,KAAK;AAAA,IACL;AAAA,IACA,EAAE,UAAU,KAAK,UAAU,gBAAgB,KAAK,MAAM;AAAA,EACxD;AACA,MAAI,CAAC,IAAI;AACP,UAAM,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,2BAA2B,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3F;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -7,14 +7,13 @@ import { platformDomains } from "@open-mercato/core/modules/customer_accounts/li
|
|
|
7
7
|
import { validateUserState } from "./customerAuth.js";
|
|
8
8
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
9
9
|
const logger = createLogger("customer_accounts").child({ component: "customer-auth-server" });
|
|
10
|
-
async function
|
|
10
|
+
async function findSessionStillActive(input) {
|
|
11
11
|
try {
|
|
12
12
|
const container = await createRequestContainer();
|
|
13
13
|
const service = container.resolve("customerSessionService");
|
|
14
|
-
|
|
15
|
-
return session !== null;
|
|
14
|
+
return await service.findActiveSessionForClaims(input);
|
|
16
15
|
} catch {
|
|
17
|
-
return
|
|
16
|
+
return null;
|
|
18
17
|
}
|
|
19
18
|
}
|
|
20
19
|
async function getCustomerAuthFromCookies(options) {
|
|
@@ -33,18 +32,19 @@ async function getCustomerAuthFromCookies(options) {
|
|
|
33
32
|
if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {
|
|
34
33
|
return null;
|
|
35
34
|
}
|
|
36
|
-
const
|
|
35
|
+
const session = await findSessionStillActive({
|
|
37
36
|
sessionId: sid,
|
|
38
37
|
userId,
|
|
39
38
|
tenantId,
|
|
40
39
|
organizationId
|
|
41
40
|
});
|
|
42
|
-
if (!
|
|
41
|
+
if (!session) return null;
|
|
43
42
|
const userState = await validateUserState(
|
|
44
43
|
userId,
|
|
45
44
|
tenantId,
|
|
46
45
|
organizationId,
|
|
47
|
-
payload.iat
|
|
46
|
+
payload.iat,
|
|
47
|
+
session.createdAt
|
|
48
48
|
);
|
|
49
49
|
if (!userState.valid || !userState.tenantId || !userState.organizationId) return null;
|
|
50
50
|
return {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/lib/customerAuthServer.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Server-side customer auth helpers for Next.js server components.\n *\n * Uses the `cookies()` API from `next/headers` to read the customer auth token\n * from cookies \u2014 analogous to `getAuthFromCookies()` for staff auth.\n */\n\nimport { cookies } from 'next/headers'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { verifyAudienceJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { CUSTOMER_JWT_AUDIENCE, CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\nimport { tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { validateUserState } from './customerAuth'\nimport type { CustomerAuthContext } from './customerAuth'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'customer-auth-server' })\n\nexport type { CustomerAuthContext }\n\nasync function
|
|
5
|
-
"mappings": "AAOA,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC,SAAS,6BAAqD;AAE9D,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAI5F,eAAe,
|
|
4
|
+
"sourcesContent": ["/**\n * Server-side customer auth helpers for Next.js server components.\n *\n * Uses the `cookies()` API from `next/headers` to read the customer auth token\n * from cookies \u2014 analogous to `getAuthFromCookies()` for staff auth.\n */\n\nimport { cookies } from 'next/headers'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { verifyAudienceJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { CUSTOMER_JWT_AUDIENCE, CustomerSessionService } from '@open-mercato/core/modules/customer_accounts/services/customerSessionService'\nimport { DomainMappingService } from '@open-mercato/core/modules/customer_accounts/services/domainMappingService'\nimport { tryNormalizeHostname } from '@open-mercato/core/modules/customer_accounts/lib/hostname'\nimport { platformDomains } from '@open-mercato/core/modules/customer_accounts/lib/platformDomains'\nimport { validateUserState } from './customerAuth'\nimport type { CustomerAuthContext } from './customerAuth'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customer_accounts').child({ component: 'customer-auth-server' })\n\nexport type { CustomerAuthContext }\n\nasync function findSessionStillActive(input: {\n sessionId: string\n userId: string\n tenantId: string\n organizationId: string\n}) {\n try {\n const container = await createRequestContainer()\n const service = container.resolve('customerSessionService') as InstanceType<typeof CustomerSessionService>\n return await service.findActiveSessionForClaims(input)\n } catch {\n return null\n }\n}\n\n/**\n * Read and verify customer auth from cookies in server components.\n *\n * Returns the customer auth context if a valid customer JWT is found,\n * or null if not authenticated.\n *\n * @example\n * ```tsx\n * // In a server component or catch-all route\n * import { getCustomerAuthFromCookies } from '@open-mercato/core/modules/customer_accounts/lib/customerAuthServer'\n *\n * const customerAuth = await getCustomerAuthFromCookies()\n * if (!customerAuth) redirect('/login')\n * ```\n */\nexport async function getCustomerAuthFromCookies(\n options?: { expectedTenantId?: string },\n): Promise<CustomerAuthContext | null> {\n const cookieStore = await cookies()\n const token = cookieStore.get('customer_auth_token')?.value\n if (!token) return null\n\n try {\n const payload = verifyAudienceJwt(CUSTOMER_JWT_AUDIENCE, token) as Record<string, unknown> | null\n if (!payload) return null\n if (payload.type !== 'customer') return null\n const sid = typeof payload.sid === 'string' ? payload.sid : ''\n if (!sid) return null\n const tenantId = String(payload.tenantId)\n const userId = String(payload.sub)\n const organizationId = String(payload.orgId)\n if (options?.expectedTenantId && options.expectedTenantId !== tenantId) {\n // Cross-host JWT replay defense. See spec rev 5 Customer Authentication\n // section: the host-resolved tenant is the authoritative scope; mismatched\n // JWTs are rejected as if unauthenticated.\n return null\n }\n const session = await findSessionStillActive({\n sessionId: sid,\n userId,\n tenantId,\n organizationId,\n })\n if (!session) 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\n/**\n * Convenience wrapper for custom-domain pages: resolves the host, calls\n * getCustomerAuthFromCookies with the host-resolved tenant as expectedTenantId.\n *\n * Use from server components rendered under custom domains.\n */\nexport async function getCustomerAuthForHost(\n host: string | null | undefined,\n): Promise<CustomerAuthContext | null> {\n if (!host) return getCustomerAuthFromCookies()\n\n try {\n const hostname = tryNormalizeHostname(host)\n if (!hostname) return getCustomerAuthFromCookies()\n if (platformDomains().includes(hostname)) return getCustomerAuthFromCookies()\n\n const container = await createRequestContainer()\n const service = container.resolve('domainMappingService') as InstanceType<typeof DomainMappingService>\n const resolved = await service.resolveByHostname(hostname)\n if (!resolved || resolved.status !== 'active') return null\n return getCustomerAuthFromCookies({ expectedTenantId: resolved.tenantId })\n } catch (err) {\n logger.warn('Domain resolve failed; falling back to platform cookie', { err })\n return getCustomerAuthFromCookies()\n }\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,eAAe;AACxB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC,SAAS,6BAAqD;AAE9D,SAAS,4BAA4B;AACrC,SAAS,uBAAuB;AAChC,SAAS,yBAAyB;AAElC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,mBAAmB,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAI5F,eAAe,uBAAuB,OAKnC;AACD,MAAI;AACF,UAAM,YAAY,MAAM,uBAAuB;AAC/C,UAAM,UAAU,UAAU,QAAQ,wBAAwB;AAC1D,WAAO,MAAM,QAAQ,2BAA2B,KAAK;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAiBA,eAAsB,2BACpB,SACqC;AACrC,QAAM,cAAc,MAAM,QAAQ;AAClC,QAAM,QAAQ,YAAY,IAAI,qBAAqB,GAAG;AACtD,MAAI,CAAC,MAAO,QAAO;AAEnB,MAAI;AACF,UAAM,UAAU,kBAAkB,uBAAuB,KAAK;AAC9D,QAAI,CAAC,QAAS,QAAO;AACrB,QAAI,QAAQ,SAAS,WAAY,QAAO;AACxC,UAAM,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,MAAM;AAC5D,QAAI,CAAC,IAAK,QAAO;AACjB,UAAM,WAAW,OAAO,QAAQ,QAAQ;AACxC,UAAM,SAAS,OAAO,QAAQ,GAAG;AACjC,UAAM,iBAAiB,OAAO,QAAQ,KAAK;AAC3C,QAAI,SAAS,oBAAoB,QAAQ,qBAAqB,UAAU;AAItE,aAAO;AAAA,IACT;AACA,UAAM,UAAU,MAAM,uBAAuB;AAAA,MAC3C,WAAW;AAAA,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@@
|
|
|
1
|
+
const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
2
|
+
const pendingSignup = {
|
|
3
|
+
isActive: true,
|
|
4
|
+
emailVerifiedAt: null,
|
|
5
|
+
lastLoginAt: null,
|
|
6
|
+
deletedAt: null
|
|
7
|
+
};
|
|
8
|
+
function signupExpiryCutoff(now) {
|
|
9
|
+
return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS);
|
|
10
|
+
}
|
|
11
|
+
export {
|
|
12
|
+
EMAIL_VERIFICATION_TTL_MS,
|
|
13
|
+
pendingSignup,
|
|
14
|
+
signupExpiryCutoff
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=pendingSignup.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/customer_accounts/lib/pendingSignup.ts"],
|
|
4
|
+
"sourcesContent": ["export const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000\n\nexport const pendingSignup = {\n isActive: true,\n emailVerifiedAt: null,\n lastLoginAt: null,\n deletedAt: null,\n} as const\n\nexport function signupExpiryCutoff(now: Date): Date {\n return new Date(now.getTime() - EMAIL_VERIFICATION_TTL_MS)\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,4BAA4B,KAAK,KAAK,KAAK;AAEjD,MAAM,gBAAgB;AAAA,EAC3B,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,WAAW;AACb;AAEO,SAAS,mBAAmB,KAAiB;AAClD,SAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,yBAAyB;AAC3D;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { LockMode } from "@mikro-orm/core";
|
|
2
|
+
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
|
+
import { CustomerUser } from "../data/entities.js";
|
|
4
|
+
import { emitCustomerAccountsEvent } from "@open-mercato/core/modules/customer_accounts/events";
|
|
5
|
+
import { signupExpiryCutoff } from "./pendingSignup.js";
|
|
6
|
+
async function verifyCustomerEmail(em, identity, sessions, options) {
|
|
7
|
+
const { userId, tenantId, organizationId } = identity;
|
|
8
|
+
const user = await findOneWithDecryption(
|
|
9
|
+
em,
|
|
10
|
+
CustomerUser,
|
|
11
|
+
{ id: userId, tenantId, ...organizationId ? { organizationId } : {}, deletedAt: null },
|
|
12
|
+
{ lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
|
|
13
|
+
{ tenantId, organizationId }
|
|
14
|
+
);
|
|
15
|
+
if (!user?.isActive) return null;
|
|
16
|
+
const now = /* @__PURE__ */ new Date();
|
|
17
|
+
const newlyVerified = !user.emailVerifiedAt;
|
|
18
|
+
if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null;
|
|
19
|
+
if (!newlyVerified && !options) return { user, newlyVerified };
|
|
20
|
+
if (!newlyVerified && !options?.reset && user.passwordHash) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const scope = { id: user.id, tenantId, organizationId: user.organizationId };
|
|
24
|
+
if (options) {
|
|
25
|
+
await options.users.updatePassword(user, options.password, em);
|
|
26
|
+
}
|
|
27
|
+
if (newlyVerified) {
|
|
28
|
+
await em.nativeUpdate(CustomerUser, scope, {
|
|
29
|
+
emailVerifiedAt: now,
|
|
30
|
+
...options ? {} : { passwordHash: null }
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
await sessions.revokeAllUserSessions(user.id, em);
|
|
34
|
+
return { user, newlyVerified };
|
|
35
|
+
}
|
|
36
|
+
function emitCustomerEmailVerified(user, verifiedBy) {
|
|
37
|
+
void emitCustomerAccountsEvent("customer_accounts.email.verified", {
|
|
38
|
+
id: user.id,
|
|
39
|
+
userId: user.id,
|
|
40
|
+
recipientUserId: user.id,
|
|
41
|
+
tenantId: user.tenantId,
|
|
42
|
+
organizationId: user.organizationId,
|
|
43
|
+
...verifiedBy ? { email: user.email, verifiedBy } : {}
|
|
44
|
+
}).catch(() => void 0);
|
|
45
|
+
}
|
|
46
|
+
export {
|
|
47
|
+
emitCustomerEmailVerified,
|
|
48
|
+
verifyCustomerEmail
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=verifyCustomerEmail.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/customer_accounts/lib/verifyCustomerEmail.ts"],
|
|
4
|
+
"sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerUser } from '../data/entities'\nimport { emitCustomerAccountsEvent } from '@open-mercato/core/modules/customer_accounts/events'\nimport type { CustomerSessionService } from '../services/customerSessionService'\nimport type { CustomerUserService } from '../services/customerUserService'\nimport { signupExpiryCutoff } from './pendingSignup'\n\nexport async function verifyCustomerEmail(\n em: EntityManager,\n identity: { userId: string; tenantId: string; organizationId?: string },\n sessions: CustomerSessionService,\n options?: { password: string; users: CustomerUserService; reset?: boolean },\n): Promise<{ user: CustomerUser; newlyVerified: boolean } | null> {\n const { userId, tenantId, organizationId } = identity\n const user = await findOneWithDecryption(\n em,\n CustomerUser,\n { id: userId, tenantId, ...(organizationId ? { organizationId } : {}), deletedAt: null },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId, organizationId },\n )\n if (!user?.isActive) return null\n\n const now = new Date()\n const newlyVerified = !user.emailVerifiedAt\n if (newlyVerified && !user.lastLoginAt && user.createdAt <= signupExpiryCutoff(now)) return null\n if (!newlyVerified && !options) return { user, newlyVerified }\n if (!newlyVerified && !options?.reset && user.passwordHash) {\n return null\n }\n\n const scope = { id: user.id, tenantId, organizationId: user.organizationId }\n if (options) {\n await options.users.updatePassword(user, options.password, em)\n }\n if (newlyVerified) {\n await em.nativeUpdate(CustomerUser, scope, {\n emailVerifiedAt: now,\n ...(options ? {} : { passwordHash: null }),\n })\n }\n await sessions.revokeAllUserSessions(user.id, em)\n return { user, newlyVerified }\n}\n\nexport function emitCustomerEmailVerified(user: CustomerUser, verifiedBy?: string): void {\n void emitCustomerAccountsEvent('customer_accounts.email.verified', {\n id: user.id,\n userId: user.id,\n recipientUserId: user.id,\n tenantId: user.tenantId,\n organizationId: user.organizationId,\n ...(verifiedBy ? { email: user.email, verifiedBy } : {}),\n }).catch(() => undefined)\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,gBAAgB;AAEzB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAG1C,SAAS,0BAA0B;AAEnC,eAAsB,oBACpB,IACA,UACA,UACA,SACgE;AAChE,QAAM,EAAE,QAAQ,UAAU,eAAe,IAAI;AAC7C,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA;AAAA,IACA,EAAE,IAAI,QAAQ,UAAU,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC,GAAI,WAAW,KAAK;AAAA,IACvF,EAAE,UAAU,SAAS,mBAAmB,SAAS,KAAK;AAAA,IACtD,EAAE,UAAU,eAAe;AAAA,EAC7B;AACA,MAAI,CAAC,MAAM,SAAU,QAAO;AAE5B,QAAM,MAAM,oBAAI,KAAK;AACrB,QAAM,gBAAgB,CAAC,KAAK;AAC5B,MAAI,iBAAiB,CAAC,KAAK,eAAe,KAAK,aAAa,mBAAmB,GAAG,EAAG,QAAO;AAC5F,MAAI,CAAC,iBAAiB,CAAC,QAAS,QAAO,EAAE,MAAM,cAAc;AAC7D,MAAI,CAAC,iBAAiB,CAAC,SAAS,SAAS,KAAK,cAAc;AAC1D,WAAO;AAAA,EACT;AAEA,QAAM,QAAQ,EAAE,IAAI,KAAK,IAAI,UAAU,gBAAgB,KAAK,eAAe;AAC3E,MAAI,SAAS;AACX,UAAM,QAAQ,MAAM,eAAe,MAAM,QAAQ,UAAU,EAAE;AAAA,EAC/D;AACA,MAAI,eAAe;AACjB,UAAM,GAAG,aAAa,cAAc,OAAO;AAAA,MACzC,iBAAiB;AAAA,MACjB,GAAI,UAAU,CAAC,IAAI,EAAE,cAAc,KAAK;AAAA,IAC1C,CAAC;AAAA,EACH;AACA,QAAM,SAAS,sBAAsB,KAAK,IAAI,EAAE;AAChD,SAAO,EAAE,MAAM,cAAc;AAC/B;AAEO,SAAS,0BAA0B,MAAoB,YAA2B;AACvF,OAAK,0BAA0B,oCAAoC;AAAA,IACjE,IAAI,KAAK;AAAA,IACT,QAAQ,KAAK;AAAA,IACb,iBAAiB,KAAK;AAAA,IACtB,UAAU,KAAK;AAAA,IACf,gBAAgB,KAAK;AAAA,IACrB,GAAI,aAAa,EAAE,OAAO,KAAK,OAAO,WAAW,IAAI,CAAC;AAAA,EACxD,CAAC,EAAE,MAAM,MAAM,MAAS;AAC1B;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -5,12 +5,14 @@ import {
|
|
|
5
5
|
CustomerUser,
|
|
6
6
|
CustomerUserInvitation,
|
|
7
7
|
CustomerUserRole,
|
|
8
|
+
CustomerUserSession,
|
|
8
9
|
CustomerRole
|
|
9
10
|
} from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
10
11
|
import { generateSecureToken, hashToken } from "@open-mercato/core/modules/customer_accounts/lib/tokenGenerator";
|
|
11
12
|
import { hashForLookup, lookupHashCandidates } from "@open-mercato/shared/lib/encryption/aes";
|
|
12
13
|
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
13
14
|
import { isCustomerTenantActive } from "@open-mercato/core/modules/customer_accounts/lib/tenantEligibility";
|
|
15
|
+
import { pendingSignup } from "../lib/pendingSignup.js";
|
|
14
16
|
const BCRYPT_COST = 10;
|
|
15
17
|
const INVITATION_TTL_MS = 72 * 60 * 60 * 1e3;
|
|
16
18
|
const CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/CustomerInvitationEmailConflictError");
|
|
@@ -189,7 +191,19 @@ class CustomerInvitationService {
|
|
|
189
191
|
scope
|
|
190
192
|
);
|
|
191
193
|
if (existingActiveUser) {
|
|
192
|
-
|
|
194
|
+
if (existingActiveUser.organizationId !== scope.organizationId || !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {
|
|
195
|
+
throw new CustomerInvitationEmailConflictError(invitation.email);
|
|
196
|
+
}
|
|
197
|
+
const retired = await transactionEm.nativeUpdate(CustomerUser, {
|
|
198
|
+
id: existingActiveUser.id,
|
|
199
|
+
...scope,
|
|
200
|
+
...pendingSignup
|
|
201
|
+
}, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt });
|
|
202
|
+
if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email);
|
|
203
|
+
await transactionEm.nativeUpdate(CustomerUserSession, {
|
|
204
|
+
user: existingActiveUser.id,
|
|
205
|
+
deletedAt: null
|
|
206
|
+
}, { deletedAt: acceptedAt });
|
|
193
207
|
}
|
|
194
208
|
const user = transactionEm.create(CustomerUser, {
|
|
195
209
|
email: invitation.email,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/customer_accounts/services/customerInvitationService.ts"],
|
|
4
|
-
"sourcesContent": ["import { LockMode, UniqueConstraintViolationException, type RequiredEntityData } from '@mikro-orm/core'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the accept route and this service are bundled into separate\n// chunks, so `instanceof` between them is false and the 409 mapping would\n// silently degrade back into the raw 500 this error exists to prevent.\nconst CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = Symbol.for('@open-mercato/CustomerInvitationEmailConflictError')\n\nexport class CustomerInvitationEmailConflictError extends Error {\n readonly [CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] = true\n\n constructor(public readonly email: string) {\n super('[internal] An account with this email address already exists')\n this.name = 'CustomerInvitationEmailConflictError'\n }\n}\n\n/**\n * Bundle-safe check for {@link CustomerInvitationEmailConflictError}. Always prefer\n * this over `instanceof` \u2014 API routes reach this service through DI and resolve a\n * different copy of this module.\n */\nexport function isCustomerInvitationEmailConflictError(\n error: unknown,\n): error is CustomerInvitationEmailConflictError {\n return !!error\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] === true\n}\n\nconst POSTGRES_UNIQUE_VIOLATION = '23505'\n\n/**\n * Unique-constraint detection that does not depend on `instanceof`: the MikroORM\n * copy this module is bundled with is not necessarily the one the driver throws\n * from, so fall back to the exception name and the Postgres SQLSTATE.\n */\nfunction isUniqueConstraintViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const candidate = error as { name?: unknown; code?: unknown; cause?: unknown }\n if (candidate.name === 'UniqueConstraintViolationException') return true\n if (candidate.code === POSTGRES_UNIQUE_VIOLATION) return true\n const cause = candidate.cause as { code?: unknown } | undefined\n return !!cause && typeof cause === 'object' && cause.code === POSTGRES_UNIQUE_VIOLATION\n}\n\nexport type CustomerInvitationRollbackState = {\n email: string\n token: string\n customerEntityId: string | null\n personEntityId: string | null\n roleIdsJson: string[]\n invitedByUserId: string | null\n invitedByCustomerUserId: string | null\n displayName: string | null\n expiresAt: Date\n}\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n personEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{\n invitation: CustomerUserInvitation\n rawToken: string\n reused: boolean\n rollbackState: CustomerInvitationRollbackState | null\n }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n return this.em.transactional(async (transactionEm) => {\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n transactionEm,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing && !existing.acceptedAt && !existing.cancelledAt && existing.expiresAt.getTime() > Date.now()) {\n const rollbackState: CustomerInvitationRollbackState = {\n email: existing.email,\n token: existing.token,\n customerEntityId: existing.customerEntityId ?? null,\n personEntityId: existing.personEntityId ?? null,\n roleIdsJson: [...(existing.roleIdsJson ?? [])],\n invitedByUserId: existing.invitedByUserId ?? null,\n invitedByCustomerUserId: existing.invitedByCustomerUserId ?? null,\n displayName: existing.displayName ?? null,\n expiresAt: new Date(existing.expiresAt),\n }\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n // Keep the CRM person link and the recipient's display name when the\n // re-invite does not carry them: the portal invite route and the admin users\n // page only ever know the company, so overwriting with null would strip an\n // invitation raised from a person card off that person's account-status card\n // and drop the personalization from the invitation email (#5499).\n existing.personEntityId = options.personEntityId || existing.personEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || existing.displayName || null\n existing.expiresAt = expiresAt\n await transactionEm.flush()\n return { invitation: existing, rawToken: token, reused: true, rollbackState }\n }\n\n const invitation = transactionEm.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n personEntityId: options.personEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as RequiredEntityData<CustomerUserInvitation>)\n await transactionEm.persist(invitation).flush()\n return { invitation, rawToken: token, reused: false, rollbackState: null }\n })\n }\n\n async rollbackInvitation(\n invitation: CustomerUserInvitation,\n rollbackState: CustomerInvitationRollbackState | null,\n expectedToken: string = invitation.token,\n ): Promise<void> {\n if (!invitation.tenantId || !invitation.organizationId || !expectedToken) return\n await this.em.transactional(async (transactionEm) => {\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const pending = await findOneWithDecryption(transactionEm, CustomerUserInvitation, {\n id: invitation.id,\n ...scope,\n token: expectedToken,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }, { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true }, scope)\n if (!pending) return\n if (!rollbackState) {\n await transactionEm.remove(pending).flush()\n return\n }\n pending.email = rollbackState.email\n pending.token = rollbackState.token\n pending.customerEntityId = rollbackState.customerEntityId\n pending.personEntityId = rollbackState.personEntityId\n pending.roleIdsJson = [...rollbackState.roleIdsJson]\n pending.invitedByUserId = rollbackState.invitedByUserId\n pending.invitedByCustomerUserId = rollbackState.invitedByCustomerUserId\n pending.displayName = rollbackState.displayName\n pending.expiresAt = new Date(rollbackState.expiresAt)\n await transactionEm.flush()\n })\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async cancelInvitation(\n invitationId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!scope.tenantId || !scope.organizationId) return false\n const cancelledAt = new Date()\n const changed = await this.em.nativeUpdate(CustomerUserInvitation, {\n id: invitationId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: cancelledAt },\n }, { cancelledAt })\n return changed === 1\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n if (!(await isCustomerTenantActive(this.em, invitation.tenantId))) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n try {\n const result = await this.em.transactional(async (transactionEm) => {\n const acceptedAt = new Date()\n const changed = await transactionEm.nativeUpdate(CustomerUserInvitation, {\n id: invitation.id,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n token: hashToken(token),\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: acceptedAt },\n }, { acceptedAt })\n if (changed !== 1) return null\n\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const existingActiveUser = await findOneWithDecryption(\n transactionEm,\n CustomerUser,\n {\n tenantId: invitation.tenantId,\n emailHash: { $in: lookupHashCandidates(invitation.email) },\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (existingActiveUser) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n\n const user = transactionEm.create(CustomerUser, {\n email: invitation.email,\n emailHash: hashForLookup(invitation.email),\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n isActive: true,\n emailVerifiedAt: acceptedAt,\n failedLoginAttempts: 0,\n createdAt: acceptedAt,\n })\n transactionEm.persist(user)\n\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n transactionEm,\n CustomerRole,\n {\n id: { $in: roleIds },\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n : []\n for (const role of roles) {\n transactionEm.persist(transactionEm.create(CustomerUserRole, {\n user,\n role,\n createdAt: acceptedAt,\n }))\n }\n await transactionEm.flush()\n return { user, acceptedAt }\n })\n if (!result) return null\n invitation.acceptedAt = result.acceptedAt\n return { user: result.user, invitation }\n } catch (error) {\n if (isUniqueConstraintViolation(error)) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n throw error\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,SAAS,UAAU,0CAAmE;AAEtF,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,eAAe,4BAA4B;AACpD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,8BAA8B;
|
|
4
|
+
"sourcesContent": ["import { LockMode, UniqueConstraintViolationException, type RequiredEntityData } from '@mikro-orm/core'\nimport { EntityManager } from '@mikro-orm/postgresql'\nimport { hash } from 'bcryptjs'\nimport {\n CustomerUser,\n CustomerUserInvitation,\n CustomerUserRole,\n CustomerUserSession,\n CustomerRole,\n} from '@open-mercato/core/modules/customer_accounts/data/entities'\nimport { generateSecureToken, hashToken } from '@open-mercato/core/modules/customer_accounts/lib/tokenGenerator'\nimport { hashForLookup, lookupHashCandidates } from '@open-mercato/shared/lib/encryption/aes'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isCustomerTenantActive } from '@open-mercato/core/modules/customer_accounts/lib/tenantEligibility'\nimport { pendingSignup } from '../lib/pendingSignup'\n\nconst BCRYPT_COST = 10\nconst INVITATION_TTL_MS = 72 * 60 * 60 * 1000 // 72 hours\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries: the accept route and this service are bundled into separate\n// chunks, so `instanceof` between them is false and the 409 mapping would\n// silently degrade back into the raw 500 this error exists to prevent.\nconst CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER = Symbol.for('@open-mercato/CustomerInvitationEmailConflictError')\n\nexport class CustomerInvitationEmailConflictError extends Error {\n readonly [CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] = true\n\n constructor(public readonly email: string) {\n super('[internal] An account with this email address already exists')\n this.name = 'CustomerInvitationEmailConflictError'\n }\n}\n\n/**\n * Bundle-safe check for {@link CustomerInvitationEmailConflictError}. Always prefer\n * this over `instanceof` \u2014 API routes reach this service through DI and resolve a\n * different copy of this module.\n */\nexport function isCustomerInvitationEmailConflictError(\n error: unknown,\n): error is CustomerInvitationEmailConflictError {\n return !!error\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[CUSTOMER_INVITATION_EMAIL_CONFLICT_MARKER] === true\n}\n\nconst POSTGRES_UNIQUE_VIOLATION = '23505'\n\n/**\n * Unique-constraint detection that does not depend on `instanceof`: the MikroORM\n * copy this module is bundled with is not necessarily the one the driver throws\n * from, so fall back to the exception name and the Postgres SQLSTATE.\n */\nfunction isUniqueConstraintViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const candidate = error as { name?: unknown; code?: unknown; cause?: unknown }\n if (candidate.name === 'UniqueConstraintViolationException') return true\n if (candidate.code === POSTGRES_UNIQUE_VIOLATION) return true\n const cause = candidate.cause as { code?: unknown } | undefined\n return !!cause && typeof cause === 'object' && cause.code === POSTGRES_UNIQUE_VIOLATION\n}\n\nexport type CustomerInvitationRollbackState = {\n email: string\n token: string\n customerEntityId: string | null\n personEntityId: string | null\n roleIdsJson: string[]\n invitedByUserId: string | null\n invitedByCustomerUserId: string | null\n displayName: string | null\n expiresAt: Date\n}\n\nexport class CustomerInvitationService {\n constructor(private em: EntityManager) {}\n\n async createInvitation(\n email: string,\n scope: { tenantId: string; organizationId: string },\n options: {\n customerEntityId?: string | null\n personEntityId?: string | null\n roleIds: string[]\n invitedByUserId?: string | null\n invitedByCustomerUserId?: string | null\n displayName?: string | null\n },\n ): Promise<{\n invitation: CustomerUserInvitation\n rawToken: string\n reused: boolean\n rollbackState: CustomerInvitationRollbackState | null\n }> {\n const token = generateSecureToken()\n const emailHash = hashForLookup(email)\n const normalizedEmail = email.toLowerCase().trim()\n const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)\n const tokenHashed = hashToken(token)\n\n return this.em.transactional(async (transactionEm) => {\n // Dedupe: reuse an existing pending (not accepted, not cancelled, unexpired)\n // invitation for the same recipient instead of inserting a new row. This caps\n // row/token growth and keeps a single live token per concurrently-pending\n // (tenant, organization, email) tuple.\n const existing = await findOneWithDecryption(\n transactionEm,\n CustomerUserInvitation,\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n emailHash,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n },\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (existing && !existing.acceptedAt && !existing.cancelledAt && existing.expiresAt.getTime() > Date.now()) {\n const rollbackState: CustomerInvitationRollbackState = {\n email: existing.email,\n token: existing.token,\n customerEntityId: existing.customerEntityId ?? null,\n personEntityId: existing.personEntityId ?? null,\n roleIdsJson: [...(existing.roleIdsJson ?? [])],\n invitedByUserId: existing.invitedByUserId ?? null,\n invitedByCustomerUserId: existing.invitedByCustomerUserId ?? null,\n displayName: existing.displayName ?? null,\n expiresAt: new Date(existing.expiresAt),\n }\n existing.email = normalizedEmail\n existing.token = tokenHashed\n existing.customerEntityId = options.customerEntityId || null\n // Keep the CRM person link and the recipient's display name when the\n // re-invite does not carry them: the portal invite route and the admin users\n // page only ever know the company, so overwriting with null would strip an\n // invitation raised from a person card off that person's account-status card\n // and drop the personalization from the invitation email (#5499).\n existing.personEntityId = options.personEntityId || existing.personEntityId || null\n existing.roleIdsJson = options.roleIds\n existing.invitedByUserId = options.invitedByUserId || null\n existing.invitedByCustomerUserId = options.invitedByCustomerUserId || null\n existing.displayName = options.displayName || existing.displayName || null\n existing.expiresAt = expiresAt\n await transactionEm.flush()\n return { invitation: existing, rawToken: token, reused: true, rollbackState }\n }\n\n const invitation = transactionEm.create(CustomerUserInvitation, {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n email: normalizedEmail,\n emailHash,\n token: tokenHashed,\n customerEntityId: options.customerEntityId || null,\n personEntityId: options.personEntityId || null,\n roleIdsJson: options.roleIds,\n invitedByUserId: options.invitedByUserId || null,\n invitedByCustomerUserId: options.invitedByCustomerUserId || null,\n displayName: options.displayName || null,\n expiresAt,\n createdAt: new Date(),\n } as RequiredEntityData<CustomerUserInvitation>)\n await transactionEm.persist(invitation).flush()\n return { invitation, rawToken: token, reused: false, rollbackState: null }\n })\n }\n\n async rollbackInvitation(\n invitation: CustomerUserInvitation,\n rollbackState: CustomerInvitationRollbackState | null,\n expectedToken: string = invitation.token,\n ): Promise<void> {\n if (!invitation.tenantId || !invitation.organizationId || !expectedToken) return\n await this.em.transactional(async (transactionEm) => {\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const pending = await findOneWithDecryption(transactionEm, CustomerUserInvitation, {\n id: invitation.id,\n ...scope,\n token: expectedToken,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: new Date() },\n }, { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true }, scope)\n if (!pending) return\n if (!rollbackState) {\n await transactionEm.remove(pending).flush()\n return\n }\n pending.email = rollbackState.email\n pending.token = rollbackState.token\n pending.customerEntityId = rollbackState.customerEntityId\n pending.personEntityId = rollbackState.personEntityId\n pending.roleIdsJson = [...rollbackState.roleIdsJson]\n pending.invitedByUserId = rollbackState.invitedByUserId\n pending.invitedByCustomerUserId = rollbackState.invitedByCustomerUserId\n pending.displayName = rollbackState.displayName\n pending.expiresAt = new Date(rollbackState.expiresAt)\n await transactionEm.flush()\n })\n }\n\n async findByToken(token: string): Promise<CustomerUserInvitation | null> {\n const tokenHashed = hashToken(token)\n const invitation = await findOneWithDecryption(\n this.em,\n CustomerUserInvitation,\n { token: tokenHashed } as any,\n )\n if (!invitation) return null\n if (invitation.acceptedAt) return null\n if (invitation.cancelledAt) return null\n if (invitation.expiresAt.getTime() < Date.now()) return null\n return invitation\n }\n\n async cancelInvitation(\n invitationId: string,\n scope: { tenantId: string; organizationId: string },\n ): Promise<boolean> {\n if (!scope.tenantId || !scope.organizationId) return false\n const cancelledAt = new Date()\n const changed = await this.em.nativeUpdate(CustomerUserInvitation, {\n id: invitationId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: cancelledAt },\n }, { cancelledAt })\n return changed === 1\n }\n\n async acceptInvitation(\n token: string,\n password: string,\n displayName: string,\n ): Promise<{ user: CustomerUser; invitation: CustomerUserInvitation } | null> {\n const invitation = await this.findByToken(token)\n if (!invitation) return null\n if (!(await isCustomerTenantActive(this.em, invitation.tenantId))) return null\n\n const passwordHash = await hash(password, BCRYPT_COST)\n try {\n const result = await this.em.transactional(async (transactionEm) => {\n const acceptedAt = new Date()\n const changed = await transactionEm.nativeUpdate(CustomerUserInvitation, {\n id: invitation.id,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n token: hashToken(token),\n acceptedAt: null,\n cancelledAt: null,\n expiresAt: { $gt: acceptedAt },\n }, { acceptedAt })\n if (changed !== 1) return null\n\n const scope = { tenantId: invitation.tenantId, organizationId: invitation.organizationId }\n const existingActiveUser = await findOneWithDecryption(\n transactionEm,\n CustomerUser,\n {\n tenantId: invitation.tenantId,\n emailHash: { $in: lookupHashCandidates(invitation.email) },\n deletedAt: null,\n },\n undefined,\n scope,\n )\n if (existingActiveUser) {\n if (existingActiveUser.organizationId !== scope.organizationId\n || !existingActiveUser.isActive || existingActiveUser.emailVerifiedAt || existingActiveUser.lastLoginAt) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n const retired = await transactionEm.nativeUpdate(CustomerUser, {\n id: existingActiveUser.id,\n ...scope,\n ...pendingSignup,\n }, { deletedAt: acceptedAt, isActive: false, passwordHash: null, sessionsRevokedAt: acceptedAt })\n if (retired !== 1) throw new CustomerInvitationEmailConflictError(invitation.email)\n await transactionEm.nativeUpdate(CustomerUserSession, {\n user: existingActiveUser.id,\n deletedAt: null,\n }, { deletedAt: acceptedAt })\n }\n\n const user = transactionEm.create(CustomerUser, {\n email: invitation.email,\n emailHash: hashForLookup(invitation.email),\n passwordHash,\n displayName: displayName || invitation.displayName || invitation.email,\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n customerEntityId: invitation.customerEntityId || null,\n personEntityId: invitation.personEntityId || null,\n isActive: true,\n emailVerifiedAt: acceptedAt,\n failedLoginAttempts: 0,\n createdAt: acceptedAt,\n })\n transactionEm.persist(user)\n\n const roleIds = Array.isArray(invitation.roleIdsJson) ? invitation.roleIdsJson : []\n const roles = roleIds.length > 0\n ? await findWithDecryption(\n transactionEm,\n CustomerRole,\n {\n id: { $in: roleIds },\n tenantId: invitation.tenantId,\n organizationId: invitation.organizationId,\n deletedAt: null,\n },\n undefined,\n scope,\n )\n : []\n for (const role of roles) {\n transactionEm.persist(transactionEm.create(CustomerUserRole, {\n user,\n role,\n createdAt: acceptedAt,\n }))\n }\n await transactionEm.flush()\n return { user, acceptedAt }\n })\n if (!result) return null\n invitation.acceptedAt = result.acceptedAt\n return { user: result.user, invitation }\n } catch (error) {\n if (isUniqueConstraintViolation(error)) {\n throw new CustomerInvitationEmailConflictError(invitation.email)\n }\n throw error\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,SAAS,UAAU,0CAAmE;AAEtF,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,iBAAiB;AAC/C,SAAS,eAAe,4BAA4B;AACpD,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAE9B,MAAM,cAAc;AACpB,MAAM,oBAAoB,KAAK,KAAK,KAAK;AAMzC,MAAM,4CAA4C,uBAAO,IAAI,oDAAoD;AAE1G,MAAM,8CAA6C,YAC9C,gDAD8C,IAAM;AAAA,EAG9D,YAA4B,OAAe;AACzC,UAAM,8DAA8D;AAD1C;AAF5B,SAAU,MAA6C;AAIrD,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,uCACd,OAC+C;AAC/C,SAAO,CAAC,CAAC,SACJ,OAAO,UAAU,YAChB,MAAkC,yCAAyC,MAAM;AACzF;AAEA,MAAM,4BAA4B;AAOlC,SAAS,4BAA4B,OAAyB;AAC5D,MAAI,iBAAiB,mCAAoC,QAAO;AAChE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAClB,MAAI,UAAU,SAAS,qCAAsC,QAAO;AACpE,MAAI,UAAU,SAAS,0BAA2B,QAAO;AACzD,QAAM,QAAQ,UAAU;AACxB,SAAO,CAA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M,OAAO,MAAM,WAAW;AAAA,IACzC,SAAS,OAAO;AACd,UAAI,4BAA4B,KAAK,GAAG;AACtC,cAAM,IAAI,qCAAqC,WAAW,KAAK;AAAA,MACjE;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,28 +4,28 @@ import {
|
|
|
4
4
|
} from "@open-mercato/core/modules/customer_accounts/data/entities";
|
|
5
5
|
import { generateSecureToken, hashToken } from "@open-mercato/core/modules/customer_accounts/lib/tokenGenerator";
|
|
6
6
|
import { isCustomerTenantActive } from "@open-mercato/core/modules/customer_accounts/lib/tenantEligibility";
|
|
7
|
+
import { EMAIL_VERIFICATION_TTL_MS } from "../lib/pendingSignup.js";
|
|
7
8
|
function getKysely(em) {
|
|
8
9
|
return em.getKysely();
|
|
9
10
|
}
|
|
10
|
-
const EMAIL_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
11
11
|
const MAGIC_LINK_TTL_MS = 15 * 60 * 1e3;
|
|
12
12
|
const PASSWORD_RESET_TTL_MS = 60 * 60 * 1e3;
|
|
13
13
|
class CustomerTokenService {
|
|
14
14
|
constructor(em) {
|
|
15
15
|
this.em = em;
|
|
16
16
|
}
|
|
17
|
-
async createEmailVerification(userId, tenantId) {
|
|
17
|
+
async createEmailVerification(userId, tenantId, createdAt = /* @__PURE__ */ new Date(), em = this.em) {
|
|
18
18
|
const rawToken = generateSecureToken();
|
|
19
19
|
const tokenHashed = hashToken(rawToken);
|
|
20
|
-
const expiresAt = new Date(
|
|
21
|
-
const record =
|
|
20
|
+
const expiresAt = new Date(createdAt.getTime() + EMAIL_VERIFICATION_TTL_MS);
|
|
21
|
+
const record = em.create(CustomerUserEmailVerification, {
|
|
22
22
|
user: userId,
|
|
23
23
|
token: tokenHashed,
|
|
24
24
|
purpose: "email_verification",
|
|
25
25
|
expiresAt,
|
|
26
|
-
createdAt
|
|
26
|
+
createdAt
|
|
27
27
|
});
|
|
28
|
-
await
|
|
28
|
+
await em.persist(record).flush();
|
|
29
29
|
return rawToken;
|
|
30
30
|
}
|
|
31
31
|
async createMagicLink(userId, tenantId) {
|
|
@@ -55,9 +55,9 @@ class CustomerTokenService {
|
|
|
55
55
|
await this.em.persist(record).flush();
|
|
56
56
|
return rawToken;
|
|
57
57
|
}
|
|
58
|
-
async verifyEmailToken(token, purpose, tenantId) {
|
|
58
|
+
async verifyEmailToken(token, purpose, tenantId, em = this.em) {
|
|
59
59
|
const tokenHashed = hashToken(token);
|
|
60
|
-
const record = await
|
|
60
|
+
const record = await em.findOne(CustomerUserEmailVerification, {
|
|
61
61
|
token: tokenHashed,
|
|
62
62
|
purpose
|
|
63
63
|
}, { populate: ["user"] });
|
|
@@ -66,8 +66,8 @@ class CustomerTokenService {
|
|
|
66
66
|
if (record.expiresAt.getTime() < Date.now()) return null;
|
|
67
67
|
const user = record.user;
|
|
68
68
|
if (tenantId && user?.tenantId !== tenantId) return null;
|
|
69
|
-
if (purpose === "magic_link" && !await isCustomerTenantActive(
|
|
70
|
-
const db = getKysely(
|
|
69
|
+
if (purpose === "magic_link" && !await isCustomerTenantActive(em, user?.tenantId)) return null;
|
|
70
|
+
const db = getKysely(em);
|
|
71
71
|
const updateResult = await db.updateTable("customer_user_email_verifications").set({ used_at: /* @__PURE__ */ new Date() }).where("id", "=", record.id).where("used_at", "is", null).where("expires_at", ">", /* @__PURE__ */ new Date()).executeTakeFirst();
|
|
72
72
|
const consumed = Number(updateResult?.numUpdatedRows ?? 0);
|
|
73
73
|
if (consumed === 0) return null;
|
|
@@ -75,9 +75,9 @@ class CustomerTokenService {
|
|
|
75
75
|
const resolvedTenantId = typeof user === "string" ? "" : user.tenantId;
|
|
76
76
|
return { userId: resolvedUserId, tenantId: resolvedTenantId };
|
|
77
77
|
}
|
|
78
|
-
async verifyPasswordResetToken(token, tenantId) {
|
|
78
|
+
async verifyPasswordResetToken(token, tenantId, em = this.em) {
|
|
79
79
|
const tokenHashed = hashToken(token);
|
|
80
|
-
const record = await
|
|
80
|
+
const record = await em.findOne(CustomerUserPasswordReset, {
|
|
81
81
|
token: tokenHashed
|
|
82
82
|
}, { populate: ["user"] });
|
|
83
83
|
if (!record) return null;
|
|
@@ -85,7 +85,7 @@ class CustomerTokenService {
|
|
|
85
85
|
if (record.expiresAt.getTime() < Date.now()) return null;
|
|
86
86
|
const user = record.user;
|
|
87
87
|
if (tenantId && user?.tenantId !== tenantId) return null;
|
|
88
|
-
const db = getKysely(
|
|
88
|
+
const db = getKysely(em);
|
|
89
89
|
const updateResult = await db.updateTable("customer_user_password_resets").set({ used_at: /* @__PURE__ */ new Date() }).where("id", "=", record.id).where("used_at", "is", null).where("expires_at", ">", /* @__PURE__ */ new Date()).executeTakeFirst();
|
|
90
90
|
const consumed = Number(updateResult?.numUpdatedRows ?? 0);
|
|
91
91
|
if (consumed === 0) return null;
|