adula 2.2.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 (132) hide show
  1. package/README.md +1 -1
  2. package/build/agent/capabilities.md +2 -3
  3. package/build/agent/skills/adula-frontend-design/SKILL.md +5 -3
  4. package/build/commands/adula_assistant_prune.d.ts +10 -0
  5. package/build/commands/adula_assistant_prune.js +12 -0
  6. package/build/commands/backup_open.d.ts +16 -0
  7. package/build/commands/backup_open.js +48 -0
  8. package/build/commands/backup_restore_test.js +3 -0
  9. package/build/commands/backup_seal.d.ts +12 -0
  10. package/build/commands/backup_seal.js +36 -0
  11. package/build/commands/backup_services.d.ts +3 -1
  12. package/build/commands/doctor.js +18 -1
  13. package/build/commands/install.js +6 -0
  14. package/build/commands/main.d.ts +2 -2
  15. package/build/commands/main.js +6 -0
  16. package/build/commands/resource_migration.js +12 -3
  17. package/build/commands/resource_snapshot.js +18 -4
  18. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  19. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  20. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  21. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  22. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  23. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  24. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  25. package/build/database/migrations/1770000000056_appearance.js +10 -0
  26. package/build/index.d.ts +36 -6
  27. package/build/index.js +18 -3
  28. package/build/src/admin/controller.js +18 -4
  29. package/build/src/admin/resource/editor.d.ts +1 -0
  30. package/build/src/admin/resource/editor.js +26 -4
  31. package/build/src/admin/resource/export.d.ts +21 -4
  32. package/build/src/admin/resource/export.js +117 -36
  33. package/build/src/admin/resource/lifecycle.d.ts +2 -0
  34. package/build/src/admin/resource/query.d.ts +14 -3
  35. package/build/src/admin/resource/query.js +98 -11
  36. package/build/src/admin/resource/read.d.ts +3 -0
  37. package/build/src/admin/resource/read.js +75 -14
  38. package/build/src/admin/resource/shared.d.ts +16 -0
  39. package/build/src/admin/resource/shared.js +47 -4
  40. package/build/src/admin/resource/write.js +37 -8
  41. package/build/src/admin/resource_service.d.ts +17 -3
  42. package/build/src/admin/resource_service.js +16 -2
  43. package/build/src/admin/resource_tools.d.ts +111 -0
  44. package/build/src/admin/resource_tools.js +139 -0
  45. package/build/src/ai/assistant.d.ts +100 -0
  46. package/build/src/ai/assistant.js +487 -0
  47. package/build/src/ai/client.d.ts +49 -0
  48. package/build/src/ai/client.js +85 -0
  49. package/build/src/ai/prompt.d.ts +23 -0
  50. package/build/src/ai/prompt.js +83 -0
  51. package/build/src/ai/settings.d.ts +56 -0
  52. package/build/src/ai/settings.js +214 -0
  53. package/build/src/ai/usage.d.ts +16 -0
  54. package/build/src/ai/usage.js +33 -0
  55. package/build/src/appearance/appearance.d.ts +134 -0
  56. package/build/src/appearance/appearance.js +461 -0
  57. package/build/src/appearance/colors.d.ts +43 -0
  58. package/build/src/appearance/colors.js +99 -0
  59. package/build/src/appearance/logo.d.ts +32 -0
  60. package/build/src/appearance/logo.js +112 -0
  61. package/build/src/auth/actor_store.d.ts +5 -1
  62. package/build/src/auth/actor_store.js +8 -4
  63. package/build/src/backups/archive.d.ts +52 -0
  64. package/build/src/backups/archive.js +362 -0
  65. package/build/src/backups/cloud_backups.d.ts +133 -0
  66. package/build/src/backups/cloud_backups.js +650 -0
  67. package/build/src/backups/doctor.d.ts +7 -0
  68. package/build/src/backups/doctor.js +55 -0
  69. package/build/src/backups/providers.d.ts +81 -0
  70. package/build/src/backups/providers.js +470 -0
  71. package/build/src/collaboration/assignments.d.ts +24 -2
  72. package/build/src/collaboration/assignments.js +88 -32
  73. package/build/src/collaboration/record_collaboration.d.ts +19 -1
  74. package/build/src/collaboration/record_collaboration.js +109 -37
  75. package/build/src/collaboration/shared.d.ts +10 -2
  76. package/build/src/collaboration/shared.js +14 -1
  77. package/build/src/commands/capabilities.js +1 -1
  78. package/build/src/commands/doctor.d.ts +10 -0
  79. package/build/src/commands/doctor.js +31 -1
  80. package/build/src/commands/snapshot.d.ts +14 -0
  81. package/build/src/commands/snapshot.js +23 -0
  82. package/build/src/core/administrators.js +19 -3
  83. package/build/src/core/avatar_image.d.ts +33 -0
  84. package/build/src/core/avatar_image.js +278 -0
  85. package/build/src/core/mail_settings.d.ts +83 -0
  86. package/build/src/core/mail_settings.js +274 -0
  87. package/build/src/core/mail_test.d.ts +16 -0
  88. package/build/src/core/mail_test.js +81 -6
  89. package/build/src/core/message_templates.d.ts +8 -0
  90. package/build/src/core/message_templates.js +12 -3
  91. package/build/src/core/roles.js +24 -7
  92. package/build/src/core/saved_views.js +55 -24
  93. package/build/src/core/settings.d.ts +2 -2
  94. package/build/src/core/settings.js +15 -4
  95. package/build/src/core/ui_preferences.d.ts +6 -0
  96. package/build/src/core/ui_preferences.js +12 -1
  97. package/build/src/core/user_avatars.d.ts +79 -0
  98. package/build/src/core/user_avatars.js +186 -0
  99. package/build/src/core/user_preferences.d.ts +36 -0
  100. package/build/src/core/user_preferences.js +125 -0
  101. package/build/src/core/users.d.ts +2 -0
  102. package/build/src/core/users.js +4 -2
  103. package/build/src/database/schema.d.ts +46 -0
  104. package/build/src/database/schema.js +182 -0
  105. package/build/src/database/schema_diff.d.ts +16 -2
  106. package/build/src/database/schema_diff.js +40 -7
  107. package/build/src/integrations/api_client.js +18 -3
  108. package/build/src/integrations/imports.d.ts +16 -4
  109. package/build/src/integrations/imports.js +36 -8
  110. package/build/src/integrations/openapi.js +15 -4
  111. package/build/src/integrations/outbound.d.ts +43 -0
  112. package/build/src/integrations/outbound.js +98 -17
  113. package/build/src/integrations/print.d.ts +2 -1
  114. package/build/src/integrations/print.js +7 -3
  115. package/build/src/integrations/print_templates.js +3 -1
  116. package/build/src/integrations/xlsx.d.ts +41 -0
  117. package/build/src/integrations/xlsx.js +519 -0
  118. package/build/src/languages/ar.js +22 -0
  119. package/build/src/languages/ar_ui.d.ts +143 -14
  120. package/build/src/languages/ar_ui.js +145 -14
  121. package/build/src/languages/en.js +22 -0
  122. package/build/src/languages/en_ui.js +144 -14
  123. package/build/src/lists/dashboards.d.ts +42 -0
  124. package/build/src/lists/dashboards.js +49 -0
  125. package/build/src/mcp/tools.js +9 -104
  126. package/build/src/resource/define_resource.js +7 -0
  127. package/build/src/resource/types.d.ts +9 -0
  128. package/build/src/workflows/delegations.d.ts +15 -1
  129. package/build/src/workflows/delegations.js +49 -10
  130. package/build/src/workflows/engine.d.ts +11 -0
  131. package/build/src/workflows/engine.js +29 -7
  132. package/package.json +5 -1
