@open-mercato/core 0.11.1-develop.8534.1.62ca6cfffa → 0.11.1-develop.8538.1.78ea48b6e6
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/.turbo/turbo-build.log +1 -1
- package/dist/modules/auth/services/rbacService.js +11 -12
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/entities/api/encryption.js +13 -2
- package/dist/modules/entities/api/encryption.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/services/rbacService.ts +12 -34
- package/src/modules/entities/api/encryption.ts +14 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -55,6 +55,12 @@ function isAclData(value) {
|
|
|
55
55
|
}
|
|
56
56
|
return true;
|
|
57
57
|
}
|
|
58
|
+
function aclAllowsOrganizationScope(acl, organizationId) {
|
|
59
|
+
if (acl.isSuperAdmin || !acl.organizations) return true;
|
|
60
|
+
if (acl.organizations.includes("__all__")) return true;
|
|
61
|
+
if (!organizationId) return acl.organizations.length > 0;
|
|
62
|
+
return acl.organizations.includes(organizationId);
|
|
63
|
+
}
|
|
58
64
|
function isRestrictedRoleAcl(acl) {
|
|
59
65
|
return Array.isArray(acl.organizationsJson) && acl.organizationsJson.length > 0 && !acl.organizationsJson.includes("__all__");
|
|
60
66
|
}
|
|
@@ -675,19 +681,16 @@ class RbacService {
|
|
|
675
681
|
async userHasAllFeaturesWithEntityManager(em, userId, required, scope) {
|
|
676
682
|
if (!required.length) return true;
|
|
677
683
|
const acl = await this.loadAclWithEntityManager(em, userId, scope);
|
|
678
|
-
const organizationAllowed = acl.isSuperAdmin || !acl.organizations || !scope.organizationId || acl.organizations.includes(scope.organizationId) || acl.organizations.includes("__all__");
|
|
679
684
|
return authorizeFeatures(required, {
|
|
680
685
|
grantedFeatures: acl.features,
|
|
681
686
|
unrestricted: acl.isSuperAdmin,
|
|
682
|
-
scopeAllowed:
|
|
687
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId)
|
|
683
688
|
});
|
|
684
689
|
}
|
|
685
690
|
async getGrantedFeaturesWithEntityManager(em, userId, scope) {
|
|
686
691
|
const acl = await this.loadAclWithEntityManager(em, userId, scope);
|
|
687
692
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(["*"]);
|
|
688
|
-
if (acl
|
|
689
|
-
return [];
|
|
690
|
-
}
|
|
693
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return [];
|
|
691
694
|
return filterGrantsByEnabledModules(acl.features);
|
|
692
695
|
}
|
|
693
696
|
/**
|
|
@@ -756,11 +759,10 @@ class RbacService {
|
|
|
756
759
|
async userHasAllFeatures(userId, required, scope) {
|
|
757
760
|
if (!required.length) return true;
|
|
758
761
|
const acl = await this.loadAcl(userId, scope);
|
|
759
|
-
const organizationAllowed = acl.isSuperAdmin || !acl.organizations || !scope.organizationId || acl.organizations.includes(scope.organizationId) || acl.organizations.includes("__all__");
|
|
760
762
|
return authorizeFeatures(required, {
|
|
761
763
|
grantedFeatures: acl.features,
|
|
762
764
|
unrestricted: acl.isSuperAdmin,
|
|
763
|
-
scopeAllowed:
|
|
765
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId)
|
|
764
766
|
});
|
|
765
767
|
}
|
|
766
768
|
async limitDelegatedKeyAcl(em, key, scope, keyAcl, uncached = false) {
|
|
@@ -942,16 +944,13 @@ class RbacService {
|
|
|
942
944
|
async getGrantedFeatures(userId, scope) {
|
|
943
945
|
const acl = await this.loadAcl(userId, scope);
|
|
944
946
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(["*"]);
|
|
945
|
-
if (acl
|
|
946
|
-
return [];
|
|
947
|
-
}
|
|
947
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return [];
|
|
948
948
|
return filterGrantsByEnabledModules(acl.features);
|
|
949
949
|
}
|
|
950
950
|
/** Returns concrete active feature IDs for browser capability payloads. */
|
|
951
951
|
async getEffectiveFeatures(userId, scope) {
|
|
952
952
|
const acl = await this.loadAcl(userId, scope);
|
|
953
|
-
|
|
954
|
-
if (!organizationAllowed) return [];
|
|
953
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return [];
|
|
955
954
|
return resolveEffectiveFeatures(acl.isSuperAdmin ? ["*"] : acl.features);
|
|
956
955
|
}
|
|
957
956
|
}
|
|
@@ -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 { 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,OA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6BAA6B,IAAI,QAAQ;AAAA,EAClD;AAAA;AAAA,EAGA,MAAM,qBACJ,QACA,OACmB;AACnB,UAAM,MAAM,MAAM,KAAK,QAAQ,QAAQ,KAAK;AAC5C,UAAM,sBAAsB,IAAI,gBAC3B,CAAC,IAAI,iBACL,CAAC,MAAM,kBACP,IAAI,cAAc,SAAS,MAAM,cAAc,KAC/C,IAAI,cAAc,SAAS,SAAS;AACzC,QAAI,CAAC,oBAAqB,QAAO,CAAC;AAClC,WAAO,yBAAyB,IAAI,eAAe,CAAC,GAAG,IAAI,IAAI,QAAQ;AAAA,EACzE;AACF;",
|
|
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 { 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 aclAllowsOrganizationScope(acl: AclData, organizationId: string | null): boolean {\n if (acl.isSuperAdmin || !acl.organizations) return true\n if (acl.organizations.includes('__all__')) return true\n if (!organizationId) return acl.organizations.length > 0\n return acl.organizations.includes(organizationId)\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 return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),\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 (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []\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 return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),\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 (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []\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 if (!aclAllowsOrganizationScope(acl, scope.organizationId)) 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,QAA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ACzE;AACF;",
|
|
6
6
|
"names": ["em", "result", "tenantId", "roleIds", "isSuper", "features", "hasApplicableRestrictedRole", "organizations", "roleScope", "roleAcls", "isSuperAdmin", "organizationId"]
|
|
7
7
|
}
|
|
@@ -4,7 +4,8 @@ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
|
|
|
4
4
|
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
|
|
5
5
|
import { EncryptionMap } from "@open-mercato/core/modules/entities/data/entities";
|
|
6
6
|
import { upsertEncryptionMapSchema } from "@open-mercato/core/modules/entities/data/validators";
|
|
7
|
-
import { CrudHttpError, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
7
|
+
import { CrudHttpError, forbidden, isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
|
|
8
|
+
import { isExplicitlyEmptyOrganizationScope } from "@open-mercato/shared/lib/auth/organizationScope";
|
|
8
9
|
import {
|
|
9
10
|
buildOptimisticLockConflictBody,
|
|
10
11
|
enforceCommandOptimisticLock,
|
|
@@ -54,6 +55,10 @@ async function GET(req) {
|
|
|
54
55
|
if (!auth?.tenantId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
55
56
|
const container = await createRequestContainer();
|
|
56
57
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
58
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) {
|
|
59
|
+
const denied = forbidden();
|
|
60
|
+
return NextResponse.json(denied.body, { status: denied.status });
|
|
61
|
+
}
|
|
57
62
|
const tenantId = scope.tenantId ?? auth.tenantId;
|
|
58
63
|
const organizationId = scope.selectedId;
|
|
59
64
|
const em = container.resolve("em");
|
|
@@ -96,6 +101,7 @@ async function POST(req) {
|
|
|
96
101
|
const payload = parsed.data;
|
|
97
102
|
const container = await createRequestContainer();
|
|
98
103
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
|
|
104
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden();
|
|
99
105
|
if (scope.selectionRejected) {
|
|
100
106
|
return NextResponse.json(
|
|
101
107
|
{
|
|
@@ -200,6 +206,7 @@ const conflictResponseSchema = z.object({
|
|
|
200
206
|
currentUpdatedAt: z.string(),
|
|
201
207
|
expectedUpdatedAt: z.string()
|
|
202
208
|
});
|
|
209
|
+
const forbiddenResponseSchema = z.object({ error: z.string() });
|
|
203
210
|
const organizationSelectionInvalidResponseSchema = z.object({
|
|
204
211
|
error: z.string(),
|
|
205
212
|
code: z.literal("organization_selection_invalid")
|
|
@@ -212,7 +219,10 @@ const openApi = {
|
|
|
212
219
|
summary: "Fetch encryption map",
|
|
213
220
|
description: "Returns the encrypted field map for the current tenant/organization scope.",
|
|
214
221
|
query: z.object({ entityId: z.string() }),
|
|
215
|
-
responses: [
|
|
222
|
+
responses: [
|
|
223
|
+
{ status: 200, description: "Map", schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },
|
|
224
|
+
{ status: 403, description: "Caller can see no organization", schema: forbiddenResponseSchema }
|
|
225
|
+
]
|
|
216
226
|
},
|
|
217
227
|
POST: {
|
|
218
228
|
summary: "Upsert encryption map",
|
|
@@ -220,6 +230,7 @@ const openApi = {
|
|
|
220
230
|
requestBody: { contentType: "application/json", schema: upsertEncryptionMapSchema },
|
|
221
231
|
responses: [
|
|
222
232
|
{ status: 200, description: "Saved", schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },
|
|
233
|
+
{ status: 403, description: "Caller can see no organization", schema: forbiddenResponseSchema },
|
|
223
234
|
{ status: 409, description: "Optimistic-lock conflict (stale write)", schema: conflictResponseSchema },
|
|
224
235
|
{ status: 422, description: "Selected organization is unavailable", schema: organizationSelectionInvalidResponseSchema }
|
|
225
236
|
]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/entities/api/encryption.ts"],
|
|
4
|
-
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n readOptimisticLockExpected,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { normalizeIsoToken, parseOptimisticLockEnv } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { OPTIMISTIC_LOCK_ENV_VAR } from '@open-mercato/shared/lib/crud/optimistic-lock-headers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n EncryptionMapVersionConflictError,\n resolveCanonicalEncryptionMap,\n upsertCanonicalEncryptionMap,\n} from '@open-mercato/core/modules/entities/lib/encryption-maps'\n\nconst ENCRYPTION_MAP_RESOURCE_KIND = 'entities.encryption_map'\n\nconst logger = createLogger('entities').child({ component: 'encryption-map-api' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction shouldEnforceVersionOnWrite(req: Request): boolean {\n const expected = readOptimisticLockExpected(req)\n if (!expected || normalizeIsoToken(expected) == null) return false\n const config = parseOptimisticLockEnv(process.env[OPTIMISTIC_LOCK_ENV_VAR])\n if (config.mode === 'off') return false\n return config.mode === 'all' || config.entities.has(ENCRYPTION_MAP_RESOURCE_KIND)\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n return trimmed.length ? trimmed : null\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n // Prefer tenant+org, then tenant-global, then global\n const candidates = [\n { entityId, tenantId, organizationId },\n { entityId, tenantId, organizationId: null },\n { entityId, tenantId: null, organizationId: null },\n ]\n let record: ReturnType<typeof resolveCanonicalEncryptionMap> = null\n for (const where of candidates) {\n const found = await repo.find(\n { ...where, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const canonical = resolveCanonicalEncryptionMap(found)\n if (canonical) {\n record = canonical\n break\n }\n }\n\n return NextResponse.json({\n entityId,\n tenantId,\n organizationId,\n fields: record?.fieldsJson ?? [],\n isActive: record?.isActive ?? true,\n updatedAt: toIsoOrNull(record?.updatedAt),\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = upsertEncryptionMapSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsed.error.flatten() }, { status: 400 })\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const payload = parsed.data\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (scope.selectionRejected) {\n return NextResponse.json(\n {\n error: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n code: 'organization_selection_invalid',\n },\n { status: 422 },\n )\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n const existingRecords = await repo.find(\n { entityId: payload.entityId, tenantId, organizationId, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const existing = resolveCanonicalEncryptionMap(existingRecords)\n\n // Reject stale writes: a save started from an older tab must not silently\n // overwrite a newer encryption configuration. No-op when the client did not\n // send the expected-version header (strictly additive).\n if (existing) {\n enforceCommandOptimisticLock({\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt,\n request: req,\n })\n }\n\n // Mutation-guard contract for custom write routes. The resource is the\n // encryption map for this entity scoped to the tenant/organization.\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing?.id ?? payload.entityId,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let saved: Awaited<ReturnType<typeof upsertCanonicalEncryptionMap>>\n try {\n saved = await upsertCanonicalEncryptionMap(em, {\n entityId: payload.entityId,\n tenantId,\n organizationId,\n fields: payload.fields,\n isActive: payload.isActive ?? true,\n // The version check above is advisory; this makes the write itself conditional so a\n // concurrent save that lands between that read and this upsert is not overwritten.\n expectedUpdatedAt: existing && shouldEnforceVersionOnWrite(req) ? existing.updatedAt : null,\n })\n } catch (err) {\n if (err instanceof EncryptionMapVersionConflictError) {\n const expectedIso = err.expectedUpdatedAt.toISOString()\n const currentIso = err.currentUpdatedAt ? err.currentUpdatedAt.toISOString() : expectedIso\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(currentIso, expectedIso))\n }\n throw err\n }\n\n // The map row is committed and every reader resolves policy from it, so a failure to drop\n // this process's per-request memo must not turn a successful write into an error response.\n try {\n const svc = container.resolve('tenantEncryptionService') as { invalidateMap?: (e: string, t: string | null, o: string | null) => Promise<void> }\n if (!svc || typeof svc.invalidateMap !== 'function') {\n throw new Error('[internal] Tenant encryption service cannot invalidate map caches')\n }\n await svc.invalidateMap(payload.entityId, tenantId, organizationId)\n } catch (err) {\n logger.warn('Encryption map saved but post-commit invalidation failed', {\n entityId: payload.entityId,\n err,\n })\n getTelemetryRuntime()?.reportError(err, {\n module: 'entities',\n code: 'entities.encryption_map_invalidation_failed',\n attributes: { entityId: payload.entityId },\n })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: saved.id,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: toIsoOrNull(saved.updatedAt) })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n throw err\n }\n}\n\nconst conflictResponseSchema = z.object({\n error: z.string(),\n code: z.string(),\n currentUpdatedAt: z.string(),\n expectedUpdatedAt: z.string(),\n})\n\nconst organizationSelectionInvalidResponseSchema = z.object({\n error: z.string(),\n code: z.literal('organization_selection_invalid'),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage encryption maps',\n methods: {\n GET: {\n summary: 'Fetch encryption map',\n description: 'Returns the encrypted field map for the current tenant/organization scope.',\n query: z.object({ entityId: z.string() }),\n responses: [{ status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) }],\n },\n POST: {\n summary: 'Upsert encryption map',\n description: 'Creates or updates the encryption map for the current tenant/organization scope. Enforces optimistic locking when the caller sends the expected version header.',\n requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },\n responses: [\n { status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },\n { status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },\n { status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AAC1C,SAAS,eAAe,uBAAuB;
|
|
4
|
+
"sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'\nimport { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { CrudHttpError, forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'\nimport {\n buildOptimisticLockConflictBody,\n enforceCommandOptimisticLock,\n readOptimisticLockExpected,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { normalizeIsoToken, parseOptimisticLockEnv } from '@open-mercato/shared/lib/crud/optimistic-lock'\nimport { OPTIMISTIC_LOCK_ENV_VAR } from '@open-mercato/shared/lib/crud/optimistic-lock-headers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n EncryptionMapVersionConflictError,\n resolveCanonicalEncryptionMap,\n upsertCanonicalEncryptionMap,\n} from '@open-mercato/core/modules/entities/lib/encryption-maps'\n\nconst ENCRYPTION_MAP_RESOURCE_KIND = 'entities.encryption_map'\n\nconst logger = createLogger('entities').child({ component: 'encryption-map-api' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n POST: { requireAuth: true, requireFeatures: ['entities.definitions.manage'] },\n}\n\nfunction shouldEnforceVersionOnWrite(req: Request): boolean {\n const expected = readOptimisticLockExpected(req)\n if (!expected || normalizeIsoToken(expected) == null) return false\n const config = parseOptimisticLockEnv(process.env[OPTIMISTIC_LOCK_ENV_VAR])\n if (config.mode === 'off') return false\n return config.mode === 'all' || config.entities.has(ENCRYPTION_MAP_RESOURCE_KIND)\n}\n\nfunction toIsoOrNull(value: Date | string | null | undefined): string | null {\n if (value == null) return null\n if (value instanceof Date) {\n const ms = value.getTime()\n return Number.isFinite(ms) ? new Date(ms).toISOString() : null\n }\n const trimmed = String(value).trim()\n return trimmed.length ? trimmed : null\n}\n\nexport async function GET(req: Request) {\n const url = new URL(req.url)\n const entityId = url.searchParams.get('entityId') || ''\n if (!entityId) return NextResponse.json({ error: 'entityId is required' }, { status: 400 })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (isExplicitlyEmptyOrganizationScope(scope)) {\n const denied = forbidden()\n return NextResponse.json(denied.body, { status: denied.status })\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n // Prefer tenant+org, then tenant-global, then global\n const candidates = [\n { entityId, tenantId, organizationId },\n { entityId, tenantId, organizationId: null },\n { entityId, tenantId: null, organizationId: null },\n ]\n let record: ReturnType<typeof resolveCanonicalEncryptionMap> = null\n for (const where of candidates) {\n const found = await repo.find(\n { ...where, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const canonical = resolveCanonicalEncryptionMap(found)\n if (canonical) {\n record = canonical\n break\n }\n }\n\n return NextResponse.json({\n entityId,\n tenantId,\n organizationId,\n fields: record?.fieldsJson ?? [],\n isActive: record?.isActive ?? true,\n updatedAt: toIsoOrNull(record?.updatedAt),\n })\n}\n\nexport async function POST(req: Request) {\n try {\n const body = await req.json().catch(() => ({}))\n const parsed = upsertEncryptionMapSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid payload', details: parsed.error.flatten() }, { status: 400 })\n }\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n const payload = parsed.data\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden()\n if (scope.selectionRejected) {\n return NextResponse.json(\n {\n error: 'Your selected organization is no longer available. Please re-select an organization and try again.',\n code: 'organization_selection_invalid',\n },\n { status: 422 },\n )\n }\n const tenantId = scope.tenantId ?? auth.tenantId\n const organizationId = scope.selectedId\n const em = container.resolve('em') as any\n const repo = em.getRepository(EncryptionMap)\n const existingRecords = await repo.find(\n { entityId: payload.entityId, tenantId, organizationId, deletedAt: null },\n { orderBy: { createdAt: 'asc', id: 'asc' } },\n )\n const existing = resolveCanonicalEncryptionMap(existingRecords)\n\n // Reject stale writes: a save started from an older tab must not silently\n // overwrite a newer encryption configuration. No-op when the client did not\n // send the expected-version header (strictly additive).\n if (existing) {\n enforceCommandOptimisticLock({\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing.id,\n current: existing.updatedAt,\n request: req,\n })\n }\n\n // Mutation-guard contract for custom write routes. The resource is the\n // encryption map for this entity scoped to the tenant/organization.\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: existing?.id ?? payload.entityId,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n let saved: Awaited<ReturnType<typeof upsertCanonicalEncryptionMap>>\n try {\n saved = await upsertCanonicalEncryptionMap(em, {\n entityId: payload.entityId,\n tenantId,\n organizationId,\n fields: payload.fields,\n isActive: payload.isActive ?? true,\n // The version check above is advisory; this makes the write itself conditional so a\n // concurrent save that lands between that read and this upsert is not overwritten.\n expectedUpdatedAt: existing && shouldEnforceVersionOnWrite(req) ? existing.updatedAt : null,\n })\n } catch (err) {\n if (err instanceof EncryptionMapVersionConflictError) {\n const expectedIso = err.expectedUpdatedAt.toISOString()\n const currentIso = err.currentUpdatedAt ? err.currentUpdatedAt.toISOString() : expectedIso\n throw new CrudHttpError(409, buildOptimisticLockConflictBody(currentIso, expectedIso))\n }\n throw err\n }\n\n // The map row is committed and every reader resolves policy from it, so a failure to drop\n // this process's per-request memo must not turn a successful write into an error response.\n try {\n const svc = container.resolve('tenantEncryptionService') as { invalidateMap?: (e: string, t: string | null, o: string | null) => Promise<void> }\n if (!svc || typeof svc.invalidateMap !== 'function') {\n throw new Error('[internal] Tenant encryption service cannot invalidate map caches')\n }\n await svc.invalidateMap(payload.entityId, tenantId, organizationId)\n } catch (err) {\n logger.warn('Encryption map saved but post-commit invalidation failed', {\n entityId: payload.entityId,\n err,\n })\n getTelemetryRuntime()?.reportError(err, {\n module: 'entities',\n code: 'entities.encryption_map_invalidation_failed',\n attributes: { entityId: payload.entityId },\n })\n }\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId,\n organizationId,\n userId: auth.sub,\n resourceKind: ENCRYPTION_MAP_RESOURCE_KIND,\n resourceId: saved.id,\n operation: existing ? 'update' : 'create',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n return NextResponse.json({ ok: true, updatedAt: toIsoOrNull(saved.updatedAt) })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n throw err\n }\n}\n\nconst conflictResponseSchema = z.object({\n error: z.string(),\n code: z.string(),\n currentUpdatedAt: z.string(),\n expectedUpdatedAt: z.string(),\n})\n\nconst forbiddenResponseSchema = z.object({ error: z.string() })\n\nconst organizationSelectionInvalidResponseSchema = z.object({\n error: z.string(),\n code: z.literal('organization_selection_invalid'),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Entities',\n summary: 'Manage encryption maps',\n methods: {\n GET: {\n summary: 'Fetch encryption map',\n description: 'Returns the encrypted field map for the current tenant/organization scope.',\n query: z.object({ entityId: z.string() }),\n responses: [\n { status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },\n { status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },\n ],\n },\n POST: {\n summary: 'Upsert encryption map',\n description: 'Creates or updates the encryption map for the current tenant/organization scope. Enforces optimistic locking when the caller sends the expected version header.',\n requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },\n responses: [\n { status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },\n { status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },\n { status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },\n { status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },\n ],\n },\n },\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,qBAAqB;AAC9B,SAAS,iCAAiC;AAC1C,SAAS,eAAe,WAAW,uBAAuB;AAC1D,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D,SAAS,+BAA+B;AACxC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,0CAA0C;AACnD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,+BAA+B;AAErC,MAAM,SAAS,aAAa,UAAU,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAE1E,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAAA,EAC3E,MAAM,EAAE,aAAa,MAAM,iBAAiB,CAAC,6BAA6B,EAAE;AAC9E;AAEA,SAAS,4BAA4B,KAAuB;AAC1D,QAAM,WAAW,2BAA2B,GAAG;AAC/C,MAAI,CAAC,YAAY,kBAAkB,QAAQ,KAAK,KAAM,QAAO;AAC7D,QAAM,SAAS,uBAAuB,QAAQ,IAAI,uBAAuB,CAAC;AAC1E,MAAI,OAAO,SAAS,MAAO,QAAO;AAClC,SAAO,OAAO,SAAS,SAAS,OAAO,SAAS,IAAI,4BAA4B;AAClF;AAEA,SAAS,YAAY,OAAwD;AAC3E,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,iBAAiB,MAAM;AACzB,UAAM,KAAK,MAAM,QAAQ;AACzB,WAAO,OAAO,S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
3
|
-
"version": "0.11.1-develop.
|
|
3
|
+
"version": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -268,16 +268,16 @@
|
|
|
268
268
|
"zod": "^4.6.6"
|
|
269
269
|
},
|
|
270
270
|
"peerDependencies": {
|
|
271
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
272
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
273
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
271
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
272
|
+
"@open-mercato/shared": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
273
|
+
"@open-mercato/ui": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
274
274
|
"react": "^19.0.0",
|
|
275
275
|
"react-dom": "^19.0.0"
|
|
276
276
|
},
|
|
277
277
|
"devDependencies": {
|
|
278
|
-
"@open-mercato/ai-assistant": "0.11.1-develop.
|
|
279
|
-
"@open-mercato/shared": "0.11.1-develop.
|
|
280
|
-
"@open-mercato/ui": "0.11.1-develop.
|
|
278
|
+
"@open-mercato/ai-assistant": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
279
|
+
"@open-mercato/shared": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
280
|
+
"@open-mercato/ui": "0.11.1-develop.8538.1.78ea48b6e6",
|
|
281
281
|
"@testing-library/dom": "^10.4.1",
|
|
282
282
|
"@testing-library/jest-dom": "^7.0.1",
|
|
283
283
|
"@testing-library/react": "^16.3.3",
|
|
@@ -79,6 +79,13 @@ function isAclData(value: unknown): value is AclData {
|
|
|
79
79
|
return true
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
function aclAllowsOrganizationScope(acl: AclData, organizationId: string | null): boolean {
|
|
83
|
+
if (acl.isSuperAdmin || !acl.organizations) return true
|
|
84
|
+
if (acl.organizations.includes('__all__')) return true
|
|
85
|
+
if (!organizationId) return acl.organizations.length > 0
|
|
86
|
+
return acl.organizations.includes(organizationId)
|
|
87
|
+
}
|
|
88
|
+
|
|
82
89
|
function isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {
|
|
83
90
|
return Array.isArray(acl.organizationsJson)
|
|
84
91
|
&& acl.organizationsJson.length > 0
|
|
@@ -912,15 +919,10 @@ export class RbacService {
|
|
|
912
919
|
): Promise<boolean> {
|
|
913
920
|
if (!required.length) return true
|
|
914
921
|
const acl = await this.loadAclWithEntityManager(em, userId, scope)
|
|
915
|
-
const organizationAllowed = acl.isSuperAdmin
|
|
916
|
-
|| !acl.organizations
|
|
917
|
-
|| !scope.organizationId
|
|
918
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
919
|
-
|| acl.organizations.includes('__all__')
|
|
920
922
|
return authorizeFeatures(required, {
|
|
921
923
|
grantedFeatures: acl.features,
|
|
922
924
|
unrestricted: acl.isSuperAdmin,
|
|
923
|
-
scopeAllowed:
|
|
925
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),
|
|
924
926
|
})
|
|
925
927
|
}
|
|
926
928
|
|
|
@@ -931,14 +933,7 @@ export class RbacService {
|
|
|
931
933
|
): Promise<string[]> {
|
|
932
934
|
const acl = await this.loadAclWithEntityManager(em, userId, scope)
|
|
933
935
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])
|
|
934
|
-
if (
|
|
935
|
-
acl.organizations
|
|
936
|
-
&& scope.organizationId
|
|
937
|
-
&& !acl.organizations.includes(scope.organizationId)
|
|
938
|
-
&& !acl.organizations.includes('__all__')
|
|
939
|
-
) {
|
|
940
|
-
return []
|
|
941
|
-
}
|
|
936
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
942
937
|
return filterGrantsByEnabledModules(acl.features)
|
|
943
938
|
}
|
|
944
939
|
|
|
@@ -1016,15 +1011,10 @@ export class RbacService {
|
|
|
1016
1011
|
async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {
|
|
1017
1012
|
if (!required.length) return true
|
|
1018
1013
|
const acl = await this.loadAcl(userId, scope)
|
|
1019
|
-
const organizationAllowed = acl.isSuperAdmin
|
|
1020
|
-
|| !acl.organizations
|
|
1021
|
-
|| !scope.organizationId
|
|
1022
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
1023
|
-
|| acl.organizations.includes('__all__')
|
|
1024
1014
|
return authorizeFeatures(required, {
|
|
1025
1015
|
grantedFeatures: acl.features,
|
|
1026
1016
|
unrestricted: acl.isSuperAdmin,
|
|
1027
|
-
scopeAllowed:
|
|
1017
|
+
scopeAllowed: aclAllowsOrganizationScope(acl, scope.organizationId),
|
|
1028
1018
|
})
|
|
1029
1019
|
}
|
|
1030
1020
|
|
|
@@ -1273,14 +1263,7 @@ export class RbacService {
|
|
|
1273
1263
|
): Promise<string[]> {
|
|
1274
1264
|
const acl = await this.loadAcl(userId, scope)
|
|
1275
1265
|
if (acl.isSuperAdmin) return filterGrantsByEnabledModules(['*'])
|
|
1276
|
-
if (
|
|
1277
|
-
acl.organizations &&
|
|
1278
|
-
scope.organizationId &&
|
|
1279
|
-
!acl.organizations.includes(scope.organizationId) &&
|
|
1280
|
-
!acl.organizations.includes('__all__')
|
|
1281
|
-
) {
|
|
1282
|
-
return []
|
|
1283
|
-
}
|
|
1266
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
1284
1267
|
return filterGrantsByEnabledModules(acl.features)
|
|
1285
1268
|
}
|
|
1286
1269
|
|
|
@@ -1290,12 +1273,7 @@ export class RbacService {
|
|
|
1290
1273
|
scope: { tenantId: string | null; organizationId: string | null },
|
|
1291
1274
|
): Promise<string[]> {
|
|
1292
1275
|
const acl = await this.loadAcl(userId, scope)
|
|
1293
|
-
|
|
1294
|
-
|| !acl.organizations
|
|
1295
|
-
|| !scope.organizationId
|
|
1296
|
-
|| acl.organizations.includes(scope.organizationId)
|
|
1297
|
-
|| acl.organizations.includes('__all__')
|
|
1298
|
-
if (!organizationAllowed) return []
|
|
1276
|
+
if (!aclAllowsOrganizationScope(acl, scope.organizationId)) return []
|
|
1299
1277
|
return resolveEffectiveFeatures(acl.isSuperAdmin ? ['*'] : acl.features)
|
|
1300
1278
|
}
|
|
1301
1279
|
}
|
|
@@ -4,7 +4,8 @@ import { createRequestContainer } from '@open-mercato/shared/lib/di/container'
|
|
|
4
4
|
import { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'
|
|
5
5
|
import { EncryptionMap } from '@open-mercato/core/modules/entities/data/entities'
|
|
6
6
|
import { upsertEncryptionMapSchema } from '@open-mercato/core/modules/entities/data/validators'
|
|
7
|
-
import { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
7
|
+
import { CrudHttpError, forbidden, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'
|
|
8
|
+
import { isExplicitlyEmptyOrganizationScope } from '@open-mercato/shared/lib/auth/organizationScope'
|
|
8
9
|
import {
|
|
9
10
|
buildOptimisticLockConflictBody,
|
|
10
11
|
enforceCommandOptimisticLock,
|
|
@@ -62,6 +63,10 @@ export async function GET(req: Request) {
|
|
|
62
63
|
|
|
63
64
|
const container = await createRequestContainer()
|
|
64
65
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
|
|
66
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) {
|
|
67
|
+
const denied = forbidden()
|
|
68
|
+
return NextResponse.json(denied.body, { status: denied.status })
|
|
69
|
+
}
|
|
65
70
|
const tenantId = scope.tenantId ?? auth.tenantId
|
|
66
71
|
const organizationId = scope.selectedId
|
|
67
72
|
const em = container.resolve('em') as any
|
|
@@ -108,6 +113,7 @@ export async function POST(req: Request) {
|
|
|
108
113
|
|
|
109
114
|
const container = await createRequestContainer()
|
|
110
115
|
const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })
|
|
116
|
+
if (isExplicitlyEmptyOrganizationScope(scope)) throw forbidden()
|
|
111
117
|
if (scope.selectionRejected) {
|
|
112
118
|
return NextResponse.json(
|
|
113
119
|
{
|
|
@@ -227,6 +233,8 @@ const conflictResponseSchema = z.object({
|
|
|
227
233
|
expectedUpdatedAt: z.string(),
|
|
228
234
|
})
|
|
229
235
|
|
|
236
|
+
const forbiddenResponseSchema = z.object({ error: z.string() })
|
|
237
|
+
|
|
230
238
|
const organizationSelectionInvalidResponseSchema = z.object({
|
|
231
239
|
error: z.string(),
|
|
232
240
|
code: z.literal('organization_selection_invalid'),
|
|
@@ -240,7 +248,10 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
240
248
|
summary: 'Fetch encryption map',
|
|
241
249
|
description: 'Returns the encrypted field map for the current tenant/organization scope.',
|
|
242
250
|
query: z.object({ entityId: z.string() }),
|
|
243
|
-
responses: [
|
|
251
|
+
responses: [
|
|
252
|
+
{ status: 200, description: 'Map', schema: z.object({ entityId: z.string(), fields: z.array(z.object({ field: z.string(), hashField: z.string().nullable().optional() })), isActive: z.boolean().optional(), updatedAt: z.string().nullable().optional() }) },
|
|
253
|
+
{ status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },
|
|
254
|
+
],
|
|
244
255
|
},
|
|
245
256
|
POST: {
|
|
246
257
|
summary: 'Upsert encryption map',
|
|
@@ -248,6 +259,7 @@ export const openApi: OpenApiRouteDoc = {
|
|
|
248
259
|
requestBody: { contentType: 'application/json', schema: upsertEncryptionMapSchema },
|
|
249
260
|
responses: [
|
|
250
261
|
{ status: 200, description: 'Saved', schema: z.object({ ok: z.boolean(), updatedAt: z.string().nullable().optional() }) },
|
|
262
|
+
{ status: 403, description: 'Caller can see no organization', schema: forbiddenResponseSchema },
|
|
251
263
|
{ status: 409, description: 'Optimistic-lock conflict (stale write)', schema: conflictResponseSchema },
|
|
252
264
|
{ status: 422, description: 'Selected organization is unavailable', schema: organizationSelectionInvalidResponseSchema },
|
|
253
265
|
],
|