@open-mercato/core 0.10.1-develop.7974.1.c98f9304d9 → 0.10.1-develop.7975.1.ada24d305c

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.
@@ -240,7 +240,11 @@ async function PUT(req) {
240
240
  let effectiveIsSuperAdmin = requestedIsSuperAdmin;
241
241
  if (!actorIsSuperAdmin) {
242
242
  if (requestedIsSuperAdmin && !existingIsSuperAdmin) {
243
- throw forbidden("Only super administrators can grant super admin access.");
243
+ const { translate } = await resolveTranslations();
244
+ throw forbidden(translate(
245
+ "auth.acl.errors.superAdminGrantDenied",
246
+ "Only super administrators can grant super admin access."
247
+ ));
244
248
  }
245
249
  if (existingIsSuperAdmin && requestedIsSuperAdmin === false) {
246
250
  effectiveIsSuperAdmin = false;
@@ -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, 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 { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\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, {\n user: parsed.data.userId as unknown as User,\n tenantId,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\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 acl = await em.findOne(UserAcl, {\n user: parsed.data.userId as unknown as User,\n tenantId,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\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 const existingOrganizations = acl ? normalizeOrganizations(acl.organizationsJson) : null\n\n // A per-user ACL is an absolute override, so an omitted dimension must keep\n // its stored value. Normalizing an omitted `features` to `[]` or an omitted\n // `organizations` to `null` turned a single-dimension edit into a silent\n // clear, deleting the row and widening the user back to their full role.\n const featuresWereProvided = parsed.data.features !== undefined\n const requestedFeatures = featuresWereProvided\n ? normalizeGrantFeatureList(parsed.data.features)\n : existingFeatures\n const requestedOrganizations = parsed.data.organizations === undefined\n ? existingOrganizations\n : normalizeOrganizations(parsed.data.organizations)\n\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? existingIsSuperAdmin\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: requestedOrganizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // An omitted feature list is already stored and in effect. Re-sanitizing it\n // during an unrelated organization edit would silently revoke grants the\n // actor did not touch, so only an explicitly submitted list is sanitized.\n const effectiveFeatures = actorIsSuperAdmin || !featuresWereProvided\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 // Retaining an organization-only override with no features would revoke every\n // role-granted feature instead of narrowing the role. Refuse that state rather\n // than persisting it or silently dropping the organization scope.\n if (!effectiveIsSuperAdmin && effectiveFeatures.length === 0 && hasOrganizationRestriction(requestedOrganizations)) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({\n error: translate(\n 'auth.acl.organizationWarning',\n 'Organization restrictions require at least one feature override. Add a feature or module wildcard, or clear the organization scope before saving.',\n ),\n }, { status: 400 })\n }\n\n // An unrestricted organization list carries no override on its own, and the guard\n // above already refused the restricted-but-featureless case, so the override is\n // custom exactly when it grants super admin or at least one feature.\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: requestedOrganizations,\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\n// Whether the caller expressed an intentional narrowing. `null` and `__all__`\n// are the two documented ways to say \"every organization\"; an empty list is the\n// editor's \"no organization picked\" state, which this route treats as\n// unrestricted rather than a deliberate restriction. Only a concrete list\n// narrows, so only a concrete list has to justify itself against the feature\n// grant below.\nfunction hasOrganizationRestriction(organizations: string[] | null): boolean {\n if (!organizations || organizations.length === 0) return false\n return !organizations.includes('__all__')\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: 'Updates a per-user ACL override. Omitted super admin, feature, and organization fields preserve their stored values. Authorization evaluates the merged ACL, so a partial request returns 403 when a preserved grant is outside the actor\\'s grantable ACL. An organization-scoped non-super-admin override requires at least one feature grant.',\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;AACvD,SAAS,2BAA2B;AAEpC,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,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,cAAc,EAAE,QAAQ;AAAA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AAA,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,0DAA0D,QAAQ,mBAAmB;AAAA,MACnH;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,8CAA8C,QAAQ,mBAAmB;AAAA,QACrG,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 { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\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, {\n user: parsed.data.userId as unknown as User,\n tenantId,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\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 acl = await em.findOne(UserAcl, {\n user: parsed.data.userId as unknown as User,\n tenantId,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\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 const existingOrganizations = acl ? normalizeOrganizations(acl.organizationsJson) : null\n\n // A per-user ACL is an absolute override, so an omitted dimension must keep\n // its stored value. Normalizing an omitted `features` to `[]` or an omitted\n // `organizations` to `null` turned a single-dimension edit into a silent\n // clear, deleting the row and widening the user back to their full role.\n const featuresWereProvided = parsed.data.features !== undefined\n const requestedFeatures = featuresWereProvided\n ? normalizeGrantFeatureList(parsed.data.features)\n : existingFeatures\n const requestedOrganizations = parsed.data.organizations === undefined\n ? existingOrganizations\n : normalizeOrganizations(parsed.data.organizations)\n\n const requestedIsSuperAdmin = parsed.data.isSuperAdmin ?? existingIsSuperAdmin\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: requestedOrganizations,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n // An omitted feature list is already stored and in effect. Re-sanitizing it\n // during an unrelated organization edit would silently revoke grants the\n // actor did not touch, so only an explicitly submitted list is sanitized.\n const effectiveFeatures = actorIsSuperAdmin || !featuresWereProvided\n ? requestedFeatures\n : sanitizeTenantFeatures(requestedFeatures)\n\n let effectiveIsSuperAdmin = requestedIsSuperAdmin\n\n if (!actorIsSuperAdmin) {\n if (requestedIsSuperAdmin && !existingIsSuperAdmin) {\n const { translate } = await resolveTranslations()\n throw forbidden(translate(\n 'auth.acl.errors.superAdminGrantDenied',\n 'Only super administrators can grant super admin access.',\n ))\n }\n if (existingIsSuperAdmin && requestedIsSuperAdmin === false) {\n effectiveIsSuperAdmin = false\n } else {\n effectiveIsSuperAdmin = existingIsSuperAdmin\n }\n }\n\n // Retaining an organization-only override with no features would revoke every\n // role-granted feature instead of narrowing the role. Refuse that state rather\n // than persisting it or silently dropping the organization scope.\n if (!effectiveIsSuperAdmin && effectiveFeatures.length === 0 && hasOrganizationRestriction(requestedOrganizations)) {\n const { translate } = await resolveTranslations()\n return NextResponse.json({\n error: translate(\n 'auth.acl.organizationWarning',\n 'Organization restrictions require at least one feature override. Add a feature or module wildcard, or clear the organization scope before saving.',\n ),\n }, { status: 400 })\n }\n\n // An unrestricted organization list carries no override on its own, and the guard\n // above already refused the restricted-but-featureless case, so the override is\n // custom exactly when it grants super admin or at least one feature.\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: requestedOrganizations,\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\n// Whether the caller expressed an intentional narrowing. `null` and `__all__`\n// are the two documented ways to say \"every organization\"; an empty list is the\n// editor's \"no organization picked\" state, which this route treats as\n// unrestricted rather than a deliberate restriction. Only a concrete list\n// narrows, so only a concrete list has to justify itself against the feature\n// grant below.\nfunction hasOrganizationRestriction(organizations: string[] | null): boolean {\n if (!organizations || organizations.length === 0) return false\n return !organizations.includes('__all__')\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: 'Updates a per-user ACL override. Omitted super admin, feature, and organization fields preserve their stored values. Authorization evaluates the merged ACL, so a partial request returns 403 when a preserved grant is outside the actor\\'s grantable ACL. An organization-scoped non-super-admin override requires at least one feature grant.',\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;AACvD,SAAS,2BAA2B;AAEpC,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,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,iBAAiB,EAAE;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KAAK,GAAG;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,QACvE,EAAE,QAAQ,KAAK,aAAa,0DAA0D,QAAQ,mBAAmB;AAAA,MACnH;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,8CAA8C,QAAQ,mBAAmB;AAAA,QACrG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,mBAAmB;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,yCAAyC,QAAQ,mBAAmB;AAAA,MAClG;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -93,12 +93,18 @@ async function assertActorCanGrantRoles(input) {
93
93
  const actorAcl = await loadActorAcl({ ...input, tenantId });
94
94
  if (actorAcl.isSuperAdmin) return;
95
95
  if (!tenantId) {
96
- throw forbidden("Tenant context is required to grant roles.");
96
+ throw forbidden(await translateAuthError(
97
+ "auth.acl.errors.roleGrantTenantRequired",
98
+ "Tenant context is required to grant roles."
99
+ ));
97
100
  }
98
101
  for (const role of input.roles) {
99
102
  const roleTenantId = normalizeNullableString(role.tenantId);
100
103
  if (roleTenantId !== tenantId) {
101
- throw forbidden("Cannot grant a role outside the target tenant.");
104
+ throw forbidden(await translateAuthError(
105
+ "auth.acl.errors.roleOutsideTargetTenant",
106
+ "Cannot grant a role outside the target tenant."
107
+ ));
102
108
  }
103
109
  const acl = await findOneWithDecryption(
104
110
  input.em,
@@ -108,7 +114,7 @@ async function assertActorCanGrantRoles(input) {
108
114
  { tenantId, organizationId: null }
109
115
  );
110
116
  if (!acl) continue;
111
- assertActorCanGrantAclSnapshot(actorAcl, {
117
+ await assertActorCanGrantAclSnapshot(actorAcl, {
112
118
  isSuperAdmin: !!acl.isSuperAdmin,
113
119
  features: normalizeStringList(acl.featuresJson),
114
120
  organizations: normalizeOrganizationList(acl.organizationsJson)
@@ -120,9 +126,12 @@ async function assertActorCanGrantAcl(input) {
120
126
  if (actorAcl.isSuperAdmin) return;
121
127
  const tenantId = normalizeNullableString(input.tenantId);
122
128
  if (!tenantId) {
123
- throw forbidden("Tenant context is required to grant ACL features.");
129
+ throw forbidden(await translateAuthError(
130
+ "auth.acl.errors.aclGrantTenantRequired",
131
+ "Tenant context is required to grant ACL features."
132
+ ));
124
133
  }
125
- assertActorCanGrantAclSnapshot(actorAcl, {
134
+ await assertActorCanGrantAclSnapshot(actorAcl, {
126
135
  isSuperAdmin: !!input.isSuperAdmin,
127
136
  features: normalizeStringList(input.features),
128
137
  organizations: input.organizations === void 0 ? void 0 : normalizeOrganizationList(input.organizations)
@@ -136,7 +145,10 @@ async function assertActorCanModifySuperAdminUserTarget(input) {
136
145
  if (actorIsSuperAdmin) return;
137
146
  const targetIsSuperAdmin = await isUserEffectivelySuperAdmin(input.em, input.targetUserId);
138
147
  if (targetIsSuperAdmin) {
139
- throw forbidden("Only super administrators can modify super administrator accounts.");
148
+ throw forbidden(await translateAuthError(
149
+ "auth.users.errors.superAdminTargetProtected",
150
+ "Only super administrators can modify super administrator accounts."
151
+ ));
140
152
  }
141
153
  }
142
154
  async function assertActorCanModifySuperAdminRoleTarget(input) {
@@ -144,7 +156,10 @@ async function assertActorCanModifySuperAdminRoleTarget(input) {
144
156
  if (actorIsSuperAdmin) return;
145
157
  const targetIsSuperAdmin = await isRoleEffectivelySuperAdmin(input.em, input.targetRoleId);
146
158
  if (targetIsSuperAdmin) {
147
- throw forbidden("Only super administrators can modify super administrator roles.");
159
+ throw forbidden(await translateAuthError(
160
+ "auth.roles.errors.superAdminTargetProtected",
161
+ "Only super administrators can modify super administrator roles."
162
+ ));
148
163
  }
149
164
  }
150
165
  async function assertActorCanAccessUserTarget(input) {
@@ -161,12 +176,15 @@ async function assertActorCanAccessUserTarget(input) {
161
176
  const actorTenantId = normalizeNullableString(input.tenantId);
162
177
  const targetTenantId = normalizeNullableString(target.tenantId);
163
178
  if (!targetTenantId || targetTenantId !== actorTenantId) {
164
- throw new CrudHttpError(404, { error: "User not found" });
179
+ throw new CrudHttpError(404, { error: await translateAuthError("auth.users.errors.notFound", "User not found") });
165
180
  }
166
181
  if (input.organizationScope.allowedIds !== null) {
167
182
  const targetOrganizationId = normalizeNullableString(target.organizationId);
168
183
  if (!targetOrganizationId || !input.organizationScope.allowedIds.includes(targetOrganizationId)) {
169
- throw forbidden("Not authorized to access this user.");
184
+ throw forbidden(await translateAuthError(
185
+ "auth.users.errors.targetAccessDenied",
186
+ "Not authorized to access this user."
187
+ ));
170
188
  }
171
189
  }
172
190
  }
@@ -184,7 +202,7 @@ async function assertActorCanAccessRoleTarget(input) {
184
202
  const actorTenantId = normalizeNullableString(input.tenantId);
185
203
  const targetTenantId = normalizeNullableString(target.tenantId);
186
204
  if (!targetTenantId || targetTenantId !== actorTenantId) {
187
- throw new CrudHttpError(404, { error: "Role not found" });
205
+ throw new CrudHttpError(404, { error: await translateAuthError("auth.roles.errors.notFound", "Role not found") });
188
206
  }
189
207
  }
190
208
  async function resolveActorIsSuperAdmin(input) {
@@ -290,7 +308,12 @@ async function listSuperAdminUserIds(em, tenantId) {
290
308
  }
291
309
  async function loadActorAcl(input) {
292
310
  const actorUserId = normalizeNullableString(input.actorUserId);
293
- if (!actorUserId) throw forbidden("Not authorized to grant ACL privileges.");
311
+ if (!actorUserId) {
312
+ throw forbidden(await translateAuthError(
313
+ "auth.acl.errors.actorRequired",
314
+ "Not authorized to grant ACL privileges."
315
+ ));
316
+ }
294
317
  const scope = {
295
318
  tenantId: normalizeNullableString(input.tenantId),
296
319
  organizationId: normalizeNullableString(input.organizationId)
@@ -319,7 +342,9 @@ async function resolveRolesForGrant(em, roleTokens, tenantId) {
319
342
  }
320
343
  if (missingRoles.length) {
321
344
  const labels = missingRoles.map((role) => `"${role}"`).join(", ");
322
- throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` });
345
+ throw new CrudHttpError(400, {
346
+ error: await translateAuthError("auth.roles.errors.rolesNotFound", "Role(s) not found: {roles}", { roles: labels })
347
+ });
323
348
  }
324
349
  return roles;
325
350
  }
@@ -334,37 +359,57 @@ async function resolveRoleForGrant(em, token, tenantId) {
334
359
  { tenantId, organizationId: null }
335
360
  );
336
361
  }
337
- function assertActorCanGrantAclSnapshot(actorAcl, requested) {
362
+ async function assertActorCanGrantAclSnapshot(actorAcl, requested) {
338
363
  if (requested.isSuperAdmin) {
339
- throw forbidden("Only super administrators can grant super admin access.");
364
+ throw forbidden(await translateAuthError(
365
+ "auth.acl.errors.superAdminGrantDenied",
366
+ "Only super administrators can grant super admin access."
367
+ ));
340
368
  }
341
369
  const actorGrantableFeatures = actorAcl.features.filter((grant) => grant !== "*");
342
370
  for (const feature of requested.features) {
343
371
  if (feature === "*") {
344
- throw forbidden("Only super administrators can grant global wildcard access.");
372
+ throw forbidden(await translateAuthError(
373
+ "auth.acl.errors.globalWildcardGrantDenied",
374
+ "Only super administrators can grant global wildcard access."
375
+ ));
345
376
  }
346
377
  if (isWildcardFeature(feature)) {
347
378
  if (!hasFeature(actorGrantableFeatures, feature)) {
348
- throw forbidden(`Cannot grant feature wildcard ${feature}.`);
379
+ throw forbidden(await translateAuthError(
380
+ "auth.acl.errors.featureWildcardGrantDenied",
381
+ "Cannot grant feature wildcard {feature}.",
382
+ { feature }
383
+ ));
349
384
  }
350
385
  continue;
351
386
  }
352
387
  if (!hasFeature(actorGrantableFeatures, feature)) {
353
- throw forbidden(`Cannot grant feature ${feature}.`);
388
+ throw forbidden(await translateAuthError(
389
+ "auth.acl.errors.featureGrantDenied",
390
+ "Cannot grant feature {feature}.",
391
+ { feature }
392
+ ));
354
393
  }
355
394
  }
356
395
  if (requested.organizations !== void 0) {
357
- assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations);
396
+ await assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations);
358
397
  }
359
398
  }
360
- function assertActorCanGrantOrganizations(actorOrganizations, requestedOrganizations) {
399
+ async function assertActorCanGrantOrganizations(actorOrganizations, requestedOrganizations) {
361
400
  if (actorOrganizations === null || actorOrganizations.includes("__all__")) return;
362
401
  if (requestedOrganizations === null || requestedOrganizations.includes("__all__")) {
363
- throw forbidden("Cannot grant unrestricted organization access.");
402
+ throw forbidden(await translateAuthError(
403
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied",
404
+ "Cannot grant unrestricted organization access."
405
+ ));
364
406
  }
365
407
  for (const organizationId of requestedOrganizations) {
366
408
  if (!actorOrganizations.includes(organizationId)) {
367
- throw forbidden("Cannot grant organization access outside actor scope.");
409
+ throw forbidden(await translateAuthError(
410
+ "auth.acl.errors.organizationOutsideScope",
411
+ "Cannot grant organization access outside actor scope."
412
+ ));
368
413
  }
369
414
  }
370
415
  }
@@ -389,9 +434,9 @@ function normalizeNullableString(value) {
389
434
  function isWildcardFeature(feature) {
390
435
  return feature.endsWith(".*");
391
436
  }
392
- async function translateAuthError(key, fallback) {
437
+ async function translateAuthError(key, fallback, params) {
393
438
  const { translate } = await resolveTranslations();
394
- return translate(key, fallback);
439
+ return translate(key, fallback, params);
395
440
  }
396
441
  export {
397
442
  assertActorCanAccessRoleTarget,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/lib/grantChecks.ts"],
4
- "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { badRequest, CrudHttpError, forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { hasFeature } from '@open-mercato/shared/security/features'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { Role, RoleAcl, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\ntype ActorAcl = {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\ntype GrantCheckContext = {\n em: EntityManager\n rbacService: RbacService\n actorUserId: string | null | undefined\n tenantId: string | null | undefined\n organizationId?: string | null | undefined\n requireBoundRbac?: boolean\n}\n\ntype RoleGrantCheckInput = GrantCheckContext & {\n roles: Role[]\n}\n\ntype RoleTokenGrantCheckInput = GrantCheckContext & {\n roleTokens: unknown\n}\n\ntype UserDestinationRolesInput = {\n em: EntityManager\n targetUserId?: string | null\n destinationTenantId: string | null | undefined\n roleTokens: unknown\n}\n\ntype UserDestinationScopeCheckInput = GrantCheckContext & {\n actorIsSuperAdmin?: boolean\n allowedOrganizationIds?: string[] | null\n destinationTenantId: string | null | undefined\n destinationOrganizationId: string | null | undefined\n roles: Role[]\n}\n\ntype FeatureGrantCheckInput = GrantCheckContext & {\n features: unknown\n isSuperAdmin?: boolean\n organizations?: string[] | null\n}\n\ntype SuperAdminUserTargetInput = GrantCheckContext & {\n targetUserId: string\n actorIsSuperAdmin?: boolean\n}\n\ntype UserTargetAccessInput = SuperAdminUserTargetInput & {\n organizationScope: Pick<OrganizationScope, 'allowedIds'>\n}\n\ntype SuperAdminRoleTargetInput = GrantCheckContext & {\n targetRoleId: string\n actorIsSuperAdmin?: boolean\n}\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\nexport async function assertActorCanGrantRoleTokens(input: RoleTokenGrantCheckInput): Promise<Role[]> {\n const tokens = normalizeStringList(input.roleTokens)\n if (!tokens.length) return []\n\n const tenantId = normalizeNullableString(input.tenantId)\n const roles = await resolveRolesForGrant(input.em, tokens, tenantId)\n await assertActorCanGrantRoles({ ...input, tenantId, roles })\n return roles\n}\n\nexport async function resolveUserDestinationRoles(input: UserDestinationRolesInput): Promise<Role[]> {\n const destinationTenantId = normalizeNullableString(input.destinationTenantId)\n if (Array.isArray(input.roleTokens)) {\n return resolveRolesForGrant(input.em, normalizeStringList(input.roleTokens), destinationTenantId)\n }\n if (!input.targetUserId) return []\n\n const links = await findWithDecryption(\n input.em,\n UserRole,\n { user: input.targetUserId as unknown as User } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const roles: Role[] = []\n for (const link of links) {\n const linkedRole = (link as { role?: Role | string | null }).role\n if (linkedRole && typeof linkedRole === 'object') {\n roles.push(linkedRole)\n continue\n }\n if (typeof linkedRole === 'string') {\n const resolvedRole = await resolveRoleForGrant(input.em, linkedRole, null)\n if (resolvedRole) {\n roles.push(resolvedRole)\n continue\n }\n }\n throw badRequest(await translateAuthError(\n 'auth.users.errors.invalidRoleAssignment',\n 'User has an invalid role assignment',\n ))\n }\n return roles\n}\n\nexport async function assertActorCanAssignUserDestination(\n input: UserDestinationScopeCheckInput,\n): Promise<void> {\n const destinationTenantId = normalizeNullableString(input.destinationTenantId)\n const destinationOrganizationId = normalizeNullableString(input.destinationOrganizationId)\n if (!destinationTenantId || !destinationOrganizationId) {\n return throwUserDestinationOrganizationNotFound(400)\n }\n\n for (const role of input.roles) {\n if (normalizeNullableString(role.tenantId) !== destinationTenantId) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.roleOutsideDestinationTenant',\n 'Cannot retain or assign a role outside the destination tenant.',\n ))\n }\n }\n\n if (await resolveActorIsSuperAdmin(input)) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n if (!actorTenantId || actorTenantId !== destinationTenantId) {\n return throwUserDestinationOrganizationNotFound(404)\n }\n\n const actorAcl = await loadActorAcl(input)\n const allowedOrganizationIds = input.allowedOrganizationIds === undefined\n ? actorAcl.organizations\n : input.allowedOrganizationIds\n if (\n allowedOrganizationIds !== null\n && !allowedOrganizationIds.includes('__all__')\n && !allowedOrganizationIds.includes(destinationOrganizationId)\n ) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.destinationOrganizationOutsideScope',\n 'Cannot assign user to a destination organization outside actor scope.',\n ))\n }\n\n await assertActorCanGrantRoles({\n ...input,\n tenantId: destinationTenantId,\n roles: input.roles,\n })\n}\n\nexport async function throwUserDestinationOrganizationNotFound(status: 400 | 404): Promise<never> {\n throw new CrudHttpError(status, {\n error: await translateAuthError(\n 'auth.users.errors.organizationNotFound',\n 'Organization not found',\n ),\n })\n}\n\nexport async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Promise<void> {\n if (!input.roles.length) return\n\n const tenantId = normalizeNullableString(input.tenantId)\n const actorAcl = await loadActorAcl({ ...input, tenantId })\n if (actorAcl.isSuperAdmin) return\n\n if (!tenantId) {\n throw forbidden('Tenant context is required to grant roles.')\n }\n\n for (const role of input.roles) {\n const roleTenantId = normalizeNullableString(role.tenantId)\n if (roleTenantId !== tenantId) {\n throw forbidden('Cannot grant a role outside the target tenant.')\n }\n\n const acl = await findOneWithDecryption(\n input.em,\n RoleAcl,\n { role, tenantId, deletedAt: null } as FilterQuery<RoleAcl>,\n {},\n { tenantId, organizationId: null },\n )\n if (!acl) continue\n\n assertActorCanGrantAclSnapshot(actorAcl, {\n isSuperAdmin: !!acl.isSuperAdmin,\n features: normalizeStringList(acl.featuresJson),\n organizations: normalizeOrganizationList(acl.organizationsJson),\n })\n }\n}\n\nexport async function assertActorCanGrantAcl(input: FeatureGrantCheckInput): Promise<void> {\n const actorAcl = await loadActorAcl(input)\n if (actorAcl.isSuperAdmin) return\n\n const tenantId = normalizeNullableString(input.tenantId)\n if (!tenantId) {\n throw forbidden('Tenant context is required to grant ACL features.')\n }\n\n assertActorCanGrantAclSnapshot(actorAcl, {\n isSuperAdmin: !!input.isSuperAdmin,\n features: normalizeStringList(input.features),\n organizations: input.organizations === undefined ? undefined : normalizeOrganizationList(input.organizations),\n })\n}\n\nexport function normalizeGrantFeatureList(features: unknown): string[] {\n return normalizeStringList(features)\n}\n\nexport async function assertActorCanModifySuperAdminUserTarget(input: SuperAdminUserTargetInput): Promise<void> {\n const actorIsSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (actorIsSuperAdmin) return\n const targetIsSuperAdmin = await isUserEffectivelySuperAdmin(input.em, input.targetUserId)\n if (targetIsSuperAdmin) {\n throw forbidden('Only super administrators can modify super administrator accounts.')\n }\n}\n\nexport async function assertActorCanModifySuperAdminRoleTarget(input: SuperAdminRoleTargetInput): Promise<void> {\n const actorIsSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (actorIsSuperAdmin) return\n const targetIsSuperAdmin = await isRoleEffectivelySuperAdmin(input.em, input.targetRoleId)\n if (targetIsSuperAdmin) {\n throw forbidden('Only super administrators can modify super administrator roles.')\n }\n}\n\n/**\n * `input.tenantId` is the ACTOR's scope, not the target's: the check below is a\n * comparison between the two, so passing a tenant derived from the target turns\n * it into a tautology. Callers that resolve a record scope separately MUST still\n * hand this guard `auth.tenantId`.\n */\nexport async function assertActorCanAccessUserTarget(input: UserTargetAccessInput): Promise<void> {\n const isSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (isSuperAdmin) return\n\n const target = await findOneWithDecryption(\n input.em,\n User,\n { id: input.targetUserId } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n // Not found (incl. soft-deleted, which MikroORM's soft-delete filter hides):\n // delegate to the caller. Every wired call site is itself tenant-scoped \u2014 the\n // ACL/consents reads filter by auth.tenantId and the user commands re-load by\n // id within tenant \u2014 so a missing target yields a safe empty/404 there. The\n // guard's job is to block a foreign *existing* target, below.\n if (!target) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)\n if (!targetTenantId || targetTenantId !== actorTenantId) {\n throw new CrudHttpError(404, { error: 'User not found' })\n }\n\n if (input.organizationScope.allowedIds !== null) {\n const targetOrganizationId = normalizeNullableString((target as { organizationId?: string | null }).organizationId)\n if (!targetOrganizationId || !input.organizationScope.allowedIds.includes(targetOrganizationId)) {\n throw forbidden('Not authorized to access this user.')\n }\n }\n}\n\nexport async function assertActorCanAccessRoleTarget(input: SuperAdminRoleTargetInput): Promise<void> {\n const isSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (isSuperAdmin) return\n\n const target = await findOneWithDecryption(\n input.em,\n Role,\n { id: input.targetRoleId } as FilterQuery<Role>,\n {},\n { tenantId: null, organizationId: null },\n )\n // Not found (incl. soft-deleted): delegate (see assertActorCanAccessUserTarget).\n if (!target) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)\n if (!targetTenantId || targetTenantId !== actorTenantId) {\n throw new CrudHttpError(404, { error: 'Role not found' })\n }\n}\n\nasync function resolveActorIsSuperAdmin(input: GrantCheckContext & { actorIsSuperAdmin?: boolean }): Promise<boolean> {\n if (typeof input.actorIsSuperAdmin === 'boolean') return input.actorIsSuperAdmin\n const acl = await loadActorAcl(input)\n return acl.isSuperAdmin\n}\n\n/**\n * Answers \"is this user effectively a super-admin\" about a TARGET \u2014 the input to\n * `assertActorCanModifySuperAdminUserTarget`, not to any authorization decision\n * about the caller.\n *\n * It is bound to the target's OWN tenant (`users.tenant_id`) and to live grant\n * rows, because that is the reading the two authorities already share:\n * `RbacService.isGlobalSuperAdmin` and `lib/sessionIntegrity.ts`\n * (`userAclGrantsSuperAdmin` / `roleAclGrantsSuperAdmin`). A protection\n * predicate that answered differently would protect people who hold nothing \u2014\n * a grant stamped a foreign tenant, or one that was revoked \u2014 while every\n * authorization path treats them as ordinary users. That over-protection does\n * not expire: nothing short of a super-admin could edit such an account again,\n * and revoking someone's super-admin would leave them permanently unmanageable\n * by their own tenant's admins.\n *\n * Two asymmetries with `isGlobalSuperAdmin` are deliberate:\n *\n * - Organization-restricted role grants are NOT excluded. That exclusion only\n * keeps them out of the GLOBAL answer; `loadAcl`'s scoped projection still\n * returns `isSuperAdmin: true` for such a role inside the organizations it\n * names, so its holder is a privileged target. A protection predicate may be\n * a superset of the authorization answer; it must never be a subset.\n * - The `User` load carries no `deletedAt` filter, matching the load in\n * `assertActorCanAccessUserTarget` below. A soft-deleted super-admin stays\n * protected; it is the ACL rows that must be live.\n *\n * \"No user row\" and \"no tenant of their own\" both answer false, as\n * `isGlobalSuperAdmin` does. Neither is exploitable, because every call site\n * pairs this guard with `assertActorCanAccessUserTarget`: that one delegates a\n * missing target to the caller's own tenant-scoped load, and 404s a target\n * whose `tenantId` is absent, so no mutation reaches either case.\n */\nexport async function isUserEffectivelySuperAdmin(em: EntityManager, userId: string): Promise<boolean> {\n const target = await findOneWithDecryption(\n em,\n User,\n { id: userId } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n const tenantId = normalizeNullableString((target as { tenantId?: string | null } | null)?.tenantId)\n if (!tenantId) return false\n const directGrant = await em.findOne(\n UserAcl,\n { user: userId as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<UserAcl>,\n )\n if (directGrant && (directGrant as { isSuperAdmin?: boolean }).isSuperAdmin === true) return true\n const links = await findWithDecryption(\n em,\n UserRole,\n // Roles of the user's own tenant, the same restriction `isGlobalSuperAdmin`\n // applies. The encryption scope stays `{ null, null }`: this is about which\n // rows count, not about which key decrypts them.\n {\n user: userId as unknown,\n deletedAt: null,\n role: { tenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const roleIds = (Array.isArray(links) ? links : [])\n .map((link) => {\n const role = (link as { role?: { id?: unknown } | string | null }).role\n if (!role) return null\n if (typeof role === 'string') return role\n return role.id ? String(role.id) : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n if (!roleIds.length) return false\n const roleGrant = await em.findOne(\n RoleAcl,\n { role: { $in: roleIds } as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<RoleAcl>,\n )\n return !!roleGrant && (roleGrant as { isSuperAdmin?: boolean }).isSuperAdmin === true\n}\n\n/**\n * The role twin of `isUserEffectivelySuperAdmin`, and it carries the same\n * reading for the same reasons: the grant must be live, and it must be stamped\n * with the role's OWN tenant. A `role_acls` row stamped elsewhere confers\n * nothing (`RbacService.loadAcl` reads role ACLs `{ tenantId, deletedAt: null }`),\n * so protecting a role on the strength of one would refuse an edit that every\n * authorization path considers ordinary.\n *\n * A role that does not exist answers false, which its paired guard\n * `assertActorCanAccessRoleTarget` then delegates to the caller in the same way\n * the user side does.\n */\nexport async function isRoleEffectivelySuperAdmin(em: EntityManager, roleId: string): Promise<boolean> {\n const role = await findOneWithDecryption(\n em,\n Role,\n { id: roleId } as FilterQuery<Role>,\n {},\n { tenantId: null, organizationId: null },\n )\n const tenantId = normalizeNullableString((role as { tenantId?: string | null } | null)?.tenantId)\n if (!tenantId) return false\n const grant = await em.findOne(\n RoleAcl,\n { role: roleId as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<RoleAcl>,\n )\n return !!grant && (grant as { isSuperAdmin?: boolean }).isSuperAdmin === true\n}\n\n/**\n * The super-admin user ids a non-super-admin must not be shown while looking at\n * `tenantId` \u2014 an exclusion list, not an authorization answer.\n *\n * `tenantId` names the tenant whose users are being listed. Because a\n * super-admin grant is bound to the holder's own tenant (see\n * `isUserEffectivelySuperAdmin` above and `RbacService.isGlobalSuperAdmin`),\n * that is also the tenant a grant must be stamped with in order to count here,\n * so the filter is applied to BOTH ACL tables. It used to reach only\n * `user_acls`, which made the two halves disagree about what a tenant-scoped\n * answer meant.\n *\n * The narrowing on `role_acls` is only safe TOGETHER with that tenant binding:\n * while a foreign-stamped row still conferred super-admin, dropping it from this\n * list would have unhidden a real one.\n *\n * The caller owes the other half of the scoping. This returns ids; it is the\n * caller's own subject query that must already be restricted to `tenantId`.\n * Both wired call sites are \u2014 `auth/api/users/route.ts` filters the user query\n * by the same tenant, and documents' principals route scopes to `ctx.tenantId`\n * \u2014 so a role member living in another tenant is merely excluded from a list\n * they were never in. That is not licence to pass a tenant unrelated to the\n * subject set.\n *\n * Deliberately NOT narrowed further: organization-restricted role grants count\n * (their holders are super-admins inside those organizations), and the\n * `user_roles` expansion stays tenant-less. Over-inclusion there is bounded by\n * the caller's subject scoping, and for an exclusion list hiding one user too\n * many is the safe direction.\n */\nexport async function listSuperAdminUserIds(em: EntityManager, tenantId: string | null): Promise<Set<string>> {\n const ids = new Set<string>()\n // A revoked override must not keep answering \u2014 the same rule the ACL reads in\n // `RbacService` follow.\n const userAclFilter: Record<string, unknown> = { isSuperAdmin: true, deletedAt: null }\n if (tenantId) userAclFilter.tenantId = tenantId\n const userAcls = await em.find(UserAcl, userAclFilter as FilterQuery<UserAcl>)\n for (const acl of userAcls) {\n const userRef = (acl as { user?: { id?: unknown } | string | null }).user\n const userId = userRef && typeof userRef === 'object'\n ? userRef.id\n : userRef\n if (userId) ids.add(String(userId))\n }\n const roleAclFilter: Record<string, unknown> = { isSuperAdmin: true, deletedAt: null }\n if (tenantId) roleAclFilter.tenantId = tenantId\n const roleAcls = await em.find(RoleAcl, roleAclFilter as FilterQuery<RoleAcl>)\n const roleIds = roleAcls\n .map((acl) => {\n const roleRef = (acl as { role?: { id?: unknown } | string | null }).role\n if (!roleRef) return null\n if (typeof roleRef === 'string') return roleRef\n return roleRef.id ? String(roleRef.id) : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n if (roleIds.length) {\n const links = await findWithDecryption(\n em,\n UserRole,\n {\n deletedAt: null,\n role: { id: { $in: roleIds }, deletedAt: null },\n } as FilterQuery<UserRole>,\n {},\n { tenantId: null, organizationId: null },\n )\n for (const link of Array.isArray(links) ? links : []) {\n const userRef = (link as { user?: { id?: unknown } | string | null }).user\n const userId = userRef && typeof userRef === 'object'\n ? userRef.id\n : userRef\n if (userId) ids.add(String(userId))\n }\n }\n return ids\n}\n\nasync function loadActorAcl(input: GrantCheckContext): Promise<ActorAcl> {\n const actorUserId = normalizeNullableString(input.actorUserId)\n if (!actorUserId) throw forbidden('Not authorized to grant ACL privileges.')\n\n const scope = {\n tenantId: normalizeNullableString(input.tenantId),\n organizationId: normalizeNullableString(input.organizationId),\n }\n const loadBound = input.rbacService.loadAclWithEntityManager\n if (input.requireBoundRbac && typeof loadBound !== 'function') {\n throw new Error('[internal] Transaction-bound RBAC resolution is unavailable')\n }\n const acl = typeof loadBound === 'function'\n ? await loadBound.call(input.rbacService, input.em, actorUserId, scope)\n : await input.rbacService.loadAcl(actorUserId, scope)\n\n return {\n isSuperAdmin: !!acl?.isSuperAdmin,\n features: normalizeStringList(acl?.features),\n organizations: normalizeOrganizationList(acl?.organizations),\n }\n}\n\nasync function resolveRolesForGrant(\n em: EntityManager,\n roleTokens: string[],\n tenantId: string | null,\n): Promise<Role[]> {\n const roles: Role[] = []\n const missingRoles: string[] = []\n\n for (const token of roleTokens) {\n const role = await resolveRoleForGrant(em, token, tenantId)\n if (!role) {\n missingRoles.push(token)\n } else {\n roles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((role) => `\"${role}\"`).join(', ')\n throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })\n }\n\n return roles\n}\n\nasync function resolveRoleForGrant(\n em: EntityManager,\n token: string,\n tenantId: string | null,\n): Promise<Role | null> {\n const where: Record<string, unknown> = UUID_RE.test(token)\n ? { id: token, deletedAt: null }\n : { name: token, deletedAt: null }\n if (tenantId) where.tenantId = tenantId\n return findOneWithDecryption(\n em,\n Role,\n where as FilterQuery<Role>,\n {},\n { tenantId, organizationId: null },\n )\n}\n\nfunction assertActorCanGrantAclSnapshot(\n actorAcl: ActorAcl,\n requested: {\n isSuperAdmin: boolean\n features: string[]\n organizations?: string[] | null\n },\n): void {\n if (requested.isSuperAdmin) {\n throw forbidden('Only super administrators can grant super admin access.')\n }\n\n const actorGrantableFeatures = actorAcl.features.filter((grant) => grant !== '*')\n for (const feature of requested.features) {\n if (feature === '*') {\n throw forbidden('Only super administrators can grant global wildcard access.')\n }\n if (isWildcardFeature(feature)) {\n if (!hasFeature(actorGrantableFeatures, feature)) {\n throw forbidden(`Cannot grant feature wildcard ${feature}.`)\n }\n continue\n }\n if (!hasFeature(actorGrantableFeatures, feature)) {\n throw forbidden(`Cannot grant feature ${feature}.`)\n }\n }\n\n if (requested.organizations !== undefined) {\n assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)\n }\n}\n\nfunction assertActorCanGrantOrganizations(\n actorOrganizations: string[] | null,\n requestedOrganizations: string[] | null,\n): void {\n if (actorOrganizations === null || actorOrganizations.includes('__all__')) return\n\n if (requestedOrganizations === null || requestedOrganizations.includes('__all__')) {\n throw forbidden('Cannot grant unrestricted organization access.')\n }\n\n for (const organizationId of requestedOrganizations) {\n if (!actorOrganizations.includes(organizationId)) {\n throw forbidden('Cannot grant organization access outside actor scope.')\n }\n }\n}\n\nfunction normalizeStringList(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n const dedup = new Set<string>()\n for (const value of values) {\n if (typeof value !== 'string') continue\n const trimmed = value.trim()\n if (!trimmed) continue\n dedup.add(trimmed)\n }\n return Array.from(dedup)\n}\n\nfunction normalizeOrganizationList(values: unknown): string[] | null {\n if (values === null || values === undefined) return null\n return normalizeStringList(values)\n}\n\nfunction normalizeNullableString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\nfunction isWildcardFeature(feature: string): boolean {\n return feature.endsWith('.*')\n}\n\nasync function translateAuthError(key: string, fallback: string): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate(key, fallback)\n}\n"],
5
- "mappings": "AACA,SAAS,YAAY,eAAe,iBAAiB;AACrD,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,2BAA2B;AACpC,SAAS,MAAM,SAAS,MAAM,SAAS,gBAAgB;AA8DvD,MAAM,UAAU;AAEhB,eAAsB,8BAA8B,OAAkD;AACpG,QAAM,SAAS,oBAAoB,MAAM,UAAU;AACnD,MAAI,CAAC,OAAO,OAAQ,QAAO,CAAC;AAE5B,QAAM,WAAW,wBAAwB,MAAM,QAAQ;AACvD,QAAM,QAAQ,MAAM,qBAAqB,MAAM,IAAI,QAAQ,QAAQ;AACnE,QAAM,yBAAyB,EAAE,GAAG,OAAO,UAAU,MAAM,CAAC;AAC5D,SAAO;AACT;AAEA,eAAsB,4BAA4B,OAAmD;AACnG,QAAM,sBAAsB,wBAAwB,MAAM,mBAAmB;AAC7E,MAAI,MAAM,QAAQ,MAAM,UAAU,GAAG;AACnC,WAAO,qBAAqB,MAAM,IAAI,oBAAoB,MAAM,UAAU,GAAG,mBAAmB;AAAA,EAClG;AACA,MAAI,CAAC,MAAM,aAAc,QAAO,CAAC;AAEjC,QAAM,QAAQ,MAAM;AAAA,IAClB,MAAM;AAAA,IACN;AAAA,IACA,EAAE,MAAM,MAAM,aAAgC;AAAA,IAC9C,EAAE,UAAU,CAAC,MAAM,EAAE;AAAA,IACrB,EAAE,UAAU,MAAM,gBAAgB,KAAK;AAAA,EACzC;AACA,QAAM,QAAgB,CAAC;AACvB,aAAW,QAAQ,OAAO;AACxB,UAAM,aAAc,KAAyC;AAC7D,QAAI,cAAc,OAAO,eAAe,UAAU;AAChD,YAAM,KAAK,UAAU;AACrB;AAAA,IACF;AACA,QAAI,OAAO,eAAe,UAAU;AAClC,YAAM,eAAe,MAAM,oBAAoB,MAAM,IAAI,YAAY,IAAI;AACzE,U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mC;AAChF,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,KAAK,QAAQ;AAChC;",
4
+ "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { badRequest, CrudHttpError, forbidden } from '@open-mercato/shared/lib/crud/errors'\nimport { hasFeature } from '@open-mercato/shared/security/features'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { TranslateParams } from '@open-mercato/shared/lib/i18n/context'\nimport { Role, RoleAcl, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'\n\ntype ActorAcl = {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\ntype GrantCheckContext = {\n em: EntityManager\n rbacService: RbacService\n actorUserId: string | null | undefined\n tenantId: string | null | undefined\n organizationId?: string | null | undefined\n requireBoundRbac?: boolean\n}\n\ntype RoleGrantCheckInput = GrantCheckContext & {\n roles: Role[]\n}\n\ntype RoleTokenGrantCheckInput = GrantCheckContext & {\n roleTokens: unknown\n}\n\ntype UserDestinationRolesInput = {\n em: EntityManager\n targetUserId?: string | null\n destinationTenantId: string | null | undefined\n roleTokens: unknown\n}\n\ntype UserDestinationScopeCheckInput = GrantCheckContext & {\n actorIsSuperAdmin?: boolean\n allowedOrganizationIds?: string[] | null\n destinationTenantId: string | null | undefined\n destinationOrganizationId: string | null | undefined\n roles: Role[]\n}\n\ntype FeatureGrantCheckInput = GrantCheckContext & {\n features: unknown\n isSuperAdmin?: boolean\n organizations?: string[] | null\n}\n\ntype SuperAdminUserTargetInput = GrantCheckContext & {\n targetUserId: string\n actorIsSuperAdmin?: boolean\n}\n\ntype UserTargetAccessInput = SuperAdminUserTargetInput & {\n organizationScope: Pick<OrganizationScope, 'allowedIds'>\n}\n\ntype SuperAdminRoleTargetInput = GrantCheckContext & {\n targetRoleId: string\n actorIsSuperAdmin?: boolean\n}\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\nexport async function assertActorCanGrantRoleTokens(input: RoleTokenGrantCheckInput): Promise<Role[]> {\n const tokens = normalizeStringList(input.roleTokens)\n if (!tokens.length) return []\n\n const tenantId = normalizeNullableString(input.tenantId)\n const roles = await resolveRolesForGrant(input.em, tokens, tenantId)\n await assertActorCanGrantRoles({ ...input, tenantId, roles })\n return roles\n}\n\nexport async function resolveUserDestinationRoles(input: UserDestinationRolesInput): Promise<Role[]> {\n const destinationTenantId = normalizeNullableString(input.destinationTenantId)\n if (Array.isArray(input.roleTokens)) {\n return resolveRolesForGrant(input.em, normalizeStringList(input.roleTokens), destinationTenantId)\n }\n if (!input.targetUserId) return []\n\n const links = await findWithDecryption(\n input.em,\n UserRole,\n { user: input.targetUserId as unknown as User } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const roles: Role[] = []\n for (const link of links) {\n const linkedRole = (link as { role?: Role | string | null }).role\n if (linkedRole && typeof linkedRole === 'object') {\n roles.push(linkedRole)\n continue\n }\n if (typeof linkedRole === 'string') {\n const resolvedRole = await resolveRoleForGrant(input.em, linkedRole, null)\n if (resolvedRole) {\n roles.push(resolvedRole)\n continue\n }\n }\n throw badRequest(await translateAuthError(\n 'auth.users.errors.invalidRoleAssignment',\n 'User has an invalid role assignment',\n ))\n }\n return roles\n}\n\nexport async function assertActorCanAssignUserDestination(\n input: UserDestinationScopeCheckInput,\n): Promise<void> {\n const destinationTenantId = normalizeNullableString(input.destinationTenantId)\n const destinationOrganizationId = normalizeNullableString(input.destinationOrganizationId)\n if (!destinationTenantId || !destinationOrganizationId) {\n return throwUserDestinationOrganizationNotFound(400)\n }\n\n for (const role of input.roles) {\n if (normalizeNullableString(role.tenantId) !== destinationTenantId) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.roleOutsideDestinationTenant',\n 'Cannot retain or assign a role outside the destination tenant.',\n ))\n }\n }\n\n if (await resolveActorIsSuperAdmin(input)) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n if (!actorTenantId || actorTenantId !== destinationTenantId) {\n return throwUserDestinationOrganizationNotFound(404)\n }\n\n const actorAcl = await loadActorAcl(input)\n const allowedOrganizationIds = input.allowedOrganizationIds === undefined\n ? actorAcl.organizations\n : input.allowedOrganizationIds\n if (\n allowedOrganizationIds !== null\n && !allowedOrganizationIds.includes('__all__')\n && !allowedOrganizationIds.includes(destinationOrganizationId)\n ) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.destinationOrganizationOutsideScope',\n 'Cannot assign user to a destination organization outside actor scope.',\n ))\n }\n\n await assertActorCanGrantRoles({\n ...input,\n tenantId: destinationTenantId,\n roles: input.roles,\n })\n}\n\nexport async function throwUserDestinationOrganizationNotFound(status: 400 | 404): Promise<never> {\n throw new CrudHttpError(status, {\n error: await translateAuthError(\n 'auth.users.errors.organizationNotFound',\n 'Organization not found',\n ),\n })\n}\n\nexport async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Promise<void> {\n if (!input.roles.length) return\n\n const tenantId = normalizeNullableString(input.tenantId)\n const actorAcl = await loadActorAcl({ ...input, tenantId })\n if (actorAcl.isSuperAdmin) return\n\n if (!tenantId) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.roleGrantTenantRequired',\n 'Tenant context is required to grant roles.',\n ))\n }\n\n for (const role of input.roles) {\n const roleTenantId = normalizeNullableString(role.tenantId)\n if (roleTenantId !== tenantId) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.roleOutsideTargetTenant',\n 'Cannot grant a role outside the target tenant.',\n ))\n }\n\n const acl = await findOneWithDecryption(\n input.em,\n RoleAcl,\n { role, tenantId, deletedAt: null } as FilterQuery<RoleAcl>,\n {},\n { tenantId, organizationId: null },\n )\n if (!acl) continue\n\n await assertActorCanGrantAclSnapshot(actorAcl, {\n isSuperAdmin: !!acl.isSuperAdmin,\n features: normalizeStringList(acl.featuresJson),\n organizations: normalizeOrganizationList(acl.organizationsJson),\n })\n }\n}\n\nexport async function assertActorCanGrantAcl(input: FeatureGrantCheckInput): Promise<void> {\n const actorAcl = await loadActorAcl(input)\n if (actorAcl.isSuperAdmin) return\n\n const tenantId = normalizeNullableString(input.tenantId)\n if (!tenantId) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.aclGrantTenantRequired',\n 'Tenant context is required to grant ACL features.',\n ))\n }\n\n await assertActorCanGrantAclSnapshot(actorAcl, {\n isSuperAdmin: !!input.isSuperAdmin,\n features: normalizeStringList(input.features),\n organizations: input.organizations === undefined ? undefined : normalizeOrganizationList(input.organizations),\n })\n}\n\nexport function normalizeGrantFeatureList(features: unknown): string[] {\n return normalizeStringList(features)\n}\n\nexport async function assertActorCanModifySuperAdminUserTarget(input: SuperAdminUserTargetInput): Promise<void> {\n const actorIsSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (actorIsSuperAdmin) return\n const targetIsSuperAdmin = await isUserEffectivelySuperAdmin(input.em, input.targetUserId)\n if (targetIsSuperAdmin) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.superAdminTargetProtected',\n 'Only super administrators can modify super administrator accounts.',\n ))\n }\n}\n\nexport async function assertActorCanModifySuperAdminRoleTarget(input: SuperAdminRoleTargetInput): Promise<void> {\n const actorIsSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (actorIsSuperAdmin) return\n const targetIsSuperAdmin = await isRoleEffectivelySuperAdmin(input.em, input.targetRoleId)\n if (targetIsSuperAdmin) {\n throw forbidden(await translateAuthError(\n 'auth.roles.errors.superAdminTargetProtected',\n 'Only super administrators can modify super administrator roles.',\n ))\n }\n}\n\n/**\n * `input.tenantId` is the ACTOR's scope, not the target's: the check below is a\n * comparison between the two, so passing a tenant derived from the target turns\n * it into a tautology. Callers that resolve a record scope separately MUST still\n * hand this guard `auth.tenantId`.\n */\nexport async function assertActorCanAccessUserTarget(input: UserTargetAccessInput): Promise<void> {\n const isSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (isSuperAdmin) return\n\n const target = await findOneWithDecryption(\n input.em,\n User,\n { id: input.targetUserId } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n // Not found (incl. soft-deleted, which MikroORM's soft-delete filter hides):\n // delegate to the caller. Every wired call site is itself tenant-scoped \u2014 the\n // ACL/consents reads filter by auth.tenantId and the user commands re-load by\n // id within tenant \u2014 so a missing target yields a safe empty/404 there. The\n // guard's job is to block a foreign *existing* target, below.\n if (!target) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)\n if (!targetTenantId || targetTenantId !== actorTenantId) {\n throw new CrudHttpError(404, { error: await translateAuthError('auth.users.errors.notFound', 'User not found') })\n }\n\n if (input.organizationScope.allowedIds !== null) {\n const targetOrganizationId = normalizeNullableString((target as { organizationId?: string | null }).organizationId)\n if (!targetOrganizationId || !input.organizationScope.allowedIds.includes(targetOrganizationId)) {\n throw forbidden(await translateAuthError(\n 'auth.users.errors.targetAccessDenied',\n 'Not authorized to access this user.',\n ))\n }\n }\n}\n\nexport async function assertActorCanAccessRoleTarget(input: SuperAdminRoleTargetInput): Promise<void> {\n const isSuperAdmin = await resolveActorIsSuperAdmin(input)\n if (isSuperAdmin) return\n\n const target = await findOneWithDecryption(\n input.em,\n Role,\n { id: input.targetRoleId } as FilterQuery<Role>,\n {},\n { tenantId: null, organizationId: null },\n )\n // Not found (incl. soft-deleted): delegate (see assertActorCanAccessUserTarget).\n if (!target) return\n\n const actorTenantId = normalizeNullableString(input.tenantId)\n const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)\n if (!targetTenantId || targetTenantId !== actorTenantId) {\n throw new CrudHttpError(404, { error: await translateAuthError('auth.roles.errors.notFound', 'Role not found') })\n }\n}\n\nasync function resolveActorIsSuperAdmin(input: GrantCheckContext & { actorIsSuperAdmin?: boolean }): Promise<boolean> {\n if (typeof input.actorIsSuperAdmin === 'boolean') return input.actorIsSuperAdmin\n const acl = await loadActorAcl(input)\n return acl.isSuperAdmin\n}\n\n/**\n * Answers \"is this user effectively a super-admin\" about a TARGET \u2014 the input to\n * `assertActorCanModifySuperAdminUserTarget`, not to any authorization decision\n * about the caller.\n *\n * It is bound to the target's OWN tenant (`users.tenant_id`) and to live grant\n * rows, because that is the reading the two authorities already share:\n * `RbacService.isGlobalSuperAdmin` and `lib/sessionIntegrity.ts`\n * (`userAclGrantsSuperAdmin` / `roleAclGrantsSuperAdmin`). A protection\n * predicate that answered differently would protect people who hold nothing \u2014\n * a grant stamped a foreign tenant, or one that was revoked \u2014 while every\n * authorization path treats them as ordinary users. That over-protection does\n * not expire: nothing short of a super-admin could edit such an account again,\n * and revoking someone's super-admin would leave them permanently unmanageable\n * by their own tenant's admins.\n *\n * Two asymmetries with `isGlobalSuperAdmin` are deliberate:\n *\n * - Organization-restricted role grants are NOT excluded. That exclusion only\n * keeps them out of the GLOBAL answer; `loadAcl`'s scoped projection still\n * returns `isSuperAdmin: true` for such a role inside the organizations it\n * names, so its holder is a privileged target. A protection predicate may be\n * a superset of the authorization answer; it must never be a subset.\n * - The `User` load carries no `deletedAt` filter, matching the load in\n * `assertActorCanAccessUserTarget` below. A soft-deleted super-admin stays\n * protected; it is the ACL rows that must be live.\n *\n * \"No user row\" and \"no tenant of their own\" both answer false, as\n * `isGlobalSuperAdmin` does. Neither is exploitable, because every call site\n * pairs this guard with `assertActorCanAccessUserTarget`: that one delegates a\n * missing target to the caller's own tenant-scoped load, and 404s a target\n * whose `tenantId` is absent, so no mutation reaches either case.\n */\nexport async function isUserEffectivelySuperAdmin(em: EntityManager, userId: string): Promise<boolean> {\n const target = await findOneWithDecryption(\n em,\n User,\n { id: userId } as FilterQuery<User>,\n {},\n { tenantId: null, organizationId: null },\n )\n const tenantId = normalizeNullableString((target as { tenantId?: string | null } | null)?.tenantId)\n if (!tenantId) return false\n const directGrant = await em.findOne(\n UserAcl,\n { user: userId as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<UserAcl>,\n )\n if (directGrant && (directGrant as { isSuperAdmin?: boolean }).isSuperAdmin === true) return true\n const links = await findWithDecryption(\n em,\n UserRole,\n // Roles of the user's own tenant, the same restriction `isGlobalSuperAdmin`\n // applies. The encryption scope stays `{ null, null }`: this is about which\n // rows count, not about which key decrypts them.\n {\n user: userId as unknown,\n deletedAt: null,\n role: { tenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const roleIds = (Array.isArray(links) ? links : [])\n .map((link) => {\n const role = (link as { role?: { id?: unknown } | string | null }).role\n if (!role) return null\n if (typeof role === 'string') return role\n return role.id ? String(role.id) : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n if (!roleIds.length) return false\n const roleGrant = await em.findOne(\n RoleAcl,\n { role: { $in: roleIds } as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<RoleAcl>,\n )\n return !!roleGrant && (roleGrant as { isSuperAdmin?: boolean }).isSuperAdmin === true\n}\n\n/**\n * The role twin of `isUserEffectivelySuperAdmin`, and it carries the same\n * reading for the same reasons: the grant must be live, and it must be stamped\n * with the role's OWN tenant. A `role_acls` row stamped elsewhere confers\n * nothing (`RbacService.loadAcl` reads role ACLs `{ tenantId, deletedAt: null }`),\n * so protecting a role on the strength of one would refuse an edit that every\n * authorization path considers ordinary.\n *\n * A role that does not exist answers false, which its paired guard\n * `assertActorCanAccessRoleTarget` then delegates to the caller in the same way\n * the user side does.\n */\nexport async function isRoleEffectivelySuperAdmin(em: EntityManager, roleId: string): Promise<boolean> {\n const role = await findOneWithDecryption(\n em,\n Role,\n { id: roleId } as FilterQuery<Role>,\n {},\n { tenantId: null, organizationId: null },\n )\n const tenantId = normalizeNullableString((role as { tenantId?: string | null } | null)?.tenantId)\n if (!tenantId) return false\n const grant = await em.findOne(\n RoleAcl,\n { role: roleId as unknown, tenantId, isSuperAdmin: true, deletedAt: null } as FilterQuery<RoleAcl>,\n )\n return !!grant && (grant as { isSuperAdmin?: boolean }).isSuperAdmin === true\n}\n\n/**\n * The super-admin user ids a non-super-admin must not be shown while looking at\n * `tenantId` \u2014 an exclusion list, not an authorization answer.\n *\n * `tenantId` names the tenant whose users are being listed. Because a\n * super-admin grant is bound to the holder's own tenant (see\n * `isUserEffectivelySuperAdmin` above and `RbacService.isGlobalSuperAdmin`),\n * that is also the tenant a grant must be stamped with in order to count here,\n * so the filter is applied to BOTH ACL tables. It used to reach only\n * `user_acls`, which made the two halves disagree about what a tenant-scoped\n * answer meant.\n *\n * The narrowing on `role_acls` is only safe TOGETHER with that tenant binding:\n * while a foreign-stamped row still conferred super-admin, dropping it from this\n * list would have unhidden a real one.\n *\n * The caller owes the other half of the scoping. This returns ids; it is the\n * caller's own subject query that must already be restricted to `tenantId`.\n * Both wired call sites are \u2014 `auth/api/users/route.ts` filters the user query\n * by the same tenant, and documents' principals route scopes to `ctx.tenantId`\n * \u2014 so a role member living in another tenant is merely excluded from a list\n * they were never in. That is not licence to pass a tenant unrelated to the\n * subject set.\n *\n * Deliberately NOT narrowed further: organization-restricted role grants count\n * (their holders are super-admins inside those organizations), and the\n * `user_roles` expansion stays tenant-less. Over-inclusion there is bounded by\n * the caller's subject scoping, and for an exclusion list hiding one user too\n * many is the safe direction.\n */\nexport async function listSuperAdminUserIds(em: EntityManager, tenantId: string | null): Promise<Set<string>> {\n const ids = new Set<string>()\n // A revoked override must not keep answering \u2014 the same rule the ACL reads in\n // `RbacService` follow.\n const userAclFilter: Record<string, unknown> = { isSuperAdmin: true, deletedAt: null }\n if (tenantId) userAclFilter.tenantId = tenantId\n const userAcls = await em.find(UserAcl, userAclFilter as FilterQuery<UserAcl>)\n for (const acl of userAcls) {\n const userRef = (acl as { user?: { id?: unknown } | string | null }).user\n const userId = userRef && typeof userRef === 'object'\n ? userRef.id\n : userRef\n if (userId) ids.add(String(userId))\n }\n const roleAclFilter: Record<string, unknown> = { isSuperAdmin: true, deletedAt: null }\n if (tenantId) roleAclFilter.tenantId = tenantId\n const roleAcls = await em.find(RoleAcl, roleAclFilter as FilterQuery<RoleAcl>)\n const roleIds = roleAcls\n .map((acl) => {\n const roleRef = (acl as { role?: { id?: unknown } | string | null }).role\n if (!roleRef) return null\n if (typeof roleRef === 'string') return roleRef\n return roleRef.id ? String(roleRef.id) : null\n })\n .filter((id): id is string => typeof id === 'string' && id.length > 0)\n if (roleIds.length) {\n const links = await findWithDecryption(\n em,\n UserRole,\n {\n deletedAt: null,\n role: { id: { $in: roleIds }, deletedAt: null },\n } as FilterQuery<UserRole>,\n {},\n { tenantId: null, organizationId: null },\n )\n for (const link of Array.isArray(links) ? links : []) {\n const userRef = (link as { user?: { id?: unknown } | string | null }).user\n const userId = userRef && typeof userRef === 'object'\n ? userRef.id\n : userRef\n if (userId) ids.add(String(userId))\n }\n }\n return ids\n}\n\nasync function loadActorAcl(input: GrantCheckContext): Promise<ActorAcl> {\n const actorUserId = normalizeNullableString(input.actorUserId)\n if (!actorUserId) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.actorRequired',\n 'Not authorized to grant ACL privileges.',\n ))\n }\n\n const scope = {\n tenantId: normalizeNullableString(input.tenantId),\n organizationId: normalizeNullableString(input.organizationId),\n }\n const loadBound = input.rbacService.loadAclWithEntityManager\n if (input.requireBoundRbac && typeof loadBound !== 'function') {\n throw new Error('[internal] Transaction-bound RBAC resolution is unavailable')\n }\n const acl = typeof loadBound === 'function'\n ? await loadBound.call(input.rbacService, input.em, actorUserId, scope)\n : await input.rbacService.loadAcl(actorUserId, scope)\n\n return {\n isSuperAdmin: !!acl?.isSuperAdmin,\n features: normalizeStringList(acl?.features),\n organizations: normalizeOrganizationList(acl?.organizations),\n }\n}\n\nasync function resolveRolesForGrant(\n em: EntityManager,\n roleTokens: string[],\n tenantId: string | null,\n): Promise<Role[]> {\n const roles: Role[] = []\n const missingRoles: string[] = []\n\n for (const token of roleTokens) {\n const role = await resolveRoleForGrant(em, token, tenantId)\n if (!role) {\n missingRoles.push(token)\n } else {\n roles.push(role)\n }\n }\n\n if (missingRoles.length) {\n const labels = missingRoles.map((role) => `\"${role}\"`).join(', ')\n throw new CrudHttpError(400, {\n error: await translateAuthError('auth.roles.errors.rolesNotFound', 'Role(s) not found: {roles}', { roles: labels }),\n })\n }\n\n return roles\n}\n\nasync function resolveRoleForGrant(\n em: EntityManager,\n token: string,\n tenantId: string | null,\n): Promise<Role | null> {\n const where: Record<string, unknown> = UUID_RE.test(token)\n ? { id: token, deletedAt: null }\n : { name: token, deletedAt: null }\n if (tenantId) where.tenantId = tenantId\n return findOneWithDecryption(\n em,\n Role,\n where as FilterQuery<Role>,\n {},\n { tenantId, organizationId: null },\n )\n}\n\nasync function assertActorCanGrantAclSnapshot(\n actorAcl: ActorAcl,\n requested: {\n isSuperAdmin: boolean\n features: string[]\n organizations?: string[] | null\n },\n): Promise<void> {\n if (requested.isSuperAdmin) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.superAdminGrantDenied',\n 'Only super administrators can grant super admin access.',\n ))\n }\n\n const actorGrantableFeatures = actorAcl.features.filter((grant) => grant !== '*')\n for (const feature of requested.features) {\n if (feature === '*') {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.globalWildcardGrantDenied',\n 'Only super administrators can grant global wildcard access.',\n ))\n }\n if (isWildcardFeature(feature)) {\n if (!hasFeature(actorGrantableFeatures, feature)) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.featureWildcardGrantDenied',\n 'Cannot grant feature wildcard {feature}.',\n { feature },\n ))\n }\n continue\n }\n if (!hasFeature(actorGrantableFeatures, feature)) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.featureGrantDenied',\n 'Cannot grant feature {feature}.',\n { feature },\n ))\n }\n }\n\n if (requested.organizations !== undefined) {\n await assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)\n }\n}\n\nasync function assertActorCanGrantOrganizations(\n actorOrganizations: string[] | null,\n requestedOrganizations: string[] | null,\n): Promise<void> {\n if (actorOrganizations === null || actorOrganizations.includes('__all__')) return\n\n if (requestedOrganizations === null || requestedOrganizations.includes('__all__')) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.unrestrictedOrganizationsGrantDenied',\n 'Cannot grant unrestricted organization access.',\n ))\n }\n\n for (const organizationId of requestedOrganizations) {\n if (!actorOrganizations.includes(organizationId)) {\n throw forbidden(await translateAuthError(\n 'auth.acl.errors.organizationOutsideScope',\n 'Cannot grant organization access outside actor scope.',\n ))\n }\n }\n}\n\nfunction normalizeStringList(values: unknown): string[] {\n if (!Array.isArray(values)) return []\n const dedup = new Set<string>()\n for (const value of values) {\n if (typeof value !== 'string') continue\n const trimmed = value.trim()\n if (!trimmed) continue\n dedup.add(trimmed)\n }\n return Array.from(dedup)\n}\n\nfunction normalizeOrganizationList(values: unknown): string[] | null {\n if (values === null || values === undefined) return null\n return normalizeStringList(values)\n}\n\nfunction normalizeNullableString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\nfunction isWildcardFeature(feature: string): boolean {\n return feature.endsWith('.*')\n}\n\nasync function translateAuthError(key: string, fallback: string, params?: TranslateParams): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate(key, fallback, params)\n}\n"],
5
+ "mappings": "AACA,SAAS,YAAY,eAAe,iBAAiB;AACrD,SAAS,kBAAkB;AAC3B,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,2BAA2B;AAEpC,SAAS,MAAM,SAAS,MAAM,SAAS,gBAAgB;AA8DvD,MAAM,UAAU;AAEhB,eAAsB,8BAA8B,OAAkD;AACpG,QAAM,SAAS,oBAAoB,MAAM,UAAU;AACnD,MAAI,CAAC,OAAO,OAAQ,QAAO,CAAC;AAE5B,QAAM,WAAW,wBAAwB,MAAM,QA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;AACnC;AAEA,SAAS,wBAAwB,OAA+B;AAC9D,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,SAAS,kBAAkB,SAA0B;AACnD,SAAO,QAAQ,SAAS,IAAI;AAC9B;AAEA,eAAe,mBAAmB,KAAa,UAAkB,QAA2C;AAC1G,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,KAAK,UAAU,MAAM;AACxC;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.10.1-develop.7974.1.c98f9304d9",
3
+ "version": "0.10.1-develop.7975.1.ada24d305c",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -266,16 +266,16 @@
266
266
  "zod": "^4.6.6"
267
267
  },
268
268
  "peerDependencies": {
269
- "@open-mercato/ai-assistant": "0.10.1-develop.7974.1.c98f9304d9",
270
- "@open-mercato/shared": "0.10.1-develop.7974.1.c98f9304d9",
271
- "@open-mercato/ui": "0.10.1-develop.7974.1.c98f9304d9",
269
+ "@open-mercato/ai-assistant": "0.10.1-develop.7975.1.ada24d305c",
270
+ "@open-mercato/shared": "0.10.1-develop.7975.1.ada24d305c",
271
+ "@open-mercato/ui": "0.10.1-develop.7975.1.ada24d305c",
272
272
  "react": "^19.0.0",
273
273
  "react-dom": "^19.0.0"
274
274
  },
275
275
  "devDependencies": {
276
- "@open-mercato/ai-assistant": "0.10.1-develop.7974.1.c98f9304d9",
277
- "@open-mercato/shared": "0.10.1-develop.7974.1.c98f9304d9",
278
- "@open-mercato/ui": "0.10.1-develop.7974.1.c98f9304d9",
276
+ "@open-mercato/ai-assistant": "0.10.1-develop.7975.1.ada24d305c",
277
+ "@open-mercato/shared": "0.10.1-develop.7975.1.ada24d305c",
278
+ "@open-mercato/ui": "0.10.1-develop.7975.1.ada24d305c",
279
279
  "@testing-library/dom": "^10.4.1",
280
280
  "@testing-library/jest-dom": "^7.0.1",
281
281
  "@testing-library/react": "^16.3.3",
@@ -338,7 +338,11 @@ export async function PUT(req: Request) {
338
338
 
339
339
  if (!actorIsSuperAdmin) {
340
340
  if (requestedIsSuperAdmin && !existingIsSuperAdmin) {
341
- throw forbidden('Only super administrators can grant super admin access.')
341
+ const { translate } = await resolveTranslations()
342
+ throw forbidden(translate(
343
+ 'auth.acl.errors.superAdminGrantDenied',
344
+ 'Only super administrators can grant super admin access.',
345
+ ))
342
346
  }
343
347
  if (existingIsSuperAdmin && requestedIsSuperAdmin === false) {
344
348
  effectiveIsSuperAdmin = false
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "\"{dependency}\" wiederherstellen",
14
14
  "auth.acl.deps.orphaned.title": "Entfernung einer Berechtigung, die andere gewährte Berechtigungen benötigen:",
15
15
  "auth.acl.deps.unknown.title": "Einige deklarierte Abhängigkeiten passen zu keiner bekannten Berechtigung:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Zum Vergeben von ACL-Berechtigungen ist ein Mandantenkontext erforderlich.",
17
+ "auth.acl.errors.actorRequired": "Keine Berechtigung zum Vergeben von ACL-Rechten.",
18
+ "auth.acl.errors.featureGrantDenied": "Die Berechtigung {feature} kann nicht vergeben werden.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "Die Platzhalter-Berechtigung {feature} kann nicht vergeben werden.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Nur Superadministratoren können globalen Platzhalterzugriff vergeben.",
21
+ "auth.acl.errors.organizationOutsideScope": "Zugriff auf Organisationen außerhalb Ihres Zugriffsbereichs kann nicht vergeben werden.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Zum Vergeben von Rollen ist ein Mandantenkontext erforderlich.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "Eine Rolle außerhalb des Zielmandanten kann nicht vergeben werden.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Nur Superadministratoren können Superadministrator-Zugriff vergeben.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "Uneingeschränkter Zugriff auf Organisationen kann nicht vergeben werden.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Administrator",
616
626
  "auth.roles.employee": "Mitarbeitende",
617
627
  "auth.roles.errors.nameExists": "Eine Rolle mit diesem Namen existiert bereits",
628
+ "auth.roles.errors.notFound": "Rolle nicht gefunden",
629
+ "auth.roles.errors.rolesNotFound": "Rolle(n) nicht gefunden: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Nur Superadministratoren können Superadministrator-Rollen ändern.",
618
631
  "auth.roles.flash.created": "Rolle erstellt",
619
632
  "auth.roles.flash.deleted": "Rolle gelöscht",
620
633
  "auth.roles.flash.updated": "Rolle gespeichert",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "E-Mail-Adresse wird bereits verwendet",
668
681
  "auth.users.errors.invalidRoleAssignment": "Der Benutzer hat eine ungültige Rollenzuweisung.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "Der letzte aktive Inhaber der Rolle \"{roleName}\" kann nicht entfernt werden",
683
+ "auth.users.errors.notFound": "Benutzer nicht gefunden",
670
684
  "auth.users.errors.organizationNotFound": "Organisation nicht gefunden",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "Eine Rolle außerhalb des Zielmandanten kann weder beibehalten noch zugewiesen werden.",
686
+ "auth.users.errors.superAdminTargetProtected": "Nur Superadministratoren können Superadministrator-Konten ändern.",
687
+ "auth.users.errors.targetAccessDenied": "Keine Berechtigung für den Zugriff auf diesen Benutzer.",
672
688
  "auth.users.flash.created": "Benutzer erstellt",
673
689
  "auth.users.flash.createdEmailFailed": "Benutzer erstellt, aber die Einladungs-E-Mail konnte nicht gesendet werden. Sie können sie über die Benutzerseite erneut senden.",
674
690
  "auth.users.flash.createdWithInvite": "Benutzer erstellt und Einladung gesendet",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "Restore \"{dependency}\"",
14
14
  "auth.acl.deps.orphaned.title": "Removing a permission that other granted permissions need:",
15
15
  "auth.acl.deps.unknown.title": "Some declared dependencies do not match any known permission:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Tenant context is required to grant ACL features.",
17
+ "auth.acl.errors.actorRequired": "Not authorized to grant ACL privileges.",
18
+ "auth.acl.errors.featureGrantDenied": "Cannot grant feature {feature}.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "Cannot grant feature wildcard {feature}.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Only super administrators can grant global wildcard access.",
21
+ "auth.acl.errors.organizationOutsideScope": "Cannot grant organization access outside actor scope.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Tenant context is required to grant roles.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "Cannot grant a role outside the target tenant.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Only super administrators can grant super admin access.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "Cannot grant unrestricted organization access.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Admin",
616
626
  "auth.roles.employee": "Employee",
617
627
  "auth.roles.errors.nameExists": "A role with this name already exists",
628
+ "auth.roles.errors.notFound": "Role not found",
629
+ "auth.roles.errors.rolesNotFound": "Role(s) not found: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Only super administrators can modify super administrator roles.",
618
631
  "auth.roles.flash.created": "Role created",
619
632
  "auth.roles.flash.deleted": "Role deleted",
620
633
  "auth.roles.flash.updated": "Role saved",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "Email already in use",
668
681
  "auth.users.errors.invalidRoleAssignment": "User has an invalid role assignment",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "Cannot remove the last active holder of role \"{roleName}\"",
683
+ "auth.users.errors.notFound": "User not found",
670
684
  "auth.users.errors.organizationNotFound": "Organization not found",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "Cannot retain or assign a role outside the destination tenant.",
686
+ "auth.users.errors.superAdminTargetProtected": "Only super administrators can modify super administrator accounts.",
687
+ "auth.users.errors.targetAccessDenied": "Not authorized to access this user.",
672
688
  "auth.users.flash.created": "User created",
673
689
  "auth.users.flash.createdEmailFailed": "User created but invitation email could not be sent. You can resend it from the user page.",
674
690
  "auth.users.flash.createdWithInvite": "User created and invitation sent",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "Restaurar \"{dependency}\"",
14
14
  "auth.acl.deps.orphaned.title": "Eliminando un permiso que otros permisos otorgados necesitan:",
15
15
  "auth.acl.deps.unknown.title": "Algunas dependencias declaradas no coinciden con ningún permiso conocido:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Se requiere un contexto de tenant para conceder permisos ACL.",
17
+ "auth.acl.errors.actorRequired": "No tienes autorización para conceder privilegios ACL.",
18
+ "auth.acl.errors.featureGrantDenied": "No se puede conceder el permiso {feature}.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "No se puede conceder el permiso comodín {feature}.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Solo los superadministradores pueden conceder acceso comodín global.",
21
+ "auth.acl.errors.organizationOutsideScope": "No se puede conceder acceso a organizaciones fuera de su ámbito de acceso.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Se requiere un contexto de tenant para conceder roles.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "No se puede conceder un rol fuera del tenant de destino.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Solo los superadministradores pueden conceder acceso de superadministrador.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "No se puede conceder acceso ilimitado a organizaciones.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Administrador",
616
626
  "auth.roles.employee": "Empleado",
617
627
  "auth.roles.errors.nameExists": "Ya existe un rol con este nombre",
628
+ "auth.roles.errors.notFound": "Rol no encontrado",
629
+ "auth.roles.errors.rolesNotFound": "Rol(es) no encontrado(s): {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Solo los superadministradores pueden modificar roles de superadministrador.",
618
631
  "auth.roles.flash.created": "Rol creado",
619
632
  "auth.roles.flash.deleted": "Rol eliminado",
620
633
  "auth.roles.flash.updated": "Rol guardado",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "El correo ya está en uso",
668
681
  "auth.users.errors.invalidRoleAssignment": "El usuario tiene una asignación de rol no válida.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "No se puede eliminar al último titular activo del rol \"{roleName}\"",
683
+ "auth.users.errors.notFound": "Usuario no encontrado",
670
684
  "auth.users.errors.organizationNotFound": "Organización no encontrada",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "No se puede conservar ni asignar un rol fuera del tenant de destino.",
686
+ "auth.users.errors.superAdminTargetProtected": "Solo los superadministradores pueden modificar cuentas de superadministrador.",
687
+ "auth.users.errors.targetAccessDenied": "No tienes autorización para acceder a este usuario.",
672
688
  "auth.users.flash.created": "Usuario creado",
673
689
  "auth.users.flash.createdEmailFailed": "Usuario creado pero no se pudo enviar el correo de invitación. Puede reenviarlo desde la página del usuario.",
674
690
  "auth.users.flash.createdWithInvite": "Usuario creado e invitación enviada",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "\"{dependency}\" 복원",
14
14
  "auth.acl.deps.orphaned.title": "다른 부여된 권한에 필요한 권한을 제거하고 있습니다:",
15
15
  "auth.acl.deps.unknown.title": "일부 선언된 종속성이 알려진 권한과 일치하지 않습니다:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "ACL 권한을 부여하려면 테넌트 컨텍스트가 필요합니다.",
17
+ "auth.acl.errors.actorRequired": "ACL 권한을 부여할 권한이 없습니다.",
18
+ "auth.acl.errors.featureGrantDenied": "{feature} 권한을 부여할 수 없습니다.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "와일드카드 권한 {feature}을(를) 부여할 수 없습니다.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "전역 와일드카드 접근 권한은 슈퍼 관리자만 부여할 수 있습니다.",
21
+ "auth.acl.errors.organizationOutsideScope": "접근 범위를 벗어난 조직에 대한 접근 권한을 부여할 수 없습니다.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "역할을 부여하려면 테넌트 컨텍스트가 필요합니다.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "대상 테넌트 외부의 역할을 부여할 수 없습니다.",
24
+ "auth.acl.errors.superAdminGrantDenied": "슈퍼 관리자 접근 권한은 슈퍼 관리자만 부여할 수 있습니다.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "모든 조직에 대한 무제한 접근 권한을 부여할 수 없습니다.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Manage agent presentation settings",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Run agents directly (Playground, evals, diagnostics)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "View agents and runs",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "관리자",
616
626
  "auth.roles.employee": "직원",
617
627
  "auth.roles.errors.nameExists": "이 이름의 역할이 이미 존재합니다",
628
+ "auth.roles.errors.notFound": "역할을 찾을 수 없습니다",
629
+ "auth.roles.errors.rolesNotFound": "역할을 찾을 수 없습니다: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "슈퍼 관리자 역할은 슈퍼 관리자만 수정할 수 있습니다.",
618
631
  "auth.roles.flash.created": "역할이 생성되었습니다",
619
632
  "auth.roles.flash.deleted": "역할이 삭제되었습니다",
620
633
  "auth.roles.flash.updated": "역할이 저장되었습니다",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "이미 사용 중인 이메일입니다",
668
681
  "auth.users.errors.invalidRoleAssignment": "사용자에게 잘못된 역할이 할당되어 있습니다.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "\"{roleName}\" 역할의 마지막 활성 보유자는 제거할 수 없습니다",
683
+ "auth.users.errors.notFound": "사용자를 찾을 수 없습니다",
670
684
  "auth.users.errors.organizationNotFound": "조직을 찾을 수 없습니다",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "대상 테넌트 외부의 역할을 유지하거나 할당할 수 없습니다.",
686
+ "auth.users.errors.superAdminTargetProtected": "슈퍼 관리자 계정은 슈퍼 관리자만 수정할 수 있습니다.",
687
+ "auth.users.errors.targetAccessDenied": "이 사용자에 접근할 권한이 없습니다.",
672
688
  "auth.users.flash.created": "사용자가 생성되었습니다",
673
689
  "auth.users.flash.createdEmailFailed": "사용자가 생성되었지만 초대 이메일을 보낼 수 없었습니다. 사용자 페이지에서 다시 보낼 수 있습니다.",
674
690
  "auth.users.flash.createdWithInvite": "사용자가 생성되고 초대가 전송되었습니다",
@@ -13,6 +13,16 @@
13
13
  "auth.acl.deps.orphaned.restore": "Przywróć \"{dependency}\"",
14
14
  "auth.acl.deps.orphaned.title": "Usuwasz uprawnienie wymagane przez inne przyznane uprawnienia:",
15
15
  "auth.acl.deps.unknown.title": "Niektóre zadeklarowane zależności nie pasują do żadnego znanego uprawnienia:",
16
+ "auth.acl.errors.aclGrantTenantRequired": "Do nadania uprawnień ACL wymagany jest kontekst najemcy.",
17
+ "auth.acl.errors.actorRequired": "Brak uprawnień do nadawania uprawnień ACL.",
18
+ "auth.acl.errors.featureGrantDenied": "Nie można nadać uprawnienia {feature}.",
19
+ "auth.acl.errors.featureWildcardGrantDenied": "Nie można nadać uprawnień z symbolem wieloznacznym {feature}.",
20
+ "auth.acl.errors.globalWildcardGrantDenied": "Tylko superadministratorzy mogą nadać pełny dostęp do wszystkich uprawnień.",
21
+ "auth.acl.errors.organizationOutsideScope": "Nie można nadać dostępu do organizacji spoza Twojego zakresu dostępu.",
22
+ "auth.acl.errors.roleGrantTenantRequired": "Do nadania ról wymagany jest kontekst najemcy.",
23
+ "auth.acl.errors.roleOutsideTargetTenant": "Nie można nadać roli spoza docelowego najemcy.",
24
+ "auth.acl.errors.superAdminGrantDenied": "Tylko superadministratorzy mogą nadać uprawnienia superadministratora.",
25
+ "auth.acl.errors.unrestrictedOrganizationsGrantDenied": "Nie można nadać nieograniczonego dostępu do organizacji.",
16
26
  "auth.acl.features.agent_orchestrator.agents.manage": "Zarządzaj ustawieniami prezentacji agentów",
17
27
  "auth.acl.features.agent_orchestrator.agents.run": "Uruchamiaj agentów bezpośrednio (Playground, ewaluacje, diagnostyka)",
18
28
  "auth.acl.features.agent_orchestrator.agents.view": "Wyświetl agentów i uruchomienia",
@@ -615,6 +625,9 @@
615
625
  "auth.roles.admin": "Administrator",
616
626
  "auth.roles.employee": "Pracownik",
617
627
  "auth.roles.errors.nameExists": "Rola o tej nazwie już istnieje",
628
+ "auth.roles.errors.notFound": "Nie znaleziono roli",
629
+ "auth.roles.errors.rolesNotFound": "Nie znaleziono ról: {roles}",
630
+ "auth.roles.errors.superAdminTargetProtected": "Tylko superadministratorzy mogą modyfikować role superadministratora.",
618
631
  "auth.roles.flash.created": "Rola utworzona",
619
632
  "auth.roles.flash.deleted": "Rola usunięta",
620
633
  "auth.roles.flash.updated": "Rola zapisana",
@@ -667,8 +680,11 @@
667
680
  "auth.users.errors.emailExists": "Adres e-mail jest już używany",
668
681
  "auth.users.errors.invalidRoleAssignment": "Użytkownik ma nieprawidłowo przypisaną rolę.",
669
682
  "auth.users.errors.lastHolderOfCriticalRole": "Nie można usunąć ostatniego aktywnego posiadacza roli \"{roleName}\"",
683
+ "auth.users.errors.notFound": "Nie znaleziono użytkownika",
670
684
  "auth.users.errors.organizationNotFound": "Nie znaleziono organizacji",
671
685
  "auth.users.errors.roleOutsideDestinationTenant": "Nie można zachować ani przypisać roli spoza docelowego tenantu.",
686
+ "auth.users.errors.superAdminTargetProtected": "Tylko superadministratorzy mogą modyfikować konta superadministratorów.",
687
+ "auth.users.errors.targetAccessDenied": "Brak uprawnień do dostępu do tego użytkownika.",
672
688
  "auth.users.flash.created": "Użytkownik utworzony",
673
689
  "auth.users.flash.createdEmailFailed": "Użytkownik utworzony, ale nie udało się wysłać e-maila z zaproszeniem. Możesz wysłać go ponownie ze strony użytkownika.",
674
690
  "auth.users.flash.createdWithInvite": "Użytkownik utworzony i zaproszenie wysłane",
@@ -3,6 +3,7 @@ import { badRequest, CrudHttpError, forbidden } from '@open-mercato/shared/lib/c
3
3
  import { hasFeature } from '@open-mercato/shared/security/features'
4
4
  import { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'
5
5
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
6
+ import type { TranslateParams } from '@open-mercato/shared/lib/i18n/context'
6
7
  import { Role, RoleAcl, User, UserAcl, UserRole } from '@open-mercato/core/modules/auth/data/entities'
7
8
  import type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'
8
9
  import type { OrganizationScope } from '@open-mercato/core/modules/directory/utils/organizationScope'
@@ -177,13 +178,19 @@ export async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Prom
177
178
  if (actorAcl.isSuperAdmin) return
178
179
 
179
180
  if (!tenantId) {
180
- throw forbidden('Tenant context is required to grant roles.')
181
+ throw forbidden(await translateAuthError(
182
+ 'auth.acl.errors.roleGrantTenantRequired',
183
+ 'Tenant context is required to grant roles.',
184
+ ))
181
185
  }
182
186
 
183
187
  for (const role of input.roles) {
184
188
  const roleTenantId = normalizeNullableString(role.tenantId)
185
189
  if (roleTenantId !== tenantId) {
186
- throw forbidden('Cannot grant a role outside the target tenant.')
190
+ throw forbidden(await translateAuthError(
191
+ 'auth.acl.errors.roleOutsideTargetTenant',
192
+ 'Cannot grant a role outside the target tenant.',
193
+ ))
187
194
  }
188
195
 
189
196
  const acl = await findOneWithDecryption(
@@ -195,7 +202,7 @@ export async function assertActorCanGrantRoles(input: RoleGrantCheckInput): Prom
195
202
  )
196
203
  if (!acl) continue
197
204
 
198
- assertActorCanGrantAclSnapshot(actorAcl, {
205
+ await assertActorCanGrantAclSnapshot(actorAcl, {
199
206
  isSuperAdmin: !!acl.isSuperAdmin,
200
207
  features: normalizeStringList(acl.featuresJson),
201
208
  organizations: normalizeOrganizationList(acl.organizationsJson),
@@ -209,10 +216,13 @@ export async function assertActorCanGrantAcl(input: FeatureGrantCheckInput): Pro
209
216
 
210
217
  const tenantId = normalizeNullableString(input.tenantId)
211
218
  if (!tenantId) {
212
- throw forbidden('Tenant context is required to grant ACL features.')
219
+ throw forbidden(await translateAuthError(
220
+ 'auth.acl.errors.aclGrantTenantRequired',
221
+ 'Tenant context is required to grant ACL features.',
222
+ ))
213
223
  }
214
224
 
215
- assertActorCanGrantAclSnapshot(actorAcl, {
225
+ await assertActorCanGrantAclSnapshot(actorAcl, {
216
226
  isSuperAdmin: !!input.isSuperAdmin,
217
227
  features: normalizeStringList(input.features),
218
228
  organizations: input.organizations === undefined ? undefined : normalizeOrganizationList(input.organizations),
@@ -228,7 +238,10 @@ export async function assertActorCanModifySuperAdminUserTarget(input: SuperAdmin
228
238
  if (actorIsSuperAdmin) return
229
239
  const targetIsSuperAdmin = await isUserEffectivelySuperAdmin(input.em, input.targetUserId)
230
240
  if (targetIsSuperAdmin) {
231
- throw forbidden('Only super administrators can modify super administrator accounts.')
241
+ throw forbidden(await translateAuthError(
242
+ 'auth.users.errors.superAdminTargetProtected',
243
+ 'Only super administrators can modify super administrator accounts.',
244
+ ))
232
245
  }
233
246
  }
234
247
 
@@ -237,7 +250,10 @@ export async function assertActorCanModifySuperAdminRoleTarget(input: SuperAdmin
237
250
  if (actorIsSuperAdmin) return
238
251
  const targetIsSuperAdmin = await isRoleEffectivelySuperAdmin(input.em, input.targetRoleId)
239
252
  if (targetIsSuperAdmin) {
240
- throw forbidden('Only super administrators can modify super administrator roles.')
253
+ throw forbidden(await translateAuthError(
254
+ 'auth.roles.errors.superAdminTargetProtected',
255
+ 'Only super administrators can modify super administrator roles.',
256
+ ))
241
257
  }
242
258
  }
243
259
 
@@ -268,13 +284,16 @@ export async function assertActorCanAccessUserTarget(input: UserTargetAccessInpu
268
284
  const actorTenantId = normalizeNullableString(input.tenantId)
269
285
  const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)
270
286
  if (!targetTenantId || targetTenantId !== actorTenantId) {
271
- throw new CrudHttpError(404, { error: 'User not found' })
287
+ throw new CrudHttpError(404, { error: await translateAuthError('auth.users.errors.notFound', 'User not found') })
272
288
  }
273
289
 
274
290
  if (input.organizationScope.allowedIds !== null) {
275
291
  const targetOrganizationId = normalizeNullableString((target as { organizationId?: string | null }).organizationId)
276
292
  if (!targetOrganizationId || !input.organizationScope.allowedIds.includes(targetOrganizationId)) {
277
- throw forbidden('Not authorized to access this user.')
293
+ throw forbidden(await translateAuthError(
294
+ 'auth.users.errors.targetAccessDenied',
295
+ 'Not authorized to access this user.',
296
+ ))
278
297
  }
279
298
  }
280
299
  }
@@ -296,7 +315,7 @@ export async function assertActorCanAccessRoleTarget(input: SuperAdminRoleTarget
296
315
  const actorTenantId = normalizeNullableString(input.tenantId)
297
316
  const targetTenantId = normalizeNullableString((target as { tenantId?: string | null }).tenantId)
298
317
  if (!targetTenantId || targetTenantId !== actorTenantId) {
299
- throw new CrudHttpError(404, { error: 'Role not found' })
318
+ throw new CrudHttpError(404, { error: await translateAuthError('auth.roles.errors.notFound', 'Role not found') })
300
319
  }
301
320
  }
302
321
 
@@ -492,7 +511,12 @@ export async function listSuperAdminUserIds(em: EntityManager, tenantId: string
492
511
 
493
512
  async function loadActorAcl(input: GrantCheckContext): Promise<ActorAcl> {
494
513
  const actorUserId = normalizeNullableString(input.actorUserId)
495
- if (!actorUserId) throw forbidden('Not authorized to grant ACL privileges.')
514
+ if (!actorUserId) {
515
+ throw forbidden(await translateAuthError(
516
+ 'auth.acl.errors.actorRequired',
517
+ 'Not authorized to grant ACL privileges.',
518
+ ))
519
+ }
496
520
 
497
521
  const scope = {
498
522
  tenantId: normalizeNullableString(input.tenantId),
@@ -532,7 +556,9 @@ async function resolveRolesForGrant(
532
556
 
533
557
  if (missingRoles.length) {
534
558
  const labels = missingRoles.map((role) => `"${role}"`).join(', ')
535
- throw new CrudHttpError(400, { error: `Role(s) not found: ${labels}` })
559
+ throw new CrudHttpError(400, {
560
+ error: await translateAuthError('auth.roles.errors.rolesNotFound', 'Role(s) not found: {roles}', { roles: labels }),
561
+ })
536
562
  }
537
563
 
538
564
  return roles
@@ -556,52 +582,72 @@ async function resolveRoleForGrant(
556
582
  )
557
583
  }
558
584
 
559
- function assertActorCanGrantAclSnapshot(
585
+ async function assertActorCanGrantAclSnapshot(
560
586
  actorAcl: ActorAcl,
561
587
  requested: {
562
588
  isSuperAdmin: boolean
563
589
  features: string[]
564
590
  organizations?: string[] | null
565
591
  },
566
- ): void {
592
+ ): Promise<void> {
567
593
  if (requested.isSuperAdmin) {
568
- throw forbidden('Only super administrators can grant super admin access.')
594
+ throw forbidden(await translateAuthError(
595
+ 'auth.acl.errors.superAdminGrantDenied',
596
+ 'Only super administrators can grant super admin access.',
597
+ ))
569
598
  }
570
599
 
571
600
  const actorGrantableFeatures = actorAcl.features.filter((grant) => grant !== '*')
572
601
  for (const feature of requested.features) {
573
602
  if (feature === '*') {
574
- throw forbidden('Only super administrators can grant global wildcard access.')
603
+ throw forbidden(await translateAuthError(
604
+ 'auth.acl.errors.globalWildcardGrantDenied',
605
+ 'Only super administrators can grant global wildcard access.',
606
+ ))
575
607
  }
576
608
  if (isWildcardFeature(feature)) {
577
609
  if (!hasFeature(actorGrantableFeatures, feature)) {
578
- throw forbidden(`Cannot grant feature wildcard ${feature}.`)
610
+ throw forbidden(await translateAuthError(
611
+ 'auth.acl.errors.featureWildcardGrantDenied',
612
+ 'Cannot grant feature wildcard {feature}.',
613
+ { feature },
614
+ ))
579
615
  }
580
616
  continue
581
617
  }
582
618
  if (!hasFeature(actorGrantableFeatures, feature)) {
583
- throw forbidden(`Cannot grant feature ${feature}.`)
619
+ throw forbidden(await translateAuthError(
620
+ 'auth.acl.errors.featureGrantDenied',
621
+ 'Cannot grant feature {feature}.',
622
+ { feature },
623
+ ))
584
624
  }
585
625
  }
586
626
 
587
627
  if (requested.organizations !== undefined) {
588
- assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)
628
+ await assertActorCanGrantOrganizations(actorAcl.organizations, requested.organizations)
589
629
  }
590
630
  }
591
631
 
592
- function assertActorCanGrantOrganizations(
632
+ async function assertActorCanGrantOrganizations(
593
633
  actorOrganizations: string[] | null,
594
634
  requestedOrganizations: string[] | null,
595
- ): void {
635
+ ): Promise<void> {
596
636
  if (actorOrganizations === null || actorOrganizations.includes('__all__')) return
597
637
 
598
638
  if (requestedOrganizations === null || requestedOrganizations.includes('__all__')) {
599
- throw forbidden('Cannot grant unrestricted organization access.')
639
+ throw forbidden(await translateAuthError(
640
+ 'auth.acl.errors.unrestrictedOrganizationsGrantDenied',
641
+ 'Cannot grant unrestricted organization access.',
642
+ ))
600
643
  }
601
644
 
602
645
  for (const organizationId of requestedOrganizations) {
603
646
  if (!actorOrganizations.includes(organizationId)) {
604
- throw forbidden('Cannot grant organization access outside actor scope.')
647
+ throw forbidden(await translateAuthError(
648
+ 'auth.acl.errors.organizationOutsideScope',
649
+ 'Cannot grant organization access outside actor scope.',
650
+ ))
605
651
  }
606
652
  }
607
653
  }
@@ -631,7 +677,7 @@ function isWildcardFeature(feature: string): boolean {
631
677
  return feature.endsWith('.*')
632
678
  }
633
679
 
634
- async function translateAuthError(key: string, fallback: string): Promise<string> {
680
+ async function translateAuthError(key: string, fallback: string, params?: TranslateParams): Promise<string> {
635
681
  const { translate } = await resolveTranslations()
636
- return translate(key, fallback)
682
+ return translate(key, fallback, params)
637
683
  }