@@ -0,0 +1,274 @@
1
+ import { isIP } from 'node:net';
2
+ import { defaultResolve, isBlockedAddress, isLinkLocalAddress, OutboundTargetError, resolveOutboundTarget, } from '../integrations/outbound.js';
3
+ import { AdulaError } from '../admin/errors.js';
4
+ import { logActivity } from './activity.js';
5
+ export const MAIL_SETTINGS_KEY = 'mail.smtp';
6
+ const RESOURCE = 'core.mail';
7
+ const SECURITIES = ['tls', 'starttls', 'none'];
8
+ const FIELDS = [
9
+ 'preset',
10
+ 'host',
11
+ 'port',
12
+ 'security',
13
+ 'username',
14
+ 'fromName',
15
+ 'fromAddress',
16
+ ];
17
+ // Control characters, including CR and LF, would let a value add mail or SMTP headers.
18
+ const CONTROL = {
19
+ test: (value) => [...value].some((char) => {
20
+ const code = char.codePointAt(0);
21
+ return code < 0x20 || code === 0x7f;
22
+ }),
23
+ };
24
+ const HOSTNAME = /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;
25
+ const ADDRESS = /^[^\s@<>()",;:\\[\]]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?\.[A-Za-z]{2,}$/;
26
+ const invalid = (code, message) => new AdulaError(422, code, message);
27
+ /**
28
+ * The stored SMTP password cannot be opened. It carries a category only, never the sealed or
29
+ * the opened value, and classifies as `password_unreadable` (see classifyMailFailure).
30
+ */
31
+ export class MailPasswordUnreadableError extends Error {
32
+ code = 'E_MAIL_PASSWORD_UNREADABLE';
33
+ constructor() {
34
+ super('The stored SMTP password cannot be opened; enter it again');
35
+ }
36
+ }
37
+ const PLAINTEXT_PUBLIC = () => invalid('E_MAIL_SECURITY', 'الإرسال بلا تشفير مسموح لخادم بريد داخلي فقط، لأنه يكشف كلمة المرور والرسائل في الطريق. اختر TLS أو STARTTLS.');
38
+ /**
39
+ * SMTP settings kept in the system setting `mail.smtp` (ADR 020 amendment), so an administrator
40
+ * configures mail from the interface without editing the environment or restarting. The password
41
+ * is sealed like the assistant key, is never returned, and is cleared whenever the server
42
+ * changes, so a stored password cannot be sent to another host. The host must resolve outside
43
+ * private networks unless the outbound policy allows them.
44
+ */
45
+ export class MailSettings {
46
+ db;
47
+ secrets;
48
+ options;
49
+ constructor(db, secrets, options = {}) {
50
+ this.db = db;
51
+ this.secrets = secrets;
52
+ this.options = options;
53
+ }
54
+ async read() {
55
+ return this.present(await this.stored());
56
+ }
57
+ /**
58
+ * The stored options with the opened password, or null while nothing is stored. A stored
59
+ * password that cannot be opened throws MailPasswordUnreadableError: the message is not sent
60
+ * without the sign-in the administrator configured.
61
+ */
62
+ async runtime() {
63
+ const value = await this.stored();
64
+ const view = this.present(value);
65
+ if (!view.configured)
66
+ return null;
67
+ if (view.passwordUnreadable)
68
+ throw new MailPasswordUnreadableError();
69
+ const password = view.hasPassword ? this.open(value?.secret) : null;
70
+ return {
71
+ host: view.host,
72
+ port: view.port,
73
+ security: view.security,
74
+ username: view.username,
75
+ password: password || null,
76
+ fromName: view.fromName,
77
+ fromAddress: view.fromAddress,
78
+ };
79
+ }
80
+ /**
81
+ * The address a connection to `host` must use; refuses private targets per the policy. An
82
+ * unencrypted connection (`none`) is refused unless the address is internal, so the password
83
+ * and the messages never cross the internet in clear text.
84
+ */
85
+ async target(host, security) {
86
+ // Resolved once here, so link-local (the metadata address) is refused even with the
87
+ // private-network opt-in; the same addresses are then checked and pinned as usual.
88
+ let addresses;
89
+ if (isIP(host))
90
+ addresses = [host];
91
+ else {
92
+ try {
93
+ addresses = await (this.options.resolve ?? defaultResolve)(host);
94
+ }
95
+ catch {
96
+ throw new OutboundTargetError('dns');
97
+ }
98
+ }
99
+ if (addresses.some(isLinkLocalAddress))
100
+ throw new OutboundTargetError('blocked-target');
101
+ const target = await resolveOutboundTarget(new URL(`smtp://${isIP(host) === 6 ? `[${host}]` : host}`), { ...this.options, resolve: async () => addresses });
102
+ if (security === 'none' && !isBlockedAddress(target.address))
103
+ throw PLAINTEXT_PUBLIC();
104
+ return target;
105
+ }
106
+ /** The opened password, or null when it cannot be opened; never logged or returned. */
107
+ open(secret) {
108
+ if (typeof secret !== 'string' || !secret)
109
+ return null;
110
+ try {
111
+ const opened = this.secrets.open(secret);
112
+ return typeof opened === 'string' && opened ? opened : null;
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ }
118
+ present(value) {
119
+ const v = value ?? {};
120
+ const host = typeof v.host === 'string' ? v.host : '';
121
+ const security = SECURITIES.includes(v.security)
122
+ ? v.security
123
+ : 'tls';
124
+ return {
125
+ configured: host.length > 0,
126
+ preset: typeof v.preset === 'string' ? v.preset : 'custom',
127
+ host,
128
+ port: Number.isSafeInteger(v.port) ? v.port : 465,
129
+ security,
130
+ username: typeof v.username === 'string' ? v.username : '',
131
+ hasPassword: typeof v.secret === 'string' && v.secret.length > 0,
132
+ passwordUnreadable: typeof v.secret === 'string' && v.secret.length > 0 && this.open(v.secret) === null,
133
+ fromName: typeof v.fromName === 'string' ? v.fromName : '',
134
+ fromAddress: typeof v.fromAddress === 'string' ? v.fromAddress : '',
135
+ updatedAt: typeof v.updatedAt === 'string' ? v.updatedAt : null,
136
+ };
137
+ }
138
+ /** Saves everything except the password. Changing the server clears the stored password. */
139
+ async save(actor, input) {
140
+ if (!input || typeof input !== 'object' || Array.isArray(input))
141
+ throw invalid('E_MAIL_SETTINGS_INPUT', 'بيانات إعداد البريد غير صالحة');
142
+ const data = input;
143
+ if (Object.keys(data).some((key) => !FIELDS.includes(key)))
144
+ throw invalid('E_MAIL_SETTINGS_INPUT', 'حقل غير معروف في إعداد البريد');
145
+ // AdonisJS turns an emptied field into null.
146
+ const text = (key) => (data[key] === null ? '' : data[key]);
147
+ const previous = (await this.stored()) ?? {};
148
+ const current = this.present(previous);
149
+ const next = { ...current };
150
+ const changed = [];
151
+ const assign = (key, value) => {
152
+ if (value !== current[key])
153
+ changed.push(key);
154
+ next[key] = value;
155
+ };
156
+ if (data.preset !== undefined) {
157
+ const preset = text('preset');
158
+ if (typeof preset !== 'string' || !/^[a-z0-9_-]{1,32}$/.test(preset))
159
+ throw invalid('E_MAIL_SETTINGS_INPUT', 'مزود البريد غير صالح');
160
+ assign('preset', preset);
161
+ }
162
+ if (data.host !== undefined) {
163
+ const host = typeof text('host') === 'string' ? text('host').trim().toLowerCase() : null;
164
+ if (host === null || !(HOSTNAME.test(host) || isIP(host)))
165
+ throw invalid('E_MAIL_HOST', 'اكتب اسم خادم SMTP وحده، مثل smtp.gmail.com، دون بادئة أو منفذ أو مسار.');
166
+ await this.assertTarget(host);
167
+ assign('host', host);
168
+ }
169
+ if (data.port !== undefined) {
170
+ const port = Number(data.port);
171
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
172
+ throw invalid('E_MAIL_PORT', 'المنفذ رقم بين 1 و65535');
173
+ assign('port', port);
174
+ }
175
+ if (data.security !== undefined) {
176
+ if (!SECURITIES.includes(data.security))
177
+ throw invalid('E_MAIL_SECURITY', 'اختر نوع الأمان: TLS أو STARTTLS أو بلا تشفير');
178
+ assign('security', data.security);
179
+ }
180
+ if (data.username !== undefined) {
181
+ const username = text('username');
182
+ if (typeof username !== 'string' || username.length > 254 || CONTROL.test(username))
183
+ throw invalid('E_MAIL_USERNAME', 'اسم المستخدم نص في سطر واحد لا يتجاوز 254 حرفًا');
184
+ assign('username', username.trim());
185
+ }
186
+ if (data.fromName !== undefined) {
187
+ const name = text('fromName');
188
+ if (typeof name !== 'string' || name.length > 100 || CONTROL.test(name) || /[<>"]/.test(name))
189
+ throw invalid('E_MAIL_FROM_NAME', 'اسم المرسل نص في سطر واحد لا يتجاوز 100 حرف، دون الرموز < > "');
190
+ assign('fromName', name.trim());
191
+ }
192
+ if (data.fromAddress !== undefined) {
193
+ const address = text('fromAddress');
194
+ if (typeof address !== 'string' || CONTROL.test(address) || !ADDRESS.test(address.trim()))
195
+ throw invalid('E_MAIL_FROM_ADDRESS', 'اكتب عنوان مرسل واحدًا صحيحًا، مثل no-reply@example.com');
196
+ assign('fromAddress', address.trim());
197
+ }
198
+ if (!next.host)
199
+ throw invalid('E_MAIL_HOST', 'اكتب اسم خادم SMTP');
200
+ if (!next.fromAddress)
201
+ throw invalid('E_MAIL_FROM_ADDRESS', 'اكتب عنوان المرسل');
202
+ if (next.security === 'none') {
203
+ const target = await this.assertTarget(next.host);
204
+ if (!isBlockedAddress(target.address))
205
+ throw PLAINTEXT_PUBLIC();
206
+ }
207
+ const passwordCleared = next.host !== current.host && current.hasPassword;
208
+ delete next.hasPassword;
209
+ delete next.passwordUnreadable;
210
+ delete next.configured;
211
+ next.updatedAt = new Date().toISOString();
212
+ if (!passwordCleared && typeof previous.secret === 'string')
213
+ next.secret = previous.secret;
214
+ await this.write(actor, next, 'settings.update', { changed, passwordCleared });
215
+ return this.read();
216
+ }
217
+ /** Stores the SMTP password sealed; it is never returned. */
218
+ async setPassword(actor, value) {
219
+ const password = typeof value === 'string' ? value : '';
220
+ if (!password.length || password.length > 500 || /[\r\n]/.test(password))
221
+ throw invalid('E_MAIL_PASSWORD', 'كلمة المرور مطلوبة، في سطر واحد لا يتجاوز 500 حرف');
222
+ const previous = (await this.stored()) ?? {};
223
+ if (!this.present(previous).configured)
224
+ throw invalid('E_MAIL_HOST', 'احفظ خادم SMTP أولًا، ثم كلمة المرور');
225
+ await this.write(actor, { ...previous, secret: this.secrets.seal(password), updatedAt: new Date().toISOString() }, 'password.set', { passwordChanged: true });
226
+ return this.read();
227
+ }
228
+ async clearPassword(actor) {
229
+ const previous = (await this.stored()) ?? {};
230
+ const next = { ...previous, updatedAt: new Date().toISOString() };
231
+ delete next.secret;
232
+ await this.write(actor, next, 'password.clear', { passwordChanged: true });
233
+ return this.read();
234
+ }
235
+ async write(actor, value, action, changes) {
236
+ await this.db.transaction(async (trx) => {
237
+ const [row] = await trx('settings')
238
+ .insert({
239
+ key: MAIL_SETTINGS_KEY,
240
+ scope: 'system',
241
+ scope_id: '0',
242
+ value: JSON.stringify(value),
243
+ })
244
+ .onConflict(['key', 'scope', 'scope_id'])
245
+ .merge(['value'])
246
+ .returning('id');
247
+ // Never a value: which fields changed, and whether the password changed or was cleared.
248
+ await logActivity(trx, {
249
+ resource: RESOURCE,
250
+ recordId: row.id,
251
+ actorId: actor.id,
252
+ impersonatorId: actor.impersonatorId,
253
+ action,
254
+ changes: changes,
255
+ });
256
+ });
257
+ }
258
+ async stored() {
259
+ const row = await this.db('settings')
260
+ .where({ key: MAIL_SETTINGS_KEY, scope: 'system', scope_id: '0' })
261
+ .first('value');
262
+ return row?.value && typeof row.value === 'object' ? row.value : null;
263
+ }
264
+ async assertTarget(host) {
265
+ try {
266
+ return await this.target(host);
267
+ }
268
+ catch (error) {
269
+ if (error.category === 'dns')
270
+ throw invalid('E_MAIL_HOST', 'تعذر العثور على خادم SMTP بهذا الاسم');
271
+ throw invalid('E_MAIL_HOST', 'لا يُسمح بعناوين الشبكة الداخلية لخادم البريد');
272
+ }
273
+ }
274
+ }
@@ -8,6 +8,22 @@ export type MailTestState = {
8
8
  requestedAt: string;
9
9
  answeredAt?: string;
10
10
  };
11
+ /** Why a test message was refused, in terms an administrator can act on. */
12
+ export type MailFailureReason = 'authentication' | 'connection' | 'host_not_found' | 'tls' | 'timeout' | 'sender_rejected' | 'recipient_rejected' | 'password_unreadable' | 'unknown';
13
+ /** A transport failure reduced to non-secret facts: never the raw message or credentials. */
14
+ export type MailFailure = {
15
+ reason: MailFailureReason;
16
+ code?: string;
17
+ responseCode?: number;
18
+ command?: string;
19
+ };
20
+ /**
21
+ * Maps an SMTP transport error (nodemailer's `code`, `responseCode` and `command`, also
22
+ * through `cause`) to a reason. Only the reason, the error code, the SMTP response code and
23
+ * an allow-listed command survive; the message, which can echo server text, is read here
24
+ * only to recognise TLS handshake failures and is never returned.
25
+ */
26
+ export declare function classifyMailFailure(error: unknown): MailFailure;
11
27
  /** Receipt is an administrator attestation, never inferred from SMTP acceptance. */
12
28
  export declare class MailDeliveryTest {
13
29
  private db;
@@ -1,8 +1,82 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { AdulaError } from '../admin/errors.js';
3
+ import { arabicMessages } from '../languages/ar.js';
3
4
  import { Settings } from '../services/settings.js';
4
5
  import { logActivity } from './activity.js';
5
6
  export const MAIL_TEST_KEY = 'mail.delivery_test';
7
+ // SMTP commands safe to record; anything else (e.g. an AUTH payload) is dropped.
8
+ const COMMANDS = new Set([
9
+ 'CONN',
10
+ 'EHLO',
11
+ 'HELO',
12
+ 'STARTTLS',
13
+ 'AUTH PLAIN',
14
+ 'AUTH LOGIN',
15
+ 'AUTH XOAUTH2',
16
+ 'MAIL FROM',
17
+ 'RCPT TO',
18
+ 'DATA',
19
+ 'API',
20
+ ]);
21
+ // One fixed catalog sentence per reason (ADR 041), so every language can translate it.
22
+ const failureMessage = (reason) => reason === 'unknown'
23
+ ? arabicMessages['errors.E_MAIL_TEST_SEND']
24
+ : arabicMessages[`errors.E_MAIL_TEST_SEND.${reason}`];
25
+ function errorChain(error) {
26
+ const chain = [];
27
+ let current = error;
28
+ while (current && typeof current === 'object' && chain.length < 5) {
29
+ chain.push(current);
30
+ current = current.cause;
31
+ }
32
+ return chain;
33
+ }
34
+ /**
35
+ * Maps an SMTP transport error (nodemailer's `code`, `responseCode` and `command`, also
36
+ * through `cause`) to a reason. Only the reason, the error code, the SMTP response code and
37
+ * an allow-listed command survive; the message, which can echo server text, is read here
38
+ * only to recognise TLS handshake failures and is never returned.
39
+ */
40
+ export function classifyMailFailure(error) {
41
+ const chain = errorChain(error);
42
+ const pick = (read) => chain.map(read).find((value) => value !== undefined);
43
+ const code = pick((entry) => (typeof entry.code === 'string' ? entry.code : undefined));
44
+ const codes = chain.map((entry) => entry.code).filter((value) => typeof value === 'string');
45
+ const responseCode = pick((entry) => typeof entry.responseCode === 'number' ? entry.responseCode : undefined);
46
+ const rawCommand = pick((entry) => typeof entry.command === 'string' ? entry.command.toUpperCase() : undefined);
47
+ const command = rawCommand && COMMANDS.has(rawCommand) ? rawCommand : undefined;
48
+ const tlsText = chain.some((entry) => typeof entry.message === 'string' &&
49
+ /wrong version number|ssl routines|tls|certificate/i.test(entry.message));
50
+ const has = (...names) => codes.some((value) => names.includes(value));
51
+ const reason = has('E_MAIL_PASSWORD_UNREADABLE')
52
+ ? 'password_unreadable'
53
+ : has('EAUTH', 'ENOAUTH') ||
54
+ responseCode === 535 ||
55
+ responseCode === 534 ||
56
+ responseCode === 530
57
+ ? 'authentication'
58
+ : has('EENVELOPE') || command === 'MAIL FROM' || command === 'RCPT TO'
59
+ ? command === 'RCPT TO'
60
+ ? 'recipient_rejected'
61
+ : 'sender_rejected'
62
+ : has('ENOTFOUND', 'EAI_AGAIN', 'EDNS')
63
+ ? 'host_not_found'
64
+ : has('ETLS') ||
65
+ codes.some((value) => /^ERR_(SSL|TLS)_|^EPROTO$/.test(value)) ||
66
+ tlsText
67
+ ? 'tls'
68
+ : has('ETIMEDOUT', 'ETIMEOUT', 'ESOCKETTIMEDOUT', 'EGREETING')
69
+ ? 'timeout'
70
+ : has('ECONNREFUSED', 'ECONNECTION', 'ECONNRESET', 'EHOSTUNREACH', 'ENETUNREACH')
71
+ ? 'connection'
72
+ : 'unknown';
73
+ return {
74
+ reason,
75
+ ...(code && /^[A-Z_0-9]{2,40}$/.test(code) ? { code } : {}),
76
+ ...(responseCode !== undefined ? { responseCode } : {}),
77
+ ...(command ? { command } : {}),
78
+ };
79
+ }
6
80
  /** Receipt is an administrator attestation, never inferred from SMTP acceptance. */
7
81
  export class MailDeliveryTest {
8
82
  db;
@@ -36,13 +110,14 @@ export class MailDeliveryTest {
36
110
  changes: { testId: state.id },
37
111
  });
38
112
  });
39
- let failed = false;
113
+ let failure = null;
40
114
  try {
41
115
  await deliver(state.id);
42
116
  }
43
- catch {
44
- failed = true;
117
+ catch (error) {
118
+ failure = classifyMailFailure(error);
45
119
  }
120
+ const failed = failure !== null;
46
121
  // Match the attempt so a delayed response cannot overwrite a newer test.
47
122
  await this.db.transaction(async (trx) => {
48
123
  await trx('settings')
@@ -54,11 +129,11 @@ export class MailDeliveryTest {
54
129
  recordId: actorId,
55
130
  actorId,
56
131
  action: failed ? 'test_send_failed' : 'test_send_accepted',
57
- changes: { testId: state.id },
132
+ changes: failure ? { testId: state.id, ...failure } : { testId: state.id },
58
133
  });
59
134
  });
60
- if (failed)
61
- throw new AdulaError(502, 'E_MAIL_TEST_SEND', 'تعذّر إرسال البريد التجريبي. راجع إعدادات البريد ثم أعد المحاولة.');
135
+ if (failure)
136
+ throw new AdulaError(502, 'E_MAIL_TEST_SEND', failureMessage(failure.reason));
62
137
  }
63
138
  async answer(actorId, recipient, fingerprint, id, received) {
64
139
  if (typeof received !== 'boolean' || typeof id !== 'string')
@@ -58,6 +58,14 @@ export declare const MAIL_CHANNEL = "mail";
58
58
  * other channel the user enabled with an address (see core/notification_channels.ts).
59
59
  */
60
60
  export declare function notifyWithTemplate(db: Knex, userId: number, key: string, variables: Record<string, unknown>, templates?: MessageTemplates, target?: NotificationTarget | null): Promise<void>;
61
+ /**
62
+ * notifyWithTemplate that also names the comment the notification quotes and returns the
63
+ * notification id. Internal (not exported from the package): RecordCollaboration links
64
+ * comment notifications so deleting or editing the comment withdraws the quoted text.
65
+ */
66
+ export declare function insertTemplatedNotification(db: Knex, userId: number, key: string, variables: Record<string, unknown>, templates?: MessageTemplates, target?: NotificationTarget | null, link?: {
67
+ commentId?: number;
68
+ }): Promise<number>;
61
69
  export type MailSender = (message: {
62
70
  to: string;
63
71
  name: string | null;
@@ -202,6 +202,14 @@ export const MAIL_CHANNEL = 'mail';
202
202
  * other channel the user enabled with an address (see core/notification_channels.ts).
203
203
  */
204
204
  export async function notifyWithTemplate(db, userId, key, variables, templates = new MessageTemplates(db), target) {
205
+ await insertTemplatedNotification(db, userId, key, variables, templates, target);
206
+ }
207
+ /**
208
+ * notifyWithTemplate that also names the comment the notification quotes and returns the
209
+ * notification id. Internal (not exported from the package): RecordCollaboration links
210
+ * comment notifications so deleting or editing the comment withdraws the quoted text.
211
+ */
212
+ export async function insertTemplatedNotification(db, userId, key, variables, templates = new MessageTemplates(db), target, link = {}) {
205
213
  const message = await templates.render(key, variables, db);
206
214
  const preferences = message.mail
207
215
  ? await db('user_notification_channels')
@@ -224,6 +232,7 @@ export async function notifyWithTemplate(db, userId, key, variables, templates =
224
232
  template_key: key,
225
233
  mail_state: message.mail ? (mailOff ? 'skipped' : 'pending') : null,
226
234
  ...targetColumns(target),
235
+ ...(link.commentId ? { comment_id: link.commentId } : {}),
227
236
  })
228
237
  .returning('id');
229
238
  if (external.length)
@@ -232,12 +241,12 @@ export async function notifyWithTemplate(db, userId, key, variables, templates =
232
241
  notification_id: row.id,
233
242
  channel: preference.channel,
234
243
  })));
244
+ return Number(row.id);
235
245
  };
236
246
  // The row and its deliveries commit together; a caller's transaction is used as-is.
237
247
  if (!external.length || db.isTransaction)
238
- await insert(db);
239
- else
240
- await db.transaction(insert);
248
+ return insert(db);
249
+ return db.transaction(insert);
241
250
  }
