adula 2.0.0 → 2.2.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 (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,660 @@
1
+ import { createHash, randomBytes, randomInt, randomUUID, timingSafeEqual } from 'node:crypto';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ import { logActivity } from './activity.js';
4
+ import { IN_APP_CHANNEL, MAIL_CHANNEL, deliverNotificationMail, } from './message_templates.js';
5
+ import { signWebhook } from '../integrations/webhooks.js';
6
+ import { createOutboundPoster, outboundErrorCategory, resolveOutboundTarget, } from '../integrations/outbound.js';
7
+ export { IN_APP_CHANNEL, MAIL_CHANNEL };
8
+ /** A failed delivery with the category stored for it (for example `http-status:503`). */
9
+ export class ChannelDeliveryError extends Error {
10
+ category;
11
+ constructor(category) {
12
+ super(`Notification channel delivery failed: ${category}`);
13
+ this.category = category;
14
+ }
15
+ }
16
+ const CHANNEL_KEY = /^[a-z][a-z0-9_]{1,39}$/;
17
+ const BACKOFF_MINUTES = [1, 5, 30, 120];
18
+ /** Upper bound of one provider call; leases cover every call of a claimed batch. */
19
+ const CALL_TIMEOUT_SECONDS = 15;
20
+ const LEASE_MARGIN_SECONDS = 60;
21
+ const CODE_MINUTES = 10;
22
+ const CODE_ATTEMPTS = 5;
23
+ const CODE_WAIT_SECONDS = 60;
24
+ const CODE_WINDOW_HOURS = 24;
25
+ const CODE_DAILY_LIMIT = 5;
26
+ /** Pending deliveries older than this are dropped rather than sent late. */
27
+ const DELIVERY_MAX_AGE_HOURS = 24;
28
+ /** Spent confirmation rows (and their numbers) are kept this long after expiry. */
29
+ const CONFIRMATION_RETENTION_DAYS = 1;
30
+ function codeHash(salt, code) {
31
+ return createHash('sha256').update(`${salt}:${code}`).digest('hex');
32
+ }
33
+ export const CHANNEL_MAX_ATTEMPTS = BACKOFF_MINUTES.length + 1;
34
+ /** The in-app channel: the notifications row itself, listed and read in the bell. */
35
+ export function inAppChannel() {
36
+ return {
37
+ key: IN_APP_CHANNEL,
38
+ label: { ar: 'داخل التطبيق', en: 'In-app' },
39
+ delivery: 'always',
40
+ deliver: async () => { },
41
+ drain: async () => ({ sent: 0, failed: 0 }),
42
+ };
43
+ }
44
+ /** The e-mail channel over the existing notifications.mail_state queue. */
45
+ export function mailChannel(send) {
46
+ return {
47
+ key: MAIL_CHANNEL,
48
+ label: { ar: 'البريد الإلكتروني', en: 'E-mail' },
49
+ delivery: 'template',
50
+ deliver: (message, recipient) => send({
51
+ to: recipient.email,
52
+ name: recipient.name,
53
+ subject: message.subject,
54
+ text: message.text,
55
+ target: message.target,
56
+ }),
57
+ drain: (db, limit) => deliverNotificationMail(db, send, limit),
58
+ };
59
+ }
60
+ /** An international phone number: an optional + and 8–15 digits; spaces and dashes are dropped. */
61
+ export function phoneAddress(value) {
62
+ const text = typeof value === 'string' ? value.replace(/[\s\-().]/g, '') : '';
63
+ if (!/^\+?[1-9][0-9]{7,14}$/.test(text))
64
+ throw new AdulaError(422, 'E_CHANNEL_ADDRESS', 'رقم الهاتف غير صالح؛ اكتبه بالصيغة الدولية مثل +966500000000');
65
+ return text.startsWith('+') ? text : `+${text}`;
66
+ }
67
+ /**
68
+ * A pluggable HTTP provider channel (SMS, WhatsApp or any gateway): POSTs a JSON body
69
+ * `{ id, channel, to, subject, text, link?, timestamp }` signed like webhooks
70
+ * (X-Adula-Signature: sha256=hex HMAC-SHA256 over `${timestamp}.${body}`). A 2xx answer
71
+ * is sent; anything else is retried. Response bodies are never read.
72
+ */
73
+ export function httpNotificationChannel(options) {
74
+ if (!CHANNEL_KEY.test(options.key) || [IN_APP_CHANNEL, MAIL_CHANNEL].includes(options.key))
75
+ throw new Error(`Invalid notification channel key: ${options.key}`);
76
+ const post = options.post ?? createOutboundPoster();
77
+ return {
78
+ key: options.key,
79
+ label: options.label ?? CHANNEL_KIND_LABELS[options.key] ?? { ar: options.key },
80
+ delivery: 'opt-in',
81
+ address: phoneAddress,
82
+ async deliver(message, recipient, context) {
83
+ if (!options.secret)
84
+ throw new ChannelDeliveryError('secret');
85
+ if (!recipient.address)
86
+ throw new ChannelDeliveryError('address');
87
+ const timestamp = String(Math.floor(Date.now() / 1000));
88
+ const link = message.target && options.link ? options.link(message.target) : null;
89
+ const body = JSON.stringify({
90
+ id: context.deliveryId,
91
+ channel: options.key,
92
+ to: recipient.address,
93
+ subject: message.subject,
94
+ text: message.text,
95
+ ...(link ? { link } : {}),
96
+ timestamp,
97
+ });
98
+ const response = await post(options.url, {
99
+ headers: {
100
+ 'Content-Type': 'application/json',
101
+ 'User-Agent': 'adula-notifications',
102
+ 'X-Adula-Channel': options.key,
103
+ 'X-Adula-Delivery': context.deliveryId,
104
+ 'X-Adula-Timestamp': timestamp,
105
+ 'X-Adula-Signature': `sha256=${signWebhook(options.secret, timestamp, body)}`,
106
+ },
107
+ body,
108
+ signal: AbortSignal.any([context.signal, AbortSignal.timeout(options.timeoutMs ?? 10000)]),
109
+ });
110
+ if (response.status < 200 || response.status >= 300)
111
+ throw new ChannelDeliveryError(`http-status:${response.status}`);
112
+ },
113
+ };
114
+ }
115
+ /**
116
+ * The channel registry and dispatcher. The worker calls deliver() on every tick; the
117
+ * profile screen reads and writes the signed-in user's preferences through it.
118
+ * In-app is always registered.
119
+ */
120
+ export class NotificationChannels {
121
+ db;
122
+ channels = new Map();
123
+ retired;
124
+ constructor(db, channels = [],
125
+ /**
126
+ * `retired`: channel keys a successful configuration read proved are off (the
127
+ * provider is disabled or set to another kind). Their pending deliveries are skipped;
128
+ * pending rows of any other unregistered channel wait, so a failed read drops nothing.
129
+ */
130
+ options = {}) {
131
+ this.db = db;
132
+ this.retired = new Set(options.retired ?? []);
133
+ for (const channel of [inAppChannel(), ...channels]) {
134
+ if (this.channels.has(channel.key) && channel.key !== IN_APP_CHANNEL)
135
+ throw new Error(`Notification channel registered twice: ${channel.key}`);
136
+ this.channels.set(channel.key, channel);
137
+ }
138
+ for (const key of this.channels.keys())
139
+ this.retired.delete(key);
140
+ }
141
+ list() {
142
+ return [...this.channels.values()].map(({ key, label, delivery }) => ({ key, label, delivery }));
143
+ }
144
+ get(key) {
145
+ return this.channels.get(key);
146
+ }
147
+ /** The user's choice per registered channel; absent rows are the defaults. */
148
+ async preferences(userId, db = this.db) {
149
+ const rows = await db('user_notification_channels').where('user_id', userId);
150
+ const stored = new Map(rows.map((row) => [String(row.channel), row]));
151
+ return [...this.channels.values()].map((channel) => {
152
+ const row = stored.get(channel.key);
153
+ // An opt-in number counts only once confirmed by its one-time code.
154
+ const address = row?.address && (channel.delivery !== 'opt-in' || row.confirmed_at)
155
+ ? String(row.address)
156
+ : null;
157
+ return {
158
+ key: channel.key,
159
+ label: channel.label,
160
+ delivery: channel.delivery,
161
+ enabled: channel.delivery === 'always'
162
+ ? true
163
+ : channel.delivery === 'template'
164
+ ? row
165
+ ? Boolean(row.enabled)
166
+ : true
167
+ : Boolean(row?.enabled) && Boolean(address),
168
+ address,
169
+ locked: channel.delivery === 'always',
170
+ };
171
+ });
172
+ }
173
+ /** Replaces the user's choices for the channels named in the input. */
174
+ async update(userId, input) {
175
+ if (!Array.isArray(input) || input.length > 20)
176
+ throw new AdulaError(422, 'E_CHANNEL_INPUT', 'قائمة القنوات غير صالحة');
177
+ const existing = await this.db('user_notification_channels').where('user_id', userId);
178
+ // Only confirmed numbers count; a row written before confirmations existed has none.
179
+ const stored = new Map(existing.map((row) => [
180
+ String(row.channel),
181
+ row.address && row.confirmed_at ? String(row.address) : null,
182
+ ]));
183
+ const confirmedAt = new Map(existing.map((row) => [String(row.channel), row.confirmed_at]));
184
+ const values = input.map((item) => {
185
+ const key = typeof item?.key === 'string' ? item.key : '';
186
+ const channel = this.channels.get(key);
187
+ if (!channel)
188
+ throw new AdulaError(422, 'E_CHANNEL_UNKNOWN', 'قناة الإشعار غير معروفة');
189
+ if (typeof item.enabled !== 'boolean')
190
+ throw new AdulaError(422, 'E_CHANNEL_INPUT', 'حدد تفعيل القناة أو إيقافها');
191
+ if (channel.delivery === 'always') {
192
+ if (!item.enabled)
193
+ throw new AdulaError(422, 'E_CHANNEL_LOCKED', 'الإشعارات داخل التطبيق لا يمكن إيقافها');
194
+ return null;
195
+ }
196
+ // The stored number is always a confirmed one: an omitted (or equal) address keeps
197
+ // it, an empty one removes it, and a different number needs confirmCode() first.
198
+ let address = item.address === undefined ? (stored.get(key) ?? null) : null;
199
+ const raw = typeof item.address === 'string' ? item.address.trim() : '';
200
+ if (channel.address && raw) {
201
+ address = channel.address(raw);
202
+ if (address !== stored.get(key))
203
+ throw new AdulaError(422, 'E_CHANNEL_CONFIRM', 'أكّد الرقم الجديد برمز التحقق أولاً');
204
+ }
205
+ if (!channel.address)
206
+ address = null;
207
+ if (channel.delivery === 'opt-in' && item.enabled && !address)
208
+ throw new AdulaError(422, 'E_CHANNEL_ADDRESS', 'أدخل رقم الهاتف لتفعيل هذه القناة');
209
+ return {
210
+ user_id: userId,
211
+ channel: key,
212
+ enabled: item.enabled,
213
+ address,
214
+ confirmed_at: address ? (confirmedAt.get(key) ?? null) : null,
215
+ };
216
+ });
217
+ const rows = values.filter((value) => value !== null);
218
+ if (new Set(rows.map((row) => row.channel)).size !== rows.length)
219
+ throw new AdulaError(422, 'E_CHANNEL_INPUT', 'كررت القناة نفسها أكثر من مرة');
220
+ return this.db.transaction(async (trx) => {
221
+ if (rows.length)
222
+ await trx('user_notification_channels')
223
+ .insert(rows.map((row) => ({ ...row, updated_at: trx.fn.now() })))
224
+ .onConflict(['user_id', 'channel'])
225
+ .merge(['enabled', 'address', 'confirmed_at', 'updated_at']);
226
+ return this.preferences(userId, trx);
227
+ });
228
+ }
229
+ /**
230
+ * Sends a one-time code to `address` through the channel itself. The number is enabled
231
+ * only by confirmCode(). One code per user and channel at a time, a new one after 60
232
+ * seconds and at most five in 24 hours; the wait and the cap are enforced by the upsert
233
+ * itself, so two parallel requests send one code.
234
+ */
235
+ async requestCode(userId, key, address) {
236
+ const channel = this.optIn(key);
237
+ const normalized = channel.address(address);
238
+ const user = await this.db('users').where('id', userId).first();
239
+ if (!user)
240
+ throw new AdulaError(404, 'E_NOT_FOUND', 'المستخدم غير موجود');
241
+ const code = String(randomInt(0, 1_000_000)).padStart(6, '0');
242
+ const salt = randomBytes(16).toString('hex');
243
+ const window = `interval '${CODE_WINDOW_HOURS} hours'`;
244
+ const result = await this.db.raw(`INSERT INTO notification_channel_confirmations AS c
245
+ (user_id, channel, address, salt, code_hash, attempts, expires_at, created_at,
246
+ sent_count, window_started_at)
247
+ VALUES (?, ?, ?, ?, ?, 0, now() + interval '${CODE_MINUTES} minutes', now(), 1, now())
248
+ ON CONFLICT (user_id, channel) DO UPDATE SET
249
+ address = EXCLUDED.address, salt = EXCLUDED.salt, code_hash = EXCLUDED.code_hash,
250
+ attempts = 0, expires_at = EXCLUDED.expires_at, created_at = now(),
251
+ sent_count = CASE WHEN c.window_started_at <= now() - ${window} THEN 1
252
+ ELSE c.sent_count + 1 END,
253
+ window_started_at = CASE WHEN c.window_started_at <= now() - ${window} THEN now()
254
+ ELSE c.window_started_at END
255
+ WHERE c.created_at <= now() - interval '${CODE_WAIT_SECONDS} seconds'
256
+ AND (c.window_started_at <= now() - ${window} OR c.sent_count < ${CODE_DAILY_LIMIT})
257
+ RETURNING id, expires_at`, [userId, key, normalized, salt, codeHash(salt, code)]);
258
+ const [row] = result.rows;
259
+ if (!row) {
260
+ const current = await this.db('notification_channel_confirmations')
261
+ .where({ user_id: userId, channel: key })
262
+ .whereRaw(`window_started_at > now() - ${window}`)
263
+ .where('sent_count', '>=', CODE_DAILY_LIMIT)
264
+ .first('id');
265
+ if (current)
266
+ throw new AdulaError(429, 'E_CHANNEL_CODE_LIMIT', 'بلغت الحد اليومي لرموز التحقق؛ حاول غداً');
267
+ throw new AdulaError(429, 'E_CHANNEL_CODE_WAIT', 'انتظر دقيقة قبل طلب رمز جديد');
268
+ }
269
+ try {
270
+ await channel.deliver({
271
+ id: 0,
272
+ subject: 'رمز التأكيد',
273
+ text: `رمز تأكيد رقم هاتفك: ${code}. ينتهي خلال ${CODE_MINUTES} دقائق.`,
274
+ target: null,
275
+ }, {
276
+ userId,
277
+ email: String(user.email ?? ''),
278
+ name: user.full_name ? String(user.full_name) : null,
279
+ address: normalized,
280
+ }, {
281
+ deliveryId: randomUUID(),
282
+ attempt: 1,
283
+ signal: AbortSignal.timeout(CALL_TIMEOUT_SECONDS * 1000),
284
+ });
285
+ }
286
+ catch {
287
+ // The code never arrived: void it and lift the wait, but it still counts for the day.
288
+ await this.db('notification_channel_confirmations')
289
+ .where('id', row.id)
290
+ .update({
291
+ attempts: CODE_ATTEMPTS,
292
+ expires_at: this.db.fn.now(),
293
+ created_at: this.db.raw(`now() - interval '${CODE_WAIT_SECONDS} seconds'`),
294
+ });
295
+ throw new AdulaError(502, 'E_CHANNEL_CODE_SEND', 'تعذر إرسال رمز التحقق؛ حاول بعد قليل');
296
+ }
297
+ return { expiresAt: new Date(row.expires_at).toISOString() };
298
+ }
299
+ /**
300
+ * Checks the code (five attempts, ten minutes) and enables the channel with its number.
301
+ * A used or exhausted code is voided, not deleted, so the wait and the daily cap remain.
302
+ */
303
+ async confirmCode(userId, key, code) {
304
+ this.optIn(key);
305
+ const text = typeof code === 'string' ? code.trim() : '';
306
+ const confirmed = await this.db.transaction(async (trx) => {
307
+ const row = await trx('notification_channel_confirmations')
308
+ .where({ user_id: userId, channel: key })
309
+ .where('expires_at', '>', trx.fn.now())
310
+ .where('attempts', '<', CODE_ATTEMPTS)
311
+ .forUpdate()
312
+ .first();
313
+ if (!row)
314
+ return null;
315
+ const expected = Buffer.from(String(row.code_hash), 'hex');
316
+ const actual = Buffer.from(codeHash(String(row.salt), text), 'hex');
317
+ if (!/^\d{6}$/.test(text) || !timingSafeEqual(expected, actual)) {
318
+ // The fifth wrong attempt voids the code (attempts reaches the limit).
319
+ await trx('notification_channel_confirmations').where('id', row.id).increment('attempts', 1);
320
+ return false;
321
+ }
322
+ await trx('user_notification_channels')
323
+ .insert({
324
+ user_id: userId,
325
+ channel: key,
326
+ enabled: true,
327
+ address: row.address,
328
+ confirmed_at: trx.fn.now(),
329
+ updated_at: trx.fn.now(),
330
+ })
331
+ .onConflict(['user_id', 'channel'])
332
+ .merge(['enabled', 'address', 'confirmed_at', 'updated_at']);
333
+ await trx('notification_channel_confirmations')
334
+ .where('id', row.id)
335
+ .update({ attempts: CODE_ATTEMPTS, expires_at: trx.fn.now() });
336
+ return true;
337
+ });
338
+ if (confirmed === null)
339
+ throw new AdulaError(422, 'E_CHANNEL_CODE', 'رمز التحقق منتهٍ أو مستنفد؛ اطلب رمزاً جديداً');
340
+ if (!confirmed)
341
+ throw new AdulaError(422, 'E_CHANNEL_CODE', 'رمز التحقق غير صحيح');
342
+ return this.preferences(userId);
343
+ }
344
+ /** Deletes spent confirmation rows a day after they expired, with their numbers. */
345
+ async cleanupConfirmations() {
346
+ return this.db('notification_channel_confirmations')
347
+ .whereRaw(`expires_at < now() - interval '${CONFIRMATION_RETENTION_DAYS} days'`)
348
+ .delete();
349
+ }
350
+ optIn(key) {
351
+ const channel = this.channels.get(key);
352
+ if (!channel || channel.delivery !== 'opt-in' || !channel.address)
353
+ throw new AdulaError(409, 'E_CHANNEL_UNAVAILABLE', 'هذه القناة غير متاحة الآن');
354
+ return channel;
355
+ }
356
+ /**
357
+ * Delivers pending work on every registered channel. Pending rows of a retired channel
358
+ * (its provider was turned off) are skipped, never sent later; rows of a channel that is
359
+ * merely unregistered on this tick stay pending.
360
+ * `limit` bounds the claimed notification_deliveries rows, `drainLimit` each own queue
361
+ * (the e-mail worker sends up to 50 per tick, as before).
362
+ */
363
+ async deliver(limit = 20, drainLimit = 50) {
364
+ const result = { sent: 0, failed: 0, skipped: 0 };
365
+ const queued = [];
366
+ for (const channel of this.channels.values()) {
367
+ if (!channel.drain) {
368
+ queued.push(channel);
369
+ continue;
370
+ }
371
+ const drained = await channel.drain(this.db, drainLimit);
372
+ result.sent += drained.sent;
373
+ result.failed += drained.failed;
374
+ }
375
+ const keys = queued.map((channel) => channel.key);
376
+ // A message that waited a day (an outage, an unregistered channel) is stale: drop it.
377
+ result.skipped += await this.db('notification_deliveries')
378
+ .where('state', 'pending')
379
+ .whereRaw(`created_at < now() - interval '${DELIVERY_MAX_AGE_HOURS} hours'`)
380
+ .update({ state: 'skipped', error_category: 'expired' });
381
+ await this.cleanupConfirmations();
382
+ if (this.retired.size)
383
+ result.skipped += await this.db('notification_deliveries')
384
+ .where('state', 'pending')
385
+ .whereIn('channel', [...this.retired])
386
+ .update({ state: 'skipped', error_category: 'channel-unavailable' });
387
+ if (!keys.length)
388
+ return result;
389
+ const lease = randomUUID();
390
+ const claimed = await this.db.transaction(async (trx) => {
391
+ const rows = await trx('notification_deliveries as d')
392
+ .join('notifications as n', 'n.id', 'd.notification_id')
393
+ .join('users as u', 'u.id', 'n.user_id')
394
+ .leftJoin('user_notification_channels as p', (join) => join.on('p.user_id', 'n.user_id').andOn('p.channel', 'd.channel'))
395
+ .where('d.state', 'pending')
396
+ .whereIn('d.channel', keys)
397
+ .where('d.next_attempt_at', '<=', trx.fn.now())
398
+ .orderBy('d.next_attempt_at')
399
+ .limit(limit)
400
+ .forUpdate('d')
401
+ .skipLocked()
402
+ .select('d.id', 'd.channel', 'd.attempts', 'n.id as notification_id', 'n.user_id', 'n.title', 'n.body', 'n.resource', 'n.record_id', 'u.email', 'u.full_name', 'u.disabled_at', 'p.enabled', 'p.address', 'p.confirmed_at');
403
+ // Lease the rows long enough for every call in this batch; the lease id makes each
404
+ // later write conditional, so a worker whose lease was taken over writes nothing.
405
+ if (rows.length)
406
+ await trx('notification_deliveries')
407
+ .whereIn('id', rows.map((row) => row.id))
408
+ .update({
409
+ lease_id: lease,
410
+ next_attempt_at: trx.raw('now() + make_interval(secs => ?)', [
411
+ rows.length * CALL_TIMEOUT_SECONDS + LEASE_MARGIN_SECONDS,
412
+ ]),
413
+ });
414
+ return rows;
415
+ });
416
+ const held = () => this.db('notification_deliveries').where({ state: 'pending', lease_id: lease });
417
+ for (const row of claimed) {
418
+ const channel = this.channels.get(String(row.channel));
419
+ // Renew this row's lease right before the call; if another worker took it over
420
+ // (the lease expired), leave the row to that worker and do not send it again.
421
+ const renewed = await held()
422
+ .where('id', row.id)
423
+ .update({
424
+ next_attempt_at: this.db.raw('now() + make_interval(secs => ?)', [
425
+ CALL_TIMEOUT_SECONDS + LEASE_MARGIN_SECONDS,
426
+ ]),
427
+ });
428
+ if (!renewed)
429
+ continue;
430
+ // The user may have turned the channel off, or been disabled, since it was queued;
431
+ // an unconfirmed number never receives messages.
432
+ if (row.disabled_at || !row.enabled || !row.address || !row.confirmed_at) {
433
+ await held()
434
+ .where('id', row.id)
435
+ .update({ state: 'skipped', error_category: row.disabled_at ? 'user-disabled' : null });
436
+ result.skipped++;
437
+ continue;
438
+ }
439
+ const attempts = Number(row.attempts) + 1;
440
+ try {
441
+ await channel.deliver({
442
+ id: Number(row.notification_id),
443
+ subject: String(row.title),
444
+ text: String(row.body),
445
+ target: row.resource && row.record_id !== null
446
+ ? { resource: String(row.resource), recordId: Number(row.record_id) }
447
+ : null,
448
+ }, {
449
+ userId: Number(row.user_id),
450
+ email: String(row.email),
451
+ name: row.full_name ? String(row.full_name) : null,
452
+ address: String(row.address),
453
+ }, {
454
+ deliveryId: String(row.id),
455
+ attempt: attempts,
456
+ signal: AbortSignal.timeout(CALL_TIMEOUT_SECONDS * 1000),
457
+ });
458
+ const written = await held().where('id', row.id).update({
459
+ state: 'sent',
460
+ attempts,
461
+ error_category: null,
462
+ sent_at: this.db.fn.now(),
463
+ });
464
+ if (written)
465
+ result.sent++;
466
+ }
467
+ catch (error) {
468
+ // Store a category only; raw messages may echo provider hosts or bodies.
469
+ const category = error instanceof ChannelDeliveryError ? error.category : outboundErrorCategory(error);
470
+ const exhausted = attempts >= CHANNEL_MAX_ATTEMPTS;
471
+ const written = await held()
472
+ .where('id', row.id)
473
+ .update({
474
+ state: exhausted ? 'failed' : 'pending',
475
+ attempts,
476
+ error_category: category.slice(0, 40),
477
+ next_attempt_at: exhausted
478
+ ? this.db.fn.now()
479
+ : this.db.raw(`now() + interval '${BACKOFF_MINUTES[attempts - 1]} minutes'`),
480
+ });
481
+ if (written)
482
+ result.failed++;
483
+ }
484
+ }
485
+ return result;
486
+ }
487
+ }
488
+ export const HTTP_CHANNEL_SETTING_KEY = 'channels.http';
489
+ export const HTTP_CHANNEL_KINDS = ['sms', 'whatsapp'];
490
+ export const CHANNEL_KIND_LABELS = {
491
+ sms: { ar: 'رسالة نصية', en: 'SMS' },
492
+ whatsapp: { ar: 'واتساب', en: 'WhatsApp' },
493
+ };
494
+ const RESOURCE = 'core.settings';
495
+ /**
496
+ * The administrator-configured HTTP provider channel, stored in the system setting
497
+ * `channels.http` as `{ enabled, kind, url, secret, updatedAt }` with the signing secret
498
+ * sealed like webhook secrets. The secret is generated on first save and on rotation,
499
+ * returned once and never again; the settings screen lists the key without it.
500
+ */
501
+ export class HttpChannelSettings {
502
+ db;
503
+ secrets;
504
+ options;
505
+ constructor(db, secrets, options = {}) {
506
+ this.db = db;
507
+ this.secrets = secrets;
508
+ this.options = options;
509
+ }
510
+ async read() {
511
+ return this.present(await this.stored());
512
+ }
513
+ present(value) {
514
+ if (!value)
515
+ return null;
516
+ return {
517
+ enabled: value.enabled === true,
518
+ kind: HTTP_CHANNEL_KINDS.includes(value.kind) ? value.kind : 'sms',
519
+ url: String(value.url ?? ''),
520
+ hasSecret: typeof value.secret === 'string' && value.secret.length > 0,
521
+ updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : null,
522
+ };
523
+ }
524
+ /** Saves the provider; returns the new secret when one was generated (first save or rotate). */
525
+ async save(actorId, input, options = {}) {
526
+ if (!HTTP_CHANNEL_KINDS.includes(input.kind))
527
+ throw new AdulaError(422, 'E_CHANNEL_KIND', 'اختر نوع القناة: رسالة نصية أو واتساب');
528
+ if (typeof input.enabled !== 'boolean')
529
+ throw new AdulaError(422, 'E_CHANNEL_INPUT', 'حدد تفعيل القناة أو إيقافها');
530
+ const url = typeof input.url === 'string' ? input.url.trim() : '';
531
+ await this.assertTarget(url);
532
+ const previous = await this.stored();
533
+ const generate = options.rotate === true || typeof previous?.secret !== 'string';
534
+ const secret = generate ? randomBytes(32).toString('base64url') : null;
535
+ const value = {
536
+ enabled: input.enabled,
537
+ kind: input.kind,
538
+ url,
539
+ secret: secret ? this.secrets.seal(secret) : String(previous.secret),
540
+ updatedAt: new Date().toISOString(),
541
+ };
542
+ await this.db.transaction(async (trx) => {
543
+ const [row] = await trx('settings')
544
+ .insert({
545
+ key: HTTP_CHANNEL_SETTING_KEY,
546
+ scope: 'system',
547
+ scope_id: '0',
548
+ value: JSON.stringify(value),
549
+ })
550
+ .onConflict(['key', 'scope', 'scope_id'])
551
+ .merge(['value'])
552
+ .returning('id');
553
+ await logActivity(trx, {
554
+ resource: RESOURCE,
555
+ recordId: row.id,
556
+ actorId,
557
+ action: 'upsert',
558
+ changes: {
559
+ key: HTTP_CHANNEL_SETTING_KEY,
560
+ scope: 'system',
561
+ scopeId: '0',
562
+ value: { enabled: value.enabled, kind: value.kind, url, secretRotated: generate },
563
+ },
564
+ });
565
+ });
566
+ return { config: (await this.read()), secret };
567
+ }
568
+ /** Replaces the signing secret and returns the new one once. */
569
+ async rotate(actorId) {
570
+ const current = await this.read();
571
+ if (!current)
572
+ throw new AdulaError(404, 'E_CHANNEL_NOT_CONFIGURED', 'لم تُضبط قناة الرسائل بعد');
573
+ return this.save(actorId, current, { rotate: true });
574
+ }
575
+ /** The configured channel while it is enabled; null otherwise. */
576
+ async channel(options = {}) {
577
+ return this.build(await this.stored(), options);
578
+ }
579
+ /**
580
+ * One read for the worker: the active channel (or null) and the HTTP channel kinds this
581
+ * read proves are off (no provider or disabled: every kind; enabled: the other kinds).
582
+ * Pass `retired` to NotificationChannels only after this call succeeded.
583
+ */
584
+ async resolve(options = {}) {
585
+ const value = await this.stored();
586
+ const channel = this.build(value, options);
587
+ return {
588
+ channel,
589
+ retired: HTTP_CHANNEL_KINDS.filter((kind) => kind !== channel?.key),
590
+ };
591
+ }
592
+ build(value, options) {
593
+ const config = this.present(value);
594
+ if (!value || !config || !config.url || (!config.enabled && !options.force))
595
+ return null;
596
+ let secret = null;
597
+ try {
598
+ secret = typeof value.secret === 'string' ? this.secrets.open(value.secret) : null;
599
+ }
600
+ catch {
601
+ secret = null;
602
+ }
603
+ return httpNotificationChannel({
604
+ key: config.kind,
605
+ url: config.url,
606
+ secret,
607
+ post: options.post ?? createOutboundPoster(this.options),
608
+ link: options.link,
609
+ });
610
+ }
611
+ /**
612
+ * Sends one test message to `to` through the configured provider (enabled or not) and
613
+ * returns the failure category, or null when the provider accepted it.
614
+ */
615
+ async test(to, options = {}) {
616
+ const channel = await this.channel({ ...options, force: true });
617
+ if (!channel)
618
+ throw new AdulaError(404, 'E_CHANNEL_NOT_CONFIGURED', 'لم تُضبط قناة الرسائل بعد');
619
+ const address = phoneAddress(to);
620
+ try {
621
+ await channel.deliver({ id: 0, subject: 'رسالة تجريبية', text: 'رسالة تجريبية من إعدادات النظام.', target: null }, { userId: 0, email: '', name: null, address }, { deliveryId: randomUUID(), attempt: 1, signal: AbortSignal.timeout(15000) });
622
+ return null;
623
+ }
624
+ catch (error) {
625
+ return error instanceof ChannelDeliveryError ? error.category : outboundErrorCategory(error);
626
+ }
627
+ }
628
+ async stored() {
629
+ const row = await this.db('settings')
630
+ .where({ key: HTTP_CHANNEL_SETTING_KEY, scope: 'system', scope_id: '0' })
631
+ .first('value');
632
+ return row?.value && typeof row.value === 'object' ? row.value : null;
633
+ }
634
+ /** HTTPS only, and no host resolving to a private address unless the policy allows it. */
635
+ async assertTarget(value) {
636
+ let url;
637
+ try {
638
+ url = new URL(value);
639
+ }
640
+ catch {
641
+ throw new AdulaError(422, 'E_CHANNEL_URL', 'عنوان URL غير صالح');
642
+ }
643
+ const allowPrivate = this.options.allowPrivateTargets === true;
644
+ if (url.protocol !== 'https:' && !(allowPrivate && url.protocol === 'http:'))
645
+ throw new AdulaError(422, 'E_CHANNEL_URL', 'يجب أن يبدأ العنوان بـ https://');
646
+ if (url.username || url.password || value.length > 2000)
647
+ throw new AdulaError(422, 'E_CHANNEL_URL', 'عنوان URL غير مسموح');
648
+ // The URL is shown and logged; credentials belong in the signing secret, not the URL.
649
+ if (url.search || url.hash || value.includes('?') || value.includes('#'))
650
+ throw new AdulaError(422, 'E_CHANNEL_URL', 'لا يُقبل عنوان يحوي معاملات استعلام أو جزءاً بعد #؛ المزوّد يتحقق بسر التوقيع');
651
+ if (allowPrivate)
652
+ return;
653
+ try {
654
+ await resolveOutboundTarget(url, this.options);
655
+ }
656
+ catch {
657
+ throw new AdulaError(422, 'E_CHANNEL_URL', 'لا يُسمح بعناوين الشبكة الداخلية');
658
+ }
659
+ }
660
+ }
@@ -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 });