@open-mercato/core 0.6.8-develop.7015.1.af90a2ddc7 → 0.6.8-develop.7016.1.4ed7b1e49d

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.
Files changed (62) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/api/keys/route.js +1 -1
  3. package/dist/modules/api_keys/api/keys/route.js.map +2 -2
  4. package/dist/modules/api_keys/di.js +9 -0
  5. package/dist/modules/api_keys/di.js.map +7 -0
  6. package/dist/modules/api_keys/services/principalService.js +31 -0
  7. package/dist/modules/api_keys/services/principalService.js.map +7 -0
  8. package/dist/modules/attachments/di.js +11 -1
  9. package/dist/modules/attachments/di.js.map +2 -2
  10. package/dist/modules/attachments/index.js.map +1 -1
  11. package/dist/modules/attachments/lib/attachment-service.js +313 -0
  12. package/dist/modules/attachments/lib/attachment-service.js.map +7 -0
  13. package/dist/modules/attachments/lib/scoped-upload-service.js +15 -2
  14. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  15. package/dist/modules/attachments/lib/upload-limits.js +6 -2
  16. package/dist/modules/attachments/lib/upload-limits.js.map +2 -2
  17. package/dist/modules/auth/data/entities.js.map +2 -2
  18. package/dist/modules/auth/di.js +35 -9
  19. package/dist/modules/auth/di.js.map +2 -2
  20. package/dist/modules/auth/services/principalService.js +200 -0
  21. package/dist/modules/auth/services/principalService.js.map +7 -0
  22. package/dist/modules/auth/services/rbacService.js +67 -24
  23. package/dist/modules/auth/services/rbacService.js.map +3 -3
  24. package/dist/modules/auth/services/roleOrganizationScope.js +41 -0
  25. package/dist/modules/auth/services/roleOrganizationScope.js.map +7 -0
  26. package/dist/modules/directory/di.js +9 -0
  27. package/dist/modules/directory/di.js.map +2 -2
  28. package/dist/modules/directory/services/organizationHierarchyService.js +29 -0
  29. package/dist/modules/directory/services/organizationHierarchyService.js.map +7 -0
  30. package/dist/modules/directory/services/organizationScopeService.js +56 -0
  31. package/dist/modules/directory/services/organizationScopeService.js.map +7 -0
  32. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  33. package/dist/modules/warranty_claims/api/portal/attachments/route.js +2 -2
  34. package/dist/modules/warranty_claims/api/portal/attachments/route.js.map +2 -2
  35. package/dist/modules/workflows/lib/activity-executor.js +4 -0
  36. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  37. package/package.json +7 -7
  38. package/src/modules/api_keys/api/keys/route.ts +3 -1
  39. package/src/modules/api_keys/di.ts +7 -0
  40. package/src/modules/api_keys/services/principalService.ts +33 -0
  41. package/src/modules/attachments/AGENTS.md +15 -0
  42. package/src/modules/attachments/di.ts +16 -0
  43. package/src/modules/attachments/i18n/de.json +5 -0
  44. package/src/modules/attachments/i18n/en.json +5 -0
  45. package/src/modules/attachments/i18n/es.json +5 -0
  46. package/src/modules/attachments/i18n/ko.json +5 -0
  47. package/src/modules/attachments/i18n/pl.json +5 -0
  48. package/src/modules/attachments/index.ts +10 -0
  49. package/src/modules/attachments/lib/attachment-service.ts +468 -0
  50. package/src/modules/attachments/lib/scoped-upload-service.ts +46 -0
  51. package/src/modules/attachments/lib/upload-limits.ts +6 -2
  52. package/src/modules/auth/data/entities.ts +4 -1
  53. package/src/modules/auth/di.ts +46 -16
  54. package/src/modules/auth/services/principalService.ts +266 -0
  55. package/src/modules/auth/services/rbacService.ts +110 -24
  56. package/src/modules/auth/services/roleOrganizationScope.ts +70 -0
  57. package/src/modules/directory/di.ts +14 -2
  58. package/src/modules/directory/services/organizationHierarchyService.ts +34 -0
  59. package/src/modules/directory/services/organizationScopeService.ts +85 -0
  60. package/src/modules/directory/utils/organizationScope.ts +4 -15
  61. package/src/modules/warranty_claims/api/portal/attachments/route.ts +2 -2
  62. package/src/modules/workflows/lib/activity-executor.ts +9 -0
