adula 2.1.0 → 2.3.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 (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -28,7 +28,7 @@ function matrixFields(resource) {
28
28
  key,
29
29
  label: field.label,
30
30
  type: field.type,
31
- conditionable: !['hasMany', 'json', 'attachment'].includes(field.type),
31
+ conditionable: !['hasMany', 'manyToMany', 'multiSelect', 'json', 'attachment'].includes(field.type),
32
32
  ...(field.type === 'user' ? { actor: true } : {}),
33
33
  }));
34
34
  }
@@ -132,7 +132,7 @@ export class RolesAdmin {
132
132
  if (role.key === key)
133
133
  return;
134
134
  if (role.key)
135
- throw new AdulaError(409, 'E_ROLE_KEY_FIXED', 'مفتاح الدور ثابت بعد تعيينه لأن تدفقات العمل والوحدات تعتمد عليه');
135
+ throw new AdulaError(409, 'E_ROLE_KEY_FIXED', 'مفتاح الدور ثابت بعد تعيينه لأن تدفقات العمل والتطبيقات تعتمد عليه');
136
136
  if (await trx('roles').where('key', key).whereNot('id', id).first())
137
137
  throw new AdulaError(409, 'E_ROLE_KEY_EXISTS', 'يوجد دور بهذا المفتاح');
138
138
  await trx('roles').where('id', id).update({ key });
@@ -149,7 +149,9 @@ export class RolesAdmin {
149
149
  const name = roleName(value);
150
150
  return this.db.transaction(async (trx) => {
151
151
  const role = await this.find(trx, id);
152
- if (role.name === 'administrator' && name !== role.name)
152
+ // adula:install finds the bootstrap role by its key; a role installed before keys
153
+ // existed is still found by its name, so that name stays until adula:install keys it.
154
+ if (role.name === 'administrator' && !role.key && name !== role.name)
153
155
  throw new AdulaError(409, 'E_BOOTSTRAP_ROLE', 'اسم دور مدير النظام الأساسي محمي لاستعادة الوصول عند الحاجة');
154
156
  if (await trx('roles').where('name', name).whereNot('id', id).first())
155
157
  throw new AdulaError(409, 'E_ROLE_EXISTS', 'يوجد دور بهذا الاسم');
@@ -198,12 +200,12 @@ export class RolesAdmin {
198
200
  const resources = this.registry.all();
199
201
  const union = ACTION_ORDER.filter((action) => resources.some((resource) => resource.actions.includes(action)));
200
202
  return {
201
- actions: [...union, 'invite', 'manage'],
203
+ actions: [...union, 'invite', 'use', 'manage'],
202
204
  subjects: [
203
205
  {
204
206
  name: 'all',
205
207
  label: ALL_SUBJECT_LABEL,
206
- actions: [...union, 'invite', 'manage'],
208
+ actions: [...union, 'invite', 'use', 'manage'],
207
209
  fields: [],
208
210
  conditionFields: [],
209
211
  },
@@ -214,6 +216,14 @@ export class RolesAdmin {
214
216
  fields: [],
215
217
  conditionFields: [],
216
218
  },
219
+ {
220
+ // Takes effect only through a deployment-wide role assignment (ADR 052).
221
+ name: 'core.ai',
222
+ label: { ar: 'المساعد الذكي', en: 'AI assistant' },
223
+ actions: ['use'],
224
+ fields: [],
225
+ conditionFields: [],
226
+ },
217
227
  ...resources.map((resource) => {
218
228
  const fields = matrixFields(resource);
219
229
  return {
@@ -368,7 +378,7 @@ export class RolesAdmin {
368
378
  validateRule(input) {
369
379
  const subject = typeof input.subject === 'string' ? input.subject : '';
370
380
  let resource;
371
- if (subject !== 'all' && subject !== 'core.users') {
381
+ if (subject !== 'all' && subject !== 'core.users' && subject !== 'core.ai') {
372
382
  try {
373
383
  resource = this.registry.get(subject);
374
384
  }
@@ -379,9 +389,16 @@ export class RolesAdmin {
379
389
  const action = typeof input.action === 'string' ? input.action : '';
380
390
  const allowed = subject === 'core.users'
381
391
  ? ['invite', 'manage']
382
- : resource
383
- ? [...resource.actions, 'manage']
384
- : [...new Set(this.registry.all().flatMap((r) => [...r.actions])), 'invite', 'manage'];
392
+ : subject === 'core.ai'
393
+ ? ['use']
394
+ : resource
395
+ ? [...resource.actions, 'manage']
396
+ : [
397
+ ...new Set(this.registry.all().flatMap((r) => [...r.actions])),
398
+ 'invite',
399
+ 'use',
400
+ 'manage',
401
+ ];
385
402
  if (!allowed.includes(action))
386
403
  throw new AdulaError(422, 'E_RULE_ACTION', 'الإجراء غير متاح لهذا الكيان');
387
404
  const inverted = Boolean(input.inverted);
@@ -1,11 +1,13 @@
1
1
  import type { Knex } from 'knex';
2
2
  import type { ResourceRegistry } from '../resource/registry.js';
3
3
  import { type Actor } from '../auth/ability.js';
4
+ import { type ListFilterValue } from '../admin/resource/query.js';
4
5
  export type SavedViewQuery = {
5
6
  search?: string;
6
7
  sort?: string;
7
8
  direction?: 'asc' | 'desc';
8
- filters?: Record<string, string | number | boolean | null>;
9
+ /** Equality values or the operator objects of ADR 046 ({ in }, { gte, lte }, { empty }). */
10
+ filters?: Record<string, ListFilterValue>;
9
11
  };
10
12
  export type SavedView = {
11
13
  id: number;
@@ -31,6 +33,11 @@ export declare class SavedViews {
31
33
  shared?: boolean;
32
34
  }): Promise<SavedView>;
33
35
  remove(name: string, actor: Actor, id: number): Promise<void>;
36
+ /**
37
+ * Saved views are personal preferences and are not audited for their owner; a change
38
+ * made by an administrator impersonating the owner is recorded with both identities.
39
+ */
40
+ private auditImpersonation;
34
41
  private authorize;
35
42
  /** Returns null for a stored view the resource no longer supports; throws on user input. */
36
43
  private sanitize;
@@ -1,10 +1,30 @@
1
1
  import { buildAbility } from '../auth/ability.js';
2
2
  import { AdulaError } from '../admin/errors.js';
3
3
  import { canQueryField } from '../admin/resource_service.js';
4
+ import { logActivity } from './activity.js';
5
+ import { ActorStore } from '../auth/actor_store.js';
6
+ import { filterCondition } from '../admin/resource/query.js';
4
7
  const NAME_LIMIT = 60;
5
8
  const VIEW_LIMIT = 50;
6
9
  /** Shared views are visible to every viewer of a resource; cap them per resource. */
7
10
  const SHARED_LIMIT = 100;
11
+ const ACTIVITY_RESOURCE = 'core.saved_views';
12
+ /** The fields a view queries: its sort, its filters and, with a search, every searchable field. */
13
+ function queriedKeys(resource, query) {
14
+ return [
15
+ ...(query.sort ? [query.sort] : []),
16
+ ...Object.keys(query.filters ?? {}),
17
+ ...(query.search
18
+ ? Object.entries(resource.fields)
19
+ .filter(([, field]) => field.searchable)
20
+ .map(([key]) => key)
21
+ : []),
22
+ ];
23
+ }
24
+ /** Publishing a view to every reader takes the right to change the resource's records. */
25
+ function canShare(resource, ability) {
26
+ return resource.actions.includes('update') && ability.can('update', resource.name);
27
+ }
8
28
  /**
9
29
  * A saved view is stored user input that later drives a list query, so every key
10
30
  * is validated against the resource definition before it is written and again
@@ -19,7 +39,7 @@ export class SavedViews {
19
39
  this.registry = registry;
20
40
  }
21
41
  async list(name, actor) {
22
- const { resource } = this.authorize(name, actor);
42
+ const { resource, ability } = this.authorize(name, actor);
23
43
  // Own views first, so colleagues' shared views can never crowd them out.
24
44
  const rows = await this.db('saved_views')
25
45
  .where('resource', resource.name)
@@ -27,20 +47,39 @@ export class SavedViews {
27
47
  .orderByRaw('(user_id = ?) DESC', [actor.id])
28
48
  .orderBy('name')
29
49
  .limit(VIEW_LIMIT + SHARED_LIMIT);
30
- return rows.flatMap((row) => {
50
+ // A colleague's shared view reaches this reader only while its author may still share
51
+ // it: views published by read-only users before sharing required `update` stay private.
52
+ const authors = new Map();
53
+ const store = new ActorStore(this.db, this.registry);
54
+ const mayShare = (userId) => {
55
+ if (!authors.has(userId))
56
+ authors.set(userId, store
57
+ .load(userId)
58
+ .then((author) => canShare(resource, buildAbility(author.rules, this.registry.all()))));
59
+ return authors.get(userId);
60
+ };
61
+ const views = [];
62
+ for (const row of rows) {
63
+ const own = Number(row.user_id) === actor.id;
31
64
  const query = this.sanitize(resource, row.query);
32
- return query
33
- ? [
34
- {
35
- id: Number(row.id),
36
- name: String(row.name),
37
- query,
38
- shared: Boolean(row.shared),
39
- own: Number(row.user_id) === actor.id,
40
- },
41
- ]
42
- : [];
43
- });
65
+ if (!query)
66
+ continue;
67
+ // Another user's view whose sort, filters or search touch a field this reader may not
68
+ // query would hand over that user's stored values on it (and the list refuses it).
69
+ if (!own &&
70
+ !queriedKeys(resource, query).every((key) => canQueryField(resource, actor, ability, key)))
71
+ continue;
72
+ if (!own && !(await mayShare(Number(row.user_id))))
73
+ continue;
74
+ views.push({
75
+ id: Number(row.id),
76
+ name: String(row.name),
77
+ query,
78
+ shared: Boolean(row.shared),
79
+ own,
80
+ });
81
+ }
82
+ return views;
44
83
  }
45
84
  async save(name, actor, input) {
46
85
  const { resource, ability } = this.authorize(name, actor);
@@ -49,19 +88,14 @@ export class SavedViews {
49
88
  throw new AdulaError(422, 'E_VIEW_NAME', 'اسم العرض مطلوب ولا يتجاوز 60 حرفاً');
50
89
  const query = this.sanitize(resource, input.query, true);
51
90
  // A view may only query what its author may query; stored filters must not probe hidden fields.
52
- const queried = [
53
- ...(query.sort ? [query.sort] : []),
54
- ...Object.keys(query.filters ?? {}),
55
- ...(query.search
56
- ? Object.entries(resource.fields)
57
- .filter(([, field]) => field.searchable)
58
- .map(([key]) => key)
59
- : []),
60
- ];
61
- for (const key of queried)
91
+ for (const key of queriedKeys(resource, query))
62
92
  if (!canQueryField(resource, actor, ability, key))
63
93
  throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `لا يمكنك الاستعلام بهذا الحقل: ${key}`);
64
94
  const shared = input.shared === true;
95
+ // A shared view reaches every reader of the resource; publishing one takes the right to
96
+ // change its records, so read-only roles cannot push views into other users' lists.
97
+ if (shared && !canShare(resource, ability))
98
+ throw new AdulaError(403, 'E_FORBIDDEN', 'مشاركة العرض تتطلب صلاحية تعديل هذا الكيان');
65
99
  const existing = await this.db('saved_views')
66
100
  .where({ user_id: actor.id, resource: resource.name, name: label })
67
101
  .first('id', 'shared');
@@ -90,6 +124,11 @@ export class SavedViews {
90
124
  const [row] = existing
91
125
  ? await this.db('saved_views').where('id', existing.id).update(values).returning('*')
92
126
  : await this.db('saved_views').insert(values).returning('*');
127
+ await this.auditImpersonation(actor, Number(row.id), 'saved_view_saved', {
128
+ resource: resource.name,
129
+ name: label,
130
+ shared,
131
+ });
93
132
  return { id: Number(row.id), name: label, query, shared, own: true };
94
133
  }
95
134
  async remove(name, actor, id) {
@@ -99,6 +138,23 @@ export class SavedViews {
99
138
  .del();
100
139
  if (!removed)
101
140
  throw new AdulaError(404, 'E_VIEW_NOT_FOUND', 'العرض المحفوظ غير موجود');
141
+ await this.auditImpersonation(actor, id, 'saved_view_removed', { resource: resource.name });
142
+ }
143
+ /**
144
+ * Saved views are personal preferences and are not audited for their owner; a change
145
+ * made by an administrator impersonating the owner is recorded with both identities.
146
+ */
147
+ async auditImpersonation(actor, viewId, action, changes) {
148
+ if (!actor.impersonatorId)
149
+ return;
150
+ await logActivity(this.db, {
151
+ resource: ACTIVITY_RESOURCE,
152
+ recordId: viewId,
153
+ actorId: actor.id,
154
+ impersonatorId: actor.impersonatorId,
155
+ action,
156
+ changes,
157
+ });
102
158
  }
103
159
  authorize(name, actor) {
104
160
  const resource = this.registry.get(name);
@@ -152,8 +208,17 @@ export class SavedViews {
152
208
  if (entry !== null &&
153
209
  typeof entry !== 'string' &&
154
210
  typeof entry !== 'number' &&
155
- typeof entry !== 'boolean')
156
- return reject('E_VIEW_QUERY', `قيمة التصفية غير صالحة: ${key}`);
211
+ typeof entry !== 'boolean') {
212
+ // An operator object is checked exactly as the list will check it.
213
+ try {
214
+ filterCondition(key, resource.fields[key], entry);
215
+ }
216
+ catch {
217
+ return reject('E_VIEW_QUERY', `قيمة التصفية غير صالحة: ${key}`);
218
+ }
219
+ filters[key] = JSON.parse(JSON.stringify(entry));
220
+ continue;
221
+ }
157
222
  filters[key] = entry;
158
223
  }
159
224
  if (Object.keys(filters).length)
@@ -0,0 +1,32 @@
1
+ import type { Knex } from 'knex';
2
+ import type { ResourceRegistry } from '../resource/registry.js';
3
+ export type SequenceRow = {
4
+ key: string;
5
+ /** The last issued value (0 before the first number); digits, since the column is bigint. */
6
+ value: string;
7
+ /** The number the next record receives, formatted exactly like `sequence()`. */
8
+ next: string;
9
+ /** Registered resource fields numbered by this sequence. */
10
+ fields: {
11
+ resource: string;
12
+ field: string;
13
+ label: string;
14
+ }[];
15
+ };
16
+ /**
17
+ * Administration of document numbering (sequences table). A sequence can only move forward:
18
+ * moving it back would issue numbers that records already carry. The key and its format are
19
+ * fixed by the resource field (`sequence: 'ORD'` issues ORD-000001), so only the next value
20
+ * changes. Changes are audited as core.sequences with record id 0 and the key in the changes.
21
+ */
22
+ export declare class SequencesAdmin {
23
+ private db;
24
+ private registry?;
25
+ constructor(db: Knex, registry?: ResourceRegistry | undefined);
26
+ private fields;
27
+ /** Stored sequences and those declared by registered fields that have not issued a number yet. */
28
+ list(): Promise<SequenceRow[]>;
29
+ /** Sets the value the next record receives; it must be ahead of the last issued value. */
30
+ setNext(actorId: number, key: unknown, next: unknown): Promise<SequenceRow>;
31
+ private toRow;
32
+ }
@@ -0,0 +1,97 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ import { formatSequence } from '../services/settings.js';
3
+ import { logActivity } from './activity.js';
4
+ const RESOURCE = 'core.sequences';
5
+ const KEY = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
6
+ function sequenceKey(value) {
7
+ if (typeof value !== 'string' || !KEY.test(value))
8
+ throw new AdulaError(404, 'E_SEQUENCE_NOT_FOUND', 'التسلسل غير موجود');
9
+ return value;
10
+ }
11
+ function nextValue(value) {
12
+ const text = typeof value === 'number' ? String(value) : value;
13
+ if (typeof text !== 'string' || !/^\d{1,18}$/.test(text.trim()) || BigInt(text.trim()) < 1n)
14
+ throw new AdulaError(422, 'E_SEQUENCE_VALUE', 'الرقم التالي يجب أن يكون عدداً صحيحاً موجباً');
15
+ return BigInt(text.trim());
16
+ }
17
+ /**
18
+ * Administration of document numbering (sequences table). A sequence can only move forward:
19
+ * moving it back would issue numbers that records already carry. The key and its format are
20
+ * fixed by the resource field (`sequence: 'ORD'` issues ORD-000001), so only the next value
21
+ * changes. Changes are audited as core.sequences with record id 0 and the key in the changes.
22
+ */
23
+ export class SequencesAdmin {
24
+ db;
25
+ registry;
26
+ constructor(db, registry) {
27
+ this.db = db;
28
+ this.registry = registry;
29
+ }
30
+ fields() {
31
+ return (this.registry?.all() ?? []).flatMap((resource) => Object.entries(resource.fields).flatMap(([field, definition]) => definition.sequence
32
+ ? [
33
+ {
34
+ key: definition.sequence,
35
+ resource: resource.name,
36
+ field,
37
+ label: definition.label.ar,
38
+ },
39
+ ]
40
+ : []));
41
+ }
42
+ /** Stored sequences and those declared by registered fields that have not issued a number yet. */
43
+ async list() {
44
+ const rows = await this.db('sequences').select('key', 'value');
45
+ const values = new Map(rows.map((row) => [String(row.key), BigInt(row.value)]));
46
+ const fields = this.fields();
47
+ for (const field of fields)
48
+ if (!values.has(field.key))
49
+ values.set(field.key, 0n);
50
+ return [...values.keys()].sort().map((key) => this.toRow(key, values.get(key), fields));
51
+ }
52
+ /** Sets the value the next record receives; it must be ahead of the last issued value. */
53
+ async setNext(actorId, key, next) {
54
+ const name = sequenceKey(key);
55
+ const target = nextValue(next);
56
+ const fields = this.fields();
57
+ return this.db.transaction(async (trx) => {
58
+ let row = await trx('sequences').where('key', name).forUpdate().first('value');
59
+ if (!row) {
60
+ if (!fields.some((field) => field.key === name))
61
+ throw new AdulaError(404, 'E_SEQUENCE_NOT_FOUND', 'التسلسل غير موجود');
62
+ await trx('sequences').insert({ key: name, value: 0 }).onConflict('key').ignore();
63
+ row = await trx('sequences').where('key', name).forUpdate().first('value');
64
+ }
65
+ const current = BigInt(row.value);
66
+ if (target <= current)
67
+ throw new AdulaError(422, 'E_SEQUENCE_BACKWARD', `لا يمكن إرجاع الترقيم: آخر رقم صدر هو ${formatSequence(name, current)}، والرجوع يكرر أرقاماً تحملها سجلات قائمة. اختر رقماً أكبر من ${current}.`);
68
+ if (target === current + 1n)
69
+ return this.toRow(name, current, fields);
70
+ await trx('sequences')
71
+ .where('key', name)
72
+ .update({ value: (target - 1n).toString() });
73
+ await logActivity(trx, {
74
+ resource: RESOURCE,
75
+ recordId: 0,
76
+ actorId,
77
+ action: 'adjust',
78
+ changes: {
79
+ key: name,
80
+ from: formatSequence(name, current + 1n),
81
+ to: formatSequence(name, target),
82
+ },
83
+ });
84
+ return this.toRow(name, target - 1n, fields);
85
+ });
86
+ }
87
+ toRow(key, value, fields) {
88
+ return {
89
+ key,
90
+ value: value.toString(),
91
+ next: formatSequence(key, value + 1n),
92
+ fields: fields
93
+ .filter((field) => field.key === key)
94
+ .map(({ resource, field, label }) => ({ resource, field, label })),
95
+ };
96
+ }
97
+ }
@@ -18,6 +18,11 @@ export type SettingInput = {
18
18
  export declare const SETTING_SCOPES: SettingScope[];
19
19
  export declare const PROTECTED_SETTING_KEYS: string[];
20
20
  export declare function isProtectedSetting(key: string): boolean;
21
+ /**
22
+ * Settings that hold a sealed secret (`channels.*`, `ai.*`, `mail.smtp`, written by their own
23
+ * section). The settings screen lists them read-only and never returns the sealed value.
24
+ */
25
+ export declare function isSealedSetting(key: string): boolean;
21
26
  export declare function parseSettingValue(text: string): unknown;
22
27
  export declare class SettingsAdmin {
23
28
  private db;
@@ -1,6 +1,7 @@
1
1
  import { AdulaError } from '../admin/errors.js';
2
2
  import { logActivity } from './activity.js';
3
3
  import { UI_PREFERENCES_KEY, validateUiPreferences } from './ui_preferences.js';
4
+ import { isPreferenceSetting } from './user_preferences.js';
4
5
  export const SETTING_SCOPES = ['system', 'org_unit', 'user'];
5
6
  // Written by install, scheduler, worker and backup verification; never by the settings screen.
6
7
  export const PROTECTED_SETTING_KEYS = [
@@ -11,7 +12,26 @@ export const PROTECTED_SETTING_KEYS = [
11
12
  ];
12
13
  const RESOURCE = 'core.settings';
13
14
  export function isProtectedSetting(key) {
14
- return (PROTECTED_SETTING_KEYS.includes(key) || key.startsWith('backup.') || key.startsWith('setup.'));
15
+ return (PROTECTED_SETTING_KEYS.includes(key) ||
16
+ key.startsWith('backup.') ||
17
+ key.startsWith('setup.') ||
18
+ // Written by the appearance section (ADR 053), which validates colours and texts.
19
+ key.startsWith('appearance.') ||
20
+ isSealedSetting(key));
21
+ }
22
+ /**
23
+ * Settings that hold a sealed secret (`channels.*`, `ai.*`, `mail.smtp`, written by their own
24
+ * section). The settings screen lists them read-only and never returns the sealed value.
25
+ */
26
+ export function isSealedSetting(key) {
27
+ return key.startsWith('channels.') || key.startsWith('ai.') || key === 'mail.smtp';
28
+ }
29
+ function presentValue(key, value) {
30
+ if (!isSealedSetting(key) || !value || typeof value !== 'object' || Array.isArray(value))
31
+ return value;
32
+ const rest = { ...value };
33
+ delete rest.secret;
34
+ return rest;
15
35
  }
16
36
  export function parseSettingValue(text) {
17
37
  try {
@@ -37,10 +57,13 @@ function toRow(row) {
37
57
  key: String(row.key),
38
58
  scope: row.scope,
39
59
  scopeId: String(row.scope_id),
40
- value: row.value,
60
+ value: presentValue(String(row.key), row.value),
41
61
  readOnly: isProtectedSetting(String(row.key)),
42
62
  };
43
63
  }
64
+ function reserved() {
65
+ throw new AdulaError(403, 'E_SETTING_RESERVED', 'هذا المفتاح تفضيل شخصي يضبطه المستخدم من حسابه');
66
+ }
44
67
  export class SettingsAdmin {
45
68
  db;
46
69
  constructor(db) {
@@ -50,11 +73,14 @@ export class SettingsAdmin {
50
73
  const rows = await this.db('settings')
51
74
  .where({ scope: settingScope(scope), scope_id: scopeId })
52
75
  .orderBy('key');
53
- return rows.map(toRow);
76
+ // A user's own interface preferences are private to that user (ADR 049).
77
+ return rows.filter((row) => !isPreferenceSetting(String(row.key))).map(toRow);
54
78
  }
55
79
  async upsert(actorId, input) {
56
80
  const key = settingKey(input.key);
57
81
  const scope = settingScope(input.scope);
82
+ if (isPreferenceSetting(key))
83
+ reserved();
58
84
  if (key === UI_PREFERENCES_KEY) {
59
85
  if (scope !== 'system')
60
86
  throw new AdulaError(422, 'E_SETTING_SCOPE', 'تفضيلات الواجهة تُضبط على مستوى النظام');
@@ -87,6 +113,8 @@ export class SettingsAdmin {
87
113
  const row = await trx('settings').where('id', id).first();
88
114
  if (!row)
89
115
  throw new AdulaError(404, 'E_SETTING_NOT_FOUND', 'الإعداد غير موجود');
116
+ if (isPreferenceSetting(row.key))
117
+ reserved();
90
118
  if (isProtectedSetting(row.key))
91
119
  throw new AdulaError(403, 'E_SETTING_READ_ONLY', 'هذا المفتاح تشغيلي للقراءة فقط');
92
120
  await trx('settings').where('id', id).delete();
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The `{{name}}` placeholder of message templates (core/message_templates.ts). Print
3
+ * templates use the same delimiters with a small block grammar on top (see parseTemplate).
4
+ */
5
+ export declare const PLACEHOLDER: RegExp;
6
+ /** Longest template accepted, in characters. */
7
+ export declare const TEMPLATE_SOURCE_LIMIT = 20000;
8
+ /** A value a template tag names. Nothing else is addressable: no expressions, no paths. */
9
+ export type TemplateRef = {
10
+ kind: 'field';
11
+ key: string;
12
+ } | {
13
+ kind: 'row';
14
+ key: string;
15
+ } | {
16
+ kind: 'lines';
17
+ key: string;
18
+ column?: string;
19
+ } | {
20
+ kind: 'meta';
21
+ key: string;
22
+ } | {
23
+ kind: 'string';
24
+ value: string;
25
+ };
26
+ export type TemplateNode = {
27
+ type: 'text';
28
+ value: string;
29
+ } | {
30
+ type: 'output';
31
+ helper: string | null;
32
+ arg: TemplateRef;
33
+ source: string;
34
+ } | {
35
+ type: 'if';
36
+ test: TemplateRef;
37
+ then: TemplateNode[];
38
+ else: TemplateNode[];
39
+ source: string;
40
+ } | {
41
+ type: 'each';
42
+ group: string;
43
+ body: TemplateNode[];
44
+ source: string;
45
+ };
46
+ export declare function templateError(message: string): never;
47
+ /**
48
+ * Parses the template language shared by print templates:
49
+ *
50
+ * - `{{field.key}}`, `{{row.key}}` (inside each), `{{name}}` (document values such as id)
51
+ * - `{{helper arg}}` where arg is one of the above, `lines.group.column` or `"text"`
52
+ * - `{{#if ref}}…{{else}}…{{/if}}` and `{{#each lines.group}}…{{/each}}` (not nested)
53
+ *
54
+ * There are no expressions, no property paths beyond these and no raw output: `{{{`
55
+ * is refused. Which names exist is checked by the caller against its own schema.
56
+ */
57
+ export declare function parseTemplate(source: string): TemplateNode[];
58
+ /** Visits every tag of a parsed template, with the line group of the enclosing each. */
59
+ export declare function walkTemplate(nodes: TemplateNode[], visit: (node: Exclude<TemplateNode, {
60
+ type: 'text';
61
+ }>, group: string | null) => void, group?: string | null): void;