@open-mercato/core 0.10.1-develop.7767.1.440f7c2b4c → 0.10.1-develop.7768.1.90fa052c11
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/api_keys/data/entities.js.map +1 -1
- package/dist/modules/api_keys/services/apiKeyService.js +1 -0
- package/dist/modules/api_keys/services/apiKeyService.js.map +2 -2
- package/dist/modules/auth/lib/authorizationStateLocks.js +13 -5
- package/dist/modules/auth/lib/authorizationStateLocks.js.map +2 -2
- package/dist/modules/auth/services/rbacService.js +68 -11
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +6 -3
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/api_keys/data/entities.ts +1 -1
- package/src/modules/api_keys/services/apiKeyService.ts +2 -0
- package/src/modules/auth/lib/authorizationStateLocks.ts +13 -7
- package/src/modules/auth/services/rbacService.ts +86 -9
- package/src/modules/directory/utils/organizationScope.ts +6 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/auth/services/rbacService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { getCurrentCacheTenant, runWithCacheTenant } from '@open-mercato/cache'\nimport { UserAcl, RoleAcl, Role, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { isSessionBoundApiKey, resolveApiKeyRoleIds } from '@open-mercato/core/modules/api_keys/services/sessionKeyRoles'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport { buildOrgScopeUserCacheTag, buildOrgScopeTenantCacheTag } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n authorizeFeatures,\n resolveEffectiveFeatures,\n} from '@open-mercato/shared/security/featurePolicy'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport { resolveRoleOrganizationScope, roleAclAllowsOrganization } from './roleOrganizationScope'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth.rbac')\n\ninterface AclData {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\nasync function resolveRoleOrganizationScopeWithEntityManager(\n em: EntityManager,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<ReadonlySet<string> | null> {\n if (!organizationId) return null\n if (!tenantId) return new Set()\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null } as FilterQuery<Organization>,\n { fields: ['id', 'ancestorIds'] },\n { tenantId, organizationId },\n )\n if (!organization) return new Set()\n const ancestors = Array.isArray(organization.ancestorIds)\n ? organization.ancestorIds.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n return new Set([organizationId, ...ancestors])\n}\n\nfunction isAclData(value: unknown): value is AclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<AclData>\n if (typeof record.isSuperAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((feature) => typeof feature !== 'string')) return false\n if (record.organizations !== null && record.organizations !== undefined) {\n if (!Array.isArray(record.organizations)) return false\n if (record.organizations.some((org) => typeof org !== 'string')) return false\n }\n return true\n}\n\nfunction isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n return Array.isArray(acl.organizationsJson)\n && acl.organizationsJson.length > 0\n && !acl.organizationsJson.includes('__all__')\n}\n\ntype FeatureOrganizationCandidate = {\n id: string\n ancestorIds?: readonly string[] | null\n}\n\ntype FeatureOrganizationAccess = {\n unrestricted: boolean\n filterOrganizationIds: (organizations: readonly FeatureOrganizationCandidate[]) => string[]\n}\n\ntype FeatureOrganizationRoleGrant = {\n isSuperAdmin: boolean\n featuresJson: string[] | null\n organizationsJson: string[] | null\n}\n\ntype FeatureOrganizationGrants =\n | { kind: 'none' }\n | { kind: 'api_key'; organizationId: string | null; roleGrants: FeatureOrganizationRoleGrant[] }\n | { kind: 'user_acl'; isSuperAdmin: boolean; features: string[]; organizations: string[] | null }\n | { kind: 'roles'; roleGrants: FeatureOrganizationRoleGrant[] }\n\nfunction isStringListOrNull(value: unknown): value is string[] | null {\n return value === null || (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n}\n\nfunction isFeatureOrganizationRoleGrant(value: unknown): value is FeatureOrganizationRoleGrant {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<FeatureOrganizationRoleGrant>\n return typeof record.isSuperAdmin === 'boolean'\n && isStringListOrNull(record.featuresJson)\n && isStringListOrNull(record.organizationsJson)\n}\n\nfunction isFeatureOrganizationGrants(value: unknown): value is FeatureOrganizationGrants {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n switch (record.kind) {\n case 'none':\n return true\n case 'api_key':\n return (record.organizationId === null || typeof record.organizationId === 'string')\n && Array.isArray(record.roleGrants)\n && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n case 'user_acl':\n return typeof record.isSuperAdmin === 'boolean'\n && Array.isArray(record.features)\n && record.features.every((feature) => typeof feature === 'string')\n && isStringListOrNull(record.organizations)\n case 'roles':\n return Array.isArray(record.roleGrants) && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n default:\n return false\n }\n}\n\nfunction toFeatureOrganizationRoleGrant(\n acl: Pick<RoleAcl, 'isSuperAdmin' | 'featuresJson' | 'organizationsJson'>,\n): FeatureOrganizationRoleGrant {\n return {\n isSuperAdmin: acl.isSuperAdmin === true,\n featuresJson: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n organizationsJson: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }\n}\n\nfunction normalizeFeatureOrganizationCandidates(\n organizations: readonly FeatureOrganizationCandidate[],\n): FeatureOrganizationCandidate[] {\n const normalized = new Map<string, FeatureOrganizationCandidate>()\n for (const organization of organizations) {\n const id = typeof organization.id === 'string' ? organization.id.trim() : ''\n if (!id || normalized.has(id)) continue\n const ancestorIds = Array.isArray(organization.ancestorIds)\n ? Array.from(new Set(organization.ancestorIds\n .map((ancestorId) => typeof ancestorId === 'string' ? ancestorId.trim() : '')\n .filter(Boolean)))\n : []\n normalized.set(id, { id, ancestorIds })\n }\n return Array.from(normalized.values())\n}\n\nfunction buildFeatureOrganizationScope(\n organization: FeatureOrganizationCandidate,\n): ReadonlySet<string> {\n return new Set([organization.id, ...(organization.ancestorIds ?? [])])\n}\n\nfunction roleAclProvidesGlobalFeatureScope(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n return !organizations || organizations.length === 0 || organizations.includes('__all__')\n}\n\nfunction roleAclProvidesGlobalVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n return emptyOrganizationsAreUnrestricted && organizations.length === 0\n}\n\nfunction roleAclProvidesOrganizationVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n organizationScope: ReadonlySet<string>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n if (organizations.length === 0) return emptyOrganizationsAreUnrestricted\n return organizations.some((organizationId) => organizationScope.has(organizationId))\n}\n\nfunction roleAclsAuthorizeFeatures(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n organization: FeatureOrganizationCandidate,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizationScope = buildFeatureOrganizationScope(organization)\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesOrganizationVisibility(acl, organizationScope, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclAllowsOrganization(acl, organizationScope)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nfunction roleAclsAuthorizeFeaturesGlobally(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesGlobalVisibility(acl, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclProvidesGlobalFeatureScope(acl)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nexport class RbacService {\n private cacheTtlMs: number = 5 * 60 * 1000 // 5 minutes default\n private cache: CacheStrategy | null = null\n private globalSuperAdminCache = new Map<string, boolean>()\n\n constructor(\n private em: EntityManager,\n cache?: CacheStrategy,\n private readonly organizationHierarchyService?: OrganizationHierarchyService,\n ) {\n this.cache = cache || null\n }\n\n /**\n * Set cache TTL in milliseconds\n * @param ttlMs - Time to live in milliseconds\n */\n setCacheTtl(ttlMs: number) {\n this.cacheTtlMs = ttlMs\n }\n\n /** Compatibility wrapper for callers that already have both feature lists. */\n public hasAllFeatures(required: string[], granted: string[]): boolean {\n return authorizeFeatures(required, { grantedFeatures: granted })\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string {\n return `rbac:${userId}:${scope.tenantId || 'null'}:${scope.organizationId || 'null'}`\n }\n\n private getUserTag(userId: string): string {\n return `rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `rbac:tenant:${tenantId}`\n }\n\n private getOrganizationTag(organizationId: string): string {\n return `rbac:org:${organizationId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<AclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isAclData(cached) ? cached : null\n }\n\n private async setCache(cacheKey: string, data: AclData, userId: string, scope: { tenantId: string | null; organizationId: string | null }): Promise<void> {\n if (!this.cache) return\n\n await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, scope),\n })\n }\n\n private buildCacheTags(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string[] {\n const tags = [\n this.getUserTag(userId),\n 'rbac:all'\n ]\n\n if (scope.tenantId) {\n tags.push(this.getTenantTag(scope.tenantId))\n // Scoped role projections depend on the selected organization's ancestor\n // chain, so Directory hierarchy changes must evict them as well as the\n // separately cached OrganizationScope entries.\n tags.push(buildOrgScopeTenantCacheTag(scope.tenantId))\n }\n\n if (scope.organizationId) {\n tags.push(this.getOrganizationTag(scope.organizationId))\n }\n\n return tags\n }\n\n /**\n * Invalidates cached ACL data for a specific user across all tenants and organizations.\n * Call this when a user's roles or user-specific ACL is modified.\n * \n * @param userId - The ID of the user whose cache should be invalidated\n */\n async invalidateUserCache(userId: string): Promise<void> {\n this.globalSuperAdminCache.delete(userId)\n // Also drop the directory OrganizationScope cache for this user. That scope's\n // accessible-org set is derived from this user's ACL/role grants, so any\n // permission change that invalidates the RBAC cache must invalidate the\n // resolved scope too. This is the missing `org-scope:user:*` caller required\n // before the cross-request scope TTL can be safely enabled (issue #2259).\n await this.deleteCacheByTags([this.getUserTag(userId), buildOrgScopeUserCacheTag(userId)])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific tenant.\n * Call this when a role's ACL is modified, since roles are tenant-scoped\n * and affect all users in that tenant who have that role.\n * \n * @param tenantId - The ID of the tenant whose cache should be invalidated\n */\n async invalidateTenantCache(tenantId: string): Promise<void> {\n this.globalSuperAdminCache.clear()\n // Role ACL changes invalidate every user in the tenant; the resolved\n // OrganizationScope for those users derives from the same grants, so drop\n // the tenant-tagged scope entries alongside the RBAC ones (issue #2259).\n await this.deleteCacheByTags([this.getTenantTag(tenantId), buildOrgScopeTenantCacheTag(tenantId)], [tenantId])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific organization.\n * Call this when organization-level permissions or visibility changes.\n * \n * @param organizationId - The ID of the organization whose cache should be invalidated\n */\n async invalidateOrganizationCache(organizationId: string): Promise<void> {\n await this.deleteCacheByTags([this.getOrganizationTag(organizationId)])\n }\n\n /**\n * Clears all cached ACL data.\n * Use this for bulk operations or system-wide ACL changes.\n */\n async invalidateAllCache(): Promise<void> {\n this.globalSuperAdminCache.clear()\n await this.deleteCacheByTags(['rbac:all'])\n }\n\n private async deleteCacheByTags(tags: string[], tenantHints?: Array<string | null>): Promise<void> {\n if (!this.cache) return\n const contexts = new Set<string | null>()\n const current = getCurrentCacheTenant()\n contexts.add(current ?? null)\n contexts.add(null)\n if (Array.isArray(tenantHints)) {\n for (const hint of tenantHints) {\n contexts.add(hint ?? null)\n }\n }\n for (const ctx of contexts) {\n if (ctx === current) {\n await this.cache.deleteByTags(tags)\n } else {\n await runWithCacheTenant(ctx, async () => {\n await this.cache!.deleteByTags(tags)\n })\n }\n }\n }\n\n // A super-admin grant is deliberately GLOBAL: it survives every scope the\n // caller asks about, which is what lets a platform super-admin work inside a\n // customer tenant. What it must not do is survive the question of whose grant\n // it is. Both lookups below are therefore evaluated against the user's OWN\n // tenant (`users.tenant_id`), never against no tenant at all.\n //\n // Without that binding a single `user_acls` row \u2014 or a role link \u2014 stamped\n // with ANY tenant confers platform super-admin everywhere, so a row written\n // under the wrong tenant becomes a full privilege escalation with nothing in\n // the schema or the UI to show for it. `user_acls` has no organization column\n // and no uniqueness beyond its primary key, so such a row is cheap to create\n // and invisible to the tenant/organization cross-wire checks.\n //\n // This is the tenant binding `resolveCanonicalStaffAuthContext` already\n // applies when it computes `auth.isSuperAdmin` (see lib/sessionIntegrity.ts:\n // `userAclGrantsSuperAdmin` / `roleAclGrantsSuperAdmin`, both bound to the\n // user's own tenant). Before this change the two authorities disagreed:\n // session integrity would say \"not a super-admin\" while `loadAcl` handed the\n // same request `['*']`.\n //\n // The memo stays keyed by `userId` alone because the answer now depends only\n // on the user's own tenant, which is a property of the user \u2014 not on the scope\n // being asked about. `invalidateUserCache` therefore still clears it correctly.\n private async isGlobalSuperAdmin(\n em: EntityManager,\n userId: string,\n userTenantId: string | null,\n useCache = true,\n ): Promise<boolean> {\n if (useCache && this.globalSuperAdminCache.has(userId)) return this.globalSuperAdminCache.get(userId)!\n if (!userTenantId) {\n logger.warn('Tenant-less principal cannot receive super-admin grants; assign an owning tenant before upgrading', { userId })\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const userSuper = await em.findOne(UserAcl, {\n user: userId as unknown as User,\n tenantId: userTenantId,\n isSuperAdmin: true,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\n if (userSuper?.isSuperAdmin) {\n if (useCache) this.globalSuperAdminCache.set(userId, true)\n return true\n }\n const links = await findWithDecryption(\n em,\n UserRole,\n // Roles that belong to the user's own tenant, as\n // `resolveCanonicalStaffAuthContext` already requires. The encryption\n // scope stays `{ null, null }` as before \u2014 this change is about which rows\n // count, not about which key decrypts them.\n {\n user: userId as unknown as User,\n deletedAt: null,\n role: { tenantId: userTenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const linkList = Array.isArray(links) ? links : []\n if (!linkList.length) {\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleIds = Array.from(new Set(linkList.map((link) => {\n const role = link.role\n return role?.id ? String(role.id) : null\n }).filter((id): id is string => typeof id === 'string' && id.length > 0)))\n if (!roleIds.length) {\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleSupers = await em.find(RoleAcl, {\n isSuperAdmin: true,\n tenantId: userTenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[] },\n } as FilterQuery<RoleAcl>)\n const result = roleSupers.some((roleAcl) => (\n !!roleAcl.isSuperAdmin && !isRestrictedRoleAcl(roleAcl)\n ))\n if (useCache) this.globalSuperAdminCache.set(userId, result)\n return result\n }\n\n /**\n * Loads the Access Control List (ACL) for a user within a given scope.\n * \n * The ACL resolution follows this priority:\n * 1. Per-user ACL (UserAcl) - if exists, use it exclusively\n * 2. Aggregated role ACLs (RoleAcl) - combine permissions from all user's roles\n * \n * Results are cached for performance (default 5 minutes TTL).\n * Cache is automatically invalidated when ACL-related data changes.\n * \n * @param userId - The ID of the user\n * @param scope - The tenant and organization context for ACL evaluation\n * @returns An object containing:\n * - isSuperAdmin: If true, user has unrestricted access to all features\n * - features: Array of feature strings (may include wildcards like 'entities.*')\n * - organizations: Array of organization IDs user can access, or null for all organizations\n * \n * @example\n * const acl = await rbacService.loadAcl('user-123', { tenantId: 'tenant-1', organizationId: 'org-1' })\n * // Returns: { isSuperAdmin: false, features: ['users.view', 'entities.*'], organizations: ['org-1', 'org-2'] }\n */\n async loadAcl(userId: string, scope: { tenantId: string | null; organizationId: string | null }): Promise<{\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n }> {\n const cacheKey = this.getCacheKey(userId, scope)\n const cached = userId.startsWith('api_key:') ? null : await this.getFromCache(cacheKey)\n if (cached) return cached\n\n if (userId.startsWith('api_key:')) {\n const apiKeyId = userId.slice('api_key:'.length)\n const em = this.em.fork()\n const key = await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n if (!key || (key.expiresAt && key.expiresAt.getTime() < Date.now())) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n const cacheable = !isSessionBoundApiKey(key)\n if (cacheable) {\n const cachedKeyAcl = await this.getFromCache(cacheKey)\n if (cachedKeyAcl) return cachedKeyAcl\n }\n const tenantId = scope.tenantId || key.tenantId || null\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n const evaluatedOrganizationId = scope.organizationId || keyOrganizationId\n let isSuper = false\n const features: string[] = []\n let roleOrganizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n if (tenantId && roleIds.length) {\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n evaluatedOrganizationId,\n )\n const racls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[], deletedAt: null },\n } as FilterQuery<RoleAcl>)\n for (const acl of racls) {\n if (roleAclAllowsOrganization(acl, roleOrganizationScope)) {\n isSuper = isSuper || !!acl.isSuperAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) if (!features.includes(f)) features.push(f)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (roleOrganizations !== null) {\n if (acl.organizationsJson == null || (Array.isArray(acl.organizationsJson) && acl.organizationsJson.length === 0)) {\n roleOrganizations = null\n } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes('__all__')) {\n roleOrganizations = null\n } else {\n roleOrganizations = Array.from(new Set([\n ...roleOrganizations,\n ...(Array.isArray(acl.organizationsJson) ? acl.organizationsJson : []),\n ]))\n }\n }\n }\n if (\n roleOrganizations !== null\n && evaluatedOrganizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !roleOrganizations.includes(evaluatedOrganizationId)\n ) {\n roleOrganizations.push(evaluatedOrganizationId)\n }\n }\n let organizations = roleOrganizations\n if (keyOrganizationId) {\n const keyOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n keyOrganizationId,\n )\n organizations = roleOrganizations === null\n || roleOrganizations.some((organizationId) => keyOrganizationScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n // A role-level super-admin grant still respects the API key's effective\n // organization allowlist. Represent it as a wildcard feature whenever\n // the key is restricted so downstream super-admin shortcuts cannot\n // bypass the key or role organization bounds.\n if (isSuper && organizations !== null && !features.includes('*')) features.push('*')\n const result = { isSuperAdmin: isSuper && organizations === null, features, organizations }\n if (cacheable) await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Use a forked EntityManager to avoid inheriting an aborted transaction from callers\n const em = this.em.fork()\n const user = await em.findOne(User, { id: userId })\n if (!user) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Direct user-level super-admin grants and unrestricted role-level\n // super-admin grants are global. Organization-restricted role grants are\n // deliberately excluded by isGlobalSuperAdmin and continue through the\n // scoped ACL projection below.\n //\n // The check runs AFTER the user is loaded because it is evaluated against\n // the user's own tenant \u2014 see isGlobalSuperAdmin. It reuses that load and\n // that EntityManager rather than issuing its own, so the reordering costs\n // no extra query. API-key principals never reached it and still do not:\n // their branch above has already returned.\n if (await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null)) {\n const result = { isSuperAdmin: true, features: ['*'], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n const tenantId = scope.tenantId || user.tenantId || null\n const orgId = scope.organizationId || user.organizationId || null\n\n if (!tenantId) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Per-user ACL first. This row REPLACES the role ACLs rather than merging\n // with them, so which row is returned decides the whole feature set. A\n // partial unique index now makes a second live row impossible\n // (`user_acls_active_unique_idx`, Migration20260828120000_auth), but the\n // ordering is stated anyway: an index can be dropped by an operator, and an\n // unordered `findOne` over a table that used to allow duplicates is exactly\n // the read this pairs with. Soft-deleted rows are excluded \u2014 a revoked\n // override must not keep answering.\n const uacl = await em.findOne(\n UserAcl,\n { user: userId as unknown as User, tenantId, deletedAt: null } as FilterQuery<UserAcl>,\n // `createdAt`/`id`, not `updatedAt`: `updated_at` is nullable and Postgres\n // sorts NULLs FIRST under DESC, so ordering by it would prefer a row that\n // was never updated. The migration's one-time collapse uses\n // `coalesce(updated_at, created_at)` because there it is picking the row\n // an operator would call current; here the only requirement is that the\n // answer not vary between requests.\n { orderBy: { createdAt: 'desc', id: 'desc' } } as const,\n )\n if (uacl) {\n const result = {\n isSuperAdmin: !!uacl.isSuperAdmin,\n features: Array.isArray(uacl.featuresJson) ? (uacl.featuresJson as string[]) : [],\n organizations: Array.isArray(uacl.organizationsJson) ? (uacl.organizationsJson as string[]) : null,\n }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Aggregate role ACLs\n const links = await findWithDecryption(\n em,\n UserRole,\n {\n user: userId as unknown as User,\n deletedAt: null,\n role: { tenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId, organizationId: orgId },\n )\n const linkList = Array.isArray(links) ? links : []\n const roleIds = linkList\n .map((link) => link.role?.id ? String(link.role.id) : null)\n .filter((roleId): roleId is string => roleId !== null)\n let isSuper = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n if (roleIds.length) {\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n scope.organizationId,\n )\n const racls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[] },\n } as FilterQuery<RoleAcl>, {})\n const roleAcls = Array.isArray(racls) ? racls : []\n for (const r of roleAcls) {\n if (roleAclAllowsOrganization(r, roleOrganizationScope)) {\n isSuper = isSuper || !!r.isSuperAdmin\n if (Array.isArray(r.featuresJson)) for (const f of r.featuresJson) if (!features.includes(f)) features.push(f)\n if (isRestrictedRoleAcl(r)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n // For a user principal an empty allowlist is a deny-all scope (#4033), not\n // \"unrestricted\": it must merge to an empty set so scoped reads and deletes\n // fail closed. Only an absent allowlist or an explicit '__all__' widens to\n // every organization. (The API-key branch above deliberately differs \u2014 an\n // empty role list there means the key inherits the key's own scope.)\n if (r.organizationsJson == null) organizations = null\n else if (Array.isArray(r.organizationsJson) && r.organizationsJson.includes('__all__')) organizations = null\n else organizations = Array.from(new Set([...(organizations || []), ...r.organizationsJson]))\n }\n }\n if (\n organizations !== null\n && scope.organizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(scope.organizationId)\n ) {\n organizations.push(scope.organizationId)\n }\n }\n if (organizations && orgId && !organizations.includes(orgId) && !organizations.includes('__all__')) {\n // Out-of-scope org; caller will enforce\n }\n const result = { isSuperAdmin: isSuper, features, organizations }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n /**\n * Cache-bypassing ACL resolution bound to a caller-supplied EntityManager.\n * Replay authorization uses this additive seam after taking its canonical\n * locks so every user, membership, role, ACL, API-key, and organization-scope\n * read observes the exact transaction that performs the mutation.\n */\n async loadAclWithEntityManager(\n em: EntityManager,\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<AclData> {\n if (userId.startsWith('api_key:')) {\n const key = await em.findOne(ApiKey, {\n id: userId.slice('api_key:'.length),\n deletedAt: null,\n })\n if (!key || (key.expiresAt && key.expiresAt.getTime() < Date.now())) {\n return { isSuperAdmin: false, features: [], organizations: null }\n }\n const tenantId = scope.tenantId || key.tenantId || null\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n const evaluatedOrganizationId = scope.organizationId || keyOrganizationId\n const roleScope = await resolveRoleOrganizationScopeWithEntityManager(\n em,\n tenantId,\n evaluatedOrganizationId,\n )\n const roleAcls = tenantId && roleIds.length\n ? await em.find(RoleAcl, { tenantId, deletedAt: null, role: { $in: roleIds as never, deletedAt: null } } as never)\n : []\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (\n acl.organizationsJson == null\n || acl.organizationsJson.length === 0\n || acl.organizationsJson.includes('__all__')\n ) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && evaluatedOrganizationId\n && roleScope !== null\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(evaluatedOrganizationId)\n ) {\n organizations.push(evaluatedOrganizationId)\n }\n if (keyOrganizationId) {\n const keyScope = await resolveRoleOrganizationScopeWithEntityManager(em, tenantId, keyOrganizationId)\n organizations = organizations === null\n || organizations.some((organizationId) => keyScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n if (isSuperAdmin && organizations !== null && !features.includes('*')) features.push('*')\n return { isSuperAdmin: isSuperAdmin && organizations === null, features, organizations }\n }\n\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n if (!user) return { isSuperAdmin: false, features: [], organizations: null }\n if (await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null, false)) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n const tenantId = scope.tenantId || user.tenantId || null\n const organizationId = scope.organizationId || user.organizationId || null\n if (!tenantId) return { isSuperAdmin: false, features: [], organizations: null }\n\n const userAcl = await em.findOne(\n UserAcl,\n { user: userId as never, tenantId, deletedAt: null } as FilterQuery<UserAcl>,\n { orderBy: { createdAt: 'desc', id: 'desc' } },\n )\n if (userAcl) {\n return {\n isSuperAdmin: userAcl.isSuperAdmin === true,\n features: Array.isArray(userAcl.featuresJson) ? [...userAcl.featuresJson] : [],\n organizations: Array.isArray(userAcl.organizationsJson) ? [...userAcl.organizationsJson] : null,\n }\n }\n\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as never, deletedAt: null, role: { tenantId, deletedAt: null } } as never,\n { populate: ['role'] },\n { tenantId, organizationId },\n )\n const roleIds = links\n .map((link) => typeof link.role === 'string' ? link.role : link.role?.id ? String(link.role.id) : null)\n .filter((roleId): roleId is string => typeof roleId === 'string' && roleId.length > 0)\n const roleAcls = roleIds.length\n ? await em.find(RoleAcl, { tenantId, deletedAt: null, role: { $in: roleIds as never, deletedAt: null } } as never)\n : []\n const roleScope = await resolveRoleOrganizationScopeWithEntityManager(\n em,\n tenantId,\n scope.organizationId,\n )\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (acl.organizationsJson == null || acl.organizationsJson.includes('__all__')) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && scope.organizationId\n && roleScope\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(scope.organizationId)\n ) {\n organizations.push(scope.organizationId)\n }\n return { isSuperAdmin, features, organizations }\n }\n\n async userHasAllFeaturesWithEntityManager(\n em: EntityManager,\n userId: string,\n required: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAclWithEntityManager(em, userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n async getGrantedFeaturesWithEntityManager(\n em: EntityManager,\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAclWithEntityManager(em, userId, scope)\n if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])\n if (\n acl.organizations\n && scope.organizationId\n && !acl.organizations.includes(scope.organizationId)\n && !acl.organizations.includes('__all__')\n ) {\n return []\n }\n return filterGrantsByEnabledModules(acl.features)\n }\n\n /**\n * Checks whether any tenant role grants a feature.\n *\n * This supports non-user runtimes such as scheduler workers that execute with\n * tenant scope but without an authenticated user.\n */\n async tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean> {\n if (!tenantId || !feature) return false\n\n const em = this.em.fork()\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n opts?.organizationId,\n )\n const roleAcls = await em.find(RoleAcl, { tenantId, deletedAt: null } as FilterQuery<RoleAcl>, {})\n const list = Array.isArray(roleAcls) ? roleAcls : []\n\n for (const acl of list) {\n if (!roleAclAllowsOrganization(acl, roleOrganizationScope)) continue\n const grants = Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n if (authorizeFeatures([feature], {\n grantedFeatures: grants,\n unrestricted: acl.isSuperAdmin,\n })) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Checks if a user has all required features within a given scope.\n *\n * This is the primary authorization check method used throughout the application.\n * It combines feature checking with organization visibility validation.\n *\n * Authorization logic:\n * 1. No features required \u2192 always returns true\n * 2. User is super admin \u2192 always returns true\n * 3. Organization restriction check: If the user's ACL has a restricted organization list\n * and the requested organization is not in that list \u2192 returns false\n * 4. Feature matching: User must have all required features (supports wildcards)\n *\n * @param userId - The ID of the user\n * @param required - Array of feature strings to check (e.g., ['users.view', 'users.edit'])\n * @param scope - The tenant and organization context for authorization\n * @returns true if the user has all required features and organization access, false otherwise\n *\n * @example\n * // Check if user can view and edit users\n * const canManageUsers = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['users.view', 'users.edit'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n *\n * @example\n * // Check with wildcard features\n * const canAccessEntities = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['entities.records.view'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n * // Returns true if user has 'entities.*', '*', or 'entities.records.view'\n */\n async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n async resolveFeatureOrganizationAccess(\n userId: string,\n required: readonly string[],\n input: { tenantId: string | null },\n ): Promise<FeatureOrganizationAccess> {\n const allowAll = (organizations: readonly FeatureOrganizationCandidate[]) =>\n normalizeFeatureOrganizationCandidates(organizations).map((organization) => organization.id)\n const denyAll = () => []\n if (!required.length) return { unrestricted: true, filterOrganizationIds: allowAll }\n if (!input.tenantId) return { unrestricted: false, filterOrganizationIds: denyAll }\n if (!userId.startsWith('api_key:')) {\n let globalSuperAdmin = this.globalSuperAdminCache.get(userId)\n if (globalSuperAdmin === undefined) {\n const em = this.em.fork()\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n globalSuperAdmin = !!user && await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null)\n }\n if (\n globalSuperAdmin\n && authorizeFeatures(required, { grantedFeatures: ['*'], unrestricted: true })\n ) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n }\n\n const grants = await this.loadFeatureOrganizationGrants(userId, input.tenantId)\n if (grants.kind === 'none') return { unrestricted: false, filterOrganizationIds: denyAll }\n\n if (grants.kind === 'api_key') {\n const keyOrganizationId = grants.organizationId\n const unrestricted = keyOrganizationId === null\n && roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, true)\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => (\n (!keyOrganizationId || organization.id === keyOrganizationId)\n && roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, true)\n ))\n .map((organization) => organization.id),\n }\n }\n\n if (grants.kind === 'user_acl') {\n const grantedFeatures = grants.features\n const allowedOrganizations = grants.organizations\n const hasGlobalScope = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n const unrestricted = authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed: hasGlobalScope,\n })\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => {\n const scopeAllowed = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n || allowedOrganizations.includes(organization.id)\n return authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed,\n })\n })\n .map((organization) => organization.id),\n }\n }\n\n if (roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, false)) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, false))\n .map((organization) => organization.id),\n }\n }\n\n private async loadFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n ): Promise<FeatureOrganizationGrants> {\n const cacheKey = `rbac:feature-organizations:${userId}:${tenantId}`\n const key = userId.startsWith('api_key:')\n ? await this.em.fork().findOne(ApiKey, { id: userId.slice('api_key:'.length), deletedAt: null })\n : undefined\n const cacheable = key === undefined || (key !== null && !isSessionBoundApiKey(key))\n if (this.cache && cacheable) {\n const cached = await this.cache.get(cacheKey)\n if (isFeatureOrganizationGrants(cached)) return cached\n }\n const grants = await this.queryFeatureOrganizationGrants(userId, tenantId, key)\n if (this.cache && cacheable) {\n await this.cache.set(cacheKey, grants, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, { tenantId, organizationId: null }),\n })\n }\n return grants\n }\n\n private async queryFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n knownApiKey?: ApiKey | null,\n ): Promise<FeatureOrganizationGrants> {\n const em = this.em.fork()\n if (userId.startsWith('api_key:')) {\n const apiKeyId = userId.slice('api_key:'.length)\n const key = knownApiKey === undefined\n ? await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n : knownApiKey\n if (\n !key\n || (key.expiresAt && key.expiresAt.getTime() < Date.now())\n || (key.tenantId && key.tenantId !== tenantId)\n ) {\n return { kind: 'none' }\n }\n\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n if (!roleIds.length) return { kind: 'none' }\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds, deletedAt: null },\n })\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n return {\n kind: 'api_key',\n organizationId: keyOrganizationId,\n roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant),\n }\n }\n\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n if (!user) return { kind: 'none' }\n\n const userAcl = await em.findOne(\n UserAcl,\n { user: userId, tenantId, deletedAt: null },\n { orderBy: { createdAt: 'desc', id: 'desc' } },\n )\n if (userAcl) {\n return {\n kind: 'user_acl',\n isSuperAdmin: userAcl.isSuperAdmin === true,\n features: Array.isArray(userAcl.featuresJson) ? [...userAcl.featuresJson] : [],\n organizations: Array.isArray(userAcl.organizationsJson) ? [...userAcl.organizationsJson] : null,\n }\n }\n\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId, deletedAt: null, role: { tenantId, deletedAt: null } },\n { populate: ['role'] },\n { tenantId, organizationId: null },\n )\n const roleIds = Array.from(new Set(links\n .map((link) => link.role?.id)\n .filter((roleId): roleId is string => typeof roleId === 'string' && roleId.length > 0)))\n if (!roleIds.length) return { kind: 'none' }\n\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds, deletedAt: null },\n })\n return { kind: 'roles', roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant) }\n }\n\n /**\n * Returns the user's infrastructure grant list, filtered to enabled modules.\n * The result may contain wildcards; authoritative checks must still go through\n * `authorizeFeatures` or `userHasAllFeatures` so null overrides are enforced.\n */\n async getGrantedFeatures(\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAcl(userId, scope)\n if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])\n if (\n acl.organizations &&\n scope.organizationId &&\n !acl.organizations.includes(scope.organizationId) &&\n !acl.organizations.includes('__all__')\n ) {\n return []\n }\n return filterGrantsByEnabledModules(acl.features)\n }\n\n /** Returns concrete active feature IDs for browser capability payloads. */\n async getEffectiveFeatures(\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n if (!organizationAllowed) return []\n return resolveEffectiveFeatures(acl.isSuperAdmin ? ['*'] : acl.features)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAEA,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,SAAS,SAAe,MAAM,gBAAgB;AACvD,SAAS,cAAc;AACvB,SAAS,sBAAsB,4BAA4B;AAC3D,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,2BAA2B,mCAAmC;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,8BAA8B,iCAAiC;AACxE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAQvC,eAAe,8CACb,IACA,UACA,gBACqC;AACrC,MAAI,CAAC,eAAgB,QAAO;AAC5B,MAAI,CAAC,SAAU,QAAO,oBAAI,IAAI;AAC9B,QAAM,eAAe,MAAM;AAAA,IACzB;AAAA,IACA;AAAA,IACA,EAAE,IAAI,gBAAgB,QAAQ,UAAU,WAAW,KAAK;AAAA,IACxD,EAAE,QAAQ,CAAC,MAAM,aAAa,EAAE;AAAA,IAChC,EAAE,UAAU,eAAe;AAAA,EAC7B;AACA,MAAI,CAAC,aAAc,QAAO,oBAAI,IAAI;AAClC,QAAM,YAAY,MAAM,QAAQ,aAAa,WAAW,IACpD,aAAa,YAAY,OAAO,CAAC,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CAAC,IACzG,CAAC;AACL,SAAO,oBAAI,IAAI,CAAC,gBAAgB,GAAG,SAAS,CAAC;AAC/C;AAEA,SAAS,UAAU,OAAkC;AACnD,MAAI,OAAO,UA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import type { CacheStrategy } from '@open-mercato/cache'\nimport { getCurrentCacheTenant, runWithCacheTenant } from '@open-mercato/cache'\nimport { UserAcl, RoleAcl, Role, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { isSessionBoundApiKey, resolveApiKeyRoleIds } from '@open-mercato/core/modules/api_keys/services/sessionKeyRoles'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport { buildOrgScopeUserCacheTag, buildOrgScopeTenantCacheTag } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n authorizeFeatures,\n resolveEffectiveFeatures,\n} from '@open-mercato/shared/security/featurePolicy'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport { hasFeature } from '@open-mercato/shared/security/features'\nimport { resolveRoleOrganizationScope, roleAclAllowsOrganization } from './roleOrganizationScope'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('auth.rbac')\n\ninterface AclData {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\nfunction intersectDelegatedAcl(keyAcl: AclData, ownerAcl: AclData): AclData {\n const keyFeatures = keyAcl.isSuperAdmin ? ['*'] : keyAcl.features\n const ownerFeatures = ownerAcl.isSuperAdmin ? ['*'] : ownerAcl.features\n const features = Array.from(new Set([\n ...keyFeatures.filter((feature) => hasFeature(ownerFeatures, feature)),\n ...ownerFeatures.filter((feature) => hasFeature(keyFeatures, feature)),\n ]))\n const keyOrganizations = keyAcl.isSuperAdmin || keyAcl.organizations?.includes('__all__')\n ? null : keyAcl.organizations\n const ownerOrganizations = ownerAcl.isSuperAdmin || ownerAcl.organizations?.includes('__all__')\n ? null : ownerAcl.organizations\n const organizations = keyOrganizations === null ? ownerOrganizations\n : ownerOrganizations === null ? keyOrganizations\n : keyOrganizations.filter((organizationId) => ownerOrganizations.includes(organizationId))\n return {\n isSuperAdmin: keyAcl.isSuperAdmin && ownerAcl.isSuperAdmin,\n features: organizations?.length === 0 ? [] : features,\n organizations,\n }\n}\n\nasync function resolveRoleOrganizationScopeWithEntityManager(\n em: EntityManager,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<ReadonlySet<string> | null> {\n if (!organizationId) return null\n if (!tenantId) return new Set()\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null } as FilterQuery<Organization>,\n { fields: ['id', 'ancestorIds'] },\n { tenantId, organizationId },\n )\n if (!organization) return new Set()\n const ancestors = Array.isArray(organization.ancestorIds)\n ? organization.ancestorIds.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n return new Set([organizationId, ...ancestors])\n}\n\nfunction isAclData(value: unknown): value is AclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<AclData>\n if (typeof record.isSuperAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((feature) => typeof feature !== 'string')) return false\n if (record.organizations !== null && record.organizations !== undefined) {\n if (!Array.isArray(record.organizations)) return false\n if (record.organizations.some((org) => typeof org !== 'string')) return false\n }\n return true\n}\n\nfunction isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n return Array.isArray(acl.organizationsJson)\n && acl.organizationsJson.length > 0\n && !acl.organizationsJson.includes('__all__')\n}\n\ntype FeatureOrganizationCandidate = {\n id: string\n ancestorIds?: readonly string[] | null\n}\n\ntype FeatureOrganizationAccess = {\n unrestricted: boolean\n filterOrganizationIds: (organizations: readonly FeatureOrganizationCandidate[]) => string[]\n}\n\ntype FeatureOrganizationRoleGrant = {\n isSuperAdmin: boolean\n featuresJson: string[] | null\n organizationsJson: string[] | null\n}\n\ntype FeatureOrganizationGrants =\n | { kind: 'none' }\n | { kind: 'api_key'; organizationId: string | null; ownerId: string | null; roleGrants: FeatureOrganizationRoleGrant[] }\n | { kind: 'user_acl'; isSuperAdmin: boolean; features: string[]; organizations: string[] | null }\n | { kind: 'roles'; roleGrants: FeatureOrganizationRoleGrant[] }\n\nfunction isStringListOrNull(value: unknown): value is string[] | null {\n return value === null || (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n}\n\nfunction isFeatureOrganizationRoleGrant(value: unknown): value is FeatureOrganizationRoleGrant {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<FeatureOrganizationRoleGrant>\n return typeof record.isSuperAdmin === 'boolean'\n && isStringListOrNull(record.featuresJson)\n && isStringListOrNull(record.organizationsJson)\n}\n\nfunction isFeatureOrganizationGrants(value: unknown): value is FeatureOrganizationGrants {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n switch (record.kind) {\n case 'none':\n return true\n case 'api_key':\n return (record.organizationId === null || typeof record.organizationId === 'string')\n && (record.ownerId === null || typeof record.ownerId === 'string')\n && Array.isArray(record.roleGrants)\n && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n case 'user_acl':\n return typeof record.isSuperAdmin === 'boolean'\n && Array.isArray(record.features)\n && record.features.every((feature) => typeof feature === 'string')\n && isStringListOrNull(record.organizations)\n case 'roles':\n return Array.isArray(record.roleGrants) && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n default:\n return false\n }\n}\n\nfunction toFeatureOrganizationRoleGrant(\n acl: Pick<RoleAcl, 'isSuperAdmin' | 'featuresJson' | 'organizationsJson'>,\n): FeatureOrganizationRoleGrant {\n return {\n isSuperAdmin: acl.isSuperAdmin === true,\n featuresJson: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n organizationsJson: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }\n}\n\nfunction normalizeFeatureOrganizationCandidates(\n organizations: readonly FeatureOrganizationCandidate[],\n): FeatureOrganizationCandidate[] {\n const normalized = new Map<string, FeatureOrganizationCandidate>()\n for (const organization of organizations) {\n const id = typeof organization.id === 'string' ? organization.id.trim() : ''\n if (!id || normalized.has(id)) continue\n const ancestorIds = Array.isArray(organization.ancestorIds)\n ? Array.from(new Set(organization.ancestorIds\n .map((ancestorId) => typeof ancestorId === 'string' ? ancestorId.trim() : '')\n .filter(Boolean)))\n : []\n normalized.set(id, { id, ancestorIds })\n }\n return Array.from(normalized.values())\n}\n\nfunction buildFeatureOrganizationScope(\n organization: FeatureOrganizationCandidate,\n): ReadonlySet<string> {\n return new Set([organization.id, ...(organization.ancestorIds ?? [])])\n}\n\nfunction roleAclProvidesGlobalFeatureScope(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n return !organizations || organizations.length === 0 || organizations.includes('__all__')\n}\n\nfunction roleAclProvidesGlobalVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n return emptyOrganizationsAreUnrestricted && organizations.length === 0\n}\n\nfunction roleAclProvidesOrganizationVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n organizationScope: ReadonlySet<string>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n if (organizations.length === 0) return emptyOrganizationsAreUnrestricted\n return organizations.some((organizationId) => organizationScope.has(organizationId))\n}\n\nfunction roleAclsAuthorizeFeatures(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n organization: FeatureOrganizationCandidate,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizationScope = buildFeatureOrganizationScope(organization)\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesOrganizationVisibility(acl, organizationScope, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclAllowsOrganization(acl, organizationScope)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nfunction roleAclsAuthorizeFeaturesGlobally(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesGlobalVisibility(acl, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclProvidesGlobalFeatureScope(acl)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nexport class RbacService {\n private cacheTtlMs: number = 5 * 60 * 1000 // 5 minutes default\n private cache: CacheStrategy | null = null\n private globalSuperAdminCache = new Map<string, boolean>()\n\n constructor(\n private em: EntityManager,\n cache?: CacheStrategy,\n private readonly organizationHierarchyService?: OrganizationHierarchyService,\n ) {\n this.cache = cache || null\n }\n\n /**\n * Set cache TTL in milliseconds\n * @param ttlMs - Time to live in milliseconds\n */\n setCacheTtl(ttlMs: number) {\n this.cacheTtlMs = ttlMs\n }\n\n /** Compatibility wrapper for callers that already have both feature lists. */\n public hasAllFeatures(required: string[], granted: string[]): boolean {\n return authorizeFeatures(required, { grantedFeatures: granted })\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string {\n const namespace = userId.startsWith('api_key:') ? 'rbac:delegated-v1' : 'rbac'\n return `${namespace}:${userId}:${scope.tenantId || 'null'}:${scope.organizationId || 'null'}`\n }\n\n private getUserTag(userId: string): string {\n return `rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `rbac:tenant:${tenantId}`\n }\n\n private getOrganizationTag(organizationId: string): string {\n return `rbac:org:${organizationId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<AclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isAclData(cached) ? cached : null\n }\n\n private async setCache(cacheKey: string, data: AclData, userId: string, scope: { tenantId: string | null; organizationId: string | null }, ownerId?: string | null): Promise<void> {\n if (!this.cache) return\n\n await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags: [...this.buildCacheTags(userId, scope), ...(ownerId ? [this.getUserTag(ownerId)] : [])],\n })\n }\n\n private buildCacheTags(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string[] {\n const tags = [\n this.getUserTag(userId),\n 'rbac:all'\n ]\n\n if (scope.tenantId) {\n tags.push(this.getTenantTag(scope.tenantId))\n // Scoped role projections depend on the selected organization's ancestor\n // chain, so Directory hierarchy changes must evict them as well as the\n // separately cached OrganizationScope entries.\n tags.push(buildOrgScopeTenantCacheTag(scope.tenantId))\n }\n\n if (scope.organizationId) {\n tags.push(this.getOrganizationTag(scope.organizationId))\n }\n\n return tags\n }\n\n /**\n * Invalidates cached ACL data for a specific user across all tenants and organizations.\n * Call this when a user's roles or user-specific ACL is modified.\n * \n * @param userId - The ID of the user whose cache should be invalidated\n */\n async invalidateUserCache(userId: string): Promise<void> {\n this.globalSuperAdminCache.delete(userId)\n // Also drop the directory OrganizationScope cache for this user. That scope's\n // accessible-org set is derived from this user's ACL/role grants, so any\n // permission change that invalidates the RBAC cache must invalidate the\n // resolved scope too. This is the missing `org-scope:user:*` caller required\n // before the cross-request scope TTL can be safely enabled (issue #2259).\n await this.deleteCacheByTags([this.getUserTag(userId), buildOrgScopeUserCacheTag(userId)])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific tenant.\n * Call this when a role's ACL is modified, since roles are tenant-scoped\n * and affect all users in that tenant who have that role.\n * \n * @param tenantId - The ID of the tenant whose cache should be invalidated\n */\n async invalidateTenantCache(tenantId: string): Promise<void> {\n this.globalSuperAdminCache.clear()\n // Role ACL changes invalidate every user in the tenant; the resolved\n // OrganizationScope for those users derives from the same grants, so drop\n // the tenant-tagged scope entries alongside the RBAC ones (issue #2259).\n await this.deleteCacheByTags([this.getTenantTag(tenantId), buildOrgScopeTenantCacheTag(tenantId)], [tenantId])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific organization.\n * Call this when organization-level permissions or visibility changes.\n * \n * @param organizationId - The ID of the organization whose cache should be invalidated\n */\n async invalidateOrganizationCache(organizationId: string): Promise<void> {\n await this.deleteCacheByTags([this.getOrganizationTag(organizationId)])\n }\n\n /**\n * Clears all cached ACL data.\n * Use this for bulk operations or system-wide ACL changes.\n */\n async invalidateAllCache(): Promise<void> {\n this.globalSuperAdminCache.clear()\n await this.deleteCacheByTags(['rbac:all'])\n }\n\n private async deleteCacheByTags(tags: string[], tenantHints?: Array<string | null>): Promise<void> {\n if (!this.cache) return\n const contexts = new Set<string | null>()\n const current = getCurrentCacheTenant()\n contexts.add(current ?? null)\n contexts.add(null)\n if (Array.isArray(tenantHints)) {\n for (const hint of tenantHints) {\n contexts.add(hint ?? null)\n }\n }\n for (const ctx of contexts) {\n if (ctx === current) {\n await this.cache.deleteByTags(tags)\n } else {\n await runWithCacheTenant(ctx, async () => {\n await this.cache!.deleteByTags(tags)\n })\n }\n }\n }\n\n // A super-admin grant is deliberately GLOBAL: it survives every scope the\n // caller asks about, which is what lets a platform super-admin work inside a\n // customer tenant. What it must not do is survive the question of whose grant\n // it is. Both lookups below are therefore evaluated against the user's OWN\n // tenant (`users.tenant_id`), never against no tenant at all.\n //\n // Without that binding a single `user_acls` row \u2014 or a role link \u2014 stamped\n // with ANY tenant confers platform super-admin everywhere, so a row written\n // under the wrong tenant becomes a full privilege escalation with nothing in\n // the schema or the UI to show for it. `user_acls` has no organization column\n // and no uniqueness beyond its primary key, so such a row is cheap to create\n // and invisible to the tenant/organization cross-wire checks.\n //\n // This is the tenant binding `resolveCanonicalStaffAuthContext` already\n // applies when it computes `auth.isSuperAdmin` (see lib/sessionIntegrity.ts:\n // `userAclGrantsSuperAdmin` / `roleAclGrantsSuperAdmin`, both bound to the\n // user's own tenant). Before this change the two authorities disagreed:\n // session integrity would say \"not a super-admin\" while `loadAcl` handed the\n // same request `['*']`.\n //\n // The memo stays keyed by `userId` alone because the answer now depends only\n // on the user's own tenant, which is a property of the user \u2014 not on the scope\n // being asked about. `invalidateUserCache` therefore still clears it correctly.\n private async isGlobalSuperAdmin(\n em: EntityManager,\n userId: string,\n userTenantId: string | null,\n useCache = true,\n ): Promise<boolean> {\n if (useCache && this.globalSuperAdminCache.has(userId)) return this.globalSuperAdminCache.get(userId)!\n if (!userTenantId) {\n logger.warn('Tenant-less principal cannot receive super-admin grants; assign an owning tenant before upgrading', { userId })\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const userSuper = await em.findOne(UserAcl, {\n user: userId as unknown as User,\n tenantId: userTenantId,\n isSuperAdmin: true,\n deletedAt: null,\n } as FilterQuery<UserAcl>)\n if (userSuper?.isSuperAdmin) {\n if (useCache) this.globalSuperAdminCache.set(userId, true)\n return true\n }\n const links = await findWithDecryption(\n em,\n UserRole,\n // Roles that belong to the user's own tenant, as\n // `resolveCanonicalStaffAuthContext` already requires. The encryption\n // scope stays `{ null, null }` as before \u2014 this change is about which rows\n // count, not about which key decrypts them.\n {\n user: userId as unknown as User,\n deletedAt: null,\n role: { tenantId: userTenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const linkList = Array.isArray(links) ? links : []\n if (!linkList.length) {\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleIds = Array.from(new Set(linkList.map((link) => {\n const role = link.role\n return role?.id ? String(role.id) : null\n }).filter((id): id is string => typeof id === 'string' && id.length > 0)))\n if (!roleIds.length) {\n if (useCache) this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleSupers = await em.find(RoleAcl, {\n isSuperAdmin: true,\n tenantId: userTenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[] },\n } as FilterQuery<RoleAcl>)\n const result = roleSupers.some((roleAcl) => (\n !!roleAcl.isSuperAdmin && !isRestrictedRoleAcl(roleAcl)\n ))\n if (useCache) this.globalSuperAdminCache.set(userId, result)\n return result\n }\n\n /**\n * Loads the Access Control List (ACL) for a user within a given scope.\n * \n * The ACL resolution follows this priority:\n * 1. Per-user ACL (UserAcl) - if exists, use it exclusively\n * 2. Aggregated role ACLs (RoleAcl) - combine permissions from all user's roles\n * \n * Results are cached for performance (default 5 minutes TTL).\n * Cache is automatically invalidated when ACL-related data changes.\n * \n * @param userId - The ID of the user\n * @param scope - The tenant and organization context for ACL evaluation\n * @returns An object containing:\n * - isSuperAdmin: If true, user has unrestricted access to all features\n * - features: Array of feature strings (may include wildcards like 'entities.*')\n * - organizations: Array of organization IDs user can access, or null for all organizations\n * \n * @example\n * const acl = await rbacService.loadAcl('user-123', { tenantId: 'tenant-1', organizationId: 'org-1' })\n * // Returns: { isSuperAdmin: false, features: ['users.view', 'entities.*'], organizations: ['org-1', 'org-2'] }\n */\n async loadAcl(userId: string, scope: { tenantId: string | null; organizationId: string | null }): Promise<{\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n }> {\n const cacheKey = this.getCacheKey(userId, scope)\n const cached = userId.startsWith('api_key:') ? null : await this.getFromCache(cacheKey)\n if (cached) return cached\n\n if (userId.startsWith('api_key:')) {\n const apiKeyId = userId.slice('api_key:'.length)\n const em = this.em.fork()\n const key = await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n if (!key || (key.expiresAt && key.expiresAt.getTime() < Date.now())) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n const cacheable = !isSessionBoundApiKey(key)\n if (cacheable) {\n const cachedKeyAcl = await this.getFromCache(cacheKey)\n if (cachedKeyAcl) return cachedKeyAcl\n }\n const tenantId = scope.tenantId || key.tenantId || null\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n const evaluatedOrganizationId = scope.organizationId || keyOrganizationId\n let isSuper = false\n const features: string[] = []\n let roleOrganizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n if (tenantId && roleIds.length) {\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n evaluatedOrganizationId,\n )\n const racls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[], deletedAt: null },\n } as FilterQuery<RoleAcl>)\n for (const acl of racls) {\n if (roleAclAllowsOrganization(acl, roleOrganizationScope)) {\n isSuper = isSuper || !!acl.isSuperAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) if (!features.includes(f)) features.push(f)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (roleOrganizations !== null) {\n if (acl.organizationsJson == null || (Array.isArray(acl.organizationsJson) && acl.organizationsJson.length === 0)) {\n roleOrganizations = null\n } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes('__all__')) {\n roleOrganizations = null\n } else {\n roleOrganizations = Array.from(new Set([\n ...roleOrganizations,\n ...(Array.isArray(acl.organizationsJson) ? acl.organizationsJson : []),\n ]))\n }\n }\n }\n if (\n roleOrganizations !== null\n && evaluatedOrganizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !roleOrganizations.includes(evaluatedOrganizationId)\n ) {\n roleOrganizations.push(evaluatedOrganizationId)\n }\n }\n let organizations = roleOrganizations\n if (keyOrganizationId) {\n const keyOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n keyOrganizationId,\n )\n organizations = roleOrganizations === null\n || roleOrganizations.some((organizationId) => keyOrganizationScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n // A role-level super-admin grant still respects the API key's effective\n // organization allowlist. Represent it as a wildcard feature whenever\n // the key is restricted so downstream super-admin shortcuts cannot\n // bypass the key or role organization bounds.\n if (isSuper && organizations !== null && !features.includes('*')) features.push('*')\n const keyAcl = { isSuperAdmin: isSuper && organizations === null, features, organizations }\n const result = await this.limitDelegatedKeyAcl(em, key, { tenantId, organizationId: evaluatedOrganizationId }, keyAcl)\n if (cacheable) await this.setCache(cacheKey, result, userId, { tenantId, organizationId: evaluatedOrganizationId }, key.sessionUserId)\n return result\n }\n\n // Use a forked EntityManager to avoid inheriting an aborted transaction from callers\n const em = this.em.fork()\n const user = await em.findOne(User, { id: userId })\n if (!user) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Direct user-level super-admin grants and unrestricted role-level\n // super-admin grants are global. Organization-restricted role grants are\n // deliberately excluded by isGlobalSuperAdmin and continue through the\n // scoped ACL projection below.\n //\n // The check runs AFTER the user is loaded because it is evaluated against\n // the user's own tenant \u2014 see isGlobalSuperAdmin. It reuses that load and\n // that EntityManager rather than issuing its own, so the reordering costs\n // no extra query. API-key principals never reached it and still do not:\n // their branch above has already returned.\n if (await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null)) {\n const result = { isSuperAdmin: true, features: ['*'], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n const tenantId = scope.tenantId || user.tenantId || null\n const orgId = scope.organizationId || user.organizationId || null\n\n if (!tenantId) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Per-user ACL first. This row REPLACES the role ACLs rather than merging\n // with them, so which row is returned decides the whole feature set. A\n // partial unique index now makes a second live row impossible\n // (`user_acls_active_unique_idx`, Migration20260828120000_auth), but the\n // ordering is stated anyway: an index can be dropped by an operator, and an\n // unordered `findOne` over a table that used to allow duplicates is exactly\n // the read this pairs with. Soft-deleted rows are excluded \u2014 a revoked\n // override must not keep answering.\n const uacl = await em.findOne(\n UserAcl,\n { user: userId as unknown as User, tenantId, deletedAt: null } as FilterQuery<UserAcl>,\n // `createdAt`/`id`, not `updatedAt`: `updated_at` is nullable and Postgres\n // sorts NULLs FIRST under DESC, so ordering by it would prefer a row that\n // was never updated. The migration's one-time collapse uses\n // `coalesce(updated_at, created_at)` because there it is picking the row\n // an operator would call current; here the only requirement is that the\n // answer not vary between requests.\n { orderBy: { createdAt: 'desc', id: 'desc' } } as const,\n )\n if (uacl) {\n const result = {\n isSuperAdmin: !!uacl.isSuperAdmin,\n features: Array.isArray(uacl.featuresJson) ? (uacl.featuresJson as string[]) : [],\n organizations: Array.isArray(uacl.organizationsJson) ? (uacl.organizationsJson as string[]) : null,\n }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Aggregate role ACLs\n const links = await findWithDecryption(\n em,\n UserRole,\n {\n user: userId as unknown as User,\n deletedAt: null,\n role: { tenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { populate: ['role'] },\n { tenantId, organizationId: orgId },\n )\n const linkList = Array.isArray(links) ? links : []\n const roleIds = linkList\n .map((link) => link.role?.id ? String(link.role.id) : null)\n .filter((roleId): roleId is string => roleId !== null)\n let isSuper = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n if (roleIds.length) {\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n scope.organizationId,\n )\n const racls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds as unknown as Role[] },\n } as FilterQuery<RoleAcl>, {})\n const roleAcls = Array.isArray(racls) ? racls : []\n for (const r of roleAcls) {\n if (roleAclAllowsOrganization(r, roleOrganizationScope)) {\n isSuper = isSuper || !!r.isSuperAdmin\n if (Array.isArray(r.featuresJson)) for (const f of r.featuresJson) if (!features.includes(f)) features.push(f)\n if (isRestrictedRoleAcl(r)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n // For a user principal an empty allowlist is a deny-all scope (#4033), not\n // \"unrestricted\": it must merge to an empty set so scoped reads and deletes\n // fail closed. Only an absent allowlist or an explicit '__all__' widens to\n // every organization. (The API-key branch above deliberately differs \u2014 an\n // empty role list there means the key inherits the key's own scope.)\n if (r.organizationsJson == null) organizations = null\n else if (Array.isArray(r.organizationsJson) && r.organizationsJson.includes('__all__')) organizations = null\n else organizations = Array.from(new Set([...(organizations || []), ...r.organizationsJson]))\n }\n }\n if (\n organizations !== null\n && scope.organizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(scope.organizationId)\n ) {\n organizations.push(scope.organizationId)\n }\n }\n if (organizations && orgId && !organizations.includes(orgId) && !organizations.includes('__all__')) {\n // Out-of-scope org; caller will enforce\n }\n const result = { isSuperAdmin: isSuper, features, organizations }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n /**\n * Cache-bypassing ACL resolution bound to a caller-supplied EntityManager.\n * Replay authorization uses this additive seam after taking its canonical\n * locks so every user, membership, role, ACL, API-key, and organization-scope\n * read observes the exact transaction that performs the mutation.\n */\n async loadAclWithEntityManager(\n em: EntityManager,\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<AclData> {\n if (userId.startsWith('api_key:')) {\n const key = await em.findOne(ApiKey, {\n id: userId.slice('api_key:'.length),\n deletedAt: null,\n })\n if (!key || (key.expiresAt && key.expiresAt.getTime() < Date.now())) {\n return { isSuperAdmin: false, features: [], organizations: null }\n }\n const tenantId = scope.tenantId || key.tenantId || null\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n const evaluatedOrganizationId = scope.organizationId || keyOrganizationId\n const roleScope = await resolveRoleOrganizationScopeWithEntityManager(\n em,\n tenantId,\n evaluatedOrganizationId,\n )\n const roleAcls = tenantId && roleIds.length\n ? await em.find(RoleAcl, { tenantId, deletedAt: null, role: { $in: roleIds as never, deletedAt: null } } as never)\n : []\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (\n acl.organizationsJson == null\n || acl.organizationsJson.length === 0\n || acl.organizationsJson.includes('__all__')\n ) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && evaluatedOrganizationId\n && roleScope !== null\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(evaluatedOrganizationId)\n ) {\n organizations.push(evaluatedOrganizationId)\n }\n if (keyOrganizationId) {\n const keyScope = await resolveRoleOrganizationScopeWithEntityManager(em, tenantId, keyOrganizationId)\n organizations = organizations === null\n || organizations.some((organizationId) => keyScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n if (isSuperAdmin && organizations !== null && !features.includes('*')) features.push('*')\n return this.limitDelegatedKeyAcl(\n em,\n key,\n { tenantId, organizationId: evaluatedOrganizationId },\n { isSuperAdmin: isSuperAdmin && organizations === null, features, organizations },\n true,\n )\n }\n\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n if (!user) return { isSuperAdmin: false, features: [], organizations: null }\n if (await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null, false)) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n const tenantId = scope.tenantId || user.tenantId || null\n const organizationId = scope.organizationId || user.organizationId || null\n if (!tenantId) return { isSuperAdmin: false, features: [], organizations: null }\n\n const userAcl = await em.findOne(\n UserAcl,\n { user: userId as never, tenantId, deletedAt: null } as FilterQuery<UserAcl>,\n { orderBy: { createdAt: 'desc', id: 'desc' } },\n )\n if (userAcl) {\n return {\n isSuperAdmin: userAcl.isSuperAdmin === true,\n features: Array.isArray(userAcl.featuresJson) ? [...userAcl.featuresJson] : [],\n organizations: Array.isArray(userAcl.organizationsJson) ? [...userAcl.organizationsJson] : null,\n }\n }\n\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as never, deletedAt: null, role: { tenantId, deletedAt: null } } as never,\n { populate: ['role'] },\n { tenantId, organizationId },\n )\n const roleIds = links\n .map((link) => typeof link.role === 'string' ? link.role : link.role?.id ? String(link.role.id) : null)\n .filter((roleId): roleId is string => typeof roleId === 'string' && roleId.length > 0)\n const roleAcls = roleIds.length\n ? await em.find(RoleAcl, { tenantId, deletedAt: null, role: { $in: roleIds as never, deletedAt: null } } as never)\n : []\n const roleScope = await resolveRoleOrganizationScopeWithEntityManager(\n em,\n tenantId,\n scope.organizationId,\n )\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (acl.organizationsJson == null || acl.organizationsJson.includes('__all__')) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && scope.organizationId\n && roleScope\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(scope.organizationId)\n ) {\n organizations.push(scope.organizationId)\n }\n return { isSuperAdmin, features, organizations }\n }\n\n async userHasAllFeaturesWithEntityManager(\n em: EntityManager,\n userId: string,\n required: string[],\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAclWithEntityManager(em, userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n async getGrantedFeaturesWithEntityManager(\n em: EntityManager,\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAclWithEntityManager(em, userId, scope)\n if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])\n if (\n acl.organizations\n && scope.organizationId\n && !acl.organizations.includes(scope.organizationId)\n && !acl.organizations.includes('__all__')\n ) {\n return []\n }\n return filterGrantsByEnabledModules(acl.features)\n }\n\n /**\n * Checks whether any tenant role grants a feature.\n *\n * This supports non-user runtimes such as scheduler workers that execute with\n * tenant scope but without an authenticated user.\n */\n async tenantHasFeature(\n tenantId: string | null | undefined,\n feature: string,\n opts?: { organizationId?: string | null },\n ): Promise<boolean> {\n if (!tenantId || !feature) return false\n\n const em = this.em.fork()\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n opts?.organizationId,\n )\n const roleAcls = await em.find(RoleAcl, { tenantId, deletedAt: null } as FilterQuery<RoleAcl>, {})\n const list = Array.isArray(roleAcls) ? roleAcls : []\n\n for (const acl of list) {\n if (!roleAclAllowsOrganization(acl, roleOrganizationScope)) continue\n const grants = Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n if (authorizeFeatures([feature], {\n grantedFeatures: grants,\n unrestricted: acl.isSuperAdmin,\n })) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Checks if a user has all required features within a given scope.\n *\n * This is the primary authorization check method used throughout the application.\n * It combines feature checking with organization visibility validation.\n *\n * Authorization logic:\n * 1. No features required \u2192 always returns true\n * 2. User is super admin \u2192 always returns true\n * 3. Organization restriction check: If the user's ACL has a restricted organization list\n * and the requested organization is not in that list \u2192 returns false\n * 4. Feature matching: User must have all required features (supports wildcards)\n *\n * @param userId - The ID of the user\n * @param required - Array of feature strings to check (e.g., ['users.view', 'users.edit'])\n * @param scope - The tenant and organization context for authorization\n * @returns true if the user has all required features and organization access, false otherwise\n *\n * @example\n * // Check if user can view and edit users\n * const canManageUsers = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['users.view', 'users.edit'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n *\n * @example\n * // Check with wildcard features\n * const canAccessEntities = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['entities.records.view'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n * // Returns true if user has 'entities.*', '*', or 'entities.records.view'\n */\n async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n private async limitDelegatedKeyAcl(\n em: EntityManager,\n key: ApiKey,\n scope: { tenantId: string | null; organizationId: string | null },\n keyAcl: AclData,\n uncached = false,\n ): Promise<AclData> {\n if (!key.sessionUserId) return keyAcl\n if (!key.tenantId || key.tenantId !== scope.tenantId) {\n return { isSuperAdmin: false, features: [], organizations: [] }\n }\n const owner = await findOneWithDecryption(em, User, {\n id: key.sessionUserId,\n tenantId: key.tenantId,\n deletedAt: null,\n }, undefined, scope)\n if (!owner) return { isSuperAdmin: false, features: [], organizations: [] }\n const ownerAcl = uncached\n ? await this.loadAclWithEntityManager(em, key.sessionUserId, scope)\n : await this.loadAcl(key.sessionUserId, scope)\n const result = intersectDelegatedAcl(keyAcl, ownerAcl)\n if (scope.organizationId && result.organizations && !result.organizations.includes(scope.organizationId)) {\n return { ...result, isSuperAdmin: false, features: [] }\n }\n return result\n }\n\n async resolveFeatureOrganizationAccess(\n userId: string,\n required: readonly string[],\n input: { tenantId: string | null },\n ): Promise<FeatureOrganizationAccess> {\n const allowAll = (organizations: readonly FeatureOrganizationCandidate[]) =>\n normalizeFeatureOrganizationCandidates(organizations).map((organization) => organization.id)\n const denyAll = () => []\n if (!required.length) return { unrestricted: true, filterOrganizationIds: allowAll }\n if (!input.tenantId) return { unrestricted: false, filterOrganizationIds: denyAll }\n if (!userId.startsWith('api_key:')) {\n let globalSuperAdmin = this.globalSuperAdminCache.get(userId)\n if (globalSuperAdmin === undefined) {\n const em = this.em.fork()\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n globalSuperAdmin = !!user && await this.isGlobalSuperAdmin(em, userId, user.tenantId ?? null)\n }\n if (\n globalSuperAdmin\n && authorizeFeatures(required, { grantedFeatures: ['*'], unrestricted: true })\n ) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n }\n\n const grants = await this.loadFeatureOrganizationGrants(userId, input.tenantId)\n if (grants.kind === 'none') return { unrestricted: false, filterOrganizationIds: denyAll }\n\n if (grants.kind === 'api_key') {\n const keyOrganizationId = grants.organizationId\n const ownerAccess = grants.ownerId\n ? await this.resolveFeatureOrganizationAccess(grants.ownerId, required, input)\n : { unrestricted: true, filterOrganizationIds: allowAll }\n const unrestricted = keyOrganizationId === null\n && ownerAccess.unrestricted\n && roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, true)\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => ownerAccess.filterOrganizationIds([organization]).length > 0)\n .filter((organization) => (\n (!keyOrganizationId || organization.id === keyOrganizationId)\n && roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, true)\n ))\n .map((organization) => organization.id),\n }\n }\n\n if (grants.kind === 'user_acl') {\n const grantedFeatures = grants.features\n const allowedOrganizations = grants.organizations\n const hasGlobalScope = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n const unrestricted = authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed: hasGlobalScope,\n })\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => {\n const scopeAllowed = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n || allowedOrganizations.includes(organization.id)\n return authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed,\n })\n })\n .map((organization) => organization.id),\n }\n }\n\n if (roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, false)) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, false))\n .map((organization) => organization.id),\n }\n }\n\n private async loadFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n ): Promise<FeatureOrganizationGrants> {\n const cacheKey = `rbac:feature-organizations:delegated-v1:${userId}:${tenantId}`\n const key = userId.startsWith('api_key:')\n ? await this.em.fork().findOne(ApiKey, { id: userId.slice('api_key:'.length), deletedAt: null })\n : undefined\n const cacheable = key === undefined || (key !== null && !isSessionBoundApiKey(key))\n if (this.cache && cacheable) {\n const cached = await this.cache.get(cacheKey)\n if (isFeatureOrganizationGrants(cached)) return cached\n }\n const grants = await this.queryFeatureOrganizationGrants(userId, tenantId, key)\n if (this.cache && cacheable) {\n await this.cache.set(cacheKey, grants, {\n ttl: this.cacheTtlMs,\n tags: [\n ...this.buildCacheTags(userId, { tenantId, organizationId: null }),\n ...(grants.kind === 'api_key' && grants.ownerId ? [this.getUserTag(grants.ownerId)] : []),\n ],\n })\n }\n return grants\n }\n\n private async queryFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n knownApiKey?: ApiKey | null,\n ): Promise<FeatureOrganizationGrants> {\n const em = this.em.fork()\n if (userId.startsWith('api_key:')) {\n const apiKeyId = userId.slice('api_key:'.length)\n const key = knownApiKey === undefined\n ? await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n : knownApiKey\n if (\n !key\n || (key.expiresAt && key.expiresAt.getTime() < Date.now())\n || (key.tenantId && key.tenantId !== tenantId)\n ) {\n return { kind: 'none' }\n }\n\n if (key.sessionUserId) {\n if (key.tenantId !== tenantId) return { kind: 'none' }\n const owner = await findOneWithDecryption(em, User, {\n id: key.sessionUserId,\n tenantId,\n deletedAt: null,\n }, undefined, { tenantId, organizationId: null })\n if (!owner) return { kind: 'none' }\n }\n\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n if (!roleIds.length) return { kind: 'none' }\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds, deletedAt: null },\n })\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n return {\n kind: 'api_key',\n organizationId: keyOrganizationId,\n ownerId: key.sessionUserId ?? null,\n roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant),\n }\n }\n\n const user = await findOneWithDecryption(\n em, User, { id: userId }, {}, { tenantId: null, organizationId: null },\n )\n if (!user) return { kind: 'none' }\n\n const userAcl = await em.findOne(\n UserAcl,\n { user: userId, tenantId, deletedAt: null },\n { orderBy: { createdAt: 'desc', id: 'desc' } },\n )\n if (userAcl) {\n return {\n kind: 'user_acl',\n isSuperAdmin: userAcl.isSuperAdmin === true,\n features: Array.isArray(userAcl.featuresJson) ? [...userAcl.featuresJson] : [],\n organizations: Array.isArray(userAcl.organizationsJson) ? [...userAcl.organizationsJson] : null,\n }\n }\n\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId, deletedAt: null, role: { tenantId, deletedAt: null } },\n { populate: ['role'] },\n { tenantId, organizationId: null },\n )\n const roleIds = Array.from(new Set(links\n .map((link) => link.role?.id)\n .filter((roleId): roleId is string => typeof roleId === 'string' && roleId.length > 0)))\n if (!roleIds.length) return { kind: 'none' }\n\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n deletedAt: null,\n role: { $in: roleIds, deletedAt: null },\n })\n return { kind: 'roles', roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant) }\n }\n\n /**\n * Returns the user's infrastructure grant list, filtered to enabled modules.\n * The result may contain wildcards; authoritative checks must still go through\n * `authorizeFeatures` or `userHasAllFeatures` so null overrides are enforced.\n */\n async getGrantedFeatures(\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAcl(userId, scope)\n if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])\n if (\n acl.organizations &&\n scope.organizationId &&\n !acl.organizations.includes(scope.organizationId) &&\n !acl.organizations.includes('__all__')\n ) {\n return []\n }\n return filterGrantsByEnabledModules(acl.features)\n }\n\n /** Returns concrete active feature IDs for browser capability payloads. */\n async getEffectiveFeatures(\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ): Promise<string[]> {\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n if (!organizationAllowed) return []\n return resolveEffectiveFeatures(acl.isSuperAdmin ? ['*'] : acl.features)\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,SAAS,SAAe,MAAM,gBAAgB;AACvD,SAAS,cAAc;AACvB,SAAS,sBAAsB,4BAA4B;AAC3D,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,2BAA2B,mCAAmC;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B,iCAAiC;AACxE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAQvC,SAAS,sBAAsB,QAAiB,UAA4B;AAC1E,QAAM,cAAc,OAAO,eAAe,CAAC,GAAG,IAAI,OAAO;AACzD,QAAM,gBAAgB,SAAS,eAAe,CAAC,GAAG,IAAI,SAAS;AAC/D,QAAM,WAAW,MAAM,KAAK,oBAAI,IAAI;AAAA,IAClC,GAAG,YAAY,OAAO,CAAC,YAAY,WAAW,eAAe,OAAO,CAAC;AAAA,IACrE,GAAG,cAAc,OAAO,CAAC,YAAY,WAAW,aAAa,OAAO,CAAC;AAAA,EACvE,CAAC,CAAC;AACF,QAAM,mBAAmB,OAAO,gBAAgB,OAAO,eAAe,SAAS,SAAS,IACpF,OAAO,OAAO;AAClB,QAAM,qBAAqB,SAAS,gBAAgB,SAAS,eAAe,SAAS,SAAS,IAC1F,OAAO,SAAS;AACpB,QAAM,gBAAgB,qBAAqB,OAAO,qBAC9C,uBAAuB,OAAO,mBAC5B,iBAAiB,OAAO,CAAC,mBAAmB,mBAAmB,SAAS,cAAc,CAAC;AAC7F,SAAO;AAAA,IACL,cAAc,OAAO,gBAAgB,SAAS;AAAA,IAC9C,UAAU,eAAe,WAAW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
|
"names": ["em", "result", "tenantId", "roleIds", "isSuper", "features", "hasApplicableRestrictedRole", "organizations", "roleScope", "roleAcls", "isSuperAdmin", "organizationId"]
|
|
7
7
|
}
|
|
@@ -18,7 +18,8 @@ function resolveOrgScopeTtlMs() {
|
|
|
18
18
|
function buildOrgScopeCacheKey(parts) {
|
|
19
19
|
const selected = parts.selectedOrgId ?? "none";
|
|
20
20
|
const requested = parts.requestedTenantId ?? "none";
|
|
21
|
-
|
|
21
|
+
const namespace = parts.userId.startsWith("api_key:") ? `${ORG_SCOPE_CACHE_KEY_PREFIX}:delegated-v1` : ORG_SCOPE_CACHE_KEY_PREFIX;
|
|
22
|
+
return `${namespace}:${parts.userId}:${parts.effectiveTenantId}:${selected}:${requested}`;
|
|
22
23
|
}
|
|
23
24
|
function buildOrgScopeUserCacheTag(userId) {
|
|
24
25
|
return `${ORG_SCOPE_CACHE_KEY_PREFIX}:user:${userId}`;
|
|
@@ -29,7 +30,8 @@ function buildOrgScopeTenantCacheTag(tenantId) {
|
|
|
29
30
|
function buildOrgScopeCacheTags(parts) {
|
|
30
31
|
return [
|
|
31
32
|
buildOrgScopeUserCacheTag(parts.userId),
|
|
32
|
-
buildOrgScopeTenantCacheTag(parts.effectiveTenantId)
|
|
33
|
+
buildOrgScopeTenantCacheTag(parts.effectiveTenantId),
|
|
34
|
+
...parts.ownerUserId ? [buildOrgScopeUserCacheTag(parts.ownerUserId)] : []
|
|
33
35
|
];
|
|
34
36
|
}
|
|
35
37
|
function isValidCachedScope(value) {
|
|
@@ -315,6 +317,7 @@ async function resolveOrganizationScopeForRequest({
|
|
|
315
317
|
const rawSelected = selectedId !== void 0 ? selectedId : request ? getSelectedOrganizationFromRequest(request) : null;
|
|
316
318
|
const normalizedSelectedId = typeof rawSelected === "string" && rawSelected.trim().length > 0 ? rawSelected.trim() : null;
|
|
317
319
|
const userId = typeof auth.sub === "string" && auth.sub.length > 0 ? auth.sub : null;
|
|
320
|
+
const ownerUserId = auth.isApiKey && typeof auth.userId === "string" && auth.userId.length > 0 ? auth.userId : null;
|
|
318
321
|
const ttlMs = resolveOrgScopeTtlMs();
|
|
319
322
|
const cache = ttlMs > 0 ? resolveCacheFromContainer(container) : null;
|
|
320
323
|
const cacheKey = userId ? buildOrgScopeCacheKey({
|
|
@@ -353,7 +356,7 @@ async function resolveOrganizationScopeForRequest({
|
|
|
353
356
|
try {
|
|
354
357
|
await crossRequestCache.set(cacheKey, baseScope, {
|
|
355
358
|
ttl: ttlMs,
|
|
356
|
-
tags: buildOrgScopeCacheTags({ userId, effectiveTenantId })
|
|
359
|
+
tags: buildOrgScopeCacheTags({ userId, effectiveTenantId, ownerUserId })
|
|
357
360
|
});
|
|
358
361
|
} catch (err) {
|
|
359
362
|
logger.warn("Cache write failed", { err });
|