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.
- package/README.md +149 -18
- package/build/agent/AGENTS.template.md +4 -4
- package/build/agent/capabilities.md +22 -12
- package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
- package/build/agent/skills/idea-review/SKILL.md +2 -2
- package/build/commands/adula_assistant_prune.d.ts +10 -0
- package/build/commands/adula_assistant_prune.js +12 -0
- package/build/commands/adula_outbox.d.ts +10 -0
- package/build/commands/adula_outbox.js +11 -0
- package/build/commands/adula_restore_reconcile.d.ts +10 -0
- package/build/commands/adula_restore_reconcile.js +34 -0
- package/build/commands/adula_runtime_health.d.ts +10 -0
- package/build/commands/adula_runtime_health.js +27 -0
- package/build/commands/adula_uploads_prune.d.ts +10 -0
- package/build/commands/adula_uploads_prune.js +16 -0
- package/build/commands/app.d.ts +10 -0
- package/build/commands/app.js +64 -0
- package/build/commands/backup_create.d.ts +11 -0
- package/build/commands/backup_create.js +99 -0
- package/build/commands/backup_open.d.ts +16 -0
- package/build/commands/backup_open.js +48 -0
- package/build/commands/backup_restore_files.d.ts +11 -0
- package/build/commands/backup_restore_files.js +44 -0
- package/build/commands/backup_restore_test.d.ts +12 -0
- package/build/commands/backup_restore_test.js +188 -0
- package/build/commands/backup_seal.d.ts +12 -0
- package/build/commands/backup_seal.js +36 -0
- package/build/commands/backup_services.d.ts +33 -0
- package/build/commands/backup_services.js +6 -0
- package/build/commands/backup_verify.d.ts +9 -0
- package/build/commands/backup_verify.js +59 -0
- package/build/commands/backup_verify_snapshot.d.ts +10 -0
- package/build/commands/backup_verify_snapshot.js +37 -0
- package/build/commands/client.d.ts +16 -0
- package/build/commands/client.js +71 -0
- package/build/commands/doctor.js +21 -1
- package/build/commands/install.d.ts +8 -0
- package/build/commands/install.js +69 -45
- package/build/commands/main.d.ts +3 -2
- package/build/commands/main.js +32 -0
- package/build/commands/module_add.js +4 -20
- package/build/commands/resource.d.ts +2 -0
- package/build/commands/resource.js +12 -3
- package/build/commands/resource_migration.d.ts +15 -0
- package/build/commands/resource_migration.js +81 -0
- package/build/commands/resource_snapshot.d.ts +2 -0
- package/build/commands/resource_snapshot.js +21 -4
- package/build/commands/sla_evaluate.d.ts +14 -0
- package/build/commands/sla_evaluate.js +16 -0
- package/build/commands/ui.js +4 -2
- package/build/commands/ui_css.d.ts +9 -0
- package/build/commands/ui_css.js +19 -0
- package/build/commands/upgrade.d.ts +1 -1
- package/build/commands/upgrade.js +1 -1
- package/build/configure.js +1 -1
- package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
- package/build/database/migrations/1770000000020_two_factor.js +10 -0
- package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
- package/build/database/migrations/1770000000041_import_modes.js +10 -0
- package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
- package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
- package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
- package/build/database/migrations/1770000000043_notification_channels.js +10 -0
- package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
- package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
- package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
- package/build/database/migrations/1770000000045_import_leases.js +10 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
- package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
- package/build/database/migrations/1770000000049_print_templates.js +10 -0
- package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
- package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
- package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
- package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
- package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
- package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
- package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
- package/build/database/migrations/1770000000056_appearance.js +10 -0
- package/build/index.d.ts +87 -11
- package/build/index.js +50 -7
- package/build/providers/adula_provider.d.ts +2 -0
- package/build/providers/adula_provider.js +7 -0
- package/build/src/admin/contracts.js +1 -1
- package/build/src/admin/controller.d.ts +14 -1
- package/build/src/admin/controller.js +91 -13
- package/build/src/admin/errors.d.ts +32 -0
- package/build/src/admin/errors.js +63 -1
- package/build/src/admin/presentation.d.ts +21 -2
- package/build/src/admin/resource/editor.d.ts +60 -0
- package/build/src/admin/resource/editor.js +345 -0
- package/build/src/admin/resource/export.d.ts +54 -0
- package/build/src/admin/resource/export.js +262 -0
- package/build/src/admin/resource/lifecycle.d.ts +23 -0
- package/build/src/admin/resource/lifecycle.js +91 -0
- package/build/src/admin/resource/query.d.ts +111 -0
- package/build/src/admin/resource/query.js +595 -0
- package/build/src/admin/resource/read.d.ts +109 -0
- package/build/src/admin/resource/read.js +388 -0
- package/build/src/admin/resource/shared.d.ts +93 -0
- package/build/src/admin/resource/shared.js +265 -0
- package/build/src/admin/resource/trash.d.ts +10 -0
- package/build/src/admin/resource/trash.js +56 -0
- package/build/src/admin/resource/write.d.ts +57 -0
- package/build/src/admin/resource/write.js +603 -0
- package/build/src/admin/resource_service.d.ts +80 -193
- package/build/src/admin/resource_service.js +81 -1343
- package/build/src/admin/resource_tools.d.ts +111 -0
- package/build/src/admin/resource_tools.js +139 -0
- package/build/src/ai/assistant.d.ts +100 -0
- package/build/src/ai/assistant.js +487 -0
- package/build/src/ai/client.d.ts +49 -0
- package/build/src/ai/client.js +85 -0
- package/build/src/ai/prompt.d.ts +23 -0
- package/build/src/ai/prompt.js +83 -0
- package/build/src/ai/settings.d.ts +56 -0
- package/build/src/ai/settings.js +214 -0
- package/build/src/ai/usage.d.ts +16 -0
- package/build/src/ai/usage.js +33 -0
- package/build/src/appearance/appearance.d.ts +134 -0
- package/build/src/appearance/appearance.js +461 -0
- package/build/src/appearance/colors.d.ts +43 -0
- package/build/src/appearance/colors.js +99 -0
- package/build/src/appearance/logo.d.ts +32 -0
- package/build/src/appearance/logo.js +112 -0
- package/build/src/attachments/attachment_service.d.ts +46 -2
- package/build/src/attachments/attachment_service.js +96 -4
- package/build/src/auth/actor_store.d.ts +5 -1
- package/build/src/auth/actor_store.js +8 -4
- package/build/src/auth/conditions.d.ts +5 -0
- package/build/src/auth/conditions.js +26 -3
- package/build/src/auth/sql.js +17 -5
- package/build/src/auth/two_factor.d.ts +96 -0
- package/build/src/auth/two_factor.js +259 -0
- package/build/src/backups/archive.d.ts +52 -0
- package/build/src/backups/archive.js +362 -0
- package/build/src/backups/cloud_backups.d.ts +133 -0
- package/build/src/backups/cloud_backups.js +650 -0
- package/build/src/backups/doctor.d.ts +7 -0
- package/build/src/backups/doctor.js +55 -0
- package/build/src/backups/providers.d.ts +81 -0
- package/build/src/backups/providers.js +470 -0
- package/build/src/collaboration/assignments.d.ts +59 -2
- package/build/src/collaboration/assignments.js +196 -74
- package/build/src/collaboration/record_collaboration.d.ts +21 -4
- package/build/src/collaboration/record_collaboration.js +126 -51
- package/build/src/collaboration/shared.d.ts +24 -0
- package/build/src/collaboration/shared.js +34 -0
- package/build/src/commands/app_scaffold.d.ts +72 -0
- package/build/src/commands/app_scaffold.js +285 -0
- package/build/src/commands/capabilities.js +35 -9
- package/build/src/commands/doctor.d.ts +24 -2
- package/build/src/commands/doctor.js +81 -6
- package/build/src/commands/gap_report.d.ts +1 -1
- package/build/src/commands/gap_report.js +2 -2
- package/build/src/commands/generator.d.ts +37 -1
- package/build/src/commands/generator.js +61 -18
- package/build/src/commands/snapshot.d.ts +24 -13
- package/build/src/commands/snapshot.js +54 -14
- package/build/src/commands/source_markers.d.ts +10 -0
- package/build/src/commands/source_markers.js +29 -0
- package/build/src/core/activity.d.ts +2 -0
- package/build/src/core/activity.js +7 -1
- package/build/src/core/administrators.d.ts +38 -0
- package/build/src/core/administrators.js +145 -0
- package/build/src/core/avatar_image.d.ts +33 -0
- package/build/src/core/avatar_image.js +278 -0
- package/build/src/core/html_sanitizer.d.ts +20 -0
- package/build/src/core/html_sanitizer.js +261 -0
- package/build/src/core/like.d.ts +5 -0
- package/build/src/core/like.js +5 -0
- package/build/src/core/lookups.d.ts +80 -0
- package/build/src/core/lookups.js +319 -0
- package/build/src/core/mail_settings.d.ts +83 -0
- package/build/src/core/mail_settings.js +274 -0
- package/build/src/core/mail_test.d.ts +16 -0
- package/build/src/core/mail_test.js +81 -6
- package/build/src/core/message_templates.d.ts +15 -2
- package/build/src/core/message_templates.js +81 -11
- package/build/src/core/module_seed.js +2 -1
- package/build/src/core/notification_channels.d.ts +235 -0
- package/build/src/core/notification_channels.js +660 -0
- package/build/src/core/roles.js +26 -9
- package/build/src/core/saved_views.d.ts +8 -1
- package/build/src/core/saved_views.js +91 -26
- package/build/src/core/sequences.d.ts +32 -0
- package/build/src/core/sequences.js +97 -0
- package/build/src/core/settings.d.ts +5 -0
- package/build/src/core/settings.js +31 -3
- package/build/src/core/template_language.d.ts +61 -0
- package/build/src/core/template_language.js +141 -0
- package/build/src/core/ui_preferences.d.ts +10 -0
- package/build/src/core/ui_preferences.js +15 -1
- package/build/src/core/user_avatars.d.ts +79 -0
- package/build/src/core/user_avatars.js +186 -0
- package/build/src/core/user_invitations.d.ts +5 -1
- package/build/src/core/user_invitations.js +7 -1
- package/build/src/core/user_preferences.d.ts +36 -0
- package/build/src/core/user_preferences.js +125 -0
- package/build/src/core/users.d.ts +2 -0
- package/build/src/core/users.js +5 -3
- package/build/src/database/calendar_days.d.ts +19 -0
- package/build/src/database/calendar_days.js +36 -0
- package/build/src/database/schema.d.ts +201 -2
- package/build/src/database/schema.js +713 -59
- package/build/src/database/schema_diff.d.ts +70 -0
- package/build/src/database/schema_diff.js +190 -0
- package/build/src/events/record_mutation.d.ts +2 -1
- package/build/src/events/record_mutation.js +1 -0
- package/build/src/integrations/api_client.d.ts +37 -0
- package/build/src/integrations/api_client.js +567 -0
- package/build/src/integrations/import_adapters.d.ts +37 -0
- package/build/src/integrations/import_adapters.js +35 -0
- package/build/src/integrations/imports.d.ts +130 -16
- package/build/src/integrations/imports.js +434 -73
- package/build/src/integrations/openapi.d.ts +3 -1
- package/build/src/integrations/openapi.js +465 -31
- package/build/src/integrations/outbound.d.ts +94 -0
- package/build/src/integrations/outbound.js +276 -0
- package/build/src/integrations/print.d.ts +22 -1
- package/build/src/integrations/print.js +68 -22
- package/build/src/integrations/print_templates.d.ts +216 -0
- package/build/src/integrations/print_templates.js +1017 -0
- package/build/src/integrations/sync_jobs.d.ts +139 -0
- package/build/src/integrations/sync_jobs.js +416 -0
- package/build/src/integrations/webhooks.d.ts +12 -12
- package/build/src/integrations/webhooks.js +34 -43
- package/build/src/integrations/xlsx.d.ts +41 -0
- package/build/src/integrations/xlsx.js +519 -0
- package/build/src/languages/ar.d.ts +11 -0
- package/build/src/languages/ar.js +358 -0
- package/build/src/languages/ar_ui.d.ts +461 -0
- package/build/src/languages/ar_ui.js +464 -0
- package/build/src/languages/catalog.d.ts +66 -0
- package/build/src/languages/catalog.js +152 -0
- package/build/src/languages/en.d.ts +7 -0
- package/build/src/languages/en.js +352 -0
- package/build/src/languages/en_ui.d.ts +3 -0
- package/build/src/languages/en_ui.js +458 -0
- package/build/src/languages/validation.d.ts +26 -0
- package/build/src/languages/validation.js +60 -0
- package/build/src/lists/bulk_actions.d.ts +89 -0
- package/build/src/lists/bulk_actions.js +268 -0
- package/build/src/lists/dashboards.d.ts +138 -0
- package/build/src/lists/dashboards.js +290 -0
- package/build/src/mcp/tools.js +9 -104
- package/build/src/resource/define_resource.d.ts +18 -1
- package/build/src/resource/define_resource.js +212 -18
- package/build/src/resource/definition.d.ts +44 -0
- package/build/src/resource/definition.js +171 -0
- package/build/src/resource/registry.js +15 -4
- package/build/src/resource/types.d.ts +313 -16
- package/build/src/resource/values.d.ts +56 -1
- package/build/src/resource/values.js +237 -5
- package/build/src/services/settings.d.ts +2 -0
- package/build/src/services/settings.js +5 -1
- package/build/src/upgrade/legacy.js +2 -2
- package/build/src/workflows/calendar.d.ts +9 -0
- package/build/src/workflows/calendar.js +44 -0
- package/build/src/workflows/define_workflow.d.ts +48 -3
- package/build/src/workflows/define_workflow.js +57 -13
- package/build/src/workflows/delegations.d.ts +107 -0
- package/build/src/workflows/delegations.js +326 -0
- package/build/src/workflows/engine.d.ts +80 -4
- package/build/src/workflows/engine.js +466 -86
- package/build/src/workflows/sla.d.ts +15 -0
- package/build/src/workflows/sla.js +8 -0
- package/build/stubs/resource_contract.txt +12 -1
- package/package.json +9 -2
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import { columnName } from '../resource/define_resource.js';
|
|
2
|
+
import { AdulaError } from '../admin/errors.js';
|
|
3
|
+
import { logActivity } from './activity.js';
|
|
4
|
+
const RESOURCE = 'core.lookups';
|
|
5
|
+
const GROUP = /^[a-z][a-z0-9_]{0,99}$/;
|
|
6
|
+
const KEY = /^[a-z0-9][a-z0-9_-]{0,99}$/;
|
|
7
|
+
function group(value) {
|
|
8
|
+
if (typeof value !== 'string' || !GROUP.test(value))
|
|
9
|
+
throw new AdulaError(422, 'E_LOOKUP_GROUP', 'اسم القائمة يبدأ بحرف إنجليزي صغير ويحوي حروفاً صغيرة وأرقاماً وشرطة سفلية فقط');
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
function key(value) {
|
|
13
|
+
if (typeof value !== 'string' || !KEY.test(value))
|
|
14
|
+
throw new AdulaError(422, 'E_LOOKUP_KEY', 'المفتاح يحوي حروفاً إنجليزية صغيرة وأرقاماً وشرطة أو شرطة سفلية فقط');
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function label(value, required) {
|
|
18
|
+
const text = typeof value === 'string' ? value.trim() : '';
|
|
19
|
+
if (value !== undefined && value !== null && typeof value !== 'string')
|
|
20
|
+
throw new AdulaError(422, 'E_LOOKUP_LABEL', 'التسمية يجب أن تكون نصاً');
|
|
21
|
+
if (required && !text)
|
|
22
|
+
throw new AdulaError(422, 'E_LOOKUP_LABEL', 'التسمية العربية مطلوبة');
|
|
23
|
+
if (text.length > 255)
|
|
24
|
+
throw new AdulaError(422, 'E_LOOKUP_LABEL', 'التسمية لا تتجاوز 255 حرفاً');
|
|
25
|
+
return text;
|
|
26
|
+
}
|
|
27
|
+
function sort(value) {
|
|
28
|
+
const number = typeof value === 'string' && value.trim() ? Number(value) : value;
|
|
29
|
+
if (typeof number !== 'number' || !Number.isSafeInteger(number) || Math.abs(number) > 2 ** 31 - 1)
|
|
30
|
+
throw new AdulaError(422, 'E_LOOKUP_SORT', 'الترتيب يجب أن يكون عدداً صحيحاً');
|
|
31
|
+
return number;
|
|
32
|
+
}
|
|
33
|
+
function lookupId(value) {
|
|
34
|
+
const id = Number(value);
|
|
35
|
+
if (!Number.isSafeInteger(id) || id <= 0)
|
|
36
|
+
throw new AdulaError(404, 'E_LOOKUP_NOT_FOUND', 'القيمة غير موجودة');
|
|
37
|
+
return id;
|
|
38
|
+
}
|
|
39
|
+
/** The English label column is required; a value without one shows its key, as imports match it. */
|
|
40
|
+
const english = (text, fallback) => text || fallback;
|
|
41
|
+
/**
|
|
42
|
+
* Administration of lookup values (lookups table). Values are never renamed or removed while
|
|
43
|
+
* records hold them: the key is immutable, a value stored by any record cannot be disabled
|
|
44
|
+
* (the record validator requires an active value on every save, so a disabled stored value
|
|
45
|
+
* would block editing those records), and only an unused value that no registered module
|
|
46
|
+
* declares may be deleted (a declared value would be seeded again on the next installation).
|
|
47
|
+
* Usage is counted from the registered resources' lookup fields; without a registry it is
|
|
48
|
+
* unknown and disabling or deleting is refused.
|
|
49
|
+
*/
|
|
50
|
+
export class LookupsAdmin {
|
|
51
|
+
db;
|
|
52
|
+
registry;
|
|
53
|
+
constructor(db, registry) {
|
|
54
|
+
this.db = db;
|
|
55
|
+
this.registry = registry;
|
|
56
|
+
}
|
|
57
|
+
/** Lookup fields of the registered resources, by group. */
|
|
58
|
+
fields(name) {
|
|
59
|
+
if (!this.registry)
|
|
60
|
+
return [];
|
|
61
|
+
return this.registry.all().flatMap((resource) => Object.entries(resource.fields).flatMap(([field, definition]) => definition.type === 'lookup' && (name === undefined || definition.group === name)
|
|
62
|
+
? [
|
|
63
|
+
{
|
|
64
|
+
resource: resource.name,
|
|
65
|
+
field,
|
|
66
|
+
label: definition.label.ar,
|
|
67
|
+
table: resource.name,
|
|
68
|
+
column: definition.column ?? columnName(field),
|
|
69
|
+
group: definition.group,
|
|
70
|
+
},
|
|
71
|
+
]
|
|
72
|
+
: []));
|
|
73
|
+
}
|
|
74
|
+
declared() {
|
|
75
|
+
const keys = new Set();
|
|
76
|
+
for (const module of this.registry?.modules() ?? [])
|
|
77
|
+
for (const [name, rows] of Object.entries(module.lookups ?? {}))
|
|
78
|
+
for (const row of rows)
|
|
79
|
+
keys.add(`${name}\u0000${row.key}`);
|
|
80
|
+
return keys;
|
|
81
|
+
}
|
|
82
|
+
async groups() {
|
|
83
|
+
const rows = await this.db('lookups')
|
|
84
|
+
.select('group')
|
|
85
|
+
.count('* as total')
|
|
86
|
+
.select(this.db.raw('count(*) FILTER (WHERE active) AS active'))
|
|
87
|
+
.groupBy('group');
|
|
88
|
+
const declared = [...this.declared()].map((entry) => entry.split('\u0000')[0]);
|
|
89
|
+
const names = new Set([
|
|
90
|
+
...rows.map((row) => String(row.group)),
|
|
91
|
+
...this.fields().map((field) => field.group),
|
|
92
|
+
...declared,
|
|
93
|
+
]);
|
|
94
|
+
return [...names].sort().map((name) => {
|
|
95
|
+
const row = rows.find((entry) => entry.group === name);
|
|
96
|
+
return {
|
|
97
|
+
group: name,
|
|
98
|
+
total: Number(row?.total ?? 0),
|
|
99
|
+
active: Number(row?.active ?? 0),
|
|
100
|
+
fields: this.fields(name).map(({ resource, field, label: text }) => ({
|
|
101
|
+
resource,
|
|
102
|
+
field,
|
|
103
|
+
label: text,
|
|
104
|
+
})),
|
|
105
|
+
declared: declared.includes(name),
|
|
106
|
+
};
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
async values(name) {
|
|
110
|
+
// A group named by a registered field is listed even when it predates the slug rule.
|
|
111
|
+
const selected = typeof name === 'string' && this.fields(name).length ? name : group(name);
|
|
112
|
+
const rows = await this.db('lookups').where('group', selected).orderBy(['sort', 'key']);
|
|
113
|
+
const usage = await this.usageByKey(this.db, selected, rows.map((row) => String(row.key)));
|
|
114
|
+
const declared = this.declared();
|
|
115
|
+
return rows.map((row) => ({
|
|
116
|
+
...this.toValue(row, declared),
|
|
117
|
+
usage: usage ? (usage.get(String(row.key)) ?? 0) : null,
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
async create(actorId, input) {
|
|
121
|
+
const values = {
|
|
122
|
+
group: group(input.group),
|
|
123
|
+
key: key(input.key),
|
|
124
|
+
labelAr: label(input.labelAr, true),
|
|
125
|
+
labelEn: label(input.labelEn, false),
|
|
126
|
+
};
|
|
127
|
+
return this.db.transaction(async (trx) => {
|
|
128
|
+
if (await trx('lookups').where({ group: values.group, key: values.key }).first('id'))
|
|
129
|
+
throw new AdulaError(409, 'E_LOOKUP_EXISTS', 'هذا المفتاح موجود في القائمة');
|
|
130
|
+
const last = await trx('lookups').where('group', values.group).max('sort as max').first();
|
|
131
|
+
const position = input.sort === undefined || input.sort === null || input.sort === ''
|
|
132
|
+
? Number(last?.max ?? -1) + 1
|
|
133
|
+
: sort(input.sort);
|
|
134
|
+
const [row] = await trx('lookups')
|
|
135
|
+
.insert({
|
|
136
|
+
group: values.group,
|
|
137
|
+
key: values.key,
|
|
138
|
+
label_ar: values.labelAr,
|
|
139
|
+
label_en: english(values.labelEn, values.key),
|
|
140
|
+
sort: position,
|
|
141
|
+
active: true,
|
|
142
|
+
})
|
|
143
|
+
.returning('*');
|
|
144
|
+
await logActivity(trx, {
|
|
145
|
+
resource: RESOURCE,
|
|
146
|
+
recordId: row.id,
|
|
147
|
+
actorId,
|
|
148
|
+
action: 'create',
|
|
149
|
+
changes: {
|
|
150
|
+
group: row.group,
|
|
151
|
+
key: row.key,
|
|
152
|
+
labelAr: row.label_ar,
|
|
153
|
+
labelEn: row.label_en,
|
|
154
|
+
sort: row.sort,
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
return { ...this.toValue(row, this.declared()), usage: 0 };
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
async update(actorId, id, input) {
|
|
161
|
+
const recordId = lookupId(id);
|
|
162
|
+
return this.db.transaction(async (trx) => {
|
|
163
|
+
const row = await this.lock(trx, recordId);
|
|
164
|
+
if (input.key !== undefined && input.key !== row.key)
|
|
165
|
+
throw new AdulaError(422, 'E_LOOKUP_KEY_IMMUTABLE', 'لا يمكن تغيير المفتاح لأن السجلات تحفظه؛ أضف قيمة جديدة وعطّل القديمة');
|
|
166
|
+
const next = {};
|
|
167
|
+
if (input.labelAr !== undefined)
|
|
168
|
+
next.label_ar = label(input.labelAr, true);
|
|
169
|
+
if (input.labelEn !== undefined)
|
|
170
|
+
next.label_en = english(label(input.labelEn, false), row.key);
|
|
171
|
+
if (input.sort !== undefined)
|
|
172
|
+
next.sort = sort(input.sort);
|
|
173
|
+
const changes = Object.fromEntries(Object.entries(next).filter(([column, value]) => row[column] !== value));
|
|
174
|
+
if (!Object.keys(changes).length)
|
|
175
|
+
return this.withUsage(trx, row);
|
|
176
|
+
const [updated] = await trx('lookups').where('id', recordId).update(changes).returning('*');
|
|
177
|
+
await logActivity(trx, {
|
|
178
|
+
resource: RESOURCE,
|
|
179
|
+
recordId,
|
|
180
|
+
actorId,
|
|
181
|
+
action: 'update',
|
|
182
|
+
changes: {
|
|
183
|
+
group: row.group,
|
|
184
|
+
key: row.key,
|
|
185
|
+
...Object.fromEntries(Object.entries(changes).map(([column, value]) => [
|
|
186
|
+
{ label_ar: 'labelAr', label_en: 'labelEn', sort: 'sort' }[column],
|
|
187
|
+
{ from: row[column], to: value },
|
|
188
|
+
])),
|
|
189
|
+
},
|
|
190
|
+
});
|
|
191
|
+
return this.withUsage(trx, updated);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/** Sets the order of a whole group: `ids` lists every value of the group once, first to last. */
|
|
195
|
+
async reorder(actorId, name, ids) {
|
|
196
|
+
const selected = group(name);
|
|
197
|
+
if (!Array.isArray(ids) || !ids.length)
|
|
198
|
+
throw new AdulaError(422, 'E_LOOKUP_ORDER', 'أرسل ترتيب قيم القائمة كاملة');
|
|
199
|
+
const order = ids.map((id) => lookupId(id));
|
|
200
|
+
return this.db.transaction(async (trx) => {
|
|
201
|
+
const rows = await trx('lookups').where('group', selected).forUpdate().select('*');
|
|
202
|
+
const known = new Set(rows.map((row) => Number(row.id)));
|
|
203
|
+
if (!rows.length ||
|
|
204
|
+
new Set(order).size !== order.length ||
|
|
205
|
+
order.length !== rows.length ||
|
|
206
|
+
order.some((id) => !known.has(id)))
|
|
207
|
+
throw new AdulaError(422, 'E_LOOKUP_ORDER', 'الترتيب يجب أن يذكر كل قيم القائمة مرة واحدة فقط');
|
|
208
|
+
for (const [position, id] of order.entries()) {
|
|
209
|
+
const row = rows.find((entry) => Number(entry.id) === id);
|
|
210
|
+
if (row.sort === position)
|
|
211
|
+
continue;
|
|
212
|
+
await trx('lookups').where('id', id).update({ sort: position });
|
|
213
|
+
await logActivity(trx, {
|
|
214
|
+
resource: RESOURCE,
|
|
215
|
+
recordId: id,
|
|
216
|
+
actorId,
|
|
217
|
+
action: 'reorder',
|
|
218
|
+
changes: { group: selected, key: row.key, sort: { from: row.sort, to: position } },
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
return new LookupsAdmin(trx, this.registry).values(selected);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
async disable(actorId, id) {
|
|
225
|
+
return this.setActive(actorId, lookupId(id), false);
|
|
226
|
+
}
|
|
227
|
+
async enable(actorId, id) {
|
|
228
|
+
return this.setActive(actorId, lookupId(id), true);
|
|
229
|
+
}
|
|
230
|
+
async delete(actorId, id) {
|
|
231
|
+
const recordId = lookupId(id);
|
|
232
|
+
return this.db.transaction(async (trx) => {
|
|
233
|
+
const row = await this.lock(trx, recordId);
|
|
234
|
+
if (this.declared().has(`${row.group}\u0000${row.key}`))
|
|
235
|
+
throw new AdulaError(409, 'E_LOOKUP_DECLARED', 'هذه القيمة معرّفة في أحد التطبيقات وتعود عند التثبيت؛ عطّلها بدلاً من حذفها');
|
|
236
|
+
await this.refuseInUse(trx, row, 'حذفها');
|
|
237
|
+
await trx('lookups').where('id', recordId).delete();
|
|
238
|
+
await logActivity(trx, {
|
|
239
|
+
resource: RESOURCE,
|
|
240
|
+
recordId,
|
|
241
|
+
actorId,
|
|
242
|
+
action: 'delete',
|
|
243
|
+
changes: { group: row.group, key: row.key, labelAr: row.label_ar },
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
async setActive(actorId, id, active) {
|
|
248
|
+
return this.db.transaction(async (trx) => {
|
|
249
|
+
const row = await this.lock(trx, id);
|
|
250
|
+
if (row.active === active)
|
|
251
|
+
return this.withUsage(trx, row);
|
|
252
|
+
if (!active)
|
|
253
|
+
await this.refuseInUse(trx, row, 'تعطيلها');
|
|
254
|
+
const [updated] = await trx('lookups').where('id', id).update({ active }).returning('*');
|
|
255
|
+
await logActivity(trx, {
|
|
256
|
+
resource: RESOURCE,
|
|
257
|
+
recordId: id,
|
|
258
|
+
actorId,
|
|
259
|
+
action: active ? 'enable' : 'disable',
|
|
260
|
+
changes: { group: row.group, key: row.key },
|
|
261
|
+
});
|
|
262
|
+
return this.withUsage(trx, updated);
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
async refuseInUse(db, row, verb) {
|
|
266
|
+
const usage = await this.usageByKey(db, row.group, [row.key]);
|
|
267
|
+
if (!usage)
|
|
268
|
+
throw new AdulaError(409, 'E_LOOKUP_USAGE_UNKNOWN', `تعذّر التحقق من استخدام القيمة، لذلك لا يمكن ${verb}`);
|
|
269
|
+
const count = usage.get(row.key) ?? 0;
|
|
270
|
+
if (count > 0)
|
|
271
|
+
throw new AdulaError(409, 'E_LOOKUP_IN_USE', `لا يمكن ${verb}: القيمة «${row.label_ar}» محفوظة في ${count} سجل. غيّر قيمة هذه السجلات أولاً.`);
|
|
272
|
+
}
|
|
273
|
+
async lock(trx, id) {
|
|
274
|
+
const row = await trx('lookups').where('id', id).forUpdate().first();
|
|
275
|
+
if (!row)
|
|
276
|
+
throw new AdulaError(404, 'E_LOOKUP_NOT_FOUND', 'القيمة غير موجودة');
|
|
277
|
+
return row;
|
|
278
|
+
}
|
|
279
|
+
async withUsage(db, row) {
|
|
280
|
+
const usage = await this.usageByKey(db, row.group, [row.key]);
|
|
281
|
+
return {
|
|
282
|
+
...this.toValue(row, this.declared()),
|
|
283
|
+
usage: usage ? (usage.get(row.key) ?? 0) : null,
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
/** Records holding each key, over every registered field of the group; null without a registry. */
|
|
287
|
+
async usageByKey(db, name, keys) {
|
|
288
|
+
if (!this.registry)
|
|
289
|
+
return null;
|
|
290
|
+
const counts = new Map();
|
|
291
|
+
if (!keys.length)
|
|
292
|
+
return counts;
|
|
293
|
+
for (const field of this.fields(name)) {
|
|
294
|
+
const exists = await db.raw('SELECT to_regclass(?) AS name', [field.table]);
|
|
295
|
+
if (!exists.rows[0]?.name)
|
|
296
|
+
continue;
|
|
297
|
+
const rows = await db(field.table)
|
|
298
|
+
.whereIn(field.column, keys)
|
|
299
|
+
.groupBy(field.column)
|
|
300
|
+
.select(`${field.column} as key`)
|
|
301
|
+
.count('* as count');
|
|
302
|
+
for (const row of rows)
|
|
303
|
+
counts.set(String(row.key), (counts.get(String(row.key)) ?? 0) + Number(row.count));
|
|
304
|
+
}
|
|
305
|
+
return counts;
|
|
306
|
+
}
|
|
307
|
+
toValue(row, declared) {
|
|
308
|
+
return {
|
|
309
|
+
id: Number(row.id),
|
|
310
|
+
group: String(row.group),
|
|
311
|
+
key: String(row.key),
|
|
312
|
+
labelAr: String(row.label_ar),
|
|
313
|
+
labelEn: String(row.label_en),
|
|
314
|
+
sort: Number(row.sort),
|
|
315
|
+
active: Boolean(row.active),
|
|
316
|
+
declared: declared.has(`${row.group}\u0000${row.key}`),
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { Knex } from 'knex';
|
|
2
|
+
import type { Actor } from '../auth/ability.js';
|
|
3
|
+
import type { SecretBox } from '../integrations/webhooks.js';
|
|
4
|
+
import { type OutboundOptions, type OutboundTarget } from '../integrations/outbound.js';
|
|
5
|
+
export declare const MAIL_SETTINGS_KEY = "mail.smtp";
|
|
6
|
+
/** How the SMTP connection is protected: implicit TLS, STARTTLS upgrade, or none. */
|
|
7
|
+
export type MailSecurity = 'tls' | 'starttls' | 'none';
|
|
8
|
+
/** The stored SMTP configuration as the administration shows it; the password never leaves. */
|
|
9
|
+
export type MailSettingsView = {
|
|
10
|
+
configured: boolean;
|
|
11
|
+
preset: string;
|
|
12
|
+
host: string;
|
|
13
|
+
port: number;
|
|
14
|
+
security: MailSecurity;
|
|
15
|
+
username: string;
|
|
16
|
+
hasPassword: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* A password is stored but cannot be opened (APP_KEY rotated, or the value is damaged).
|
|
19
|
+
* Nothing is sent until it is entered again; sending never falls back to no sign-in.
|
|
20
|
+
*/
|
|
21
|
+
passwordUnreadable: boolean;
|
|
22
|
+
fromName: string;
|
|
23
|
+
fromAddress: string;
|
|
24
|
+
updatedAt: string | null;
|
|
25
|
+
};
|
|
26
|
+
export type MailSettingsInput = Partial<Pick<MailSettingsView, 'preset' | 'host' | 'port' | 'security' | 'username' | 'fromName' | 'fromAddress'>>;
|
|
27
|
+
/** What the sending process needs: the options and the opened password, server side only. */
|
|
28
|
+
export type MailRuntime = {
|
|
29
|
+
host: string;
|
|
30
|
+
port: number;
|
|
31
|
+
security: MailSecurity;
|
|
32
|
+
username: string;
|
|
33
|
+
password: string | null;
|
|
34
|
+
fromName: string;
|
|
35
|
+
fromAddress: string;
|
|
36
|
+
};
|
|
37
|
+
type Who = Pick<Actor, 'id' | 'impersonatorId'>;
|
|
38
|
+
/**
|
|
39
|
+
* The stored SMTP password cannot be opened. It carries a category only, never the sealed or
|
|
40
|
+
* the opened value, and classifies as `password_unreadable` (see classifyMailFailure).
|
|
41
|
+
*/
|
|
42
|
+
export declare class MailPasswordUnreadableError extends Error {
|
|
43
|
+
readonly code = "E_MAIL_PASSWORD_UNREADABLE";
|
|
44
|
+
constructor();
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* SMTP settings kept in the system setting `mail.smtp` (ADR 020 amendment), so an administrator
|
|
48
|
+
* configures mail from the interface without editing the environment or restarting. The password
|
|
49
|
+
* is sealed like the assistant key, is never returned, and is cleared whenever the server
|
|
50
|
+
* changes, so a stored password cannot be sent to another host. The host must resolve outside
|
|
51
|
+
* private networks unless the outbound policy allows them.
|
|
52
|
+
*/
|
|
53
|
+
export declare class MailSettings {
|
|
54
|
+
private db;
|
|
55
|
+
private secrets;
|
|
56
|
+
private options;
|
|
57
|
+
constructor(db: Knex, secrets: SecretBox, options?: OutboundOptions);
|
|
58
|
+
read(): Promise<MailSettingsView>;
|
|
59
|
+
/**
|
|
60
|
+
* The stored options with the opened password, or null while nothing is stored. A stored
|
|
61
|
+
* password that cannot be opened throws MailPasswordUnreadableError: the message is not sent
|
|
62
|
+
* without the sign-in the administrator configured.
|
|
63
|
+
*/
|
|
64
|
+
runtime(): Promise<MailRuntime | null>;
|
|
65
|
+
/**
|
|
66
|
+
* The address a connection to `host` must use; refuses private targets per the policy. An
|
|
67
|
+
* unencrypted connection (`none`) is refused unless the address is internal, so the password
|
|
68
|
+
* and the messages never cross the internet in clear text.
|
|
69
|
+
*/
|
|
70
|
+
target(host: string, security?: MailSecurity): Promise<OutboundTarget>;
|
|
71
|
+
/** The opened password, or null when it cannot be opened; never logged or returned. */
|
|
72
|
+
private open;
|
|
73
|
+
private present;
|
|
74
|
+
/** Saves everything except the password. Changing the server clears the stored password. */
|
|
75
|
+
save(actor: Who, input: unknown): Promise<MailSettingsView>;
|
|
76
|
+
/** Stores the SMTP password sealed; it is never returned. */
|
|
77
|
+
setPassword(actor: Who, value: unknown): Promise<MailSettingsView>;
|
|
78
|
+
clearPassword(actor: Who): Promise<MailSettingsView>;
|
|
79
|
+
private write;
|
|
80
|
+
private stored;
|
|
81
|
+
private assertTarget;
|
|
82
|
+
}
|
|
83
|
+
export {};
|
|
@@ -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
|
+
}
|