@directus/api 19.3.0 → 20.0.0-rc.0

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 (287) hide show
  1. package/dist/app.js +4 -4
  2. package/dist/auth/drivers/ldap.js +4 -4
  3. package/dist/auth/drivers/local.js +4 -4
  4. package/dist/auth/drivers/oauth2.js +4 -4
  5. package/dist/auth/drivers/openid.js +2 -4
  6. package/dist/cache.js +3 -0
  7. package/dist/cli/commands/bootstrap/index.js +8 -2
  8. package/dist/cli/commands/init/index.js +9 -10
  9. package/dist/cli/utils/defaults.d.ts +4 -11
  10. package/dist/cli/utils/defaults.js +7 -1
  11. package/dist/constants.d.ts +1 -1
  12. package/dist/controllers/access.d.ts +2 -0
  13. package/dist/controllers/access.js +148 -0
  14. package/dist/controllers/auth.js +5 -16
  15. package/dist/controllers/permissions.js +14 -2
  16. package/dist/controllers/policies.d.ts +2 -0
  17. package/dist/controllers/policies.js +169 -0
  18. package/dist/controllers/roles.js +22 -1
  19. package/dist/controllers/users.js +0 -55
  20. package/dist/database/errors/dialects/mysql.js +23 -23
  21. package/dist/database/get-ast-from-query/get-ast-from-query.d.ts +16 -0
  22. package/dist/database/get-ast-from-query/get-ast-from-query.js +82 -0
  23. package/dist/database/get-ast-from-query/lib/convert-wildcards.d.ts +13 -0
  24. package/dist/database/get-ast-from-query/lib/convert-wildcards.js +69 -0
  25. package/dist/database/get-ast-from-query/lib/parse-fields.d.ts +15 -0
  26. package/dist/database/get-ast-from-query/lib/parse-fields.js +190 -0
  27. package/dist/database/get-ast-from-query/utils/get-deep-query.d.ts +14 -0
  28. package/dist/database/get-ast-from-query/utils/get-deep-query.js +17 -0
  29. package/dist/database/get-ast-from-query/utils/get-related-collection.d.ts +2 -0
  30. package/dist/database/get-ast-from-query/utils/get-related-collection.js +13 -0
  31. package/dist/database/get-ast-from-query/utils/get-relation.d.ts +2 -0
  32. package/dist/database/get-ast-from-query/utils/get-relation.js +7 -0
  33. package/dist/database/helpers/fn/types.d.ts +2 -1
  34. package/dist/database/helpers/fn/types.js +1 -1
  35. package/dist/database/helpers/geometry/dialects/mssql.d.ts +1 -1
  36. package/dist/database/helpers/geometry/dialects/mssql.js +4 -2
  37. package/dist/database/helpers/geometry/dialects/mysql.js +1 -1
  38. package/dist/database/helpers/geometry/dialects/oracle.d.ts +1 -1
  39. package/dist/database/helpers/geometry/dialects/oracle.js +5 -3
  40. package/dist/database/helpers/geometry/types.d.ts +1 -1
  41. package/dist/database/helpers/geometry/types.js +4 -2
  42. package/dist/database/index.js +2 -1
  43. package/dist/database/migrations/20240619A-permissions-policies.d.ts +3 -0
  44. package/dist/database/migrations/20240619A-permissions-policies.js +163 -0
  45. package/dist/database/run-ast/lib/get-db-query.d.ts +4 -0
  46. package/dist/database/run-ast/lib/get-db-query.js +194 -0
  47. package/dist/database/run-ast/lib/parse-current-level.d.ts +7 -0
  48. package/dist/database/run-ast/lib/parse-current-level.js +41 -0
  49. package/dist/database/run-ast/run-ast.d.ts +7 -0
  50. package/dist/database/run-ast/run-ast.js +107 -0
  51. package/dist/database/{run-ast.d.ts → run-ast/types.d.ts} +3 -9
  52. package/dist/database/run-ast/types.js +1 -0
  53. package/dist/database/run-ast/utils/apply-case-when.d.ts +16 -0
  54. package/dist/database/run-ast/utils/apply-case-when.js +26 -0
  55. package/dist/database/run-ast/utils/apply-parent-filters.d.ts +3 -0
  56. package/dist/database/run-ast/utils/apply-parent-filters.js +55 -0
  57. package/dist/database/run-ast/utils/get-column-pre-processor.d.ts +10 -0
  58. package/dist/database/run-ast/utils/get-column-pre-processor.js +57 -0
  59. package/dist/database/run-ast/utils/get-field-alias.d.ts +2 -0
  60. package/dist/database/run-ast/utils/get-field-alias.js +4 -0
  61. package/dist/database/run-ast/utils/get-inner-query-column-pre-processor.d.ts +5 -0
  62. package/dist/database/run-ast/utils/get-inner-query-column-pre-processor.js +23 -0
  63. package/dist/database/run-ast/utils/merge-with-parent-items.d.ts +3 -0
  64. package/dist/database/run-ast/utils/merge-with-parent-items.js +87 -0
  65. package/dist/database/run-ast/utils/remove-temporary-fields.d.ts +3 -0
  66. package/dist/database/run-ast/utils/remove-temporary-fields.js +73 -0
  67. package/dist/extensions/lib/sandbox/generate-api-extensions-sandbox-entrypoint.d.ts +1 -1
  68. package/dist/flows.js +3 -4
  69. package/dist/middleware/authenticate.js +2 -7
  70. package/dist/middleware/cache.js +1 -1
  71. package/dist/middleware/cors.js +4 -4
  72. package/dist/middleware/respond.js +1 -1
  73. package/dist/permissions/cache.d.ts +2 -0
  74. package/dist/permissions/cache.js +23 -0
  75. package/dist/permissions/lib/fetch-permissions.d.ts +10 -0
  76. package/dist/permissions/lib/fetch-permissions.js +55 -0
  77. package/dist/permissions/lib/fetch-policies.d.ts +7 -0
  78. package/dist/permissions/lib/fetch-policies.js +28 -0
  79. package/dist/permissions/lib/fetch-roles-tree.d.ts +3 -0
  80. package/dist/permissions/lib/fetch-roles-tree.js +28 -0
  81. package/dist/{services/permissions → permissions}/lib/with-app-minimal-permissions.d.ts +1 -1
  82. package/dist/permissions/lib/with-app-minimal-permissions.js +10 -0
  83. package/dist/permissions/modules/fetch-accountability-collection-access/fetch-accountability-collection-access.d.ts +7 -0
  84. package/dist/permissions/modules/fetch-accountability-collection-access/fetch-accountability-collection-access.js +56 -0
  85. package/dist/permissions/modules/fetch-accountability-policy-globals/fetch-accountability-policy-globals.d.ts +3 -0
  86. package/dist/permissions/modules/fetch-accountability-policy-globals/fetch-accountability-policy-globals.js +16 -0
  87. package/dist/permissions/modules/fetch-allowed-collections/fetch-allowed-collections.d.ts +8 -0
  88. package/dist/permissions/modules/fetch-allowed-collections/fetch-allowed-collections.js +24 -0
  89. package/dist/permissions/modules/fetch-allowed-field-map/fetch-allowed-field-map.d.ts +9 -0
  90. package/dist/permissions/modules/fetch-allowed-field-map/fetch-allowed-field-map.js +31 -0
  91. package/dist/permissions/modules/fetch-allowed-fields/fetch-allowed-fields.d.ts +16 -0
  92. package/dist/permissions/modules/fetch-allowed-fields/fetch-allowed-fields.js +27 -0
  93. package/dist/permissions/modules/fetch-global-access/fetch-global-access.d.ts +10 -0
  94. package/dist/permissions/modules/fetch-global-access/fetch-global-access.js +23 -0
  95. package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-roles.d.ts +5 -0
  96. package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-roles.js +7 -0
  97. package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-user.d.ts +5 -0
  98. package/dist/permissions/modules/fetch-global-access/lib/fetch-global-access-for-user.js +10 -0
  99. package/dist/permissions/modules/fetch-global-access/types.d.ts +4 -0
  100. package/dist/permissions/modules/fetch-global-access/types.js +1 -0
  101. package/dist/permissions/modules/fetch-global-access/utils/fetch-global-access-for-query.d.ts +4 -0
  102. package/dist/permissions/modules/fetch-global-access/utils/fetch-global-access-for-query.js +27 -0
  103. package/dist/permissions/modules/fetch-inconsistent-field-map/fetch-inconsistent-field-map.d.ts +12 -0
  104. package/dist/permissions/modules/fetch-inconsistent-field-map/fetch-inconsistent-field-map.js +32 -0
  105. package/dist/permissions/modules/fetch-policies-ip-access/fetch-policies-ip-access.d.ts +4 -0
  106. package/dist/permissions/modules/fetch-policies-ip-access/fetch-policies-ip-access.js +29 -0
  107. package/dist/permissions/modules/process-ast/lib/extract-fields-from-children.d.ts +4 -0
  108. package/dist/permissions/modules/process-ast/lib/extract-fields-from-children.js +49 -0
  109. package/dist/permissions/modules/process-ast/lib/extract-fields-from-query.d.ts +3 -0
  110. package/dist/permissions/modules/process-ast/lib/extract-fields-from-query.js +56 -0
  111. package/dist/permissions/modules/process-ast/lib/field-map-from-ast.d.ts +4 -0
  112. package/dist/permissions/modules/process-ast/lib/field-map-from-ast.js +8 -0
  113. package/dist/permissions/modules/process-ast/lib/inject-cases.d.ts +9 -0
  114. package/dist/permissions/modules/process-ast/lib/inject-cases.js +93 -0
  115. package/dist/permissions/modules/process-ast/process-ast.d.ts +9 -0
  116. package/dist/permissions/modules/process-ast/process-ast.js +39 -0
  117. package/dist/permissions/modules/process-ast/types.d.ts +24 -0
  118. package/dist/permissions/modules/process-ast/types.js +1 -0
  119. package/dist/permissions/modules/process-ast/utils/collections-in-field-map.d.ts +2 -0
  120. package/dist/permissions/modules/process-ast/utils/collections-in-field-map.js +7 -0
  121. package/dist/permissions/modules/process-ast/utils/dedupe-access.d.ts +12 -0
  122. package/dist/permissions/modules/process-ast/utils/dedupe-access.js +30 -0
  123. package/dist/permissions/modules/process-ast/utils/extract-paths-from-query.d.ts +15 -0
  124. package/dist/permissions/modules/process-ast/utils/extract-paths-from-query.js +50 -0
  125. package/dist/permissions/modules/process-ast/utils/find-related-collection.d.ts +3 -0
  126. package/dist/permissions/modules/process-ast/utils/find-related-collection.js +9 -0
  127. package/dist/permissions/modules/process-ast/utils/flatten-filter.d.ts +3 -0
  128. package/dist/permissions/modules/process-ast/utils/flatten-filter.js +24 -0
  129. package/dist/permissions/modules/process-ast/utils/format-a2o-key.d.ts +1 -0
  130. package/dist/permissions/modules/process-ast/utils/format-a2o-key.js +3 -0
  131. package/dist/permissions/modules/process-ast/utils/get-info-for-path.d.ts +5 -0
  132. package/dist/permissions/modules/process-ast/utils/get-info-for-path.js +7 -0
  133. package/dist/permissions/modules/process-ast/utils/has-item-permissions.d.ts +2 -0
  134. package/dist/permissions/modules/process-ast/utils/has-item-permissions.js +3 -0
  135. package/dist/permissions/modules/process-ast/utils/stringify-query-path.d.ts +2 -0
  136. package/dist/permissions/modules/process-ast/utils/stringify-query-path.js +3 -0
  137. package/dist/permissions/modules/process-ast/utils/validate-path/create-error.d.ts +3 -0
  138. package/dist/permissions/modules/process-ast/utils/validate-path/create-error.js +16 -0
  139. package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-existence.d.ts +2 -0
  140. package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-existence.js +12 -0
  141. package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-permissions.d.ts +2 -0
  142. package/dist/permissions/modules/process-ast/utils/validate-path/validate-path-permissions.js +28 -0
  143. package/dist/permissions/modules/process-payload/lib/is-field-nullable.d.ts +5 -0
  144. package/dist/permissions/modules/process-payload/lib/is-field-nullable.js +12 -0
  145. package/dist/permissions/modules/process-payload/process-payload.d.ts +13 -0
  146. package/dist/permissions/modules/process-payload/process-payload.js +77 -0
  147. package/dist/permissions/modules/validate-access/lib/validate-collection-access.d.ts +12 -0
  148. package/dist/permissions/modules/validate-access/lib/validate-collection-access.js +11 -0
  149. package/dist/permissions/modules/validate-access/lib/validate-item-access.d.ts +9 -0
  150. package/dist/permissions/modules/validate-access/lib/validate-item-access.js +33 -0
  151. package/dist/permissions/modules/validate-access/validate-access.d.ts +14 -0
  152. package/dist/permissions/modules/validate-access/validate-access.js +28 -0
  153. package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-count.d.ts +1 -0
  154. package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-count.js +8 -0
  155. package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-users.d.ts +5 -0
  156. package/dist/permissions/modules/validate-remaining-admin/validate-remaining-admin-users.js +10 -0
  157. package/dist/permissions/types.d.ts +6 -0
  158. package/dist/permissions/types.js +1 -0
  159. package/dist/permissions/utils/create-default-accountability.d.ts +2 -0
  160. package/dist/permissions/utils/create-default-accountability.js +11 -0
  161. package/dist/permissions/utils/extract-required-dynamic-variable-context.d.ts +8 -0
  162. package/dist/permissions/utils/extract-required-dynamic-variable-context.js +27 -0
  163. package/dist/permissions/utils/fetch-dynamic-variable-context.d.ts +9 -0
  164. package/dist/permissions/utils/fetch-dynamic-variable-context.js +43 -0
  165. package/dist/permissions/utils/filter-policies-by-ip.d.ts +2 -0
  166. package/dist/permissions/utils/filter-policies-by-ip.js +15 -0
  167. package/dist/permissions/utils/get-unaliased-field-key.d.ts +5 -0
  168. package/dist/permissions/utils/get-unaliased-field-key.js +17 -0
  169. package/dist/permissions/utils/process-permissions.d.ts +7 -0
  170. package/dist/permissions/utils/process-permissions.js +9 -0
  171. package/dist/permissions/utils/with-cache.d.ts +10 -0
  172. package/dist/permissions/utils/with-cache.js +25 -0
  173. package/dist/services/access.d.ts +10 -0
  174. package/dist/services/access.js +43 -0
  175. package/dist/services/activity.js +22 -10
  176. package/dist/services/assets.d.ts +2 -3
  177. package/dist/services/assets.js +10 -5
  178. package/dist/services/authentication.js +18 -18
  179. package/dist/services/collections.js +18 -17
  180. package/dist/services/fields.d.ts +0 -1
  181. package/dist/services/fields.js +53 -24
  182. package/dist/services/files.d.ts +0 -4
  183. package/dist/services/files.js +10 -10
  184. package/dist/services/flows.d.ts +0 -2
  185. package/dist/services/flows.js +2 -14
  186. package/dist/services/graphql/index.d.ts +3 -3
  187. package/dist/services/graphql/index.js +126 -22
  188. package/dist/services/graphql/subscription.js +2 -4
  189. package/dist/services/import-export.js +23 -9
  190. package/dist/services/index.d.ts +3 -2
  191. package/dist/services/index.js +3 -2
  192. package/dist/services/items.d.ts +40 -14
  193. package/dist/services/items.js +182 -79
  194. package/dist/services/meta.js +60 -23
  195. package/dist/services/notifications.d.ts +0 -1
  196. package/dist/services/notifications.js +0 -7
  197. package/dist/services/operations.d.ts +0 -2
  198. package/dist/services/operations.js +2 -14
  199. package/dist/services/payload.d.ts +9 -10
  200. package/dist/services/payload.js +35 -19
  201. package/dist/services/{permissions/index.d.ts → permissions.d.ts} +5 -7
  202. package/dist/services/{permissions/index.js → permissions.js} +30 -54
  203. package/dist/services/policies.d.ts +12 -0
  204. package/dist/services/policies.js +87 -0
  205. package/dist/services/relations.d.ts +0 -6
  206. package/dist/services/relations.js +26 -29
  207. package/dist/services/roles.d.ts +4 -14
  208. package/dist/services/roles.js +56 -420
  209. package/dist/services/shares.d.ts +0 -2
  210. package/dist/services/shares.js +12 -8
  211. package/dist/services/specifications.d.ts +2 -2
  212. package/dist/services/specifications.js +39 -27
  213. package/dist/services/users.d.ts +2 -20
  214. package/dist/services/users.js +87 -190
  215. package/dist/services/utils.js +11 -7
  216. package/dist/services/versions.d.ts +0 -2
  217. package/dist/services/versions.js +34 -10
  218. package/dist/telemetry/lib/get-report.js +6 -3
  219. package/dist/telemetry/types/report.d.ts +4 -0
  220. package/dist/telemetry/utils/check-user-limits.d.ts +5 -0
  221. package/dist/telemetry/utils/check-user-limits.js +19 -0
  222. package/dist/telemetry/utils/get-filesize-sum.d.ts +5 -0
  223. package/dist/telemetry/utils/get-filesize-sum.js +7 -0
  224. package/dist/telemetry/utils/should-check-user-limits.d.ts +4 -0
  225. package/dist/telemetry/utils/should-check-user-limits.js +13 -0
  226. package/dist/types/ast.d.ts +43 -1
  227. package/dist/types/items.d.ts +11 -0
  228. package/dist/utils/apply-query.d.ts +4 -3
  229. package/dist/utils/apply-query.js +37 -8
  230. package/dist/utils/fetch-user-count/fetch-access-lookup.d.ts +17 -0
  231. package/dist/utils/fetch-user-count/fetch-access-lookup.js +22 -0
  232. package/dist/utils/fetch-user-count/fetch-access-roles.d.ts +16 -0
  233. package/dist/utils/fetch-user-count/fetch-access-roles.js +37 -0
  234. package/dist/utils/fetch-user-count/fetch-active-users.d.ts +6 -0
  235. package/dist/utils/fetch-user-count/fetch-active-users.js +3 -0
  236. package/dist/utils/fetch-user-count/fetch-user-count.d.ts +12 -0
  237. package/dist/utils/fetch-user-count/fetch-user-count.js +57 -0
  238. package/dist/utils/fetch-user-count/get-user-count-query.d.ts +20 -0
  239. package/dist/utils/fetch-user-count/get-user-count-query.js +17 -0
  240. package/dist/utils/get-accountability-for-role.js +16 -25
  241. package/dist/utils/get-accountability-for-token.js +17 -16
  242. package/dist/utils/get-cache-key.d.ts +1 -1
  243. package/dist/utils/get-cache-key.js +12 -1
  244. package/dist/utils/get-column.d.ts +2 -1
  245. package/dist/utils/get-column.js +1 -0
  246. package/dist/utils/get-graphql-type.js +1 -0
  247. package/dist/utils/get-service.d.ts +1 -1
  248. package/dist/utils/get-service.js +14 -10
  249. package/dist/utils/reduce-schema.d.ts +4 -6
  250. package/dist/utils/reduce-schema.js +14 -34
  251. package/dist/utils/validate-user-count-integrity.d.ts +13 -0
  252. package/dist/utils/validate-user-count-integrity.js +29 -0
  253. package/dist/websocket/authenticate.d.ts +0 -2
  254. package/dist/websocket/authenticate.js +0 -12
  255. package/dist/websocket/controllers/graphql.js +1 -4
  256. package/dist/websocket/controllers/hooks.js +4 -0
  257. package/dist/websocket/controllers/rest.js +0 -2
  258. package/dist/websocket/handlers/subscribe.js +0 -2
  259. package/dist/websocket/utils/items.d.ts +1 -1
  260. package/dist/websocket/utils/items.js +4 -1
  261. package/package.json +36 -35
  262. package/dist/database/run-ast.js +0 -450
  263. package/dist/middleware/check-ip.d.ts +0 -2
  264. package/dist/middleware/check-ip.js +0 -37
  265. package/dist/middleware/get-permissions.d.ts +0 -3
  266. package/dist/middleware/get-permissions.js +0 -10
  267. package/dist/services/authorization.d.ts +0 -17
  268. package/dist/services/authorization.js +0 -456
  269. package/dist/services/permissions/lib/with-app-minimal-permissions.js +0 -13
  270. package/dist/telemetry/utils/check-increased-user-limits.d.ts +0 -7
  271. package/dist/telemetry/utils/check-increased-user-limits.js +0 -22
  272. package/dist/telemetry/utils/get-role-counts-by-roles.d.ts +0 -6
  273. package/dist/telemetry/utils/get-role-counts-by-roles.js +0 -27
  274. package/dist/telemetry/utils/get-role-counts-by-users.d.ts +0 -11
  275. package/dist/telemetry/utils/get-role-counts-by-users.js +0 -34
  276. package/dist/telemetry/utils/get-user-count.d.ts +0 -8
  277. package/dist/telemetry/utils/get-user-count.js +0 -33
  278. package/dist/telemetry/utils/get-user-counts-by-roles.d.ts +0 -7
  279. package/dist/telemetry/utils/get-user-counts-by-roles.js +0 -35
  280. package/dist/utils/get-ast-from-query.d.ts +0 -13
  281. package/dist/utils/get-ast-from-query.js +0 -297
  282. package/dist/utils/get-permissions.d.ts +0 -2
  283. package/dist/utils/get-permissions.js +0 -150
  284. package/dist/utils/merge-permissions-for-share.d.ts +0 -4
  285. package/dist/utils/merge-permissions-for-share.js +0 -109
  286. package/dist/utils/merge-permissions.d.ts +0 -3
  287. package/dist/utils/merge-permissions.js +0 -95
