@jmruthers/pace-core 0.5.184 → 0.5.186

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 (319) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +60 -1
  3. package/core-usage-manifest.json +312 -0
  4. package/dist/{DataTable-QAB34V6K.js → DataTable-IX2NBUTP.js} +6 -6
  5. package/dist/{DataTable-Bz8ffqyA.d.ts → DataTable-Z9NLVJh0.d.ts} +1 -1
  6. package/dist/{index-Bl--n7-T.d.ts → PublicPageProvider-DIzEzwKl.d.ts} +23 -10
  7. package/dist/{UnifiedAuthProvider-7F6T4B6K.js → UnifiedAuthProvider-A4BCQRJY.js} +4 -2
  8. package/dist/{UnifiedAuthProvider-F86d7dSi.d.ts → UnifiedAuthProvider-BG0AL5eE.d.ts} +2 -1
  9. package/dist/{api-ROMBCNKU.js → api-BMFCXVQX.js} +2 -2
  10. package/dist/{chunk-RA3JUFMW.js → chunk-445GEP27.js} +154 -4
  11. package/dist/{chunk-RA3JUFMW.js.map → chunk-445GEP27.js.map} +1 -1
  12. package/dist/{chunk-W22JP75J.js → chunk-DAGICKHT.js} +9 -7
  13. package/dist/chunk-DAGICKHT.js.map +1 -0
  14. package/dist/{chunk-FUEYYMX5.js → chunk-FXFJRTKI.js} +24 -3
  15. package/dist/chunk-FXFJRTKI.js.map +1 -0
  16. package/dist/{chunk-CSOFYHAG.js → chunk-GRIQLQ52.js} +374 -60
  17. package/dist/chunk-GRIQLQ52.js.map +1 -0
  18. package/dist/{chunk-NQPMQGS2.js → chunk-HDCUMOOI.js} +497 -399
  19. package/dist/chunk-HDCUMOOI.js.map +1 -0
  20. package/dist/chunk-HESYZWZW.js +388 -0
  21. package/dist/chunk-HESYZWZW.js.map +1 -0
  22. package/dist/{chunk-QUVSNGIP.js → chunk-HGPQUCBC.js} +34 -9
  23. package/dist/{chunk-QUVSNGIP.js.map → chunk-HGPQUCBC.js.map} +1 -1
  24. package/dist/{chunk-PWAHJW4G.js → chunk-OALXJH4Y.js} +86 -33
  25. package/dist/chunk-OALXJH4Y.js.map +1 -0
  26. package/dist/{chunk-MI7HBHN3.js → chunk-TC7D3CR3.js} +89 -9
  27. package/dist/chunk-TC7D3CR3.js.map +1 -0
  28. package/dist/chunk-THRPYOFK.js +215 -0
  29. package/dist/chunk-THRPYOFK.js.map +1 -0
  30. package/dist/{chunk-M7W4CP3M.js → chunk-U6WNSFX5.js} +2 -1
  31. package/dist/chunk-U6WNSFX5.js.map +1 -0
  32. package/dist/{chunk-UHNYIBXL.js → chunk-UQWSHFVX.js} +1 -1
  33. package/dist/chunk-UQWSHFVX.js.map +1 -0
  34. package/dist/{chunk-QCDXODCA.js → chunk-XAUHJD3L.js} +2 -2
  35. package/dist/components.d.ts +182 -6
  36. package/dist/components.js +157 -11
  37. package/dist/components.js.map +1 -1
  38. package/dist/{database.generated-CBmg2950.d.ts → database.generated-DI89OQeI.d.ts} +63 -9
  39. package/dist/eslint-rules/pace-core-compliance.cjs +406 -0
  40. package/dist/{file-reference-D06mEEWW.d.ts → file-reference-PRTSLxKx.d.ts} +10 -1
  41. package/dist/hooks.d.ts +52 -15
  42. package/dist/hooks.js +12 -22
  43. package/dist/hooks.js.map +1 -1
  44. package/dist/index.d.ts +12 -12
  45. package/dist/index.js +82 -18
  46. package/dist/index.js.map +1 -1
  47. package/dist/providers.d.ts +1 -1
  48. package/dist/providers.js +3 -1
  49. package/dist/rbac/index.d.ts +206 -15
  50. package/dist/rbac/index.js +28 -6
  51. package/dist/timezone-_pgH8qrY.d.ts +530 -0
  52. package/dist/{types-_x1f4QBF.d.ts → types-DUyCRSTj.d.ts} +1 -1
  53. package/dist/types.d.ts +2 -2
  54. package/dist/types.js +1 -1
  55. package/dist/{usePublicRouteParams-JJczomYq.d.ts → usePublicRouteParams-D71QLlg4.d.ts} +114 -3
  56. package/dist/utils.d.ts +110 -152
  57. package/dist/utils.js +128 -138
  58. package/dist/utils.js.map +1 -1
  59. package/docs/api/README.md +60 -1
  60. package/docs/api/classes/ColumnFactory.md +1 -1
  61. package/docs/api/classes/ErrorBoundary.md +1 -1
  62. package/docs/api/classes/InvalidScopeError.md +1 -1
  63. package/docs/api/classes/Logger.md +178 -0
  64. package/docs/api/classes/MissingUserContextError.md +1 -1
  65. package/docs/api/classes/OrganisationContextRequiredError.md +1 -1
  66. package/docs/api/classes/PermissionDeniedError.md +1 -1
  67. package/docs/api/classes/RBACAuditManager.md +2 -2
  68. package/docs/api/classes/RBACCache.md +1 -1
  69. package/docs/api/classes/RBACEngine.md +2 -2
  70. package/docs/api/classes/RBACError.md +1 -1
  71. package/docs/api/classes/RBACNotInitializedError.md +1 -1
  72. package/docs/api/classes/SecureSupabaseClient.md +5 -5
  73. package/docs/api/classes/StorageUtils.md +1 -1
  74. package/docs/api/enums/FileCategory.md +1 -1
  75. package/docs/api/enums/LogLevel.md +54 -0
  76. package/docs/api/enums/RBACErrorCode.md +1 -1
  77. package/docs/api/enums/RPCFunction.md +1 -1
  78. package/docs/api/interfaces/AggregateConfig.md +1 -1
  79. package/docs/api/interfaces/BadgeProps.md +1 -1
  80. package/docs/api/interfaces/ButtonProps.md +1 -1
  81. package/docs/api/interfaces/CalendarProps.md +18 -2
  82. package/docs/api/interfaces/CardProps.md +1 -1
  83. package/docs/api/interfaces/ColorPalette.md +1 -1
  84. package/docs/api/interfaces/ColorShade.md +1 -1
  85. package/docs/api/interfaces/ComplianceResult.md +30 -0
  86. package/docs/api/interfaces/DataAccessRecord.md +1 -1
  87. package/docs/api/interfaces/DataRecord.md +1 -1
  88. package/docs/api/interfaces/DataTableAction.md +1 -1
  89. package/docs/api/interfaces/DataTableColumn.md +1 -1
  90. package/docs/api/interfaces/DataTableProps.md +1 -1
  91. package/docs/api/interfaces/DataTableToolbarButton.md +1 -1
  92. package/docs/api/interfaces/DatabaseComplianceResult.md +85 -0
  93. package/docs/api/interfaces/DatabaseIssue.md +41 -0
  94. package/docs/api/interfaces/EmptyStateConfig.md +1 -1
  95. package/docs/api/interfaces/EnhancedNavigationMenuProps.md +1 -1
  96. package/docs/api/interfaces/EventAppRoleData.md +6 -6
  97. package/docs/api/interfaces/ExportColumn.md +1 -1
  98. package/docs/api/interfaces/ExportOptions.md +1 -1
  99. package/docs/api/interfaces/FileDisplayProps.md +1 -1
  100. package/docs/api/interfaces/FileMetadata.md +1 -1
  101. package/docs/api/interfaces/FileReference.md +1 -1
  102. package/docs/api/interfaces/FileSizeLimits.md +1 -1
  103. package/docs/api/interfaces/FileUploadOptions.md +48 -8
  104. package/docs/api/interfaces/FileUploadProps.md +46 -13
  105. package/docs/api/interfaces/FooterProps.md +1 -1
  106. package/docs/api/interfaces/FormFieldProps.md +1 -1
  107. package/docs/api/interfaces/FormProps.md +1 -1
  108. package/docs/api/interfaces/GrantEventAppRoleParams.md +9 -9
  109. package/docs/api/interfaces/InactivityWarningModalProps.md +1 -1
  110. package/docs/api/interfaces/InputProps.md +1 -1
  111. package/docs/api/interfaces/LabelProps.md +1 -1
  112. package/docs/api/interfaces/LoggerConfig.md +62 -0
  113. package/docs/api/interfaces/LoginFormProps.md +1 -1
  114. package/docs/api/interfaces/NavigationAccessRecord.md +1 -1
  115. package/docs/api/interfaces/NavigationContextType.md +1 -1
  116. package/docs/api/interfaces/NavigationGuardProps.md +1 -1
  117. package/docs/api/interfaces/NavigationItem.md +1 -1
  118. package/docs/api/interfaces/NavigationMenuProps.md +1 -1
  119. package/docs/api/interfaces/NavigationProviderProps.md +1 -1
  120. package/docs/api/interfaces/Organisation.md +1 -1
  121. package/docs/api/interfaces/OrganisationContextType.md +1 -1
  122. package/docs/api/interfaces/OrganisationMembership.md +1 -1
  123. package/docs/api/interfaces/OrganisationProviderProps.md +1 -1
  124. package/docs/api/interfaces/OrganisationSecurityError.md +1 -1
  125. package/docs/api/interfaces/PaceAppLayoutProps.md +36 -23
  126. package/docs/api/interfaces/PaceLoginPageProps.md +1 -1
  127. package/docs/api/interfaces/PageAccessRecord.md +1 -1
  128. package/docs/api/interfaces/PagePermissionContextType.md +1 -1
  129. package/docs/api/interfaces/PagePermissionGuardProps.md +11 -11
  130. package/docs/api/interfaces/PagePermissionProviderProps.md +1 -1
  131. package/docs/api/interfaces/PaletteData.md +1 -1
  132. package/docs/api/interfaces/PermissionEnforcerProps.md +1 -1
  133. package/docs/api/interfaces/ProgressProps.md +1 -1
  134. package/docs/api/interfaces/ProtectedRouteProps.md +6 -6
  135. package/docs/api/interfaces/PublicPageFooterProps.md +1 -1
  136. package/docs/api/interfaces/PublicPageHeaderProps.md +1 -1
  137. package/docs/api/interfaces/PublicPageLayoutProps.md +1 -1
  138. package/docs/api/interfaces/QuickFix.md +52 -0
  139. package/docs/api/interfaces/RBACAccessValidateParams.md +1 -1
  140. package/docs/api/interfaces/RBACAccessValidateResult.md +1 -1
  141. package/docs/api/interfaces/RBACAuditLogParams.md +1 -1
  142. package/docs/api/interfaces/RBACAuditLogResult.md +1 -1
  143. package/docs/api/interfaces/RBACConfig.md +4 -4
  144. package/docs/api/interfaces/RBACContext.md +1 -1
  145. package/docs/api/interfaces/RBACLogger.md +1 -1
  146. package/docs/api/interfaces/RBACPageAccessCheckParams.md +1 -1
  147. package/docs/api/interfaces/RBACPermissionCheckParams.md +1 -1
  148. package/docs/api/interfaces/RBACPermissionCheckResult.md +1 -1
  149. package/docs/api/interfaces/RBACPermissionsGetParams.md +1 -1
  150. package/docs/api/interfaces/RBACPermissionsGetResult.md +1 -1
  151. package/docs/api/interfaces/RBACResult.md +1 -1
  152. package/docs/api/interfaces/RBACRoleGrantParams.md +1 -1
  153. package/docs/api/interfaces/RBACRoleGrantResult.md +1 -1
  154. package/docs/api/interfaces/RBACRoleRevokeParams.md +1 -1
  155. package/docs/api/interfaces/RBACRoleRevokeResult.md +1 -1
  156. package/docs/api/interfaces/RBACRoleValidateParams.md +1 -1
  157. package/docs/api/interfaces/RBACRoleValidateResult.md +1 -1
  158. package/docs/api/interfaces/RBACRolesListParams.md +1 -1
  159. package/docs/api/interfaces/RBACRolesListResult.md +1 -1
  160. package/docs/api/interfaces/RBACSessionTrackParams.md +1 -1
  161. package/docs/api/interfaces/RBACSessionTrackResult.md +1 -1
  162. package/docs/api/interfaces/ResourcePermissions.md +1 -1
  163. package/docs/api/interfaces/RevokeEventAppRoleParams.md +7 -7
  164. package/docs/api/interfaces/RoleBasedRouterContextType.md +1 -1
  165. package/docs/api/interfaces/RoleBasedRouterProps.md +1 -1
  166. package/docs/api/interfaces/RoleManagementResult.md +5 -5
  167. package/docs/api/interfaces/RouteAccessRecord.md +1 -1
  168. package/docs/api/interfaces/RouteConfig.md +1 -1
  169. package/docs/api/interfaces/RuntimeComplianceResult.md +55 -0
  170. package/docs/api/interfaces/SecureDataContextType.md +1 -1
  171. package/docs/api/interfaces/SecureDataProviderProps.md +1 -1
  172. package/docs/api/interfaces/SessionRestorationLoaderProps.md +1 -1
  173. package/docs/api/interfaces/SetupIssue.md +41 -0
  174. package/docs/api/interfaces/StorageConfig.md +1 -1
  175. package/docs/api/interfaces/StorageFileInfo.md +1 -1
  176. package/docs/api/interfaces/StorageFileMetadata.md +1 -1
  177. package/docs/api/interfaces/StorageListOptions.md +1 -1
  178. package/docs/api/interfaces/StorageListResult.md +1 -1
  179. package/docs/api/interfaces/StorageUploadOptions.md +1 -1
  180. package/docs/api/interfaces/StorageUploadResult.md +1 -1
  181. package/docs/api/interfaces/StorageUrlOptions.md +1 -1
  182. package/docs/api/interfaces/StyleImport.md +1 -1
  183. package/docs/api/interfaces/SwitchProps.md +1 -1
  184. package/docs/api/interfaces/TabsContentProps.md +1 -1
  185. package/docs/api/interfaces/TabsListProps.md +1 -1
  186. package/docs/api/interfaces/TabsProps.md +1 -1
  187. package/docs/api/interfaces/TabsTriggerProps.md +1 -1
  188. package/docs/api/interfaces/TextareaProps.md +1 -1
  189. package/docs/api/interfaces/ToastActionElement.md +1 -1
  190. package/docs/api/interfaces/ToastProps.md +1 -1
  191. package/docs/api/interfaces/UnifiedAuthContextType.md +1 -1
  192. package/docs/api/interfaces/UnifiedAuthProviderProps.md +1 -1
  193. package/docs/api/interfaces/UseFormDialogOptions.md +62 -0
  194. package/docs/api/interfaces/UseFormDialogReturn.md +117 -0
  195. package/docs/api/interfaces/UseInactivityTrackerOptions.md +1 -1
  196. package/docs/api/interfaces/UseInactivityTrackerReturn.md +1 -1
  197. package/docs/api/interfaces/UsePublicEventLogoOptions.md +2 -2
  198. package/docs/api/interfaces/UsePublicEventLogoReturn.md +1 -1
  199. package/docs/api/interfaces/UsePublicEventOptions.md +1 -1
  200. package/docs/api/interfaces/UsePublicEventReturn.md +1 -1
  201. package/docs/api/interfaces/UsePublicFileDisplayOptions.md +2 -2
  202. package/docs/api/interfaces/UsePublicFileDisplayReturn.md +1 -1
  203. package/docs/api/interfaces/UsePublicRouteParamsReturn.md +1 -1
  204. package/docs/api/interfaces/UseResolvedScopeOptions.md +2 -2
  205. package/docs/api/interfaces/UseResolvedScopeReturn.md +1 -1
  206. package/docs/api/interfaces/UseResourcePermissionsOptions.md +1 -1
  207. package/docs/api/interfaces/UserEventAccess.md +1 -1
  208. package/docs/api/interfaces/UserMenuProps.md +1 -1
  209. package/docs/api/interfaces/UserProfile.md +1 -1
  210. package/docs/api/modules.md +746 -50
  211. package/docs/api-reference/components.md +26 -12
  212. package/docs/api-reference/hooks.md +111 -0
  213. package/docs/api-reference/rpc-functions.md +1 -1
  214. package/docs/api-reference/utilities.md +184 -0
  215. package/docs/getting-started/installation-guide.md +75 -16
  216. package/docs/getting-started/quick-start.md +61 -11
  217. package/docs/implementation-guides/authentication.md +88 -12
  218. package/docs/implementation-guides/file-reference-system.md +26 -3
  219. package/docs/implementation-guides/file-upload-storage.md +30 -1
  220. package/docs/rbac/README.md +1 -0
  221. package/docs/rbac/compliance/compliance-guide.md +544 -0
  222. package/docs/rbac/getting-started.md +158 -33
  223. package/docs/standards/pace-core-compliance.md +432 -0
  224. package/eslint-config-pace-core.cjs +93 -0
  225. package/package.json +15 -3
  226. package/scripts/analyze-bundle.js +232 -0
  227. package/scripts/build-css.js +56 -0
  228. package/scripts/build-docs-incremental.js +1015 -0
  229. package/scripts/check-pace-core-compliance.cjs +2353 -0
  230. package/scripts/check-pace-core-compliance.js +512 -0
  231. package/scripts/generate-docs.js +157 -0
  232. package/scripts/setup-build-cache.js +73 -0
  233. package/scripts/utils/command-runner.js +131 -0
  234. package/scripts/utils/env.js +33 -0
  235. package/scripts/utils/index.js +10 -0
  236. package/scripts/utils/logger.js +88 -0
  237. package/scripts/utils/path-helpers.js +37 -0
  238. package/scripts/validate-formats.js +133 -0
  239. package/scripts/validate-master.js +155 -0
  240. package/scripts/validate-pre-publish.js +140 -0
  241. package/scripts/validate-theme.js +142 -0
  242. package/src/components/Calendar/Calendar.tsx +8 -1
  243. package/src/components/Card/Card.tsx +47 -8
  244. package/src/components/DatePickerWithTimezone/DatePickerWithTimezone.test.tsx +314 -0
  245. package/src/components/DatePickerWithTimezone/DatePickerWithTimezone.tsx +126 -0
  246. package/src/components/DatePickerWithTimezone/README.md +135 -0
  247. package/src/components/DatePickerWithTimezone/index.ts +10 -0
  248. package/src/components/DateTimeField/DateTimeField.test.tsx +358 -0
  249. package/src/components/DateTimeField/DateTimeField.tsx +232 -0
  250. package/src/components/DateTimeField/README.md +148 -0
  251. package/src/components/DateTimeField/index.ts +10 -0
  252. package/src/components/FileUpload/FileUpload.test.tsx +2 -0
  253. package/src/components/FileUpload/FileUpload.tsx +10 -1
  254. package/src/components/Header/Header.test.tsx +47 -18
  255. package/src/components/Header/Header.tsx +22 -7
  256. package/src/components/PaceAppLayout/PaceAppLayout.tsx +29 -20
  257. package/src/components/PaceAppLayout/README.md +9 -0
  258. package/src/components/ProtectedRoute/ProtectedRoute.test.tsx +37 -8
  259. package/src/components/ProtectedRoute/ProtectedRoute.tsx +146 -5
  260. package/src/components/index.ts +8 -0
  261. package/src/eslint-rules/pace-core-compliance.cjs +406 -0
  262. package/src/eslint-rules/pace-core-compliance.js +640 -0
  263. package/src/hooks/__tests__/useFormDialog.test.ts +478 -0
  264. package/src/hooks/index.ts +5 -0
  265. package/src/hooks/useFileReference.test.ts +2 -0
  266. package/src/hooks/useFormDialog.ts +147 -0
  267. package/src/hooks/usePreventTabReload.ts +106 -0
  268. package/src/hooks/useSecureDataAccess.ts +2 -2
  269. package/src/index.ts +27 -0
  270. package/src/providers/services/OrganisationServiceProvider.tsx +6 -5
  271. package/src/providers/services/UnifiedAuthProvider.tsx +24 -3
  272. package/src/rbac/__tests__/rbac-role-isolation.test.ts +456 -0
  273. package/src/rbac/__tests__/scenarios.user-role.test.tsx +3 -0
  274. package/src/rbac/compliance/database-validator.ts +165 -0
  275. package/src/rbac/compliance/index.ts +38 -0
  276. package/src/rbac/compliance/quick-fix-suggestions.ts +209 -0
  277. package/src/rbac/compliance/runtime-compliance.ts +77 -0
  278. package/src/rbac/compliance/setup-validator.ts +131 -0
  279. package/src/rbac/components/PagePermissionGuard.tsx +8 -64
  280. package/src/rbac/components/__tests__/PagePermissionGuard.test.tsx +35 -21
  281. package/src/rbac/docs/event-based-apps.md +285 -0
  282. package/src/rbac/errors.ts +11 -0
  283. package/src/rbac/hooks/useRoleManagement.ts +292 -12
  284. package/src/rbac/index.ts +30 -0
  285. package/src/services/OrganisationService.ts +4 -0
  286. package/src/styles/core.css +5 -5
  287. package/src/types/database.generated.ts +63 -9
  288. package/src/types/file-reference.ts +9 -0
  289. package/src/utils/__tests__/timezone.test.ts +345 -0
  290. package/src/utils/file-reference/__tests__/file-reference.test.ts +60 -4
  291. package/src/utils/file-reference/index.ts +13 -2
  292. package/src/utils/formatting/formatDateTimeTimezone.test.ts +167 -0
  293. package/src/utils/formatting/formatting.ts +179 -0
  294. package/src/utils/index.ts +27 -1
  295. package/src/utils/location/index.ts +16 -0
  296. package/src/utils/location/location.test.ts +286 -0
  297. package/src/utils/location/location.ts +175 -0
  298. package/src/utils/security/secureDataAccess.ts +1 -1
  299. package/src/utils/storage/helpers.ts +68 -0
  300. package/src/utils/timezone/index.ts +17 -0
  301. package/src/utils/timezone/timezone.test.ts +349 -0
  302. package/src/utils/timezone/timezone.ts +281 -0
  303. package/dist/chunk-CSOFYHAG.js.map +0 -1
  304. package/dist/chunk-FUEYYMX5.js.map +0 -1
  305. package/dist/chunk-HKIT6O7W.js +0 -198
  306. package/dist/chunk-HKIT6O7W.js.map +0 -1
  307. package/dist/chunk-KUEN3HFB.js +0 -94
  308. package/dist/chunk-KUEN3HFB.js.map +0 -1
  309. package/dist/chunk-M7W4CP3M.js.map +0 -1
  310. package/dist/chunk-MI7HBHN3.js.map +0 -1
  311. package/dist/chunk-NQPMQGS2.js.map +0 -1
  312. package/dist/chunk-PWAHJW4G.js.map +0 -1
  313. package/dist/chunk-UHNYIBXL.js.map +0 -1
  314. package/dist/chunk-W22JP75J.js.map +0 -1
  315. package/dist/formatting-5wETwiGF.d.ts +0 -162
  316. /package/dist/{DataTable-QAB34V6K.js.map → DataTable-IX2NBUTP.js.map} +0 -0
  317. /package/dist/{UnifiedAuthProvider-7F6T4B6K.js.map → UnifiedAuthProvider-A4BCQRJY.js.map} +0 -0
  318. /package/dist/{api-ROMBCNKU.js.map → api-BMFCXVQX.js.map} +0 -0
  319. /package/dist/{chunk-QCDXODCA.js.map → chunk-XAUHJD3L.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rbac/types/functions.ts","../src/rbac/components/PagePermissionProvider.tsx","../src/rbac/components/PagePermissionGuard.tsx","../src/rbac/components/SecureDataProvider.tsx","../src/rbac/components/PermissionEnforcer.tsx","../src/rbac/components/RoleBasedRouter.tsx","../src/rbac/components/NavigationProvider.tsx","../src/rbac/components/NavigationGuard.tsx","../src/rbac/components/EnhancedNavigationMenu.tsx","../src/rbac/adapters.tsx","../src/rbac/permissions.ts","../src/rbac/compliance/setup-validator.ts","../src/rbac/compliance/runtime-compliance.ts","../src/rbac/compliance/database-validator.ts","../src/rbac/compliance/quick-fix-suggestions.ts"],"sourcesContent":["/**\n * @file RBAC Function Types\n * @package @jmruthers/pace-core\n * @module RBAC/Types/Functions\n * @since 1.0.0\n * \n * TypeScript types for standardized RBAC RPC functions.\n * These types define the parameters and return types for database RPC functions.\n */\n\nimport type { UUID, Operation } from '../types';\nimport type { AppId, PageId } from '../../types/core';\n\n// ============================================================================\n// PERMISSION CHECKING FUNCTION TYPES\n// ============================================================================\n\nexport interface RBACPermissionCheckParams {\n p_operation: Operation;\n p_page_name: string;\n p_user_id?: UUID;\n p_organisation_id?: UUID;\n p_event_id?: string;\n p_app_id?: AppId | UUID;\n}\n\nexport interface RBACPermissionCheckResult {\n has_permission: boolean;\n role_name: string | null;\n permission_source: 'global' | 'organisation' | 'event_app' | 'default' | 'none';\n granted_at: string | null;\n}\n\nexport interface RBACPermissionsGetParams {\n p_user_id: UUID; // REQUIRED - no default, must be explicitly provided\n p_organisation_id?: UUID;\n p_event_id?: string;\n p_app_id?: AppId | UUID;\n p_page_id?: PageId | UUID;\n}\n\nexport interface RBACPermissionsGetResult {\n permission_type: string;\n role_name: string;\n has_permission: boolean;\n granted_at: string;\n context_id: string;\n}\n\nexport interface RBACAccessValidateParams {\n p_resource_type: 'organisation' | 'event';\n p_resource_id: string;\n p_user_id?: UUID;\n p_operation?: Operation;\n}\n\nexport interface RBACAccessValidateResult {\n has_access: boolean;\n access_level: AccessLevelContext;\n context_id: string | null;\n}\n\nexport interface RBACPageAccessCheckParams {\n p_app_id: AppId | UUID;\n p_page_id: PageId | UUID;\n p_operation: Operation;\n p_user_id?: UUID;\n p_event_id?: string;\n p_organisation_id?: UUID;\n}\n\n// ============================================================================\n// ROLE MANAGEMENT FUNCTION TYPES\n// ============================================================================\n\nexport interface RBACRoleGrantParams {\n p_user_id: UUID;\n p_role_type: 'global' | 'organisation' | 'event_app';\n p_role_name: string;\n p_context_id?: string;\n p_granted_by?: UUID;\n}\n\nexport interface RBACRoleGrantResult {\n success: boolean;\n message: string;\n role_id: UUID | null;\n error_code: string | null;\n}\n\nexport interface RBACRoleRevokeParams {\n p_user_id: UUID;\n p_role_type: 'global' | 'organisation' | 'event_app';\n p_role_name: string;\n p_context_id?: string;\n p_revoked_by?: UUID;\n}\n\nexport interface RBACRoleRevokeResult {\n success: boolean;\n message: string;\n revoked_count: number;\n error_code: string | null;\n}\n\nexport interface RBACRolesListParams {\n p_user_id?: UUID;\n p_organisation_id?: UUID;\n p_event_id?: string;\n p_app_id?: AppId | UUID;\n}\n\nexport interface RBACRolesListResult {\n role_type: 'global' | 'organisation' | 'event_app';\n role_name: string;\n context_id: string;\n granted_at: string;\n status: 'active' | 'inactive' | 'expired';\n granted_by: UUID | null;\n}\n\nexport interface RBACRoleValidateParams {\n p_user_id: UUID;\n p_role_type: 'global' | 'organisation' | 'event_app';\n p_role_name: string;\n p_context_id?: string;\n}\n\nexport interface RBACRoleValidateResult {\n is_valid: boolean;\n role_id: UUID | null;\n granted_at: string | null;\n expires_at: string | null;\n status: string;\n}\n\n// ============================================================================\n// SESSION & AUDIT FUNCTION TYPES\n// ============================================================================\n\nexport interface RBACSessionTrackParams {\n p_user_id?: UUID;\n p_session_type?: 'web' | 'mobile' | 'api' | 'admin';\n p_event_id?: string;\n p_app_id?: AppId | UUID;\n p_ip_address?: string;\n p_user_agent?: string;\n}\n\nexport interface RBACSessionTrackResult {\n success: boolean;\n session_id: UUID | null;\n message: string;\n error_code: string | null;\n}\n\nexport interface RBACAuditLogParams {\n p_event_type: 'role_granted' | 'role_revoked' | 'permission_checked' | 'access_granted' | 'access_denied' | 'session_started' | 'session_ended' | 'login' | 'logout' | 'organisation_switched' | 'event_switched' | 'app_switched';\n p_user_id?: UUID;\n p_organisation_id?: UUID;\n p_permission?: string;\n p_metadata?: Record<string, unknown>;\n p_ip_address?: string;\n p_user_agent?: string;\n}\n\nexport interface RBACAuditLogResult {\n success: boolean;\n audit_id: UUID | null;\n message: string;\n error_code: string | null;\n}\n\n// ============================================================================\n// RPC FUNCTION NAMES\n// ============================================================================\n\nexport enum RPCFunction {\n // Permission Checking Functions\n RBAC_PERMISSION_CHECK = 'rbac_permission_check',\n RBAC_PERMISSIONS_GET = 'rbac_permissions_get',\n RBAC_ACCESS_VALIDATE = 'rbac_access_validate',\n RBAC_PAGE_ACCESS_CHECK = 'rbac_page_access_check',\n \n // Role Management Functions\n RBAC_ROLE_GRANT = 'rbac_role_grant',\n RBAC_ROLE_REVOKE = 'rbac_role_revoke',\n RBAC_ROLES_LIST = 'rbac_roles_list',\n RBAC_ROLE_VALIDATE = 'rbac_role_validate',\n \n // Session & Audit Functions\n RBAC_SESSION_TRACK = 'rbac_session_track',\n RBAC_AUDIT_LOG = 'rbac_audit_log',\n}\n\n// ============================================================================\n// ERROR CODES\n// ============================================================================\n\nexport enum RBACErrorCode {\n USER_NOT_FOUND = 'USER_NOT_FOUND',\n INVALID_ROLE_TYPE = 'INVALID_ROLE_TYPE',\n INVALID_ROLE_NAME = 'INVALID_ROLE_NAME',\n MISSING_ORGANISATION_ID = 'MISSING_ORGANISATION_ID',\n MISSING_EVENT_APP_CONTEXT = 'MISSING_EVENT_APP_CONTEXT',\n ORGANISATION_NOT_FOUND = 'ORGANISATION_NOT_FOUND',\n EVENT_NOT_FOUND = 'EVENT_NOT_FOUND',\n APP_NOT_FOUND = 'APP_NOT_FOUND',\n INVALID_SESSION_TYPE = 'INVALID_SESSION_TYPE',\n INVALID_EVENT_TYPE = 'INVALID_EVENT_TYPE',\n DATABASE_ERROR = 'DATABASE_ERROR',\n ROLE_NOT_FOUND = 'ROLE_NOT_FOUND',\n USER_NOT_AUTHENTICATED = 'USER_NOT_AUTHENTICATED',\n INVALID_GLOBAL_ROLE = 'INVALID_GLOBAL_ROLE',\n INVALID_ORGANISATION_ROLE = 'INVALID_ORGANISATION_ROLE',\n INVALID_EVENT_APP_ROLE = 'INVALID_EVENT_APP_ROLE',\n INVALID_EVENT_APP_FORMAT = 'INVALID_EVENT_APP_FORMAT',\n MISSING_CONTEXT = 'MISSING_CONTEXT',\n INVALID_CONTEXT = 'INVALID_CONTEXT',\n GRANTED_BY_NOT_FOUND = 'GRANTED_BY_NOT_FOUND',\n}\n\n// ============================================================================\n// PERMISSION TYPES\n// ============================================================================\n\n/**\n * Permission source indicates where a permission was granted from\n */\nexport type PermissionSource = 'global' | 'organisation' | 'event_app' | 'default' | 'none';\n\n/**\n * Access level context for RPC functions (different from RBAC AccessLevel)\n * Indicates the scope/context of access validation\n */\nexport type AccessLevelContext = 'super_admin' | 'organisation' | 'event' | 'none';\n\n// ============================================================================\n// SESSION TYPES\n// ============================================================================\n\nexport type SessionType = 'web' | 'mobile' | 'api' | 'admin';\n\n// ============================================================================\n// AUDIT EVENT TYPES\n// ============================================================================\n\nexport type AuditEventType = \n | 'role_granted' \n | 'role_revoked' \n | 'permission_checked' \n | 'access_granted' \n | 'access_denied' \n | 'session_started' \n | 'session_ended' \n | 'login' \n | 'logout'\n | 'organisation_switched' \n | 'event_switched' \n | 'app_switched';\n\n// ============================================================================\n// UTILITY TYPES\n// ============================================================================\n\nexport interface RBACContext {\n user_id: UUID;\n organisation_id?: UUID;\n event_id?: string;\n app_id?: AppId | UUID;\n}\n\nexport interface RBACResult<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n error_code?: RBACErrorCode;\n}\n\n// ============================================================================\n// FUNCTION RESPONSE TYPES\n// ============================================================================\n\nexport type RBACFunctionResponse<T> = {\n data: T | null;\n error: unknown | null;\n count?: number | null;\n status: number;\n statusText: string;\n};\n\n","/**\n * @file Page Permission Provider Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/PagePermissionProvider\n * @since 2.0.0\n *\n * A context provider that manages page-level permissions across the entire application.\n * This component ensures that all pages are properly protected and provides centralized\n * page permission management.\n *\n * Features:\n * - App-wide page permission management\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Page permission tracking\n * - Error handling and recovery\n *\n * @example\n * ```tsx\n * // Basic app setup with page permissions\n * <PagePermissionProvider strictMode={true} auditLog={true}>\n * <App />\n * </PagePermissionProvider>\n * \n * // With custom configuration\n * <PagePermissionProvider\n * strictMode={true}\n * auditLog={true}\n * onPageAccess={(pageName, operation, allowed) => {\n * console.log(`Page access: ${pageName} ${operation} - ${allowed ? 'allowed' : 'denied'}`);\n * }}\n * >\n * <App />\n * </PagePermissionProvider>\n * ```\n *\n * @security\n * - Enforces page-level permissions across the app\n * - Prevents apps from bypassing permission checks\n * - Automatic audit logging for all page access attempts\n * - Integration with existing RBAC system\n * - Page permission tracking and monitoring\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Efficient context updates\n * - Minimal re-renders\n * - Cached permission checks\n *\n * @dependencies\n * - React 18+ - Context and hooks\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { createContext, useContext, useState, useCallback, useMemo, useEffect } from 'react';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { UUID, Scope, Permission } from '../types';\nimport { createLogger } from '../../utils/core/logger';\n\nconst log = createLogger('PagePermissionProvider');\n\nexport interface PagePermissionContextType {\n /** Check if user has permission for a page */\n hasPagePermission: (pageName: string, operation: string, pageId?: string, scope?: Scope) => boolean;\n \n /** Get all page permissions for current user */\n getPagePermissions: () => Record<string, string[]>;\n \n /** Check if page permission checking is enabled */\n isEnabled: boolean;\n \n /** Check if strict mode is enabled */\n isStrictMode: boolean;\n \n /** Check if audit logging is enabled */\n isAuditLogEnabled: boolean;\n \n /** Get page access history */\n getPageAccessHistory: () => PageAccessRecord[];\n \n /** Clear page access history */\n clearPageAccessHistory: () => void;\n}\n\nexport interface PageAccessRecord {\n pageName: string;\n operation: string;\n userId: UUID;\n scope: Scope;\n allowed: boolean;\n timestamp: string;\n pageId?: string;\n}\n\nexport interface PagePermissionProviderProps {\n /** Child components */\n children: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Enable audit logging (default: true) */\n auditLog?: boolean;\n \n /** Callback when page access is attempted */\n onPageAccess?: (pageName: string, operation: string, allowed: boolean, record: PageAccessRecord) => void;\n \n /** Callback when strict mode violation occurs */\n onStrictModeViolation?: (pageName: string, operation: string, record: PageAccessRecord) => void;\n \n /** Maximum number of access records to keep in history */\n maxHistorySize?: number;\n}\n\nconst PagePermissionContext = createContext<PagePermissionContextType | null>(null);\n\n/**\n * PagePermissionProvider - Manages page-level permissions across the app\n * \n * This provider ensures that all pages are properly protected and provides\n * centralized page permission management with strict enforcement.\n * \n * @param props - Provider props\n * @returns React element with page permission context\n */\nexport function PagePermissionProvider({\n children,\n strictMode = true,\n auditLog = true,\n onPageAccess,\n onStrictModeViolation,\n maxHistorySize = 1000\n}: PagePermissionProviderProps) {\n const { user, selectedOrganisation, selectedEvent } = useUnifiedAuth();\n const [pageAccessHistory, setPageAccessHistory] = useState<PageAccessRecord[]>([]);\n const [isEnabled, setIsEnabled] = useState(true);\n\n // Get current scope\n const currentScope = useMemo((): Scope | null => {\n if (!selectedOrganisation) return null;\n \n return {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n };\n }, [selectedOrganisation, selectedEvent]);\n\n // Check if user has permission for a page\n const hasPagePermission = useCallback((\n pageName: string, \n operation: string, \n pageId?: string, \n scope?: Scope\n ): boolean => {\n if (!isEnabled) return true;\n if (!user?.id) return false;\n \n const effectiveScope = scope || currentScope;\n if (!effectiveScope) return false;\n \n // Use the existing RBAC system to check permissions\n // This is a synchronous check for the context - actual permission checking\n // happens in the PagePermissionGuard component using useCan hook\n const permission = `${operation}:page.${pageName}` as Permission;\n \n // Return false by default (secure by default) - let individual PagePermissionGuard\n // components handle the actual permission checking asynchronously\n // This context is mainly for tracking and audit purposes\n return false;\n }, [isEnabled, user?.id, currentScope]);\n\n // Get all page permissions for current user\n const getPagePermissions = useCallback((): Record<string, string[]> => {\n if (!isEnabled || !user?.id) return {};\n \n // For now, return empty object - this will be enhanced with actual permission checking\n // when we integrate with the existing RBAC system\n return {};\n }, [isEnabled, user?.id]);\n\n // Get page access history\n const getPageAccessHistory = useCallback((): PageAccessRecord[] => {\n return [...pageAccessHistory];\n }, [pageAccessHistory]);\n\n // Clear page access history\n const clearPageAccessHistory = useCallback(() => {\n setPageAccessHistory([]);\n }, []);\n\n // Record page access attempt\n const recordPageAccess = useCallback((\n pageName: string,\n operation: string,\n allowed: boolean,\n pageId?: string,\n scope?: Scope\n ) => {\n if (!auditLog || !user?.id) return;\n \n const record: PageAccessRecord = {\n pageName,\n operation,\n userId: user.id,\n scope: scope || currentScope || { organisationId: '' },\n allowed,\n timestamp: new Date().toISOString(),\n pageId\n };\n \n setPageAccessHistory(prev => {\n const newHistory = [record, ...prev];\n return newHistory.slice(0, maxHistorySize);\n });\n \n if (onPageAccess) {\n onPageAccess(pageName, operation, allowed, record);\n }\n \n if (strictMode && !allowed && onStrictModeViolation) {\n onStrictModeViolation(pageName, operation, record);\n }\n }, [auditLog, user?.id, currentScope, maxHistorySize, onPageAccess, onStrictModeViolation, strictMode]);\n\n // Context value\n const contextValue = useMemo((): PagePermissionContextType => ({\n hasPagePermission,\n getPagePermissions,\n isEnabled,\n isStrictMode: strictMode,\n isAuditLogEnabled: auditLog,\n getPageAccessHistory,\n clearPageAccessHistory\n }), [\n hasPagePermission,\n getPagePermissions,\n isEnabled,\n strictMode,\n auditLog,\n getPageAccessHistory,\n clearPageAccessHistory\n ]);\n\n // Log strict mode violations\n useEffect(() => {\n if (strictMode && auditLog) {\n log.debug('Strict mode enabled - all page access attempts will be logged and enforced');\n }\n }, [strictMode, auditLog]);\n\n return (\n <PagePermissionContext.Provider value={contextValue}>\n {children}\n </PagePermissionContext.Provider>\n );\n}\n\n/**\n * Hook to use page permission context\n * \n * @returns Page permission context\n * @throws Error if used outside of PagePermissionProvider\n */\nexport function usePagePermissions(): PagePermissionContextType {\n const context = useContext(PagePermissionContext);\n \n if (!context) {\n throw new Error('usePagePermissions must be used within a PagePermissionProvider');\n }\n \n return context;\n}\n\nexport default PagePermissionProvider;\n","/**\n * @file Page Permission Guard Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/PagePermissionGuard\n * @since 2.0.0\n *\n * A component that enforces page-level permissions and prevents apps from bypassing\n * permission checks. This is a critical security component that ensures all pages\n * are properly protected.\n *\n * Features:\n * - Page-level permission enforcement\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized access\n * - TypeScript support with strict typing\n *\n * @example\n * ```tsx\n * // Basic page protection\n * <PagePermissionGuard\n * pageName=\"dashboard\"\n * operation=\"read\"\n * fallback={<AccessDeniedPage />}\n * >\n * <DashboardPage />\n * </PagePermissionGuard>\n * \n * // Strict mode (prevents bypassing)\n * <PagePermissionGuard\n * pageName=\"admin\"\n * operation=\"read\"\n * strictMode={true}\n * fallback={<AccessDeniedPage />}\n * >\n * <AdminPage />\n * </PagePermissionGuard>\n * \n * // With custom fallback\n * <PagePermissionGuard\n * pageName=\"settings\"\n * operation=\"update\"\n * fallback={<div>You don't have permission to access settings</div>}\n * >\n * <SettingsPage />\n * </PagePermissionGuard>\n * ```\n *\n * @security\n * - Enforces page-level permissions\n * - Prevents apps from bypassing permission checks\n * - Automatic audit logging for all page access attempts\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized access\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Cached permission checks\n * - Minimal re-renders\n * - Efficient error handling\n *\n * @dependencies\n * - React 18+ - Component framework\n * - useCan hook - Permission checking\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { useMemo, useCallback, useEffect, useState, useRef } from 'react';\nimport { useCan } from '../hooks';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { UUID, Permission, Scope } from '../types';\nimport { createScopeFromEvent } from '../utils/eventContext';\nimport { getRBACLogger } from '../config';\n\nexport interface PagePermissionGuardProps {\n /** Name of the page being protected */\n pageName: string;\n \n /** Operation being performed on the page */\n operation: 'read' | 'create' | 'update' | 'delete';\n \n /** Content to render when user has permission */\n children: React.ReactNode;\n \n /** Content to render when user lacks permission */\n fallback?: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Force audit logging for this page access (default: true) */\n auditLog?: boolean;\n \n /** Custom page ID for permission checking */\n pageId?: string;\n \n /** Custom scope for permission checking */\n scope?: Scope;\n \n /** Callback when access is denied */\n onDenied?: (pageName: string, operation: string) => void;\n \n /** Loading state content */\n loading?: React.ReactNode;\n}\n\n/**\n * PagePermissionGuard - Enforces page-level permissions\n * \n * This component ensures that users can only access pages they have permission for.\n * It integrates with the existing RBAC system and provides strict enforcement to\n * prevent apps from bypassing permission checks.\n * \n * @param props - Component props\n * @returns React element with permission enforcement\n */\nconst PagePermissionGuardComponent = ({\n pageName,\n operation,\n children,\n fallback = <DefaultAccessDenied />,\n strictMode = true,\n auditLog = true,\n pageId,\n scope,\n onDenied,\n loading = <DefaultLoading />\n}: PagePermissionGuardProps) => {\n // Track render count for debugging\n const renderCountRef = useRef(0);\n renderCountRef.current += 1;\n \n // Generate a unique instance ID for debugging (must be called before any conditional returns)\n const instanceId = useMemo(() => Math.random().toString(36).substr(2, 9), []);\n \n // Use UnifiedAuth hook - if context is not available, it will throw and ErrorBoundary will handle it\n // This is better than checking for context and returning early, which causes infinite loops\n const { user, selectedOrganisation, selectedEvent, supabase, appId: contextAppId } = useUnifiedAuth();\n \n const [hasChecked, setHasChecked] = useState(false);\n const [checkError, setCheckError] = useState<Error | null>(null);\n const [resolvedScope, setResolvedScope] = useState<Scope | null>(null);\n const scopeResolutionAbortRef = useRef<AbortController | null>(null);\n \n // Use ref to avoid infinite re-renders from supabase dependency\n const supabaseRef = useRef(supabase);\n supabaseRef.current = supabase;\n \n // Resolve scope - either use provided scope or resolve from context\n useEffect(() => {\n const abortController = new AbortController();\n scopeResolutionAbortRef.current?.abort();\n scopeResolutionAbortRef.current = abortController;\n const { signal } = abortController;\n\n const safeSetResolvedScope = (value: Scope | null) => {\n if (!signal.aborted) {\n setResolvedScope(value);\n }\n };\n\n const safeSetCheckError = (value: Error | null) => {\n if (!signal.aborted) {\n setCheckError(value);\n }\n };\n\n const resolveScope = async () => {\n if (signal.aborted) {\n return;\n }\n\n if (scope) {\n safeSetResolvedScope(scope);\n safeSetCheckError(null);\n return;\n }\n\n // Get app ID from UnifiedAuth context (already resolved on login)\n // This is much faster than querying the database\n const appId = contextAppId;\n\n if (signal.aborted) {\n return;\n }\n\n // If we have both organisation and event, use them directly\n if (selectedOrganisation && selectedEvent) {\n if (!appId) {\n const logger = getRBACLogger();\n if (import.meta.env.MODE === 'test') {\n logger.warn('App ID not resolved in test environment, proceeding without it');\n } else {\n logger.error('CRITICAL: App ID not resolved. Check console for details.');\n safeSetCheckError(new Error('App ID not resolved. Check console for database errors.'));\n safeSetResolvedScope(null);\n return;\n }\n }\n\n if (import.meta.env.MODE === 'production' && appId) {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(appId)) {\n const logger = getRBACLogger();\n logger.error('CRITICAL: App ID is not a valid UUID:', appId);\n safeSetCheckError(new Error(`Invalid app ID format: ${appId}. Expected UUID.`));\n safeSetResolvedScope(null);\n return;\n }\n }\n const resolvedContext = {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent.event_id,\n appId: appId\n };\n safeSetResolvedScope(resolvedContext);\n safeSetCheckError(null);\n return;\n }\n\n if (signal.aborted) {\n return;\n }\n\n // If we only have organisation, use it\n if (selectedOrganisation) {\n if (!appId) {\n const logger = getRBACLogger();\n if (import.meta.env.MODE === 'test') {\n logger.warn('App ID not resolved in test environment, proceeding without it');\n } else {\n logger.error('CRITICAL: App ID not resolved. Check console for details.');\n safeSetCheckError(new Error('App ID not resolved. Check console for database errors.'));\n safeSetResolvedScope(null);\n return;\n }\n }\n\n if (import.meta.env.MODE === 'production' && appId) {\n const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n if (!uuidRegex.test(appId)) {\n const logger = getRBACLogger();\n logger.error('CRITICAL: App ID is not a valid UUID:', appId);\n safeSetCheckError(new Error(`Invalid app ID format: ${appId}. Expected UUID.`));\n safeSetResolvedScope(null);\n return;\n }\n }\n const resolvedContext = {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: appId\n };\n safeSetResolvedScope(resolvedContext);\n safeSetCheckError(null);\n return;\n }\n\n if (signal.aborted) {\n return;\n }\n\n // If we only have event, resolve organisation from event\n if (selectedEvent && supabaseRef.current) {\n try {\n const eventScope = await createScopeFromEvent(supabaseRef.current, selectedEvent.event_id);\n\n if (signal.aborted) {\n return;\n }\n\n if (!eventScope) {\n safeSetCheckError(new Error('Could not resolve organization from event context'));\n safeSetResolvedScope(null);\n return;\n }\n safeSetResolvedScope({\n ...eventScope,\n appId: appId || eventScope.appId\n });\n safeSetCheckError(null);\n } catch (error) {\n if (signal.aborted) {\n return;\n }\n safeSetCheckError(error as Error);\n safeSetResolvedScope(null);\n }\n return;\n }\n\n if (signal.aborted) {\n return;\n }\n\n const errorMessage = !selectedOrganisation && !selectedEvent\n ? 'Either organisation context or event context is required for page permission checking'\n : 'Insufficient context for permission checking. Please ensure you are properly authenticated and have selected an organisation or event.';\n\n const logger = getRBACLogger();\n logger.error('Context resolution failed:', {\n selectedOrganisation: selectedOrganisation ? (selectedOrganisation as any).id : null,\n selectedEvent: selectedEvent ? (selectedEvent as any).event_id : null,\n appId,\n error: errorMessage\n });\n\n safeSetCheckError(new Error(errorMessage));\n safeSetResolvedScope(null);\n };\n\n resolveScope();\n\n return () => {\n abortController.abort();\n if (scopeResolutionAbortRef.current === abortController) {\n scopeResolutionAbortRef.current = null;\n }\n };\n }, [scope, selectedOrganisation, selectedEvent]);\n\n // Determine the page ID for permission checking\n const effectivePageId = useMemo((): string => {\n return pageId || pageName;\n }, [pageId, pageName]);\n\n // Build the permission string\n const permission = useMemo((): Permission => {\n return `${operation}:page.${pageName}` as Permission;\n }, [operation, pageName]);\n\n // Create a stable scope that only includes valid values\n // OrganisationId is required - use undefined if not available, useCan will handle loading state\n const stableScope = useMemo(() => {\n if (resolvedScope && resolvedScope.organisationId) {\n return {\n organisationId: resolvedScope.organisationId,\n appId: resolvedScope.appId || undefined,\n eventId: resolvedScope.eventId || undefined\n };\n }\n // Return scope without organisationId - useCan will keep loading state until resolved\n // Scope.organisationId is optional, so undefined is valid\n return { organisationId: undefined, appId: undefined, eventId: undefined };\n }, [resolvedScope]);\n\n // Check if user has permission - only call useCan when we have a resolved scope with valid organisationId\n // If resolvedScope is null or has no organisationId, useCan will keep isLoading=true\n const { can, isLoading: canIsLoading, error: canError } = useCan(\n user?.id || '',\n stableScope,\n permission,\n effectivePageId,\n true // Use cache\n );\n \n \n // Combine loading states - we're loading if either scope is resolving OR permission check is loading\n const isLoading = !resolvedScope || canIsLoading;\n const error = checkError || canError;\n\n // Handle permission check completion\n useEffect(() => {\n if (!isLoading && !error) {\n setHasChecked(true);\n setCheckError(null); // Clear any previous errors when permission check succeeds\n \n if (!can && onDenied) {\n onDenied(pageName, operation);\n }\n } else if (error) {\n setCheckError(error);\n setHasChecked(true);\n }\n }, [can, isLoading, error, pageName, operation, onDenied]);\n\n // Log page access attempt for audit\n useEffect(() => {\n if (auditLog && hasChecked && !isLoading) {\n const rbacLogger = getRBACLogger();\n rbacLogger.debug('Page access attempt:', {\n pageName,\n operation,\n userId: user?.id,\n scope: resolvedScope,\n allowed: can,\n timestamp: new Date().toISOString()\n });\n }\n }, [auditLog, hasChecked, isLoading, pageName, operation, user?.id, resolvedScope, can]);\n\n\n // Handle strict mode violations\n useEffect(() => {\n if (strictMode && hasChecked && !isLoading && !can) {\n const logger = getRBACLogger();\n logger.error(`STRICT MODE VIOLATION: User attempted to access protected page without permission`, {\n pageName,\n operation,\n permission: `${operation}:page.${pageName}`,\n pageId: effectivePageId,\n userId: user?.id,\n scope: resolvedScope,\n scopeValid: resolvedScope && resolvedScope.organisationId ? true : false,\n checkError,\n canError,\n timestamp: new Date().toISOString()\n });\n }\n }, [strictMode, hasChecked, isLoading, can, pageName, operation, effectivePageId, user?.id, resolvedScope, checkError, canError]);\n\n // Calculate the actual render state - FIXED: Proper state calculation\n // Add defensive checks to ensure we have valid state\n const hasValidScope = resolvedScope && resolvedScope.organisationId;\n const hasValidUser = user && user.id;\n const isPermissionCheckComplete = hasChecked && !isLoading;\n \n const shouldShowAccessDenied = isPermissionCheckComplete && hasValidScope && hasValidUser && !checkError && !can;\n const shouldShowContent = isPermissionCheckComplete && hasValidScope && hasValidUser && !checkError && can;\n\n // Create a key to force re-render when scope or permission state changes\n const scopeKey = resolvedScope ? `${resolvedScope.organisationId}-${resolvedScope.eventId}-${resolvedScope.appId}` : 'no-scope';\n const permissionKey = `${scopeKey}-${can}-${isLoading}-${!!checkError}-${hasChecked}`;\n \n \n\n // Show loading state - if we're still loading or don't have valid state\n if (isLoading || !hasValidScope || !hasValidUser || !hasChecked) {\n return loading || <div>Checking permissions...</div>;\n }\n\n // Show error state - only if we have an error AND no permission\n if (checkError && !can) {\n return fallback;\n }\n\n // Show access denied - if permission check is complete and user doesn't have permission\n if (shouldShowAccessDenied) {\n return fallback;\n }\n\n // Show protected content - if permission check is complete and user has permission\n if (shouldShowContent) {\n return <>{children}</>;\n }\n\n // Fallback: This should never happen, but just in case\n return fallback;\n}\n\n/**\n * Default access denied component\n */\nfunction DefaultAccessDenied() {\n return (\n <div className=\"flex flex-col items-center justify-center min-h-[200px] p-8 text-center\">\n <div className=\"mb-4\">\n <svg className=\"w-16 h-16 text-acc-500 mx-auto\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z\" />\n </svg>\n </div>\n <h2 className=\"text-xl font-semibold text-sec-900 mb-2\">Access Denied</h2>\n <p className=\"text-sec-600 mb-4\">You don't have permission to access this page.</p>\n <button \n onClick={() => window.history.back()}\n className=\"px-4 py-2 bg-main-600 text-main-50 rounded-md hover:bg-main-700 transition-colors\"\n >\n Go Back\n </button>\n </div>\n );\n}\n\n/**\n * Default loading component\n */\nfunction DefaultLoading() {\n return (\n <div className=\"flex items-center justify-center min-h-[200px] p-8\">\n <div className=\"flex items-center space-x-2\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-main-600\"></div>\n <span className=\"text-sec-600\">Checking permissions...</span>\n </div>\n </div>\n );\n};\n\nexport const PagePermissionGuard = PagePermissionGuardComponent;\nexport default PagePermissionGuard;\n","/**\n * @file Secure Data Provider Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/SecureDataProvider\n * @since 2.0.0\n *\n * A context provider that prevents apps from accessing Supabase directly and ensures\n * all data access goes through the secure RBAC system. This is a critical security\n * component that enforces data access control.\n *\n * Features:\n * - Prevents direct Supabase client access\n * - Enforces secure data access patterns\n * - Automatic organisation context injection\n * - RLS policy enforcement\n * - Audit logging for all data access\n * - Integration with existing RBAC system\n *\n * @example\n * ```tsx\n * // Basic app setup with secure data access\n * <SecureDataProvider strictMode={true} auditLog={true}>\n * <App />\n * </SecureDataProvider>\n * \n * // With custom configuration\n * <SecureDataProvider\n * strictMode={true}\n * auditLog={true}\n * onDataAccess={(table, operation, allowed) => {\n * console.log(`Data access: ${table} ${operation} - ${allowed ? 'allowed' : 'denied'}`);\n * }}\n * >\n * <App />\n * </SecureDataProvider>\n * ```\n *\n * @security\n * - Prevents direct Supabase client access\n * - Enforces secure data access patterns\n * - Automatic organisation context injection\n * - RLS policy enforcement\n * - Audit logging for all data access\n * - Integration with existing RBAC system\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Efficient context updates\n * - Minimal re-renders\n * - Cached permission checks\n *\n * @dependencies\n * - React 18+ - Context and hooks\n * - useUnifiedAuth - Authentication context\n * - useSecureDataAccess - Secure data access hook\n * - RBAC types - Type definitions\n */\n\nimport React, { createContext, useContext, useState, useCallback, useMemo, useEffect } from 'react';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { useSecureDataAccess } from '../../hooks/useSecureDataAccess';\nimport { UUID, Scope, Permission } from '../types';\nimport { getRBACLogger } from '../config';\n\nexport interface DataAccessRecord {\n table: string;\n operation: string;\n userId: UUID;\n scope: Scope;\n allowed: boolean;\n timestamp: string;\n query?: string;\n filters?: Record<string, any>;\n}\n\nexport interface SecureDataContextType {\n /** Check if data access is allowed for a table and operation */\n isDataAccessAllowed: (table: string, operation: string, scope?: Scope) => boolean;\n \n /** Get all data access permissions for current user */\n getDataAccessPermissions: () => Record<string, string[]>;\n \n /** Check if secure data access is enabled */\n isEnabled: boolean;\n \n /** Check if strict mode is enabled */\n isStrictMode: boolean;\n \n /** Check if audit logging is enabled */\n isAuditLogEnabled: boolean;\n \n /** Get data access history */\n getDataAccessHistory: () => DataAccessRecord[];\n \n /** Clear data access history */\n clearDataAccessHistory: () => void;\n \n /** Validate data access attempt */\n validateDataAccess: (table: string, operation: string, scope?: Scope) => boolean;\n}\n\nexport interface SecureDataProviderProps {\n /** Child components */\n children: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Enable audit logging (default: true) */\n auditLog?: boolean;\n \n /** Callback when data access is attempted */\n onDataAccess?: (table: string, operation: string, allowed: boolean, record: DataAccessRecord) => void;\n \n /** Callback when strict mode violation occurs */\n onStrictModeViolation?: (table: string, operation: string, record: DataAccessRecord) => void;\n \n /** Maximum number of access records to keep in history */\n maxHistorySize?: number;\n \n /** Enable RLS enforcement (default: true) */\n enforceRLS?: boolean;\n}\n\nconst SecureDataContext = createContext<SecureDataContextType | null>(null);\n\n/**\n * SecureDataProvider - Prevents direct Supabase access and enforces secure data patterns\n * \n * This provider ensures that all data access goes through the secure RBAC system\n * and prevents apps from bypassing data access controls.\n * \n * @param props - Provider props\n * @returns React element with secure data context\n */\nexport function SecureDataProvider({\n children,\n strictMode = true,\n auditLog = true,\n onDataAccess,\n onStrictModeViolation,\n maxHistorySize = 1000,\n enforceRLS = true\n}: SecureDataProviderProps) {\n const { user, selectedOrganisation, selectedEvent } = useUnifiedAuth();\n const { validateContext } = useSecureDataAccess();\n const [dataAccessHistory, setDataAccessHistory] = useState<DataAccessRecord[]>([]);\n const [isEnabled, setIsEnabled] = useState(true);\n\n // Get current scope\n const currentScope = useMemo((): Scope | null => {\n if (!selectedOrganisation) return null;\n \n return {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n };\n }, [selectedOrganisation, selectedEvent]);\n\n // Check if data access is allowed for a table and operation\n const isDataAccessAllowed = useCallback((\n table: string, \n operation: string, \n scope?: Scope\n ): boolean => {\n if (!isEnabled) return true;\n if (!user?.id) return false;\n \n const effectiveScope = scope || currentScope;\n if (!effectiveScope) return false;\n \n // Use the existing RBAC system to check data access permissions\n // This is a synchronous check for the context - actual permission checking\n // happens in the useSecureDataAccess hook using the RBAC engine\n const permission = `${operation}:data.${table}` as Permission;\n \n // For now, we'll return true and let the useSecureDataAccess hook\n // handle the actual permission checking asynchronously\n // This context is mainly for tracking and audit purposes\n return true;\n }, [isEnabled, user?.id, currentScope]);\n\n // Get all data access permissions for current user\n const getDataAccessPermissions = useCallback((): Record<string, string[]> => {\n if (!isEnabled || !user?.id) return {};\n \n // For now, return empty object - this will be enhanced with actual permission checking\n // when we integrate with the existing RBAC system\n return {};\n }, [isEnabled, user?.id]);\n\n // Get data access history\n const getDataAccessHistory = useCallback((): DataAccessRecord[] => {\n return [...dataAccessHistory];\n }, [dataAccessHistory]);\n\n // Clear data access history\n const clearDataAccessHistory = useCallback(() => {\n setDataAccessHistory([]);\n }, []);\n\n // Validate data access attempt\n const validateDataAccess = useCallback((\n table: string,\n operation: string,\n scope?: Scope\n ): boolean => {\n if (!isEnabled) return true;\n if (!user?.id) return false;\n \n const effectiveScope = scope || currentScope;\n if (!effectiveScope) return false;\n \n // Validate organisation context\n try {\n validateContext();\n } catch (error) {\n const logger = getRBACLogger();\n logger.error('Organisation context validation failed:', error);\n return false;\n }\n \n return isDataAccessAllowed(table, operation, effectiveScope);\n }, [isEnabled, user?.id, currentScope, validateContext, isDataAccessAllowed]);\n\n // Record data access attempt\n const recordDataAccess = useCallback((\n table: string,\n operation: string,\n allowed: boolean,\n query?: string,\n filters?: Record<string, any>,\n scope?: Scope\n ) => {\n if (!auditLog || !user?.id) return;\n \n const record: DataAccessRecord = {\n table,\n operation,\n userId: user.id,\n scope: scope || currentScope || { organisationId: '' },\n allowed,\n timestamp: new Date().toISOString(),\n query,\n filters\n };\n \n setDataAccessHistory(prev => {\n const newHistory = [record, ...prev];\n return newHistory.slice(0, maxHistorySize);\n });\n \n if (onDataAccess) {\n onDataAccess(table, operation, allowed, record);\n }\n \n if (strictMode && !allowed && onStrictModeViolation) {\n onStrictModeViolation(table, operation, record);\n }\n }, [auditLog, user?.id, currentScope, maxHistorySize, onDataAccess, onStrictModeViolation, strictMode]);\n\n // Context value\n const contextValue = useMemo((): SecureDataContextType => ({\n isDataAccessAllowed,\n getDataAccessPermissions,\n isEnabled,\n isStrictMode: strictMode,\n isAuditLogEnabled: auditLog,\n getDataAccessHistory,\n clearDataAccessHistory,\n validateDataAccess\n }), [\n isDataAccessAllowed,\n getDataAccessPermissions,\n isEnabled,\n strictMode,\n auditLog,\n getDataAccessHistory,\n clearDataAccessHistory,\n validateDataAccess\n ]);\n\n // Log strict mode violations\n useEffect(() => {\n if (strictMode && auditLog) {\n const logger = getRBACLogger();\n logger.debug('Strict mode enabled - all data access attempts will be logged and enforced');\n }\n }, [strictMode, auditLog]);\n\n // Log RLS enforcement\n useEffect(() => {\n if (enforceRLS && auditLog) {\n const logger = getRBACLogger();\n logger.debug('RLS enforcement enabled - all queries will include organisation context');\n }\n }, [enforceRLS, auditLog]);\n\n return (\n <SecureDataContext.Provider value={contextValue}>\n {children}\n </SecureDataContext.Provider>\n );\n}\n\n/**\n * Hook to use secure data context\n * \n * @returns Secure data context\n * @throws Error if used outside of SecureDataProvider\n */\nexport function useSecureData(): SecureDataContextType {\n const context = useContext(SecureDataContext);\n \n if (!context) {\n throw new Error('useSecureData must be used within a SecureDataProvider');\n }\n \n return context;\n}\n\nexport default SecureDataProvider;\n","/**\n * @file Permission Enforcer Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/PermissionEnforcer\n * @since 2.0.0\n *\n * A component that enforces permissions and prevents apps from bypassing permission checks.\n * This is a critical security component that provides centralized permission enforcement.\n *\n * Features:\n * - Centralized permission enforcement\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Multiple permission checking\n * - Clear error messages for unauthorized access\n *\n * @example\n * ```tsx\n * // Basic permission enforcement\n * <PermissionEnforcer\n * permissions={['read:events', 'update:events']}\n * operation=\"event-management\"\n * fallback={<AccessDeniedPage />}\n * >\n * <EventManagementPage />\n * </PermissionEnforcer>\n * \n * // Strict mode (prevents bypassing)\n * <PermissionEnforcer\n * permissions={['admin:system']}\n * operation=\"system-administration\"\n * strictMode={true}\n * fallback={<AccessDeniedPage />}\n * >\n * <SystemAdminPage />\n * </PermissionEnforcer>\n * \n * // With custom fallback\n * <PermissionEnforcer\n * permissions={['update:settings']}\n * operation=\"settings-update\"\n * fallback={<div>You don't have permission to update settings</div>}\n * >\n * <SettingsUpdatePage />\n * </PermissionEnforcer>\n * ```\n *\n * @security\n * - Enforces permissions for all operations\n * - Prevents apps from bypassing permission checks\n * - Automatic audit logging for all permission checks\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized access\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Cached permission checks\n * - Minimal re-renders\n * - Efficient error handling\n *\n * @dependencies\n * - React 18+ - Component framework\n * - useCan hook - Permission checking\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { useMemo, useCallback, useEffect, useState } from 'react';\nimport { useMultiplePermissions } from '../hooks/usePermissions';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { UUID, Permission, Scope } from '../types';\nimport { createScopeFromEvent } from '../utils/eventContext';\nimport { getRBACLogger } from '../config';\nimport { createLogger } from '../../utils/core/logger';\n\nconst log = createLogger('PermissionEnforcer');\n\nexport interface PermissionEnforcerProps {\n /** Permissions required for access */\n permissions: Permission[];\n \n /** Operation being performed */\n operation: string;\n \n /** Content to render when user has permission */\n children: React.ReactNode;\n \n /** Content to render when user lacks permission */\n fallback?: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Force audit logging for this operation (default: true) */\n auditLog?: boolean;\n \n /** Custom scope for permission checking */\n scope?: Scope;\n \n /** Callback when access is denied */\n onDenied?: (permissions: Permission[], operation: string) => void;\n \n /** Loading state content */\n loading?: React.ReactNode;\n \n /** Require all permissions (AND) or any permission (OR) */\n requireAll?: boolean;\n}\n\n/**\n * PermissionEnforcer - Enforces permissions for operations\n * \n * This component ensures that users can only perform operations they have permission for.\n * It integrates with the existing RBAC system and provides strict enforcement to\n * prevent apps from bypassing permission checks.\n * \n * @param props - Component props\n * @returns React element with permission enforcement\n */\nexport function PermissionEnforcer({\n permissions,\n operation,\n children,\n fallback = <DefaultAccessDenied />,\n strictMode = true,\n auditLog = true,\n scope,\n onDenied,\n loading = <DefaultLoading />,\n requireAll = true\n}: PermissionEnforcerProps) {\n const { user, selectedOrganisation, selectedEvent, supabase } = useUnifiedAuth();\n const [hasChecked, setHasChecked] = useState(false);\n const [checkError, setCheckError] = useState<Error | null>(null);\n const [resolvedScope, setResolvedScope] = useState<Scope | null>(null);\n\n // Resolve scope - either use provided scope or resolve from context\n useEffect(() => {\n const resolveScope = async () => {\n if (scope) {\n setResolvedScope(scope);\n return;\n }\n\n // If we have both organisation and event, use them directly\n if (selectedOrganisation && selectedEvent) {\n setResolvedScope({\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent.event_id,\n appId: undefined\n });\n return;\n }\n\n // If we only have organisation, use it\n if (selectedOrganisation) {\n setResolvedScope({\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n });\n return;\n }\n\n // If we only have event, resolve organisation from event\n if (selectedEvent && supabase) {\n try {\n const eventScope = await createScopeFromEvent(supabase, selectedEvent.event_id);\n if (!eventScope) {\n setCheckError(new Error('Could not resolve organization from event context'));\n return;\n }\n setResolvedScope(eventScope);\n } catch (error) {\n setCheckError(error as Error);\n }\n return;\n }\n\n // No context available\n setCheckError(new Error('Either organisation context or event context is required for permission checking'));\n };\n\n resolveScope();\n }, [scope, selectedOrganisation, selectedEvent, supabase]);\n\n // Check all permissions using useMultiplePermissions hook\n const { results: permissionResults, isLoading, error } = useMultiplePermissions(\n user?.id || '',\n resolvedScope || { eventId: selectedEvent?.event_id || undefined },\n permissions,\n true // Use cache\n );\n\n // Determine if user has required permissions based on requireAll prop\n const hasRequiredPermissions = useMemo((): boolean => {\n if (permissions.length === 0) return true;\n \n // If permissionResults is not yet available or empty, deny access\n if (!permissionResults || Object.keys(permissionResults).length === 0) {\n return false;\n }\n \n if (requireAll) {\n // User must have ALL permissions\n return Object.values(permissionResults).every(result => result === true);\n } else {\n // User must have ANY permission (default behavior)\n return Object.values(permissionResults).some(result => result === true);\n }\n }, [permissions, permissionResults, requireAll]);\n\n // Handle permission check completion\n useEffect(() => {\n if (!isLoading && !error) {\n setHasChecked(true);\n setCheckError(null);\n \n if (!hasRequiredPermissions && onDenied) {\n onDenied(permissions, operation);\n }\n } else if (error) {\n setCheckError(error);\n setHasChecked(true);\n }\n }, [hasRequiredPermissions, isLoading, error, permissions, operation, onDenied]);\n\n // Log permission check attempt for audit\n useEffect(() => {\n if (auditLog && hasChecked && !isLoading) {\n log.debug('Permission check attempt:', {\n permissions,\n operation,\n userId: user?.id,\n scope: resolvedScope,\n allowed: hasRequiredPermissions,\n requireAll,\n timestamp: new Date().toISOString()\n });\n }\n }, [auditLog, hasChecked, isLoading, permissions, operation, user?.id, resolvedScope, hasRequiredPermissions, requireAll]);\n\n // Handle strict mode violations\n useEffect(() => {\n if (strictMode && hasChecked && !isLoading && !hasRequiredPermissions) {\n const logger = getRBACLogger();\n logger.error(`STRICT MODE VIOLATION: User attempted to perform operation without permission`, {\n permissions,\n operation,\n userId: user?.id,\n scope: resolvedScope,\n requireAll,\n timestamp: new Date().toISOString()\n });\n }\n }, [strictMode, hasChecked, isLoading, hasRequiredPermissions, permissions, operation, user?.id, resolvedScope, requireAll]);\n\n // Show loading state\n if (isLoading || !hasChecked) {\n return <>{loading}</>;\n }\n\n // Show error state\n if (checkError) {\n const logger = getRBACLogger();\n logger.error(`Permission check failed for operation ${operation}:`, checkError);\n return <>{fallback}</>;\n }\n\n // Show access denied\n if (!hasRequiredPermissions) {\n return <>{fallback}</>;\n }\n\n // Show protected content\n return <>{children}</>;\n}\n\n/**\n * Default access denied component\n */\nfunction DefaultAccessDenied() {\n return (\n <div className=\"flex flex-col items-center justify-center min-h-[200px] p-8 text-center\">\n <div className=\"mb-4\">\n <svg className=\"w-16 h-16 text-acc-500 mx-auto\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z\" />\n </svg>\n </div>\n <h2 className=\"text-xl font-semibold text-sec-900 mb-2\">Access Denied</h2>\n <p className=\"text-sec-600 mb-4\">You don't have permission to perform this operation.</p>\n <button \n onClick={() => window.history.back()}\n className=\"px-4 py-2 bg-main-600 text-main-50 rounded-md hover:bg-main-700 transition-colors\"\n >\n Go Back\n </button>\n </div>\n );\n}\n\n/**\n * Default loading component\n */\nfunction DefaultLoading() {\n return (\n <div className=\"flex items-center justify-center min-h-[200px] p-8\">\n <div className=\"flex items-center space-x-2\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-main-600\"></div>\n <span className=\"text-sec-600\">Checking permissions...</span>\n </div>\n </div>\n );\n}\n\nexport default PermissionEnforcer;\n","/**\n * @file Role Based Router Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/RoleBasedRouter\n * @since 2.0.0\n *\n * A component that provides centralized routing control and prevents apps from\n * implementing custom routing that bypasses permission checks. This is a critical\n * security component that ensures all routes are properly protected.\n *\n * Features:\n * - Centralized routing control\n * - Role-based route protection\n * - Permission-based route filtering\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized routes\n *\n * @example\n * ```tsx\n * // Basic role-based routing\n * <RoleBasedRouter\n * routes={routeConfig}\n * fallbackRoute=\"/unauthorized\"\n * strictMode={true}\n * >\n * <App />\n * </RoleBasedRouter>\n * \n * // With custom configuration\n * <RoleBasedRouter\n * routes={routeConfig}\n * fallbackRoute=\"/unauthorized\"\n * strictMode={true}\n * auditLog={true}\n * onRouteAccess={(route, allowed) => {\n * console.log(`Route access: ${route} - ${allowed ? 'allowed' : 'denied'}`);\n * }}\n * >\n * <App />\n * </RoleBasedRouter>\n * ```\n *\n * @security\n * - Enforces route-level permissions\n * - Prevents apps from bypassing route protection\n * - Automatic audit logging for all route access attempts\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized routes\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Cached permission checks\n * - Minimal re-renders\n * - Efficient route matching\n *\n * @dependencies\n * - React 18+ - Component framework\n * - React Router - Routing functionality\n * - useCan hook - Permission checking\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { useMemo, useCallback, useEffect, useState, createContext, useContext } from 'react';\nimport { useLocation, useNavigate, Outlet } from 'react-router-dom';\nimport { useCan } from '../hooks';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { UUID, Permission, Scope, AccessLevel } from '../types';\nimport { getRBACLogger } from '../config';\n\nexport interface RouteConfig {\n /** Route path */\n path: string;\n \n /** React component to render */\n component: React.ComponentType;\n \n /** Permissions required for this route */\n permissions: Permission[];\n \n /** If true, this route is public and doesn't require permission checks */\n public?: boolean;\n \n /** Roles that can access this route */\n roles?: string[];\n \n /** Minimum access level required */\n accessLevel?: AccessLevel;\n \n /** Page ID for permission checking */\n pageId?: string;\n \n /** Enable strict mode for this route */\n strictMode?: boolean;\n \n /** Route metadata */\n meta?: {\n title?: string;\n description?: string;\n requiresAuth?: boolean;\n hidden?: boolean;\n };\n}\n\nexport interface RouteAccessRecord {\n route: string;\n permissions: Permission[];\n userId: UUID;\n scope: Scope;\n allowed: boolean;\n timestamp: string;\n pageId?: string;\n roles?: string[];\n accessLevel?: AccessLevel;\n}\n\nexport interface RoleBasedRouterContextType {\n /** Get all accessible routes for current user */\n getAccessibleRoutes: () => RouteConfig[];\n \n /** Check if user can access a specific route */\n canAccessRoute: (path: string) => boolean;\n \n /** Get route configuration for a path */\n getRouteConfig: (path: string) => RouteConfig | null;\n \n /** Get route access history */\n getRouteAccessHistory: () => RouteAccessRecord[];\n \n /** Clear route access history */\n clearRouteAccessHistory: () => void;\n \n /** Check if strict mode is enabled */\n isStrictMode: boolean;\n \n /** Check if audit logging is enabled */\n isAuditLogEnabled: boolean;\n}\n\nexport interface RoleBasedRouterProps {\n /** Route configuration */\n routes: RouteConfig[];\n \n /** Fallback route for unauthorized access */\n fallbackRoute?: string;\n \n /** Child components */\n children: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Enable audit logging (default: true) */\n auditLog?: boolean;\n \n /** Callback when route access is attempted */\n onRouteAccess?: (route: string, allowed: boolean, record: RouteAccessRecord) => void;\n \n /** Callback when strict mode violation occurs */\n onStrictModeViolation?: (route: string, record: RouteAccessRecord) => void;\n \n /** Maximum number of access records to keep in history */\n maxHistorySize?: number;\n \n /** Custom unauthorized component */\n unauthorizedComponent?: React.ComponentType<{ route: string; reason: string }>;\n}\n\nconst RoleBasedRouterContext = createContext<RoleBasedRouterContextType | null>(null);\n\n/**\n * RoleBasedRouter - Centralized routing control with role-based protection\n * \n * This component ensures that all routes are properly protected and provides\n * centralized routing control to prevent apps from bypassing route protection.\n * \n * @param props - Router props\n * @returns React element with role-based routing\n */\nexport function RoleBasedRouter({\n routes,\n fallbackRoute = '/unauthorized',\n children,\n strictMode = true,\n auditLog = true,\n onRouteAccess,\n onStrictModeViolation,\n maxHistorySize = 1000,\n unauthorizedComponent: UnauthorizedComponent = DefaultUnauthorizedComponent\n}: RoleBasedRouterProps) {\n const { user, selectedOrganisation, selectedEvent } = useUnifiedAuth();\n const location = useLocation();\n const navigate = useNavigate();\n const [routeAccessHistory, setRouteAccessHistory] = useState<RouteAccessRecord[]>([]);\n const [currentRoute, setCurrentRoute] = useState<string>('');\n\n // Get current scope\n const currentScope = useMemo((): Scope | null => {\n if (!selectedOrganisation) return null;\n \n return {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n };\n }, [selectedOrganisation, selectedEvent]);\n\n // Get route configuration for current path\n const currentRouteConfig = useMemo((): RouteConfig | null => {\n const currentPath = location.pathname;\n return routes.find(route => route.path === currentPath) || null;\n }, [routes, location.pathname]);\n\n // Check if user can access a specific route\n const canAccessRoute = useCallback((path: string): boolean => {\n if (!user?.id || !currentScope) return false;\n \n const routeConfig = routes.find(route => route.path === path);\n if (!routeConfig) return false;\n \n // Use the existing RBAC system to check route permissions\n // This is a synchronous check for the context - actual permission checking\n // happens in the individual route components using useCan hook\n // For now, we'll return true and let the individual route components\n // handle the actual permission checking asynchronously\n return true;\n }, [user?.id, currentScope, routes]);\n\n // Use useCan hook for actual permission checking\n const { can: canAccessCurrentRoute, isLoading: permissionLoading } = useCan(\n user?.id || '',\n currentScope || { organisationId: '', eventId: undefined, appId: undefined },\n currentRouteConfig?.permissions?.[0] || 'read:page',\n currentRouteConfig?.pageId\n );\n\n // Check if route is public\n const isPublicRoute = currentRouteConfig?.public === true;\n \n // If route has no permissions and is not public, deny access (secure by default)\n const hasPermissions = currentRouteConfig?.permissions && currentRouteConfig.permissions.length > 0;\n const finalCanAccess = isPublicRoute ? true : (hasPermissions ? canAccessCurrentRoute : false);\n const finalLoading = isPublicRoute ? false : (hasPermissions ? permissionLoading : false);\n\n // Get all accessible routes for current user\n const getAccessibleRoutes = useCallback((): RouteConfig[] => {\n if (!user?.id || !currentScope) return [];\n \n return routes.filter(route => canAccessRoute(route.path));\n }, [user?.id, currentScope, routes, canAccessRoute]);\n\n // Get route configuration for a path\n const getRouteConfig = useCallback((path: string): RouteConfig | null => {\n return routes.find(route => route.path === path) || null;\n }, [routes]);\n\n // Get route access history\n const getRouteAccessHistory = useCallback((): RouteAccessRecord[] => {\n return [...routeAccessHistory];\n }, [routeAccessHistory]);\n\n // Clear route access history\n const clearRouteAccessHistory = useCallback(() => {\n setRouteAccessHistory([]);\n }, []);\n\n // Record route access attempt\n const recordRouteAccess = useCallback((\n route: string,\n allowed: boolean,\n routeConfig: RouteConfig\n ) => {\n if (!auditLog || !user?.id || !currentScope) return;\n \n const record: RouteAccessRecord = {\n route,\n permissions: routeConfig.permissions,\n userId: user.id,\n scope: currentScope,\n allowed,\n timestamp: new Date().toISOString(),\n pageId: routeConfig.pageId,\n roles: routeConfig.roles,\n accessLevel: routeConfig.accessLevel\n };\n \n setRouteAccessHistory(prev => {\n const newHistory = [record, ...prev];\n return newHistory.slice(0, maxHistorySize);\n });\n \n if (onRouteAccess) {\n onRouteAccess(route, allowed, record);\n }\n \n if (strictMode && !allowed && onStrictModeViolation) {\n onStrictModeViolation(route, record);\n }\n }, [auditLog, user?.id, currentScope, maxHistorySize, onRouteAccess, onStrictModeViolation, strictMode]);\n\n // Check route access on location change\n useEffect(() => {\n const currentPath = location.pathname;\n setCurrentRoute(currentPath);\n \n if (!currentRouteConfig) {\n // Route not found in configuration\n if (strictMode) {\n const logger = getRBACLogger();\n logger.error(`STRICT MODE VIOLATION: Route not found in configuration`, {\n route: currentPath,\n userId: user?.id,\n timestamp: new Date().toISOString()\n });\n \n if (onStrictModeViolation) {\n onStrictModeViolation(currentPath, {\n route: currentPath,\n permissions: [],\n userId: user?.id || '',\n scope: currentScope || { organisationId: '' },\n allowed: false,\n timestamp: new Date().toISOString()\n });\n }\n }\n return;\n }\n \n // Use the actual permission check result\n const allowed = finalCanAccess;\n // Log route access (including public routes for audit monitoring)\n recordRouteAccess(currentPath, allowed, currentRouteConfig);\n \n if (!allowed && !isPublicRoute) {\n // Redirect to fallback route (skip for public routes)\n navigate(fallbackRoute, { replace: true });\n }\n }, [location.pathname, currentRouteConfig, canAccessCurrentRoute, recordRouteAccess, strictMode, user?.id, currentScope, onStrictModeViolation, navigate, fallbackRoute, isPublicRoute]);\n\n // Context value\n const contextValue = useMemo((): RoleBasedRouterContextType => ({\n getAccessibleRoutes,\n canAccessRoute,\n getRouteConfig,\n getRouteAccessHistory,\n clearRouteAccessHistory,\n isStrictMode: strictMode,\n isAuditLogEnabled: auditLog\n }), [\n getAccessibleRoutes,\n canAccessRoute,\n getRouteConfig,\n getRouteAccessHistory,\n clearRouteAccessHistory,\n strictMode,\n auditLog\n ]);\n\n // Show loading state while checking permissions (skip for public routes)\n if (finalLoading && !isPublicRoute) {\n return (\n <div className=\"flex items-center justify-center min-h-screen\">\n <div className=\"text-center\">\n <div className=\"animate-spin rounded-full h-8 w-8 border-b-2 border-main-600 mx-auto mb-4\"></div>\n <p className=\"text-sec-600\">Checking permissions...</p>\n </div>\n </div>\n );\n }\n\n // Show unauthorized component if user can't access current route\n if (currentRouteConfig && !finalCanAccess && !isPublicRoute) {\n return (\n <UnauthorizedComponent \n route={currentRoute} \n reason=\"Insufficient permissions\" \n />\n );\n }\n return (\n <RoleBasedRouterContext.Provider value={contextValue}>\n {children}\n <Outlet />\n </RoleBasedRouterContext.Provider>\n );\n}\n\n/**\n * Hook to use role-based router context\n * \n * @returns Role-based router context\n * @throws Error if used outside of RoleBasedRouter\n */\nexport function useRoleBasedRouter(): RoleBasedRouterContextType {\n const context = useContext(RoleBasedRouterContext);\n \n if (!context) {\n throw new Error('useRoleBasedRouter must be used within a RoleBasedRouter');\n }\n \n return context;\n}\n\n/**\n * Default unauthorized component\n */\nfunction DefaultUnauthorizedComponent({ route, reason }: { route: string; reason: string }) {\n return (\n <div className=\"flex flex-col items-center justify-center min-h-screen p-8 text-center\">\n <div className=\"mb-4\">\n <svg className=\"w-16 h-16 text-acc-500 mx-auto\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z\" />\n </svg>\n </div>\n <h2 className=\"text-xl font-semibold text-sec-900 mb-2\">Access Denied</h2>\n <p className=\"text-sec-600 mb-4\">\n You don't have permission to access <code className=\"bg-sec-100 px-2 py-1 rounded\">{route}</code>\n </p>\n <p className=\"text-sm text-sec-500 mb-4\">Reason: {reason}</p>\n <button \n onClick={() => window.history.back()}\n className=\"px-4 py-2 bg-main-600 text-main-50 rounded-md hover:bg-main-700 transition-colors\"\n >\n Go Back\n </button>\n </div>\n );\n}\n\nexport default RoleBasedRouter;\n\n","/**\n * @file Navigation Provider Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/NavigationProvider\n * @since 2.0.0\n *\n * A context provider that manages navigation permissions across the entire application.\n * This component ensures that all navigation items are properly protected and provides\n * centralized navigation permission management.\n *\n * Features:\n * - App-wide navigation permission management\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Navigation permission tracking\n * - Error handling and recovery\n *\n * @example\n * ```tsx\n * // Basic app setup with navigation permissions\n * <NavigationProvider strictMode={true} auditLog={true}>\n * <App />\n * </NavigationProvider>\n * \n * // With custom configuration\n * <NavigationProvider\n * strictMode={true}\n * auditLog={true}\n * onNavigationAccess={(item, allowed) => {\n * console.log(`Navigation access: ${item} - ${allowed ? 'allowed' : 'denied'}`);\n * }}\n * >\n * <App />\n * </NavigationProvider>\n * ```\n *\n * @security\n * - Enforces navigation-level permissions across the app\n * - Prevents apps from bypassing navigation permission checks\n * - Automatic audit logging for all navigation access attempts\n * - Integration with existing RBAC system\n * - Navigation permission tracking and monitoring\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Efficient context updates\n * - Minimal re-renders\n * - Cached permission checks\n *\n * @dependencies\n * - React 18+ - Context and hooks\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { createContext, useContext, useState, useCallback, useMemo, useEffect } from 'react';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { useCan } from '../hooks';\nimport { UUID, Scope, Permission } from '../types';\nimport { getRBACLogger } from '../config';\nimport { logger } from '../../utils/core/logger';\n\nexport interface NavigationItem {\n /** Unique identifier for the navigation item */\n id: string;\n \n /** Display label for the navigation item */\n label: string;\n \n /** Navigation path/URL */\n path: string;\n \n /** Permissions required for this navigation item */\n permissions: Permission[];\n \n /** Roles that can access this navigation item */\n roles?: string[];\n \n /** Minimum access level required */\n accessLevel?: 'viewer' | 'participant' | 'planner' | 'admin' | 'super';\n \n /** Page ID for permission checking */\n pageId?: string;\n \n /** Enable strict mode for this navigation item */\n strictMode?: boolean;\n \n /** Navigation item metadata */\n meta?: {\n icon?: string;\n description?: string;\n hidden?: boolean;\n order?: number;\n };\n}\n\nexport interface NavigationAccessRecord {\n navigationItem: string;\n permissions: Permission[];\n userId: UUID;\n scope: Scope;\n allowed: boolean;\n timestamp: string;\n pageId?: string;\n roles?: string[];\n accessLevel?: string;\n}\n\nexport interface NavigationContextType {\n /** Check if user has permission for a navigation item */\n hasNavigationPermission: (item: NavigationItem) => boolean;\n \n /** Get all navigation permissions for current user */\n getNavigationPermissions: () => Record<string, string[]>;\n \n /** Get filtered navigation items based on permissions */\n getFilteredNavigationItems: (items: NavigationItem[]) => NavigationItem[];\n \n /** Check if navigation permission checking is enabled */\n isEnabled: boolean;\n \n /** Check if strict mode is enabled */\n isStrictMode: boolean;\n \n /** Check if audit logging is enabled */\n isAuditLogEnabled: boolean;\n \n /** Get navigation access history */\n getNavigationAccessHistory: () => NavigationAccessRecord[];\n \n /** Clear navigation access history */\n clearNavigationAccessHistory: () => void;\n}\n\nexport interface NavigationProviderProps {\n /** Child components */\n children: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Enable audit logging (default: true) */\n auditLog?: boolean;\n \n /** Callback when navigation access is attempted */\n onNavigationAccess?: (item: NavigationItem, allowed: boolean, record: NavigationAccessRecord) => void;\n \n /** Callback when strict mode violation occurs */\n onStrictModeViolation?: (item: NavigationItem, record: NavigationAccessRecord) => void;\n \n /** Maximum number of access records to keep in history */\n maxHistorySize?: number;\n}\n\nconst NavigationContext = createContext<NavigationContextType | null>(null);\n\n/**\n * NavigationProvider - Manages navigation-level permissions across the app\n * \n * This provider ensures that all navigation items are properly protected and provides\n * centralized navigation permission management with strict enforcement.\n * \n * @param props - Provider props\n * @returns React element with navigation permission context\n */\nexport function NavigationProvider({\n children,\n strictMode = true,\n auditLog = true,\n onNavigationAccess,\n onStrictModeViolation,\n maxHistorySize = 1000\n}: NavigationProviderProps) {\n const { user, selectedOrganisation, selectedEvent } = useUnifiedAuth();\n const [navigationAccessHistory, setNavigationAccessHistory] = useState<NavigationAccessRecord[]>([]);\n const [isEnabled, setIsEnabled] = useState(true);\n\n // Get current scope\n const currentScope = useMemo((): Scope | null => {\n if (!selectedOrganisation) return null;\n \n return {\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n };\n }, [selectedOrganisation, selectedEvent]);\n\n // Check if user has permission for a navigation item\n // NOTE: This is a synchronous check for basic validation only.\n // Actual permission checking should be done by individual NavigationGuard components\n // using the useCan hook for proper async RBAC integration.\n const hasNavigationPermission = useCallback((\n item: NavigationItem\n ): boolean => {\n if (!isEnabled) return true;\n if (!user?.id) return false; // No user context - deny access for security\n \n if (!currentScope) return false; // No scope context - deny access for security\n \n // If no permissions are defined for the navigation item, deny access by default\n if (!item.permissions || item.permissions.length === 0) {\n logger.warn('NavigationProvider', `Navigation item \"${item.id}\" has no permissions defined - denying access`);\n return false;\n }\n \n // Use the first permission for checking (as per original implementation)\n const permission = item.permissions[0];\n \n // Call useCan hook for actual permission checking\n const { can, error } = useCan(\n user.id,\n currentScope,\n permission,\n item.pageId,\n true // useCache\n );\n \n // Handle errors gracefully - allow access when there are permission check errors (graceful degradation)\n // This ensures navigation doesn't break when the permission service has issues\n if (error) {\n logger.warn('NavigationProvider', `Permission check error for \"${item.id}\": ${error.message} - allowing access for graceful degradation`);\n return true;\n }\n \n return can;\n }, [isEnabled, user?.id, currentScope]);\n\n // Get all navigation permissions for current user\n const getNavigationPermissions = useCallback((): Record<string, string[]> => {\n if (!isEnabled || !user?.id) return {};\n \n // For now, return empty object - this will be enhanced with actual permission checking\n // when we integrate with the existing RBAC system\n return {};\n }, [isEnabled, user?.id]);\n\n // Get filtered navigation items based on permissions\n const getFilteredNavigationItems = useCallback((items: NavigationItem[]): NavigationItem[] => {\n if (!isEnabled) return items;\n \n return items.filter(item => hasNavigationPermission(item));\n }, [isEnabled, hasNavigationPermission]);\n\n // Get navigation access history\n const getNavigationAccessHistory = useCallback((): NavigationAccessRecord[] => {\n return [...navigationAccessHistory];\n }, [navigationAccessHistory]);\n\n // Clear navigation access history\n const clearNavigationAccessHistory = useCallback(() => {\n setNavigationAccessHistory([]);\n }, []);\n\n // Record navigation access attempt\n const recordNavigationAccess = useCallback((\n item: NavigationItem,\n allowed: boolean\n ) => {\n if (!auditLog || !user?.id || !currentScope) return;\n \n const record: NavigationAccessRecord = {\n navigationItem: item.id,\n permissions: item.permissions,\n userId: user.id,\n scope: currentScope,\n allowed,\n timestamp: new Date().toISOString(),\n pageId: item.pageId,\n roles: item.roles,\n accessLevel: item.accessLevel\n };\n \n setNavigationAccessHistory(prev => {\n const newHistory = [record, ...prev];\n return newHistory.slice(0, maxHistorySize);\n });\n \n if (onNavigationAccess) {\n onNavigationAccess(item, allowed, record);\n }\n \n if (strictMode && !allowed && onStrictModeViolation) {\n onStrictModeViolation(item, record);\n }\n }, [auditLog, user?.id, currentScope, maxHistorySize, onNavigationAccess, onStrictModeViolation, strictMode]);\n\n // Context value\n const contextValue = useMemo((): NavigationContextType => ({\n hasNavigationPermission,\n getNavigationPermissions,\n getFilteredNavigationItems,\n isEnabled,\n isStrictMode: strictMode,\n isAuditLogEnabled: auditLog,\n getNavigationAccessHistory,\n clearNavigationAccessHistory\n }), [\n hasNavigationPermission,\n getNavigationPermissions,\n getFilteredNavigationItems,\n isEnabled,\n strictMode,\n auditLog,\n getNavigationAccessHistory,\n clearNavigationAccessHistory\n ]);\n\n // Log strict mode violations\n useEffect(() => {\n if (strictMode && auditLog) {\n const logger = getRBACLogger();\n logger.debug('Strict mode enabled - all navigation access attempts will be logged and enforced');\n }\n }, [strictMode, auditLog]);\n\n return (\n <NavigationContext.Provider value={contextValue}>\n {children}\n </NavigationContext.Provider>\n );\n}\n\n/**\n * Hook to use navigation permission context\n * \n * @returns Navigation permission context\n * @throws Error if used outside of NavigationProvider\n */\nexport function useNavigationPermissions(): NavigationContextType {\n const context = useContext(NavigationContext);\n \n if (!context) {\n throw new Error('useNavigationPermissions must be used within a NavigationProvider');\n }\n \n return context;\n}\n\nexport default NavigationProvider;","/**\n * @file Navigation Guard Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/NavigationGuard\n * @since 2.0.0\n *\n * A component that enforces navigation-level permissions and prevents apps from bypassing\n * navigation permission checks. This is a critical security component that ensures all\n * navigation items are properly protected.\n *\n * Features:\n * - Navigation-level permission enforcement\n * - Strict mode to prevent bypassing\n * - Automatic audit logging\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized navigation\n * - TypeScript support with strict typing\n *\n * @example\n * ```tsx\n * // Basic navigation protection\n * <NavigationGuard\n * navigationItem={navItem}\n * fallback={<AccessDeniedNavItem />}\n * >\n * <NavigationLink />\n * </NavigationGuard>\n * \n * // Strict mode (prevents bypassing)\n * <NavigationGuard\n * navigationItem={adminNavItem}\n * strictMode={true}\n * fallback={<AccessDeniedNavItem />}\n * >\n * <AdminNavigationLink />\n * </NavigationGuard>\n * \n * // With custom fallback\n * <NavigationGuard\n * navigationItem={settingsNavItem}\n * fallback={<div>You don't have permission to access settings</div>}\n * >\n * <SettingsNavigationLink />\n * </NavigationGuard>\n * ```\n *\n * @security\n * - Enforces navigation-level permissions\n * - Prevents apps from bypassing navigation permission checks\n * - Automatic audit logging for all navigation access attempts\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized navigation\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Cached permission checks\n * - Minimal re-renders\n * - Efficient error handling\n *\n * @dependencies\n * - React 18+ - Component framework\n * - useCan hook - Permission checking\n * - useUnifiedAuth - Authentication context\n * - RBAC types - Type definitions\n */\n\nimport React, { useMemo, useCallback, useEffect, useState } from 'react';\nimport { useMultiplePermissions } from '../hooks/usePermissions';\nimport { useUnifiedAuth } from '../../providers/services/UnifiedAuthProvider';\nimport { UUID, Permission, Scope } from '../types';\nimport { createScopeFromEvent } from '../utils/eventContext';\nimport { NavigationItem } from './NavigationProvider';\nimport { getRBACLogger } from '../config';\n\nexport interface NavigationGuardProps {\n /** Navigation item being protected */\n navigationItem: NavigationItem;\n \n /** Content to render when user has permission */\n children: React.ReactNode;\n \n /** Content to render when user lacks permission */\n fallback?: React.ReactNode;\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Force audit logging for this navigation access (default: true) */\n auditLog?: boolean;\n \n /** Custom scope for permission checking */\n scope?: Scope;\n \n /** Callback when access is denied */\n onDenied?: (item: NavigationItem) => void;\n \n /** Loading state content */\n loading?: React.ReactNode;\n \n /** Require all permissions (AND) or any permission (OR) */\n requireAll?: boolean;\n}\n\n/**\n * NavigationGuard - Enforces navigation-level permissions\n * \n * This component ensures that users can only access navigation items they have permission for.\n * It integrates with the existing RBAC system and provides strict enforcement to\n * prevent apps from bypassing navigation permission checks.\n * \n * @param props - Component props\n * @returns React element with navigation permission enforcement\n */\nexport function NavigationGuard({\n navigationItem,\n children,\n fallback = <DefaultAccessDenied />,\n strictMode = true,\n auditLog = true,\n scope,\n onDenied,\n loading = <DefaultLoading />,\n requireAll = true\n}: NavigationGuardProps) {\n const { user, selectedOrganisation, selectedEvent, supabase } = useUnifiedAuth();\n const [hasChecked, setHasChecked] = useState(false);\n const [checkError, setCheckError] = useState<Error | null>(null);\n const [resolvedScope, setResolvedScope] = useState<Scope | null>(null);\n\n // Resolve scope - either use provided scope or resolve from context\n useEffect(() => {\n const resolveScope = async () => {\n if (scope) {\n setResolvedScope(scope);\n return;\n }\n\n // If we have both organisation and event, use them directly\n if (selectedOrganisation && selectedEvent) {\n setResolvedScope({\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent.event_id,\n appId: undefined\n });\n return;\n }\n\n // If we only have organisation, use it\n if (selectedOrganisation) {\n setResolvedScope({\n organisationId: selectedOrganisation.id,\n eventId: selectedEvent?.event_id || undefined,\n appId: undefined\n });\n return;\n }\n\n // If we only have event, resolve organisation from event\n if (selectedEvent && supabase) {\n try {\n const eventScope = await createScopeFromEvent(supabase, selectedEvent.event_id);\n if (!eventScope) {\n setCheckError(new Error('Could not resolve organization from event context'));\n return;\n }\n setResolvedScope(eventScope);\n } catch (error) {\n setCheckError(error as Error);\n }\n return;\n }\n\n // No context available\n setCheckError(new Error('Either organisation context or event context is required for navigation permission checking'));\n };\n\n resolveScope();\n }, [scope, selectedOrganisation, selectedEvent, supabase]);\n\n // Check all permissions using useMultiplePermissions hook\n const { results: permissionResults, isLoading, error } = useMultiplePermissions(\n user?.id || '',\n resolvedScope || { eventId: selectedEvent?.event_id || undefined },\n navigationItem.permissions || [],\n true // Use cache\n );\n\n // Determine if user has required permissions based on requireAll prop\n const hasRequiredPermissions = useMemo((): boolean => {\n if (!navigationItem.permissions || navigationItem.permissions.length === 0) return true;\n \n if (requireAll) {\n // User must have ALL permissions\n return Object.values(permissionResults).every(result => result === true);\n } else {\n // User must have ANY permission (default behavior)\n return Object.values(permissionResults).some(result => result === true);\n }\n }, [navigationItem.permissions, permissionResults, requireAll]);\n\n // Handle permission check completion\n useEffect(() => {\n if (!isLoading && !error) {\n setHasChecked(true);\n setCheckError(null);\n \n if (!hasRequiredPermissions && onDenied) {\n onDenied(navigationItem);\n }\n } else if (error) {\n setCheckError(error);\n setHasChecked(true);\n }\n }, [hasRequiredPermissions, isLoading, error, navigationItem, onDenied]);\n\n // Log navigation access attempt for audit\n useEffect(() => {\n if (auditLog && hasChecked && !isLoading) {\n const logger = getRBACLogger();\n logger.debug('Navigation access attempt:', {\n navigationItem: navigationItem.id,\n permissions: navigationItem.permissions,\n userId: user?.id,\n scope: resolvedScope,\n allowed: hasRequiredPermissions,\n requireAll,\n timestamp: new Date().toISOString()\n });\n }\n }, [auditLog, hasChecked, isLoading, navigationItem, user?.id, resolvedScope, hasRequiredPermissions, requireAll]);\n\n // Handle strict mode violations\n useEffect(() => {\n if (strictMode && hasChecked && !isLoading && !hasRequiredPermissions) {\n const logger = getRBACLogger();\n logger.error(`STRICT MODE VIOLATION: User attempted to access protected navigation item without permission`, {\n navigationItem: navigationItem.id,\n permissions: navigationItem.permissions,\n userId: user?.id,\n scope: resolvedScope,\n requireAll,\n timestamp: new Date().toISOString()\n });\n }\n }, [strictMode, hasChecked, isLoading, hasRequiredPermissions, navigationItem, user?.id, resolvedScope, requireAll]);\n\n // Show loading state\n if (isLoading || !resolvedScope || !hasChecked) {\n return <>{loading}</>;\n }\n\n // Show error state\n if (checkError) {\n const logger = getRBACLogger();\n logger.error(`Permission check failed for navigation item ${navigationItem.id}:`, checkError);\n return <>{fallback}</>;\n }\n\n // Show access denied\n if (!hasRequiredPermissions) {\n return <>{fallback}</>;\n }\n\n // Show protected content\n return <>{children}</>;\n}\n\n/**\n * Default access denied component\n */\nfunction DefaultAccessDenied() {\n return (\n <div className=\"flex items-center justify-center p-2 text-center\">\n <div className=\"flex items-center space-x-2\">\n <svg className=\"w-4 h-4 text-acc-500\" fill=\"none\" stroke=\"currentColor\" viewBox=\"0 0 24 24\">\n <path strokeLinecap=\"round\" strokeLinejoin=\"round\" strokeWidth={2} d=\"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z\" />\n </svg>\n <span className=\"text-sm text-sec-600\">Access Denied</span>\n </div>\n </div>\n );\n}\n\n/**\n * Default loading component\n */\nfunction DefaultLoading() {\n return (\n <div className=\"flex items-center justify-center p-2\">\n <div className=\"flex items-center space-x-2\">\n <div className=\"animate-spin rounded-full h-4 w-4 border-b-2 border-main-600\"></div>\n <span className=\"text-sm text-sec-600\">Checking...</span>\n </div>\n </div>\n );\n}\n\nexport default NavigationGuard;","/**\n * @file Enhanced Navigation Menu Component\n * @package @jmruthers/pace-core\n * @module RBAC/Components/EnhancedNavigationMenu\n * @since 2.0.0\n *\n * An enhanced navigation menu component that integrates with the RBAC system to provide\n * secure navigation with automatic permission filtering and enforcement.\n *\n * Features:\n * - Automatic permission-based filtering\n * - Strict mode enforcement\n * - Audit logging for navigation access\n * - Integration with existing RBAC system\n * - Customizable navigation items\n * - Error handling and recovery\n *\n * @example\n * ```tsx\n * // Basic enhanced navigation menu\n * <EnhancedNavigationMenu\n * items={navigationItems}\n * strictMode={true}\n * auditLog={true}\n * />\n * \n * // With custom configuration\n * <EnhancedNavigationMenu\n * items={navigationItems}\n * strictMode={true}\n * auditLog={true}\n * onNavigationAccess={(item, allowed) => {\n * console.log(`Navigation access: ${item.id} - ${allowed ? 'allowed' : 'denied'}`);\n * }}\n * />\n * ```\n *\n * @security\n * - Enforces navigation-level permissions\n * - Prevents apps from bypassing navigation permission checks\n * - Automatic audit logging for all navigation access attempts\n * - Integration with existing RBAC system\n * - Clear error messages for unauthorized navigation\n *\n * @performance\n * - Optimized with useMemo and useCallback\n * - Cached permission checks\n * - Minimal re-renders\n * - Efficient filtering\n *\n * @dependencies\n * - React 18+ - Component framework\n * - NavigationProvider - Navigation permission context\n * - NavigationGuard - Individual navigation item protection\n * - RBAC types - Type definitions\n */\n\nimport React, { useMemo, useCallback, useEffect, useState } from 'react';\nimport { useNavigationPermissions, NavigationItem } from './NavigationProvider';\nimport NavigationGuard from './NavigationGuard';\nimport { getRBACLogger } from '../config';\n\nexport interface EnhancedNavigationMenuProps {\n /** Navigation items to display */\n items: NavigationItem[];\n \n /** Enable strict mode to prevent bypassing (default: true) */\n strictMode?: boolean;\n \n /** Enable audit logging (default: true) */\n auditLog?: boolean;\n \n /** Callback when navigation access is attempted */\n onNavigationAccess?: (item: NavigationItem, allowed: boolean) => void;\n \n /** Callback when strict mode violation occurs */\n onStrictModeViolation?: (item: NavigationItem) => void;\n \n /** Custom className for the navigation menu */\n className?: string;\n \n /** Custom className for navigation items */\n itemClassName?: string;\n \n /** Custom className for active navigation items */\n activeItemClassName?: string;\n \n /** Custom className for disabled navigation items */\n disabledItemClassName?: string;\n \n /** Show/hide navigation items that user doesn't have permission for */\n hideUnauthorizedItems?: boolean;\n \n /** Custom render function for navigation items */\n renderItem?: (item: NavigationItem, isAuthorized: boolean) => React.ReactNode;\n \n /** Current active path for highlighting */\n activePath?: string;\n \n /** Navigation item click handler */\n onItemClick?: (item: NavigationItem) => void;\n}\n\n/**\n * EnhancedNavigationMenu - Secure navigation menu with RBAC integration\n * \n * This component provides a navigation menu that automatically filters items based on\n * user permissions and enforces strict security controls.\n * \n * @param props - Component props\n * @returns React element with enhanced navigation menu\n */\nexport function EnhancedNavigationMenu({\n items,\n strictMode = true,\n auditLog = true,\n onNavigationAccess,\n onStrictModeViolation,\n className = 'flex flex-col space-y-1',\n itemClassName = 'px-3 py-2 rounded-md text-sm font-medium transition-colors',\n activeItemClassName = 'bg-main-100 text-main-700',\n disabledItemClassName = 'text-sec-400 cursor-not-allowed',\n hideUnauthorizedItems = false,\n renderItem,\n activePath,\n onItemClick\n}: EnhancedNavigationMenuProps) {\n const { \n hasNavigationPermission, \n getFilteredNavigationItems,\n isEnabled,\n isStrictMode,\n isAuditLogEnabled \n } = useNavigationPermissions();\n \n const [navigationHistory, setNavigationHistory] = useState<NavigationItem[]>([]);\n\n // Get filtered navigation items based on permissions\n const filteredItems = useMemo((): NavigationItem[] => {\n if (!isEnabled) return items;\n \n return getFilteredNavigationItems(items);\n }, [isEnabled, items, getFilteredNavigationItems]);\n\n // Handle navigation access attempt\n const handleNavigationAccess = useCallback((item: NavigationItem, allowed: boolean) => {\n if (onNavigationAccess) {\n onNavigationAccess(item, allowed);\n }\n \n if (auditLog) {\n const logger = getRBACLogger();\n logger.debug('Navigation access attempt:', {\n item: item.id,\n allowed,\n strictMode,\n timestamp: new Date().toISOString()\n });\n }\n }, [onNavigationAccess, auditLog, strictMode]);\n\n // Handle strict mode violation\n const handleStrictModeViolation = useCallback((item: NavigationItem) => {\n if (onStrictModeViolation) {\n onStrictModeViolation(item);\n }\n \n if (strictMode) {\n const logger = getRBACLogger();\n logger.error(`STRICT MODE VIOLATION: User attempted to access protected navigation item without permission`, {\n item: item.id,\n path: item.path,\n permissions: item.permissions,\n timestamp: new Date().toISOString()\n });\n }\n }, [onStrictModeViolation, strictMode]);\n\n // Handle navigation item click\n const handleItemClick = useCallback((item: NavigationItem) => {\n // Check if user has permission for this item\n const isAuthorized = hasNavigationPermission(item);\n \n // Call navigation access handler\n handleNavigationAccess(item, isAuthorized);\n \n if (onItemClick) {\n onItemClick(item);\n }\n \n // Record navigation attempt\n if (auditLog) {\n const logger = getRBACLogger();\n logger.debug('Navigation item clicked:', {\n item: item.id,\n path: item.path,\n permissions: item.permissions,\n timestamp: new Date().toISOString()\n });\n }\n \n // Add to navigation history\n setNavigationHistory(prev => {\n const newHistory = [item, ...prev.filter(i => i.id !== item.id)];\n return newHistory.slice(0, 10); // Keep last 10 items\n });\n }, [onItemClick, auditLog, hasNavigationPermission, handleNavigationAccess]);\n\n // Default render function for navigation items\n const defaultRenderItem = useCallback((item: NavigationItem, isAuthorized: boolean) => {\n const isActive = activePath === item.path;\n const isDisabled = !isAuthorized;\n \n return (\n <NavigationGuard\n key={item.id}\n navigationItem={item}\n strictMode={strictMode}\n auditLog={auditLog}\n onDenied={handleStrictModeViolation}\n fallback={\n hideUnauthorizedItems ? null : (\n <div className={`${itemClassName} ${disabledItemClassName}`}>\n <div className=\"flex items-center space-x-2\">\n {item.meta?.icon && (\n <span className=\"text-sm\">{item.meta.icon}</span>\n )}\n <span>{item.label}</span>\n <span className=\"text-xs text-sec-400\">(Access Denied)</span>\n </div>\n </div>\n )\n }\n >\n <button\n onClick={() => handleItemClick(item)}\n className={`${itemClassName} ${\n isActive ? activeItemClassName : ''\n } ${\n isDisabled ? disabledItemClassName : 'hover:bg-sec-100'\n }`}\n disabled={isDisabled}\n >\n <div className=\"flex items-center space-x-2\">\n {item.meta?.icon && (\n <span className=\"text-sm\">{item.meta.icon}</span>\n )}\n <span>{item.label}</span>\n {item.meta?.description && (\n <span className=\"text-xs text-sec-500 ml-auto\">\n {item.meta.description}\n </span>\n )}\n </div>\n </button>\n </NavigationGuard>\n );\n }, [\n activePath,\n itemClassName,\n activeItemClassName,\n disabledItemClassName,\n hideUnauthorizedItems,\n strictMode,\n auditLog,\n handleStrictModeViolation,\n handleItemClick\n ]);\n\n // Log strict mode violations\n useEffect(() => {\n if (strictMode && auditLog) {\n const logger = getRBACLogger();\n logger.debug('Strict mode enabled - all navigation access attempts will be logged and enforced');\n }\n }, [strictMode, auditLog]);\n\n // Log navigation menu initialization\n useEffect(() => {\n if (auditLog) {\n const logger = getRBACLogger();\n logger.debug('Navigation menu initialized:', {\n totalItems: items.length,\n filteredItems: filteredItems.length,\n strictMode,\n timestamp: new Date().toISOString()\n });\n }\n }, [items.length, filteredItems.length, strictMode, auditLog]);\n\n return (\n <nav className={className}>\n {filteredItems.map(item => {\n const isAuthorized = hasNavigationPermission(item);\n \n if (renderItem) {\n return renderItem(item, isAuthorized);\n }\n \n return defaultRenderItem(item, isAuthorized);\n })}\n </nav>\n );\n}\n\nexport default EnhancedNavigationMenu;\n","/**\n * RBAC Adapters\n * @package @jmruthers/pace-core\n * @module RBAC/Adapters\n * @since 1.0.0\n * \n * This module provides adapters for different frameworks and server runtimes.\n */\n\nimport React, { ReactNode } from 'react';\nimport { UUID, Permission } from './types';\nimport { useCan } from './hooks';\nimport { rbacCache, RBACCache } from './cache';\nimport { getRBACLogger } from './config';\nimport { useUnifiedAuth } from '../providers/services/UnifiedAuthProvider';\n\n// ============================================================================\n// REACT COMPONENTS\n// ============================================================================\n\n/**\n * Permission Guard Component\n * \n * A React component that conditionally renders children based on permissions.\n * Can auto-infer userId from context if not provided.\n * \n * @example\n * ```tsx\n * // With explicit userId and scope\n * <PermissionGuard\n * userId=\"user-123\"\n * scope={{ organisationId: 'org-456' }}\n * permission=\"update:events\"\n * pageId=\"page-789\"\n * fallback={<AccessDenied />}\n * >\n * <AdminPanel />\n * </PermissionGuard>\n * \n * // With context inference (requires auth context)\n * <PermissionGuard\n * permission=\"update:events\"\n * scope={{ organisationId: 'org-456' }}\n * fallback={<AccessDenied />}\n * >\n * <AdminPanel />\n * </PermissionGuard>\n * ```\n */\nexport function PermissionGuard({\n userId,\n scope,\n permission,\n pageId,\n children,\n fallback = null,\n onDenied,\n loading = null,\n // NEW: Phase 1 - Enhanced Security Features\n strictMode = true,\n auditLog = true,\n enforceAudit = true,\n}: {\n userId?: UUID;\n scope: { organisationId: UUID; eventId?: string; appId?: UUID };\n permission: Permission;\n pageId?: UUID;\n children: ReactNode;\n fallback?: ReactNode;\n onDenied?: () => void;\n loading?: ReactNode;\n // NEW: Phase 1 - Enhanced Security Features\n strictMode?: boolean;\n auditLog?: boolean;\n enforceAudit?: boolean;\n}): React.ReactNode {\n const logger = getRBACLogger();\n\n let authContext: ReturnType<typeof useUnifiedAuth> | null = null;\n try {\n authContext = useUnifiedAuth();\n } catch (error) {\n if (error instanceof Error && error.message.includes('must be used within')) {\n authContext = null;\n } else {\n throw error;\n }\n }\n\n const effectiveUserId = userId ?? authContext?.user?.id ?? null;\n\n // Always call useCan hook, but handle the case where userId might be undefined\n const { can, isLoading, error } = useCan(effectiveUserId || '', scope, permission, pageId);\n\n // If still no userId, show helpful error\n if (!effectiveUserId) {\n logger.error('PermissionGuard: No userId provided and could not infer from context');\n return fallback ?? null;\n }\n\n // Handle loading state\n if (isLoading) {\n return loading || (\n <div className=\"rbac-loading\" role=\"status\" aria-live=\"polite\">\n <span className=\"sr-only\">Checking permissions...</span>\n </div>\n );\n }\n\n // Handle error state\n if (error) {\n logger.error('Permission check failed:', error);\n // NEW: Phase 1 - Record failed permission check for audit\n if (auditLog) {\n logger.info(`[PermissionGuard] Permission check failed:`, {\n userId: effectiveUserId,\n scope,\n permission,\n pageId,\n error: error.message,\n timestamp: new Date().toISOString()\n });\n }\n return fallback;\n }\n\n // Handle permission denied\n if (!can) {\n // NEW: Phase 1 - Record denied permission check for audit\n if (auditLog) {\n logger.info(`[PermissionGuard] Permission denied:`, {\n userId: effectiveUserId,\n scope,\n permission,\n pageId,\n timestamp: new Date().toISOString()\n });\n }\n \n // NEW: Phase 1 - Handle strict mode violations\n if (strictMode) {\n logger.error(`[PermissionGuard] STRICT MODE VIOLATION: User attempted to access protected resource without permission`, {\n userId: effectiveUserId,\n scope,\n permission,\n pageId,\n timestamp: new Date().toISOString()\n });\n }\n \n if (onDenied) {\n onDenied();\n }\n return <>{fallback}</>;\n }\n\n // NEW: Phase 1 - Record successful permission check for audit\n if (auditLog) {\n logger.info(`[PermissionGuard] Permission granted:`, {\n userId: effectiveUserId,\n scope,\n permission,\n pageId,\n timestamp: new Date().toISOString()\n });\n }\n\n // Render children if permission granted\n return <>{children}</>;\n}\n\n/**\n * Access Level Guard Component\n * \n * A React component that conditionally renders children based on access level.\n * Can auto-infer userId from context if not provided.\n * \n * @example\n * ```tsx\n * // With explicit userId and scope\n * <AccessLevelGuard\n * userId=\"user-123\"\n * scope={{ organisationId: 'org-456' }}\n * minLevel=\"admin\"\n * fallback={<AccessDenied />}\n * >\n * <AdminPanel />\n * </AccessLevelGuard>\n * \n * // With context inference (requires auth context)\n * <AccessLevelGuard\n * minLevel=\"admin\"\n * scope={{ organisationId: 'org-456' }}\n * fallback={<AccessDenied />}\n * >\n * <AdminPanel />\n * </AccessLevelGuard>\n * ```\n */\nexport function AccessLevelGuard({\n userId,\n scope,\n minLevel,\n children,\n fallback = null,\n loading = null,\n}: {\n userId?: UUID;\n scope: { organisationId: UUID; eventId?: string; appId?: UUID };\n minLevel: 'viewer' | 'participant' | 'planner' | 'admin' | 'super';\n children: ReactNode;\n fallback?: ReactNode;\n loading?: ReactNode;\n}): React.ReactNode {\n const logger = getRBACLogger();\n\n let authContext: ReturnType<typeof useUnifiedAuth> | null = null;\n try {\n authContext = useUnifiedAuth();\n } catch (error) {\n if (error instanceof Error && error.message.includes('must be used within')) {\n authContext = null;\n } else {\n throw error;\n }\n }\n\n const effectiveUserId = userId ?? authContext?.user?.id ?? null;\n\n // Always call useAccessLevel hook, but handle the case where userId might be undefined\n const { accessLevel, isLoading, error } = useAccessLevel(effectiveUserId || '', scope);\n\n // If still no userId, show helpful error\n if (!effectiveUserId) {\n logger.error('AccessLevelGuard: No userId provided and could not infer from context');\n return fallback ?? null;\n }\n\n // Handle loading state\n if (isLoading) {\n return loading || (\n <div className=\"rbac-loading\" role=\"status\" aria-live=\"polite\">\n <span className=\"sr-only\">Checking access level...</span>\n </div>\n );\n }\n\n // Handle error state\n if (error) {\n logger.error('Access level check failed:', error);\n return fallback;\n }\n\n // Check access level\n const levelHierarchy = ['viewer', 'participant', 'planner', 'admin', 'super'];\n const userLevelIndex = accessLevel ? levelHierarchy.indexOf(accessLevel) : -1;\n const requiredLevelIndex = levelHierarchy.indexOf(minLevel);\n\n if (userLevelIndex < requiredLevelIndex) {\n return <>{fallback}</>;\n }\n\n return <>{children}</>;\n}\n\n// ============================================================================\n// SERVER ADAPTERS\n// ============================================================================\n\n/**\n * Permission Guard for Server Handlers\n * \n * Wraps a server handler with permission checking.\n * \n * @param config - Permission guard configuration\n * @param handler - Handler function to wrap\n * @returns Wrapped handler function\n * \n * @example\n * ```typescript\n * const protectedHandler = withPermissionGuard(\n * { permission: 'update:events', pageId: 'page-789' },\n * async (req, res) => {\n * // Handler logic here\n * res.json({ success: true });\n * }\n * );\n * ```\n */\nexport function withPermissionGuard<T extends any[]>(\n config: {\n permission: Permission;\n pageId?: UUID;\n },\n handler: (...args: T) => Promise<any>\n) {\n return async (...args: T): Promise<any> => {\n // Extract user context from request\n const [req] = args;\n const userId = req.user?.id;\n const organisationId = req.organisationId;\n const eventId = req.eventId;\n const appId = req.appId;\n\n if (!userId || !organisationId) {\n throw new Error('User context required for permission check');\n }\n\n // Check permission\n const { isPermitted } = await import('./api');\n const hasPermission = await isPermitted({\n userId,\n scope: { organisationId, eventId, appId },\n permission: config.permission,\n pageId: config.pageId,\n });\n\n if (!hasPermission) {\n throw new Error(`Permission denied: ${config.permission}`);\n }\n\n // Execute handler\n return handler(...args);\n };\n}\n\n/**\n * Access Level Guard for Server Handlers\n * \n * Wraps a server handler with access level checking.\n * \n * @param minLevel - Minimum access level required\n * @param handler - Handler function to wrap\n * @returns Wrapped handler function\n * \n * @example\n * ```typescript\n * const adminHandler = withAccessLevelGuard(\n * 'admin',\n * async (req, res) => {\n * // Admin-only logic here\n * res.json({ success: true });\n * }\n * );\n * ```\n */\nexport function withAccessLevelGuard<T extends any[]>(\n minLevel: 'viewer' | 'participant' | 'planner' | 'admin' | 'super',\n handler: (...args: T) => Promise<any>\n) {\n return async (...args: T): Promise<any> => {\n // Extract user context from request\n const [req] = args;\n const userId = req.user?.id;\n const organisationId = req.organisationId;\n const eventId = req.eventId;\n const appId = req.appId;\n\n if (!userId || !organisationId) {\n throw new Error('User context required for access level check');\n }\n\n // Check access level\n const { getAccessLevel } = await import('./api');\n const accessLevel = await getAccessLevel({\n userId,\n scope: { organisationId, eventId, appId },\n });\n\n const levelHierarchy = ['viewer', 'participant', 'planner', 'admin', 'super'];\n const userLevelIndex = levelHierarchy.indexOf(accessLevel);\n const requiredLevelIndex = levelHierarchy.indexOf(minLevel);\n\n if (userLevelIndex < requiredLevelIndex) {\n throw new Error(`Access level required: ${minLevel}, got: ${accessLevel}`);\n }\n\n // Execute handler\n return handler(...args);\n };\n}\n\n/**\n * Role Guard for Server Handlers\n * \n * Wraps a server handler with role-based access control.\n * This is the primary middleware for routing protection as specified in the contract.\n * \n * @param config - Role guard configuration\n * @param handler - Handler function to wrap\n * @returns Wrapped handler function\n * \n * @example\n * ```typescript\n * const adminHandler = withRoleGuard(\n * { \n * globalRoles: ['super_admin'],\n * organisationRoles: ['org_admin', 'leader'],\n * eventAppRoles: ['event_admin', 'planner']\n * },\n * async (req, res) => {\n * // Admin-only logic here\n * res.json({ success: true });\n * }\n * );\n * ```\n */\nexport function withRoleGuard<T extends any[]>(\n config: {\n globalRoles?: string[];\n organisationRoles?: string[];\n eventAppRoles?: string[];\n requireAll?: boolean;\n },\n handler: (...args: T) => Promise<any>\n) {\n return async (...args: T): Promise<any> => {\n // Extract user context from request\n const [req] = args;\n const userId = req.user?.id;\n const organisationId = req.organisationId;\n const eventId = req.eventId;\n const appId = req.appId;\n\n if (!userId || !organisationId) {\n throw new Error('User context required for role check');\n }\n\n // Check global roles first (super_admin bypasses all)\n if (config.globalRoles && config.globalRoles.length > 0) {\n const { isSuperAdmin } = await import('./api');\n const isSuper = await isSuperAdmin(userId);\n \n if (isSuper) {\n // Log bypass for super admin - only if we have a valid organisation ID\n if (organisationId) {\n const { emitAuditEvent } = await import('./audit');\n await emitAuditEvent({\n type: 'permission_check',\n userId,\n organisationId,\n eventId,\n appId,\n permission: 'bypass:all',\n decision: true,\n source: 'api',\n bypass: true,\n duration_ms: 0,\n metadata: {\n operation: 'role_guard',\n reason: 'super_admin_bypass'\n }\n });\n }\n \n return handler(...args);\n }\n }\n\n // Check organisation roles\n if (config.organisationRoles && config.organisationRoles.length > 0) {\n const { isOrganisationAdmin } = await import('./api');\n const isOrgAdmin = await isOrganisationAdmin(userId, organisationId);\n \n if (!isOrgAdmin && config.requireAll !== false) {\n throw new Error(`Organisation admin role required`);\n }\n }\n\n // Check event-app roles if event and app context provided\n if (config.eventAppRoles && config.eventAppRoles.length > 0 && eventId && appId) {\n const { isEventAdmin } = await import('./api');\n const isEventAdminUser = await isEventAdmin(userId, { organisationId, eventId, appId });\n \n if (!isEventAdminUser && config.requireAll !== false) {\n throw new Error(`Event admin role required`);\n }\n }\n\n // Log successful role check - only if we have a valid organisation ID\n if (organisationId) {\n const { emitAuditEvent } = await import('./audit');\n await emitAuditEvent({\n type: 'permission_check',\n userId,\n organisationId,\n eventId,\n appId,\n permission: 'role:check',\n decision: true,\n source: 'api',\n bypass: false,\n duration_ms: 0,\n metadata: {\n operation: 'role_guard'\n }\n });\n }\n\n // Execute handler\n return handler(...args);\n };\n}\n\n// ============================================================================\n// NEXT.JS MIDDLEWARE\n// ============================================================================\n\n/**\n * Next.js Middleware for RBAC\n * \n * Middleware that checks permissions before allowing access to pages.\n * \n * @param config - Middleware configuration\n * @returns Next.js middleware function\n * \n * @example\n * ```typescript\n * // middleware.ts\n * import { createRBACMiddleware } from '@jmruthers/pace-core/rbac';\n * \n * export default createRBACMiddleware({\n * protectedRoutes: [\n * { path: '/admin', permission: 'update:admin' },\n * { path: '/events', permission: 'read:events' },\n * ],\n * fallbackUrl: '/access-denied',\n * });\n * ```\n */\nexport function createRBACMiddleware(config: {\n protectedRoutes: Array<{\n path: string;\n permission: Permission;\n pageId?: UUID;\n }>;\n fallbackUrl?: string;\n}) {\n return async (req: { nextUrl: { pathname: string }; user?: { id: string }; organisationId?: string }, res: { redirect: (url: string) => void }, next: () => void) => {\n const { pathname } = req.nextUrl;\n const userId = req.user?.id;\n const organisationId = req.organisationId;\n\n if (!userId || !organisationId) {\n return res.redirect(config.fallbackUrl || '/login');\n }\n\n // Find matching protected route\n const protectedRoute = config.protectedRoutes.find(route => \n pathname.startsWith(route.path)\n );\n\n if (protectedRoute) {\n try {\n const { isPermitted } = await import('./api');\n const hasPermission = await isPermitted({\n userId,\n scope: { organisationId },\n permission: protectedRoute.permission,\n pageId: protectedRoute.pageId,\n });\n\n if (!hasPermission) {\n return res.redirect(config.fallbackUrl || '/access-denied');\n }\n } catch (_error) {\n // Permission check failed - error logged via RBAC logger\n return res.redirect(config.fallbackUrl || '/access-denied');\n }\n }\n\n next();\n };\n}\n\n// ============================================================================\n// EXPRESS MIDDLEWARE\n// ============================================================================\n\n/**\n * Express Middleware for RBAC\n * \n * Middleware that checks permissions for Express routes.\n * \n * @param config - Middleware configuration\n * @returns Express middleware function\n * \n * @example\n * ```typescript\n * import { createRBACExpressMiddleware } from '@jmruthers/pace-core/rbac';\n * \n * app.use(createRBACExpressMiddleware({\n * permission: 'read:api',\n * pageId: 'api-page-123',\n * }));\n * ```\n */\nexport function createRBACExpressMiddleware(config: {\n permission: Permission;\n pageId?: UUID;\n}) {\n return async (req: { user?: { id: string }; organisationId?: string; eventId?: string; appId?: string }, res: { status: (code: number) => { json: (data: object) => void } }, next: () => void) => {\n const userId = req.user?.id;\n const organisationId = req.organisationId;\n const eventId = req.eventId;\n const appId = req.appId;\n\n if (!userId || !organisationId) {\n return res.status(401).json({ error: 'User context required' });\n }\n\n try {\n const { isPermitted } = await import('./api');\n const hasPermission = await isPermitted({\n userId,\n scope: { organisationId, eventId, appId },\n permission: config.permission,\n pageId: config.pageId,\n });\n\n if (!hasPermission) {\n return res.status(403).json({ error: 'Permission denied' });\n }\n\n next();\n } catch (_error) {\n // Permission check failed - error logged via RBAC logger\n return res.status(500).json({ error: 'Permission check failed' });\n }\n };\n}\n\n// ============================================================================\n// UTILITY FUNCTIONS\n// ============================================================================\n\n/**\n * Check if a user has a permission (synchronous cache check only)\n * \n * @param userId - User ID\n * @param scope - Permission scope\n * @param permission - Permission to check\n * @param pageId - Optional page ID\n * @returns True if permission is cached and granted\n */\nexport function hasPermissionCached(\n userId: UUID,\n scope: { organisationId: UUID; eventId?: string; appId?: UUID },\n _permission: Permission,\n _pageId?: UUID\n): boolean {\n const cacheKey = RBACCache.generatePermissionKey({\n userId,\n organisationId: scope.organisationId,\n eventId: scope.eventId,\n appId: scope.appId,\n });\n \n return rbacCache.get<boolean>(cacheKey) || false;\n}\n\n/**\n * Check if a user has any of the specified permissions (synchronous cache check only)\n * \n * @param userId - User ID\n * @param scope - Permission scope\n * @param permissions - Array of permissions to check\n * @param pageId - Optional page ID\n * @returns True if any permission is cached and granted\n */\nexport function hasAnyPermissionCached(\n userId: UUID,\n scope: { organisationId: UUID; eventId?: string; appId?: UUID },\n permissions: Permission[],\n pageId?: UUID\n): boolean {\n return permissions.some(permission => \n hasPermissionCached(userId, scope, permission, pageId)\n );\n}\n\n// Import useAccessLevel for AccessLevelGuard\nimport { useAccessLevel } from './hooks';\n","/**\n * RBAC Permissions Definitions\n * @package @jmruthers/pace-core\n * @module RBAC/Permissions\n * @since 1.0.0\n * \n * This module defines all permissions used in the RBAC system.\n * All permission strings must be imported from this file to ensure consistency.\n */\n\nimport { Permission } from './types';\nimport { createLogger } from '../utils/core/logger';\n\nconst log = createLogger('RBACPermissions');\n\n// ============================================================================\n// GLOBAL PERMISSIONS\n// ============================================================================\n\nexport const GLOBAL_PERMISSIONS = {\n READ_ALL: 'read:*' as Permission,\n CREATE_ALL: 'create:*' as Permission,\n UPDATE_ALL: 'update:*' as Permission,\n DELETE_ALL: 'delete:*' as Permission,\n} as const;\n\n// ============================================================================\n// ORGANISATION PERMISSIONS\n// ============================================================================\n\nexport const ORGANISATION_PERMISSIONS = {\n // Organisation management\n READ_ORGANISATION: 'read:organisation' as Permission,\n UPDATE_ORGANISATION: 'update:organisation' as Permission,\n DELETE_ORGANISATION: 'delete:organisation' as Permission,\n \n // User management\n READ_USERS: 'read:users' as Permission,\n CREATE_USERS: 'create:users' as Permission,\n UPDATE_USERS: 'update:users' as Permission,\n DELETE_USERS: 'delete:users' as Permission,\n \n // Role management\n READ_ROLES: 'read:roles' as Permission,\n CREATE_ROLES: 'create:roles' as Permission,\n UPDATE_ROLES: 'update:roles' as Permission,\n DELETE_ROLES: 'delete:roles' as Permission,\n \n // Event management\n READ_EVENTS: 'read:events' as Permission,\n CREATE_EVENTS: 'create:events' as Permission,\n UPDATE_EVENTS: 'update:events' as Permission,\n DELETE_EVENTS: 'delete:events' as Permission,\n \n // App management\n READ_APPS: 'read:apps' as Permission,\n CREATE_APPS: 'create:apps' as Permission,\n UPDATE_APPS: 'update:apps' as Permission,\n DELETE_APPS: 'delete:apps' as Permission,\n} as const;\n\n// ============================================================================\n// EVENT-APP PERMISSIONS\n// ============================================================================\n\nexport const EVENT_APP_PERMISSIONS = {\n // Event management\n READ_EVENT: 'read:event' as Permission,\n CREATE_EVENT: 'create:event' as Permission,\n UPDATE_EVENT: 'update:event' as Permission,\n DELETE_EVENT: 'delete:event' as Permission,\n \n // App management\n READ_APP: 'read:app' as Permission,\n CREATE_APP: 'create:app' as Permission,\n UPDATE_APP: 'update:app' as Permission,\n DELETE_APP: 'delete:app' as Permission,\n \n // Team management\n READ_TEAM: 'read:team' as Permission,\n CREATE_TEAM: 'create:team' as Permission,\n UPDATE_TEAM: 'update:team' as Permission,\n DELETE_TEAM: 'delete:team' as Permission,\n \n // Team members\n READ_TEAM_MEMBERS: 'read:team.members' as Permission,\n CREATE_TEAM_MEMBERS: 'create:team.members' as Permission,\n UPDATE_TEAM_MEMBERS: 'update:team.members' as Permission,\n DELETE_TEAM_MEMBERS: 'delete:team.members' as Permission,\n \n // Event content\n READ_EVENT_CONTENT: 'read:event.content' as Permission,\n CREATE_EVENT_CONTENT: 'create:event.content' as Permission,\n UPDATE_EVENT_CONTENT: 'update:event.content' as Permission,\n DELETE_EVENT_CONTENT: 'delete:event.content' as Permission,\n \n // Event settings\n READ_EVENT_SETTINGS: 'read:event.settings' as Permission,\n CREATE_EVENT_SETTINGS: 'create:event.settings' as Permission,\n UPDATE_EVENT_SETTINGS: 'update:event.settings' as Permission,\n DELETE_EVENT_SETTINGS: 'delete:event.settings' as Permission,\n} as const;\n\n// ============================================================================\n// PAGE PERMISSIONS\n// ============================================================================\n\nexport const PAGE_PERMISSIONS = {\n // General page access\n READ_PAGE: 'read:page' as Permission,\n CREATE_PAGE: 'create:page' as Permission,\n UPDATE_PAGE: 'update:page' as Permission,\n DELETE_PAGE: 'delete:page' as Permission,\n \n // Admin pages\n READ_ADMIN: 'read:admin' as Permission,\n CREATE_ADMIN: 'create:admin' as Permission,\n UPDATE_ADMIN: 'update:admin' as Permission,\n DELETE_ADMIN: 'delete:admin' as Permission,\n \n // Dashboard pages\n READ_DASHBOARD: 'read:dashboard' as Permission,\n CREATE_DASHBOARD: 'create:dashboard' as Permission,\n UPDATE_DASHBOARD: 'update:dashboard' as Permission,\n DELETE_DASHBOARD: 'delete:dashboard' as Permission,\n \n // Settings pages\n READ_SETTINGS: 'read:settings' as Permission,\n CREATE_SETTINGS: 'create:settings' as Permission,\n UPDATE_SETTINGS: 'update:settings' as Permission,\n DELETE_SETTINGS: 'delete:settings' as Permission,\n \n // Reports pages\n READ_REPORTS: 'read:reports' as Permission,\n CREATE_REPORTS: 'create:reports' as Permission,\n UPDATE_REPORTS: 'update:reports' as Permission,\n DELETE_REPORTS: 'delete:reports' as Permission,\n} as const;\n\n// ============================================================================\n// PERMISSION GROUPS - REMOVED\n// ============================================================================\n// NOTE: Hardcoded permission groups have been removed to ensure RBAC compliance.\n// Permissions must be queried from the rbac_page_permissions database table.\n// This ensures organizations can customize their own page-level permissions.\n// The permission string constants above can still be used for TypeScript\n// type safety and autocomplete, but actual permission grants come from the database.\n\n// ============================================================================\n// PERMISSION VALIDATION\n// ============================================================================\n\n/**\n * Validate that a permission string is properly formatted\n * \n * @param permission - Permission string to validate\n * @returns True if valid, false otherwise\n */\nexport function isValidPermission(permission: string): permission is Permission {\n // Allow wildcard only at the end: read:* or read:events\n // But not: read:events* or read:*events\n // Also reject uppercase operations and resource names\n // NOTE: Only CRUD operations are allowed (read, create, update, delete)\n // Resource names must be lowercase letters, numbers, and dots only\n // Cannot start or end with dots, cannot have consecutive dots\n const pattern = /^(read|create|update|delete):[a-z0-9]+(\\.[a-z0-9]+)*$|^(read|create|update|delete):\\*$/;\n return pattern.test(permission);\n}\n\n/**\n * Get all permissions for a role - REMOVED\n * \n * @deprecated This function has been removed to ensure RBAC compliance.\n * Permissions must be queried from the rbac_page_permissions database table,\n * not hardcoded in application code. This allows organizations to customize\n * their own page-level permissions as required by the RBAC specification.\n * \n * To get permissions for a role, query the database:\n * ```typescript\n * const { data } = await supabase\n * .from('rbac_page_permissions')\n * .select('operation, allowed')\n * .eq('role_name', roleName)\n * .eq('organisation_id', organisationId)\n * .eq('allowed', true);\n * ```\n * \n * @param role - Role name\n * @returns Empty array (function deprecated)\n */\nexport function getPermissionsForRole(role: string): Permission[] {\n log.warn(\n 'getPermissionsForRole() is deprecated. ' +\n 'Permissions must be queried from rbac_page_permissions table. ' +\n `Called with role: ${role}`\n );\n return [];\n}\n\n// ============================================================================\n// EXPORTS\n// ============================================================================\n\nexport const ALL_PERMISSIONS = {\n ...GLOBAL_PERMISSIONS,\n ...ORGANISATION_PERMISSIONS,\n ...EVENT_APP_PERMISSIONS,\n ...PAGE_PERMISSIONS,\n} as const;\n\nexport type AllPermissions = typeof ALL_PERMISSIONS;\n","/**\n * RBAC Setup Validator\n * @package @jmruthers/pace-core\n * @module RBAC/Compliance/SetupValidator\n * @since 1.0.0\n * \n * This module provides utilities to validate RBAC setup state.\n */\n\nimport { getRBACConfig } from '../config';\nimport { RBACNotInitializedError } from '../errors';\n\nexport interface SetupIssue {\n type: 'not-initialized' | 'missing-config' | 'invalid-config' | 'missing-provider-context';\n message: string;\n recommendation: string;\n}\n\nexport interface ComplianceResult {\n isCompliant: boolean;\n issues: SetupIssue[];\n}\n\n/**\n * Check if RBAC system is initialized\n * \n * @returns true if RBAC is initialized, false otherwise\n */\nexport function isRBACInitialized(): boolean {\n try {\n const config = getRBACConfig();\n return config !== null && config.supabase !== null;\n } catch (error) {\n if (error instanceof RBACNotInitializedError) {\n return false;\n }\n // Re-throw unexpected errors\n throw error;\n }\n}\n\n/**\n * Get setup issues\n * \n * @returns Array of setup issues\n */\nexport function getSetupIssues(): SetupIssue[] {\n const issues: SetupIssue[] = [];\n \n const config = getRBACConfig();\n \n if (!config) {\n issues.push({\n type: 'not-initialized',\n message: 'RBAC system has not been initialized. setupRBAC() has not been called.',\n recommendation: 'Call setupRBAC(supabase) before using any RBAC features. This should be done in your main entry point (main.tsx or App.tsx) before rendering the app.'\n });\n return issues;\n }\n \n if (!config.supabase) {\n issues.push({\n type: 'missing-config',\n message: 'RBAC configuration is missing Supabase client.',\n recommendation: 'Ensure setupRBAC() is called with a valid Supabase client instance.'\n });\n }\n \n return issues;\n}\n\n/**\n * Check if UnifiedAuthProvider context is available\n * \n * This function can be called from React components to check if the context\n * is available. It uses React's useContext hook, so it must be called from\n * within a React component.\n * \n * @returns true if context is available, false otherwise\n * @throws Error if called outside React component context\n */\nexport function isUnifiedAuthContextAvailable(): boolean {\n try {\n // This will only work if called from within a React component\n // We can't import useContext here directly as it would require React\n // Instead, we'll check if the context can be accessed\n // Note: This is a best-effort check and may not work in all scenarios\n return true; // Context availability is checked by useUnifiedAuth hook itself\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Get provider context setup issues\n * \n * This provides guidance on common provider setup problems.\n * Actual context availability must be checked at component level.\n * \n * @returns Array of setup issues related to provider context\n */\nexport function getProviderContextIssues(): SetupIssue[] {\n const issues: SetupIssue[] = [];\n \n // Check if RBAC is initialized (prerequisite for provider context)\n if (!isRBACInitialized()) {\n issues.push({\n type: 'not-initialized',\n message: 'RBAC system must be initialized before provider context can be used.',\n recommendation: 'Call setupRBAC(supabase) before rendering UnifiedAuthProvider.'\n });\n }\n \n return issues;\n}\n\n/**\n * Validate RBAC setup\n * \n * @returns Compliance result with issues and recommendations\n */\nexport function validateRBACSetup(): ComplianceResult {\n const issues = getSetupIssues();\n const providerIssues = getProviderContextIssues();\n \n return {\n isCompliant: issues.length === 0 && providerIssues.length === 0,\n issues: [...issues, ...providerIssues]\n };\n}\n\n","/**\n * Runtime Compliance Checking\n * @package @jmruthers/pace-core\n * @module RBAC/Compliance/RuntimeCompliance\n * @since 1.0.0\n * \n * This module provides runtime compliance checking utilities.\n */\n\nimport { validateRBACSetup, SetupIssue } from './setup-validator';\nimport { getRBACLogger } from '../config';\n\nexport interface RuntimeComplianceResult {\n setup: {\n isCompliant: boolean;\n issues: SetupIssue[];\n };\n warnings: string[];\n providerContext?: {\n available: boolean;\n message?: string;\n };\n}\n\n/**\n * Check runtime compliance\n * \n * This function checks if the RBAC system is properly set up and logs warnings\n * to the console if issues are found. This is intended for development-time\n * validation only.\n * \n * @returns Runtime compliance result\n */\nexport function checkRuntimeCompliance(): RuntimeComplianceResult {\n const logger = getRBACLogger();\n const setupValidation = validateRBACSetup();\n const warnings: string[] = [];\n \n if (!setupValidation.isCompliant) {\n setupValidation.issues.forEach(issue => {\n const warning = `[RBAC Compliance] ${issue.message}\\n Recommendation: ${issue.recommendation}`;\n warnings.push(warning);\n logger.warn(warning);\n });\n }\n \n // Check for provider context issues\n const providerContextIssues = setupValidation.issues.filter(\n issue => issue.type === 'missing-provider-context' || issue.type === 'not-initialized'\n );\n \n const providerContext = providerContextIssues.length > 0 ? {\n available: false,\n message: 'UnifiedAuthProvider context may not be available. Ensure your app is wrapped with UnifiedAuthProvider from @jmruthers/pace-core.'\n } : {\n available: true\n };\n \n return {\n setup: setupValidation,\n warnings,\n providerContext\n };\n}\n\n/**\n * Validate and warn about RBAC setup issues\n * \n * This is a convenience function that checks compliance and logs warnings.\n * Call this in development mode to get early warnings about setup issues.\n */\nexport function validateAndWarn(): void {\n if (import.meta.env.MODE === 'development' || import.meta.env.DEV) {\n checkRuntimeCompliance();\n }\n}\n\n","/**\n * Database Configuration Validator\n * @package @jmruthers/pace-core\n * @module RBAC/Compliance/DatabaseValidator\n * @since 1.0.0\n * \n * This module provides utilities to validate database configuration for RBAC.\n */\n\nimport { SupabaseClient } from '@supabase/supabase-js';\nimport { Database } from '../../types/database';\n\nexport interface DatabaseIssue {\n type: 'app-not-configured' | 'app-name-mismatch' | 'pages-not-configured' | 'permissions-not-configured' | 'rls-not-active' | 'roles-not-configured';\n message: string;\n recommendation: string;\n}\n\nexport interface DatabaseComplianceResult {\n appConfigured: boolean;\n pagesConfigured: boolean;\n permissionsConfigured: boolean;\n rlsPoliciesActive: boolean;\n rolesConfigured: boolean;\n issues: DatabaseIssue[];\n recommendations: string[];\n}\n\n/**\n * Validate database configuration\n * \n * @param supabase - Supabase client\n * @param appName - Application name to validate\n * @returns Database compliance result\n */\nexport async function validateDatabaseConfiguration(\n supabase: SupabaseClient<Database>,\n appName: string\n): Promise<DatabaseComplianceResult> {\n const issues: DatabaseIssue[] = [];\n const recommendations: string[] = [];\n \n let appConfigured = false;\n let pagesConfigured = false;\n let permissionsConfigured = false;\n let rlsPoliciesActive = false;\n let rolesConfigured = false;\n \n try {\n // Check if app exists in rbac_apps\n const { data: app, error: appError } = await supabase\n .from('rbac_apps')\n .select('id, name')\n .eq('name', appName)\n .single();\n \n if (appError || !app) {\n issues.push({\n type: 'app-not-configured',\n message: `App '${appName}' not found in rbac_apps table.`,\n recommendation: `Register your app in the rbac_apps table with name '${appName}' (case-sensitive).`\n });\n } else {\n appConfigured = true;\n \n // Check if app name matches exactly\n if (app.name !== appName) {\n issues.push({\n type: 'app-name-mismatch',\n message: `App name mismatch. Database has '${app.name}', but environment variable has '${appName}'.`,\n recommendation: `Ensure VITE_APP_NAME (or NEXT_PUBLIC_APP_NAME) matches the app name in rbac_apps table exactly (case-sensitive).`\n });\n }\n \n // Check if pages are configured\n const { data: pages, error: pagesError } = await supabase\n .from('rbac_app_pages')\n .select('id')\n .eq('app_id', app.id)\n .limit(1);\n \n if (pagesError || !pages || pages.length === 0) {\n issues.push({\n type: 'pages-not-configured',\n message: `No pages found for app '${appName}' in rbac_app_pages table.`,\n recommendation: 'Register your app pages in the rbac_app_pages table. Each route/page should have an entry.'\n });\n } else {\n pagesConfigured = true;\n \n // Check if permissions are configured for pages\n const { data: permissions, error: permissionsError } = await supabase\n .from('rbac_page_permissions')\n .select('id')\n .in('page_id', pages.map(p => p.id))\n .limit(1);\n \n if (permissionsError || !permissions || permissions.length === 0) {\n issues.push({\n type: 'permissions-not-configured',\n message: `No permissions found for app '${appName}' pages in rbac_page_permissions table.`,\n recommendation: 'Configure permissions for your app pages in the rbac_page_permissions table. Each page should have permissions for different operations (read, create, update, delete).'\n });\n } else {\n permissionsConfigured = true;\n }\n }\n }\n \n // Check if RLS is enabled on RBAC tables (basic check)\n // Note: This is a simplified check - full RLS validation would require more complex queries\n try {\n // Type assertion needed because rbac_check_rls_status may not be in generated types yet\n const { data: rbacTables, error: rlsError } = await (supabase.rpc as any)('rbac_check_rls_status');\n \n if (rlsError) {\n // RLS check function might not exist, which is okay\n // We'll assume RLS is active if we can query the tables\n rlsPoliciesActive = true;\n recommendations.push('Consider adding an RLS status check function to validate RLS policies are active.');\n } else {\n rlsPoliciesActive = true;\n }\n } catch (error) {\n // RLS check function might not exist or be available\n // We'll assume RLS is active if we can query the tables\n rlsPoliciesActive = true;\n recommendations.push('Consider adding an RLS status check function to validate RLS policies are active.');\n }\n \n // Check if organisation roles exist (sample check)\n const { data: orgRoles, error: rolesError } = await supabase\n .from('rbac_organisation_roles')\n .select('id')\n .limit(1);\n \n if (rolesError) {\n issues.push({\n type: 'roles-not-configured',\n message: 'Unable to query rbac_organisation_roles table. RLS might be blocking access or table might not exist.',\n recommendation: 'Ensure rbac_organisation_roles table exists and RLS policies allow read access for authenticated users.'\n });\n } else {\n rolesConfigured = true;\n }\n \n } catch (error) {\n issues.push({\n type: 'app-not-configured',\n message: `Error validating database configuration: ${error instanceof Error ? error.message : 'Unknown error'}`,\n recommendation: 'Check your Supabase connection and ensure you have the necessary permissions to query RBAC tables.'\n });\n }\n \n return {\n appConfigured,\n pagesConfigured,\n permissionsConfigured,\n rlsPoliciesActive,\n rolesConfigured,\n issues,\n recommendations\n };\n}\n\n","/**\n * Quick Fix Suggestions for RBAC/Auth Compliance\n * @package @jmruthers/pace-core\n * @module RBAC/Compliance/QuickFixSuggestions\n * @since 1.0.0\n * \n * This module provides auto-suggest fixes for common RBAC/auth compliance issues.\n */\n\nexport interface QuickFix {\n issue: string;\n suggestion: string;\n codeExample?: string;\n migrationSteps?: string[];\n}\n\n/**\n * Get quick fix suggestions for custom auth code\n */\nexport function getCustomAuthCodeFixes(customCodeName: string, type: 'hook' | 'component' | 'util'): QuickFix {\n const fixes: Record<string, QuickFix> = {\n 'useAuth': {\n issue: `Custom ${type} '${customCodeName}' detected`,\n suggestion: `Replace with useUnifiedAuth from pace-core`,\n codeExample: `// Before\nimport { useAuth } from './hooks/useAuth';\n\n// After\nimport { useUnifiedAuth } from '@jmruthers/pace-core';`,\n migrationSteps: [\n 'Remove custom useAuth hook',\n 'Import useUnifiedAuth from @jmruthers/pace-core',\n 'Update all usages to use useUnifiedAuth',\n 'Ensure UnifiedAuthProvider wraps your app'\n ]\n },\n 'usePermissions': {\n issue: `Custom ${type} '${customCodeName}' detected`,\n suggestion: `Replace with usePermissions from pace-core`,\n codeExample: `// Before\nimport { usePermissions } from './hooks/usePermissions';\n\n// After\nimport { usePermissions } from '@jmruthers/pace-core/rbac';`,\n migrationSteps: [\n 'Remove custom usePermissions hook',\n 'Import usePermissions from @jmruthers/pace-core/rbac',\n 'Update all usages - ensure setupRBAC() has been called',\n 'Verify provider hierarchy is correct'\n ]\n },\n 'PermissionGuard': {\n issue: `Custom ${type} '${customCodeName}' detected`,\n suggestion: `Replace with PagePermissionGuard from pace-core`,\n codeExample: `// Before\nimport { PermissionGuard } from './components/PermissionGuard';\n\n// After\nimport { PagePermissionGuard } from '@jmruthers/pace-core/rbac';`,\n migrationSteps: [\n 'Remove custom PermissionGuard component',\n 'Import PagePermissionGuard from @jmruthers/pace-core/rbac',\n 'Wrap pages with PagePermissionGuard',\n 'Use pageName and operation props instead of custom permission strings'\n ]\n },\n 'checkPermission': {\n issue: `Custom ${type} '${customCodeName}' detected`,\n suggestion: `Replace with isPermitted from pace-core`,\n codeExample: `// Before\nimport { checkPermission } from './utils/permissions';\n\n// After\nimport { isPermitted } from '@jmruthers/pace-core/rbac';`,\n migrationSteps: [\n 'Remove custom checkPermission utility',\n 'Import isPermitted from @jmruthers/pace-core/rbac',\n 'Update all usages to use isPermitted with proper scope',\n 'Ensure setupRBAC() has been called'\n ]\n }\n };\n \n return fixes[customCodeName] || {\n issue: `Custom ${type} '${customCodeName}' detected`,\n suggestion: `Use pace-core's equivalent instead. Check @jmruthers/pace-core documentation for the correct import.`,\n migrationSteps: [\n `Remove custom ${customCodeName} ${type}`,\n 'Find equivalent in pace-core',\n 'Import from @jmruthers/pace-core or @jmruthers/pace-core/rbac',\n 'Update all usages'\n ]\n };\n}\n\n/**\n * Get quick fix suggestions for duplicate Supabase config\n */\nexport function getDuplicateConfigFixes(): QuickFix {\n return {\n issue: 'Multiple Supabase client instantiations found',\n suggestion: 'Consolidate to a single Supabase client configuration',\n codeExample: `// Before - Multiple createClient calls\n// src/lib/supabase.ts\nexport const supabase = createClient(url, key);\n\n// src/utils/api.ts\nexport const supabase = createClient(url, key);\n\n// After - Single configuration\n// src/lib/supabase.ts\nexport const supabase = createClient(\n import.meta.env.VITE_SUPABASE_URL,\n import.meta.env.VITE_SUPABASE_ANON_KEY\n);\n\n// src/utils/api.ts\nimport { supabase } from '../lib/supabase';`,\n migrationSteps: [\n 'Create a single supabase.ts file in a shared location (e.g., src/lib/supabase.ts)',\n 'Move all Supabase client creation to this file',\n 'Export the client instance',\n 'Update all files to import from the shared location',\n 'Remove duplicate createClient calls'\n ]\n };\n}\n\n/**\n * Get quick fix suggestions for unprotected pages\n */\nexport function getUnprotectedPageFixes(): QuickFix {\n return {\n issue: 'Route/page found without PagePermissionGuard',\n suggestion: 'Wrap all routes with PagePermissionGuard',\n codeExample: `// Before\n<Route path=\"/dashboard\" element={<Dashboard />} />\n\n// After\n<Route \n path=\"/dashboard\" \n element={\n <PagePermissionGuard pageName=\"dashboard\" operation=\"read\">\n <Dashboard />\n </PagePermissionGuard>\n } \n/>`,\n migrationSteps: [\n 'Import PagePermissionGuard from @jmruthers/pace-core/rbac',\n 'Wrap each route/page component with PagePermissionGuard',\n 'Set pageName prop to match your page name in rbac_app_pages table',\n 'Set operation prop (read, create, update, or delete)',\n 'Ensure setupRBAC() has been called and providers are set up correctly'\n ]\n };\n}\n\n/**\n * Get quick fix suggestions for direct Supabase auth usage\n */\nexport function getDirectSupabaseAuthFixes(): QuickFix {\n return {\n issue: 'Direct Supabase auth usage detected',\n suggestion: 'Use UnifiedAuthProvider and useUnifiedAuth from pace-core',\n codeExample: `// Before\nimport { createClient } from '@supabase/supabase-js';\nconst supabase = createClient(url, key);\nawait supabase.auth.signInWithPassword({ email, password });\n\n// After\nimport { useUnifiedAuth } from '@jmruthers/pace-core';\nconst { signIn } = useUnifiedAuth();\nawait signIn({ email, password });`,\n migrationSteps: [\n 'Remove direct Supabase auth calls',\n 'Import useUnifiedAuth from @jmruthers/pace-core',\n 'Use the auth methods from useUnifiedAuth hook',\n 'Ensure UnifiedAuthProvider wraps your app',\n 'Update all auth-related code to use pace-core hooks'\n ]\n };\n}\n\n/**\n * Get all quick fix suggestions for a compliance issue\n */\nexport function getQuickFixes(issueType: string, details?: Record<string, any>): QuickFix[] {\n const fixes: QuickFix[] = [];\n \n switch (issueType) {\n case 'custom-auth-code':\n if (details?.name && details?.type) {\n fixes.push(getCustomAuthCodeFixes(details.name, details.type));\n }\n break;\n case 'duplicate-config':\n fixes.push(getDuplicateConfigFixes());\n break;\n case 'unprotected-pages':\n fixes.push(getUnprotectedPageFixes());\n break;\n case 'direct-supabase-auth':\n fixes.push(getDirectSupabaseAuthFixes());\n break;\n }\n \n return fixes;\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiLO,IAAK,cAAL,kBAAKA,iBAAL;AAEL,EAAAA,aAAA,2BAAwB;AACxB,EAAAA,aAAA,0BAAuB;AACvB,EAAAA,aAAA,0BAAuB;AACvB,EAAAA,aAAA,4BAAyB;AAGzB,EAAAA,aAAA,qBAAkB;AAClB,EAAAA,aAAA,sBAAmB;AACnB,EAAAA,aAAA,qBAAkB;AAClB,EAAAA,aAAA,wBAAqB;AAGrB,EAAAA,aAAA,wBAAqB;AACrB,EAAAA,aAAA,oBAAiB;AAfP,SAAAA;AAAA,GAAA;AAsBL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,oBAAiB;AACjB,EAAAA,eAAA,uBAAoB;AACpB,EAAAA,eAAA,uBAAoB;AACpB,EAAAA,eAAA,6BAA0B;AAC1B,EAAAA,eAAA,+BAA4B;AAC5B,EAAAA,eAAA,4BAAyB;AACzB,EAAAA,eAAA,qBAAkB;AAClB,EAAAA,eAAA,mBAAgB;AAChB,EAAAA,eAAA,0BAAuB;AACvB,EAAAA,eAAA,wBAAqB;AACrB,EAAAA,eAAA,oBAAiB;AACjB,EAAAA,eAAA,oBAAiB;AACjB,EAAAA,eAAA,4BAAyB;AACzB,EAAAA,eAAA,yBAAsB;AACtB,EAAAA,eAAA,+BAA4B;AAC5B,EAAAA,eAAA,4BAAyB;AACzB,EAAAA,eAAA,8BAA2B;AAC3B,EAAAA,eAAA,qBAAkB;AAClB,EAAAA,eAAA,qBAAkB;AAClB,EAAAA,eAAA,0BAAuB;AApBb,SAAAA;AAAA,GAAA;;;AC/IZ,SAAgB,eAAe,YAAY,UAAU,aAAa,SAAS,iBAAiB;AAsMxF;AAjMJ,IAAM,MAAM,aAAa,wBAAwB;A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AAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,6BAAuC;AACrD,SAAO;AAAA,IACL,OAAO;AAAA,IACP,YAAY;AAAA,IACZ,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASb,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAKO,SAAS,cAAc,WAAmB,SAA2C;AAC1F,QAAM,QAAoB,CAAC;AAE3B,UAAQ,WAAW;AAAA,IACjB,KAAK;AACH,UAAI,SAAS,QAAQ,SAAS,MAAM;AAClC,cAAM,KAAK,uBAAuB,QAAQ,MAAM,QAAQ,IAAI,CAAC;AAAA,MAC/D;AACA;AAAA,IACF,KAAK;AACH,YAAM,KAAK,wBAAwB,CAAC;AACpC;AAAA,IACF,KAAK;AACH,YAAM,KAAK,wBAAwB,CAAC;AACpC;AAAA,IACF,KAAK;AACH,YAAM,KAAK,2BAA2B,CAAC;AACvC;AAAA,EACJ;AAEA,SAAO;AACT;","names":["RPCFunction","RBACErrorCode","useMemo","useEffect","useState","jsx","useMemo","useState","useEffect","logger","error","createContext","useContext","useState","useCallback","useMemo","useEffect","jsx","createContext","useState","useMemo","useCallback","logger","useEffect","useContext","useMemo","useEffect","useState","Fragment","jsx","jsxs","log","DefaultAccessDenied","DefaultLoading","useState","useEffect","error","useMemo","logger","useMemo","useCallback","useEffect","useState","createContext","useContext","jsx","jsxs","createContext","useState","useMemo","useCallback","useEffect","logger","useContext","createContext","useContext","useState","useCallback","useMemo","useEffect","jsx","createContext","useState","useMemo","useCallback","useEffect","logger","useContext","useMemo","useEffect","useState","Fragment","jsx","jsxs","DefaultAccessDenied","DefaultLoading","useState","useEffect","error","useMemo","logger","useMemo","useCallback","useEffect","useState","jsx","jsxs","useState","useMemo","useCallback","logger","useEffect","Fragment","jsx","logger","error","isPermitted","hasPermission","getAccessLevel","emitAuditEvent","log","logger"]}