@open-mercato/core 0.10.1-develop.7749.1.ea3edf75e3 → 0.10.1-develop.7751.1.a11f57298b
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/api_keys/services/principalService.js +3 -2
- package/dist/modules/api_keys/services/principalService.js.map +2 -2
- package/dist/modules/api_keys/services/sessionKeyRoles.js +29 -0
- package/dist/modules/api_keys/services/sessionKeyRoles.js.map +7 -0
- package/dist/modules/auth/services/rbacService.js +18 -10
- package/dist/modules/auth/services/rbacService.js.map +2 -2
- package/dist/modules/business_rules/lib/action-executor.js +2 -1
- package/dist/modules/business_rules/lib/action-executor.js.map +2 -2
- package/dist/modules/directory/utils/organizationScope.js +11 -4
- package/dist/modules/directory/utils/organizationScope.js.map +2 -2
- package/dist/modules/warranty_claims/commands/claim-lines.js +25 -1
- package/dist/modules/warranty_claims/commands/claim-lines.js.map +3 -3
- package/dist/modules/warranty_claims/commands/claims.js +19 -1
- package/dist/modules/warranty_claims/commands/claims.js.map +2 -2
- package/dist/modules/warranty_claims/commands/shared.js +30 -0
- package/dist/modules/warranty_claims/commands/shared.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/api_keys/services/principalService.ts +3 -2
- package/src/modules/api_keys/services/sessionKeyRoles.ts +35 -0
- package/src/modules/auth/services/rbacService.ts +22 -9
- package/src/modules/business_rules/lib/action-executor.ts +2 -3
- package/src/modules/directory/utils/organizationScope.ts +11 -4
- package/src/modules/warranty_claims/commands/claim-lines.ts +26 -1
- package/src/modules/warranty_claims/commands/claims.ts +19 -1
- package/src/modules/warranty_claims/commands/shared.ts +36 -1
- package/src/modules/warranty_claims/i18n/de.json +1 -0
- package/src/modules/warranty_claims/i18n/en.json +1 -0
- package/src/modules/warranty_claims/i18n/es.json +1 -0
- package/src/modules/warranty_claims/i18n/ko.json +1 -0
- package/src/modules/warranty_claims/i18n/pl.json +1 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
2
2
|
import { ApiKey } from "../data/entities.js";
|
|
3
|
+
import { resolveApiKeyRoleIds } from "./sessionKeyRoles.js";
|
|
3
4
|
function normalizeIds(ids) {
|
|
4
5
|
if (!Array.isArray(ids)) return [];
|
|
5
6
|
return Array.from(new Set(ids.map((id) => typeof id === "string" ? id.trim() : "").filter(Boolean)));
|
|
@@ -18,11 +19,11 @@ class DefaultApiKeyPrincipalService {
|
|
|
18
19
|
deletedAt: null,
|
|
19
20
|
$or: [{ organizationId: null }, { organizationId: scope.organizationId }]
|
|
20
21
|
},
|
|
21
|
-
{ fields: ["rolesJson", "expiresAt"] },
|
|
22
|
+
{ fields: ["rolesJson", "expiresAt", "tenantId", "sessionTokenHash", "sessionUserId", "sessionSecretEncrypted", "opencodeSessionId"] },
|
|
22
23
|
scope
|
|
23
24
|
);
|
|
24
25
|
if (!apiKey || apiKey.expiresAt && apiKey.expiresAt.getTime() <= Date.now()) return [];
|
|
25
|
-
return normalizeIds(apiKey.
|
|
26
|
+
return normalizeIds(await resolveApiKeyRoleIds(this.em, apiKey, scope.tenantId));
|
|
26
27
|
}
|
|
27
28
|
}
|
|
28
29
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/api_keys/services/principalService.ts"],
|
|
4
|
-
"sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ApiKeyPrincipalService, PrincipalScope } from '@open-mercato/shared/lib/auth/principal-service'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { ApiKey } from '../data/entities'\n\nfunction normalizeIds(ids: unknown): string[] {\n if (!Array.isArray(ids)) return []\n return Array.from(new Set(ids\n .map((id) => typeof id === 'string' ? id.trim() : '')\n .filter(Boolean)))\n}\n\nexport class DefaultApiKeyPrincipalService implements ApiKeyPrincipalService {\n constructor(private readonly em: EntityManager) {}\n\n async resolveAssignedRoleIds(apiKeyId: string, scope: PrincipalScope): Promise<string[]> {\n const apiKey = await findOneWithDecryption(\n this.em,\n ApiKey,\n {\n id: apiKeyId,\n tenantId: scope.tenantId,\n deletedAt: null,\n $or: [{ organizationId: null }, { organizationId: scope.organizationId }],\n } as FilterQuery<ApiKey>,\n { fields: ['rolesJson', 'expiresAt'] as const },\n scope,\n )\n if (!apiKey || (apiKey.expiresAt && apiKey.expiresAt.getTime() <= Date.now())) return []\n return normalizeIds(apiKey.
|
|
5
|
-
"mappings": "AAGA,SAAS,6BAA6B;AACtC,SAAS,cAAc;
|
|
4
|
+
"sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ApiKeyPrincipalService, PrincipalScope } from '@open-mercato/shared/lib/auth/principal-service'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { ApiKey } from '../data/entities'\nimport { resolveApiKeyRoleIds } from './sessionKeyRoles'\n\nfunction normalizeIds(ids: unknown): string[] {\n if (!Array.isArray(ids)) return []\n return Array.from(new Set(ids\n .map((id) => typeof id === 'string' ? id.trim() : '')\n .filter(Boolean)))\n}\n\nexport class DefaultApiKeyPrincipalService implements ApiKeyPrincipalService {\n constructor(private readonly em: EntityManager) {}\n\n async resolveAssignedRoleIds(apiKeyId: string, scope: PrincipalScope): Promise<string[]> {\n const apiKey = await findOneWithDecryption(\n this.em,\n ApiKey,\n {\n id: apiKeyId,\n tenantId: scope.tenantId,\n deletedAt: null,\n $or: [{ organizationId: null }, { organizationId: scope.organizationId }],\n } as FilterQuery<ApiKey>,\n { fields: ['rolesJson', 'expiresAt', 'tenantId', 'sessionTokenHash', 'sessionUserId', 'sessionSecretEncrypted', 'opencodeSessionId'] as const },\n scope,\n )\n if (!apiKey || (apiKey.expiresAt && apiKey.expiresAt.getTime() <= Date.now())) return []\n return normalizeIds(await resolveApiKeyRoleIds(this.em, apiKey, scope.tenantId))\n }\n}\n"],
|
|
5
|
+
"mappings": "AAGA,SAAS,6BAA6B;AACtC,SAAS,cAAc;AACvB,SAAS,4BAA4B;AAErC,SAAS,aAAa,KAAwB;AAC5C,MAAI,CAAC,MAAM,QAAQ,GAAG,EAAG,QAAO,CAAC;AACjC,SAAO,MAAM,KAAK,IAAI,IAAI,IACvB,IAAI,CAAC,OAAO,OAAO,OAAO,WAAW,GAAG,KAAK,IAAI,EAAE,EACnD,OAAO,OAAO,CAAC,CAAC;AACrB;AAEO,MAAM,8BAAgE;AAAA,EAC3E,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAEjD,MAAM,uBAAuB,UAAkB,OAA0C;AACvF,UAAM,SAAS,MAAM;AAAA,MACnB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,IAAI;AAAA,QACJ,UAAU,MAAM;AAAA,QAChB,WAAW;AAAA,QACX,KAAK,CAAC,EAAE,gBAAgB,KAAK,GAAG,EAAE,gBAAgB,MAAM,eAAe,CAAC;AAAA,MAC1E;AAAA,MACA,EAAE,QAAQ,CAAC,aAAa,aAAa,YAAY,oBAAoB,iBAAiB,0BAA0B,mBAAmB,EAAW;AAAA,MAC9I;AAAA,IACF;AACA,QAAI,CAAC,UAAW,OAAO,aAAa,OAAO,UAAU,QAAQ,KAAK,KAAK,IAAI,EAAI,QAAO,CAAC;AACvF,WAAO,aAAa,MAAM,qBAAqB,KAAK,IAAI,QAAQ,MAAM,QAAQ,CAAC;AAAA,EACjF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { UserRole } from "@open-mercato/core/modules/auth/data/entities";
|
|
2
|
+
import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
3
|
+
function isSessionBoundApiKey(key) {
|
|
4
|
+
return Boolean(key.sessionTokenHash || key.sessionUserId || key.sessionSecretEncrypted || key.opencodeSessionId);
|
|
5
|
+
}
|
|
6
|
+
async function resolveApiKeyRoleIds(em, key, tenantId = key.tenantId ?? null) {
|
|
7
|
+
const issuedRoleIds = Array.isArray(key.rolesJson) ? key.rolesJson.filter((roleId) => typeof roleId === "string" && roleId.length > 0) : [];
|
|
8
|
+
if (!isSessionBoundApiKey(key)) return issuedRoleIds;
|
|
9
|
+
const ownerId = key.sessionUserId?.trim();
|
|
10
|
+
if (!ownerId || !tenantId || tenantId !== key.tenantId || !issuedRoleIds.length) return [];
|
|
11
|
+
const links = await findWithDecryption(
|
|
12
|
+
em,
|
|
13
|
+
UserRole,
|
|
14
|
+
{
|
|
15
|
+
user: { id: ownerId, tenantId, deletedAt: null },
|
|
16
|
+
role: { id: { $in: issuedRoleIds }, tenantId, deletedAt: null },
|
|
17
|
+
deletedAt: null
|
|
18
|
+
},
|
|
19
|
+
{ populate: ["role"] },
|
|
20
|
+
{ tenantId, organizationId: null }
|
|
21
|
+
);
|
|
22
|
+
const currentRoleIds = new Set(links.map((link) => typeof link.role === "string" ? link.role : link.role.id));
|
|
23
|
+
return issuedRoleIds.filter((roleId) => currentRoleIds.has(roleId));
|
|
24
|
+
}
|
|
25
|
+
export {
|
|
26
|
+
isSessionBoundApiKey,
|
|
27
|
+
resolveApiKeyRoleIds
|
|
28
|
+
};
|
|
29
|
+
//# sourceMappingURL=sessionKeyRoles.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/api_keys/services/sessionKeyRoles.ts"],
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { ApiKey } from '../data/entities'\nimport { UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nexport function isSessionBoundApiKey(key: ApiKey): boolean {\n return Boolean(key.sessionTokenHash || key.sessionUserId || key.sessionSecretEncrypted || key.opencodeSessionId)\n}\n\nexport async function resolveApiKeyRoleIds(\n em: EntityManager,\n key: ApiKey,\n tenantId: string | null = key.tenantId ?? null,\n): Promise<string[]> {\n const issuedRoleIds = Array.isArray(key.rolesJson)\n ? key.rolesJson.filter((roleId): roleId is string => typeof roleId === 'string' && roleId.length > 0)\n : []\n if (!isSessionBoundApiKey(key)) return issuedRoleIds\n const ownerId = key.sessionUserId?.trim()\n if (!ownerId || !tenantId || tenantId !== key.tenantId || !issuedRoleIds.length) return []\n\n const links = await findWithDecryption(\n em,\n UserRole,\n {\n user: { id: ownerId, tenantId, deletedAt: null },\n role: { id: { $in: issuedRoleIds }, tenantId, deletedAt: null },\n deletedAt: null,\n },\n { populate: ['role'] },\n { tenantId, organizationId: null },\n )\n const currentRoleIds = new Set(links.map((link) => typeof link.role === 'string' ? link.role : link.role.id))\n return issuedRoleIds.filter((roleId) => currentRoleIds.has(roleId))\n}\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AAE5B,SAAS,qBAAqB,KAAsB;AACzD,SAAO,QAAQ,IAAI,oBAAoB,IAAI,iBAAiB,IAAI,0BAA0B,IAAI,iBAAiB;AACjH;AAEA,eAAsB,qBACpB,IACA,KACA,WAA0B,IAAI,YAAY,MACvB;AACnB,QAAM,gBAAgB,MAAM,QAAQ,IAAI,SAAS,IAC7C,IAAI,UAAU,OAAO,CAAC,WAA6B,OAAO,WAAW,YAAY,OAAO,SAAS,CAAC,IAClG,CAAC;AACL,MAAI,CAAC,qBAAqB,GAAG,EAAG,QAAO;AACvC,QAAM,UAAU,IAAI,eAAe,KAAK;AACxC,MAAI,CAAC,WAAW,CAAC,YAAY,aAAa,IAAI,YAAY,CAAC,cAAc,OAAQ,QAAO,CAAC;AAEzF,QAAM,QAAQ,MAAM;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,MACE,MAAM,EAAE,IAAI,SAAS,UAAU,WAAW,KAAK;AAAA,MAC/C,MAAM,EAAE,IAAI,EAAE,KAAK,cAAc,GAAG,UAAU,WAAW,KAAK;AAAA,MAC9D,WAAW;AAAA,IACb;AAAA,IACA,EAAE,UAAU,CAAC,MAAM,EAAE;AAAA,IACrB,EAAE,UAAU,gBAAgB,KAAK;AAAA,EACnC;AACA,QAAM,iBAAiB,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,KAAK,KAAK,EAAE,CAAC;AAC5G,SAAO,cAAc,OAAO,CAAC,WAAW,eAAe,IAAI,MAAM,CAAC;AACpE;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getCurrentCacheTenant, runWithCacheTenant } from "@open-mercato/cache";
|
|
2
2
|
import { UserAcl, RoleAcl, User, UserRole } from "@open-mercato/core/modules/auth/data/entities";
|
|
3
3
|
import { ApiKey } from "@open-mercato/core/modules/api_keys/data/entities";
|
|
4
|
+
import { isSessionBoundApiKey, resolveApiKeyRoleIds } from "@open-mercato/core/modules/api_keys/services/sessionKeyRoles";
|
|
4
5
|
import { Organization } from "@open-mercato/core/modules/directory/data/entities";
|
|
5
6
|
import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
6
7
|
import { buildOrgScopeUserCacheTag, buildOrgScopeTenantCacheTag } from "@open-mercato/core/modules/directory/utils/organizationScope";
|
|
@@ -313,7 +314,7 @@ class RbacService {
|
|
|
313
314
|
*/
|
|
314
315
|
async loadAcl(userId, scope) {
|
|
315
316
|
const cacheKey = this.getCacheKey(userId, scope);
|
|
316
|
-
const cached = await this.getFromCache(cacheKey);
|
|
317
|
+
const cached = userId.startsWith("api_key:") ? null : await this.getFromCache(cacheKey);
|
|
317
318
|
if (cached) return cached;
|
|
318
319
|
if (!userId.startsWith("api_key:")) {
|
|
319
320
|
if (await this.isGlobalSuperAdmin(userId)) {
|
|
@@ -331,8 +332,13 @@ class RbacService {
|
|
|
331
332
|
await this.setCache(cacheKey, result3, userId, scope);
|
|
332
333
|
return result3;
|
|
333
334
|
}
|
|
335
|
+
const cacheable = !isSessionBoundApiKey(key);
|
|
336
|
+
if (cacheable) {
|
|
337
|
+
const cachedKeyAcl = await this.getFromCache(cacheKey);
|
|
338
|
+
if (cachedKeyAcl) return cachedKeyAcl;
|
|
339
|
+
}
|
|
334
340
|
const tenantId2 = scope.tenantId || key.tenantId || null;
|
|
335
|
-
const roleIds2 =
|
|
341
|
+
const roleIds2 = await resolveApiKeyRoleIds(em2, key, tenantId2);
|
|
336
342
|
const keyOrganizationId = typeof key.organizationId === "string" && key.organizationId.trim().length > 0 ? key.organizationId.trim() : null;
|
|
337
343
|
const evaluatedOrganizationId = scope.organizationId || keyOrganizationId;
|
|
338
344
|
let isSuper2 = false;
|
|
@@ -382,7 +388,7 @@ class RbacService {
|
|
|
382
388
|
}
|
|
383
389
|
if (isSuper2 && organizations2 !== null && !features2.includes("*")) features2.push("*");
|
|
384
390
|
const result2 = { isSuperAdmin: isSuper2 && organizations2 === null, features: features2, organizations: organizations2 };
|
|
385
|
-
await this.setCache(cacheKey, result2, userId, scope);
|
|
391
|
+
if (cacheable) await this.setCache(cacheKey, result2, userId, scope);
|
|
386
392
|
return result2;
|
|
387
393
|
}
|
|
388
394
|
const em = this.em.fork();
|
|
@@ -470,7 +476,7 @@ class RbacService {
|
|
|
470
476
|
return { isSuperAdmin: false, features: [], organizations: null };
|
|
471
477
|
}
|
|
472
478
|
const tenantId2 = scope.tenantId || key.tenantId || null;
|
|
473
|
-
const roleIds2 =
|
|
479
|
+
const roleIds2 = await resolveApiKeyRoleIds(em, key, tenantId2);
|
|
474
480
|
const keyOrganizationId = typeof key.organizationId === "string" && key.organizationId.trim().length > 0 ? key.organizationId.trim() : null;
|
|
475
481
|
const evaluatedOrganizationId = scope.organizationId || keyOrganizationId;
|
|
476
482
|
const roleScope2 = await resolveRoleOrganizationScopeWithEntityManager(
|
|
@@ -730,12 +736,14 @@ class RbacService {
|
|
|
730
736
|
}
|
|
731
737
|
async loadFeatureOrganizationGrants(userId, tenantId) {
|
|
732
738
|
const cacheKey = `rbac:feature-organizations:${userId}:${tenantId}`;
|
|
733
|
-
|
|
739
|
+
const key = userId.startsWith("api_key:") ? await this.em.fork().findOne(ApiKey, { id: userId.slice("api_key:".length), deletedAt: null }) : void 0;
|
|
740
|
+
const cacheable = key === void 0 || key !== null && !isSessionBoundApiKey(key);
|
|
741
|
+
if (this.cache && cacheable) {
|
|
734
742
|
const cached = await this.cache.get(cacheKey);
|
|
735
743
|
if (isFeatureOrganizationGrants(cached)) return cached;
|
|
736
744
|
}
|
|
737
|
-
const grants = await this.queryFeatureOrganizationGrants(userId, tenantId);
|
|
738
|
-
if (this.cache) {
|
|
745
|
+
const grants = await this.queryFeatureOrganizationGrants(userId, tenantId, key);
|
|
746
|
+
if (this.cache && cacheable) {
|
|
739
747
|
await this.cache.set(cacheKey, grants, {
|
|
740
748
|
ttl: this.cacheTtlMs,
|
|
741
749
|
tags: this.buildCacheTags(userId, { tenantId, organizationId: null })
|
|
@@ -743,15 +751,15 @@ class RbacService {
|
|
|
743
751
|
}
|
|
744
752
|
return grants;
|
|
745
753
|
}
|
|
746
|
-
async queryFeatureOrganizationGrants(userId, tenantId) {
|
|
754
|
+
async queryFeatureOrganizationGrants(userId, tenantId, knownApiKey) {
|
|
747
755
|
const em = this.em.fork();
|
|
748
756
|
if (userId.startsWith("api_key:")) {
|
|
749
757
|
const apiKeyId = userId.slice("api_key:".length);
|
|
750
|
-
const key = await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null });
|
|
758
|
+
const key = knownApiKey === void 0 ? await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null }) : knownApiKey;
|
|
751
759
|
if (!key || key.expiresAt && key.expiresAt.getTime() < Date.now() || key.tenantId && key.tenantId !== tenantId) {
|
|
752
760
|
return { kind: "none" };
|
|
753
761
|
}
|
|
754
|
-
const roleIds2 =
|
|
762
|
+
const roleIds2 = await resolveApiKeyRoleIds(em, key, tenantId);
|
|
755
763
|
if (!roleIds2.length) return { kind: "none" };
|
|
756
764
|
const roleAcls2 = await em.find(RoleAcl, {
|
|
757
765
|
tenantId,
|
|
@@ -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, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport { buildOrgScopeUserCacheTag, buildOrgScopeTenantCacheTag } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n authorizeFeatures,\n resolveEffectiveFeatures,\n} from '@open-mercato/shared/security/featurePolicy'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport { resolveRoleOrganizationScope, roleAclAllowsOrganization } from './roleOrganizationScope'\n\ninterface AclData {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\nasync function resolveRoleOrganizationScopeWithEntityManager(\n em: EntityManager,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<ReadonlySet<string> | null> {\n if (!organizationId) return null\n if (!tenantId) return new Set()\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null } as FilterQuery<Organization>,\n { fields: ['id', 'ancestorIds'] },\n { tenantId, organizationId },\n )\n if (!organization) return new Set()\n const ancestors = Array.isArray(organization.ancestorIds)\n ? organization.ancestorIds.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n return new Set([organizationId, ...ancestors])\n}\n\nfunction isAclData(value: unknown): value is AclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<AclData>\n if (typeof record.isSuperAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((feature) => typeof feature !== 'string')) return false\n if (record.organizations !== null && record.organizations !== undefined) {\n if (!Array.isArray(record.organizations)) return false\n if (record.organizations.some((org) => typeof org !== 'string')) return false\n }\n return true\n}\n\nfunction isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n return Array.isArray(acl.organizationsJson)\n && acl.organizationsJson.length > 0\n && !acl.organizationsJson.includes('__all__')\n}\n\ntype FeatureOrganizationCandidate = {\n id: string\n ancestorIds?: readonly string[] | null\n}\n\ntype FeatureOrganizationAccess = {\n unrestricted: boolean\n filterOrganizationIds: (organizations: readonly FeatureOrganizationCandidate[]) => string[]\n}\n\ntype FeatureOrganizationRoleGrant = {\n isSuperAdmin: boolean\n featuresJson: string[] | null\n organizationsJson: string[] | null\n}\n\ntype FeatureOrganizationGrants =\n | { kind: 'none' }\n | { kind: 'api_key'; organizationId: string | null; roleGrants: FeatureOrganizationRoleGrant[] }\n | { kind: 'user_acl'; isSuperAdmin: boolean; features: string[]; organizations: string[] | null }\n | { kind: 'roles'; roleGrants: FeatureOrganizationRoleGrant[] }\n\nfunction isStringListOrNull(value: unknown): value is string[] | null {\n return value === null || (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n}\n\nfunction isFeatureOrganizationRoleGrant(value: unknown): value is FeatureOrganizationRoleGrant {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<FeatureOrganizationRoleGrant>\n return typeof record.isSuperAdmin === 'boolean'\n && isStringListOrNull(record.featuresJson)\n && isStringListOrNull(record.organizationsJson)\n}\n\nfunction isFeatureOrganizationGrants(value: unknown): value is FeatureOrganizationGrants {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n switch (record.kind) {\n case 'none':\n return true\n case 'api_key':\n return (record.organizationId === null || typeof record.organizationId === 'string')\n && Array.isArray(record.roleGrants)\n && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n case 'user_acl':\n return typeof record.isSuperAdmin === 'boolean'\n && Array.isArray(record.features)\n && record.features.every((feature) => typeof feature === 'string')\n && isStringListOrNull(record.organizations)\n case 'roles':\n return Array.isArray(record.roleGrants) && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n default:\n return false\n }\n}\n\nfunction toFeatureOrganizationRoleGrant(\n acl: Pick<RoleAcl, 'isSuperAdmin' | 'featuresJson' | 'organizationsJson'>,\n): FeatureOrganizationRoleGrant {\n return {\n isSuperAdmin: acl.isSuperAdmin === true,\n featuresJson: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n organizationsJson: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }\n}\n\nfunction normalizeFeatureOrganizationCandidates(\n organizations: readonly FeatureOrganizationCandidate[],\n): FeatureOrganizationCandidate[] {\n const normalized = new Map<string, FeatureOrganizationCandidate>()\n for (const organization of organizations) {\n const id = typeof organization.id === 'string' ? organization.id.trim() : ''\n if (!id || normalized.has(id)) continue\n const ancestorIds = Array.isArray(organization.ancestorIds)\n ? Array.from(new Set(organization.ancestorIds\n .map((ancestorId) => typeof ancestorId === 'string' ? ancestorId.trim() : '')\n .filter(Boolean)))\n : []\n normalized.set(id, { id, ancestorIds })\n }\n return Array.from(normalized.values())\n}\n\nfunction buildFeatureOrganizationScope(\n organization: FeatureOrganizationCandidate,\n): ReadonlySet<string> {\n return new Set([organization.id, ...(organization.ancestorIds ?? [])])\n}\n\nfunction roleAclProvidesGlobalFeatureScope(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n return !organizations || organizations.length === 0 || organizations.includes('__all__')\n}\n\nfunction roleAclProvidesGlobalVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n return emptyOrganizationsAreUnrestricted && organizations.length === 0\n}\n\nfunction roleAclProvidesOrganizationVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n organizationScope: ReadonlySet<string>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n if (organizations.length === 0) return emptyOrganizationsAreUnrestricted\n return organizations.some((organizationId) => organizationScope.has(organizationId))\n}\n\nfunction roleAclsAuthorizeFeatures(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n organization: FeatureOrganizationCandidate,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizationScope = buildFeatureOrganizationScope(organization)\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesOrganizationVisibility(acl, organizationScope, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclAllowsOrganization(acl, organizationScope)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nfunction roleAclsAuthorizeFeaturesGlobally(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesGlobalVisibility(acl, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclProvidesGlobalFeatureScope(acl)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nexport class RbacService {\n private cacheTtlMs: number = 5 * 60 * 1000 // 5 minutes default\n private cache: CacheStrategy | null = null\n private globalSuperAdminCache = new Map<string, boolean>()\n\n constructor(\n private em: EntityManager,\n cache?: CacheStrategy,\n private readonly organizationHierarchyService?: OrganizationHierarchyService,\n ) {\n this.cache = cache || null\n }\n\n /**\n * Set cache TTL in milliseconds\n * @param ttlMs - Time to live in milliseconds\n */\n setCacheTtl(ttlMs: number) {\n this.cacheTtlMs = ttlMs\n }\n\n /** Compatibility wrapper for callers that already have both feature lists. */\n public hasAllFeatures(required: string[], granted: string[]): boolean {\n return authorizeFeatures(required, { grantedFeatures: granted })\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string {\n return `rbac:${userId}:${scope.tenantId || 'null'}:${scope.organizationId || 'null'}`\n }\n\n private getUserTag(userId: string): string {\n return `rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `rbac:tenant:${tenantId}`\n }\n\n private getOrganizationTag(organizationId: string): string {\n return `rbac:org:${organizationId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<AclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isAclData(cached) ? cached : null\n }\n\n private async setCache(cacheKey: string, data: AclData, userId: string, scope: { tenantId: string | null; organizationId: string | null }): Promise<void> {\n if (!this.cache) return\n\n await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, scope),\n })\n }\n\n private buildCacheTags(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string[] {\n const tags = [\n this.getUserTag(userId),\n 'rbac:all'\n ]\n\n if (scope.tenantId) {\n tags.push(this.getTenantTag(scope.tenantId))\n // Scoped role projections depend on the selected organization's ancestor\n // chain, so Directory hierarchy changes must evict them as well as the\n // separately cached OrganizationScope entries.\n tags.push(buildOrgScopeTenantCacheTag(scope.tenantId))\n }\n\n if (scope.organizationId) {\n tags.push(this.getOrganizationTag(scope.organizationId))\n }\n\n return tags\n }\n\n /**\n * Invalidates cached ACL data for a specific user across all tenants and organizations.\n * Call this when a user's roles or user-specific ACL is modified.\n * \n * @param userId - The ID of the user whose cache should be invalidated\n */\n async invalidateUserCache(userId: string): Promise<void> {\n this.globalSuperAdminCache.delete(userId)\n // Also drop the directory OrganizationScope cache for this user. That scope's\n // accessible-org set is derived from this user's ACL/role grants, so any\n // permission change that invalidates the RBAC cache must invalidate the\n // resolved scope too. This is the missing `org-scope:user:*` caller required\n // before the cross-request scope TTL can be safely enabled (issue #2259).\n await this.deleteCacheByTags([this.getUserTag(userId), buildOrgScopeUserCacheTag(userId)])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific tenant.\n * Call this when a role's ACL is modified, since roles are tenant-scoped\n * and affect all users in that tenant who have that role.\n * \n * @param tenantId - The ID of the tenant whose cache should be invalidated\n */\n async invalidateTenantCache(tenantId: string): Promise<void> {\n this.globalSuperAdminCache.clear()\n // Role ACL changes invalidate every user in the tenant; the resolved\n // OrganizationScope for those users derives from the same grants, so drop\n // the tenant-tagged scope entries alongside the RBAC ones (issue #2259).\n await this.deleteCacheByTags([this.getTenantTag(tenantId), buildOrgScopeTenantCacheTag(tenantId)], [tenantId])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific organization.\n * Call this when organization-level permissions or visibility changes.\n * \n * @param organizationId - The ID of the organization whose cache should be invalidated\n */\n async invalidateOrganizationCache(organizationId: string): Promise<void> {\n await this.deleteCacheByTags([this.getOrganizationTag(organizationId)])\n }\n\n /**\n * Clears all cached ACL data.\n * Use this for bulk operations or system-wide ACL changes.\n */\n async invalidateAllCache(): Promise<void> {\n this.globalSuperAdminCache.clear()\n await this.deleteCacheByTags(['rbac:all'])\n }\n\n private async deleteCacheByTags(tags: string[], tenantHints?: Array<string | null>): Promise<void> {\n if (!this.cache) return\n const contexts = new Set<string | null>()\n const current = getCurrentCacheTenant()\n contexts.add(current ?? null)\n contexts.add(null)\n if (Array.isArray(tenantHints)) {\n for (const hint of tenantHints) {\n contexts.add(hint ?? null)\n }\n }\n for (const ctx of contexts) {\n if (ctx === current) {\n await this.cache.deleteByTags(tags)\n } else {\n await runWithCacheTenant(ctx, async () => {\n await this.cache!.deleteByTags(tags)\n })\n }\n }\n }\n\n private async isGlobalSuperAdmin(userId: string): Promise<boolean> {\n if (this.globalSuperAdminCache.has(userId)) return this.globalSuperAdminCache.get(userId)!\n const em = this.em.fork()\n const userSuper = await em.findOne(UserAcl, { user: userId as any, isSuperAdmin: true })\n if (userSuper && (userSuper as any).isSuperAdmin) {\n this.globalSuperAdminCache.set(userId, true)\n return true\n }\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as any },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const linkList = Array.isArray(links) ? links : []\n if (!linkList.length) {\n this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleIds = Array.from(new Set(linkList.map((link) => {\n const role = link.role as any\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 this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleSupers = await em.find(RoleAcl, { isSuperAdmin: true, role: { $in: roleIds as any } } as any)\n const result = roleSupers.some((roleAcl) => (\n !!roleAcl.isSuperAdmin && !isRestrictedRoleAcl(roleAcl)\n ))\n 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 = await this.getFromCache(cacheKey)\n if (cached) return cached\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 if (!userId.startsWith('api_key:')) {\n if (await this.isGlobalSuperAdmin(userId)) {\n const result = { isSuperAdmin: true, features: ['*'], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n }\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 tenantId = scope.tenantId || key.tenantId || null\n const roleIds = Array.isArray(key.rolesJson) ? key.rolesJson.filter(Boolean) : []\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, { tenantId, role: { $in: roleIds as any } } as any)\n for (const acl of racls) {\n if (roleAclAllowsOrganization(acl, roleOrganizationScope)) {\n isSuper = isSuper || !!acl.isSuperAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) if (!features.includes(f)) features.push(f)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (roleOrganizations !== null) {\n if (acl.organizationsJson == null || (Array.isArray(acl.organizationsJson) && acl.organizationsJson.length === 0)) {\n roleOrganizations = null\n } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes('__all__')) {\n roleOrganizations = null\n } else {\n roleOrganizations = Array.from(new Set([\n ...roleOrganizations,\n ...(Array.isArray(acl.organizationsJson) ? acl.organizationsJson : []),\n ]))\n }\n }\n }\n if (\n roleOrganizations !== null\n && evaluatedOrganizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !roleOrganizations.includes(evaluatedOrganizationId)\n ) {\n roleOrganizations.push(evaluatedOrganizationId)\n }\n }\n let organizations = roleOrganizations\n if (keyOrganizationId) {\n const keyOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n keyOrganizationId,\n )\n organizations = roleOrganizations === null\n || roleOrganizations.some((organizationId) => keyOrganizationScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n // A role-level super-admin grant still respects the API key's effective\n // organization allowlist. Represent it as a wildcard feature whenever\n // the key is restricted so downstream super-admin shortcuts cannot\n // bypass the key or role organization bounds.\n if (isSuper && organizations !== null && !features.includes('*')) features.push('*')\n const result = { isSuperAdmin: isSuper && organizations === null, features, organizations }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Use a forked EntityManager to avoid inheriting an aborted transaction from callers\n const em = this.em.fork()\n const user = await em.findOne(User, { id: userId })\n if (!user) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n 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\n const uacl = await em.findOne(UserAcl, { user: userId as any, tenantId })\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 { user: userId as any, role: { tenantId } } as any,\n { populate: ['role'] },\n { tenantId, organizationId: orgId },\n )\n const linkList = Array.isArray(links) ? links : []\n const roleIds = linkList.map((l) => (l.role as any)?.id).filter(Boolean)\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, { tenantId, role: { $in: roleIds as any } } as any, {})\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 = Array.isArray(key.rolesJson) ? key.rolesJson.filter(Boolean) : []\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, role: { $in: roleIds as never } } as never)\n : []\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (\n acl.organizationsJson == null\n || acl.organizationsJson.length === 0\n || acl.organizationsJson.includes('__all__')\n ) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && evaluatedOrganizationId\n && roleScope !== null\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(evaluatedOrganizationId)\n ) {\n organizations.push(evaluatedOrganizationId)\n }\n if (keyOrganizationId) {\n const keyScope = await resolveRoleOrganizationScopeWithEntityManager(em, tenantId, keyOrganizationId)\n organizations = organizations === null\n || organizations.some((organizationId) => keyScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n if (isSuperAdmin && organizations !== null && !features.includes('*')) features.push('*')\n return { isSuperAdmin: isSuperAdmin && organizations === null, features, organizations }\n }\n\n const directGlobalGrant = await em.findOne(\n UserAcl,\n { user: userId as never, isSuperAdmin: true } as never,\n )\n if (directGlobalGrant?.isSuperAdmin) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n const globalLinks = await findWithDecryption(\n em,\n UserRole,\n { user: userId as never },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const globalRoleIds = globalLinks\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 if (globalRoleIds.length) {\n const globalRoleGrants = await em.find(\n RoleAcl,\n {\n role: { $in: globalRoleIds as never },\n isSuperAdmin: true,\n } as never,\n )\n if (globalRoleGrants.some((grant) => grant.isSuperAdmin && !isRestrictedRoleAcl(grant))) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n }\n\n const user = await em.findOne(User, { id: userId })\n if (!user) return { isSuperAdmin: false, features: [], organizations: null }\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(UserAcl, { user: userId as never, tenantId } as never)\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, role: { tenantId } } 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, role: { $in: roleIds as never } } 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 any, {})\n const list = Array.isArray(roleAcls) ? roleAcls : []\n\n for (const acl of list) {\n if (!roleAclAllowsOrganization(acl, roleOrganizationScope)) continue\n const grants = Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n if (authorizeFeatures([feature], {\n grantedFeatures: grants,\n unrestricted: acl.isSuperAdmin,\n })) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Checks if a user has all required features within a given scope.\n *\n * This is the primary authorization check method used throughout the application.\n * It combines feature checking with organization visibility validation.\n *\n * Authorization logic:\n * 1. No features required \u2192 always returns true\n * 2. User is super admin \u2192 always returns true\n * 3. Organization restriction check: If the user's ACL has a restricted organization list\n * and the requested organization is not in that list \u2192 returns false\n * 4. Feature matching: User must have all required features (supports wildcards)\n *\n * @param userId - The ID of the user\n * @param required - Array of feature strings to check (e.g., ['users.view', 'users.edit'])\n * @param scope - The tenant and organization context for authorization\n * @returns true if the user has all required features and organization access, false otherwise\n *\n * @example\n * // Check if user can view and edit users\n * const canManageUsers = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['users.view', 'users.edit'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n *\n * @example\n * // Check with wildcard features\n * const canAccessEntities = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['entities.records.view'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n * // Returns true if user has 'entities.*', '*', or 'entities.records.view'\n */\n async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n async resolveFeatureOrganizationAccess(\n userId: string,\n required: readonly string[],\n input: { tenantId: string | null },\n ): Promise<FeatureOrganizationAccess> {\n const allowAll = (organizations: readonly FeatureOrganizationCandidate[]) =>\n normalizeFeatureOrganizationCandidates(organizations).map((organization) => organization.id)\n const denyAll = () => []\n if (!required.length) return { unrestricted: true, filterOrganizationIds: allowAll }\n if (!input.tenantId) return { unrestricted: false, filterOrganizationIds: denyAll }\n if (\n !userId.startsWith('api_key:')\n && await this.isGlobalSuperAdmin(userId)\n && authorizeFeatures(required, { grantedFeatures: ['*'], unrestricted: true })\n ) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n const grants = await this.loadFeatureOrganizationGrants(userId, input.tenantId)\n if (grants.kind === 'none') return { unrestricted: false, filterOrganizationIds: denyAll }\n\n if (grants.kind === 'api_key') {\n const keyOrganizationId = grants.organizationId\n const unrestricted = keyOrganizationId === null\n && roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, true)\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => (\n (!keyOrganizationId || organization.id === keyOrganizationId)\n && roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, true)\n ))\n .map((organization) => organization.id),\n }\n }\n\n if (grants.kind === 'user_acl') {\n const grantedFeatures = grants.features\n const allowedOrganizations = grants.organizations\n const hasGlobalScope = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n const unrestricted = authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed: hasGlobalScope,\n })\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => {\n const scopeAllowed = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n || allowedOrganizations.includes(organization.id)\n return authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed,\n })\n })\n .map((organization) => organization.id),\n }\n }\n\n if (roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, false)) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, false))\n .map((organization) => organization.id),\n }\n }\n\n private async loadFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n ): Promise<FeatureOrganizationGrants> {\n const cacheKey = `rbac:feature-organizations:${userId}:${tenantId}`\n if (this.cache) {\n const cached = await this.cache.get(cacheKey)\n if (isFeatureOrganizationGrants(cached)) return cached\n }\n const grants = await this.queryFeatureOrganizationGrants(userId, tenantId)\n if (this.cache) {\n await this.cache.set(cacheKey, grants, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, { tenantId, organizationId: null }),\n })\n }\n return grants\n }\n\n private async queryFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n ): 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 = await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n if (\n !key\n || (key.expiresAt && key.expiresAt.getTime() < Date.now())\n || (key.tenantId && key.tenantId !== tenantId)\n ) {\n return { kind: 'none' }\n }\n\n const roleIds = Array.isArray(key.rolesJson) ? key.rolesJson.filter(Boolean) : []\n if (!roleIds.length) return { kind: 'none' }\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n role: { $in: roleIds },\n })\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n return {\n kind: 'api_key',\n organizationId: keyOrganizationId,\n roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant),\n }\n }\n\n const user = await em.findOne(User, { id: userId })\n if (!user) return { kind: 'none' }\n\n const userAcl = await em.findOne(UserAcl, { user: userId, tenantId })\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, role: { tenantId } },\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 role: { $in: roleIds },\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,SAAS,MAAM,gBAAgB;AACjD,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,2BAA2B,mCAAmC;A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AI,IAAI,aAAc,QAAO,6BAA6B,CAAC,GAAG,CAAC;AAC/D,QACE,IAAI,iBACJ,MAAM,kBACN,CAAC,IAAI,cAAc,SAAS,MAAM,cAAc,KAChD,CAAC,IAAI,cAAc,SAAS,SAAS,GACrC;AACA,aAAO,CAAC;AAAA,IACV;AACA,WAAO,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, User, UserRole } from '@open-mercato/core/modules/auth/data/entities'\nimport { ApiKey } from '@open-mercato/core/modules/api_keys/data/entities'\nimport { isSessionBoundApiKey, resolveApiKeyRoleIds } from '@open-mercato/core/modules/api_keys/services/sessionKeyRoles'\nimport { Organization } from '@open-mercato/core/modules/directory/data/entities'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport { buildOrgScopeUserCacheTag, buildOrgScopeTenantCacheTag } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport {\n authorizeFeatures,\n resolveEffectiveFeatures,\n} from '@open-mercato/shared/security/featurePolicy'\nimport { filterGrantsByEnabledModules } from '@open-mercato/shared/security/enabledModulesRegistry'\nimport { resolveRoleOrganizationScope, roleAclAllowsOrganization } from './roleOrganizationScope'\n\ninterface AclData {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\n}\n\nasync function resolveRoleOrganizationScopeWithEntityManager(\n em: EntityManager,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<ReadonlySet<string> | null> {\n if (!organizationId) return null\n if (!tenantId) return new Set()\n const organization = await findOneWithDecryption(\n em,\n Organization,\n { id: organizationId, tenant: tenantId, deletedAt: null } as FilterQuery<Organization>,\n { fields: ['id', 'ancestorIds'] },\n { tenantId, organizationId },\n )\n if (!organization) return new Set()\n const ancestors = Array.isArray(organization.ancestorIds)\n ? organization.ancestorIds.filter((value): value is string => typeof value === 'string' && value.length > 0)\n : []\n return new Set([organizationId, ...ancestors])\n}\n\nfunction isAclData(value: unknown): value is AclData {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<AclData>\n if (typeof record.isSuperAdmin !== 'boolean') return false\n if (!Array.isArray(record.features) || record.features.some((feature) => typeof feature !== 'string')) return false\n if (record.organizations !== null && record.organizations !== undefined) {\n if (!Array.isArray(record.organizations)) return false\n if (record.organizations.some((org) => typeof org !== 'string')) return false\n }\n return true\n}\n\nfunction isRestrictedRoleAcl(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n return Array.isArray(acl.organizationsJson)\n && acl.organizationsJson.length > 0\n && !acl.organizationsJson.includes('__all__')\n}\n\ntype FeatureOrganizationCandidate = {\n id: string\n ancestorIds?: readonly string[] | null\n}\n\ntype FeatureOrganizationAccess = {\n unrestricted: boolean\n filterOrganizationIds: (organizations: readonly FeatureOrganizationCandidate[]) => string[]\n}\n\ntype FeatureOrganizationRoleGrant = {\n isSuperAdmin: boolean\n featuresJson: string[] | null\n organizationsJson: string[] | null\n}\n\ntype FeatureOrganizationGrants =\n | { kind: 'none' }\n | { kind: 'api_key'; organizationId: string | null; roleGrants: FeatureOrganizationRoleGrant[] }\n | { kind: 'user_acl'; isSuperAdmin: boolean; features: string[]; organizations: string[] | null }\n | { kind: 'roles'; roleGrants: FeatureOrganizationRoleGrant[] }\n\nfunction isStringListOrNull(value: unknown): value is string[] | null {\n return value === null || (Array.isArray(value) && value.every((entry) => typeof entry === 'string'))\n}\n\nfunction isFeatureOrganizationRoleGrant(value: unknown): value is FeatureOrganizationRoleGrant {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Partial<FeatureOrganizationRoleGrant>\n return typeof record.isSuperAdmin === 'boolean'\n && isStringListOrNull(record.featuresJson)\n && isStringListOrNull(record.organizationsJson)\n}\n\nfunction isFeatureOrganizationGrants(value: unknown): value is FeatureOrganizationGrants {\n if (typeof value !== 'object' || value === null) return false\n const record = value as Record<string, unknown>\n switch (record.kind) {\n case 'none':\n return true\n case 'api_key':\n return (record.organizationId === null || typeof record.organizationId === 'string')\n && Array.isArray(record.roleGrants)\n && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n case 'user_acl':\n return typeof record.isSuperAdmin === 'boolean'\n && Array.isArray(record.features)\n && record.features.every((feature) => typeof feature === 'string')\n && isStringListOrNull(record.organizations)\n case 'roles':\n return Array.isArray(record.roleGrants) && record.roleGrants.every(isFeatureOrganizationRoleGrant)\n default:\n return false\n }\n}\n\nfunction toFeatureOrganizationRoleGrant(\n acl: Pick<RoleAcl, 'isSuperAdmin' | 'featuresJson' | 'organizationsJson'>,\n): FeatureOrganizationRoleGrant {\n return {\n isSuperAdmin: acl.isSuperAdmin === true,\n featuresJson: Array.isArray(acl.featuresJson) ? [...acl.featuresJson] : null,\n organizationsJson: Array.isArray(acl.organizationsJson) ? [...acl.organizationsJson] : null,\n }\n}\n\nfunction normalizeFeatureOrganizationCandidates(\n organizations: readonly FeatureOrganizationCandidate[],\n): FeatureOrganizationCandidate[] {\n const normalized = new Map<string, FeatureOrganizationCandidate>()\n for (const organization of organizations) {\n const id = typeof organization.id === 'string' ? organization.id.trim() : ''\n if (!id || normalized.has(id)) continue\n const ancestorIds = Array.isArray(organization.ancestorIds)\n ? Array.from(new Set(organization.ancestorIds\n .map((ancestorId) => typeof ancestorId === 'string' ? ancestorId.trim() : '')\n .filter(Boolean)))\n : []\n normalized.set(id, { id, ancestorIds })\n }\n return Array.from(normalized.values())\n}\n\nfunction buildFeatureOrganizationScope(\n organization: FeatureOrganizationCandidate,\n): ReadonlySet<string> {\n return new Set([organization.id, ...(organization.ancestorIds ?? [])])\n}\n\nfunction roleAclProvidesGlobalFeatureScope(acl: Pick<RoleAcl, 'organizationsJson'>): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n return !organizations || organizations.length === 0 || organizations.includes('__all__')\n}\n\nfunction roleAclProvidesGlobalVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n return emptyOrganizationsAreUnrestricted && organizations.length === 0\n}\n\nfunction roleAclProvidesOrganizationVisibility(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n organizationScope: ReadonlySet<string>,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.includes('__all__')) return true\n if (organizations.length === 0) return emptyOrganizationsAreUnrestricted\n return organizations.some((organizationId) => organizationScope.has(organizationId))\n}\n\nfunction roleAclsAuthorizeFeatures(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n organization: FeatureOrganizationCandidate,\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const organizationScope = buildFeatureOrganizationScope(organization)\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesOrganizationVisibility(acl, organizationScope, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclAllowsOrganization(acl, organizationScope)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nfunction roleAclsAuthorizeFeaturesGlobally(\n roleAcls: readonly FeatureOrganizationRoleGrant[],\n required: readonly string[],\n emptyOrganizationsAreUnrestricted: boolean,\n): boolean {\n const grantedFeatures = new Set<string>()\n let unrestricted = false\n let scopeAllowed = false\n\n for (const acl of roleAcls) {\n if (roleAclProvidesGlobalVisibility(acl, emptyOrganizationsAreUnrestricted)) {\n scopeAllowed = true\n }\n if (!roleAclProvidesGlobalFeatureScope(acl)) continue\n unrestricted = unrestricted || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n grantedFeatures.add(feature)\n }\n }\n\n return authorizeFeatures([...required], {\n grantedFeatures: Array.from(grantedFeatures),\n unrestricted,\n scopeAllowed: scopeAllowed || unrestricted,\n })\n}\n\nexport class RbacService {\n private cacheTtlMs: number = 5 * 60 * 1000 // 5 minutes default\n private cache: CacheStrategy | null = null\n private globalSuperAdminCache = new Map<string, boolean>()\n\n constructor(\n private em: EntityManager,\n cache?: CacheStrategy,\n private readonly organizationHierarchyService?: OrganizationHierarchyService,\n ) {\n this.cache = cache || null\n }\n\n /**\n * Set cache TTL in milliseconds\n * @param ttlMs - Time to live in milliseconds\n */\n setCacheTtl(ttlMs: number) {\n this.cacheTtlMs = ttlMs\n }\n\n /** Compatibility wrapper for callers that already have both feature lists. */\n public hasAllFeatures(required: string[], granted: string[]): boolean {\n return authorizeFeatures(required, { grantedFeatures: granted })\n }\n\n private getCacheKey(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string {\n return `rbac:${userId}:${scope.tenantId || 'null'}:${scope.organizationId || 'null'}`\n }\n\n private getUserTag(userId: string): string {\n return `rbac:user:${userId}`\n }\n\n private getTenantTag(tenantId: string): string {\n return `rbac:tenant:${tenantId}`\n }\n\n private getOrganizationTag(organizationId: string): string {\n return `rbac:org:${organizationId}`\n }\n\n private async getFromCache(cacheKey: string): Promise<AclData | null> {\n if (!this.cache) return null\n const cached = await this.cache.get(cacheKey)\n if (!cached) return null\n return isAclData(cached) ? cached : null\n }\n\n private async setCache(cacheKey: string, data: AclData, userId: string, scope: { tenantId: string | null; organizationId: string | null }): Promise<void> {\n if (!this.cache) return\n\n await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, scope),\n })\n }\n\n private buildCacheTags(userId: string, scope: { tenantId: string | null; organizationId: string | null }): string[] {\n const tags = [\n this.getUserTag(userId),\n 'rbac:all'\n ]\n\n if (scope.tenantId) {\n tags.push(this.getTenantTag(scope.tenantId))\n // Scoped role projections depend on the selected organization's ancestor\n // chain, so Directory hierarchy changes must evict them as well as the\n // separately cached OrganizationScope entries.\n tags.push(buildOrgScopeTenantCacheTag(scope.tenantId))\n }\n\n if (scope.organizationId) {\n tags.push(this.getOrganizationTag(scope.organizationId))\n }\n\n return tags\n }\n\n /**\n * Invalidates cached ACL data for a specific user across all tenants and organizations.\n * Call this when a user's roles or user-specific ACL is modified.\n * \n * @param userId - The ID of the user whose cache should be invalidated\n */\n async invalidateUserCache(userId: string): Promise<void> {\n this.globalSuperAdminCache.delete(userId)\n // Also drop the directory OrganizationScope cache for this user. That scope's\n // accessible-org set is derived from this user's ACL/role grants, so any\n // permission change that invalidates the RBAC cache must invalidate the\n // resolved scope too. This is the missing `org-scope:user:*` caller required\n // before the cross-request scope TTL can be safely enabled (issue #2259).\n await this.deleteCacheByTags([this.getUserTag(userId), buildOrgScopeUserCacheTag(userId)])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific tenant.\n * Call this when a role's ACL is modified, since roles are tenant-scoped\n * and affect all users in that tenant who have that role.\n * \n * @param tenantId - The ID of the tenant whose cache should be invalidated\n */\n async invalidateTenantCache(tenantId: string): Promise<void> {\n this.globalSuperAdminCache.clear()\n // Role ACL changes invalidate every user in the tenant; the resolved\n // OrganizationScope for those users derives from the same grants, so drop\n // the tenant-tagged scope entries alongside the RBAC ones (issue #2259).\n await this.deleteCacheByTags([this.getTenantTag(tenantId), buildOrgScopeTenantCacheTag(tenantId)], [tenantId])\n }\n\n /**\n * Invalidates cached ACL data for all users within a specific organization.\n * Call this when organization-level permissions or visibility changes.\n * \n * @param organizationId - The ID of the organization whose cache should be invalidated\n */\n async invalidateOrganizationCache(organizationId: string): Promise<void> {\n await this.deleteCacheByTags([this.getOrganizationTag(organizationId)])\n }\n\n /**\n * Clears all cached ACL data.\n * Use this for bulk operations or system-wide ACL changes.\n */\n async invalidateAllCache(): Promise<void> {\n this.globalSuperAdminCache.clear()\n await this.deleteCacheByTags(['rbac:all'])\n }\n\n private async deleteCacheByTags(tags: string[], tenantHints?: Array<string | null>): Promise<void> {\n if (!this.cache) return\n const contexts = new Set<string | null>()\n const current = getCurrentCacheTenant()\n contexts.add(current ?? null)\n contexts.add(null)\n if (Array.isArray(tenantHints)) {\n for (const hint of tenantHints) {\n contexts.add(hint ?? null)\n }\n }\n for (const ctx of contexts) {\n if (ctx === current) {\n await this.cache.deleteByTags(tags)\n } else {\n await runWithCacheTenant(ctx, async () => {\n await this.cache!.deleteByTags(tags)\n })\n }\n }\n }\n\n private async isGlobalSuperAdmin(userId: string): Promise<boolean> {\n if (this.globalSuperAdminCache.has(userId)) return this.globalSuperAdminCache.get(userId)!\n const em = this.em.fork()\n const userSuper = await em.findOne(UserAcl, { user: userId as any, isSuperAdmin: true })\n if (userSuper && (userSuper as any).isSuperAdmin) {\n this.globalSuperAdminCache.set(userId, true)\n return true\n }\n const links = await findWithDecryption(\n em,\n UserRole,\n { user: userId as any },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const linkList = Array.isArray(links) ? links : []\n if (!linkList.length) {\n this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleIds = Array.from(new Set(linkList.map((link) => {\n const role = link.role as any\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 this.globalSuperAdminCache.set(userId, false)\n return false\n }\n const roleSupers = await em.find(RoleAcl, { isSuperAdmin: true, role: { $in: roleIds as any } } as any)\n const result = roleSupers.some((roleAcl) => (\n !!roleAcl.isSuperAdmin && !isRestrictedRoleAcl(roleAcl)\n ))\n 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 // 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 if (!userId.startsWith('api_key:')) {\n if (await this.isGlobalSuperAdmin(userId)) {\n const result = { isSuperAdmin: true, features: ['*'], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n }\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, { tenantId, role: { $in: roleIds as any } } as any)\n for (const acl of racls) {\n if (roleAclAllowsOrganization(acl, roleOrganizationScope)) {\n isSuper = isSuper || !!acl.isSuperAdmin\n if (Array.isArray(acl.featuresJson)) {\n for (const f of acl.featuresJson) if (!features.includes(f)) features.push(f)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (roleOrganizations !== null) {\n if (acl.organizationsJson == null || (Array.isArray(acl.organizationsJson) && acl.organizationsJson.length === 0)) {\n roleOrganizations = null\n } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes('__all__')) {\n roleOrganizations = null\n } else {\n roleOrganizations = Array.from(new Set([\n ...roleOrganizations,\n ...(Array.isArray(acl.organizationsJson) ? acl.organizationsJson : []),\n ]))\n }\n }\n }\n if (\n roleOrganizations !== null\n && evaluatedOrganizationId\n && roleOrganizationScope !== null\n && roleOrganizationScope.size > 0\n && hasApplicableRestrictedRole\n && !roleOrganizations.includes(evaluatedOrganizationId)\n ) {\n roleOrganizations.push(evaluatedOrganizationId)\n }\n }\n let organizations = roleOrganizations\n if (keyOrganizationId) {\n const keyOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n tenantId,\n keyOrganizationId,\n )\n organizations = roleOrganizations === null\n || roleOrganizations.some((organizationId) => keyOrganizationScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n // A role-level super-admin grant still respects the API key's effective\n // organization allowlist. Represent it as a wildcard feature whenever\n // the key is restricted so downstream super-admin shortcuts cannot\n // bypass the key or role organization bounds.\n if (isSuper && organizations !== null && !features.includes('*')) features.push('*')\n const result = { isSuperAdmin: isSuper && organizations === null, features, organizations }\n if (cacheable) await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n\n // Use a forked EntityManager to avoid inheriting an aborted transaction from callers\n const em = this.em.fork()\n const user = await em.findOne(User, { id: userId })\n if (!user) {\n const result = { isSuperAdmin: false, features: [], organizations: null }\n await this.setCache(cacheKey, result, userId, scope)\n return result\n }\n 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\n const uacl = await em.findOne(UserAcl, { user: userId as any, tenantId })\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 { user: userId as any, role: { tenantId } } as any,\n { populate: ['role'] },\n { tenantId, organizationId: orgId },\n )\n const linkList = Array.isArray(links) ? links : []\n const roleIds = linkList.map((l) => (l.role as any)?.id).filter(Boolean)\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, { tenantId, role: { $in: roleIds as any } } as any, {})\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, role: { $in: roleIds as never } } as never)\n : []\n let isSuperAdmin = false\n const features: string[] = []\n let organizations: string[] | null = []\n let hasApplicableRestrictedRole = false\n for (const acl of roleAcls) {\n if (roleAclAllowsOrganization(acl, roleScope)) {\n isSuperAdmin = isSuperAdmin || acl.isSuperAdmin === true\n for (const feature of Array.isArray(acl.featuresJson) ? acl.featuresJson : []) {\n if (!features.includes(feature)) features.push(feature)\n }\n if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole = true\n }\n if (organizations !== null) {\n if (\n acl.organizationsJson == null\n || acl.organizationsJson.length === 0\n || acl.organizationsJson.includes('__all__')\n ) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...organizations, ...acl.organizationsJson]))\n }\n }\n }\n if (\n organizations !== null\n && evaluatedOrganizationId\n && roleScope !== null\n && roleScope.size > 0\n && hasApplicableRestrictedRole\n && !organizations.includes(evaluatedOrganizationId)\n ) {\n organizations.push(evaluatedOrganizationId)\n }\n if (keyOrganizationId) {\n const keyScope = await resolveRoleOrganizationScopeWithEntityManager(em, tenantId, keyOrganizationId)\n organizations = organizations === null\n || organizations.some((organizationId) => keyScope?.has(organizationId))\n ? [keyOrganizationId]\n : []\n }\n if (isSuperAdmin && organizations !== null && !features.includes('*')) features.push('*')\n return { isSuperAdmin: isSuperAdmin && organizations === null, features, organizations }\n }\n\n const directGlobalGrant = await em.findOne(\n UserAcl,\n { user: userId as never, isSuperAdmin: true } as never,\n )\n if (directGlobalGrant?.isSuperAdmin) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n const globalLinks = await findWithDecryption(\n em,\n UserRole,\n { user: userId as never },\n { populate: ['role'] },\n { tenantId: null, organizationId: null },\n )\n const globalRoleIds = globalLinks\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 if (globalRoleIds.length) {\n const globalRoleGrants = await em.find(\n RoleAcl,\n {\n role: { $in: globalRoleIds as never },\n isSuperAdmin: true,\n } as never,\n )\n if (globalRoleGrants.some((grant) => grant.isSuperAdmin && !isRestrictedRoleAcl(grant))) {\n return { isSuperAdmin: true, features: ['*'], organizations: null }\n }\n }\n\n const user = await em.findOne(User, { id: userId })\n if (!user) return { isSuperAdmin: false, features: [], organizations: null }\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(UserAcl, { user: userId as never, tenantId } as never)\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, role: { tenantId } } 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, role: { $in: roleIds as never } } 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 any, {})\n const list = Array.isArray(roleAcls) ? roleAcls : []\n\n for (const acl of list) {\n if (!roleAclAllowsOrganization(acl, roleOrganizationScope)) continue\n const grants = Array.isArray(acl.featuresJson) ? acl.featuresJson : []\n if (authorizeFeatures([feature], {\n grantedFeatures: grants,\n unrestricted: acl.isSuperAdmin,\n })) {\n return true\n }\n }\n\n return false\n }\n\n /**\n * Checks if a user has all required features within a given scope.\n *\n * This is the primary authorization check method used throughout the application.\n * It combines feature checking with organization visibility validation.\n *\n * Authorization logic:\n * 1. No features required \u2192 always returns true\n * 2. User is super admin \u2192 always returns true\n * 3. Organization restriction check: If the user's ACL has a restricted organization list\n * and the requested organization is not in that list \u2192 returns false\n * 4. Feature matching: User must have all required features (supports wildcards)\n *\n * @param userId - The ID of the user\n * @param required - Array of feature strings to check (e.g., ['users.view', 'users.edit'])\n * @param scope - The tenant and organization context for authorization\n * @returns true if the user has all required features and organization access, false otherwise\n *\n * @example\n * // Check if user can view and edit users\n * const canManageUsers = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['users.view', 'users.edit'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n *\n * @example\n * // Check with wildcard features\n * const canAccessEntities = await rbacService.userHasAllFeatures(\n * 'user-123',\n * ['entities.records.view'],\n * { tenantId: 'tenant-1', organizationId: 'org-1' }\n * )\n * // Returns true if user has 'entities.*', '*', or 'entities.records.view'\n */\n async userHasAllFeatures(userId: string, required: string[], scope: { tenantId: string | null; organizationId: string | null }): Promise<boolean> {\n if (!required.length) return true\n const acl = await this.loadAcl(userId, scope)\n const organizationAllowed = acl.isSuperAdmin\n || !acl.organizations\n || !scope.organizationId\n || acl.organizations.includes(scope.organizationId)\n || acl.organizations.includes('__all__')\n return authorizeFeatures(required, {\n grantedFeatures: acl.features,\n unrestricted: acl.isSuperAdmin,\n scopeAllowed: organizationAllowed,\n })\n }\n\n async resolveFeatureOrganizationAccess(\n userId: string,\n required: readonly string[],\n input: { tenantId: string | null },\n ): Promise<FeatureOrganizationAccess> {\n const allowAll = (organizations: readonly FeatureOrganizationCandidate[]) =>\n normalizeFeatureOrganizationCandidates(organizations).map((organization) => organization.id)\n const denyAll = () => []\n if (!required.length) return { unrestricted: true, filterOrganizationIds: allowAll }\n if (!input.tenantId) return { unrestricted: false, filterOrganizationIds: denyAll }\n if (\n !userId.startsWith('api_key:')\n && await this.isGlobalSuperAdmin(userId)\n && authorizeFeatures(required, { grantedFeatures: ['*'], unrestricted: true })\n ) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n const grants = await this.loadFeatureOrganizationGrants(userId, input.tenantId)\n if (grants.kind === 'none') return { unrestricted: false, filterOrganizationIds: denyAll }\n\n if (grants.kind === 'api_key') {\n const keyOrganizationId = grants.organizationId\n const unrestricted = keyOrganizationId === null\n && roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, true)\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => (\n (!keyOrganizationId || organization.id === keyOrganizationId)\n && roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, true)\n ))\n .map((organization) => organization.id),\n }\n }\n\n if (grants.kind === 'user_acl') {\n const grantedFeatures = grants.features\n const allowedOrganizations = grants.organizations\n const hasGlobalScope = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n const unrestricted = authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed: hasGlobalScope,\n })\n if (unrestricted) return { unrestricted: true, filterOrganizationIds: allowAll }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => {\n const scopeAllowed = grants.isSuperAdmin\n || allowedOrganizations === null\n || allowedOrganizations.includes('__all__')\n || allowedOrganizations.includes(organization.id)\n return authorizeFeatures([...required], {\n grantedFeatures,\n unrestricted: grants.isSuperAdmin,\n scopeAllowed,\n })\n })\n .map((organization) => organization.id),\n }\n }\n\n if (roleAclsAuthorizeFeaturesGlobally(grants.roleGrants, required, false)) {\n return { unrestricted: true, filterOrganizationIds: allowAll }\n }\n\n return {\n unrestricted: false,\n filterOrganizationIds: (candidates) => normalizeFeatureOrganizationCandidates(candidates)\n .filter((organization) => roleAclsAuthorizeFeatures(grants.roleGrants, required, organization, false))\n .map((organization) => organization.id),\n }\n }\n\n private async loadFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n ): Promise<FeatureOrganizationGrants> {\n const cacheKey = `rbac:feature-organizations:${userId}:${tenantId}`\n const key = userId.startsWith('api_key:')\n ? await this.em.fork().findOne(ApiKey, { id: userId.slice('api_key:'.length), deletedAt: null })\n : undefined\n const cacheable = key === undefined || (key !== null && !isSessionBoundApiKey(key))\n if (this.cache && cacheable) {\n const cached = await this.cache.get(cacheKey)\n if (isFeatureOrganizationGrants(cached)) return cached\n }\n const grants = await this.queryFeatureOrganizationGrants(userId, tenantId, key)\n if (this.cache && cacheable) {\n await this.cache.set(cacheKey, grants, {\n ttl: this.cacheTtlMs,\n tags: this.buildCacheTags(userId, { tenantId, organizationId: null }),\n })\n }\n return grants\n }\n\n private async queryFeatureOrganizationGrants(\n userId: string,\n tenantId: string,\n knownApiKey?: ApiKey | null,\n ): Promise<FeatureOrganizationGrants> {\n const em = this.em.fork()\n if (userId.startsWith('api_key:')) {\n const apiKeyId = userId.slice('api_key:'.length)\n const key = knownApiKey === undefined\n ? await em.findOne(ApiKey, { id: apiKeyId, deletedAt: null })\n : knownApiKey\n if (\n !key\n || (key.expiresAt && key.expiresAt.getTime() < Date.now())\n || (key.tenantId && key.tenantId !== tenantId)\n ) {\n return { kind: 'none' }\n }\n\n const roleIds = await resolveApiKeyRoleIds(em, key, tenantId)\n if (!roleIds.length) return { kind: 'none' }\n const roleAcls = await em.find(RoleAcl, {\n tenantId,\n role: { $in: roleIds },\n })\n const keyOrganizationId = typeof key.organizationId === 'string' && key.organizationId.trim().length > 0\n ? key.organizationId.trim()\n : null\n return {\n kind: 'api_key',\n organizationId: keyOrganizationId,\n roleGrants: roleAcls.map(toFeatureOrganizationRoleGrant),\n }\n }\n\n const user = await em.findOne(User, { id: userId })\n if (!user) return { kind: 'none' }\n\n const userAcl = await em.findOne(UserAcl, { user: userId, tenantId })\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, role: { tenantId } },\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 role: { $in: roleIds },\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,SAAS,MAAM,gBAAgB;AACjD,SAAS,cAAc;AACvB,SAAS,sBAAsB,4BAA4B;AAC3D,SAAS,oBAAoB;AAC7B,SAAS,uBAAuB,0BAA0B;AAE1D,SAAS,2BAA2B,mCAAmC;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,8BAA8B,iCAAiC;AAQxE,eAAe,8CACb,IACA,UACA,gBACqC;AACrC,MAAI,CAAC,eAAgB,QAAO;AAC5B,MAAI,CAAC,SAAU,QAAO,oBAAI,IAAI;AAC9B,QAAM,eAAe,MAAM;AAAA,IACzB;AAAA,IACA;AAAA,IACA,EAAE,IAAI,gBAAgB,QAAQ,UAAU,WAAW,KAAK;AAAA,IACxD,EAAE,QAAQ,CAAC,MAAM,aAAa,EAAE;AAAA,IAChC,EAAE,UAAU,eAAe;AAAA,EAC7B;AACA,MAAI,CAAC,aAAc,QAAO,oBAAI,IAAI;AAClC,QAAM,YAAY,MAAM,QAAQ,aAAa,WAAW,IACpD,aAAa,YAAY,OAAO,CA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S,GACrC;AACA,aAAO,CAAC;AAAA,IACV;AACA,WAAO,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;",
|
|
6
6
|
"names": ["result", "em", "tenantId", "roleIds", "isSuper", "features", "hasApplicableRestrictedRole", "organizations", "roleScope", "roleAcls", "isSuperAdmin", "organizationId"]
|
|
7
7
|
}
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
resolveOpenMercatoApiKeyProfile
|
|
7
7
|
} from "./openmercato-call-options.js";
|
|
8
8
|
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
|
|
9
|
+
import { resolveApiKeyRoleIds } from "@open-mercato/core/modules/api_keys/services/sessionKeyRoles";
|
|
9
10
|
async function executeActions(actions, context) {
|
|
10
11
|
const startTime = Date.now();
|
|
11
12
|
const results = [];
|
|
@@ -254,7 +255,7 @@ async function handleCallOpenMercato(action, context) {
|
|
|
254
255
|
if (!apiKeyProfile) {
|
|
255
256
|
throw new Error("CALL_OPEN_MERCATO action requires an active API key profile in scope");
|
|
256
257
|
}
|
|
257
|
-
const roleIds =
|
|
258
|
+
const roleIds = await resolveApiKeyRoleIds(em, apiKeyProfile, tenantId);
|
|
258
259
|
if (roleIds.length === 0) {
|
|
259
260
|
throw new Error("CALL_OPEN_MERCATO action requires an API key profile with at least one role");
|
|
260
261
|
}
|