@@ -0,0 +1,50 @@
1
+ import { isEqual, uniqWith } from 'lodash-es';
2
+ import { flattenFilter } from './flatten-filter.js';
3
+ /**
4
+ * Converts the passed Query object into a unique list of path arrays, for example:
5
+ *
6
+ * ```
7
+ * [
8
+ * ['author', 'age'],
9
+ * ['category']
10
+ * ]
11
+ * ```
12
+ */
13
+ export function extractPathsFromQuery(query) {
14
+ /**
15
+ * All nested paths used in the current query scope.
16
+ * This is generated by flattening the filters and adding in the used sort/aggregate fields.
17
+ */
18
+ const paths = [];
19
+ const readOnlyPaths = [];
20
+ if (query.filter) {
21
+ flattenFilter(readOnlyPaths, query.filter);
22
+ }
23
+ if (query.sort) {
24
+ for (const field of query.sort) {
25
+ // Sort can have dot notation fields for sorting on m2o values Sort fields can start with
26
+ // `-` to indicate descending order, which should be dropped for permissions checks
27
+ readOnlyPaths.push(field.split('.').map((field) => (field.startsWith('-') ? field.substring(1) : field)));
28
+ }
29
+ }
30
+ if (query.aggregate) {
31
+ for (const fields of Object.values(query.aggregate)) {
32
+ for (const field of fields) {
33
+ // Aggregate doesn't currently support aggregating on nested fields, but it doesn't hurt
34
+ // to standardize it in the validation layer
35
+ paths.push(field.split('.'));
36
+ }
37
+ }
38
+ }
39
+ if (query.group) {
40
+ for (const field of query.group) {
41
+ // Grouping doesn't currently support grouping on nested fields, but it doesn't hurt to
42
+ // standardize it in the validation layer
43
+ paths.push(field.split('.'));
44
+ }
45
+ }
46
+ return {
47
+ paths: uniqWith(paths, isEqual),
48
+ readOnlyPaths: uniqWith(readOnlyPaths, isEqual),
49
+ };
50
+ }
@@ -0,0 +1,3 @@
1
+ import type { SchemaOverview } from '@directus/types';
2
+ import type { CollectionKey, FieldKey } from '../types.js';
3
+ export declare function findRelatedCollection(collection: CollectionKey, field: FieldKey, schema: SchemaOverview): CollectionKey | null;
@@ -0,0 +1,9 @@
1
+ import { getRelationInfo } from '../../../../utils/get-relation-info.js';
2
+ export function findRelatedCollection(collection, field, schema) {
3
+ const { relation } = getRelationInfo(schema.relations, collection, field);
4
+ if (!relation)
5
+ return null;
6
+ const isO2m = relation.related_collection === collection;
7
+ const relatedCollectionName = isO2m ? relation.collection : relation.related_collection;
8
+ return relatedCollectionName;
9
+ }
@@ -0,0 +1,3 @@
1
+ import type { Query } from '@directus/types';
2
+ import type { FieldKey } from '../types.js';
3
+ export declare function flattenFilter(paths: FieldKey[][], filter: Query['filter']): void;
@@ -0,0 +1,24 @@
1
+ export function flattenFilter(paths, filter) {
2
+ if (!filter)
3
+ return;
4
+ const stack = [{ current: filter, path: [] }];
5
+ while (stack.length > 0) {
6
+ const { current, path } = stack.pop();
7
+ if (typeof current === 'object' && current !== null) {
8
+ // If the current nested value is an array, we ignore the array order and flatten all
9
+ // nested objects
10
+ const isArray = Array.isArray(current);
11
+ for (const key in current) {
12
+ stack.push({
13
+ current: current[key],
14
+ path: isArray ? path : [...path, key],
15
+ });
16
+ }
17
+ }
18
+ else {
19
+ paths.push(
20
+ // Ignore all operators and logical grouping in the field paths
21
+ path.filter((part) => part.startsWith('_') === false));
22
+ }
23
+ }
24
+ }
@@ -0,0 +1 @@
1
+ export declare function formatA2oKey(fieldKey: string, collection: string): string;
@@ -0,0 +1,3 @@
1
+ export function formatA2oKey(fieldKey, collection) {
2
+ return `${fieldKey}:${collection}`;
3
+ }
@@ -0,0 +1,5 @@
1
+ import type { CollectionKey, FieldMap, QueryPath } from '../types.js';
2
+ export declare function getInfoForPath(fieldMap: FieldMap, group: keyof FieldMap, path: QueryPath, collection: CollectionKey): {
3
+ collection: string;
4
+ fields: Set<string>;
5
+ };
@@ -0,0 +1,7 @@
1
+ export function getInfoForPath(fieldMap, group, path, collection) {
2
+ const pathStr = path.join('.');
3
+ if (fieldMap[group].has(pathStr) === false) {
4
+ fieldMap[group].set(pathStr, { collection, fields: new Set() });
5
+ }
6
+ return fieldMap[group].get(pathStr);
7
+ }
@@ -0,0 +1,2 @@
1
+ import type { Permission } from '@directus/types';
2
+ export declare function hasItemPermissions(permission: Permission): boolean;
@@ -0,0 +1,3 @@
1
+ export function hasItemPermissions(permission) {
2
+ return permission.permissions !== null && Object.keys(permission.permissions).length > 0;
3
+ }
@@ -0,0 +1,2 @@
1
+ import type { QueryPath } from '../types.js';
2
+ export declare function stringifyQueryPath(queryPath: QueryPath): string;
@@ -0,0 +1,3 @@
1
+ export function stringifyQueryPath(queryPath) {
2
+ return queryPath.join('.');
3
+ }
@@ -0,0 +1,3 @@
1
+ import { type DirectusError } from '@directus/errors';
2
+ export declare function createCollectionForbiddenError(path: string, collection: string): DirectusError<any>;
3
+ export declare function createFieldsForbiddenError(path: string, collection: string, fields: string[]): DirectusError<any>;
@@ -0,0 +1,16 @@
1
+ import { ForbiddenError } from '@directus/errors';
2
+ export function createCollectionForbiddenError(path, collection) {
3
+ const pathSuffix = path === '' ? 'root' : `"${path}"`;
4
+ return new ForbiddenError({
5
+ reason: `You don't have permission to access collection "${collection}" or it does not exist. Queried in ${pathSuffix}.`,
6
+ });
7
+ }
8
+ export function createFieldsForbiddenError(path, collection, fields) {
9
+ const pathSuffix = path === '' ? 'root' : `"${path}"`;
10
+ const fieldStr = fields.map((field) => `"${field}"`).join(', ');
11
+ return new ForbiddenError({
12
+ reason: fields.length === 1
13
+ ? `You don't have permission to access field ${fieldStr} in collection "${collection}" or it does not exist. Queried in ${pathSuffix}.`
14
+ : `You don't have permission to access fields ${fieldStr} in collection "${collection}" or they do not exist. Queried in ${pathSuffix}.`,
15
+ });
16
+ }
@@ -0,0 +1,2 @@
1
+ import type { SchemaOverview } from '@directus/types';
2
+ export declare function validatePathExistence(path: string, collection: string, fields: Set<string>, schema: SchemaOverview): void;
@@ -0,0 +1,12 @@
1
+ import { createCollectionForbiddenError, createFieldsForbiddenError } from './create-error.js';
2
+ export function validatePathExistence(path, collection, fields, schema) {
3
+ const collectionInfo = schema.collections[collection];
4
+ if (collectionInfo === undefined) {
5
+ throw createCollectionForbiddenError(path, collection);
6
+ }
7
+ const requestedFields = Array.from(fields);
8
+ const nonExistentFields = requestedFields.filter((field) => collectionInfo.fields[field] === undefined);
9
+ if (nonExistentFields.length > 0) {
10
+ throw createFieldsForbiddenError(path, collection, nonExistentFields);
11
+ }
12
+ }
@@ -0,0 +1,2 @@
1
+ import type { Permission } from '@directus/types';
2
+ export declare function validatePathPermissions(path: string, permissions: Permission[], collection: string, fields: Set<string>): void;
@@ -0,0 +1,28 @@
1
+ import { createCollectionForbiddenError, createFieldsForbiddenError } from './create-error.js';
2
+ export function validatePathPermissions(path, permissions, collection, fields) {
3
+ const permissionsForCollection = permissions.filter((permission) => permission.collection === collection);
4
+ if (permissionsForCollection.length === 0) {
5
+ throw createCollectionForbiddenError(path, collection);
6
+ }
7
+ // Set of all fields that are allowed to be queried combined
8
+ const allowedFields = new Set();
9
+ for (const { fields } of permissionsForCollection) {
10
+ if (!fields) {
11
+ continue;
12
+ }
13
+ for (const field of fields) {
14
+ if (field === '*') {
15
+ // Early exit in case all fields are allowed
16
+ return;
17
+ }
18
+ allowedFields.add(field);
19
+ }
20
+ }
21
+ const requestedFields = Array.from(fields);
22
+ const forbiddenFields = allowedFields.has('*')
23
+ ? []
24
+ : requestedFields.filter((field) => allowedFields.has(field) === false);
25
+ if (forbiddenFields.length > 0) {
26
+ throw createFieldsForbiddenError(path, collection, forbiddenFields);
27
+ }
28
+ }
@@ -0,0 +1,5 @@
1
+ import type { FieldOverview } from '@directus/types';
2
+ /**
3
+ * Checks if a given field is allowed to be set to `null`.
4
+ */
5
+ export declare function isFieldNullable(field: FieldOverview): boolean;
@@ -0,0 +1,12 @@
1
+ import { GENERATE_SPECIAL } from '../../../../constants.js';
2
+ /**
3
+ * Checks if a given field is allowed to be set to `null`.
4
+ */
5
+ export function isFieldNullable(field) {
6
+ if (field.nullable)
7
+ return true;
8
+ if (field.generated)
9
+ return true;
10
+ const hasGenerateSpecial = GENERATE_SPECIAL.some((name) => field.special.includes(name));
11
+ return hasGenerateSpecial;
12
+ }
@@ -0,0 +1,13 @@
1
+ import type { Accountability, Item, PermissionsAction } from '@directus/types';
2
+ import type { Context } from '../../types.js';
3
+ export interface ProcessPayloadOptions {
4
+ accountability: Accountability;
5
+ action: PermissionsAction;
6
+ collection: string;
7
+ payload: Item;
8
+ }
9
+ /**
10
+ * @note this only validates the top-level fields. The expectation is that this function is called
11
+ * for each level of nested insert separately
12
+ */
13
+ export declare function processPayload(options: ProcessPayloadOptions, context: Context): Promise<any>;
@@ -0,0 +1,77 @@
1
+ import { ForbiddenError } from '@directus/errors';
2
+ import { validatePayload } from '@directus/utils';
3
+ import { FailedValidationError, joiValidationErrorItemToErrorExtensions } from '@directus/validation';
4
+ import { assign, difference, uniq } from 'lodash-es';
5
+ import { fetchPermissions } from '../../lib/fetch-permissions.js';
6
+ import { fetchPolicies } from '../../lib/fetch-policies.js';
7
+ import { isFieldNullable } from './lib/is-field-nullable.js';
8
+ /**
9
+ * @note this only validates the top-level fields. The expectation is that this function is called
10
+ * for each level of nested insert separately
11
+ */
12
+ export async function processPayload(options, context) {
13
+ let permissions;
14
+ let permissionValidationRules = [];
15
+ if (!options.accountability.admin) {
16
+ const policies = await fetchPolicies(options.accountability, context);
17
+ permissions = await fetchPermissions({ action: options.action, policies, collections: [options.collection], accountability: options.accountability }, context);
18
+ if (permissions.length === 0) {
19
+ throw new ForbiddenError({
20
+ reason: `You don't have permission to "${options.action}" from collection "${options.collection}" or it does not exist.`,
21
+ });
22
+ }
23
+ const fieldsAllowed = uniq(permissions.map(({ fields }) => fields ?? []).flat());
24
+ if (fieldsAllowed.includes('*') === false) {
25
+ const fieldsUsed = Object.keys(options.payload);
26
+ const notAllowed = difference(fieldsUsed, fieldsAllowed);
27
+ if (notAllowed.length > 0) {
28
+ const fieldStr = notAllowed.map((field) => `"${field}"`).join(', ');
29
+ throw new ForbiddenError({
30
+ reason: notAllowed.length === 1
31
+ ? `You don't have permission to access field ${fieldStr} in collection "${options.collection}" or it does not exist.`
32
+ : `You don't have permission to access fields ${fieldStr} in collection "${options.collection}" or they do not exist.`,
33
+ });
34
+ }
35
+ }
36
+ permissionValidationRules = permissions.map(({ validation }) => validation);
37
+ }
38
+ const fields = Object.values(context.schema.collections[options.collection]?.fields ?? {});
39
+ const fieldValidationRules = [];
40
+ for (const field of fields) {
41
+ if (!isFieldNullable(field)) {
42
+ const isSubmissionRequired = options.action === 'create' && field.defaultValue === null;
43
+ if (isSubmissionRequired) {
44
+ fieldValidationRules.push({
45
+ [field.field]: {
46
+ _submitted: true,
47
+ },
48
+ });
49
+ }
50
+ fieldValidationRules.push({
51
+ [field.field]: {
52
+ _nnull: true,
53
+ },
54
+ });
55
+ }
56
+ fieldValidationRules.push(field.validation);
57
+ }
58
+ const validationRules = [...fieldValidationRules, ...permissionValidationRules].filter((rule) => {
59
+ if (rule === null)
60
+ return false;
61
+ if (Object.keys(rule).length === 0)
62
+ return false;
63
+ return true;
64
+ });
65
+ if (validationRules.length > 0) {
66
+ const validationErrors = [];
67
+ validationErrors.push(...validatePayload({ _and: validationRules }, options.payload)
68
+ .map((error) => error.details.map((details) => new FailedValidationError(joiValidationErrorItemToErrorExtensions(details))))
69
+ .flat());
70
+ if (validationErrors.length > 0)
71
+ throw validationErrors;
72
+ }
73
+ if (!permissions)
74
+ return options.payload;
75
+ const presets = permissions.map((permission) => permission.presets);
76
+ return assign({}, ...presets, options.payload);
77
+ }
@@ -0,0 +1,12 @@
1
+ import type { Accountability, PermissionsAction } from '@directus/types';
2
+ import type { Context } from '../../../types.js';
3
+ export interface ValidateCollectionAccessOptions {
4
+ accountability: Accountability;
5
+ action: PermissionsAction;
6
+ collection: string;
7
+ }
8
+ /**
9
+ * Check if you have (limited) access to a given collection by making sure there's at least 1
10
+ * permission rule available for the collection and action combo
11
+ */
12
+ export declare function validateCollectionAccess(options: ValidateCollectionAccessOptions, context: Context): Promise<boolean>;
@@ -0,0 +1,11 @@
1
+ import { fetchPermissions } from '../../../lib/fetch-permissions.js';
2
+ import { fetchPolicies } from '../../../lib/fetch-policies.js';
3
+ /**
4
+ * Check if you have (limited) access to a given collection by making sure there's at least 1
5
+ * permission rule available for the collection and action combo
6
+ */
7
+ export async function validateCollectionAccess(options, context) {
8
+ const policies = await fetchPolicies(options.accountability, context);
9
+ const permissions = await fetchPermissions({ action: options.action, policies, collections: [options.collection], accountability: options.accountability }, context);
10
+ return permissions.length > 0;
11
+ }
@@ -0,0 +1,9 @@
1
+ import type { Accountability, PermissionsAction, PrimaryKey } from '@directus/types';
2
+ import type { Context } from '../../../types.js';
3
+ export interface ValidateItemAccessOptions {
4
+ accountability: Accountability;
5
+ action: PermissionsAction;
6
+ collection: string;
7
+ primaryKeys: PrimaryKey[];
8
+ }
9
+ export declare function validateItemAccess(options: ValidateItemAccessOptions, context: Context): Promise<boolean>;
@@ -0,0 +1,33 @@
1
+ import { getAstFromQuery } from '../../../../database/get-ast-from-query/get-ast-from-query.js';
2
+ import { runAst } from '../../../../database/run-ast/run-ast.js';
3
+ import { processAst } from '../../process-ast/process-ast.js';
4
+ export async function validateItemAccess(options, context) {
5
+ const primaryKeyField = context.schema.collections[options.collection]?.primary;
6
+ if (!primaryKeyField) {
7
+ throw new Error(`Cannot find primary key for collection "${options.collection}"`);
8
+ }
9
+ // When we're looking up access to specific items, we have to read them from the database to
10
+ // make sure you are allowed to access them.
11
+ const query = {
12
+ // We don't actually need any of the field data, just want to know if we can read the item as
13
+ // whole or not
14
+ fields: [],
15
+ limit: options.primaryKeys.length,
16
+ filter: {
17
+ [primaryKeyField]: {
18
+ _in: options.primaryKeys,
19
+ },
20
+ },
21
+ };
22
+ const ast = await getAstFromQuery({
23
+ accountability: options.accountability,
24
+ query,
25
+ collection: options.collection,
26
+ }, context);
27
+ await processAst({ ast, ...options }, context);
28
+ const items = await runAst(ast, context.schema, { knex: context.knex });
29
+ if (items && items.length === options.primaryKeys.length) {
30
+ return true;
31
+ }
32
+ return false;
33
+ }
@@ -0,0 +1,14 @@
1
+ import type { Accountability, PermissionsAction, PrimaryKey } from '@directus/types';
2
+ import type { Context } from '../../types.js';
3
+ export interface ValidateAccessOptions {
4
+ accountability: Accountability;
5
+ action: PermissionsAction;
6
+ collection: string;
7
+ primaryKeys?: PrimaryKey[];
8
+ }
9
+ /**
10
+ * Validate if the current user has access to perform action against the given collection and
11
+ * optional primary keys. This is done by reading the item from the database using the access
12
+ * control rules and checking if we got the expected result back
13
+ */
14
+ export declare function validateAccess(options: ValidateAccessOptions, context: Context): Promise<void>;
@@ -0,0 +1,28 @@
1
+ import { ForbiddenError } from '@directus/errors';
2
+ import { validateCollectionAccess } from './lib/validate-collection-access.js';
3
+ import { validateItemAccess } from './lib/validate-item-access.js';
4
+ /**
5
+ * Validate if the current user has access to perform action against the given collection and
6
+ * optional primary keys. This is done by reading the item from the database using the access
7
+ * control rules and checking if we got the expected result back
8
+ */
9
+ export async function validateAccess(options, context) {
10
+ if (options.accountability.admin === true) {
11
+ return;
12
+ }
13
+ let access;
14
+ // If primary keys are passed, we have to confirm the access by actually trying to read the items
15
+ // from the database. If no keys are passed, we can simply check if the collection+action combo
16
+ // exists within permissions
17
+ if (options.primaryKeys) {
18
+ access = await validateItemAccess(options, context);
19
+ }
20
+ else {
21
+ access = await validateCollectionAccess(options, context);
22
+ }
23
+ if (!access) {
24
+ throw new ForbiddenError({
25
+ reason: `You don't have permission to "${options.action}" from collection "${options.collection}" or it does not exist.`,
26
+ });
27
+ }
28
+ }
@@ -0,0 +1 @@
1
+ export declare function validateRemainingAdminCount(count: number): void;
@@ -0,0 +1,8 @@
1
+ import { UnprocessableContentError } from '@directus/errors';
2
+ export function validateRemainingAdminCount(count) {
3
+ if (count <= 0) {
4
+ throw new UnprocessableContentError({
5
+ reason: `Cannot remove the last admin user from the system`,
6
+ });
7
+ }
8
+ }
@@ -0,0 +1,5 @@
1
+ import { type FetchUserCountOptions } from '../../../utils/fetch-user-count/fetch-user-count.js';
2
+ import type { Context } from '../../types.js';
3
+ export interface ValidateRemainingAdminUsersOptions extends Pick<FetchUserCountOptions, 'excludeAccessRows' | 'excludePolicies' | 'excludeUsers' | 'excludeRoles'> {
4
+ }
5
+ export declare function validateRemainingAdminUsers(options: ValidateRemainingAdminUsersOptions, context: Context): Promise<void>;
@@ -0,0 +1,10 @@
1
+ import { fetchUserCount } from '../../../utils/fetch-user-count/fetch-user-count.js';
2
+ import { validateRemainingAdminCount } from './validate-remaining-admin-count.js';
3
+ export async function validateRemainingAdminUsers(options, context) {
4
+ const { admin } = await fetchUserCount({
5
+ ...options,
6
+ adminOnly: true,
7
+ knex: context.knex,
8
+ });
9
+ validateRemainingAdminCount(admin);
10
+ }
@@ -0,0 +1,6 @@
1
+ import type { SchemaOverview } from '@directus/types';
2
+ import type { Knex } from 'knex';
3
+ export interface Context {
4
+ schema: SchemaOverview;
5
+ knex: Knex;
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import type { Accountability } from '@directus/types';
2
+ export declare function createDefaultAccountability(overrides?: Partial<Accountability>): Accountability;
@@ -0,0 +1,11 @@
1
+ export function createDefaultAccountability(overrides) {
2
+ return {
3
+ role: null,
4
+ user: null,
5
+ roles: [],
6
+ admin: false,
7
+ app: false,
8
+ ip: null,
9
+ ...overrides,
10
+ };
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { Permission } from '@directus/types';
2
+ export interface RequiredPermissionContext {
3
+ $CURRENT_USER: Set<string>;
4
+ $CURRENT_ROLE: Set<string>;
5
+ $CURRENT_ROLES: Set<string>;
6
+ $CURRENT_POLICIES: Set<string>;
7
+ }
8
+ export declare function extractRequiredDynamicVariableContext(permissions: Permission[]): RequiredPermissionContext;
@@ -0,0 +1,27 @@
1
+ import { deepMap } from '@directus/utils';
2
+ export function extractRequiredDynamicVariableContext(permissions) {
3
+ const permissionContext = {
4
+ $CURRENT_USER: new Set(),
5
+ $CURRENT_ROLE: new Set(),
6
+ $CURRENT_ROLES: new Set(),
7
+ $CURRENT_POLICIES: new Set(),
8
+ };
9
+ for (const permission of permissions) {
10
+ deepMap(permission.permissions, extractPermissionData);
11
+ deepMap(permission.validation, extractPermissionData);
12
+ deepMap(permission.presets, extractPermissionData);
13
+ }
14
+ return permissionContext;
15
+ function extractPermissionData(val) {
16
+ for (const placeholder of [
17
+ '$CURRENT_USER',
18
+ '$CURRENT_ROLE',
19
+ '$CURRENT_ROLES',
20
+ '$CURRENT_POLICIES',
21
+ ]) {
22
+ if (typeof val === 'string' && val.startsWith(`${placeholder}.`)) {
23
+ permissionContext[placeholder].add(val.replace(`${placeholder}.`, ''));
24
+ }
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,9 @@
1
+ import type { Accountability, Permission } from '@directus/types';
2
+ import type { Context } from '../types.js';
3
+ export declare const fetchDynamicVariableContext: typeof _fetchDynamicVariableContext;
4
+ export interface FetchDynamicVariableContext {
5
+ accountability: Pick<Accountability, 'user' | 'role' | 'roles'>;
6
+ policies: string[];
7
+ permissions: Permission[];
8
+ }
9
+ export declare function _fetchDynamicVariableContext(options: FetchDynamicVariableContext, context: Context): Promise<Record<string, any>>;
@@ -0,0 +1,43 @@
1
+ import { extractRequiredDynamicVariableContext } from './extract-required-dynamic-variable-context.js';
2
+ import { withCache } from './with-cache.js';
3
+ export const fetchDynamicVariableContext = withCache('permission-dynamic-variables', _fetchDynamicVariableContext, ({ policies, permissions, accountability: { user, role, roles } }) => ({
4
+ policies,
5
+ permissions,
6
+ accountability: {
7
+ user,
8
+ role,
9
+ roles,
10
+ },
11
+ }));
12
+ export async function _fetchDynamicVariableContext(options, context) {
13
+ const { UsersService } = await import('../../services/users.js');
14
+ const { RolesService } = await import('../../services/roles.js');
15
+ const { PoliciesService } = await import('../../services/policies.js');
16
+ const contextData = {};
17
+ const permissionContext = extractRequiredDynamicVariableContext(options.permissions);
18
+ if (options.accountability.user && (permissionContext.$CURRENT_USER?.size ?? 0) > 0) {
19
+ const usersService = new UsersService(context);
20
+ contextData['$CURRENT_USER'] = await usersService.readOne(options.accountability.user, {
21
+ fields: Array.from(permissionContext.$CURRENT_USER),
22
+ });
23
+ }
24
+ if (options.accountability.role && (permissionContext.$CURRENT_ROLE?.size ?? 0) > 0) {
25
+ const rolesService = new RolesService(context);
26
+ contextData['$CURRENT_ROLE'] = await rolesService.readOne(options.accountability.role, {
27
+ fields: Array.from(permissionContext.$CURRENT_ROLE),
28
+ });
29
+ }
30
+ if (options.accountability.roles.length > 0 && (permissionContext.$CURRENT_ROLES?.size ?? 0) > 0) {
31
+ const rolesService = new RolesService(context);
32
+ contextData['$CURRENT_ROLES'] = await rolesService.readMany(options.accountability.roles, {
33
+ fields: Array.from(permissionContext.$CURRENT_ROLES),
34
+ });
35
+ }
36
+ if (options.policies.length > 0 && (permissionContext.$CURRENT_POLICIES?.size ?? 0) > 0) {
37
+ const policiesService = new PoliciesService(context);
38
+ contextData['$CURRENT_POLICIES'] = await policiesService.readMany(options.policies, {
39
+ fields: Array.from(permissionContext.$CURRENT_POLICIES),
40
+ });
41
+ }
42
+ return contextData;
43
+ }
@@ -0,0 +1,2 @@
1
+ import type { AccessRow } from '../modules/process-ast/types.js';
2
+ export declare function filterPoliciesByIp(policies: AccessRow[], ip: string | null | undefined): AccessRow[];
@@ -0,0 +1,15 @@
1
+ import { ipInNetworks } from '../../utils/ip-in-networks.js';
2
+ export function filterPoliciesByIp(policies, ip) {
3
+ return policies.filter(({ policy }) => {
4
+ // Keep policies that don't have an ip address allow list configured
5
+ if (!policy.ip_access || policy.ip_access.length === 0) {
6
+ return true;
7
+ }
8
+ // If the client's IP address is unknown, we can't validate it against the allow list and will
9
+ // have to default to the more secure option of preventing access
10
+ if (!ip) {
11
+ return false;
12
+ }
13
+ return ipInNetworks(ip, policy.ip_access);
14
+ });
15
+ }
@@ -0,0 +1,5 @@
1
+ import type { FieldNode, FunctionFieldNode, NestedCollectionNode } from '../../types/index.js';
2
+ /**
3
+ * Derive the unaliased field key from the given AST node.
4
+ */
5
+ export declare function getUnaliasedFieldKey(node: NestedCollectionNode | FieldNode | FunctionFieldNode): string;