@open-mercato/core 0.10.1-develop.7974.1.c98f9304d9 → 0.10.1-develop.7976.1.c0ee1c7c28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modules/auth/api/users/acl/route.js +5 -1
- package/dist/modules/auth/api/users/acl/route.js.map +2 -2
- package/dist/modules/auth/lib/grantChecks.js +68 -23
- package/dist/modules/auth/lib/grantChecks.js.map +2 -2
- package/dist/modules/customers/commands/personCompanyLinks.js +101 -6
- package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/api/users/acl/route.ts +5 -1
- package/src/modules/auth/i18n/de.json +16 -0
- package/src/modules/auth/i18n/en.json +16 -0
- package/src/modules/auth/i18n/es.json +16 -0
- package/src/modules/auth/i18n/ko.json +16 -0
- package/src/modules/auth/i18n/pl.json +16 -0
- package/src/modules/auth/lib/grantChecks.ts +71 -25
- package/src/modules/customers/commands/personCompanyLinks.ts +132 -7
|
@@ -240,7 +240,11 @@ async function PUT(req) {
|
|
|
240
240
|
let effectiveIsSuperAdmin = requestedIsSuperAdmin;
|
|
241
241
|
if (!actorIsSuperAdmin) {
|
|
242
242
|
if (requestedIsSuperAdmin && !existingIsSuperAdmin) {
|
|
243
|
-
|
|
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,SA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B,MAAM,0BAA0B,IAAI,YAAY,IAAI,CAAC;AAC9E,QAAM,wBAAwB,MAAM,uBAAuB,IAAI,iBAAiB,IAAI;AAMpF,QAAM,uBAAuB,OAAO,KAAK,aAAa;AACtD,QAAM,oBAAoB,uBACtB,0BAA0B,OAAO,KAAK,QAAQ,IAC9C;AACJ,QAAM,yBAAyB,OAAO,KAAK,kBAAkB,SACzD,wBACA,uBAAuB,OAAO,KAAK,aAAa;AAEpD,QAAM,wBAAwB,OAAO,KAAK,gBAAgB;AAE1D,MAAI;AACF,UAAM,uBAAuB;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,aAAa,KAAK;AAAA,MAClB,UAAU;AAAA,MACV,gBAAgB,KAAK,SAAS;AAAA,MAC9B,cAAc;AAAA,MACd,UAAU;AAAA,MACV,eAAe;AAAA,IACjB,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,EAAG,QAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AACnF,UAAM;AAAA,EACR;AAKA,QAAM,oBAAoB,qBAAqB,CAAC,uBAC5C,oBACA,uBAAuB,iBAAiB;AAE5C,MAAI,wBAAwB;AAE5B,MAAI,CAAC,mBAAmB;AACtB,QAAI,yBAAyB,CAAC,sBAAsB;AAClD,YAAM,UAAU,
|
|
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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C,QAAM,cAAc,IAAI,IAAI,QAAQ;AAEpC,MAAI,aAAa,SAAS,YAAY,MAAM;AAC1C,QAAI,YAAY;AAChB,eAAW,SAAS,cAAc;AAChC,UAAI,CAAC,YAAY,IAAI,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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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)
|
|
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, {
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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,I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eAAe,mBAAmB,KAAa,UAAmC;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,CAA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