@open-mercato/core 0.6.8-develop.7023.1.a1960eb208 → 0.6.8-develop.7026.1.23445b3f3e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/auth/api/roles/acl/route.js +28 -33
  3. package/dist/modules/auth/api/roles/acl/route.js.map +2 -2
  4. package/dist/modules/auth/api/users/acl/route.js +96 -51
  5. package/dist/modules/auth/api/users/acl/route.js.map +2 -2
  6. package/dist/modules/auth/commands/acl.js +254 -0
  7. package/dist/modules/auth/commands/acl.js.map +7 -0
  8. package/dist/modules/auth/lib/grantChecks.js.map +2 -2
  9. package/dist/modules/communication_channels/commands/ingest-inbound-message.js +9 -1
  10. package/dist/modules/communication_channels/commands/ingest-inbound-message.js.map +2 -2
  11. package/dist/modules/inbox_ops/lib/htmlToPlainText.js +1 -12
  12. package/dist/modules/inbox_ops/lib/htmlToPlainText.js.map +2 -2
  13. package/dist/modules/messages/api/[id]/route.js +3 -0
  14. package/dist/modules/messages/api/[id]/route.js.map +2 -2
  15. package/dist/modules/messages/api/openapi.js +3 -0
  16. package/dist/modules/messages/api/openapi.js.map +2 -2
  17. package/dist/modules/messages/components/MessagesInboxPageClient.js +3 -13
  18. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  19. package/dist/modules/messages/components/inboxFilters.js +15 -0
  20. package/dist/modules/messages/components/inboxFilters.js.map +2 -2
  21. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.js +11 -1
  22. package/dist/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.js.map +2 -2
  23. package/dist/modules/messages/components/message-detail/panels/MessageHeader.js +3 -1
  24. package/dist/modules/messages/components/message-detail/panels/MessageHeader.js.map +2 -2
  25. package/dist/modules/messages/components/message-detail/panels/thread-panel.js +2 -1
  26. package/dist/modules/messages/components/message-detail/panels/thread-panel.js.map +2 -2
  27. package/dist/modules/messages/components/messageListLabels.js +14 -2
  28. package/dist/modules/messages/components/messageListLabels.js.map +2 -2
  29. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +64 -14
  30. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  31. package/package.json +7 -9
  32. package/src/modules/auth/api/roles/acl/route.ts +42 -39
  33. package/src/modules/auth/api/users/acl/route.ts +177 -53
  34. package/src/modules/auth/commands/acl.ts +495 -0
  35. package/src/modules/auth/i18n/de.json +2 -0
  36. package/src/modules/auth/i18n/en.json +2 -0
  37. package/src/modules/auth/i18n/es.json +2 -0
  38. package/src/modules/auth/i18n/ko.json +2 -0
  39. package/src/modules/auth/i18n/pl.json +2 -0
  40. package/src/modules/auth/lib/grantChecks.ts +6 -0
  41. package/src/modules/communication_channels/commands/ingest-inbound-message.ts +33 -1
  42. package/src/modules/inbox_ops/lib/htmlToPlainText.ts +1 -17
  43. package/src/modules/messages/api/[id]/route.ts +3 -0
  44. package/src/modules/messages/api/openapi.ts +3 -0
  45. package/src/modules/messages/components/MessagesInboxPageClient.tsx +5 -16
  46. package/src/modules/messages/components/inboxFilters.ts +36 -0
  47. package/src/modules/messages/components/message-detail/hooks/useMessageDetailsConversation.ts +14 -1
  48. package/src/modules/messages/components/message-detail/panels/MessageHeader.tsx +3 -1
  49. package/src/modules/messages/components/message-detail/panels/thread-panel.tsx +2 -1
  50. package/src/modules/messages/components/message-detail/types.ts +3 -0
  51. package/src/modules/messages/components/messageListLabels.ts +52 -3
  52. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +101 -14
  53. package/src/modules/sales/i18n/de.json +2 -0
  54. package/src/modules/sales/i18n/en.json +2 -0
  55. package/src/modules/sales/i18n/es.json +2 -0
  56. package/src/modules/sales/i18n/ko.json +2 -0
  57. package/src/modules/sales/i18n/pl.json +2 -0
@@ -1,4 +1,4 @@
1
- [build:core] found 4323 entry points
1
+ [build:core] found 4325 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 218 entry points
4
4
  [build:core:generated] built successfully
@@ -5,7 +5,6 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { logCrudAccess } from "@open-mercato/shared/lib/crud/factory";
6
6
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
7
  import { enforceCommandOptimisticLockWithGuards } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
8
- import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
9
8
  import { RoleAcl, Role } from "@open-mercato/core/modules/auth/data/entities";
10
9
  import { resolveIsSuperAdmin } from "@open-mercato/core/modules/auth/lib/tenantAccess";