@@ -0,0 +1,200 @@
1
+ import { sql } from "kysely";
2
+ import { escapeLikePattern } from "@open-mercato/shared/lib/db/escapeLikePattern";
3
+ import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
4
+ import { Role, RoleAcl, User, UserRole } from "../data/entities.js";
5
+ import { listSuperAdminUserIds } from "../lib/grantChecks.js";
6
+ import { resolveRoleOrganizationScope, roleAclGrantsPrincipalOrganization } from "./roleOrganizationScope.js";
7
+ const MAX_ROLE_PAGE_SIZE = 100;
8
+ const MAX_ROLE_RESULTS = 1e3;
9
+ function normalizeIds(ids) {
10
+ return Array.from(new Set(ids.map((id) => id.trim()).filter(Boolean)));
11
+ }
12
+ function relationId(value) {
13
+ if (typeof value === "string") return value.trim() || null;
14
+ if (!value || typeof value !== "object") return null;
15
+ const id = value.id;
16
+ return typeof id === "string" && id.trim().length > 0 ? id.trim() : null;
17
+ }
18
+ class DefaultAuthPrincipalService {
19
+ constructor(em, organizationHierarchyService) {
20
+ this.em = em;
21
+ this.organizationHierarchyService = organizationHierarchyService;
22
+ }
23
+ async principalExists(input) {
24
+ if (input.type === "role") {
25
+ return (await this.filterActiveRoleIds([input.id], input.scope)).includes(input.id);
26
+ }
27
+ return Boolean(await findOneWithDecryption(
28
+ this.em,
29
+ User,
30
+ {
31
+ id: input.id,
32
+ tenantId: input.scope.tenantId,
33
+ deletedAt: null,
34
+ $or: [{ organizationId: null }, { organizationId: input.scope.organizationId }]
35
+ },
36
+ { fields: ["id"] },
37
+ input.scope
38
+ ));
39
+ }
40
+ async resolveActiveUserRoleIds(userId, scope) {
41
+ const links = await findWithDecryption(
42
+ this.em,
43
+ UserRole,
44
+ {
45
+ user: userId,
46
+ deletedAt: null,
47
+ role: { tenantId: scope.tenantId, deletedAt: null }
48
+ },
49
+ { fields: ["role"] },
50
+ scope
51
+ );
52
+ return this.filterActiveRoleIds(
53
+ normalizeIds(links.flatMap((link) => {
54
+ const id = relationId(link.role);
55
+ return id ? [id] : [];
56
+ })),
57
+ scope
58
+ );
59
+ }
60
+ async filterActiveRoleIds(roleIds, scope) {
61
+ const ids = normalizeIds(roleIds);
62
+ if (ids.length === 0) return [];
63
+ const roles = await findWithDecryption(
64
+ this.em,
65
+ Role,
66
+ { id: { $in: ids }, tenantId: scope.tenantId, deletedAt: null },
67
+ { fields: ["id"] },
68
+ scope
69
+ );
70
+ const activeIds = normalizeIds(roles.map((role) => role.id));
71
+ if (activeIds.length === 0) return [];
72
+ const roleOrganizationScope = await resolveRoleOrganizationScope(
73
+ this.organizationHierarchyService,
74
+ scope.tenantId,
75
+ scope.organizationId
76
+ );
77
+ const acls = await findWithDecryption(
78
+ this.em,
79
+ RoleAcl,
80
+ {
81
+ tenantId: scope.tenantId,
82
+ role: { $in: activeIds },
83
+ deletedAt: null
84
+ },
85
+ { fields: ["role", "organizationsJson"] },
86
+ scope
87
+ );
88
+ const eligibilityById = /* @__PURE__ */ new Map();
89
+ for (const acl of acls) {
90
+ const id = relationId(acl.role);
91
+ if (!id) continue;
92
+ eligibilityById.set(
93
+ id,
94
+ eligibilityById.get(id) === true || roleAclGrantsPrincipalOrganization(acl, roleOrganizationScope)
95
+ );
96
+ }
97
+ return activeIds.filter((id) => eligibilityById.get(id) !== false);
98
+ }
99
+ async resolveLabels(input) {
100
+ const ids = normalizeIds(input.ids);
101
+ if (ids.length === 0) return [];
102
+ if (input.type === "role") {
103
+ const eligibleIds = await this.filterActiveRoleIds(ids, input.scope);
104
+ if (eligibleIds.length === 0) return [];
105
+ const roles = await findWithDecryption(
106
+ this.em,
107
+ Role,
108
+ { id: { $in: eligibleIds }, tenantId: input.scope.tenantId, deletedAt: null },
109
+ { fields: ["id", "name"] },
110
+ input.scope
111
+ );
112
+ return roles.map((role) => ({ id: role.id, label: role.name, secondary: null }));
113
+ }
114
+ const users = await findWithDecryption(
115
+ this.em,
116
+ User,
117
+ {
118
+ id: { $in: ids },
119
+ tenantId: input.scope.tenantId,
120
+ deletedAt: null,
121
+ $or: [{ organizationId: null }, { organizationId: input.scope.organizationId }]
122
+ },
123
+ { fields: ["id", "name", "email"] },
124
+ input.scope
125
+ );
126
+ return users.map((user) => ({
127
+ id: user.id,
128
+ label: user.name?.trim() || user.email,
129
+ secondary: user.name?.trim() && user.email !== user.name.trim() ? user.email : null
130
+ }));
131
+ }
132
+ async queryActiveRolePage(input) {
133
+ const page = Math.max(1, Math.floor(input.page));
134
+ const pageSize = Math.min(MAX_ROLE_PAGE_SIZE, Math.max(1, Math.floor(input.pageSize)));
135
+ const offset = (page - 1) * pageSize;
136
+ const excludedIds = normalizeIds(input.excludedIds ?? []);
137
+ const roleOrganizationScope = await resolveRoleOrganizationScope(
138
+ this.organizationHierarchyService,
139
+ input.scope.tenantId,
140
+ input.scope.organizationId
141
+ );
142
+ const db = this.em.getKysely();
143
+ let eligibleRoles = db.selectFrom("roles as r").where("r.tenant_id", "=", input.scope.tenantId).where("r.deleted_at", "is", null);
144
+ if (roleOrganizationScope) {
145
+ const allowedOrganizations = Array.from(roleOrganizationScope);
146
+ const organizationPredicates = [
147
+ sql`ra.organizations_json is null`,
148
+ sql`ra.organizations_json::jsonb @> ${JSON.stringify(["__all__"])}::jsonb`,
149
+ ...allowedOrganizations.map((organizationId) => sql`ra.organizations_json::jsonb @> ${JSON.stringify([organizationId])}::jsonb`)
150
+ ];
151
+ const organizationAllowed = sql`(${sql.join(organizationPredicates, sql` or `)})`;
152
+ eligibleRoles = eligibleRoles.where(sql`(
153
+ not exists (
154
+ select 1
155
+ from role_acls as ra_any
156
+ where ra_any.role_id = r.id
157
+ and ra_any.tenant_id = ${input.scope.tenantId}
158
+ and ra_any.deleted_at is null
159
+ )
160
+ or exists (
161
+ select 1
162
+ from role_acls as ra
163
+ where ra.role_id = r.id
164
+ and ra.tenant_id = ${input.scope.tenantId}
165
+ and ra.deleted_at is null
166
+ and ${organizationAllowed}
167
+ )
168
+ )`);
169
+ }
170
+ if (input.search?.trim()) {
171
+ const searchPattern = `%${escapeLikePattern(input.search.trim())}%`;
172
+ eligibleRoles = eligibleRoles.where(sql`r.name ilike ${searchPattern}`);
173
+ }
174
+ if (excludedIds.length > 0) {
175
+ eligibleRoles = eligibleRoles.where("r.id", "not in", excludedIds);
176
+ }
177
+ const boundedRoleIds = eligibleRoles.select("r.id").limit(MAX_ROLE_RESULTS).as("bounded_roles");
178
+ const countQuery = db.selectFrom(boundedRoleIds).select(sql`count(*)`.as("count"));
179
+ const pageQuery = eligibleRoles.select(["r.id", "r.name"]).orderBy("r.id", "asc").limit(offset < MAX_ROLE_RESULTS ? Math.min(pageSize, MAX_ROLE_RESULTS - offset) : 0).offset(Math.min(offset, MAX_ROLE_RESULTS));
180
+ const [rows, countRow] = await Promise.all([
181
+ pageQuery.execute(),
182
+ countQuery.executeTakeFirst()
183
+ ]);
184
+ const parsedTotal = Number(countRow?.count ?? 0);
185
+ const total = Number.isFinite(parsedTotal) ? Math.min(MAX_ROLE_RESULTS, Math.max(0, Math.floor(parsedTotal))) : 0;
186
+ return {
187
+ items: rows.map((role) => ({ id: role.id, label: role.name, secondary: null })),
188
+ page,
189
+ pageSize,
190
+ total
191
+ };
192
+ }
193
+ async listSuperAdminUserIds(tenantId) {
194
+ return Array.from(await listSuperAdminUserIds(this.em, tenantId));
195
+ }
196
+ }
197
+ export {
198
+ DefaultAuthPrincipalService
199
+ };
200
+ //# sourceMappingURL=principalService.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/auth/services/principalService.ts"],
4
+ "sourcesContent": ["import type { FilterQuery } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { sql } from 'kysely'\nimport type {\n AuthPrincipalLabel,\n AuthPrincipalRolePage,\n AuthPrincipalService,\n OrganizationHierarchyService,\n PrincipalScope,\n} from '@open-mercato/shared/lib/auth/principal-service'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { Role, RoleAcl, User, UserRole } from '../data/entities'\nimport { listSuperAdminUserIds } from '../lib/grantChecks'\nimport { resolveRoleOrganizationScope, roleAclGrantsPrincipalOrganization } from './roleOrganizationScope'\n\nconst MAX_ROLE_PAGE_SIZE = 100\nconst MAX_ROLE_RESULTS = 1_000\n\ntype AuthPrincipalDatabase = {\n roles: {\n id: string\n tenant_id: string\n name: string\n deleted_at: Date | null\n }\n role_acls: {\n role_id: string\n tenant_id: string\n organizations_json: string[] | null\n deleted_at: Date | null\n }\n}\n\nfunction normalizeIds(ids: string[]): string[] {\n return Array.from(new Set(ids.map((id) => id.trim()).filter(Boolean)))\n}\n\nfunction relationId(value: unknown): string | null {\n if (typeof value === 'string') return value.trim() || null\n if (!value || typeof value !== 'object') return null\n const id = (value as { id?: unknown }).id\n return typeof id === 'string' && id.trim().length > 0 ? id.trim() : null\n}\n\nexport class DefaultAuthPrincipalService implements AuthPrincipalService {\n constructor(\n private readonly em: EntityManager,\n private readonly organizationHierarchyService?: OrganizationHierarchyService,\n ) {}\n\n async principalExists(input: {\n type: 'user' | 'role'\n id: string\n scope: PrincipalScope\n }): Promise<boolean> {\n if (input.type === 'role') {\n return (await this.filterActiveRoleIds([input.id], input.scope)).includes(input.id)\n }\n return Boolean(await findOneWithDecryption(\n this.em,\n User,\n {\n id: input.id,\n tenantId: input.scope.tenantId,\n deletedAt: null,\n $or: [{ organizationId: null }, { organizationId: input.scope.organizationId }],\n } as FilterQuery<User>,\n { fields: ['id'] as const },\n input.scope,\n ))\n }\n\n async resolveActiveUserRoleIds(userId: string, scope: PrincipalScope): Promise<string[]> {\n const links = await findWithDecryption(\n this.em,\n UserRole,\n {\n user: userId,\n deletedAt: null,\n role: { tenantId: scope.tenantId, deletedAt: null },\n } as FilterQuery<UserRole>,\n { fields: ['role'] as const },\n scope,\n )\n return this.filterActiveRoleIds(\n normalizeIds(links.flatMap((link) => {\n const id = relationId(link.role)\n return id ? [id] : []\n })),\n scope,\n )\n }\n\n async filterActiveRoleIds(roleIds: string[], scope: PrincipalScope): Promise<string[]> {\n const ids = normalizeIds(roleIds)\n if (ids.length === 0) return []\n const roles = await findWithDecryption(\n this.em,\n Role,\n { id: { $in: ids }, tenantId: scope.tenantId, deletedAt: null } as FilterQuery<Role>,\n { fields: ['id'] as const },\n scope,\n )\n const activeIds = normalizeIds(roles.map((role) => role.id))\n if (activeIds.length === 0) return []\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n scope.tenantId,\n scope.organizationId,\n )\n const acls = await findWithDecryption(\n this.em,\n RoleAcl,\n {\n tenantId: scope.tenantId,\n role: { $in: activeIds },\n deletedAt: null,\n } as FilterQuery<RoleAcl>,\n { fields: ['role', 'organizationsJson'] as const },\n scope,\n )\n const eligibilityById = new Map<string, boolean>()\n for (const acl of acls) {\n const id = relationId(acl.role)\n if (!id) continue\n eligibilityById.set(\n id,\n eligibilityById.get(id) === true || roleAclGrantsPrincipalOrganization(acl, roleOrganizationScope),\n )\n }\n // A tenant role without an ACL remains a valid explicit-share principal.\n // Only an existing ACL can restrict that role away from this organization.\n return activeIds.filter((id) => eligibilityById.get(id) !== false)\n }\n\n async resolveLabels(input: {\n type: 'user' | 'role'\n ids: string[]\n scope: PrincipalScope\n }): Promise<AuthPrincipalLabel[]> {\n const ids = normalizeIds(input.ids)\n if (ids.length === 0) return []\n if (input.type === 'role') {\n const eligibleIds = await this.filterActiveRoleIds(ids, input.scope)\n if (eligibleIds.length === 0) return []\n const roles = await findWithDecryption(\n this.em,\n Role,\n { id: { $in: eligibleIds }, tenantId: input.scope.tenantId, deletedAt: null } as FilterQuery<Role>,\n { fields: ['id', 'name'] as const },\n input.scope,\n )\n return roles.map((role) => ({ id: role.id, label: role.name, secondary: null }))\n }\n const users = await findWithDecryption(\n this.em,\n User,\n {\n id: { $in: ids },\n tenantId: input.scope.tenantId,\n deletedAt: null,\n $or: [{ organizationId: null }, { organizationId: input.scope.organizationId }],\n } as FilterQuery<User>,\n { fields: ['id', 'name', 'email'] as const },\n input.scope,\n )\n return users.map((user) => ({\n id: user.id,\n label: user.name?.trim() || user.email,\n secondary: user.name?.trim() && user.email !== user.name.trim() ? user.email : null,\n }))\n }\n\n async queryActiveRolePage(input: {\n scope: PrincipalScope\n search?: string\n excludedIds?: string[]\n page: number\n pageSize: number\n }): Promise<AuthPrincipalRolePage> {\n const page = Math.max(1, Math.floor(input.page))\n const pageSize = Math.min(MAX_ROLE_PAGE_SIZE, Math.max(1, Math.floor(input.pageSize)))\n const offset = (page - 1) * pageSize\n const excludedIds = normalizeIds(input.excludedIds ?? [])\n const roleOrganizationScope = await resolveRoleOrganizationScope(\n this.organizationHierarchyService,\n input.scope.tenantId,\n input.scope.organizationId,\n )\n const db = this.em.getKysely<AuthPrincipalDatabase>()\n let eligibleRoles = db\n .selectFrom('roles as r')\n .where('r.tenant_id', '=', input.scope.tenantId)\n .where('r.deleted_at', 'is', null)\n\n if (roleOrganizationScope) {\n const allowedOrganizations = Array.from(roleOrganizationScope)\n const organizationPredicates = [\n sql<boolean>`ra.organizations_json is null`,\n sql<boolean>`ra.organizations_json::jsonb @> ${JSON.stringify(['__all__'])}::jsonb`,\n ...allowedOrganizations.map((organizationId) => (\n sql<boolean>`ra.organizations_json::jsonb @> ${JSON.stringify([organizationId])}::jsonb`\n )),\n ]\n const organizationAllowed = sql<boolean>`(${sql.join(organizationPredicates, sql` or `)})`\n eligibleRoles = eligibleRoles.where(sql<boolean>`(\n not exists (\n select 1\n from role_acls as ra_any\n where ra_any.role_id = r.id\n and ra_any.tenant_id = ${input.scope.tenantId}\n and ra_any.deleted_at is null\n )\n or exists (\n select 1\n from role_acls as ra\n where ra.role_id = r.id\n and ra.tenant_id = ${input.scope.tenantId}\n and ra.deleted_at is null\n and ${organizationAllowed}\n )\n )`)\n }\n if (input.search?.trim()) {\n const searchPattern = `%${escapeLikePattern(input.search.trim())}%`\n eligibleRoles = eligibleRoles.where(sql<boolean>`r.name ilike ${searchPattern}`)\n }\n if (excludedIds.length > 0) {\n eligibleRoles = eligibleRoles.where('r.id', 'not in', excludedIds)\n }\n\n const boundedRoleIds = eligibleRoles\n .select('r.id')\n .limit(MAX_ROLE_RESULTS)\n .as('bounded_roles')\n const countQuery = db\n .selectFrom(boundedRoleIds)\n .select(sql<string>`count(*)`.as('count'))\n const pageQuery = eligibleRoles\n .select(['r.id', 'r.name'])\n .orderBy('r.id', 'asc')\n .limit(offset < MAX_ROLE_RESULTS ? Math.min(pageSize, MAX_ROLE_RESULTS - offset) : 0)\n .offset(Math.min(offset, MAX_ROLE_RESULTS))\n\n const [rows, countRow] = await Promise.all([\n pageQuery.execute() as Promise<Array<{ id: string; name: string }>>,\n countQuery.executeTakeFirst() as Promise<{ count?: string | number } | undefined>,\n ])\n const parsedTotal = Number(countRow?.count ?? 0)\n const total = Number.isFinite(parsedTotal)\n ? Math.min(MAX_ROLE_RESULTS, Math.max(0, Math.floor(parsedTotal)))\n : 0\n\n return {\n items: rows.map((role) => ({ id: role.id, label: role.name, secondary: null })),\n page,\n pageSize,\n total,\n }\n }\n\n async listSuperAdminUserIds(tenantId: string): Promise<string[]> {\n return Array.from(await listSuperAdminUserIds(this.em, tenantId))\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,WAAW;AAQpB,SAAS,yBAAyB;AAClC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,MAAM,SAAS,MAAM,gBAAgB;AAC9C,SAAS,6BAA6B;AACtC,SAAS,8BAA8B,0CAA0C;AAEjF,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AAiBzB,SAAS,aAAa,KAAyB;AAC7C,SAAO,MAAM,KAAK,IAAI,IAAI,IAAI,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE,OAAO,OAAO,CAAC,CAAC;AACvE;AAEA,SAAS,WAAW,OAA+B;AACjD,MAAI,OAAO,UAAU,SAAU,QAAO,MAAM,KAAK,KAAK;AACtD,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,KAAM,MAA2B;AACvC,SAAO,OAAO,OAAO,YAAY,GAAG,KAAK,EAAE,SAAS,IAAI,GAAG,KAAK,IAAI;AACtE;AAEO,MAA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QAAQ;AAAA,MAClB,WAAW,iBAAiB;AAAA,IAC9B,CAAC;AACD,UAAM,cAAc,OAAO,UAAU,SAAS,CAAC;AAC/C,UAAM,QAAQ,OAAO,SAAS,WAAW,IACrC,KAAK,IAAI,kBAAkB,KAAK,IAAI,GAAG,KAAK,MAAM,WAAW,CAAC,CAAC,IAC/D;AAEJ,WAAO;AAAA,MACL,OAAO,KAAK,IAAI,CAAC,UAAU,EAAE,IAAI,KAAK,IAAI,OAAO,KAAK,MAAM,WAAW,KAAK,EAAE;AAAA,MAC9E;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,sBAAsB,UAAqC;AAC/D,WAAO,MAAM,KAAK,MAAM,sBAAsB,KAAK,IAAI,QAAQ,CAAC;AAAA,EAClE;AACF;",
6
+ "names": []
7
+ }
@@ -8,6 +8,7 @@ import {
8
8
  resolveEffectiveFeatures
9
9
  } from "@open-mercato/shared/security/featurePolicy";
