@open-mercato/core 0.6.8-develop.7000.1.0ae682bad1 → 0.6.8-develop.7003.1.24fef49d48

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.
@@ -1,39 +1,66 @@
1
1
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
2
2
  import { verifyJwt } from "@open-mercato/shared/lib/auth/jwt";
3
3
  import { buildSafeRedirectResponse } from "@open-mercato/core/modules/auth/lib/requestRedirect";
4
+ import { emitAuthEvent } from "@open-mercato/core/modules/auth/events";
5
+ const emptyAuthTokenClaims = Object.freeze({
6
+ userId: null,
7
+ sessionId: null,
8
+ tenantId: null,
9
+ organizationId: null
10
+ });
4
11
  function parseCookie(req, name) {
5
12
  const cookie = req.headers.get("cookie") || "";
6
13
  const m = cookie.match(new RegExp("(?:^|;\\s*)" + name + "=([^;]+)"));
7
14
  return m ? decodeURIComponent(m[1]) : null;
8
15
  }
9
- function extractSessionIdFromAuthToken(token) {
10
- if (!token) return null;
16
+ function readStringClaim(payload, key) {
17
+ const value = payload[key];
18
+ return typeof value === "string" && value.length > 0 ? value : null;
19
+ }
20
+ function extractAuthTokenClaims(token) {
21
+ if (!token) return emptyAuthTokenClaims;
11
22
  try {
12
23
  const payload = verifyJwt(token);
13
- if (!payload) return null;
14
- const sid = payload.sid;
15
- return typeof sid === "string" && sid.length > 0 ? sid : null;
24
+ if (!payload) return emptyAuthTokenClaims;
25
+ return {
26
+ userId: readStringClaim(payload, "sub"),
27
+ sessionId: readStringClaim(payload, "sid"),
28
+ tenantId: readStringClaim(payload, "tenantId"),
29
+ organizationId: readStringClaim(payload, "orgId")
30
+ };
16
31
  } catch {
17
- return null;
32
+ return emptyAuthTokenClaims;
18
33
  }
19
34
  }
20
35
  async function POST(req) {
21
36
  const sessToken = parseCookie(req, "session_token");
22
37
  const authToken = parseCookie(req, "auth_token");
23
- const sessionId = extractSessionIdFromAuthToken(authToken);
24
- if (sessToken || sessionId) {
38
+ const claims = extractAuthTokenClaims(authToken);
39
+ let sessionRevoked = false;
40
+ if (sessToken || claims.sessionId) {
25
41
  try {
26
42
  const c = await createRequestContainer();
27
43
  const auth = c.resolve("authService");
28
- if (sessionId) {
29
- await auth.deleteSessionById(sessionId);
44
+ if (claims.sessionId) {
45
+ await auth.deleteSessionById(claims.sessionId);
30
46
  }
31
47
  if (sessToken) {
32
48
  await auth.deleteSessionByToken(sessToken);
33
49
  }
50
+ sessionRevoked = true;
34
51
  } catch {
35
52
  }
36
53
  }
54
+ if (claims.userId) {
55
+ void emitAuthEvent("auth.logout", {
56
+ id: claims.userId,
57
+ tenantId: claims.tenantId,
58
+ organizationId: claims.organizationId,
59
+ sessionId: claims.sessionId,
60
+ sessionRevoked,
61
+ at: (/* @__PURE__ */ new Date()).toISOString()
62
+ }, { persistent: true }).catch(() => void 0);
63
+ }
37
64
  const res = buildSafeRedirectResponse(req, "/login");
38
65
  res.cookies.set("auth_token", "", { path: "/", maxAge: 0 });
39
66
  res.cookies.set("session_token", "", { path: "/", maxAge: 0 });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/api/logout.ts"],
4
- "sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { buildSafeRedirectResponse } from '@open-mercato/core/modules/auth/lib/requestRedirect'\n\nfunction parseCookie(req: Request, name: string): string | null {\n const cookie = req.headers.get('cookie') || ''\n const m = cookie.match(new RegExp('(?:^|;\\\\s*)' + name + '=([^;]+)'))\n return m ? decodeURIComponent(m[1]) : null\n}\n\nfunction extractSessionIdFromAuthToken(token: string | null): string | null {\n if (!token) return null\n try {\n const payload = verifyJwt(token) as Record<string, unknown> | null\n if (!payload) return null\n const sid = payload.sid\n return typeof sid === 'string' && sid.length > 0 ? sid : null\n } catch {\n return null\n }\n}\n\nexport async function POST(req: Request) {\n const sessToken = parseCookie(req, 'session_token')\n const authToken = parseCookie(req, 'auth_token')\n const sessionId = extractSessionIdFromAuthToken(authToken)\n if (sessToken || sessionId) {\n try {\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n if (sessionId) {\n await auth.deleteSessionById(sessionId)\n }\n if (sessToken) {\n await auth.deleteSessionByToken(sessToken)\n }\n } catch {}\n }\n const res = buildSafeRedirectResponse(req, '/login')\n res.cookies.set('auth_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('session_token', '', { path: '/', maxAge: 0 })\n return res\n}\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Log out current session',\n methods: {\n POST: {\n summary: 'Invalidate session and redirect',\n description: 'Clears authentication cookies and redirects the browser to the login page.',\n responses: [\n { status: 302, description: 'Redirect to login after successful logout', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
5
- "mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,SAAS,iCAAiC;AAE1C,SAAS,YAAY,KAAc,MAA6B;AAC9D,QAAM,SAAS,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAC5C,QAAM,IAAI,OAAO,MAAM,IAAI,OAAO,gBAAgB,OAAO,UAAU,CAAC;AACpE,SAAO,IAAI,mBAAmB,EAAE,CAAC,CAAC,IAAI;AACxC;AAEA,SAAS,8BAA8B,OAAqC;AAC1E,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,UAAU,UAAU,KAAK;AAC/B,QAAI,CAAC,QAAS,QAAO;AACrB,UAAM,MAAM,QAAQ;AACpB,WAAO,OAAO,QAAQ,YAAY,IAAI,SAAS,IAAI,MAAM;AAAA,EAC3D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,KAAK,KAAc;AACvC,QAAM,YAAY,YAAY,KAAK,eAAe;AAClD,QAAM,YAAY,YAAY,KAAK,YAAY;AAC/C,QAAM,YAAY,8BAA8B,SAAS;AACzD,MAAI,aAAa,WAAW;AAC1B,QAAI;AACF,YAAM,IAAI,MAAM,uBAAuB;AACvC,YAAM,OAAO,EAAE,QAAqB,aAAa;AACjD,UAAI,WAAW;AACb,cAAM,KAAK,kBAAkB,SAAS;AAAA,MACxC;AACA,UAAI,WAAW;AACb,cAAM,KAAK,qBAAqB,SAAS;AAAA,MAC3C;AAAA,IACF,QAAQ;AAAA,IAAC;AAAA,EACX;AACA,QAAM,MAAM,0BAA0B,KAAK,QAAQ;AACnD,MAAI,QAAQ,IAAI,cAAc,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC1D,MAAI,QAAQ,IAAI,iBAAiB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC7D,SAAO;AACT;AAEO,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,6CAA6C,WAAW,YAAY;AAAA,MAClG;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { verifyJwt } from '@open-mercato/shared/lib/auth/jwt'\nimport { buildSafeRedirectResponse } from '@open-mercato/core/modules/auth/lib/requestRedirect'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\n\ntype AuthTokenClaims = {\n userId: string | null\n sessionId: string | null\n tenantId: string | null\n organizationId: string | null\n}\n\nconst emptyAuthTokenClaims: AuthTokenClaims = Object.freeze({\n userId: null,\n sessionId: null,\n tenantId: null,\n organizationId: null,\n})\n\nfunction parseCookie(req: Request, name: string): string | null {\n const cookie = req.headers.get('cookie') || ''\n const m = cookie.match(new RegExp('(?:^|;\\\\s*)' + name + '=([^;]+)'))\n return m ? decodeURIComponent(m[1]) : null\n}\n\nfunction readStringClaim(payload: Record<string, unknown>, key: string): string | null {\n const value = payload[key]\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction extractAuthTokenClaims(token: string | null): AuthTokenClaims {\n if (!token) return emptyAuthTokenClaims\n try {\n const payload = verifyJwt(token) as Record<string, unknown> | null\n if (!payload) return emptyAuthTokenClaims\n return {\n userId: readStringClaim(payload, 'sub'),\n sessionId: readStringClaim(payload, 'sid'),\n tenantId: readStringClaim(payload, 'tenantId'),\n organizationId: readStringClaim(payload, 'orgId'),\n }\n } catch {\n return emptyAuthTokenClaims\n }\n}\n\nexport async function POST(req: Request) {\n const sessToken = parseCookie(req, 'session_token')\n const authToken = parseCookie(req, 'auth_token')\n const claims = extractAuthTokenClaims(authToken)\n let sessionRevoked = false\n if (sessToken || claims.sessionId) {\n try {\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n if (claims.sessionId) {\n await auth.deleteSessionById(claims.sessionId)\n }\n if (sessToken) {\n await auth.deleteSessionByToken(sessToken)\n }\n sessionRevoked = true\n } catch {}\n }\n if (claims.userId) {\n void emitAuthEvent('auth.logout', {\n id: claims.userId,\n tenantId: claims.tenantId,\n organizationId: claims.organizationId,\n sessionId: claims.sessionId,\n sessionRevoked,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n const res = buildSafeRedirectResponse(req, '/login')\n res.cookies.set('auth_token', '', { path: '/', maxAge: 0 })\n res.cookies.set('session_token', '', { path: '/', maxAge: 0 })\n return res\n}\n\nexport const metadata = {\n POST: { requireAuth: true },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Log out current session',\n methods: {\n POST: {\n summary: 'Invalidate session and redirect',\n description: 'Clears authentication cookies and redirects the browser to the login page.',\n responses: [\n { status: 302, description: 'Redirect to login after successful logout', mediaType: 'text/html' },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AACA,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,SAAS,iCAAiC;AAC1C,SAAS,qBAAqB;AAS9B,MAAM,uBAAwC,OAAO,OAAO;AAAA,EAC1D,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,UAAU;AAAA,EACV,gBAAgB;AAClB,CAAC;AAED,SAAS,YAAY,KAAc,MAA6B;AAC9D,QAAM,SAAS,IAAI,QAAQ,IAAI,QAAQ,KAAK;AAC5C,QAAM,IAAI,OAAO,MAAM,IAAI,OAAO,gBAAgB,OAAO,UAAU,CAAC;AACpE,SAAO,IAAI,mBAAmB,EAAE,CAAC,CAAC,IAAI;AACxC;AAEA,SAAS,gBAAgB,SAAkC,KAA4B;AACrF,QAAM,QAAQ,QAAQ,GAAG;AACzB,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAEA,SAAS,uBAAuB,OAAuC;AACrE,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,UAAU,UAAU,KAAK;AAC/B,QAAI,CAAC,QAAS,QAAO;AACrB,WAAO;AAAA,MACL,QAAQ,gBAAgB,SAAS,KAAK;AAAA,MACtC,WAAW,gBAAgB,SAAS,KAAK;AAAA,MACzC,UAAU,gBAAgB,SAAS,UAAU;AAAA,MAC7C,gBAAgB,gBAAgB,SAAS,OAAO;AAAA,IAClD;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAsB,KAAK,KAAc;AACvC,QAAM,YAAY,YAAY,KAAK,eAAe;AAClD,QAAM,YAAY,YAAY,KAAK,YAAY;AAC/C,QAAM,SAAS,uBAAuB,SAAS;AAC/C,MAAI,iBAAiB;AACrB,MAAI,aAAa,OAAO,WAAW;AACjC,QAAI;AACF,YAAM,IAAI,MAAM,uBAAuB;AACvC,YAAM,OAAO,EAAE,QAAqB,aAAa;AACjD,UAAI,OAAO,WAAW;AACpB,cAAM,KAAK,kBAAkB,OAAO,SAAS;AAAA,MAC/C;AACA,UAAI,WAAW;AACb,cAAM,KAAK,qBAAqB,SAAS;AAAA,MAC3C;AACA,uBAAiB;AAAA,IACnB,QAAQ;AAAA,IAAC;AAAA,EACX;AACA,MAAI,OAAO,QAAQ;AACjB,SAAK,cAAc,eAAe;AAAA,MAChC,IAAI,OAAO;AAAA,MACX,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,WAAW,OAAO;AAAA,MAClB;AAAA,MACA,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,IAC7B,GAAG,EAAE,YAAY,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,EAChD;AACA,QAAM,MAAM,0BAA0B,KAAK,QAAQ;AACnD,MAAI,QAAQ,IAAI,cAAc,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC1D,MAAI,QAAQ,IAAI,iBAAiB,IAAI,EAAE,MAAM,KAAK,QAAQ,EAAE,CAAC;AAC7D,SAAO;AACT;AAEO,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,KAAK;AAC5B;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,6CAA6C,WAAW,YAAY;AAAA,MAClG;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -9,6 +9,7 @@ import { rateLimitErrorSchema } from "@open-mercato/shared/lib/ratelimit/helpers
9
9
  import { readEndpointRateLimitConfig } from "@open-mercato/shared/lib/ratelimit/config";
10
10
  import { checkAuthRateLimit } from "@open-mercato/core/modules/auth/lib/rateLimitCheck";
11
11
  import { createLogger } from "@open-mercato/shared/lib/logger";
12
+ import { emitAuthEvent } from "@open-mercato/core/modules/auth/events";
12
13
  const logger = createLogger("auth").child({ component: "reset-confirm" });
13
14
  const resetConfirmRateLimitConfig = readEndpointRateLimitConfig("RESET_CONFIRM", {
14
15
  points: 5,
@@ -27,6 +28,12 @@ async function POST(req) {
27
28
  const auth = c.resolve("authService");
28
29
  const user = await auth.confirmPasswordReset(parsed.data.token, parsed.data.password);
29
30
  if (!user) return NextResponse.json({ ok: false, error: "Invalid or expired token" }, { status: 400 });
31
+ void emitAuthEvent("auth.password.reset.completed", {
32
+ id: String(user.id),
33
+ tenantId: user.tenantId ? String(user.tenantId) : null,
34
+ organizationId: user.organizationId ? String(user.organizationId) : null,
35
+ at: (/* @__PURE__ */ new Date()).toISOString()
36
+ }, { persistent: true }).catch(() => void 0);
30
37
  try {
31
38
  const tenantId = user.tenantId ? String(user.tenantId) : null;
32
39
  if (tenantId) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/auth/api/reset/confirm.ts"],
4
- "sourcesContent": ["import { confirmPasswordResetSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { z } from 'zod'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth').child({ component: 'reset-confirm' })\n\nconst resetConfirmRateLimitConfig = readEndpointRateLimitConfig('RESET_CONFIRM', {\n points: 5, duration: 300, keyPrefix: 'reset-confirm',\n})\n\n// validation via confirmPasswordResetSchema\n\nexport async function POST(req: Request) {\n const form = await req.formData()\n const token = String(form.get('token') ?? '')\n const password = String(form.get('password') ?? '')\n // Rate limit by IP \u2014 checked before validation and DB work\n const { error: rateLimitError } = await checkAuthRateLimit({ req, ipConfig: resetConfirmRateLimitConfig })\n if (rateLimitError) return rateLimitError\n const parsed = confirmPasswordResetSchema.safeParse({ token, password })\n if (!parsed.success) return NextResponse.json({ ok: false, error: 'Invalid request' }, { status: 400 })\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n const user = await auth.confirmPasswordReset(parsed.data.token, parsed.data.password)\n if (!user) return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n try {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (tenantId) {\n const notificationService = resolveNotificationService(c)\n const typeDef = notificationTypes.find((type) => type.type === 'auth.password_reset.completed')\n if (typeDef) {\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, {\n tenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n return NextResponse.json({ ok: true, redirect: '/login' })\n}\n\nexport const metadata = { requireAuth: false }\n\nconst passwordResetConfirmResponseSchema = z.object({\n ok: z.literal(true),\n redirect: z.string(),\n})\n\nconst passwordResetErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Confirm password reset',\n methods: {\n POST: {\n summary: 'Complete password reset',\n description: 'Validates the reset token and updates the user password.',\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: confirmPasswordResetSchema,\n },\n responses: [\n { status: 200, description: 'Password reset succeeded', schema: passwordResetConfirmResponseSchema },\n { status: 400, description: 'Invalid token or payload', schema: passwordResetErrorSchema },\n ],\n errors: [\n { status: 429, description: 'Too many reset confirmation attempts', schema: rateLimitErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AAEvC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,OAAO,uBAAuB;AAC9B,SAAS,SAAS;AAClB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,MAAM,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAExE,MAAM,8BAA8B,4BAA4B,iBAAiB;AAAA,EAC/E,QAAQ;AAAA,EAAG,UAAU;AAAA,EAAK,WAAW;AACvC,CAAC;AAID,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,IAAI,SAAS;AAChC,QAAM,QAAQ,OAAO,KAAK,IAAI,OAAO,KAAK,EAAE;AAC5C,QAAM,WAAW,OAAO,KAAK,IAAI,UAAU,KAAK,EAAE;AAElD,QAAM,EAAE,OAAO,eAAe,IAAI,MAAM,mBAAmB,EAAE,KAAK,UAAU,4BAA4B,CAAC;AACzG,MAAI,eAAgB,QAAO;AAC3B,QAAM,SAAS,2BAA2B,UAAU,EAAE,OAAO,SAAS,CAAC;AACvE,MAAI,CAAC,OAAO,QAAS,QAAO,aAAa,KAAK,EAAE,IAAI,OAAO,OAAO,kBAAkB,GAAG,EAAE,QAAQ,IAAI,CAAC;AACtG,QAAM,IAAI,MAAM,uBAAuB;AACvC,QAAM,OAAO,EAAE,QAAqB,aAAa;AACjD,QAAM,OAAO,MAAM,KAAK,qBAAqB,OAAO,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MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,mCAAmC;AAAA,QACnG,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,yBAAyB;AAAA,MAC3F;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,qBAAqB;AAAA,MACnG;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { confirmPasswordResetSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { z } from 'zod'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\n\nconst logger = createLogger('auth').child({ component: 'reset-confirm' })\n\nconst resetConfirmRateLimitConfig = readEndpointRateLimitConfig('RESET_CONFIRM', {\n points: 5, duration: 300, keyPrefix: 'reset-confirm',\n})\n\n// validation via confirmPasswordResetSchema\n\nexport async function POST(req: Request) {\n const form = await req.formData()\n const token = String(form.get('token') ?? '')\n const password = String(form.get('password') ?? '')\n // Rate limit by IP \u2014 checked before validation and DB work\n const { error: rateLimitError } = await checkAuthRateLimit({ req, ipConfig: resetConfirmRateLimitConfig })\n if (rateLimitError) return rateLimitError\n const parsed = confirmPasswordResetSchema.safeParse({ token, password })\n if (!parsed.success) return NextResponse.json({ ok: false, error: 'Invalid request' }, { status: 400 })\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n const user = await auth.confirmPasswordReset(parsed.data.token, parsed.data.password)\n if (!user) return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })\n void emitAuthEvent('auth.password.reset.completed', {\n id: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n try {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (tenantId) {\n const notificationService = resolveNotificationService(c)\n const typeDef = notificationTypes.find((type) => type.type === 'auth.password_reset.completed')\n if (typeDef) {\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, {\n tenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n return NextResponse.json({ ok: true, redirect: '/login' })\n}\n\nexport const metadata = { requireAuth: false }\n\nconst passwordResetConfirmResponseSchema = z.object({\n ok: z.literal(true),\n redirect: z.string(),\n})\n\nconst passwordResetErrorSchema = z.object({\n ok: z.literal(false),\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Confirm password reset',\n methods: {\n POST: {\n summary: 'Complete password reset',\n description: 'Validates the reset token and updates the user password.',\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: confirmPasswordResetSchema,\n },\n responses: [\n { status: 200, description: 'Password reset succeeded', schema: passwordResetConfirmResponseSchema },\n { status: 400, description: 'Invalid token or payload', schema: passwordResetErrorSchema },\n ],\n errors: [\n { status: 429, description: 'Too many reset confirmation attempts', schema: rateLimitErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,S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aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,mCAAmC;AAAA,QACnG,EAAE,QAAQ,KAAK,aAAa,4BAA4B,QAAQ,yBAAyB;AAAA,MAC3F;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,wCAAwC,QAAQ,qBAAqB;AAAA,MACnG;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -13,6 +13,7 @@ import { readEndpointRateLimitConfig } from "@open-mercato/shared/lib/ratelimit/
13
13
  import { checkAuthRateLimit } from "@open-mercato/core/modules/auth/lib/rateLimitCheck";
14
14
  import { mapSecurityEmailUrlError, toSecurityEmailUrl } from "@open-mercato/shared/lib/url";
15
15
  import { createLogger } from "@open-mercato/shared/lib/logger";
16
+ import { emitAuthEvent } from "@open-mercato/core/modules/auth/events";
16
17
  const logger = createLogger("auth").child({ component: "reset" });
17
18
  const resetRateLimitConfig = readEndpointRateLimitConfig("RESET", {
18
19
  points: 3,
@@ -58,6 +59,12 @@ async function POST(req) {
58
59
  if (!resReq) return NextResponse.json({ ok: true });
59
60
  const { user, token } = resReq;
60
61
  const resetUrl = resetUrlTemplate.replace("__token__", token);
62
+ void emitAuthEvent("auth.password.reset.requested", {
63
+ id: String(user.id),
64
+ tenantId: user.tenantId ? String(user.tenantId) : null,
65
+ organizationId: user.organizationId ? String(user.organizationId) : null,
66
+ at: (/* @__PURE__ */ new Date()).toISOString()
67
+ }, { persistent: true }).catch(() => void 0);
61
68
  const { translate } = await resolveTranslations();
62
69
  const subject = translate("auth.email.resetPassword.subject", "Reset your password");
63
70
  const copy = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/api/reset.ts"],
4
- "sourcesContent": ["import { requestPasswordResetSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport ResetPasswordEmail from '@open-mercato/core/modules/auth/emails/ResetPasswordEmail'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { z } from 'zod'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { mapSecurityEmailUrlError, toSecurityEmailUrl } from '@open-mercato/shared/lib/url'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth').child({ component: 'reset' })\n\nconst resetRateLimitConfig = readEndpointRateLimitConfig('RESET', {\n points: 3, duration: 60, blockDuration: 60, keyPrefix: 'reset',\n})\nconst resetIpRateLimitConfig = readEndpointRateLimitConfig('RESET_IP', {\n points: 10, duration: 60, blockDuration: 60, keyPrefix: 'reset-ip',\n})\n\n// validation via requestPasswordResetSchema\n\nexport async function POST(req: Request) {\n const form = await req.formData()\n const email = String(form.get('email') ?? '')\n // Rate limit \u2014 two layers, both checked before validation and DB work\n const { error: rateLimitError } = await checkAuthRateLimit({\n req, ipConfig: resetIpRateLimitConfig, compoundConfig: resetRateLimitConfig, compoundIdentifier: email,\n })\n if (rateLimitError) return rateLimitError\n const parsed = requestPasswordResetSchema.safeParse({ email })\n if (!parsed.success) {\n const fieldErrors = parsed.error.flatten().fieldErrors\n return NextResponse.json({ error: 'Validation failed', fieldErrors }, { status: 422 })\n }\n let resetUrlTemplate: string\n try {\n resetUrlTemplate = toSecurityEmailUrl(req, '/reset/__token__')\n } catch (error) {\n const mapped = mapSecurityEmailUrlError(error, {\n scope: 'auth.reset',\n configMessage: 'Password reset is not configured',\n })\n if (mapped) return NextResponse.json(mapped.body, { status: mapped.status })\n throw error\n }\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n const resReq = await auth.requestPasswordReset(parsed.data.email)\n if (!resReq) return NextResponse.json({ ok: true })\n const { user, token } = resReq\n const resetUrl = resetUrlTemplate.replace('__token__', token)\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.resetPassword.subject', 'Reset your password')\n const copy = {\n preview: translate('auth.email.resetPassword.preview', 'Reset your password'),\n title: translate('auth.email.resetPassword.title', 'Reset your password'),\n body: translate('auth.email.resetPassword.body', 'Click the link below to set a new password. This link will expire in 60 minutes.'),\n cta: translate('auth.email.resetPassword.cta', 'Set a new password'),\n hint: translate('auth.email.resetPassword.hint', \"If you didn't request this, you can safely ignore this email.\"),\n }\n\n try {\n await sendEmail({ to: user.email, subject, react: ResetPasswordEmail({ resetUrl, copy }) })\n } catch (err) {\n logger.error('Failed to send reset email', { err })\n }\n try {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (tenantId) {\n const notificationService = resolveNotificationService(c)\n const typeDef = notificationTypes.find((type) => type.type === 'auth.password_reset.requested')\n if (typeDef) {\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, {\n tenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const metadata = { requireAuth: false }\n\nconst passwordResetRequestSchema = z.object({\n email: z.string().email(),\n})\n\nconst passwordResetResponseSchema = z.object({\n ok: z.literal(true),\n})\n\nconst passwordResetErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Request password reset',\n methods: {\n POST: {\n summary: 'Send reset email',\n description: 'Requests a password reset email for the given account. The endpoint always returns `ok: true` to avoid leaking account existence.',\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: passwordResetRequestSchema,\n },\n responses: [\n { status: 200, description: 'Reset email dispatched (or ignored for unknown accounts)', schema: passwordResetResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid request origin', schema: passwordResetErrorSchema },\n { status: 429, description: 'Too many password reset requests', schema: rateLimitErrorSchema },\n { status: 500, description: 'Password reset email origin is not configured', schema: passwordResetErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,OAAO,wBAAwB;AAC/B,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,OAAO,uBAAuB;AAC9B,SAAS,SAAS;AAClB,SAAS,4BAA4B;AACrC,SAAS,mCAAmC;AAC5C,SAAS,0BAA0B;AACnC,SAAS,0BAA0B,0BAA0B;AAC7D,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,MAAM,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAEhE,MAAM,uBAAuB,4BAA4B,SAAS;AAAA,EAChE,QAAQ;AAAA,EAAG,UAAU;AAAA,EAAI,eAAe;AAAA,EAAI,WAAW;AACzD,CAAC;AACD,MAAM,yBAAyB,4BAA4B,YAAY;AAAA,EACrE,QAAQ;AAAA,EAAI,UAAU;AAAA,EAAI,eAAe;AAAA,EAAI,WAAW;AAC1D,CAAC;AAID,eAAsB,KAAK,KAAc;AACvC,QAAM,OAAO,MAAM,IAAI,SAAS;AAChC,QAAM,QAAQ,OAAO,KAAK,IAAI,OAAO,KAAK,EAAE;AAE5C,QAAM,EAAE,OAAO,eA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,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,4DAA4D,QAAQ,4BAA4B;AAAA,MAC9H;AAAA,MACA,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,yBAAyB;AAAA,QACvF,EAAE,QAAQ,KAAK,aAAa,oCAAoC,QAAQ,qBAAqB;AAAA,QAC7F,EAAE,QAAQ,KAAK,aAAa,iDAAiD,QAAQ,yBAAyB;AAAA,MAChH;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { requestPasswordResetSchema } from '@open-mercato/core/modules/auth/data/validators'\nimport { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { AuthService } from '@open-mercato/core/modules/auth/services/authService'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport ResetPasswordEmail from '@open-mercato/core/modules/auth/emails/ResetPasswordEmail'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { z } from 'zod'\nimport { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers'\nimport { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'\nimport { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'\nimport { mapSecurityEmailUrlError, toSecurityEmailUrl } from '@open-mercato/shared/lib/url'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\n\nconst logger = createLogger('auth').child({ component: 'reset' })\n\nconst resetRateLimitConfig = readEndpointRateLimitConfig('RESET', {\n points: 3, duration: 60, blockDuration: 60, keyPrefix: 'reset',\n})\nconst resetIpRateLimitConfig = readEndpointRateLimitConfig('RESET_IP', {\n points: 10, duration: 60, blockDuration: 60, keyPrefix: 'reset-ip',\n})\n\n// validation via requestPasswordResetSchema\n\nexport async function POST(req: Request) {\n const form = await req.formData()\n const email = String(form.get('email') ?? '')\n // Rate limit \u2014 two layers, both checked before validation and DB work\n const { error: rateLimitError } = await checkAuthRateLimit({\n req, ipConfig: resetIpRateLimitConfig, compoundConfig: resetRateLimitConfig, compoundIdentifier: email,\n })\n if (rateLimitError) return rateLimitError\n const parsed = requestPasswordResetSchema.safeParse({ email })\n if (!parsed.success) {\n const fieldErrors = parsed.error.flatten().fieldErrors\n return NextResponse.json({ error: 'Validation failed', fieldErrors }, { status: 422 })\n }\n let resetUrlTemplate: string\n try {\n resetUrlTemplate = toSecurityEmailUrl(req, '/reset/__token__')\n } catch (error) {\n const mapped = mapSecurityEmailUrlError(error, {\n scope: 'auth.reset',\n configMessage: 'Password reset is not configured',\n })\n if (mapped) return NextResponse.json(mapped.body, { status: mapped.status })\n throw error\n }\n const c = await createRequestContainer()\n const auth = c.resolve<AuthService>('authService')\n const resReq = await auth.requestPasswordReset(parsed.data.email)\n if (!resReq) return NextResponse.json({ ok: true })\n const { user, token } = resReq\n const resetUrl = resetUrlTemplate.replace('__token__', token)\n void emitAuthEvent('auth.password.reset.requested', {\n id: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.resetPassword.subject', 'Reset your password')\n const copy = {\n preview: translate('auth.email.resetPassword.preview', 'Reset your password'),\n title: translate('auth.email.resetPassword.title', 'Reset your password'),\n body: translate('auth.email.resetPassword.body', 'Click the link below to set a new password. This link will expire in 60 minutes.'),\n cta: translate('auth.email.resetPassword.cta', 'Set a new password'),\n hint: translate('auth.email.resetPassword.hint', \"If you didn't request this, you can safely ignore this email.\"),\n }\n\n try {\n await sendEmail({ to: user.email, subject, react: ResetPasswordEmail({ resetUrl, copy }) })\n } catch (err) {\n logger.error('Failed to send reset email', { err })\n }\n try {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (tenantId) {\n const notificationService = resolveNotificationService(c)\n const typeDef = notificationTypes.find((type) => type.type === 'auth.password_reset.requested')\n if (typeDef) {\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, {\n tenantId,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n return NextResponse.json({ ok: true })\n}\n\nexport const metadata = { requireAuth: false }\n\nconst passwordResetRequestSchema = z.object({\n email: z.string().email(),\n})\n\nconst passwordResetResponseSchema = z.object({\n ok: z.literal(true),\n})\n\nconst passwordResetErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Request password reset',\n methods: {\n POST: {\n summary: 'Send reset email',\n description: 'Requests a password reset email for the given account. The endpoint always returns `ok: true` to avoid leaking account existence.',\n requestBody: {\n contentType: 'application/x-www-form-urlencoded',\n schema: passwordResetRequestSchema,\n },\n responses: [\n { status: 200, description: 'Reset email dispatched (or ignored for unknown accounts)', schema: passwordResetResponseSchema },\n ],\n errors: [\n { status: 400, description: 'Invalid request origin', schema: passwordResetErrorSchema },\n { status: 429, description: 'Too many password reset requests', schema: rateLimitErrorSchema },\n { status: 500, description: 'Password reset email origin is not configured', schema: passwordResetErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,kCAAkC;AAC3C,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AAEvC,SAAS,iBAAiB;AAC1B,OAAO,wBAAwB;AAC/B,SAAS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AoC,QAAQ,qBAAqB;AAAA,QAC7F,EAAE,QAAQ,KAAK,aAAa,iDAAiD,QAAQ,yBAAyB;AAAA,MAChH;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -30,6 +30,7 @@ import { buildNotificationFromType } from "@open-mercato/core/modules/notificati
30
30
  import { resolveNotificationService } from "@open-mercato/core/modules/notifications/lib/notificationService";
31
31
  import notificationTypes from "@open-mercato/core/modules/auth/notifications";
32
32
  import { buildPasswordSchema } from "@open-mercato/shared/lib/auth/passwordPolicy";
33
+ import { emitAuthEvent } from "@open-mercato/core/modules/auth/events";
33
34
  import { sendEmail } from "@open-mercato/shared/lib/email/send";
34
35
  import InviteUserEmail from "@open-mercato/core/modules/auth/emails/InviteUserEmail";
35
36
  import { INVITE_TOKEN_TTL_MS } from "@open-mercato/core/modules/auth/lib/inviteToken";
@@ -589,6 +590,18 @@ const updateUserCommand = {
589
590
  events: userCrudEvents,
590
591
  indexer: userCrudIndexer
591
592
  });
593
+ if (hashed) {
594
+ const actorId = ctx.auth?.sub ? String(ctx.auth.sub) : null;
595
+ const changedBy = ctx.systemActor === true || !actorId ? "system" : actorId === identifiers.id ? "self" : "admin";
596
+ void emitAuthEvent("auth.password.changed", {
597
+ id: identifiers.id,
598
+ tenantId: identifiers.tenantId,
599
+ organizationId: identifiers.organizationId,
600
+ changedBy,
601
+ changedById: actorId,
602
+ at: (/* @__PURE__ */ new Date()).toISOString()
603
+ }, { persistent: true }).catch(() => void 0);
604
+ }
592
605
  if (Array.isArray(parsed.roles) && rolesBefore) {
593
606
  const rolesAfter = await loadUserRoleNames(em, String(user.id));
594
607
  const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/commands/users.ts"],
4
- "sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n buildChanges,\n requireId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudEventsConfig, CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { UniqueConstraintViolationException, LockMode } from '@mikro-orm/core'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { User, UserRole, Role, UserAcl, Session, PasswordReset } from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { resolveOrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { E } from '#generated/entities.ids.generated'\nimport { z } from 'zod'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n diffCustomFieldChanges,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { normalizeTenantId } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport InviteUserEmail from '@open-mercato/core/modules/auth/emails/InviteUserEmail'\nimport { INVITE_TOKEN_TTL_MS } from '@open-mercato/core/modules/auth/lib/inviteToken'\nimport { getSecurityEmailBaseUrl } from '@open-mercato/shared/lib/url'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { normalizeDisplayNameInput } from '@open-mercato/core/modules/auth/lib/displayName'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n assertActorCanAssignUserDestination,\n resolveUserDestinationRoles,\n throwUserDestinationOrganizationNotFound,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('auth').child({ component: 'users-commands' })\n\ntype SerializedUser = {\n email: string\n organizationId: string | null\n tenantId: string | null\n roles: string[]\n name: string | null\n isConfirmed: boolean\n custom?: Record<string, unknown>\n}\n\ntype UserAclSnapshot = {\n tenantId: string\n features: string[] | null\n isSuperAdmin: boolean\n organizations: string[] | null\n}\n\ntype UserUndoSnapshot = {\n id: string\n email: string\n organizationId: string | null\n tenantId: string | null\n passwordHash: string | null\n name: string | null\n isConfirmed: boolean\n roles: string[]\n acls: UserAclSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype UserSnapshots = {\n view: SerializedUser\n undo: UserUndoSnapshot\n}\n\nfunction resolveActorTenantScope(ctx: CommandRuntimeContext): string | null {\n if (ctx.systemActor === true) return null\n const auth = ctx.auth\n if (!auth) return null\n if ((auth as { isSuperAdmin?: boolean }).isSuperAdmin === true) return null\n const actorTenantId = normalizeTenantId(auth.tenantId ?? null) ?? null\n return actorTenantId\n}\n\nfunction assertTargetTenantInScope(actorTenantScope: string | null, targetTenantId: unknown, notFoundError: string): void {\n if (!actorTenantScope) return\n const targetTenant = normalizeTenantId(targetTenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) {\n throw new CrudHttpError(404, { error: notFoundError })\n }\n}\n\nconst passwordSchema = buildPasswordSchema()\n\nconst displayNameSchema = z.preprocess(\n normalizeDisplayNameInput,\n z.string().trim().min(1).max(120).nullable().optional(),\n)\n\nconst createSchema = z.object({\n email: z.string().email(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n sendInviteEmail: z.boolean().optional(),\n organizationId: z.string().uuid(),\n roles: z.array(z.string()).optional(),\n}).refine(\n (data) => data.password || data.sendInviteEmail,\n { message: 'Either password or sendInviteEmail is required', path: ['password'] },\n)\n\nconst updateSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email().optional(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n organizationId: z.string().uuid().optional(),\n roles: z.array(z.string()).optional(),\n isConfirmed: z.boolean().optional(),\n})\n\nexport const userCrudEvents: CrudEventsConfig = {\n module: 'auth',\n entity: 'user',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nexport const userCrudIndexer: CrudIndexerConfig = {\n entityType: E.auth.user,\n buildUpsertPayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n buildDeletePayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nasync function notifyRoleChanges(\n ctx: CommandRuntimeContext,\n user: User,\n assignedRoles: string[],\n revokedRoles: string[],\n): Promise<void> {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (!tenantId) return\n const organizationId = user.organizationId ? String(user.organizationId) : null\n\n try {\n const notificationService = resolveNotificationService(ctx.container)\n if (assignedRoles.length) {\n const assignedType = notificationTypes.find((type) => type.type === 'auth.role.assigned')\n if (assignedType) {\n const notificationInput = buildNotificationFromType(assignedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n\n if (revokedRoles.length) {\n const revokedType = notificationTypes.find((type) => type.type === 'auth.role.revoked')\n if (revokedType) {\n const notificationInput = buildNotificationFromType(revokedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n}\n\ntype CreateUserResult = { user: User; warning?: 'invite_email_failed' }\n\nconst createUserCommand: CommandHandler<Record<string, unknown>, CreateUserResult> = {\n id: 'auth.users.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(createSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId },\n )\n if (!organization) throw new CrudHttpError(400, { error: 'Organization not found' })\n const tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n assertTargetTenantInScope(resolveActorTenantScope(ctx), tenantId, 'Organization not found')\n\n const emailHash = computeEmailHash(parsed.email)\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq). Scope the duplicate check to the target tenant so the same\n // email may legitimately exist in other tenants without blocking creation or leaking\n // cross-tenant account existence (#2934).\n const duplicate = await findOneWithDecryption(em, User, { $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }], deletedAt: null, tenantId } as any, {}, { tenantId: null, organizationId: null })\n if (duplicate) await throwDuplicateEmailError()\n\n let passwordHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n passwordHash = await hash(parsed.password, 10)\n }\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user: User\n try {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n email: parsed.email,\n name: parsed.name,\n emailHash,\n passwordHash,\n isConfirmed: true,\n organizationId: parsed.organizationId,\n tenantId,\n },\n })\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n\n let assignedRoles: string[] = []\n if (Array.isArray(parsed.roles) && parsed.roles.length) {\n await syncUserRoles(em, user, parsed.roles, tenantId)\n assignedRoles = await loadUserRoleNames(em, String(user.id))\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: tenantId,\n values: custom,\n })\n\n let inviteEmailSent = false\n if (parsed.sendInviteEmail) {\n const inviteResult = await sendInviteToUser(em, user)\n inviteEmailSent = inviteResult.emailSent\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (assignedRoles.length && !parsed.sendInviteEmail) {\n await notifyRoleChanges(ctx, user, assignedRoles, [])\n }\n\n const warning = (parsed.sendInviteEmail && !inviteEmailSent) ? 'invite_email_failed' as const : undefined\n\n return { user, warning }\n },\n captureAfter: async (_input, { user }, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n return serializeUser(user, roles, custom)\n },\n buildLog: async ({ result: { user }, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n const snapshot = captureUserSnapshots(user, roles, undefined, custom)\n return {\n actionLabel: translate('auth.audit.users.create', 'Create user'),\n resourceKind: 'auth.user',\n resourceId: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n snapshotAfter: snapshot.view,\n payload: {\n undo: {\n after: snapshot.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const userId = typeof logEntry?.resourceId === 'string' ? logEntry.resourceId : null\n if (!userId) return\n const snapshot = logEntry?.snapshotAfter as SerializedUser | undefined\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Evaluate the floor against the user's CURRENT tenant, not the one recorded at\n // creation. A user moved to another tenant after being created would otherwise be\n // checked against the origin tenant \u2014 where they no longer hold anything \u2014 and the\n // undo would hard-delete the destination tenant's last administrator unchecked.\n // The create snapshot is only a fallback for a row that is already gone.\n let removed: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const floorTenantId = current?.tenantId ? String(current.tenantId) : (snapshot?.tenantId ?? null)\n\n // Undoing a create hard-deletes the user, so it can strip a tenant's last active\n // admin exactly like `auth.users.delete` can \u2014 promote a second admin, delete the\n // first, then undo the promotion's create. Same guard applies.\n await enforceProtectedRoleFloor(em, floorTenantId, userId, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: userId })\n await em.nativeDelete(UserRole, { user: userId })\n await em.nativeDelete(Session, { user: userId })\n await em.nativeDelete(PasswordReset, { user: userId })\n\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const reset = buildCustomFieldResetMap(undefined, snapshot.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: userId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: reset,\n notify: false,\n })\n }\n }\n removed = await de.deleteOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n soft: false,\n })\n },\n ], { transaction: true, label: 'auth.users.create.undo' })\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: removed,\n identifiers: {\n id: userId,\n organizationId: snapshot?.organizationId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n // The create-undo hard-deletes the user, but the after-snapshot persists the\n // original passwordHash (see captureUserSnapshots), so redo restores the row\n // with the SAME id and the SAME hash \u2014 never fabricating credentials (#2506).\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<UserUndoSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for user create' })\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const emailHash = computeEmailHash(after.email)\n\n let user = await findOneWithDecryption(em, User, { id: after.id }, {}, { tenantId: null, organizationId: null })\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n user.deletedAt = null\n user.email = after.email\n user.emailHash = emailHash\n user.organizationId = after.organizationId ?? null\n user.tenantId = after.tenantId ?? null\n user.passwordHash = after.passwordHash ?? null\n user.name = after.name ?? null\n user.isConfirmed = after.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: after.id,\n email: after.email,\n emailHash,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n passwordHash: after.passwordHash ?? null,\n name: after.name ?? null,\n isConfirmed: after.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: after.id })\n await syncUserRoles(em, user, after.roles, after.tenantId)\n await restoreUserAcls(em, user, after.acls)\n\n if (after.custom && Object.keys(after.custom).length) {\n const reset = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n }\n },\n ], { transaction: true })\n\n if (!user) throw new CrudHttpError(400, { error: '[internal] redo failed to restore user row' })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, after.id)\n\n return { user }\n },\n}\n\nasync function sendInviteToUser(\n em: EntityManager,\n user: User,\n): Promise<{ emailSent: boolean }> {\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + INVITE_TOKEN_TTL_MS)\n const row = em.create(PasswordReset, { user, token: tokenHash, expiresAt, createdAt: new Date() })\n await em.persist(row).flush()\n\n const base = getSecurityEmailBaseUrl()\n const inviteUrl = `${base}/reset/${rawToken}`\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.invite.subject', 'You have been invited')\n const copy = {\n preview: translate('auth.email.invite.preview', 'Set up your account'),\n title: translate('auth.email.invite.title', 'You have been invited'),\n body: translate('auth.email.invite.body', 'An administrator has created an account for you. Click the link below to set your password. This link will expire in 48 hours.'),\n cta: translate('auth.email.invite.cta', 'Set up your password'),\n hint: translate('auth.email.invite.hint', 'If you did not expect this invitation, you can safely ignore this email.'),\n }\n\n let emailSent = true\n try {\n await sendEmail({ to: user.email, subject, react: InviteUserEmail({ inviteUrl, copy }) })\n } catch (err) {\n logger.error('Failed to send invitation email', { err })\n emailSent = false\n }\n\n return { emailSent }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const code = (error as { code?: string }).code\n if (code === '23505') return true\n const messageRaw = (error as { message?: string })?.message\n const message = typeof messageRaw === 'string' ? messageRaw : ''\n return message.toLowerCase().includes('duplicate key')\n}\n\nconst updateUserCommand: CommandHandler<Record<string, unknown>, User> = {\n id: 'auth.users.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n assertTargetTenantInScope(resolveActorTenantScope(ctx), existing.tenantId, 'User not found')\n const roles = await loadUserRoleNames(em, parsed.id)\n const acls = await loadUserAclSnapshots(em, parsed.id)\n const custom = await loadUserCustomSnapshot(\n em,\n parsed.id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const actorTenantScope = resolveActorTenantScope(ctx)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const rolesBefore = Array.isArray(parsed.roles)\n ? await loadUserRoleNames(em, parsed.id)\n : null\n\n let tenantId: string | null | undefined\n let destinationChanged = false\n if (parsed.organizationId !== undefined) {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId ?? null },\n )\n if (!organization) return throwUserDestinationOrganizationNotFound(400)\n tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n if (!tenantId) return throwUserDestinationOrganizationNotFound(400)\n const currentUser = await findOneWithDecryption(\n em,\n User,\n { id: parsed.id, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!currentUser) throw new CrudHttpError(404, { error: 'User not found' })\n const currentOrganizationId = currentUser.organizationId ? String(currentUser.organizationId) : null\n const currentTenantId = currentUser.tenantId ? String(currentUser.tenantId) : null\n destinationChanged = currentOrganizationId !== parsed.organizationId || currentTenantId !== tenantId\n if (destinationChanged) {\n const rbacService = ctx.container.resolve('rbacService') as RbacService\n const destinationRoles = await resolveUserDestinationRoles({\n em,\n targetUserId: parsed.id,\n destinationTenantId: tenantId,\n roleTokens: parsed.roles,\n })\n const actorIsSuperAdmin = ctx.systemActor === true || ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope?.tenantId === tenantId\n ? ctx.organizationScope\n : !actorIsSuperAdmin && ctx.auth?.sub\n ? await resolveOrganizationScope({\n em,\n rbac: rbacService,\n auth: ctx.auth,\n tenantId,\n })\n : null\n await assertActorCanAssignUserDestination({\n em,\n rbacService,\n actorUserId: ctx.auth?.sub,\n actorIsSuperAdmin,\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n allowedOrganizationIds: organizationScope?.allowedIds,\n destinationTenantId: tenantId,\n destinationOrganizationId: parsed.organizationId,\n roles: destinationRoles,\n })\n }\n }\n\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n const targetTenantId = tenantId !== undefined ? tenantId : userTenantId\n const isTenantChanging = targetTenantId !== userTenantId\n\n // Hash password BEFORE transaction begins to avoid holding locks during CPU-heavy tasks\n let hashed: string | null = null\n let emailHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n hashed = await hash(parsed.password, 10)\n }\n if (parsed.email !== undefined) {\n emailHash = computeEmailHash(parsed.email)\n }\n\n const updateWhere: Record<string, unknown> = { id: parsed.id, deletedAt: null }\n if (actorTenantScope) updateWhere.tenantId = actorTenantScope\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user!: User\n\n await withAtomicFlush(em, [\n async () => {\n // Floor check must run inside the transaction so that LockMode.PESSIMISTIC_WRITE locks Role rows properly\n await enforceProtectedRoleFloor(em, userTenantId, parsed.id, {\n deactivating: parsed.isConfirmed === false || isTenantChanging,\n newRoles: parsed.roles,\n }, ctx)\n\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq) \u2014 a matching email in another tenant must not block\n // the update or leak cross-tenant account existence (#2934). `targetTenantId` is the\n // tenant the user will belong to after this update, so the check follows a move.\n if (parsed.email !== undefined) {\n const duplicate = await findOneWithDecryption(\n em,\n User,\n {\n $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }],\n deletedAt: null,\n tenantId: targetTenantId,\n id: { $ne: parsed.id } as any,\n } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n if (duplicate) await throwDuplicateEmailError()\n }\n\n try {\n const updated = await de.updateOrmEntity({\n entity: User,\n where: updateWhere as FilterQuery<User>,\n apply: (entity) => {\n if (parsed.email !== undefined) {\n entity.email = parsed.email\n entity.emailHash = emailHash\n }\n if (parsed.name !== undefined) {\n entity.name = parsed.name\n }\n if (parsed.organizationId !== undefined) {\n entity.organizationId = parsed.organizationId\n entity.tenantId = tenantId ?? null\n }\n if (parsed.isConfirmed !== undefined) {\n entity.isConfirmed = parsed.isConfirmed\n }\n if (hashed) entity.passwordHash = hashed\n },\n })\n if (updated) user = updated\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n if (!user) throw new CrudHttpError(404, { error: 'User not found' })\n\n if (hashed || parsed.isConfirmed === false) {\n await em.nativeDelete(Session, { user: parsed.id })\n }\n\n if (Array.isArray(parsed.roles)) {\n await syncUserRoles(em, user, parsed.roles, user.tenantId ? String(user.tenantId) : tenantId ?? null)\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n values: custom,\n })\n }\n ], { transaction: true, label: destinationChanged ? 'auth.users.update.destination' : 'auth.users.update' })\n\n const identifiers = {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: user,\n identifiers,\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (Array.isArray(parsed.roles) && rolesBefore) {\n const rolesAfter = await loadUserRoleNames(em, String(user.id))\n const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter)\n if (assigned.length || revoked.length) {\n await notifyRoleChanges(ctx, user, assigned, revoked)\n }\n }\n\n await invalidateUserCache(ctx, parsed.id)\n\n return user\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(result.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n return serializeUser(result, roles, custom)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterRoles = await loadUserRoleNames(em, String(result.id))\n const afterCustom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n const afterSnapshots = captureUserSnapshots(result, afterRoles, undefined, afterCustom)\n const after = afterSnapshots.view\n const changes = buildChanges(before ?? null, after as Record<string, unknown>, ['email', 'organizationId', 'tenantId', 'name', 'isConfirmed'])\n if (before && !arrayEquals(before.roles, afterRoles)) {\n changes.roles = { from: before.roles, to: afterRoles }\n }\n const customDiff = diffCustomFieldChanges(before?.custom, afterCustom)\n for (const [key, diff] of Object.entries(customDiff)) {\n changes[`cf_${key}`] = diff\n }\n return {\n actionLabel: translate('auth.audit.users.update', 'Update user'),\n resourceKind: 'auth.user',\n resourceId: String(result.id),\n tenantId: result.tenantId ? String(result.tenantId) : null,\n organizationId: result.organizationId ? String(result.organizationId) : null,\n changes,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: {\n before: beforeUndo,\n after: afterSnapshots.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n const after = payload?.after\n if (!before) return\n const userId = before.id\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Reverting an update can drop the tenant below a protected role's floor just as the\n // forward path can \u2014 restoring an empty `before.roles` on what is now the last admin,\n // or restoring `isConfirmed: false`. Undo is reachable from the audit-log UI, so the\n // guard has to run here too, inside a transaction so the row lock is valid.\n const restoredTenantId = before.tenantId ? String(before.tenantId) : null\n\n let updated: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const currentTenantId = current?.tenantId ? String(current.tenantId) : null\n\n await enforceProtectedRoleFloor(em, currentTenantId, userId, {\n deactivating: before.isConfirmed === false || restoredTenantId !== currentTenantId,\n newRoles: before.roles,\n }, ctx)\n\n updated = await de.updateOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n apply: (entity) => {\n entity.email = before.email\n entity.organizationId = before.organizationId ?? null\n entity.tenantId = before.tenantId ?? null\n entity.passwordHash = before.passwordHash ?? null\n entity.name = before.name ?? null\n entity.isConfirmed = before.isConfirmed\n },\n })\n\n if (updated) {\n await syncUserRoles(em, updated, before.roles, before.tenantId)\n }\n },\n ], { transaction: true, label: 'auth.users.update.undo' })\n\n const reset = buildCustomFieldResetMap(before.custom, after?.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: updated,\n identifiers: {\n id: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n}\n\nconst deleteUserCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, User> = {\n id: 'auth.users.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) return {}\n const actorTenantScope = resolveActorTenantScope(ctx)\n if (actorTenantScope) {\n const targetTenant = normalizeTenantId(existing.tenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) return {}\n }\n const roles = await loadUserRoleNames(em, id)\n const acls = await loadUserAclSnapshots(em, id)\n const custom = await loadUserCustomSnapshot(\n em,\n id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const actorTenantScope = resolveActorTenantScope(ctx)\n\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const deleteWhere: Record<string, unknown> = { id, deletedAt: null }\n if (actorTenantScope) deleteWhere.tenantId = actorTenantScope\n\n let user!: User\n await withAtomicFlush(em, [\n async () => {\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n await enforceProtectedRoleFloor(em, userTenantId, id, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: id })\n await em.nativeDelete(UserRole, { user: id })\n await em.nativeDelete(Session, { user: id })\n await em.nativeDelete(PasswordReset, { user: id })\n const removed = await de.deleteOrmEntity({\n entity: User,\n where: deleteWhere as FilterQuery<User>,\n soft: false,\n })\n if (!removed) throw new CrudHttpError(404, { error: 'User not found' })\n user = removed\n },\n ], { transaction: true })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: user,\n identifiers: {\n id: String(id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, id)\n\n return user\n },\n buildLog: async ({ snapshots, input, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const id = requireId(input, 'User id required')\n return {\n actionLabel: translate('auth.audit.users.delete', 'Delete user'),\n resourceKind: 'auth.user',\n resourceId: id,\n snapshotBefore: before ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n payload: {\n undo: {\n before: beforeUndo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager)\n let user = await findOneWithDecryption(em, User, { id: before.id }, {}, { tenantId: null, organizationId: null })\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n if (user.deletedAt) {\n user.deletedAt = null\n }\n user.email = before.email\n user.organizationId = before.organizationId ?? null\n user.tenantId = before.tenantId ?? null\n user.passwordHash = before.passwordHash ?? null\n user.name = before.name ?? null\n user.isConfirmed = before.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: before.id,\n email: before.email,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n passwordHash: before.passwordHash ?? null,\n name: before.name ?? null,\n isConfirmed: before.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: before.id })\n await syncUserRoles(em, user, before.roles, before.tenantId)\n\n await restoreUserAcls(em, user, before.acls)\n\n const reset = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n },\n ], { transaction: true })\n\n await invalidateUserCache(ctx, before.id)\n },\n}\n\nregisterCommand(createUserCommand)\nregisterCommand(updateUserCommand)\nregisterCommand(deleteUserCommand)\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nasync function resolveRole(\n em: EntityManager,\n value: string,\n normalizedTenantId: string | null,\n): Promise<Role | null> {\n if (UUID_RE.test(value)) {\n const where: Record<string, unknown> = { id: value }\n if (normalizedTenantId !== null) {\n where.tenantId = normalizedTenantId\n }\n return findOneWithDecryption(em, Role, where as any, {}, { tenantId: normalizedTenantId, organizationId: null })\n }\n return findOneWithDecryption(em, Role, { name: value, tenantId: normalizedTenantId }, {}, { tenantId: normalizedTenantId, organizationId: null })\n}\n\nasync function syncUserRoles(em: EntityManager, user: User, desiredRoles: string[], tenantId: string | null) {\n const unique = Array.from(new Set(desiredRoles.map((role) => role.trim()).filter(Boolean)))\n const normalizedTenantId = normalizeTenantId(tenantId ?? null) ?? null\n\n const resolvedRoles: Role[] = []\n const missingRoles: string[] = []\n for (const value of unique) {\n const role = await resolveRole(em, value, normalizedTenantId)\n if (!role) {\n missingRoles.push(value)\n } else {\n resolvedRoles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((n) => `\"${n}\"`).join(', ')\n throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })\n }\n\n const desiredIds = new Set(resolvedRoles.map((r) => String(r.id)))\n const currentLinks = await findWithDecryption(em, UserRole, { user }, {}, { tenantId: null, organizationId: null })\n const currentRoleIds = new Map(\n currentLinks.map((link) => {\n const roleId = String(link.role?.id ?? (link.role as unknown as string) ?? '')\n return [roleId, link] as const\n }),\n )\n\n for (const [roleId, link] of currentRoleIds.entries()) {\n if (!desiredIds.has(roleId) && link) {\n em.remove(link)\n }\n }\n\n for (const role of resolvedRoles) {\n if (!currentRoleIds.has(String(role.id))) {\n em.persist(em.create(UserRole, { user, role, createdAt: new Date() }))\n }\n }\n\n await em.flush()\n}\n\nasync function loadUserRoleNames(em: EntityManager, userId: string): Promise<string[]> {\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as unknown as User },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const names = links\n .map((link) => link.role?.name ?? '')\n .filter((name): name is string => !!name)\n return Array.from(new Set(names)).sort((a, b) => a.localeCompare(b))\n}\n\nfunction serializeUser(user: User, roles: string[], custom?: Record<string, unknown> | null): SerializedUser {\n const payload: SerializedUser = {\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n roles,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n }\n if (custom && Object.keys(custom).length) payload.custom = custom\n return payload\n}\n\nfunction captureUserSnapshots(\n user: User,\n roles: string[],\n acls: UserAclSnapshot[] = [],\n custom?: Record<string, unknown> | null\n): UserSnapshots {\n return {\n view: serializeUser(user, roles, custom),\n undo: {\n id: String(user.id),\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n passwordHash: user.passwordHash ? String(user.passwordHash) : null,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n roles: [...roles],\n acls,\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n },\n }\n}\n\nasync function loadUserAclSnapshots(em: EntityManager, userId: string): Promise<UserAclSnapshot[]> {\n const list = await findWithDecryption(em, UserAcl, { user: userId as unknown as User }, {}, { tenantId: null, organizationId: null })\n return list.map((acl) => ({\n tenantId: String(acl.tenantId),\n features: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n isSuperAdmin: Boolean(acl.isSuperAdmin),\n organizations: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }))\n}\n\nasync function restoreUserAcls(em: EntityManager, user: User, acls: UserAclSnapshot[]) {\n await em.nativeDelete(UserAcl, { user: String(user.id) })\n for (const acl of acls) {\n const entity = em.create(UserAcl, {\n user,\n tenantId: acl.tenantId,\n featuresJson: acl.features ?? null,\n isSuperAdmin: acl.isSuperAdmin,\n organizationsJson: acl.organizations ?? null,\n createdAt: new Date(),\n })\n em.persist(entity)\n }\n await em.flush()\n}\n\nasync function loadUserCustomSnapshot(\n em: EntityManager,\n id: string,\n tenantId: string | null,\n organizationId: string | null\n): Promise<Record<string, unknown>> {\n return await loadCustomFieldSnapshot(em, {\n entityId: E.auth.user,\n recordId: id,\n tenantId,\n organizationId,\n })\n}\n\nasync function invalidateUserCache(ctx: CommandRuntimeContext, userId: string) {\n try {\n const rbacService = ctx.container.resolve('rbacService') as { invalidateUserCache: (uid: string) => Promise<void> }\n await rbacService.invalidateUserCache(userId)\n } catch {\n // RBAC not available\n }\n\n try {\n const cache = ctx.container.resolve('cache') as { deleteByTags?: (tags: string[]) => Promise<void> }\n if (cache?.deleteByTags) await cache.deleteByTags([`rbac:user:${userId}`])\n } catch {\n // cache not available\n }\n}\n\nfunction diffRoleChanges(before: string[], after: string[]) {\n const beforeSet = new Set(before)\n const afterSet = new Set(after)\n const assigned = after.filter((role) => !beforeSet.has(role))\n const revoked = before.filter((role) => !afterSet.has(role))\n return { assigned, revoked }\n}\n\nfunction arrayEquals(left: string[] | undefined, right: string[]): boolean {\n if (!left) return false\n if (left.length !== right.length) return false\n return left.every((value, idx) => value === right[idx])\n}\n\nasync function throwDuplicateEmailError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('auth.users.errors.emailExists', 'Email already in use')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { email: message },\n details: [{ path: ['email'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\ntype ProtectedRoleFloorOptions = {\n deactivating?: boolean\n newRoles?: string[]\n deleting?: boolean\n}\n\n/**\n * True when the requested mutation can lower a role's active holder count. Guards the\n * floor check so that ordinary edits (display name, password, email) never take the\n * tenant-wide role lock \u2014 `PUT /api/auth/profile` routes every self-service password\n * change through `auth.users.update`, so an unconditional lock would serialize them.\n */\nfunction couldReduceActiveHolders(options: ProtectedRoleFloorOptions): boolean {\n return options.deleting === true || options.deactivating === true || options.newRoles !== undefined\n}\n\nasync function enforceProtectedRoleFloor(\n em: EntityManager,\n tenantId: string | null,\n userId: string,\n options: ProtectedRoleFloorOptions,\n ctx?: CommandRuntimeContext,\n): Promise<void> {\n // Internal automation (CLI, migrations, tenant teardown) must never be blocked by the\n // floor. Superadmins are deliberately NOT exempt \u2014 see the spec's Risks section.\n if (ctx?.systemActor === true) return\n if (!couldReduceActiveHolders(options)) return\n\n const normalizedTenantId = normalizeTenantId(tenantId) ?? null\n if (!normalizedTenantId) return\n\n // Find all protected roles in this tenant, acquiring a pessimistic write lock in a deterministic primary key order\n const protectedRoles = await findWithDecryption(em, Role, {\n tenantId: normalizedTenantId,\n minActiveHolders: { $gt: 0 },\n deletedAt: null\n }, {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n orderBy: { id: 'ASC' }\n }, { tenantId: normalizedTenantId, organizationId: null })\n\n if (protectedRoles.length === 0) return\n\n const { translate } = await resolveTranslations()\n\n for (const role of protectedRoles) {\n const minFloor = role.minActiveHolders ?? 0\n if (minFloor <= 0) continue\n\n // Active links for this role, scoped to the tenant by the nested user filter so the\n // database \u2014 not a post-filter \u2014 enforces isolation. Deliberately NOT populated:\n // `findWithDecryption` runs `decryptEntityGraph` over loaded relations, which would\n // decrypt every admin's email and name on each check just to read their ids.\n const activeLinks = await findWithDecryption(em, UserRole, {\n role: role.id,\n deletedAt: null,\n user: {\n deletedAt: null,\n isConfirmed: true,\n tenantId: normalizedTenantId\n }\n }, {}, { tenantId: null, organizationId: null })\n\n // Count distinct user IDs in the tenant holding this role to prevent overcounting due to duplicate links\n const activeUserIds = Array.from(\n new Set(\n activeLinks\n .map((link) => {\n const userRef = link.user as unknown as { id?: string } | string | null | undefined\n const linkedUserId = typeof userRef === 'string' ? userRef : userRef?.id\n return linkedUserId ? String(linkedUserId) : null\n })\n .filter((id): id is string => !!id)\n )\n )\n\n // Is the target user currently one of the active holders?\n if (activeUserIds.includes(userId)) {\n // Determine if they will remain an active holder\n let willStillBeActiveHolder = true\n\n if (options.deleting || options.deactivating) {\n willStillBeActiveHolder = false\n } else if (options.newRoles !== undefined) {\n // Checking role list\n const desiredUnique = Array.from(new Set(options.newRoles.map((r) => r.trim().toLowerCase()).filter(Boolean)))\n const roleNameLower = role.name.toLowerCase()\n const hasRoleByName = desiredUnique.includes(roleNameLower) || desiredUnique.includes(String(role.id).toLowerCase())\n if (!hasRoleByName) {\n willStillBeActiveHolder = false\n }\n }\n\n if (!willStillBeActiveHolder) {\n const remaining = activeUserIds.length - 1\n if (remaining < minFloor) {\n throw new CrudHttpError(400, {\n error: translate('auth.users.errors.lastHolderOfCriticalRole', 'Cannot remove the last active holder of role \"{roleName}\"', { roleName: role.name })\n })\n }\n }\n }\n }\n}\n"],
5
- "mappings": "AACA,SAAS,uBAAuB;AAChC;AAAA,EACE;A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B;AAE9B,UAAI,QAAQ,YAAY,QAAQ,cAAc;AAC5C,kCAA0B;AAAA,MAC5B,WAAW,QAAQ,aAAa,QAAW;AAEzC,cAAM,gBAAgB,MAAM,KAAK,IAAI,IAAI,QAAQ,SAAS,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE,YAAY,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC;AAC7G,cAAM,gBAAgB,KAAK,KAAK,YAAY;AAC5C,cAAM,gBAAgB,cAAc,SAAS,aAAa,KAAK,cAAc,SAAS,OAAO,KAAK,EAAE,EAAE,YAAY,CAAC;AACnH,YAAI,CAAC,eAAe;AAClB,oCAA0B;AAAA,QAC5B;AAAA,MACF;AAEA,UAAI,CAAC,yBAAyB;AAC5B,cAAM,YAAY,cAAc,SAAS;AACzC,YAAI,YAAY,UAAU;AACxB,gBAAM,IAAI,cAAc,KAAK;AAAA,YAC3B,OAAO,UAAU,8CAA8C,6DAA6D,EAAE,UAAU,KAAK,KAAK,CAAC;AAAA,UACrJ,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n buildChanges,\n requireId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudEventsConfig, CrudIndexerConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { UniqueConstraintViolationException, LockMode } from '@mikro-orm/core'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { User, UserRole, Role, UserAcl, Session, PasswordReset } from '@open-mercato/core/modules/auth/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { resolveOrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { E } from '#generated/entities.ids.generated'\nimport { z } from 'zod'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n diffCustomFieldChanges,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { extractUndoPayload, type UndoPayload } from '@open-mercato/shared/lib/commands/undo'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { normalizeTenantId } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { computeEmailHash, emailHashLookupValues } from '@open-mercato/core/modules/auth/lib/emailHash'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport notificationTypes from '@open-mercato/core/modules/auth/notifications'\nimport { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'\nimport { emitAuthEvent } from '@open-mercato/core/modules/auth/events'\nimport { sendEmail } from '@open-mercato/shared/lib/email/send'\nimport InviteUserEmail from '@open-mercato/core/modules/auth/emails/InviteUserEmail'\nimport { INVITE_TOKEN_TTL_MS } from '@open-mercato/core/modules/auth/lib/inviteToken'\nimport { getSecurityEmailBaseUrl } from '@open-mercato/shared/lib/url'\nimport { generateAuthToken, hashAuthToken } from '@open-mercato/core/modules/auth/lib/tokenHash'\nimport { normalizeDisplayNameInput } from '@open-mercato/core/modules/auth/lib/displayName'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport {\n assertActorCanAssignUserDestination,\n resolveUserDestinationRoles,\n throwUserDestinationOrganizationNotFound,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\n\nconst logger = createLogger('auth').child({ component: 'users-commands' })\n\ntype SerializedUser = {\n email: string\n organizationId: string | null\n tenantId: string | null\n roles: string[]\n name: string | null\n isConfirmed: boolean\n custom?: Record<string, unknown>\n}\n\ntype UserAclSnapshot = {\n tenantId: string\n features: string[] | null\n isSuperAdmin: boolean\n organizations: string[] | null\n}\n\ntype UserUndoSnapshot = {\n id: string\n email: string\n organizationId: string | null\n tenantId: string | null\n passwordHash: string | null\n name: string | null\n isConfirmed: boolean\n roles: string[]\n acls: UserAclSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype UserSnapshots = {\n view: SerializedUser\n undo: UserUndoSnapshot\n}\n\nfunction resolveActorTenantScope(ctx: CommandRuntimeContext): string | null {\n if (ctx.systemActor === true) return null\n const auth = ctx.auth\n if (!auth) return null\n if ((auth as { isSuperAdmin?: boolean }).isSuperAdmin === true) return null\n const actorTenantId = normalizeTenantId(auth.tenantId ?? null) ?? null\n return actorTenantId\n}\n\nfunction assertTargetTenantInScope(actorTenantScope: string | null, targetTenantId: unknown, notFoundError: string): void {\n if (!actorTenantScope) return\n const targetTenant = normalizeTenantId(targetTenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) {\n throw new CrudHttpError(404, { error: notFoundError })\n }\n}\n\nconst passwordSchema = buildPasswordSchema()\n\nconst displayNameSchema = z.preprocess(\n normalizeDisplayNameInput,\n z.string().trim().min(1).max(120).nullable().optional(),\n)\n\nconst createSchema = z.object({\n email: z.string().email(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n sendInviteEmail: z.boolean().optional(),\n organizationId: z.string().uuid(),\n roles: z.array(z.string()).optional(),\n}).refine(\n (data) => data.password || data.sendInviteEmail,\n { message: 'Either password or sendInviteEmail is required', path: ['password'] },\n)\n\nconst updateSchema = z.object({\n id: z.string().uuid(),\n email: z.string().email().optional(),\n name: displayNameSchema,\n password: passwordSchema.optional(),\n organizationId: z.string().uuid().optional(),\n roles: z.array(z.string()).optional(),\n isConfirmed: z.boolean().optional(),\n})\n\nexport const userCrudEvents: CrudEventsConfig = {\n module: 'auth',\n entity: 'user',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nexport const userCrudIndexer: CrudIndexerConfig = {\n entityType: E.auth.user,\n buildUpsertPayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n buildDeletePayload: (ctx) => ({\n entityType: E.auth.user,\n recordId: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\nasync function notifyRoleChanges(\n ctx: CommandRuntimeContext,\n user: User,\n assignedRoles: string[],\n revokedRoles: string[],\n): Promise<void> {\n const tenantId = user.tenantId ? String(user.tenantId) : null\n if (!tenantId) return\n const organizationId = user.organizationId ? String(user.organizationId) : null\n\n try {\n const notificationService = resolveNotificationService(ctx.container)\n if (assignedRoles.length) {\n const assignedType = notificationTypes.find((type) => type.type === 'auth.role.assigned')\n if (assignedType) {\n const notificationInput = buildNotificationFromType(assignedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n\n if (revokedRoles.length) {\n const revokedType = notificationTypes.find((type) => type.type === 'auth.role.revoked')\n if (revokedType) {\n const notificationInput = buildNotificationFromType(revokedType, {\n recipientUserId: String(user.id),\n sourceEntityType: 'auth:user',\n sourceEntityId: String(user.id),\n })\n await notificationService.create(notificationInput, { tenantId, organizationId })\n }\n }\n } catch (err) {\n logger.error('Failed to create notification', { err })\n }\n}\n\ntype CreateUserResult = { user: User; warning?: 'invite_email_failed' }\n\nconst createUserCommand: CommandHandler<Record<string, unknown>, CreateUserResult> = {\n id: 'auth.users.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(createSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId },\n )\n if (!organization) throw new CrudHttpError(400, { error: 'Organization not found' })\n const tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n assertTargetTenantInScope(resolveActorTenantScope(ctx), tenantId, 'Organization not found')\n\n const emailHash = computeEmailHash(parsed.email)\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq). Scope the duplicate check to the target tenant so the same\n // email may legitimately exist in other tenants without blocking creation or leaking\n // cross-tenant account existence (#2934).\n const duplicate = await findOneWithDecryption(em, User, { $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }], deletedAt: null, tenantId } as any, {}, { tenantId: null, organizationId: null })\n if (duplicate) await throwDuplicateEmailError()\n\n let passwordHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n passwordHash = await hash(parsed.password, 10)\n }\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user: User\n try {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n email: parsed.email,\n name: parsed.name,\n emailHash,\n passwordHash,\n isConfirmed: true,\n organizationId: parsed.organizationId,\n tenantId,\n },\n })\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n\n let assignedRoles: string[] = []\n if (Array.isArray(parsed.roles) && parsed.roles.length) {\n await syncUserRoles(em, user, parsed.roles, tenantId)\n assignedRoles = await loadUserRoleNames(em, String(user.id))\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: tenantId,\n values: custom,\n })\n\n let inviteEmailSent = false\n if (parsed.sendInviteEmail) {\n const inviteResult = await sendInviteToUser(em, user)\n inviteEmailSent = inviteResult.emailSent\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (assignedRoles.length && !parsed.sendInviteEmail) {\n await notifyRoleChanges(ctx, user, assignedRoles, [])\n }\n\n const warning = (parsed.sendInviteEmail && !inviteEmailSent) ? 'invite_email_failed' as const : undefined\n\n return { user, warning }\n },\n captureAfter: async (_input, { user }, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n return serializeUser(user, roles, custom)\n },\n buildLog: async ({ result: { user }, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(user.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(user.id),\n user.tenantId ? String(user.tenantId) : null,\n user.organizationId ? String(user.organizationId) : null\n )\n const snapshot = captureUserSnapshots(user, roles, undefined, custom)\n return {\n actionLabel: translate('auth.audit.users.create', 'Create user'),\n resourceKind: 'auth.user',\n resourceId: String(user.id),\n tenantId: user.tenantId ? String(user.tenantId) : null,\n organizationId: user.organizationId ? String(user.organizationId) : null,\n snapshotAfter: snapshot.view,\n payload: {\n undo: {\n after: snapshot.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const userId = typeof logEntry?.resourceId === 'string' ? logEntry.resourceId : null\n if (!userId) return\n const snapshot = logEntry?.snapshotAfter as SerializedUser | undefined\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Evaluate the floor against the user's CURRENT tenant, not the one recorded at\n // creation. A user moved to another tenant after being created would otherwise be\n // checked against the origin tenant \u2014 where they no longer hold anything \u2014 and the\n // undo would hard-delete the destination tenant's last administrator unchecked.\n // The create snapshot is only a fallback for a row that is already gone.\n let removed: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const floorTenantId = current?.tenantId ? String(current.tenantId) : (snapshot?.tenantId ?? null)\n\n // Undoing a create hard-deletes the user, so it can strip a tenant's last active\n // admin exactly like `auth.users.delete` can \u2014 promote a second admin, delete the\n // first, then undo the promotion's create. Same guard applies.\n await enforceProtectedRoleFloor(em, floorTenantId, userId, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: userId })\n await em.nativeDelete(UserRole, { user: userId })\n await em.nativeDelete(Session, { user: userId })\n await em.nativeDelete(PasswordReset, { user: userId })\n\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const reset = buildCustomFieldResetMap(undefined, snapshot.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: userId,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: reset,\n notify: false,\n })\n }\n }\n removed = await de.deleteOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n soft: false,\n })\n },\n ], { transaction: true, label: 'auth.users.create.undo' })\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: removed,\n identifiers: {\n id: userId,\n organizationId: snapshot?.organizationId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n // The create-undo hard-deletes the user, but the after-snapshot persists the\n // original passwordHash (see captureUserSnapshots), so redo restores the row\n // with the SAME id and the SAME hash \u2014 never fabricating credentials (#2506).\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<UserUndoSnapshot>(logEntry)\n if (!after) throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for user create' })\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const emailHash = computeEmailHash(after.email)\n\n let user = await findOneWithDecryption(em, User, { id: after.id }, {}, { tenantId: null, organizationId: null })\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n user.deletedAt = null\n user.email = after.email\n user.emailHash = emailHash\n user.organizationId = after.organizationId ?? null\n user.tenantId = after.tenantId ?? null\n user.passwordHash = after.passwordHash ?? null\n user.name = after.name ?? null\n user.isConfirmed = after.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: after.id,\n email: after.email,\n emailHash,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n passwordHash: after.passwordHash ?? null,\n name: after.name ?? null,\n isConfirmed: after.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: after.id })\n await syncUserRoles(em, user, after.roles, after.tenantId)\n await restoreUserAcls(em, user, after.acls)\n\n if (after.custom && Object.keys(after.custom).length) {\n const reset = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n }\n },\n ], { transaction: true })\n\n if (!user) throw new CrudHttpError(400, { error: '[internal] redo failed to restore user row' })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: user,\n identifiers: {\n id: after.id,\n organizationId: after.organizationId ?? null,\n tenantId: after.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, after.id)\n\n return { user }\n },\n}\n\nasync function sendInviteToUser(\n em: EntityManager,\n user: User,\n): Promise<{ emailSent: boolean }> {\n const rawToken = generateAuthToken()\n const tokenHash = hashAuthToken(rawToken)\n const expiresAt = new Date(Date.now() + INVITE_TOKEN_TTL_MS)\n const row = em.create(PasswordReset, { user, token: tokenHash, expiresAt, createdAt: new Date() })\n await em.persist(row).flush()\n\n const base = getSecurityEmailBaseUrl()\n const inviteUrl = `${base}/reset/${rawToken}`\n\n const { translate } = await resolveTranslations()\n const subject = translate('auth.email.invite.subject', 'You have been invited')\n const copy = {\n preview: translate('auth.email.invite.preview', 'Set up your account'),\n title: translate('auth.email.invite.title', 'You have been invited'),\n body: translate('auth.email.invite.body', 'An administrator has created an account for you. Click the link below to set your password. This link will expire in 48 hours.'),\n cta: translate('auth.email.invite.cta', 'Set up your password'),\n hint: translate('auth.email.invite.hint', 'If you did not expect this invitation, you can safely ignore this email.'),\n }\n\n let emailSent = true\n try {\n await sendEmail({ to: user.email, subject, react: InviteUserEmail({ inviteUrl, copy }) })\n } catch (err) {\n logger.error('Failed to send invitation email', { err })\n emailSent = false\n }\n\n return { emailSent }\n}\n\nfunction isUniqueViolation(error: unknown): boolean {\n if (error instanceof UniqueConstraintViolationException) return true\n if (!error || typeof error !== 'object') return false\n const code = (error as { code?: string }).code\n if (code === '23505') return true\n const messageRaw = (error as { message?: string })?.message\n const message = typeof messageRaw === 'string' ? messageRaw : ''\n return message.toLowerCase().includes('duplicate key')\n}\n\nconst updateUserCommand: CommandHandler<Record<string, unknown>, User> = {\n id: 'auth.users.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n assertTargetTenantInScope(resolveActorTenantScope(ctx), existing.tenantId, 'User not found')\n const roles = await loadUserRoleNames(em, parsed.id)\n const acls = await loadUserAclSnapshots(em, parsed.id)\n const custom = await loadUserCustomSnapshot(\n em,\n parsed.id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(updateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const actorTenantScope = resolveActorTenantScope(ctx)\n const existing = await findOneWithDecryption(em, User, { id: parsed.id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const rolesBefore = Array.isArray(parsed.roles)\n ? await loadUserRoleNames(em, parsed.id)\n : null\n\n let tenantId: string | null | undefined\n let destinationChanged = false\n if (parsed.organizationId !== undefined) {\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: parsed.organizationId },\n { populate: ['tenant'] },\n { tenantId: null, organizationId: parsed.organizationId ?? null },\n )\n if (!organization) return throwUserDestinationOrganizationNotFound(400)\n tenantId = organization.tenant?.id ? String(organization.tenant.id) : null\n if (!tenantId) return throwUserDestinationOrganizationNotFound(400)\n const currentUser = await findOneWithDecryption(\n em,\n User,\n { id: parsed.id, deletedAt: null },\n {},\n { tenantId: null, organizationId: null },\n )\n if (!currentUser) throw new CrudHttpError(404, { error: 'User not found' })\n const currentOrganizationId = currentUser.organizationId ? String(currentUser.organizationId) : null\n const currentTenantId = currentUser.tenantId ? String(currentUser.tenantId) : null\n destinationChanged = currentOrganizationId !== parsed.organizationId || currentTenantId !== tenantId\n if (destinationChanged) {\n const rbacService = ctx.container.resolve('rbacService') as RbacService\n const destinationRoles = await resolveUserDestinationRoles({\n em,\n targetUserId: parsed.id,\n destinationTenantId: tenantId,\n roleTokens: parsed.roles,\n })\n const actorIsSuperAdmin = ctx.systemActor === true || ctx.auth?.isSuperAdmin === true\n const organizationScope = ctx.organizationScope?.tenantId === tenantId\n ? ctx.organizationScope\n : !actorIsSuperAdmin && ctx.auth?.sub\n ? await resolveOrganizationScope({\n em,\n rbac: rbacService,\n auth: ctx.auth,\n tenantId,\n })\n : null\n await assertActorCanAssignUserDestination({\n em,\n rbacService,\n actorUserId: ctx.auth?.sub,\n actorIsSuperAdmin,\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.auth?.orgId ?? null,\n allowedOrganizationIds: organizationScope?.allowedIds,\n destinationTenantId: tenantId,\n destinationOrganizationId: parsed.organizationId,\n roles: destinationRoles,\n })\n }\n }\n\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n const targetTenantId = tenantId !== undefined ? tenantId : userTenantId\n const isTenantChanging = targetTenantId !== userTenantId\n\n // Hash password BEFORE transaction begins to avoid holding locks during CPU-heavy tasks\n let hashed: string | null = null\n let emailHash: string | null = null\n if (parsed.password) {\n const { hash } = await import('bcryptjs')\n hashed = await hash(parsed.password, 10)\n }\n if (parsed.email !== undefined) {\n emailHash = computeEmailHash(parsed.email)\n }\n\n const updateWhere: Record<string, unknown> = { id: parsed.id, deletedAt: null }\n if (actorTenantScope) updateWhere.tenantId = actorTenantScope\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n let user!: User\n\n await withAtomicFlush(em, [\n async () => {\n // Floor check must run inside the transaction so that LockMode.PESSIMISTIC_WRITE locks Role rows properly\n await enforceProtectedRoleFloor(em, userTenantId, parsed.id, {\n deactivating: parsed.isConfirmed === false || isTenantChanging,\n newRoles: parsed.roles,\n }, ctx)\n\n // Email is unique per-tenant, not globally (see Migration20260610120000:\n // users_tenant_email_hash_uniq) \u2014 a matching email in another tenant must not block\n // the update or leak cross-tenant account existence (#2934). `targetTenantId` is the\n // tenant the user will belong to after this update, so the check follows a move.\n if (parsed.email !== undefined) {\n const duplicate = await findOneWithDecryption(\n em,\n User,\n {\n $or: [{ email: parsed.email }, { emailHash: { $in: emailHashLookupValues(parsed.email) } }],\n deletedAt: null,\n tenantId: targetTenantId,\n id: { $ne: parsed.id } as any,\n } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n if (duplicate) await throwDuplicateEmailError()\n }\n\n try {\n const updated = await de.updateOrmEntity({\n entity: User,\n where: updateWhere as FilterQuery<User>,\n apply: (entity) => {\n if (parsed.email !== undefined) {\n entity.email = parsed.email\n entity.emailHash = emailHash\n }\n if (parsed.name !== undefined) {\n entity.name = parsed.name\n }\n if (parsed.organizationId !== undefined) {\n entity.organizationId = parsed.organizationId\n entity.tenantId = tenantId ?? null\n }\n if (parsed.isConfirmed !== undefined) {\n entity.isConfirmed = parsed.isConfirmed\n }\n if (hashed) entity.passwordHash = hashed\n },\n })\n if (updated) user = updated\n } catch (error) {\n if (isUniqueViolation(error)) await throwDuplicateEmailError()\n throw error\n }\n if (!user) throw new CrudHttpError(404, { error: 'User not found' })\n\n if (hashed || parsed.isConfirmed === false) {\n await em.nativeDelete(Session, { user: parsed.id })\n }\n\n if (Array.isArray(parsed.roles)) {\n await syncUserRoles(em, user, parsed.roles, user.tenantId ? String(user.tenantId) : tenantId ?? null)\n }\n\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n values: custom,\n })\n }\n ], { transaction: true, label: destinationChanged ? 'auth.users.update.destination' : 'auth.users.update' })\n\n const identifiers = {\n id: String(user.id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : tenantId ?? null,\n }\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: user,\n identifiers,\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n if (hashed) {\n const actorId = ctx.auth?.sub ? String(ctx.auth.sub) : null\n // `system` covers a command invocation with no auth context and one running under\n // `ctx.systemActor`. Without it those writes would be indistinguishable from an\n // administrator setting someone else's password, which is exactly the case security\n // alerting escalates on. Password writes that never reach this command \u2014 `mercato\n // auth set-password`, tenant provisioning \u2014 set `passwordHash` directly and emit\n // nothing, so a subscriber cannot treat this event as covering every credential change.\n const changedBy = ctx.systemActor === true || !actorId\n ? 'system'\n : actorId === identifiers.id ? 'self' : 'admin'\n void emitAuthEvent('auth.password.changed', {\n id: identifiers.id,\n tenantId: identifiers.tenantId,\n organizationId: identifiers.organizationId,\n changedBy,\n changedById: actorId,\n at: new Date().toISOString(),\n }, { persistent: true }).catch(() => undefined)\n }\n\n if (Array.isArray(parsed.roles) && rolesBefore) {\n const rolesAfter = await loadUserRoleNames(em, String(user.id))\n const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter)\n if (assigned.length || revoked.length) {\n await notifyRoleChanges(ctx, user, assigned, revoked)\n }\n }\n\n await invalidateUserCache(ctx, parsed.id)\n\n return user\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const roles = await loadUserRoleNames(em, String(result.id))\n const custom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n return serializeUser(result, roles, custom)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterRoles = await loadUserRoleNames(em, String(result.id))\n const afterCustom = await loadUserCustomSnapshot(\n em,\n String(result.id),\n result.tenantId ? String(result.tenantId) : null,\n result.organizationId ? String(result.organizationId) : null\n )\n const afterSnapshots = captureUserSnapshots(result, afterRoles, undefined, afterCustom)\n const after = afterSnapshots.view\n const changes = buildChanges(before ?? null, after as Record<string, unknown>, ['email', 'organizationId', 'tenantId', 'name', 'isConfirmed'])\n if (before && !arrayEquals(before.roles, afterRoles)) {\n changes.roles = { from: before.roles, to: afterRoles }\n }\n const customDiff = diffCustomFieldChanges(before?.custom, afterCustom)\n for (const [key, diff] of Object.entries(customDiff)) {\n changes[`cf_${key}`] = diff\n }\n return {\n actionLabel: translate('auth.audit.users.update', 'Update user'),\n resourceKind: 'auth.user',\n resourceId: String(result.id),\n tenantId: result.tenantId ? String(result.tenantId) : null,\n organizationId: result.organizationId ? String(result.organizationId) : null,\n changes,\n snapshotBefore: before ?? null,\n snapshotAfter: after,\n payload: {\n undo: {\n before: beforeUndo,\n after: afterSnapshots.undo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n const after = payload?.after\n if (!before) return\n const userId = before.id\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n // Reverting an update can drop the tenant below a protected role's floor just as the\n // forward path can \u2014 restoring an empty `before.roles` on what is now the last admin,\n // or restoring `isConfirmed: false`. Undo is reachable from the audit-log UI, so the\n // guard has to run here too, inside a transaction so the row lock is valid.\n const restoredTenantId = before.tenantId ? String(before.tenantId) : null\n\n let updated: User | null = null\n await withAtomicFlush(em, [\n async () => {\n const current = await findOneWithDecryption(em, User, { id: userId, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n const currentTenantId = current?.tenantId ? String(current.tenantId) : null\n\n await enforceProtectedRoleFloor(em, currentTenantId, userId, {\n deactivating: before.isConfirmed === false || restoredTenantId !== currentTenantId,\n newRoles: before.roles,\n }, ctx)\n\n updated = await de.updateOrmEntity({\n entity: User,\n where: { id: userId, deletedAt: null } as FilterQuery<User>,\n apply: (entity) => {\n entity.email = before.email\n entity.organizationId = before.organizationId ?? null\n entity.tenantId = before.tenantId ?? null\n entity.passwordHash = before.passwordHash ?? null\n entity.name = before.name ?? null\n entity.isConfirmed = before.isConfirmed\n },\n })\n\n if (updated) {\n await syncUserRoles(em, updated, before.roles, before.tenantId)\n }\n },\n ], { transaction: true, label: 'auth.users.update.undo' })\n\n const reset = buildCustomFieldResetMap(before.custom, after?.custom)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: updated,\n identifiers: {\n id: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, userId)\n },\n}\n\nconst deleteUserCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, User> = {\n id: 'auth.users.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) return {}\n const actorTenantScope = resolveActorTenantScope(ctx)\n if (actorTenantScope) {\n const targetTenant = normalizeTenantId(existing.tenantId) ?? null\n if (!targetTenant || targetTenant !== actorTenantScope) return {}\n }\n const roles = await loadUserRoleNames(em, id)\n const acls = await loadUserAclSnapshots(em, id)\n const custom = await loadUserCustomSnapshot(\n em,\n id,\n existing.tenantId ? String(existing.tenantId) : null,\n existing.organizationId ? String(existing.organizationId) : null\n )\n return { before: captureUserSnapshots(existing, roles, acls, custom) }\n },\n async execute(input, ctx) {\n const id = requireId(input, 'User id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n const actorTenantScope = resolveActorTenantScope(ctx)\n\n const existing = await findOneWithDecryption(em, User, { id, deletedAt: null }, {}, { tenantId: null, organizationId: null })\n if (!existing) throw new CrudHttpError(404, { error: 'User not found' })\n if (actorTenantScope && existing.tenantId && String(existing.tenantId) !== actorTenantScope) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n const deleteWhere: Record<string, unknown> = { id, deletedAt: null }\n if (actorTenantScope) deleteWhere.tenantId = actorTenantScope\n\n let user!: User\n await withAtomicFlush(em, [\n async () => {\n const userTenantId = existing.tenantId ? String(existing.tenantId) : null\n await enforceProtectedRoleFloor(em, userTenantId, id, { deleting: true }, ctx)\n\n await em.nativeDelete(UserAcl, { user: id })\n await em.nativeDelete(UserRole, { user: id })\n await em.nativeDelete(Session, { user: id })\n await em.nativeDelete(PasswordReset, { user: id })\n const removed = await de.deleteOrmEntity({\n entity: User,\n where: deleteWhere as FilterQuery<User>,\n soft: false,\n })\n if (!removed) throw new CrudHttpError(404, { error: 'User not found' })\n user = removed\n },\n ], { transaction: true })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: user,\n identifiers: {\n id: String(id),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n },\n events: userCrudEvents,\n indexer: userCrudIndexer,\n })\n\n await invalidateUserCache(ctx, id)\n\n return user\n },\n buildLog: async ({ snapshots, input, ctx }) => {\n const { translate } = await resolveTranslations()\n const beforeSnapshots = snapshots.before as UserSnapshots | undefined\n const before = beforeSnapshots?.view\n const beforeUndo = beforeSnapshots?.undo ?? null\n const id = requireId(input, 'User id required')\n return {\n actionLabel: translate('auth.audit.users.delete', 'Delete user'),\n resourceKind: 'auth.user',\n resourceId: id,\n snapshotBefore: before ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n payload: {\n undo: {\n before: beforeUndo,\n },\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<UndoPayload<UserUndoSnapshot>>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager)\n let user = await findOneWithDecryption(em, User, { id: before.id }, {}, { tenantId: null, organizationId: null })\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n\n await withAtomicFlush(em, [\n async () => {\n if (user) {\n if (user.deletedAt) {\n user.deletedAt = null\n }\n user.email = before.email\n user.organizationId = before.organizationId ?? null\n user.tenantId = before.tenantId ?? null\n user.passwordHash = before.passwordHash ?? null\n user.name = before.name ?? null\n user.isConfirmed = before.isConfirmed\n await em.flush()\n } else {\n user = await de.createOrmEntity({\n entity: User,\n data: {\n id: before.id,\n email: before.email,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n passwordHash: before.passwordHash ?? null,\n name: before.name ?? null,\n isConfirmed: before.isConfirmed,\n },\n })\n }\n\n if (!user) return\n\n await em.nativeDelete(UserRole, { user: before.id })\n await syncUserRoles(em, user, before.roles, before.tenantId)\n\n await restoreUserAcls(em, user, before.acls)\n\n const reset = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(reset).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: E.auth.user,\n recordId: before.id,\n organizationId: before.organizationId ?? null,\n tenantId: before.tenantId ?? null,\n values: reset,\n notify: false,\n })\n }\n },\n ], { transaction: true })\n\n await invalidateUserCache(ctx, before.id)\n },\n}\n\nregisterCommand(createUserCommand)\nregisterCommand(updateUserCommand)\nregisterCommand(deleteUserCommand)\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nasync function resolveRole(\n em: EntityManager,\n value: string,\n normalizedTenantId: string | null,\n): Promise<Role | null> {\n if (UUID_RE.test(value)) {\n const where: Record<string, unknown> = { id: value }\n if (normalizedTenantId !== null) {\n where.tenantId = normalizedTenantId\n }\n return findOneWithDecryption(em, Role, where as any, {}, { tenantId: normalizedTenantId, organizationId: null })\n }\n return findOneWithDecryption(em, Role, { name: value, tenantId: normalizedTenantId }, {}, { tenantId: normalizedTenantId, organizationId: null })\n}\n\nasync function syncUserRoles(em: EntityManager, user: User, desiredRoles: string[], tenantId: string | null) {\n const unique = Array.from(new Set(desiredRoles.map((role) => role.trim()).filter(Boolean)))\n const normalizedTenantId = normalizeTenantId(tenantId ?? null) ?? null\n\n const resolvedRoles: Role[] = []\n const missingRoles: string[] = []\n for (const value of unique) {\n const role = await resolveRole(em, value, normalizedTenantId)\n if (!role) {\n missingRoles.push(value)\n } else {\n resolvedRoles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((n) => `\"${n}\"`).join(', ')\n throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })\n }\n\n const desiredIds = new Set(resolvedRoles.map((r) => String(r.id)))\n const currentLinks = await findWithDecryption(em, UserRole, { user }, {}, { tenantId: null, organizationId: null })\n const currentRoleIds = new Map(\n currentLinks.map((link) => {\n const roleId = String(link.role?.id ?? (link.role as unknown as string) ?? '')\n return [roleId, link] as const\n }),\n )\n\n for (const [roleId, link] of currentRoleIds.entries()) {\n if (!desiredIds.has(roleId) && link) {\n em.remove(link)\n }\n }\n\n for (const role of resolvedRoles) {\n if (!currentRoleIds.has(String(role.id))) {\n em.persist(em.create(UserRole, { user, role, createdAt: new Date() }))\n }\n }\n\n await em.flush()\n}\n\nasync function loadUserRoleNames(em: EntityManager, userId: string): Promise<string[]> {\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as unknown as User },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const names = links\n .map((link) => link.role?.name ?? '')\n .filter((name): name is string => !!name)\n return Array.from(new Set(names)).sort((a, b) => a.localeCompare(b))\n}\n\nfunction serializeUser(user: User, roles: string[], custom?: Record<string, unknown> | null): SerializedUser {\n const payload: SerializedUser = {\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n roles,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n }\n if (custom && Object.keys(custom).length) payload.custom = custom\n return payload\n}\n\nfunction captureUserSnapshots(\n user: User,\n roles: string[],\n acls: UserAclSnapshot[] = [],\n custom?: Record<string, unknown> | null\n): UserSnapshots {\n return {\n view: serializeUser(user, roles, custom),\n undo: {\n id: String(user.id),\n email: String(user.email ?? ''),\n organizationId: user.organizationId ? String(user.organizationId) : null,\n tenantId: user.tenantId ? String(user.tenantId) : null,\n passwordHash: user.passwordHash ? String(user.passwordHash) : null,\n name: user.name ? String(user.name) : null,\n isConfirmed: Boolean(user.isConfirmed),\n roles: [...roles],\n acls,\n ...(custom && Object.keys(custom).length ? { custom } : {}),\n },\n }\n}\n\nasync function loadUserAclSnapshots(em: EntityManager, userId: string): Promise<UserAclSnapshot[]> {\n const list = await findWithDecryption(em, UserAcl, { user: userId as unknown as User }, {}, { tenantId: null, organizationId: null })\n return list.map((acl) => ({\n tenantId: String(acl.tenantId),\n features: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n isSuperAdmin: Boolean(acl.isSuperAdmin),\n organizations: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }))\n}\n\nasync function restoreUserAcls(em: EntityManager, user: User, acls: UserAclSnapshot[]) {\n await em.nativeDelete(UserAcl, { user: String(user.id) })\n for (const acl of acls) {\n const entity = em.create(UserAcl, {\n user,\n tenantId: acl.tenantId,\n featuresJson: acl.features ?? null,\n isSuperAdmin: acl.isSuperAdmin,\n organizationsJson: acl.organizations ?? null,\n createdAt: new Date(),\n })\n em.persist(entity)\n }\n await em.flush()\n}\n\nasync function loadUserCustomSnapshot(\n em: EntityManager,\n id: string,\n tenantId: string | null,\n organizationId: string | null\n): Promise<Record<string, unknown>> {\n return await loadCustomFieldSnapshot(em, {\n entityId: E.auth.user,\n recordId: id,\n tenantId,\n organizationId,\n })\n}\n\nasync function invalidateUserCache(ctx: CommandRuntimeContext, userId: string) {\n try {\n const rbacService = ctx.container.resolve('rbacService') as { invalidateUserCache: (uid: string) => Promise<void> }\n await rbacService.invalidateUserCache(userId)\n } catch {\n // RBAC not available\n }\n\n try {\n const cache = ctx.container.resolve('cache') as { deleteByTags?: (tags: string[]) => Promise<void> }\n if (cache?.deleteByTags) await cache.deleteByTags([`rbac:user:${userId}`])\n } catch {\n // cache not available\n }\n}\n\nfunction diffRoleChanges(before: string[], after: string[]) {\n const beforeSet = new Set(before)\n const afterSet = new Set(after)\n const assigned = after.filter((role) => !beforeSet.has(role))\n const revoked = before.filter((role) => !afterSet.has(role))\n return { assigned, revoked }\n}\n\nfunction arrayEquals(left: string[] | undefined, right: string[]): boolean {\n if (!left) return false\n if (left.length !== right.length) return false\n return left.every((value, idx) => value === right[idx])\n}\n\nasync function throwDuplicateEmailError(): Promise<never> {\n const { translate } = await resolveTranslations()\n const message = translate('auth.users.errors.emailExists', 'Email already in use')\n throw new CrudHttpError(400, {\n error: message,\n fieldErrors: { email: message },\n details: [{ path: ['email'], message, code: 'duplicate', origin: 'validation' }],\n })\n}\n\ntype ProtectedRoleFloorOptions = {\n deactivating?: boolean\n newRoles?: string[]\n deleting?: boolean\n}\n\n/**\n * True when the requested mutation can lower a role's active holder count. Guards the\n * floor check so that ordinary edits (display name, password, email) never take the\n * tenant-wide role lock \u2014 `PUT /api/auth/profile` routes every self-service password\n * change through `auth.users.update`, so an unconditional lock would serialize them.\n */\nfunction couldReduceActiveHolders(options: ProtectedRoleFloorOptions): boolean {\n return options.deleting === true || options.deactivating === true || options.newRoles !== undefined\n}\n\nasync function enforceProtectedRoleFloor(\n em: EntityManager,\n tenantId: string | null,\n userId: string,\n options: ProtectedRoleFloorOptions,\n ctx?: CommandRuntimeContext,\n): Promise<void> {\n // Internal automation (CLI, migrations, tenant teardown) must never be blocked by the\n // floor. Superadmins are deliberately NOT exempt \u2014 see the spec's Risks section.\n if (ctx?.systemActor === true) return\n if (!couldReduceActiveHolders(options)) return\n\n const normalizedTenantId = normalizeTenantId(tenantId) ?? null\n if (!normalizedTenantId) return\n\n // Find all protected roles in this tenant, acquiring a pessimistic write lock in a deterministic primary key order\n const protectedRoles = await findWithDecryption(em, Role, {\n tenantId: normalizedTenantId,\n minActiveHolders: { $gt: 0 },\n deletedAt: null\n }, {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n orderBy: { id: 'ASC' }\n }, { tenantId: normalizedTenantId, organizationId: null })\n\n if (protectedRoles.length === 0) return\n\n const { translate } = await resolveTranslations()\n\n for (const role of protectedRoles) {\n const minFloor = role.minActiveHolders ?? 0\n if (minFloor <= 0) continue\n\n // Active links for this role, scoped to the tenant by the nested user filter so the\n // database \u2014 not a post-filter \u2014 enforces isolation. Deliberately NOT populated:\n // `findWithDecryption` runs `decryptEntityGraph` over loaded relations, which would\n // decrypt every admin's email and name on each check just to read their ids.\n const activeLinks = await findWithDecryption(em, UserRole, {\n role: role.id,\n deletedAt: null,\n user: {\n deletedAt: null,\n isConfirmed: true,\n tenantId: normalizedTenantId\n }\n }, {}, { tenantId: null, organizationId: null })\n\n // Count distinct user IDs in the tenant holding this role to prevent overcounting due to duplicate links\n const activeUserIds = Array.from(\n new Set(\n activeLinks\n .map((link) => {\n const userRef = link.user as unknown as { id?: string } | string | null | undefined\n const linkedUserId = typeof userRef === 'string' ? userRef : userRef?.id\n return linkedUserId ? String(linkedUserId) : null\n })\n .filter((id): id is string => !!id)\n )\n )\n\n // Is the target user currently one of the active holders?\n if (activeUserIds.includes(userId)) {\n // Determine if they will remain an active holder\n let willStillBeActiveHolder = true\n\n if (options.deleting || options.deactivating) {\n willStillBeActiveHolder = false\n } else if (options.newRoles !== undefined) {\n // Checking role list\n const desiredUnique = Array.from(new Set(options.newRoles.map((r) => r.trim().toLowerCase()).filter(Boolean)))\n const roleNameLower = role.name.toLowerCase()\n const hasRoleByName = desiredUnique.includes(roleNameLower) || desiredUnique.includes(String(role.id).toLowerCase())\n if (!hasRoleByName) {\n willStillBeActiveHolder = false\n }\n }\n\n if (!willStillBeActiveHolder) {\n const remaining = activeUserIds.length - 1\n if (remaining < minFloor) {\n throw new CrudHttpError(400, {\n error: translate('auth.users.errors.lastHolderOfCriticalRole', 'Cannot remove the last active holder of role \"{roleName}\"', { roleName: role.name })\n })\n }\n }\n }\n }\n}\n"],
5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entication events
12
12
  { id: "auth.login.success", label: "Login Successful", category: "lifecycle" },
13
13
  { id: "auth.login.failed", label: "Login Failed", category: "lifecycle" },
14
+ // The logout and password payloads below identify the user by `id` only. They are
15
+ // emitted with `{ persistent: true }`, so the whole payload is serialized into the
16
+ // durable events queue, while `email` is encrypted at rest under the `auth:user`
17
+ // encryption map — a subscriber that needs the address resolves it with
18
+ // `findOneWithDecryption` under the tenant's own key.
19
+ // `sessionRevoked` reports that server-side revocation ran without throwing, not that
20
+ // a session row was removed: a session that had already expired still reports `true`.
14
21
  { id: "auth.logout", label: "User Logged Out", category: "lifecycle" },
22
+ // `changedBy` discriminates who performed the write: `self` (the account owner),
23
+ // `admin` (another authenticated user) or `system` (an `auth.users.update` carrying no
24
+ // auth context, or running under `ctx.systemActor`). `changedById` carries the actor id
25
+ // whenever there is one. Password writes that bypass the command emit nothing at all —
26
+ // `mercato auth set-password` and tenant provisioning both set `passwordHash` directly.
15
27
  { id: "auth.password.changed", label: "Password Changed", category: "lifecycle" },
16
28
  { id: "auth.password.reset.requested", label: "Password Reset Requested", category: "lifecycle" },
29
+ // Also emitted when an invited user sets their initial password: invitation
30
+ // emails link to /reset/<token> and post to the same confirm endpoint, so
31
+ // those completions arrive with no preceding `auth.password.reset.requested`.
17
32
  { id: "auth.password.reset.completed", label: "Password Reset Completed", category: "lifecycle" }
18
33
  ];
19
34
  const eventsConfig = createModuleEvents({
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/auth/events.ts"],
4
- "sourcesContent": ["import { createModuleEvents } from '@open-mercato/shared/modules/events'\n\n/**\n * Auth Module Events\n *\n * Declares all events that can be emitted by the auth module.\n */\nconst events = [\n // Users\n { id: 'auth.user.created', label: 'User Created', entity: 'user', category: 'crud' },\n { id: 'auth.user.updated', label: 'User Updated', entity: 'user', category: 'crud' },\n { id: 'auth.user.deleted', label: 'User Deleted', entity: 'user', category: 'crud' },\n\n // Roles\n { id: 'auth.role.created', label: 'Role Created', entity: 'role', category: 'crud' },\n { id: 'auth.role.updated', label: 'Role Updated', entity: 'role', category: 'crud' },\n { id: 'auth.role.deleted', label: 'Role Deleted', entity: 'role', category: 'crud' },\n\n // Authentication events\n { id: 'auth.login.success', label: 'Login Successful', category: 'lifecycle' },\n { id: 'auth.login.failed', label: 'Login Failed', category: 'lifecycle' },\n { id: 'auth.logout', label: 'User Logged Out', category: 'lifecycle' },\n { id: 'auth.password.changed', label: 'Password Changed', category: 'lifecycle' },\n { id: 'auth.password.reset.requested', label: 'Password Reset Requested', category: 'lifecycle' },\n { id: 'auth.password.reset.completed', label: 'Password Reset Completed', category: 'lifecycle' },\n] as const\n\nexport const eventsConfig = createModuleEvents({\n moduleId: 'auth',\n events,\n})\n\n/** Type-safe event emitter for auth module */\nexport const emitAuthEvent = eventsConfig.emit\n\n/** Event IDs that can be emitted by the auth module */\nexport type AuthEventId = typeof events[number]['id']\n\nexport default eventsConfig\n"],
5
- "mappings": "AAAA,SAAS,0BAA0B;AAOnC,MAAM,SAAS;AAAA;AAAA,EAEb,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA;AAAA,EAGnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA;AAAA,EAGnF,EAAE,IAAI,sBAAsB,OAAO,oBAAoB,UAAU,YAAY;AAAA,EAC7E,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,UAAU,YAAY;AAAA,EACxE,EAAE,IAAI,eAAe,OAAO,mBAAmB,UAAU,YAAY;AAAA,EACrE,EAAE,IAAI,yBAAyB,OAAO,oBAAoB,UAAU,YAAY;AAAA,EAChF,EAAE,IAAI,iCAAiC,OAAO,4BAA4B,UAAU,YAAY;AAAA,EAChG,EAAE,IAAI,iCAAiC,OAAO,4BAA4B,UAAU,YAAY;AAClG;AAEO,MAAM,eAAe,mBAAmB;AAAA,EAC7C,UAAU;AAAA,EACV;AACF,CAAC;AAGM,MAAM,gBAAgB,aAAa;AAK1C,IAAO,iBAAQ;",
4
+ "sourcesContent": ["import { createModuleEvents } from '@open-mercato/shared/modules/events'\n\n/**\n * Auth Module Events\n *\n * Declares all events that can be emitted by the auth module.\n */\nconst events = [\n // Users\n { id: 'auth.user.created', label: 'User Created', entity: 'user', category: 'crud' },\n { id: 'auth.user.updated', label: 'User Updated', entity: 'user', category: 'crud' },\n { id: 'auth.user.deleted', label: 'User Deleted', entity: 'user', category: 'crud' },\n\n // Roles\n { id: 'auth.role.created', label: 'Role Created', entity: 'role', category: 'crud' },\n { id: 'auth.role.updated', label: 'Role Updated', entity: 'role', category: 'crud' },\n { id: 'auth.role.deleted', label: 'Role Deleted', entity: 'role', category: 'crud' },\n\n // Authentication events\n { id: 'auth.login.success', label: 'Login Successful', category: 'lifecycle' },\n { id: 'auth.login.failed', label: 'Login Failed', category: 'lifecycle' },\n // The logout and password payloads below identify the user by `id` only. They are\n // emitted with `{ persistent: true }`, so the whole payload is serialized into the\n // durable events queue, while `email` is encrypted at rest under the `auth:user`\n // encryption map \u2014 a subscriber that needs the address resolves it with\n // `findOneWithDecryption` under the tenant's own key.\n // `sessionRevoked` reports that server-side revocation ran without throwing, not that\n // a session row was removed: a session that had already expired still reports `true`.\n { id: 'auth.logout', label: 'User Logged Out', category: 'lifecycle' },\n // `changedBy` discriminates who performed the write: `self` (the account owner),\n // `admin` (another authenticated user) or `system` (an `auth.users.update` carrying no\n // auth context, or running under `ctx.systemActor`). `changedById` carries the actor id\n // whenever there is one. Password writes that bypass the command emit nothing at all \u2014\n // `mercato auth set-password` and tenant provisioning both set `passwordHash` directly.\n { id: 'auth.password.changed', label: 'Password Changed', category: 'lifecycle' },\n { id: 'auth.password.reset.requested', label: 'Password Reset Requested', category: 'lifecycle' },\n // Also emitted when an invited user sets their initial password: invitation\n // emails link to /reset/<token> and post to the same confirm endpoint, so\n // those completions arrive with no preceding `auth.password.reset.requested`.\n { id: 'auth.password.reset.completed', label: 'Password Reset Completed', category: 'lifecycle' },\n] as const\n\nexport const eventsConfig = createModuleEvents({\n moduleId: 'auth',\n events,\n})\n\n/** Type-safe event emitter for auth module */\nexport const emitAuthEvent = eventsConfig.emit\n\n/** Event IDs that can be emitted by the auth module */\nexport type AuthEventId = typeof events[number]['id']\n\nexport default eventsConfig\n"],
5
+ "mappings": "AAAA,SAAS,0BAA0B;AAOnC,MAAM,SAAS;AAAA;AAAA,EAEb,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA;AAAA,EAGnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA,EACnF,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,QAAQ,QAAQ,UAAU,OAAO;AAAA;AAAA,EAGnF,EAAE,IAAI,sBAAsB,OAAO,oBAAoB,UAAU,YAAY;AAAA,EAC7E,EAAE,IAAI,qBAAqB,OAAO,gBAAgB,UAAU,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQxE,EAAE,IAAI,eAAe,OAAO,mBAAmB,UAAU,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrE,EAAE,IAAI,yBAAyB,OAAO,oBAAoB,UAAU,YAAY;AAAA,EAChF,EAAE,IAAI,iCAAiC,OAAO,4BAA4B,UAAU,YAAY;AAAA;AAAA;AAAA;AAAA,EAIhG,EAAE,IAAI,iCAAiC,OAAO,4BAA4B,UAAU,YAAY;AAClG;AAEO,MAAM,eAAe,mBAAmB;AAAA,EAC7C,UAAU;AAAA,EACV;AACF,CAAC;AAGM,MAAM,gBAAgB,aAAa;AAK1C,IAAO,iBAAQ;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.6.8-develop.7000.1.0ae682bad1",
3
+ "version": "0.6.8-develop.7003.1.24fef49d48",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -254,16 +254,16 @@
254
254
  "zod": "^4.4.3"
255
255
  },
256
256
  "peerDependencies": {
257
- "@open-mercato/ai-assistant": "0.6.8-develop.7000.1.0ae682bad1",
258
- "@open-mercato/shared": "0.6.8-develop.7000.1.0ae682bad1",
259
- "@open-mercato/ui": "0.6.8-develop.7000.1.0ae682bad1",
257
+ "@open-mercato/ai-assistant": "0.6.8-develop.7003.1.24fef49d48",
258
+ "@open-mercato/shared": "0.6.8-develop.7003.1.24fef49d48",
259
+ "@open-mercato/ui": "0.6.8-develop.7003.1.24fef49d48",
260
260
  "react": "^19.0.0",
261
261
  "react-dom": "^19.0.0"
262
262
  },
263
263
  "devDependencies": {
264
- "@open-mercato/ai-assistant": "0.6.8-develop.7000.1.0ae682bad1",
265
- "@open-mercato/shared": "0.6.8-develop.7000.1.0ae682bad1",
266
- "@open-mercato/ui": "0.6.8-develop.7000.1.0ae682bad1",
264
+ "@open-mercato/ai-assistant": "0.6.8-develop.7003.1.24fef49d48",
265
+ "@open-mercato/shared": "0.6.8-develop.7003.1.24fef49d48",
266
+ "@open-mercato/ui": "0.6.8-develop.7003.1.24fef49d48",
267
267
  "@testing-library/dom": "^10.4.1",
268
268
  "@testing-library/jest-dom": "^7.0.0",
269
269
  "@testing-library/react": "^16.3.1",
@@ -3,6 +3,21 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
3
3
  import { AuthService } from '@open-mercato/core/modules/auth/services/authService'
4
4
  import { verifyJwt } from '@open-mercato/shared/lib/auth/jwt'
5
5
  import { buildSafeRedirectResponse } from '@open-mercato/core/modules/auth/lib/requestRedirect'
6
+ import { emitAuthEvent } from '@open-mercato/core/modules/auth/events'
7
+
8
+ type AuthTokenClaims = {
9
+ userId: string | null
10
+ sessionId: string | null
11
+ tenantId: string | null
12
+ organizationId: string | null
13
+ }
14
+
15
+ const emptyAuthTokenClaims: AuthTokenClaims = Object.freeze({
16
+ userId: null,
17
+ sessionId: null,
18
+ tenantId: null,
19
+ organizationId: null,
20
+ })
6
21
 
7
22
  function parseCookie(req: Request, name: string): string | null {
8
23
  const cookie = req.headers.get('cookie') || ''
@@ -10,34 +25,55 @@ function parseCookie(req: Request, name: string): string | null {
10
25
  return m ? decodeURIComponent(m[1]) : null
11
26
  }
12
27
 
13
- function extractSessionIdFromAuthToken(token: string | null): string | null {
14
- if (!token) return null
28
+ function readStringClaim(payload: Record<string, unknown>, key: string): string | null {
29
+ const value = payload[key]
30
+ return typeof value === 'string' && value.length > 0 ? value : null
31
+ }
32
+
33
+ function extractAuthTokenClaims(token: string | null): AuthTokenClaims {
34
+ if (!token) return emptyAuthTokenClaims
15
35
  try {
16
36
  const payload = verifyJwt(token) as Record<string, unknown> | null
17
- if (!payload) return null
18
- const sid = payload.sid
19
- return typeof sid === 'string' && sid.length > 0 ? sid : null
37
+ if (!payload) return emptyAuthTokenClaims
38
+ return {
39
+ userId: readStringClaim(payload, 'sub'),
40
+ sessionId: readStringClaim(payload, 'sid'),
41
+ tenantId: readStringClaim(payload, 'tenantId'),
42
+ organizationId: readStringClaim(payload, 'orgId'),
43
+ }
20
44
  } catch {
21
- return null
45
+ return emptyAuthTokenClaims
22
46
  }
23
47
  }
24
48
 
25
49
  export async function POST(req: Request) {
26
50
  const sessToken = parseCookie(req, 'session_token')
27
51
  const authToken = parseCookie(req, 'auth_token')
28
- const sessionId = extractSessionIdFromAuthToken(authToken)
29
- if (sessToken || sessionId) {
52
+ const claims = extractAuthTokenClaims(authToken)
53
+ let sessionRevoked = false
54
+ if (sessToken || claims.sessionId) {
30
55
  try {
31
56
  const c = await createRequestContainer()
32
57
  const auth = c.resolve<AuthService>('authService')
33
- if (sessionId) {
34
- await auth.deleteSessionById(sessionId)
58
+ if (claims.sessionId) {
59
+ await auth.deleteSessionById(claims.sessionId)
35
60
  }
36
61
  if (sessToken) {
37
62
  await auth.deleteSessionByToken(sessToken)
38
63
  }
64
+ sessionRevoked = true
39
65
  } catch {}
40
66
  }
67
+ if (claims.userId) {
68
+ void emitAuthEvent('auth.logout', {
69
+ id: claims.userId,
70
+ tenantId: claims.tenantId,
71
+ organizationId: claims.organizationId,
72
+ sessionId: claims.sessionId,
73
+ sessionRevoked,
74
+ at: new Date().toISOString(),
75
+ }, { persistent: true }).catch(() => undefined)
76
+ }
41
77
  const res = buildSafeRedirectResponse(req, '/login')
42
78
  res.cookies.set('auth_token', '', { path: '/', maxAge: 0 })
43
79
  res.cookies.set('session_token', '', { path: '/', maxAge: 0 })
@@ -11,6 +11,7 @@ import { rateLimitErrorSchema } from '@open-mercato/shared/lib/ratelimit/helpers
11
11
  import { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/config'
12
12
  import { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'
13
13
  import { createLogger } from '@open-mercato/shared/lib/logger'
14
+ import { emitAuthEvent } from '@open-mercato/core/modules/auth/events'
14
15
 
15
16
  const logger = createLogger('auth').child({ component: 'reset-confirm' })
16
17
 
@@ -33,6 +34,12 @@ export async function POST(req: Request) {
33
34
  const auth = c.resolve<AuthService>('authService')
34
35
  const user = await auth.confirmPasswordReset(parsed.data.token, parsed.data.password)
35
36
  if (!user) return NextResponse.json({ ok: false, error: 'Invalid or expired token' }, { status: 400 })
37
+ void emitAuthEvent('auth.password.reset.completed', {
38
+ id: String(user.id),
39
+ tenantId: user.tenantId ? String(user.tenantId) : null,
40
+ organizationId: user.organizationId ? String(user.organizationId) : null,
41
+ at: new Date().toISOString(),
42
+ }, { persistent: true }).catch(() => undefined)
36
43
  try {
37
44
  const tenantId = user.tenantId ? String(user.tenantId) : null
38
45
  if (tenantId) {
@@ -15,6 +15,7 @@ import { readEndpointRateLimitConfig } from '@open-mercato/shared/lib/ratelimit/
15
15
  import { checkAuthRateLimit } from '@open-mercato/core/modules/auth/lib/rateLimitCheck'
16
16
  import { mapSecurityEmailUrlError, toSecurityEmailUrl } from '@open-mercato/shared/lib/url'
17
17
  import { createLogger } from '@open-mercato/shared/lib/logger'
18
+ import { emitAuthEvent } from '@open-mercato/core/modules/auth/events'
18
19
 
19
20
  const logger = createLogger('auth').child({ component: 'reset' })
20
21
 
@@ -57,6 +58,12 @@ export async function POST(req: Request) {
57
58
  if (!resReq) return NextResponse.json({ ok: true })
58
59
  const { user, token } = resReq
59
60
  const resetUrl = resetUrlTemplate.replace('__token__', token)
61
+ void emitAuthEvent('auth.password.reset.requested', {
62
+ id: String(user.id),
63
+ tenantId: user.tenantId ? String(user.tenantId) : null,
64
+ organizationId: user.organizationId ? String(user.organizationId) : null,
65
+ at: new Date().toISOString(),
66
+ }, { persistent: true }).catch(() => undefined)
60
67
 
61
68
  const { translate } = await resolveTranslations()
62
69
  const subject = translate('auth.email.resetPassword.subject', 'Reset your password')
@@ -35,6 +35,7 @@ import { buildNotificationFromType } from '@open-mercato/core/modules/notificati
35
35
  import { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'
36
36
  import notificationTypes from '@open-mercato/core/modules/auth/notifications'
37
37
  import { buildPasswordSchema } from '@open-mercato/shared/lib/auth/passwordPolicy'
38
+ import { emitAuthEvent } from '@open-mercato/core/modules/auth/events'
38
39
  import { sendEmail } from '@open-mercato/shared/lib/email/send'
39
40
  import InviteUserEmail from '@open-mercato/core/modules/auth/emails/InviteUserEmail'
40
41
  import { INVITE_TOKEN_TTL_MS } from '@open-mercato/core/modules/auth/lib/inviteToken'
@@ -724,6 +725,27 @@ const updateUserCommand: CommandHandler<Record<string, unknown>, User> = {
724
725
  indexer: userCrudIndexer,
725
726
  })
726
727
 
728
+ if (hashed) {
729
+ const actorId = ctx.auth?.sub ? String(ctx.auth.sub) : null
730
+ // `system` covers a command invocation with no auth context and one running under
731
+ // `ctx.systemActor`. Without it those writes would be indistinguishable from an
732
+ // administrator setting someone else's password, which is exactly the case security
733
+ // alerting escalates on. Password writes that never reach this command — `mercato
734
+ // auth set-password`, tenant provisioning — set `passwordHash` directly and emit
735
+ // nothing, so a subscriber cannot treat this event as covering every credential change.
736
+ const changedBy = ctx.systemActor === true || !actorId
737
+ ? 'system'
738
+ : actorId === identifiers.id ? 'self' : 'admin'
739
+ void emitAuthEvent('auth.password.changed', {
740
+ id: identifiers.id,
741
+ tenantId: identifiers.tenantId,
742
+ organizationId: identifiers.organizationId,
743
+ changedBy,
744
+ changedById: actorId,
745
+ at: new Date().toISOString(),
746
+ }, { persistent: true }).catch(() => undefined)
747
+ }
748
+
727
749
  if (Array.isArray(parsed.roles) && rolesBefore) {
728
750
  const rolesAfter = await loadUserRoleNames(em, String(user.id))
729
751
  const { assigned, revoked } = diffRoleChanges(rolesBefore, rolesAfter)
@@ -19,9 +19,24 @@ const events = [
19
19
  // Authentication events
20
20
  { id: 'auth.login.success', label: 'Login Successful', category: 'lifecycle' },
21
21
  { id: 'auth.login.failed', label: 'Login Failed', category: 'lifecycle' },
22
+ // The logout and password payloads below identify the user by `id` only. They are
23
+ // emitted with `{ persistent: true }`, so the whole payload is serialized into the
24
+ // durable events queue, while `email` is encrypted at rest under the `auth:user`
25
+ // encryption map — a subscriber that needs the address resolves it with
26
+ // `findOneWithDecryption` under the tenant's own key.
27
+ // `sessionRevoked` reports that server-side revocation ran without throwing, not that
28
+ // a session row was removed: a session that had already expired still reports `true`.
22
29
  { id: 'auth.logout', label: 'User Logged Out', category: 'lifecycle' },
30
+ // `changedBy` discriminates who performed the write: `self` (the account owner),
31
+ // `admin` (another authenticated user) or `system` (an `auth.users.update` carrying no
32
+ // auth context, or running under `ctx.systemActor`). `changedById` carries the actor id
33
+ // whenever there is one. Password writes that bypass the command emit nothing at all —
34
+ // `mercato auth set-password` and tenant provisioning both set `passwordHash` directly.
23
35
  { id: 'auth.password.changed', label: 'Password Changed', category: 'lifecycle' },
24
36
  { id: 'auth.password.reset.requested', label: 'Password Reset Requested', category: 'lifecycle' },
37
+ // Also emitted when an invited user sets their initial password: invitation
38
+ // emails link to /reset/<token> and post to the same confirm endpoint, so
39
+ // those completions arrive with no preceding `auth.password.reset.requested`.
25
40
  { id: 'auth.password.reset.completed', label: 'Password Reset Completed', category: 'lifecycle' },
26
41
  ] as const
27
42