11
10
  import {
@@ -13,6 +12,9 @@ import {
13
12
  assertActorCanModifySuperAdminRoleTarget,
14
13
  normalizeGrantFeatureList
15
14
  } from "@open-mercato/core/modules/auth/lib/grantChecks";
15
+ import {
16
+ AUTH_ROLE_ACL_UPDATE_COMMAND_ID
17
+ } from "@open-mercato/core/modules/auth/commands/acl";
16
18
  const getSchema = z.object({
17
19
  roleId: z.string().uuid(),
18
20
  tenantId: z.string().uuid().optional()
@@ -149,7 +151,7 @@ async function PUT(req) {
149
151
  throw err;
150
152
  }
151
153
  }
152
- let acl = await em.findOne(RoleAcl, { role, tenantId: targetTenantId });
154
+ const acl = await em.findOne(RoleAcl, { role, tenantId: targetTenantId });
153
155
  if (acl) {
154
156
  try {
155
157
  await enforceCommandOptimisticLockWithGuards(container, {
@@ -162,17 +164,10 @@ async function PUT(req) {
162
164
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
163
165
  throw err;
164
166
  }
165
- } else {
166
- acl = em.create(RoleAcl, {
167
- role,
168
- tenantId: targetTenantId,
169
- createdAt: /* @__PURE__ */ new Date(),
170
- isSuperAdmin: false
171
- });
172
167
  }
173
- const existingIsSuperAdmin = !!acl.isSuperAdmin;
174
- const existingFeatures = normalizeGrantFeatureList(acl.featuresJson);
175
- const existingOrganizations = normalizeOrganizations(acl.organizationsJson);
168
+ const existingIsSuperAdmin = !!acl?.isSuperAdmin;
169
+ const existingFeatures = normalizeGrantFeatureList(acl?.featuresJson);
170
+ const existingOrganizations = normalizeOrganizations(acl?.organizationsJson);
176
171
  const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? existingIsSuperAdmin;
177
172
  const requestedFeatures = parsed.data.features === void 0 ? existingFeatures : normalizeGrantFeatureList(parsed.data.features);
178
173
  const requestedOrganizations = parsed.data.organizations === void 0 ? existingOrganizations : normalizeOrganizations(parsed.data.organizations);
@@ -191,27 +186,27 @@ async function PUT(req) {
191
186
  if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
192
187
  throw err;
193
188
  }
194
- const aclToPersist = acl;
195
- await withAtomicFlush(
196
- em,
197
- [
198
- () => {
199
- aclToPersist.organizationsJson = requestedOrganizations;
200
- aclToPersist.isSuperAdmin = requestedIsSuperAdmin;
201
- aclToPersist.featuresJson = requestedFeatures;
202
- em.persist(aclToPersist);
203
- }
204
- ],
205
- { transaction: true }
206
- );
207
- if (targetTenantId) {
208
- await rbacService.invalidateTenantCache(targetTenantId);
209
- try {
210
- const cache = container.resolve("cache");
211
- if (cache?.deleteByTags) await cache.deleteByTags([`rbac:tenant:${targetTenantId}`]);
212
- } catch {
213
- }
214
- }
189
+ const commandBus = container.resolve("commandBus");
190
+ const isForeignTenant = targetTenantId !== (auth.tenantId ?? null);
191
+ const actorOrgId = isForeignTenant ? null : auth.orgId ?? null;
192
+ const commandCtx = {
193
+ container,
194
+ auth: isForeignTenant ? { ...auth, orgId: null } : auth,
195
+ organizationScope: null,
196
+ selectedOrganizationId: actorOrgId,
197
+ organizationIds: actorOrgId ? [actorOrgId] : null,
198
+ request: req
199
+ };
200
+ await commandBus.execute(AUTH_ROLE_ACL_UPDATE_COMMAND_ID, {
201
+ input: {
202
+ roleId: String(role.id),
203
+ tenantId: targetTenantId,
204
+ isSuperAdmin: requestedIsSuperAdmin,
205
+ features: requestedFeatures,
206
+ organizations: requestedOrganizations
207
+ },
208
+ ctx: commandCtx
209
+ });
215
210
  return NextResponse.json({
216
211
  ok: true,
217
212
  sanitized: false
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/auth/api/roles/acl/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { logCrudAccess } from '@open-mercato/shared/lib/crud/factory'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { RoleAcl, Role } from '@open-mercato/core/modules/auth/data/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n assertActorCanGrantAcl,\n assertActorCanModifySuperAdminRoleTarget,\n normalizeGrantFeatureList,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\n\ntype TaggableCache = { deleteByTags?: (tags: string[]) => Promise<void> | void }\n\nconst getSchema = z.object({\n roleId: z.string().uuid(),\n tenantId: z.string().uuid().optional(),\n})\nconst putSchema = z.object({\n roleId: z.string().uuid(),\n isSuperAdmin: z.boolean().optional(),\n features: z.array(z.string()).optional(),\n organizations: z.array(z.string()).nullable().optional(),\n tenantId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\nconst roleAclResponseSchema = z.object({\n isSuperAdmin: z.boolean(),\n features: z.array(z.string()),\n organizations: z.array(z.string()).nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst roleAclUpdateResponseSchema = z.object({\n ok: z.literal(true),\n sanitized: z.boolean(),\n})\n\nconst roleAclErrorSchema = z.object({ error: z.string() })\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsed = getSchema.safeParse({\n roleId: url.searchParams.get('roleId'),\n tenantId: url.searchParams.get('tenantId') || undefined,\n })\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const isSuperAdmin = await resolveIsSuperAdmin({ auth, container })\n const em = container.resolve('em') as EntityManager\n const authTenantId = auth.tenantId ?? null\n const roleFilter: Record<string, unknown> = { id: parsed.data.roleId }\n if (!isSuperAdmin && authTenantId) {\n roleFilter.$or = [{ tenantId: authTenantId }, { tenantId: null }]\n }\n const role = await em.findOne(Role, roleFilter)\n if (!role) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n const roleTenantId = role?.tenantId ? String(role.tenantId) : null\n\n let tenantScope = parsed.data.tenantId ?? roleTenantId ?? authTenantId ?? null\n if (parsed.data.tenantId && parsed.data.tenantId !== tenantScope) {\n if (isSuperAdmin || parsed.data.tenantId === authTenantId) tenantScope = parsed.data.tenantId\n else return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n if (!tenantScope && !isSuperAdmin) tenantScope = authTenantId ?? null\n\n if (!isSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminRoleTarget({\n em,\n rbacService: container.resolve('rbacService') as RbacService,\n actorUserId: auth.sub,\n tenantId: tenantScope,\n organizationId: auth.orgId ?? null,\n targetRoleId: parsed.data.roleId,\n actorIsSuperAdmin: false,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const acl = tenantScope\n ? await em.findOne(RoleAcl, { role, tenantId: tenantScope })\n : null\n const response = acl\n ? {\n isSuperAdmin: !!acl.isSuperAdmin,\n features: Array.isArray(acl.featuresJson) ? acl.featuresJson : [],\n organizations: Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null,\n updatedAt: acl.updatedAt instanceof Date ? acl.updatedAt.toISOString() : null,\n }\n : { isSuperAdmin: false, features: [], organizations: null, updatedAt: null }\n\n await logCrudAccess({\n container,\n auth,\n request: req,\n items: [{ id: parsed.data.roleId, ...response }],\n idField: 'id',\n resourceKind: 'auth.role_acl',\n organizationId: auth.orgId ?? null,\n tenantId: tenantScope,\n query: { roleId: parsed.data.roleId, tenantId: tenantScope },\n accessType: 'read:item',\n })\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const body = await req.json().catch(() => ({}))\n const parsed = putSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const isSuperAdmin = await resolveIsSuperAdmin({ auth, container })\n const rbacService = container.resolve('rbacService') as RbacService\n const authTenantId = auth.tenantId ?? null\n const putRoleFilter: Record<string, unknown> = { id: parsed.data.roleId }\n if (!isSuperAdmin && authTenantId) {\n putRoleFilter.$or = [{ tenantId: authTenantId }, { tenantId: null }]\n }\n const role = await em.findOne(Role, putRoleFilter)\n if (!role) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n\n const roleTenantId = role?.tenantId ? String(role.tenantId) : null\n\n let targetTenantId = parsed.data.tenantId ?? roleTenantId ?? authTenantId ?? null\n if (parsed.data.tenantId && parsed.data.tenantId !== targetTenantId) {\n if (isSuperAdmin || parsed.data.tenantId === authTenantId) {\n targetTenantId = parsed.data.tenantId\n } else {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n }\n if (!targetTenantId && !isSuperAdmin) targetTenantId = authTenantId ?? null\n if (!targetTenantId) return NextResponse.json({ error: 'Tenant required' }, { status: 400 })\n\n if (!isSuperAdmin && targetTenantId !== authTenantId) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n if (!isSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminRoleTarget({\n em,\n rbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n targetRoleId: parsed.data.roleId,\n actorIsSuperAdmin: false,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n let acl = await em.findOne(RoleAcl, { role, tenantId: targetTenantId })\n // Optimistic lock: refuse a stale ACL overwrite so two admins editing the same\n // role's features in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 when the client sends no expected-version header\n // it is a no-op. Skipped when the ACL row does not exist yet (first grant has\n // no prior version to conflict with).\n if (acl) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'auth.role_acl',\n resourceId: acl.id,\n current: acl.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n } else {\n acl = em.create(RoleAcl, {\n role,\n tenantId: targetTenantId,\n createdAt: new Date(),\n isSuperAdmin: false,\n })\n }\n\n const existingIsSuperAdmin = !!acl.isSuperAdmin\n const existingFeatures = normalizeGrantFeatureList(acl.featuresJson)\n const existingOrganizations = normalizeOrganizations(acl.organizationsJson)\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? existingIsSuperAdmin\n const requestedFeatures = parsed.data.features === undefined\n ? existingFeatures\n : normalizeGrantFeatureList(parsed.data.features)\n const requestedOrganizations = parsed.data.organizations === undefined\n ? existingOrganizations\n : normalizeOrganizations(parsed.data.organizations)\n\n try {\n await assertActorCanGrantAcl({\n em,\n rbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n isSuperAdmin: requestedIsSuperAdmin,\n features: requestedFeatures,\n organizations: requestedOrganizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Persist the ACL mutation inside a transaction so the role-permission write\n // commits atomically (proper ACL-edit transaction handling).\n const aclToPersist = acl\n await withAtomicFlush(\n em,\n [\n () => {\n aclToPersist.organizationsJson = requestedOrganizations\n aclToPersist.isSuperAdmin = requestedIsSuperAdmin\n aclToPersist.featuresJson = requestedFeatures\n em.persist(aclToPersist)\n },\n ],\n { transaction: true },\n )\n\n // Invalidate cache for all users in this tenant since role ACL changed\n if (targetTenantId) {\n await rbacService.invalidateTenantCache(targetTenantId)\n // Sidebar nav caches depend on RBAC; invalidate tenant scope nav caches\n try {\n const cache = container.resolve('cache') as TaggableCache | undefined\n if (cache?.deleteByTags) await cache.deleteByTags([`rbac:tenant:${targetTenantId}`])\n } catch {}\n }\n \n return NextResponse.json({\n ok: true,\n sanitized: false,\n })\n}\n\nfunction normalizeOrganizations(organizations: unknown): string[] | null {\n if (!Array.isArray(organizations)) return null\n return normalizeGrantFeatureList(organizations)\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Role ACL management',\n methods: {\n GET: {\n summary: 'Fetch role ACL',\n description: 'Returns the feature and organization assignments associated with a role within the current tenant.',\n query: getSchema,\n responses: [\n { status: 200, description: 'Role ACL entry', schema: roleAclResponseSchema },\n { status: 400, description: 'Invalid role id', schema: roleAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: roleAclErrorSchema },\n { status: 404, description: 'Role not found', schema: roleAclErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update role ACL',\n description: 'Replaces the feature list, super admin flag, and optional organization assignments for a role.',\n requestBody: {\n contentType: 'application/json',\n schema: putSchema,\n },\n responses: [\n { status: 200, description: 'Role ACL updated', schema: roleAclUpdateResponseSchema },\n { status: 400, description: 'Invalid payload', schema: roleAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: roleAclErrorSchema },\n { status: 403, description: 'Insufficient privileges to modify ACL', schema: roleAclErrorSchema },\n { status: 404, description: 'Role not found', schema: roleAclErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAChC,SAAS,SAAS,YAAY;AAE9B,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAIP,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AACD,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,cAAc,EAAE,QAAQ,EAAE,SAAS;AAAA,EACnC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACvC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS;AAAA,EACvD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AAAA,EAC/D,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AACjE;AAEA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,cAAc,EAAE,QAAQ;AAAA,EACxB,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EAC5B,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC5C,WAAW,EAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAED,MAAM,8BA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AAK;AAAA,IACvB,IAAI;AAAA,IACJ,WAAW;AAAA,EACb,CAAC;AACH;AAEA,SAAS,uBAAuB,eAAyC;AACvE,MAAI,CAAC,MAAM,QAAQ,aAAa,EAAG,QAAO;AAC1C,SAAO,0BAA0B,aAAa;AAChD;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,sBAAsB;AAAA,QAC5E,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,mBAAmB;AAAA,MAC3E;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,4BAA4B;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,mBAAmB;AAAA,QAChG,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,mBAAmB;AAAA,MAC3E;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { logCrudAccess } from '@open-mercato/shared/lib/crud/factory'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { RoleAcl, Role } from '@open-mercato/core/modules/auth/data/entities'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { resolveIsSuperAdmin } from '@open-mercato/core/modules/auth/lib/tenantAccess'\nimport { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport {\n assertActorCanGrantAcl,\n assertActorCanModifySuperAdminRoleTarget,\n normalizeGrantFeatureList,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport {\n AUTH_ROLE_ACL_UPDATE_COMMAND_ID,\n type AclUpdateResult,\n type RoleAclUpdateInput,\n} from '@open-mercato/core/modules/auth/commands/acl'\n\nconst getSchema = z.object({\n roleId: z.string().uuid(),\n tenantId: z.string().uuid().optional(),\n})\nconst putSchema = z.object({\n roleId: z.string().uuid(),\n isSuperAdmin: z.boolean().optional(),\n features: z.array(z.string()).optional(),\n organizations: z.array(z.string()).nullable().optional(),\n tenantId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\nconst roleAclResponseSchema = z.object({\n isSuperAdmin: z.boolean(),\n features: z.array(z.string()),\n organizations: z.array(z.string()).nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst roleAclUpdateResponseSchema = z.object({\n ok: z.literal(true),\n sanitized: z.boolean(),\n})\n\nconst roleAclErrorSchema = z.object({ error: z.string() })\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsed = getSchema.safeParse({\n roleId: url.searchParams.get('roleId'),\n tenantId: url.searchParams.get('tenantId') || undefined,\n })\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const isSuperAdmin = await resolveIsSuperAdmin({ auth, container })\n const em = container.resolve('em') as EntityManager\n const authTenantId = auth.tenantId ?? null\n const roleFilter: Record<string, unknown> = { id: parsed.data.roleId }\n if (!isSuperAdmin && authTenantId) {\n roleFilter.$or = [{ tenantId: authTenantId }, { tenantId: null }]\n }\n const role = await em.findOne(Role, roleFilter)\n if (!role) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n const roleTenantId = role?.tenantId ? String(role.tenantId) : null\n\n let tenantScope = parsed.data.tenantId ?? roleTenantId ?? authTenantId ?? null\n if (parsed.data.tenantId && parsed.data.tenantId !== tenantScope) {\n if (isSuperAdmin || parsed.data.tenantId === authTenantId) tenantScope = parsed.data.tenantId\n else return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n if (!tenantScope && !isSuperAdmin) tenantScope = authTenantId ?? null\n\n if (!isSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminRoleTarget({\n em,\n rbacService: container.resolve('rbacService') as RbacService,\n actorUserId: auth.sub,\n tenantId: tenantScope,\n organizationId: auth.orgId ?? null,\n targetRoleId: parsed.data.roleId,\n actorIsSuperAdmin: false,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const acl = tenantScope\n ? await em.findOne(RoleAcl, { role, tenantId: tenantScope })\n : null\n const response = acl\n ? {\n isSuperAdmin: !!acl.isSuperAdmin,\n features: Array.isArray(acl.featuresJson) ? acl.featuresJson : [],\n organizations: Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null,\n updatedAt: acl.updatedAt instanceof Date ? acl.updatedAt.toISOString() : null,\n }\n : { isSuperAdmin: false, features: [], organizations: null, updatedAt: null }\n\n await logCrudAccess({\n container,\n auth,\n request: req,\n items: [{ id: parsed.data.roleId, ...response }],\n idField: 'id',\n resourceKind: 'auth.role_acl',\n organizationId: auth.orgId ?? null,\n tenantId: tenantScope,\n query: { roleId: parsed.data.roleId, tenantId: tenantScope },\n accessType: 'read:item',\n })\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const body = await req.json().catch(() => ({}))\n const parsed = putSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as EntityManager\n const isSuperAdmin = await resolveIsSuperAdmin({ auth, container })\n const rbacService = container.resolve('rbacService') as RbacService\n const authTenantId = auth.tenantId ?? null\n const putRoleFilter: Record<string, unknown> = { id: parsed.data.roleId }\n if (!isSuperAdmin && authTenantId) {\n putRoleFilter.$or = [{ tenantId: authTenantId }, { tenantId: null }]\n }\n const role = await em.findOne(Role, putRoleFilter)\n if (!role) return NextResponse.json({ error: 'Not found' }, { status: 404 })\n\n const roleTenantId = role?.tenantId ? String(role.tenantId) : null\n\n let targetTenantId = parsed.data.tenantId ?? roleTenantId ?? authTenantId ?? null\n if (parsed.data.tenantId && parsed.data.tenantId !== targetTenantId) {\n if (isSuperAdmin || parsed.data.tenantId === authTenantId) {\n targetTenantId = parsed.data.tenantId\n } else {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n }\n if (!targetTenantId && !isSuperAdmin) targetTenantId = authTenantId ?? null\n if (!targetTenantId) return NextResponse.json({ error: 'Tenant required' }, { status: 400 })\n\n if (!isSuperAdmin && targetTenantId !== authTenantId) {\n return NextResponse.json({ error: 'Forbidden' }, { status: 403 })\n }\n\n if (!isSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminRoleTarget({\n em,\n rbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n targetRoleId: parsed.data.roleId,\n actorIsSuperAdmin: false,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const acl = await em.findOne(RoleAcl, { role, tenantId: targetTenantId })\n // Optimistic lock: refuse a stale ACL overwrite so two admins editing the same\n // role's features in parallel cannot silently clobber each other (#2055). The\n // check is strictly additive \u2014 when the client sends no expected-version header\n // it is a no-op. Skipped when the ACL row does not exist yet (first grant has\n // no prior version to conflict with).\n if (acl) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'auth.role_acl',\n resourceId: acl.id,\n current: acl.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const existingIsSuperAdmin = !!acl?.isSuperAdmin\n const existingFeatures = normalizeGrantFeatureList(acl?.featuresJson)\n const existingOrganizations = normalizeOrganizations(acl?.organizationsJson)\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? existingIsSuperAdmin\n const requestedFeatures = parsed.data.features === undefined\n ? existingFeatures\n : normalizeGrantFeatureList(parsed.data.features)\n const requestedOrganizations = parsed.data.organizations === undefined\n ? existingOrganizations\n : normalizeOrganizations(parsed.data.organizations)\n\n try {\n await assertActorCanGrantAcl({\n em,\n rbacService,\n actorUserId: auth.sub,\n tenantId: targetTenantId,\n organizationId: auth.orgId ?? null,\n isSuperAdmin: requestedIsSuperAdmin,\n features: requestedFeatures,\n organizations: requestedOrganizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // Route the write through the command bus so the permission change lands in\n // the action log. The command owns the transactional write and the RBAC cache\n // invalidation that used to live here.\n const commandBus = container.resolve('commandBus') as CommandBus\n // A super admin may edit a role in another tenant. The actor's organization\n // belongs to *their* tenant, and the command bus resolves the log row's\n // organization as `metadata.organizationId ?? ctx.selectedOrganizationId ??\n // ctx.auth.orgId` \u2014 a `??` chain, so a handler cannot express \"explicitly no\n // organization\" on its own. Strip the organization from the context instead,\n // otherwise the entry is stamped (target tenant, actor's foreign organization)\n // and `ActionLogService` \u2014 which filters organization with strict equality \u2014\n // can never surface it for anyone.\n const isForeignTenant = targetTenantId !== (auth.tenantId ?? null)\n const actorOrgId = isForeignTenant ? null : auth.orgId ?? null\n const commandCtx: CommandRuntimeContext = {\n container,\n auth: isForeignTenant ? { ...auth, orgId: null } : auth,\n organizationScope: null,\n selectedOrganizationId: actorOrgId,\n organizationIds: actorOrgId ? [actorOrgId] : null,\n request: req,\n }\n await commandBus.execute<RoleAclUpdateInput, AclUpdateResult>(AUTH_ROLE_ACL_UPDATE_COMMAND_ID, {\n input: {\n roleId: String(role.id),\n tenantId: targetTenantId,\n isSuperAdmin: requestedIsSuperAdmin,\n features: requestedFeatures,\n organizations: requestedOrganizations,\n },\n ctx: commandCtx,\n })\n\n return NextResponse.json({\n ok: true,\n sanitized: false,\n })\n}\n\nfunction normalizeOrganizations(organizations: unknown): string[] | null {\n if (!Array.isArray(organizations)) return null\n return normalizeGrantFeatureList(organizations)\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Role ACL management',\n methods: {\n GET: {\n summary: 'Fetch role ACL',\n description: 'Returns the feature and organization assignments associated with a role within the current tenant.',\n query: getSchema,\n responses: [\n { status: 200, description: 'Role ACL entry', schema: roleAclResponseSchema },\n { status: 400, description: 'Invalid role id', schema: roleAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: roleAclErrorSchema },\n { status: 404, description: 'Role not found', schema: roleAclErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update role ACL',\n description: 'Replaces the feature list, super admin flag, and optional organization assignments for a role.',\n requestBody: {\n contentType: 'application/json',\n schema: putSchema,\n },\n responses: [\n { status: 200, description: 'Role ACL updated', schema: roleAclUpdateResponseSchema },\n { status: 400, description: 'Invalid payload', schema: roleAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: roleAclErrorSchema },\n { status: 403, description: 'Insufficient privileges to modify ACL', schema: roleAclErrorSchema },\n { status: 404, description: 'Role not found', schema: roleAclErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,8CAA8C;AAEvD,SAAS,SAAS,YAAY;AAE9B,SAAS,2BAA2B;AAEpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAGK;AAEP,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AACD,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,cAAc,EAAE,QAAQ,EAAE,SAAS;AAAA,EACnC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACvC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS;AAAA,EACvD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AAAA,EAC/D,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;AACjE;AAEA,MAAM,wBAAwB,EAAE,OAAO;AAAA,EACrC,cAAc,EAAE,QAAQ;AAAA,EACxB,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EAC5B,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EAC5C,WAAW,EAAE,OAAO,EAAE,SAAS;AACj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AAAA,IACJ,WAAW;AAAA,EACb,CAAC;AACH;AAEA,SAAS,uBAAuB,eAAyC;AACvE,MAAI,CAAC,MAAM,QAAQ,aAAa,EAAG,QAAO;AAC1C,SAAO,0BAA0B,aAAa;AAChD;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,sBAAsB;AAAA,QAC5E,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,mBAAmB;AAAA,MAC3E;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,4BAA4B;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,mBAAmB;AAAA,QAChG,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,mBAAmB;AAAA,MAC3E;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -5,21 +5,28 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
5
  import { logCrudAccess } from "@open-mercato/shared/lib/crud/factory";
6
6
  import { forbidden, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
7
7
  import { enforceCommandOptimisticLockWithGuards } from "@open-mercato/shared/lib/crud/optimistic-lock-command";
8
- import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
9
- import { UserAcl } from "@open-mercato/core/modules/auth/data/entities";
8
+ import { User, UserAcl } from "@open-mercato/core/modules/auth/data/entities";
10
9
  import {
11
10
  assertActorCanAccessUserTarget,
12
11
  assertActorCanGrantAcl,
13
12
  assertActorCanModifySuperAdminUserTarget,
14
13
  normalizeGrantFeatureList
15
14
  } from "@open-mercato/core/modules/auth/lib/grantChecks";
15
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
16
16
  import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
17
- const getSchema = z.object({ userId: z.string().uuid() });
17
+ import {
18
+ AUTH_USER_ACL_UPDATE_COMMAND_ID
19
+ } from "@open-mercato/core/modules/auth/commands/acl";
20
+ const getSchema = z.object({
21
+ userId: z.string().uuid(),
22
+ tenantId: z.string().uuid().optional()
23
+ });
18
24
  const putSchema = z.object({
19
25
  userId: z.string().uuid(),
20
26
  isSuperAdmin: z.boolean().optional(),
21
27
  features: z.array(z.string()).optional(),
22
- organizations: z.array(z.string()).nullable().optional()
28
+ organizations: z.array(z.string()).nullable().optional(),
29
+ tenantId: z.string().uuid().optional()
23
30
  });
24
31
  const metadata = {
25
32
  GET: { requireAuth: true, requireFeatures: ["auth.acl.manage"] },
@@ -37,23 +44,54 @@ const userAclUpdateResponseSchema = z.object({
37
44
  sanitized: z.boolean()
38
45
  });
39
46
  const userAclErrorSchema = z.object({ error: z.string() });
47
+ async function resolveAclTenantId(args) {
48
+ const authTenantId = args.auth.tenantId ?? null;
49
+ if (args.requestedTenantId && args.requestedTenantId !== authTenantId && !args.actorIsSuperAdmin) {
50
+ return { error: NextResponse.json({ error: "Forbidden" }, { status: 403 }) };
51
+ }
52
+ const known = args.requestedTenantId ?? authTenantId;
53
+ if (known) return { tenantId: known };
54
+ if (!args.actorIsSuperAdmin) return { tenantId: null };
55
+ const targetUser = await findOneWithDecryption(
56
+ args.em,
57
+ User,
58
+ { id: args.userId },
59
+ {},
60
+ { tenantId: null, organizationId: args.auth.orgId ?? null }
61
+ );
62
+ return { tenantId: targetUser?.tenantId ? String(targetUser.tenantId) : null };
63
+ }
40
64
  async function GET(req) {
41
65
  const auth = await getAuthFromRequest(req);
42
66
  if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
43
67
  const url = new URL(req.url);
44
- const parsed = getSchema.safeParse({ userId: url.searchParams.get("userId") });
68
+ const parsed = getSchema.safeParse({
69
+ userId: url.searchParams.get("userId"),
70
+ tenantId: url.searchParams.get("tenantId") || void 0
71
+ });
45
72
  if (!parsed.success) return NextResponse.json({ error: "Invalid input" }, { status: 400 });
46
73
  const container = await createRequestContainer();
47
74
  const em = container.resolve("em");
48
75
  const rbacService = container.resolve("rbacService");
49
- const actorAcl = auth.sub ? await rbacService.loadAcl(auth.sub, { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null }) : null;
50
- if (!actorAcl?.isSuperAdmin && auth.sub) {
76
+ const actorTenantId = auth.tenantId ?? null;
77
+ const actorAcl = auth.sub ? await rbacService.loadAcl(auth.sub, { tenantId: actorTenantId, organizationId: auth.orgId ?? null }) : null;
78
+ const actorIsSuperAdmin = !!actorAcl?.isSuperAdmin;
79
+ const resolution = await resolveAclTenantId({
80
+ em,
81
+ auth,
82
+ actorIsSuperAdmin,
83
+ userId: parsed.data.userId,
84
+ requestedTenantId: parsed.data.tenantId
85
+ });
86
+ if ("error" in resolution) return resolution.error;
87
+ const tenantId = resolution.tenantId;
88
+ if (!actorIsSuperAdmin && auth.sub) {
51
89
  try {
52
90
  await assertActorCanModifySuperAdminUserTarget({
53
91
  em,
54
92
  rbacService,
55
93
  actorUserId: auth.sub,
56
- tenantId: auth.tenantId ?? null,
94
+ tenantId: actorTenantId,
57
95
  organizationId: auth.orgId ?? null,
58
96
  targetUserId: parsed.data.userId,
59
97
  actorIsSuperAdmin: false
@@ -62,7 +100,7 @@ async function GET(req) {
62
100
  em,
63
101
  rbacService,
64
102
  actorUserId: auth.sub,
65
- tenantId: auth.tenantId ?? null,
103
+ tenantId: actorTenantId,
66
104
  organizationId: auth.orgId ?? null,
67
105
  targetUserId: parsed.data.userId,
68
106
  actorIsSuperAdmin: false,
@@ -70,7 +108,7 @@ async function GET(req) {
70
108
  container,
71
109
  auth,
72
110
  request: req,
73
- tenantId: auth.tenantId ?? null
111
+ tenantId: actorTenantId
74
112
  })
75
113
  });
76
114
  } catch (err) {
@@ -78,7 +116,7 @@ async function GET(req) {
78
116
  throw err;
79
117
  }
80
118
  }
81
- const acl = await em.findOne(UserAcl, { user: parsed.data.userId, tenantId: auth.tenantId });
119
+ const acl = tenantId ? await em.findOne(UserAcl, { user: parsed.data.userId, tenantId }) : null;
82
120
  const response = acl ? {
83
121
  hasCustomAcl: true,
84
122
  isSuperAdmin: !!acl.isSuperAdmin,
@@ -94,8 +132,8 @@ async function GET(req) {
94
132
  idField: "id",
95
133
  resourceKind: "auth.user_acl",
96
134
  organizationId: auth.orgId ?? null,
97
- tenantId: auth.tenantId ?? null,
98
- query: { userId: parsed.data.userId },
135
+ tenantId,
136
+ query: { userId: parsed.data.userId, tenantId },
99
137
  accessType: "read:item"
100
138
  });
101
139
  return NextResponse.json(response);
@@ -109,15 +147,26 @@ async function PUT(req) {
109
147
  const container = await createRequestContainer();
110
148
  const em = container.resolve("em");
111
149
  const rbacService = container.resolve("rbacService");
112
- const actorAcl = auth.sub ? await rbacService.loadAcl(auth.sub, { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null }) : null;
150
+ const actorTenantId = auth.tenantId ?? null;
151
+ const actorAcl = auth.sub ? await rbacService.loadAcl(auth.sub, { tenantId: actorTenantId, organizationId: auth.orgId ?? null }) : null;
113
152
  const actorIsSuperAdmin = !!actorAcl?.isSuperAdmin;
153
+ const resolution = await resolveAclTenantId({
154
+ em,
155
+ auth,
156
+ actorIsSuperAdmin,
157
+ userId: parsed.data.userId,
158
+ requestedTenantId: parsed.data.tenantId
159
+ });
160
+ if ("error" in resolution) return resolution.error;
161
+ const tenantId = resolution.tenantId;
162
+ if (!tenantId) return NextResponse.json({ error: "Tenant required" }, { status: 400 });
114
163
  if (!actorIsSuperAdmin && auth.sub) {
115
164
  try {
116
165
  await assertActorCanModifySuperAdminUserTarget({
117
166
  em,
118
167
  rbacService,
119
168
  actorUserId: auth.sub,
120
- tenantId: auth.tenantId ?? null,
169
+ tenantId: actorTenantId,
121
170
  organizationId: auth.orgId ?? null,
122
171
  targetUserId: parsed.data.userId,
123
172
  actorIsSuperAdmin: false
@@ -126,7 +175,7 @@ async function PUT(req) {
126
175
  em,
127
176
  rbacService,
128
177
  actorUserId: auth.sub,
129
- tenantId: auth.tenantId ?? null,
178
+ tenantId: actorTenantId,
130
179
  organizationId: auth.orgId ?? null,
131
180
  targetUserId: parsed.data.userId,
132
181
  actorIsSuperAdmin: false,
@@ -134,7 +183,7 @@ async function PUT(req) {
134
183
  container,
135
184
  auth,
136
185
  request: req,
137
- tenantId: auth.tenantId ?? null
186
+ tenantId: actorTenantId
138
187
  })
139
188
  });
140
189
  } catch (err) {
@@ -144,7 +193,7 @@ async function PUT(req) {
144
193
  }
145
194
  const requestedFeatures = normalizeGrantFeatureList(parsed.data.features);
146
195
  const organizations = normalizeOrganizations(parsed.data.organizations);
147
- let acl = await em.findOne(UserAcl, { user: parsed.data.userId, tenantId: auth.tenantId });
196
+ const acl = await em.findOne(UserAcl, { user: parsed.data.userId, tenantId });
148
197
  if (acl) {
149
198
  try {
150
199
  await enforceCommandOptimisticLockWithGuards(container, {
@@ -166,7 +215,7 @@ async function PUT(req) {
166
215
  em,
167
216
  rbacService,
168
217
  actorUserId: auth.sub,
169
- tenantId: auth.tenantId ?? null,
218
+ tenantId: actorTenantId,
170
219
  organizationId: auth.orgId ?? null,
171
220
  isSuperAdmin: requestedIsSuperAdmin,
172
221
  features: requestedFeatures,
@@ -189,35 +238,30 @@ async function PUT(req) {
189
238
  }
190
239
  }
191
240
  const hasCustomAcl = effectiveIsSuperAdmin || effectiveFeatures.length > 0;
192
- if (!hasCustomAcl) {
193
- if (acl) {
194
- const aclToRemove = acl;
195
- await withAtomicFlush(em, [() => em.remove(aclToRemove)], { transaction: true });
196
- }
197
- } else {
198
- if (!acl) {
199
- acl = em.create(UserAcl, { user: parsed.data.userId, tenantId: auth.tenantId });
200
- }
201
- const aclRecord = acl;
202
- await withAtomicFlush(
203
- em,
204
- [
205
- () => {
206
- aclRecord.isSuperAdmin = effectiveIsSuperAdmin;
207
- aclRecord.featuresJson = effectiveFeatures;
208
- aclRecord.organizationsJson = organizations;
209
- em.persist(aclRecord);
210
- }
211
- ],
212
- { transaction: true }
213
- );
214
- }
215
- await rbacService.invalidateUserCache(parsed.data.userId);
216
- try {
217
- const cache = container.resolve("cache");
218
- if (cache) await cache.deleteByTags([`rbac:user:${parsed.data.userId}`]);
219
- } catch {
220
- }
241
+ const strippedFeatures = requestedFeatures.filter((feature) => !effectiveFeatures.includes(feature));
242
+ const commandBus = container.resolve("commandBus");
243
+ const isForeignTenant = tenantId !== (auth.tenantId ?? null);
244
+ const actorOrgId = isForeignTenant ? null : auth.orgId ?? null;
245
+ const commandCtx = {
246
+ container,
247
+ auth: isForeignTenant ? { ...auth, orgId: null } : auth,
248
+ organizationScope: null,
249
+ selectedOrganizationId: actorOrgId,
250
+ organizationIds: actorOrgId ? [actorOrgId] : null,
251
+ request: req
252
+ };
253
+ await commandBus.execute(AUTH_USER_ACL_UPDATE_COMMAND_ID, {
254
+ input: {
255
+ userId: parsed.data.userId,
256
+ tenantId,
257
+ isSuperAdmin: effectiveIsSuperAdmin,
258
+ features: effectiveFeatures,
259
+ organizations,
260
+ clear: !hasCustomAcl,
261
+ requested: strippedFeatures.length ? { features: requestedFeatures } : null
262
+ },
263
+ ctx: commandCtx
264
+ });
221
265
  return NextResponse.json({
222
266
  ok: true,
223
267
  sanitized: !actorIsSuperAdmin && (hasRestrictedChanges(requestedFeatures, effectiveFeatures, existingFeatures) || requestedIsSuperAdmin !== effectiveIsSuperAdmin)
@@ -257,12 +301,13 @@ const openApi = {
257
301
  methods: {
258
302
  GET: {
259
303
  summary: "Fetch user ACL",
260
- description: "Returns custom ACL overrides for a user within the current tenant, if any.",
304
+ description: "Returns custom ACL overrides for a user, scoped to the requested tenant when supplied and to the actor or target user tenant otherwise.",
261
305
  query: getSchema,
262
306
  responses: [
263
307
  { status: 200, description: "User ACL entry", schema: userAclResponseSchema },
264
308
  { status: 400, description: "Invalid user id", schema: userAclErrorSchema },
265
- { status: 401, description: "Unauthorized", schema: userAclErrorSchema }
309
+ { status: 401, description: "Unauthorized", schema: userAclErrorSchema },
310
+ { status: 403, description: "Insufficient privileges for the requested tenant scope", schema: userAclErrorSchema }
266
311
  ]
267
312
  },
268
313
  PUT: {
@@ -274,7 +319,7 @@ const openApi = {
274
319
  },
275
320
  responses: [
276
321
  { status: 200, description: "User ACL updated", schema: userAclUpdateResponseSchema },
277
- { status: 400, description: "Invalid payload", schema: userAclErrorSchema },
322
+ { status: 400, description: "Invalid payload or unresolved tenant scope", schema: userAclErrorSchema },
278
323
  { status: 401, description: "Unauthorized", schema: userAclErrorSchema },
279
324
  { status: 403, description: "Insufficient privileges to modify ACL", schema: userAclErrorSchema }
280
325
  ]
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/auth/api/users/acl/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { logCrudAccess } from '@open-mercato/shared/lib/crud/factory'\nimport { forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { UserAcl } from '@open-mercato/core/modules/auth/data/entities'\nimport {\n assertActorCanAccessUserTarget,\n assertActorCanGrantAcl,\n assertActorCanModifySuperAdminUserTarget,\n normalizeGrantFeatureList,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\nconst getSchema = z.object({ userId: z.string().uuid() })\nconst putSchema = z.object({\n userId: z.string().uuid(),\n isSuperAdmin: z.boolean().optional(),\n features: z.array(z.string()).optional(),\n organizations: z.array(z.string()).nullable().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\nconst userAclResponseSchema = z.object({\n hasCustomAcl: z.boolean(),\n isSuperAdmin: z.boolean(),\n features: z.array(z.string()),\n organizations: z.array(z.string()).nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst userAclUpdateResponseSchema = z.object({\n ok: z.literal(true),\n sanitized: z.boolean(),\n})\n\nconst userAclErrorSchema = z.object({ error: z.string() })\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsed = getSchema.safeParse({ userId: url.searchParams.get('userId') })\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as any\n const rbacService = container.resolve('rbacService') as any\n const actorAcl = auth.sub\n ? await rbacService.loadAcl(auth.sub, { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null })\n : null\n if (!actorAcl?.isSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n })\n await assertActorCanAccessUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n organizationScope: await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n tenantId: auth.tenantId ?? null,\n }),\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n const acl = await em.findOne(UserAcl, { user: parsed.data.userId as any, tenantId: auth.tenantId as any })\n const response = acl\n ? {\n hasCustomAcl: true,\n isSuperAdmin: !!acl.isSuperAdmin,\n features: Array.isArray(acl.featuresJson) ? acl.featuresJson : [],\n organizations: Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null,\n updatedAt: acl.updatedAt instanceof Date ? acl.updatedAt.toISOString() : null,\n }\n : { hasCustomAcl: false, isSuperAdmin: false, features: [], organizations: null, updatedAt: null }\n\n await logCrudAccess({\n container,\n auth,\n request: req,\n items: [{ id: parsed.data.userId, ...response }],\n idField: 'id',\n resourceKind: 'auth.user_acl',\n organizationId: auth.orgId ?? null,\n tenantId: auth.tenantId ?? null,\n query: { userId: parsed.data.userId },\n accessType: 'read:item',\n })\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const body = await req.json().catch(() => ({}))\n const parsed = putSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as any\n const rbacService = container.resolve('rbacService') as any\n\n const actorAcl = auth.sub\n ? await rbacService.loadAcl(auth.sub, { tenantId: auth.tenantId ?? null, organizationId: auth.orgId ?? null })\n : null\n const actorIsSuperAdmin = !!actorAcl?.isSuperAdmin\n\n if (!actorIsSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n })\n await assertActorCanAccessUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n organizationScope: await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n tenantId: auth.tenantId ?? null,\n }),\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const requestedFeatures = normalizeGrantFeatureList(parsed.data.features)\n const organizations = normalizeOrganizations(parsed.data.organizations)\n\n let acl = await em.findOne(UserAcl, { user: parsed.data.userId as any, tenantId: auth.tenantId as any })\n // Optimistic lock: refuse a stale per-user ACL overwrite so concurrent edits\n // cannot silently clobber each other (#2055). Strictly additive \u2014 a no-op when\n // the client sends no expected-version header; skipped when no ACL row exists.\n if (acl) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'auth.user_acl',\n resourceId: acl.id,\n current: acl.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n const existingIsSuperAdmin = acl ? !!acl.isSuperAdmin : false\n const existingFeatures = acl ? normalizeGrantFeatureList(acl.featuresJson) : []\n\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? false\n\n try {\n await assertActorCanGrantAcl({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: auth.tenantId ?? null,\n organizationId: auth.orgId ?? null,\n isSuperAdmin: requestedIsSuperAdmin,\n features: requestedFeatures,\n organizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const effectiveFeatures = actorIsSuperAdmin\n ? requestedFeatures\n : sanitizeTenantFeatures(requestedFeatures)\n\n let effectiveIsSuperAdmin = requestedIsSuperAdmin\n\n if (!actorIsSuperAdmin) {\n if (requestedIsSuperAdmin && !existingIsSuperAdmin) {\n throw forbidden('Only super administrators can grant super admin access.')\n }\n if (existingIsSuperAdmin && requestedIsSuperAdmin === false) {\n effectiveIsSuperAdmin = false\n } else {\n effectiveIsSuperAdmin = existingIsSuperAdmin\n }\n }\n\n const hasCustomAcl = effectiveIsSuperAdmin || effectiveFeatures.length > 0\n\n // Persist the ACL mutation inside a transaction so the per-user permission\n // write (or removal) commits atomically (proper ACL-edit transaction handling).\n if (!hasCustomAcl) {\n if (acl) {\n const aclToRemove = acl\n await withAtomicFlush(em, [() => em.remove(aclToRemove)], { transaction: true })\n }\n } else {\n if (!acl) {\n acl = em.create(UserAcl, { user: parsed.data.userId as any, tenantId: auth.tenantId as any })\n }\n const aclRecord = acl as any\n await withAtomicFlush(\n em,\n [\n () => {\n aclRecord.isSuperAdmin = effectiveIsSuperAdmin\n aclRecord.featuresJson = effectiveFeatures\n aclRecord.organizationsJson = organizations\n em.persist(aclRecord)\n },\n ],\n { transaction: true },\n )\n }\n\n // Invalidate cache for this user\n await rbacService.invalidateUserCache(parsed.data.userId)\n try {\n const cache = container.resolve('cache') as any\n if (cache) await cache.deleteByTags([`rbac:user:${parsed.data.userId}`])\n } catch {}\n\n return NextResponse.json({\n ok: true,\n sanitized: !actorIsSuperAdmin && (hasRestrictedChanges(requestedFeatures, effectiveFeatures, existingFeatures) || requestedIsSuperAdmin !== effectiveIsSuperAdmin),\n })\n}\n\nfunction normalizeOrganizations(organizations: unknown): string[] | null {\n if (!Array.isArray(organizations)) return null\n return normalizeGrantFeatureList(organizations)\n}\n\nfunction sanitizeTenantFeatures(features: string[]): string[] {\n return features.filter((feature) => !isTenantRestrictedFeature(feature))\n}\n\nfunction isTenantRestrictedFeature(feature: string): boolean {\n if (feature === '*' || feature === 'directory.*') return true\n if (feature.startsWith('directory.tenants')) return true\n return false\n}\n\nfunction hasRestrictedChanges(requested: string[], effective: string[], existing: string[]): boolean {\n if (requested.length === effective.length) return false\n const effectiveSet = new Set(effective)\n const existingSet = new Set(existing)\n // If the effective set matches existing, we only trimmed restricted duplicates and should not report\n if (effectiveSet.size === existingSet.size) {\n let identical = true\n for (const value of effectiveSet) {\n if (!existingSet.has(value)) {\n identical = false\n break\n }\n }\n if (identical) return false\n }\n return true\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'User ACL management',\n methods: {\n GET: {\n summary: 'Fetch user ACL',\n description: 'Returns custom ACL overrides for a user within the current tenant, if any.',\n query: getSchema,\n responses: [\n { status: 200, description: 'User ACL entry', schema: userAclResponseSchema },\n { status: 400, description: 'Invalid user id', schema: userAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: userAclErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update user ACL',\n description: 'Configures per-user ACL overrides, including super admin access, feature list, and organization scope.',\n requestBody: {\n contentType: 'application/json',\n schema: putSchema,\n },\n responses: [\n { status: 200, description: 'User ACL updated', schema: userAclUpdateResponseSchema },\n { status: 400, description: 'Invalid payload', schema: userAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: userAclErrorSchema },\n { status: 403, description: 'Insufficient privileges to modify ACL', schema: userAclErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,WAAW,uBAAuB;AAC3C,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;A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AAC3B,oBAAY;AACZ;AAAA,MACF;AAAA,IACF;AACA,QAAI,UAAW,QAAO;AAAA,EACxB;AACA,SAAO;AACT;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,sBAAsB;AAAA,QAC5E,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,MACzE;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,oBAAoB,QAAQ,4BAA4B;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,mBAAmB,QAAQ,mBAAmB;AAAA,QAC1E,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,mBAAmB;AAAA,MAClG;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { getAuthFromRequest, type AuthContext } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { logCrudAccess } from '@open-mercato/shared/lib/crud/factory'\nimport { forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport type { CommandBus, CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { User, UserAcl } from '@open-mercato/core/modules/auth/data/entities'\nimport {\n assertActorCanAccessUserTarget,\n assertActorCanGrantAcl,\n assertActorCanModifySuperAdminUserTarget,\n normalizeGrantFeatureList,\n} from '@open-mercato/core/modules/auth/lib/grantChecks'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n AUTH_USER_ACL_UPDATE_COMMAND_ID,\n type AclUpdateResult,\n type UserAclUpdateInput,\n} from '@open-mercato/core/modules/auth/commands/acl'\n\nconst getSchema = z.object({\n userId: z.string().uuid(),\n tenantId: z.string().uuid().optional(),\n})\nconst putSchema = z.object({\n userId: z.string().uuid(),\n isSuperAdmin: z.boolean().optional(),\n features: z.array(z.string()).optional(),\n organizations: z.array(z.string()).nullable().optional(),\n tenantId: z.string().uuid().optional(),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['auth.acl.manage'] },\n}\n\nconst userAclResponseSchema = z.object({\n hasCustomAcl: z.boolean(),\n isSuperAdmin: z.boolean(),\n features: z.array(z.string()),\n organizations: z.array(z.string()).nullable(),\n updatedAt: z.string().nullable(),\n})\n\nconst userAclUpdateResponseSchema = z.object({\n ok: z.literal(true),\n sanitized: z.boolean(),\n})\n\nconst userAclErrorSchema = z.object({ error: z.string() })\n\ntype TenantResolution = { tenantId: string | null } | { error: NextResponse }\n\n/**\n * The single tenant scope both handlers work in. GET and PUT MUST resolve it the\n * same way: the admin user form PUTs the ACL panel's state on every save, so a\n * GET that reads a narrower scope than the PUT writes hands the operator an\n * empty form and turns the next name-only edit into a silent revocation, with no\n * `updatedAt` to arm the optimistic lock against it.\n *\n * `user_acls.tenant_id` is NOT NULL while `users.tenant_id` is nullable, so a\n * global account legitimately signs in with `auth.tenantId === null` and the\n * scope has to come from the target user instead. That fallback is reserved for\n * a super admin: for anyone else it would let the target pick the scope its own\n * access is then checked against, and it decrypts a possibly foreign user ahead\n * of every guard. A tenant-less non-super-admin therefore resolves to `null`,\n * which reads as \"no override\" and refuses to write \u2014 the behaviour that held\n * before this route resolved a scope at all. The read is also skipped whenever a\n * tenant is already known.\n *\n * An explicit `tenantId` wins, mirroring the role ACL route (additive there and\n * here; no caller sends it yet) \u2014 but only for a super admin or for the actor's\n * own tenant, so it cannot widen anyone's reach. The result is that for a\n * non-super-admin the resolved scope is always the actor's own.\n */\nasync function resolveAclTenantId(args: {\n em: EntityManager\n auth: NonNullable<AuthContext>\n actorIsSuperAdmin: boolean\n userId: string\n requestedTenantId?: string\n}): Promise<TenantResolution> {\n const authTenantId = args.auth.tenantId ?? null\n if (args.requestedTenantId && args.requestedTenantId !== authTenantId && !args.actorIsSuperAdmin) {\n return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) }\n }\n const known = args.requestedTenantId ?? authTenantId\n if (known) return { tenantId: known }\n if (!args.actorIsSuperAdmin) return { tenantId: null }\n const targetUser = await findOneWithDecryption(\n args.em,\n User,\n { id: args.userId } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: args.auth.orgId ?? null },\n )\n return { tenantId: targetUser?.tenantId ? String(targetUser.tenantId) : null }\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const url = new URL(req.url)\n const parsed = getSchema.safeParse({\n userId: url.searchParams.get('userId'),\n tenantId: url.searchParams.get('tenantId') || undefined,\n })\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as any\n const rbacService = container.resolve('rbacService') as any\n // Every grant check is answered in the actor's own scope, never in the scope\n // resolved for the record: passing the resolved one would ask a foreign tenant\n // whether this caller may act there, and for a tenant-less actor \u2014 whose scope\n // comes from the target \u2014 it would compare the target against itself.\n const actorTenantId = auth.tenantId ?? null\n const actorAcl = auth.sub\n ? await rbacService.loadAcl(auth.sub, { tenantId: actorTenantId, organizationId: auth.orgId ?? null })\n : null\n const actorIsSuperAdmin = !!actorAcl?.isSuperAdmin\n\n const resolution = await resolveAclTenantId({\n em: em as EntityManager,\n auth,\n actorIsSuperAdmin,\n userId: parsed.data.userId,\n requestedTenantId: parsed.data.tenantId,\n })\n if ('error' in resolution) return resolution.error\n // An unresolvable scope reads as \"no override\", which is what PUT then refuses\n // to write (`Tenant required`) \u2014 so the pair still cannot destroy a row.\n const tenantId = resolution.tenantId\n\n if (!actorIsSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: actorTenantId,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n })\n await assertActorCanAccessUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: actorTenantId,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n organizationScope: await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n tenantId: actorTenantId,\n }),\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n const acl = tenantId\n ? await em.findOne(UserAcl, { user: parsed.data.userId as any, tenantId })\n : null\n const response = acl\n ? {\n hasCustomAcl: true,\n isSuperAdmin: !!acl.isSuperAdmin,\n features: Array.isArray(acl.featuresJson) ? acl.featuresJson : [],\n organizations: Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null,\n updatedAt: acl.updatedAt instanceof Date ? acl.updatedAt.toISOString() : null,\n }\n : { hasCustomAcl: false, isSuperAdmin: false, features: [], organizations: null, updatedAt: null }\n\n await logCrudAccess({\n container,\n auth,\n request: req,\n items: [{ id: parsed.data.userId, ...response }],\n idField: 'id',\n resourceKind: 'auth.user_acl',\n organizationId: auth.orgId ?? null,\n tenantId,\n query: { userId: parsed.data.userId, tenantId },\n accessType: 'read:item',\n })\n\n return NextResponse.json(response)\n}\n\nexport async function PUT(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const body = await req.json().catch(() => ({}))\n const parsed = putSchema.safeParse(body)\n if (!parsed.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 })\n const container = await createRequestContainer()\n const em = container.resolve('em') as any\n const rbacService = container.resolve('rbacService') as any\n\n // Every grant check is answered in the actor's own scope, never in the scope\n // resolved for the record: passing the resolved one would ask a foreign tenant\n // whether this caller may act there, and for a tenant-less actor \u2014 whose scope\n // comes from the target \u2014 it would compare the target against itself.\n const actorTenantId = auth.tenantId ?? null\n const actorAcl = auth.sub\n ? await rbacService.loadAcl(auth.sub, { tenantId: actorTenantId, organizationId: auth.orgId ?? null })\n : null\n const actorIsSuperAdmin = !!actorAcl?.isSuperAdmin\n\n // The scope the row is read and written in. `auth.tenantId` is `string | null`\n // \u2014 never `undefined`, since every producer normalizes with `?? null` \u2014 so the\n // pre-fix lookup ran `tenant_id IS NULL` against a NOT NULL column: it matched\n // no row, leaving create/update to fail the NOT NULL constraint and clear to\n // no-op silently. Nothing cross-tenant was ever matched; the fix turns a 500\n // into a working, correctly scoped write.\n const resolution = await resolveAclTenantId({\n em: em as EntityManager,\n auth,\n actorIsSuperAdmin,\n userId: parsed.data.userId,\n requestedTenantId: parsed.data.tenantId,\n })\n if ('error' in resolution) return resolution.error\n const tenantId = resolution.tenantId\n if (!tenantId) return NextResponse.json({ error: 'Tenant required' }, { status: 400 })\n\n if (!actorIsSuperAdmin && auth.sub) {\n try {\n await assertActorCanModifySuperAdminUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: actorTenantId,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n })\n await assertActorCanAccessUserTarget({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: actorTenantId,\n organizationId: auth.orgId ?? null,\n targetUserId: parsed.data.userId,\n actorIsSuperAdmin: false,\n organizationScope: await resolveOrganizationScopeForRequest({\n container,\n auth,\n request: req,\n tenantId: actorTenantId,\n }),\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n\n const requestedFeatures = normalizeGrantFeatureList(parsed.data.features)\n const organizations = normalizeOrganizations(parsed.data.organizations)\n\n const acl = await em.findOne(UserAcl, { user: parsed.data.userId as any, tenantId })\n // Optimistic lock: refuse a stale per-user ACL overwrite so concurrent edits\n // cannot silently clobber each other (#2055). Strictly additive \u2014 a no-op when\n // the client sends no expected-version header; skipped when no ACL row exists.\n if (acl) {\n try {\n await enforceCommandOptimisticLockWithGuards(container, {\n resourceKind: 'auth.user_acl',\n resourceId: acl.id,\n current: acl.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n }\n const existingIsSuperAdmin = acl ? !!acl.isSuperAdmin : false\n const existingFeatures = acl ? normalizeGrantFeatureList(acl.featuresJson) : []\n\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? false\n\n try {\n await assertActorCanGrantAcl({\n em: em as EntityManager,\n rbacService: rbacService as RbacService,\n actorUserId: auth.sub,\n tenantId: actorTenantId,\n organizationId: auth.orgId ?? null,\n isSuperAdmin: requestedIsSuperAdmin,\n features: requestedFeatures,\n organizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n const effectiveFeatures = actorIsSuperAdmin\n ? requestedFeatures\n : sanitizeTenantFeatures(requestedFeatures)\n\n let effectiveIsSuperAdmin = requestedIsSuperAdmin\n\n if (!actorIsSuperAdmin) {\n if (requestedIsSuperAdmin && !existingIsSuperAdmin) {\n throw forbidden('Only super administrators can grant super admin access.')\n }\n if (existingIsSuperAdmin && requestedIsSuperAdmin === false) {\n effectiveIsSuperAdmin = false\n } else {\n effectiveIsSuperAdmin = existingIsSuperAdmin\n }\n }\n\n const hasCustomAcl = effectiveIsSuperAdmin || effectiveFeatures.length > 0\n\n // What the caller asked for, handed to the command only when it exceeds what\n // is about to be written. `assertActorCanGrantAcl` above refuses the blatant\n // escalations; what reaches the strip is quieter \u2014 a restricted grant the\n // actor does hold \u2014 and it leaves before/after identical, so the audit entry\n // would otherwise be indistinguishable from a no-op and skipped as one.\n //\n // Features are the only axis that can be trimmed. A super-admin request is\n // either honoured or refused outright above, never silently downgraded, so\n // comparing the two flags here would be dead weight.\n //\n // Deliberately independent of the `sanitized` response flag below:\n // `hasRestrictedChanges` stays false when the trimmed result equals the\n // existing ACL, to avoid nagging the user about a save that changed nothing \u2014\n // but that is precisely an attempt the trail must keep.\n const strippedFeatures = requestedFeatures.filter((feature) => !effectiveFeatures.includes(feature))\n\n // Route the write through the command bus so the permission change lands in\n // the action log. The command owns the transactional write (or removal) and\n // the RBAC cache invalidation that used to live here.\n const commandBus = container.resolve('commandBus') as CommandBus\n // A tenant-less actor edits an override in the target user's tenant, so their\n // organization belongs to a tenant the entry is not about. The bus resolves\n // the log row's organization as `metadata.organizationId ??\n // ctx.selectedOrganizationId ?? ctx.auth.orgId` \u2014 a `??` chain, so the\n // handler's `resolveOrganizationId` cannot express \"explicitly no\n // organization\" and the actor's would be restored. Strip it from the context\n // instead, exactly as the roles route does: otherwise the entry carries a\n // (target tenant, foreign organization) pair that `ActionLogService` \u2014 which\n // filters organization with strict equality \u2014 can never surface for anyone.\n const isForeignTenant = tenantId !== (auth.tenantId ?? null)\n const actorOrgId = isForeignTenant ? null : auth.orgId ?? null\n const commandCtx: CommandRuntimeContext = {\n container,\n auth: isForeignTenant ? { ...auth, orgId: null } : auth,\n organizationScope: null,\n selectedOrganizationId: actorOrgId,\n organizationIds: actorOrgId ? [actorOrgId] : null,\n request: req,\n }\n await commandBus.execute<UserAclUpdateInput, AclUpdateResult>(AUTH_USER_ACL_UPDATE_COMMAND_ID, {\n input: {\n userId: parsed.data.userId,\n tenantId,\n isSuperAdmin: effectiveIsSuperAdmin,\n features: effectiveFeatures,\n organizations,\n clear: !hasCustomAcl,\n requested: strippedFeatures.length ? { features: requestedFeatures } : null,\n },\n ctx: commandCtx,\n })\n\n return NextResponse.json({\n ok: true,\n sanitized: !actorIsSuperAdmin && (hasRestrictedChanges(requestedFeatures, effectiveFeatures, existingFeatures) || requestedIsSuperAdmin !== effectiveIsSuperAdmin),\n })\n}\n\nfunction normalizeOrganizations(organizations: unknown): string[] | null {\n if (!Array.isArray(organizations)) return null\n return normalizeGrantFeatureList(organizations)\n}\n\nfunction sanitizeTenantFeatures(features: string[]): string[] {\n return features.filter((feature) => !isTenantRestrictedFeature(feature))\n}\n\nfunction isTenantRestrictedFeature(feature: string): boolean {\n if (feature === '*' || feature === 'directory.*') return true\n if (feature.startsWith('directory.tenants')) return true\n return false\n}\n\nfunction hasRestrictedChanges(requested: string[], effective: string[], existing: string[]): boolean {\n if (requested.length === effective.length) return false\n const effectiveSet = new Set(effective)\n const existingSet = new Set(existing)\n // If the effective set matches existing, we only trimmed restricted duplicates and should not report\n if (effectiveSet.size === existingSet.size) {\n let identical = true\n for (const value of effectiveSet) {\n if (!existingSet.has(value)) {\n identical = false\n break\n }\n }\n if (identical) return false\n }\n return true\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'User ACL management',\n methods: {\n GET: {\n summary: 'Fetch user ACL',\n description: 'Returns custom ACL overrides for a user, scoped to the requested tenant when supplied and to the actor or target user tenant otherwise.',\n query: getSchema,\n responses: [\n { status: 200, description: 'User ACL entry', schema: userAclResponseSchema },\n { status: 400, description: 'Invalid user id', schema: userAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: userAclErrorSchema },\n { status: 403, description: 'Insufficient privileges for the requested tenant scope', schema: userAclErrorSchema },\n ],\n },\n PUT: {\n summary: 'Update user ACL',\n description: 'Configures per-user ACL overrides, including super admin access, feature list, and organization scope.',\n requestBody: {\n contentType: 'application/json',\n schema: putSchema,\n },\n responses: [\n { status: 200, description: 'User ACL updated', schema: userAclUpdateResponseSchema },\n { status: 400, description: 'Invalid payload or unresolved tenant scope', schema: userAclErrorSchema },\n { status: 401, description: 'Unauthorized', schema: userAclErrorSchema },\n { status: 403, description: 'Insufficient privileges to modify ACL', schema: userAclErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA4C;AACrD,SAAS,8BAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,WAAW,uBAAuB;AAC3C,SAAS,8CAA8C;AAEvD,SAAS,MAAM,eAAe;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,6BAA6B;AAEtC,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,OAGK;AAEP,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AACD,MAAM,YAAY,EAAE,OAAO;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,KAAK;AAAA,EACxB,cAAc,EAAE,QAAQ,EAAE,SAAS;AAAA,EACnC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACvC,eAAe,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS,EAAE,SAAS;AAAA,EACvD,UAAU,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AACvC,CAAC;AAEM,MAAM,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