10
10
  import { filterGrantsByEnabledModules } from "@open-mercato/shared/security/enabledModulesRegistry";
11
+ import { resolveRoleOrganizationScope, roleAclAllowsOrganization } from "./roleOrganizationScope.js";
11
12
  function isAclData(value) {
12
13
  if (typeof value !== "object" || value === null) return false;
13
14
  const record = value;
@@ -19,9 +20,13 @@ function isAclData(value) {
19
20
  }
20
21
  return true;
21
22
  }
23
+ function isRestrictedRoleAcl(acl) {
24
+ return Array.isArray(acl.organizationsJson) && acl.organizationsJson.length > 0 && !acl.organizationsJson.includes("__all__");
25
+ }
22
26
  class RbacService {
23
- constructor(em, cache) {
27
+ constructor(em, cache, organizationHierarchyService) {
24
28
  this.em = em;
29
+ this.organizationHierarchyService = organizationHierarchyService;
25
30
  this.cacheTtlMs = 5 * 60 * 1e3;
26
31
  // 5 minutes default
27
32
  this.cache = null;
@@ -39,12 +44,6 @@ class RbacService {
39
44
  hasAllFeatures(required, granted) {
40
45
  return authorizeFeatures(required, { grantedFeatures: granted });
41
46
  }
42
- roleAclAllowsOrganization(acl, organizationId) {
43
- if (!organizationId) return true;
44
- const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null;
45
- if (!organizations || !organizations.length || organizations.includes("__all__")) return true;
46
- return organizations.includes(organizationId);
47
- }
48
47
  getCacheKey(userId, scope) {
49
48
  return `rbac:${userId}:${scope.tenantId || "null"}:${scope.organizationId || "null"}`;
50
49
  }
@@ -71,6 +70,7 @@ class RbacService {
71
70
  ];
72
71
  if (scope.tenantId) {
73
72
  tags.push(this.getTenantTag(scope.tenantId));
73
+ tags.push(buildOrgScopeTenantCacheTag(scope.tenantId));
74
74
  }
75
75
  if (scope.organizationId) {
76
76
  tags.push(this.getOrganizationTag(scope.organizationId));
@@ -167,8 +167,8 @@ class RbacService {
167
167
  this.globalSuperAdminCache.set(userId, false);
168
168
  return false;
169
169
  }
170
- const roleSuper = await em.findOne(RoleAcl, { isSuperAdmin: true, role: { $in: roleIds } });
171
- const result = !!(roleSuper && roleSuper.isSuperAdmin);
170
+ const roleSupers = await em.find(RoleAcl, { isSuperAdmin: true, role: { $in: roleIds } });
171
+ const result = roleSupers.some((roleAcl) => !!roleAcl.isSuperAdmin && !isRestrictedRoleAcl(roleAcl));
172
172
  this.globalSuperAdminCache.set(userId, result);
173
173
  return result;
174
174
  }
@@ -215,28 +215,55 @@ class RbacService {
215
215
  }
216
216
  const tenantId2 = scope.tenantId || key.tenantId || null;
217
217
  const roleIds2 = Array.isArray(key.rolesJson) ? key.rolesJson.filter(Boolean) : [];
218
+ const keyOrganizationId = typeof key.organizationId === "string" && key.organizationId.trim().length > 0 ? key.organizationId.trim() : null;
219
+ const evaluatedOrganizationId = scope.organizationId || keyOrganizationId;
218
220
  let isSuper2 = false;
219
221
  const features2 = [];
220
- let organizations2 = key.organizationId ? [key.organizationId] : null;
222
+ let roleOrganizations = [];
223
+ let hasApplicableRestrictedRole2 = false;
221
224
  if (tenantId2 && roleIds2.length) {
225
+ const roleOrganizationScope = await resolveRoleOrganizationScope(
226
+ this.organizationHierarchyService,
227
+ tenantId2,
228
+ evaluatedOrganizationId
229
+ );
222
230
  const racls = await em2.find(RoleAcl, { tenantId: tenantId2, role: { $in: roleIds2 } });
223
231
  for (const acl of racls) {
224
- isSuper2 = isSuper2 || !!acl.isSuperAdmin;
225
- if (Array.isArray(acl.featuresJson)) {
226
- for (const f of acl.featuresJson) if (!features2.includes(f)) features2.push(f);
232
+ if (roleAclAllowsOrganization(acl, roleOrganizationScope)) {
233
+ isSuper2 = isSuper2 || !!acl.isSuperAdmin;
234
+ if (Array.isArray(acl.featuresJson)) {
235
+ for (const f of acl.featuresJson) if (!features2.includes(f)) features2.push(f);
236
+ }
237
+ if (isRestrictedRoleAcl(acl)) hasApplicableRestrictedRole2 = true;
227
238
  }
228
- if (organizations2 !== null) {
229
- if (acl.organizationsJson == null) {
230
- organizations2 = null;
239
+ if (roleOrganizations !== null) {
240
+ if (acl.organizationsJson == null || Array.isArray(acl.organizationsJson) && acl.organizationsJson.length === 0) {
241
+ roleOrganizations = null;
231
242
  } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes("__all__")) {
232
- organizations2 = null;
243
+ roleOrganizations = null;
233
244
  } else {
234
- organizations2 = Array.from(/* @__PURE__ */ new Set([...organizations2 || [], ...acl.organizationsJson]));
245
+ roleOrganizations = Array.from(/* @__PURE__ */ new Set([
246
+ ...roleOrganizations,
247
+ ...Array.isArray(acl.organizationsJson) ? acl.organizationsJson : []
248
+ ]));
235
249
  }
236
250
  }
237
251
  }
252
+ if (roleOrganizations !== null && evaluatedOrganizationId && roleOrganizationScope !== null && roleOrganizationScope.size > 0 && hasApplicableRestrictedRole2 && !roleOrganizations.includes(evaluatedOrganizationId)) {
253
+ roleOrganizations.push(evaluatedOrganizationId);
254
+ }
238
255
  }
239
- const result2 = { isSuperAdmin: isSuper2, features: features2, organizations: organizations2 };
256
+ let organizations2 = roleOrganizations;
257
+ if (keyOrganizationId) {
258
+ const keyOrganizationScope = await resolveRoleOrganizationScope(
259
+ this.organizationHierarchyService,
260
+ tenantId2,
261
+ keyOrganizationId
262
+ );
263
+ organizations2 = roleOrganizations === null || roleOrganizations.some((organizationId) => keyOrganizationScope?.has(organizationId)) ? [keyOrganizationId] : [];
264
+ }
265
+ if (isSuper2 && organizations2 !== null && !features2.includes("*")) features2.push("*");
266
+ const result2 = { isSuperAdmin: isSuper2 && organizations2 === null, features: features2, organizations: organizations2 };
240
267
  await this.setCache(cacheKey, result2, userId, scope);
241
268
  return result2;
242
269
  }
@@ -276,13 +303,22 @@ class RbacService {
276
303
  let isSuper = false;
277
304
  const features = [];
278
305
  let organizations = [];
306
+ let hasApplicableRestrictedRole = false;
279
307
  if (roleIds.length) {
308
+ const roleOrganizationScope = await resolveRoleOrganizationScope(
309
+ this.organizationHierarchyService,
310
+ tenantId,
311
+ scope.organizationId
312
+ );
280
313
  const racls = await em.find(RoleAcl, { tenantId, role: { $in: roleIds } }, {});
281
314
  const roleAcls = Array.isArray(racls) ? racls : [];
282
315
  for (const r of roleAcls) {
283
- isSuper = isSuper || !!r.isSuperAdmin;
284
- if (Array.isArray(r.featuresJson)) {
285
- for (const f of r.featuresJson) if (!features.includes(f)) features.push(f);
316
+ if (roleAclAllowsOrganization(r, roleOrganizationScope)) {
317
+ isSuper = isSuper || !!r.isSuperAdmin;
318
+ if (Array.isArray(r.featuresJson)) {
319
+ for (const f of r.featuresJson) if (!features.includes(f)) features.push(f);
320
+ }
321
+ if (isRestrictedRoleAcl(r)) hasApplicableRestrictedRole = true;
286
322
  }
287
323
  if (organizations !== null) {
288
324
  if (r.organizationsJson == null) organizations = null;
@@ -290,6 +326,9 @@ class RbacService {
290
326
  else organizations = Array.from(/* @__PURE__ */ new Set([...organizations || [], ...r.organizationsJson]));
291
327
  }
292
328
  }
329
+ if (organizations !== null && scope.organizationId && roleOrganizationScope !== null && roleOrganizationScope.size > 0 && hasApplicableRestrictedRole && !organizations.includes(scope.organizationId)) {
330
+ organizations.push(scope.organizationId);
331
+ }
293
332
  }
294
333
  if (organizations && orgId && !organizations.includes(orgId) && !organizations.includes("__all__")) {
295
334
  }
@@ -306,11 +345,15 @@ class RbacService {
306
345
  async tenantHasFeature(tenantId, feature, opts) {
307
346
  if (!tenantId || !feature) return false;
308
347
  const em = this.em.fork();
348
+ const roleOrganizationScope = await resolveRoleOrganizationScope(
349
+ this.organizationHierarchyService,
350
+ tenantId,
351
+ opts?.organizationId
352
+ );
309
353
  const roleAcls = await em.find(RoleAcl, { tenantId, deletedAt: null }, {});
310
354
  const list = Array.isArray(roleAcls) ? roleAcls : [];
311
- const organizationId = opts?.organizationId ?? null;
312
355
  for (const acl of list) {
313
- if (!this.roleAclAllowsOrganization(acl, organizationId)) continue;
356
+ if (!roleAclAllowsOrganization(acl, roleOrganizationScope)) continue;
314
357
  const grants = Array.isArray(acl.featuresJson) ? acl.featuresJson : [];
315
358
  if (authorizeFeatures([feature], {
316
359
  grantedFeatures: grants,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/auth/services/rbacService.ts"],
4
- "sourcesContent": ["import type { EntityManager } 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 { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\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'\n\ninterface AclData {\n isSuperAdmin: boolean\n features: string[]\n organizations: string[] | null\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\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(private em: EntityManager, cache?: CacheStrategy) {\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 roleAclAllowsOrganization(acl: RoleAcl, organizationId: string | null | undefined): boolean {\n if (!organizationId) return true\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || !organizations.length || organizations.includes('__all__')) return true\n return organizations.includes(organizationId)\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 const tags = [\n this.getUserTag(userId),\n 'rbac:all'\n ]\n\n if (scope.tenantId) {\n tags.push(this.getTenantTag(scope.tenantId))\n }\n\n if (scope.organizationId) {\n tags.push(this.getOrganizationTag(scope.organizationId))\n }\n\n await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags\n })\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 roleSuper = await em.findOne(RoleAcl, { isSuperAdmin: true, role: { $in: roleIds as any } } as any)\n const result = !!(roleSuper && (roleSuper as any).isSuperAdmin)\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 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 let isSuper = false\n const features: string[] = []\n let organizations: string[] | null = key.organizationId ? [key.organizationId] : null\n if (tenantId && roleIds.length) {\n const racls = await em.find(RoleAcl, { tenantId, role: { $in: roleIds as any } } as any)\n for (const acl of racls) {\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 (organizations !== null) {\n if (acl.organizationsJson == null) {\n organizations = null\n } else if (Array.isArray(acl.organizationsJson) && acl.organizationsJson.includes('__all__')) {\n organizations = null\n } else {\n organizations = Array.from(new Set([...(organizations || []), ...acl.organizationsJson]))\n }\n }\n }\n }\n const result = { isSuperAdmin: isSuper, 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 if (roleIds.length) {\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 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 (organizations !== null) {\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 }\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 * 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 roleAcls = await em.find(RoleAcl, { tenantId, deletedAt: null } as any, {})\n const list = Array.isArray(roleAcls) ? roleAcls : []\n const organizationId = opts?.organizationId ?? null\n\n for (const acl of list) {\n if (!this.roleAclAllowsOrganization(acl, organizationId)) 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 /**\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,0BAA0B;AACnC,SAAS,2BAA2B,mCAAmC;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAQ7C,SAAS,UAAU,OAAkC;AACnD,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;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;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,mBACJ,QACA,OACmB;AACnB,UAAM,MAAM,MAAM,KAAK,QAAQ,QAAQ,KAAK;AAC5C,QAAI,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;",
6
- "names": ["result", "em", "tenantId", "roleIds", "isSuper", "features", "organizations"]
4
+ "sourcesContent": ["import type { EntityManager } 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 { 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\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\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 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 await this.cache.set(cacheKey, data, {\n ttl: this.cacheTtlMs,\n tags\n })\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 * 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 /**\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,0BAA0B;AAEnC,SAAS,2BAA2B,mCAAmC;AACvE;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,8BAA8B,iCAAiC;AAQxE,SAAS,UAAU,OAAkC;AACnD,MAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;AACxD,QAAM,SAAS;AACf,MAAI,OAAO,OAAO,iBAAiB,UAAW,QAAO;AACrD,MAAI,CAAC,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,KAAK,CAAC,YAAY,OAAO,YAAY,QAAQ,EAAG,QAAO;AAC9G,MAAI,OAAO,kBAAkB,QAAQ,OAAO,kBAAkB,QAAW;AACvE,QAAI,CAAC,MAAM,QAAQ,OAAO,aAAa,EAAG,QAAO;AACjD,QAAI,OAAO,cAAc,KAAK,CAAC,QAAQ,OAAO,QAAQ,QAAQ,EAAG,QAAO;AAAA,EAC1E;AACA,SAAO;AACT;AAEA,SAAS,oBAAoB,KAAkD;AAC7E,SAAO,MAAM,QAAQ,IAAI,iBAAiB,KACrC,IAAI,kBAAkB,SAAS,KAC/B,CAAC,IAAI,kBAAkB,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Q,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
+ "names": ["result", "em", "tenantId", "roleIds", "isSuper", "features", "hasApplicableRestrictedRole", "organizations"]
7
7
  }
@@ -0,0 +1,41 @@
1
+ function normalizeId(value) {
2
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
3
+ }
4
+ async function resolveRoleOrganizationScope(hierarchyService, tenantId, organizationId) {
5
+ const selectedId = normalizeId(organizationId);
6
+ if (!selectedId) return null;
7
+ const normalizedTenantId = normalizeId(tenantId);
8
+ if (!normalizedTenantId) return /* @__PURE__ */ new Set();
9
+ const ids = /* @__PURE__ */ new Set([selectedId]);
10
+ if (!hierarchyService) return ids;
11
+ const ancestorIds = await hierarchyService.resolveAncestorIds({
12
+ tenantId: normalizedTenantId,
13
+ organizationId: selectedId
14
+ });
15
+ if (ancestorIds === null) return /* @__PURE__ */ new Set();
16
+ for (const ancestorId of ancestorIds) {
17
+ const normalized = normalizeId(ancestorId);
18
+ if (normalized) ids.add(normalized);
19
+ }
20
+ return ids;
21
+ }
22
+ function roleAclAllowsOrganization(acl, scope) {
23
+ if (!scope) return true;
24
+ const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null;
25
+ if (!organizations || organizations.length === 0 || organizations.includes("__all__")) return true;
26
+ return organizations.some((organizationId) => scope.has(organizationId));
27
+ }
28
+ function roleAclGrantsPrincipalOrganization(acl, scope) {
29
+ if (!scope) return true;
30
+ const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null;
31
+ if (!organizations) return true;
32
+ if (organizations.length === 0) return false;
33
+ if (organizations.includes("__all__")) return true;
34
+ return organizations.some((organizationId) => scope.has(organizationId));
35
+ }
36
+ export {
37
+ resolveRoleOrganizationScope,
38
+ roleAclAllowsOrganization,
39
+ roleAclGrantsPrincipalOrganization
40
+ };
41
+ //# sourceMappingURL=roleOrganizationScope.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/auth/services/roleOrganizationScope.ts"],
4
+ "sourcesContent": ["import type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport type { RoleAcl } from '../data/entities'\n\nexport type RoleOrganizationScope = ReadonlySet<string> | null\n\nfunction normalizeId(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null\n}\n\nexport async function resolveRoleOrganizationScope(\n hierarchyService: OrganizationHierarchyService | null | undefined,\n tenantId: string | null | undefined,\n organizationId: string | null | undefined,\n): Promise<RoleOrganizationScope> {\n const selectedId = normalizeId(organizationId)\n if (!selectedId) return null\n const normalizedTenantId = normalizeId(tenantId)\n if (!normalizedTenantId) return new Set()\n\n const ids = new Set<string>([selectedId])\n // Auth remains independently usable when Directory is disabled: exact-org\n // grants still apply, while parent-to-descendant expansion fails closed.\n if (!hierarchyService) return ids\n\n const ancestorIds = await hierarchyService.resolveAncestorIds({\n tenantId: normalizedTenantId,\n organizationId: selectedId,\n })\n // A registered Directory seam can prove an invalid/wrong-tenant selection.\n // Fail closed for restricted roles in that case.\n if (ancestorIds === null) return new Set()\n for (const ancestorId of ancestorIds) {\n const normalized = normalizeId(ancestorId)\n if (normalized) ids.add(normalized)\n }\n return ids\n}\n\nexport function roleAclAllowsOrganization(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n scope: RoleOrganizationScope,\n): boolean {\n if (!scope) return true\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations || organizations.length === 0 || organizations.includes('__all__')) return true\n return organizations.some((organizationId) => scope.has(organizationId))\n}\n\n/**\n * Principal eligibility \u2014 which roles may be selected as, or resolved into, an explicit share\n * target \u2014 follows the human-principal deny-all contract instead: an empty allowlist grants no\n * organization reach, so such a role must not become a share principal here (#4033).\n *\n * This deliberately differs from `roleAclAllowsOrganization` above, which governs *feature*\n * evaluation and keeps the wider \"an empty list applies everywhere\" meaning, and from the\n * API-key projection, where an empty list means \"inherit the key's own organization binding\".\n * Without this split a user who reaches an organization through a second role could inherit\n * viewer/editor access from a share assigned to a deny-all role.\n */\nexport function roleAclGrantsPrincipalOrganization(\n acl: Pick<RoleAcl, 'organizationsJson'>,\n scope: RoleOrganizationScope,\n): boolean {\n if (!scope) return true\n const organizations = Array.isArray(acl.organizationsJson) ? acl.organizationsJson : null\n if (!organizations) return true\n if (organizations.length === 0) return false\n if (organizations.includes('__all__')) return true\n return organizations.some((organizationId) => scope.has(organizationId))\n}\n"],
5
+ "mappings": "AAKA,SAAS,YAAY,OAA+B;AAClD,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,eAAsB,6BACpB,kBACA,UACA,gBACgC;AAChC,QAAM,aAAa,YAAY,cAAc;AAC7C,MAAI,CAAC,WAAY,QAAO;AACxB,QAAM,qBAAqB,YAAY,QAAQ;AAC/C,MAAI,CAAC,mBAAoB,QAAO,oBAAI,IAAI;AAExC,QAAM,MAAM,oBAAI,IAAY,CAAC,UAAU,CAAC;AAGxC,MAAI,CAAC,iBAAkB,QAAO;AAE9B,QAAM,cAAc,MAAM,iBAAiB,mBAAmB;AAAA,IAC5D,UAAU;AAAA,IACV,gBAAgB;AAAA,EAClB,CAAC;AAGD,MAAI,gBAAgB,KAAM,QAAO,oBAAI,IAAI;AACzC,aAAW,cAAc,aAAa;AACpC,UAAM,aAAa,YAAY,UAAU;AACzC,QAAI,WAAY,KAAI,IAAI,UAAU;AAAA,EACpC;AACA,SAAO;AACT;AAEO,SAAS,0BACd,KACA,OACS;AACT,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,gBAAgB,MAAM,QAAQ,IAAI,iBAAiB,IAAI,IAAI,oBAAoB;AACrF,MAAI,CAAC,iBAAiB,cAAc,WAAW,KAAK,cAAc,SAAS,SAAS,EAAG,QAAO;AAC9F,SAAO,cAAc,KAAK,CAAC,mBAAmB,MAAM,IAAI,cAAc,CAAC;AACzE;AAaO,SAAS,mCACd,KACA,OACS;AACT,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,gBAAgB,MAAM,QAAQ,IAAI,iBAAiB,IAAI,IAAI,oBAAoB;AACrF,MAAI,CAAC,cAAe,QAAO;AAC3B,MAAI,cAAc,WAAW,EAAG,QAAO;AACvC,MAAI,cAAc,SAAS,SAAS,EAAG,QAAO;AAC9C,SAAO,cAAc,KAAK,CAAC,mBAAmB,MAAM,IAAI,cAAc,CAAC;AACzE;",
6
+ "names": []
7
+ }
@@ -1,4 +1,13 @@
1
+ import { asClass, asFunction } from "awilix";
2
+ import { DefaultOrganizationScopeService } from "./services/organizationScopeService.js";
3
+ import { DefaultOrganizationHierarchyService } from "./services/organizationHierarchyService.js";
1
4
  function register(container) {
5
+ container.register({
6
+ organizationHierarchyService: asClass(DefaultOrganizationHierarchyService).scoped(),
7
+ organizationScopeService: asFunction(
8
+ (cradle) => new DefaultOrganizationScopeService(cradle.em, cradle.rbacService, container)
9
+ ).scoped().proxy()
10
+ });
2
11
  }
3
12
  export {
4
13
  register