242
251
  /**
243
252
  * Delivers pending notification e-mails. Rows are claimed with SKIP LOCKED so
@@ -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);
@@ -2,12 +2,29 @@ import { buildAbility } from '../auth/ability.js';
2
2
  import { AdulaError } from '../admin/errors.js';
3
3
  import { canQueryField } from '../admin/resource_service.js';
4
4
  import { logActivity } from './activity.js';
5
+ import { ActorStore } from '../auth/actor_store.js';
5
6
  import { filterCondition } from '../admin/resource/query.js';
6
7
  const NAME_LIMIT = 60;
7
8
  const VIEW_LIMIT = 50;
8
9
  /** Shared views are visible to every viewer of a resource; cap them per resource. */
9
10
  const SHARED_LIMIT = 100;
10
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
+ }
11
28
  /**
12
29
  * A saved view is stored user input that later drives a list query, so every key
13
30
  * is validated against the resource definition before it is written and again
@@ -22,7 +39,7 @@ export class SavedViews {
22
39
  this.registry = registry;
23
40
  }
24
41
  async list(name, actor) {
25
- const { resource } = this.authorize(name, actor);
42
+ const { resource, ability } = this.authorize(name, actor);
26
43
  // Own views first, so colleagues' shared views can never crowd them out.
27
44
  const rows = await this.db('saved_views')
28
45
  .where('resource', resource.name)
@@ -30,20 +47,39 @@ export class SavedViews {
30
47
  .orderByRaw('(user_id = ?) DESC', [actor.id])
31
48
  .orderBy('name')
32
49
  .limit(VIEW_LIMIT + SHARED_LIMIT);
33
- 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;
34
64
  const query = this.sanitize(resource, row.query);
35
- return query
36
- ? [
37
- {
38
- id: Number(row.id),
39
- name: String(row.name),
40
- query,
41
- shared: Boolean(row.shared),
42
- own: Number(row.user_id) === actor.id,
43
- },
44
- ]
45
- : [];
46
- });
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;
47
83
  }
48
84
  async save(name, actor, input) {
49
85
  const { resource, ability } = this.authorize(name, actor);
@@ -52,19 +88,14 @@ export class SavedViews {
52
88
  throw new AdulaError(422, 'E_VIEW_NAME', 'اسم العرض مطلوب ولا يتجاوز 60 حرفاً');
53
89
  const query = this.sanitize(resource, input.query, true);
54
90
  // A view may only query what its author may query; stored filters must not probe hidden fields.
55
- const queried = [
56
- ...(query.sort ? [query.sort] : []),
57
- ...Object.keys(query.filters ?? {}),
58
- ...(query.search
59
- ? Object.entries(resource.fields)
60
- .filter(([, field]) => field.searchable)
61
- .map(([key]) => key)
62
- : []),
63
- ];
64
- for (const key of queried)
91
+ for (const key of queriedKeys(resource, query))
65
92
  if (!canQueryField(resource, actor, ability, key))
66
93
  throw new AdulaError(403, 'E_FIELD_FORBIDDEN', `لا يمكنك الاستعلام بهذا الحقل: ${key}`);
67
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', 'مشاركة العرض تتطلب صلاحية تعديل هذا الكيان');
68
99
  const existing = await this.db('saved_views')
69
100
  .where({ user_id: actor.id, resource: resource.name, name: label })
70
101
  .first('id', 'shared');
@@ -19,8 +19,8 @@ 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
21
  /**
22
- * Settings that hold a sealed secret (`channels.*`, written by their own section). The
23
- * settings screen lists them read-only and never returns the sealed value.
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
24
  */
25
25
  export declare function isSealedSetting(key: string): boolean;
26
26
  export declare function parseSettingValue(text: string): unknown;