adula 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -12
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_assistant_prune.d.ts +10 -0
  7. package/build/commands/adula_assistant_prune.js +12 -0
  8. package/build/commands/adula_outbox.d.ts +10 -0
  9. package/build/commands/adula_outbox.js +11 -0
  10. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  11. package/build/commands/adula_restore_reconcile.js +34 -0
  12. package/build/commands/adula_runtime_health.d.ts +10 -0
  13. package/build/commands/adula_runtime_health.js +27 -0
  14. package/build/commands/adula_uploads_prune.d.ts +10 -0
  15. package/build/commands/adula_uploads_prune.js +16 -0
  16. package/build/commands/app.d.ts +10 -0
  17. package/build/commands/app.js +64 -0
  18. package/build/commands/backup_create.d.ts +11 -0
  19. package/build/commands/backup_create.js +99 -0
  20. package/build/commands/backup_open.d.ts +16 -0
  21. package/build/commands/backup_open.js +48 -0
  22. package/build/commands/backup_restore_files.d.ts +11 -0
  23. package/build/commands/backup_restore_files.js +44 -0
  24. package/build/commands/backup_restore_test.d.ts +12 -0
  25. package/build/commands/backup_restore_test.js +188 -0
  26. package/build/commands/backup_seal.d.ts +12 -0
  27. package/build/commands/backup_seal.js +36 -0
  28. package/build/commands/backup_services.d.ts +33 -0
  29. package/build/commands/backup_services.js +6 -0
  30. package/build/commands/backup_verify.d.ts +9 -0
  31. package/build/commands/backup_verify.js +59 -0
  32. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  33. package/build/commands/backup_verify_snapshot.js +37 -0
  34. package/build/commands/client.d.ts +16 -0
  35. package/build/commands/client.js +71 -0
  36. package/build/commands/doctor.js +21 -1
  37. package/build/commands/install.d.ts +8 -0
  38. package/build/commands/install.js +69 -45
  39. package/build/commands/main.d.ts +3 -2
  40. package/build/commands/main.js +32 -0
  41. package/build/commands/module_add.js +4 -20
  42. package/build/commands/resource.d.ts +2 -0
  43. package/build/commands/resource.js +12 -3
  44. package/build/commands/resource_migration.d.ts +15 -0
  45. package/build/commands/resource_migration.js +81 -0
  46. package/build/commands/resource_snapshot.d.ts +2 -0
  47. package/build/commands/resource_snapshot.js +21 -4
  48. package/build/commands/sla_evaluate.d.ts +14 -0
  49. package/build/commands/sla_evaluate.js +16 -0
  50. package/build/commands/ui.js +4 -2
  51. package/build/commands/ui_css.d.ts +9 -0
  52. package/build/commands/ui_css.js +19 -0
  53. package/build/commands/upgrade.d.ts +1 -1
  54. package/build/commands/upgrade.js +1 -1
  55. package/build/configure.js +1 -1
  56. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  57. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  58. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  59. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  60. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  61. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  62. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  63. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  64. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  65. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  66. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  67. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  68. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  69. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  70. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  71. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  72. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  73. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  74. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  75. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  76. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  77. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  78. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  79. package/build/database/migrations/1770000000056_appearance.js +10 -0
  80. package/build/index.d.ts +87 -11
  81. package/build/index.js +50 -7
  82. package/build/providers/adula_provider.d.ts +2 -0
  83. package/build/providers/adula_provider.js +7 -0
  84. package/build/src/admin/contracts.js +1 -1
  85. package/build/src/admin/controller.d.ts +14 -1
  86. package/build/src/admin/controller.js +91 -13
  87. package/build/src/admin/errors.d.ts +32 -0
  88. package/build/src/admin/errors.js +63 -1
  89. package/build/src/admin/presentation.d.ts +21 -2
  90. package/build/src/admin/resource/editor.d.ts +60 -0
  91. package/build/src/admin/resource/editor.js +345 -0
  92. package/build/src/admin/resource/export.d.ts +54 -0
  93. package/build/src/admin/resource/export.js +262 -0
  94. package/build/src/admin/resource/lifecycle.d.ts +23 -0
  95. package/build/src/admin/resource/lifecycle.js +91 -0
  96. package/build/src/admin/resource/query.d.ts +111 -0
  97. package/build/src/admin/resource/query.js +595 -0
  98. package/build/src/admin/resource/read.d.ts +109 -0
  99. package/build/src/admin/resource/read.js +388 -0
  100. package/build/src/admin/resource/shared.d.ts +93 -0
  101. package/build/src/admin/resource/shared.js +265 -0
  102. package/build/src/admin/resource/trash.d.ts +10 -0
  103. package/build/src/admin/resource/trash.js +56 -0
  104. package/build/src/admin/resource/write.d.ts +57 -0
  105. package/build/src/admin/resource/write.js +603 -0
  106. package/build/src/admin/resource_service.d.ts +80 -193
  107. package/build/src/admin/resource_service.js +81 -1343
  108. package/build/src/admin/resource_tools.d.ts +111 -0
  109. package/build/src/admin/resource_tools.js +139 -0
  110. package/build/src/ai/assistant.d.ts +100 -0
  111. package/build/src/ai/assistant.js +487 -0
  112. package/build/src/ai/client.d.ts +49 -0
  113. package/build/src/ai/client.js +85 -0
  114. package/build/src/ai/prompt.d.ts +23 -0
  115. package/build/src/ai/prompt.js +83 -0
  116. package/build/src/ai/settings.d.ts +56 -0
  117. package/build/src/ai/settings.js +214 -0
  118. package/build/src/ai/usage.d.ts +16 -0
  119. package/build/src/ai/usage.js +33 -0
  120. package/build/src/appearance/appearance.d.ts +134 -0
  121. package/build/src/appearance/appearance.js +461 -0
  122. package/build/src/appearance/colors.d.ts +43 -0
  123. package/build/src/appearance/colors.js +99 -0
  124. package/build/src/appearance/logo.d.ts +32 -0
  125. package/build/src/appearance/logo.js +112 -0
  126. package/build/src/attachments/attachment_service.d.ts +46 -2
  127. package/build/src/attachments/attachment_service.js +96 -4
  128. package/build/src/auth/actor_store.d.ts +5 -1
  129. package/build/src/auth/actor_store.js +8 -4
  130. package/build/src/auth/conditions.d.ts +5 -0
  131. package/build/src/auth/conditions.js +26 -3
  132. package/build/src/auth/sql.js +17 -5
  133. package/build/src/auth/two_factor.d.ts +96 -0
  134. package/build/src/auth/two_factor.js +259 -0
  135. package/build/src/backups/archive.d.ts +52 -0
  136. package/build/src/backups/archive.js +362 -0
  137. package/build/src/backups/cloud_backups.d.ts +133 -0
  138. package/build/src/backups/cloud_backups.js +650 -0
  139. package/build/src/backups/doctor.d.ts +7 -0
  140. package/build/src/backups/doctor.js +55 -0
  141. package/build/src/backups/providers.d.ts +81 -0
  142. package/build/src/backups/providers.js +470 -0
  143. package/build/src/collaboration/assignments.d.ts +59 -2
  144. package/build/src/collaboration/assignments.js +196 -74
  145. package/build/src/collaboration/record_collaboration.d.ts +21 -4
  146. package/build/src/collaboration/record_collaboration.js +126 -51
  147. package/build/src/collaboration/shared.d.ts +24 -0
  148. package/build/src/collaboration/shared.js +34 -0
  149. package/build/src/commands/app_scaffold.d.ts +72 -0
  150. package/build/src/commands/app_scaffold.js +285 -0
  151. package/build/src/commands/capabilities.js +35 -9
  152. package/build/src/commands/doctor.d.ts +24 -2
  153. package/build/src/commands/doctor.js +81 -6
  154. package/build/src/commands/gap_report.d.ts +1 -1
  155. package/build/src/commands/gap_report.js +2 -2
  156. package/build/src/commands/generator.d.ts +37 -1
  157. package/build/src/commands/generator.js +61 -18
  158. package/build/src/commands/snapshot.d.ts +24 -13
  159. package/build/src/commands/snapshot.js +54 -14
  160. package/build/src/commands/source_markers.d.ts +10 -0
  161. package/build/src/commands/source_markers.js +29 -0
  162. package/build/src/core/activity.d.ts +2 -0
  163. package/build/src/core/activity.js +7 -1
  164. package/build/src/core/administrators.d.ts +38 -0
  165. package/build/src/core/administrators.js +145 -0
  166. package/build/src/core/avatar_image.d.ts +33 -0
  167. package/build/src/core/avatar_image.js +278 -0
  168. package/build/src/core/html_sanitizer.d.ts +20 -0
  169. package/build/src/core/html_sanitizer.js +261 -0
  170. package/build/src/core/like.d.ts +5 -0
  171. package/build/src/core/like.js +5 -0
  172. package/build/src/core/lookups.d.ts +80 -0
  173. package/build/src/core/lookups.js +319 -0
  174. package/build/src/core/mail_settings.d.ts +83 -0
  175. package/build/src/core/mail_settings.js +274 -0
  176. package/build/src/core/mail_test.d.ts +16 -0
  177. package/build/src/core/mail_test.js +81 -6
  178. package/build/src/core/message_templates.d.ts +15 -2
  179. package/build/src/core/message_templates.js +81 -11
  180. package/build/src/core/module_seed.js +2 -1
  181. package/build/src/core/notification_channels.d.ts +235 -0
  182. package/build/src/core/notification_channels.js +660 -0
  183. package/build/src/core/roles.js +26 -9
  184. package/build/src/core/saved_views.d.ts +8 -1
  185. package/build/src/core/saved_views.js +91 -26
  186. package/build/src/core/sequences.d.ts +32 -0
  187. package/build/src/core/sequences.js +97 -0
  188. package/build/src/core/settings.d.ts +5 -0
  189. package/build/src/core/settings.js +31 -3
  190. package/build/src/core/template_language.d.ts +61 -0
  191. package/build/src/core/template_language.js +141 -0
  192. package/build/src/core/ui_preferences.d.ts +10 -0
  193. package/build/src/core/ui_preferences.js +15 -1
  194. package/build/src/core/user_avatars.d.ts +79 -0
  195. package/build/src/core/user_avatars.js +186 -0
  196. package/build/src/core/user_invitations.d.ts +5 -1
  197. package/build/src/core/user_invitations.js +7 -1
  198. package/build/src/core/user_preferences.d.ts +36 -0
  199. package/build/src/core/user_preferences.js +125 -0
  200. package/build/src/core/users.d.ts +2 -0
  201. package/build/src/core/users.js +5 -3
  202. package/build/src/database/calendar_days.d.ts +19 -0
  203. package/build/src/database/calendar_days.js +36 -0
  204. package/build/src/database/schema.d.ts +201 -2
  205. package/build/src/database/schema.js +713 -59
  206. package/build/src/database/schema_diff.d.ts +70 -0
  207. package/build/src/database/schema_diff.js +190 -0
  208. package/build/src/events/record_mutation.d.ts +2 -1
  209. package/build/src/events/record_mutation.js +1 -0
  210. package/build/src/integrations/api_client.d.ts +37 -0
  211. package/build/src/integrations/api_client.js +567 -0
  212. package/build/src/integrations/import_adapters.d.ts +37 -0
  213. package/build/src/integrations/import_adapters.js +35 -0
  214. package/build/src/integrations/imports.d.ts +130 -16
  215. package/build/src/integrations/imports.js +434 -73
  216. package/build/src/integrations/openapi.d.ts +3 -1
  217. package/build/src/integrations/openapi.js +465 -31
  218. package/build/src/integrations/outbound.d.ts +94 -0
  219. package/build/src/integrations/outbound.js +276 -0
  220. package/build/src/integrations/print.d.ts +22 -1
  221. package/build/src/integrations/print.js +68 -22
  222. package/build/src/integrations/print_templates.d.ts +216 -0
  223. package/build/src/integrations/print_templates.js +1017 -0
  224. package/build/src/integrations/sync_jobs.d.ts +139 -0
  225. package/build/src/integrations/sync_jobs.js +416 -0
  226. package/build/src/integrations/webhooks.d.ts +12 -12
  227. package/build/src/integrations/webhooks.js +34 -43
  228. package/build/src/integrations/xlsx.d.ts +41 -0
  229. package/build/src/integrations/xlsx.js +519 -0
  230. package/build/src/languages/ar.d.ts +11 -0
  231. package/build/src/languages/ar.js +358 -0
  232. package/build/src/languages/ar_ui.d.ts +461 -0
  233. package/build/src/languages/ar_ui.js +464 -0
  234. package/build/src/languages/catalog.d.ts +66 -0
  235. package/build/src/languages/catalog.js +152 -0
  236. package/build/src/languages/en.d.ts +7 -0
  237. package/build/src/languages/en.js +352 -0
  238. package/build/src/languages/en_ui.d.ts +3 -0
  239. package/build/src/languages/en_ui.js +458 -0
  240. package/build/src/languages/validation.d.ts +26 -0
  241. package/build/src/languages/validation.js +60 -0
  242. package/build/src/lists/bulk_actions.d.ts +89 -0
  243. package/build/src/lists/bulk_actions.js +268 -0
  244. package/build/src/lists/dashboards.d.ts +138 -0
  245. package/build/src/lists/dashboards.js +290 -0
  246. package/build/src/mcp/tools.js +9 -104
  247. package/build/src/resource/define_resource.d.ts +18 -1
  248. package/build/src/resource/define_resource.js +212 -18
  249. package/build/src/resource/definition.d.ts +44 -0
  250. package/build/src/resource/definition.js +171 -0
  251. package/build/src/resource/registry.js +15 -4
  252. package/build/src/resource/types.d.ts +313 -16
  253. package/build/src/resource/values.d.ts +56 -1
  254. package/build/src/resource/values.js +237 -5
  255. package/build/src/services/settings.d.ts +2 -0
  256. package/build/src/services/settings.js +5 -1
  257. package/build/src/upgrade/legacy.js +2 -2
  258. package/build/src/workflows/calendar.d.ts +9 -0
  259. package/build/src/workflows/calendar.js +44 -0
  260. package/build/src/workflows/define_workflow.d.ts +48 -3
  261. package/build/src/workflows/define_workflow.js +57 -13
  262. package/build/src/workflows/delegations.d.ts +107 -0
  263. package/build/src/workflows/delegations.js +326 -0
  264. package/build/src/workflows/engine.d.ts +80 -4
  265. package/build/src/workflows/engine.js +466 -86
  266. package/build/src/workflows/sla.d.ts +15 -0
  267. package/build/src/workflows/sla.js +8 -0
  268. package/build/stubs/resource_contract.txt +12 -1
  269. package/package.json +9 -2
@@ -0,0 +1,650 @@
1
+ import { randomBytes, randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, mkdtemp, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, relative, resolve, sep } from 'node:path';
5
+ import { AdulaError } from '../admin/errors.js';
6
+ import { logActivity } from '../core/activity.js';
7
+ import { BACKUP_ARCHIVE_EXTENSION, BackupArchiveError, sealBackupArchive } from './archive.js';
8
+ import { BackupProviderError, pkcePair, } from './providers.js';
9
+ const KINDS = ['download', 'google', 'onedrive'];
10
+ const PROVIDERS = ['google', 'onedrive'];
11
+ const SCHEDULES = ['off', 'daily', 'weekly'];
12
+ const CLAIM_LOCK = 19300251;
13
+ const STORED_FILE = /^\d+-[0-9a-f-]{36}\.adulabackup(\.part)?$/;
14
+ /** The Arabic text stored and shown for a failure category; never a raw error message. */
15
+ export const BACKUP_FAILURE_MESSAGES = {
16
+ 'not-configured': 'مفتاح تشفير النسخ الاحتياطية غير مضبوط في بيئة التشغيل',
17
+ 'connection': 'الوجهة غير متصلة. أعد ربطها',
18
+ 'actor': 'من ربط الوجهة لم يعد مديرًا للنظام. أعد ربطها بحساب مدير',
19
+ 'revoked': 'سحب الحساب إذن الوصول. أعد ربط الوجهة',
20
+ 'auth': 'رفض مزود الخدمة بيانات الاعتماد',
21
+ 'quota': 'لا توجد مساحة كافية في حساب التخزين',
22
+ 'integrity': 'لم يطابق الملف المرفوع النسخة المحلية',
23
+ 'snapshot': 'تعذر إنشاء لقطة من قاعدة البيانات والملفات',
24
+ 'archive': 'تعذر تشفير النسخة الاحتياطية',
25
+ 'timeout': 'انتهت مهلة العملية',
26
+ 'interrupted': 'توقفت العملية قبل اكتمالها',
27
+ 'response': 'رد مزود الخدمة بصيغة غير متوقعة',
28
+ 'blocked-target': 'عنوان مزود الخدمة غير مسموح',
29
+ 'dns': 'تعذر الوصول إلى مزود الخدمة',
30
+ 'connect': 'تعذر الاتصال بمزود الخدمة',
31
+ 'tls': 'فشل الاتصال الآمن بمزود الخدمة',
32
+ };
33
+ function failureMessage(category) {
34
+ return (BACKUP_FAILURE_MESSAGES[category] ??
35
+ (category.startsWith('http-status:')
36
+ ? `رد مزود الخدمة برمز ${category.slice('http-status:'.length)}`
37
+ : 'تعذر إكمال النسخ الاحتياطي'));
38
+ }
39
+ function iso(value) {
40
+ return value ? new Date(value).toISOString() : null;
41
+ }
42
+ function runFrom(row) {
43
+ return {
44
+ id: Number(row.id),
45
+ kind: row.kind,
46
+ trigger: row.trigger,
47
+ status: row.status,
48
+ requestedBy: Number(row.requested_by),
49
+ fileName: row.status === 'succeeded' && row.kind === 'download' ? downloadName(row) : null,
50
+ size: row.size_bytes === null || row.size_bytes === undefined ? null : Number(row.size_bytes),
51
+ sha256: row.sha256 ?? null,
52
+ expiresAt: iso(row.expires_at),
53
+ errorCategory: row.error_category ?? null,
54
+ error: row.error_message ?? null,
55
+ createdAt: iso(row.created_at),
56
+ startedAt: iso(row.started_at),
57
+ finishedAt: iso(row.finished_at),
58
+ };
59
+ }
60
+ function connectionFrom(row) {
61
+ // Explicit columns only: the sealed refresh token never leaves the class.
62
+ return {
63
+ provider: row.provider,
64
+ status: row.status,
65
+ accountLabel: row.account_label ?? null,
66
+ schedule: row.schedule,
67
+ connectedBy: Number(row.connected_by),
68
+ connectedAt: iso(row.connected_at),
69
+ };
70
+ }
71
+ /** The file name an administrator receives: the run's start time, never the stored name. */
72
+ function downloadName(row) {
73
+ const at = new Date(row.started_at ?? row.created_at);
74
+ const stamp = at.toISOString().slice(0, 16).replace(/[-:]/g, '').replace('T', '-');
75
+ return `adulajs-backup-${stamp}${BACKUP_ARCHIVE_EXTENSION}`;
76
+ }
77
+ function notConfigured() {
78
+ return new AdulaError(409, 'E_BACKUP_NOT_CONFIGURED', 'مفتاح تشفير النسخ الاحتياطية غير مضبوط في بيئة التشغيل');
79
+ }
80
+ function within(parent, child) {
81
+ const path = relative(parent, child);
82
+ return (path === '' || (!path.startsWith('..') && !path.startsWith(sep) && !/^[A-Za-z]:/.test(path)));
83
+ }
84
+ /** The most recent scheduled time at or before `now`: 02:00 UTC daily, or on Fridays. */
85
+ export function lastDueTime(schedule, now) {
86
+ if (schedule === 'off')
87
+ return null;
88
+ const due = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 2));
89
+ if (due > now)
90
+ due.setUTCDate(due.getUTCDate() - 1);
91
+ if (schedule === 'weekly')
92
+ while (due.getUTCDay() !== 5)
93
+ due.setUTCDate(due.getUTCDate() - 1);
94
+ return due;
95
+ }
96
+ export class CloudBackups {
97
+ db;
98
+ options;
99
+ now;
100
+ downloadTtlMs;
101
+ timeoutMs;
102
+ constructor(db, options) {
103
+ this.db = db;
104
+ this.options = options;
105
+ this.now = options.now ?? (() => new Date());
106
+ this.downloadTtlMs = options.downloadTtlMs ?? 24 * 60 * 60 * 1000;
107
+ this.timeoutMs = options.timeoutMs ?? 6 * 60 * 60 * 1000;
108
+ }
109
+ get configured() {
110
+ return this.options.key !== null;
111
+ }
112
+ provider(provider) {
113
+ if (!PROVIDERS.includes(provider))
114
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الوجهة غير موجودة');
115
+ const client = this.options.providers[provider];
116
+ if (!client)
117
+ throw new AdulaError(409, 'E_BACKUP_PROVIDER_NOT_CONFIGURED', 'هذه الوجهة غير مهيأة في بيئة التشغيل');
118
+ return client;
119
+ }
120
+ /** Connection state, last results and ready downloads; never a token. */
121
+ async status() {
122
+ const connections = await this.db('backup_connections').select('provider', 'status', 'account_label', 'schedule', 'connected_by', 'connected_at');
123
+ const destinations = [];
124
+ for (const kind of KINDS) {
125
+ const last = await this.db('backup_runs')
126
+ .where({ kind })
127
+ .whereIn('status', ['succeeded', 'failed', 'expired'])
128
+ .orderBy('id', 'desc')
129
+ .first();
130
+ const connection = connections.find((row) => row.provider === kind);
131
+ destinations.push({
132
+ kind,
133
+ configured: kind === 'download' ? true : Boolean(this.options.providers[kind]),
134
+ connection: connection ? connectionFrom(connection) : null,
135
+ lastRun: last ? runFrom(last) : null,
136
+ });
137
+ }
138
+ const downloads = await this.db('backup_runs')
139
+ .where({ kind: 'download', status: 'succeeded' })
140
+ .where('expires_at', '>', this.now())
141
+ .orderBy('id', 'desc')
142
+ .limit(10);
143
+ const active = await this.db('backup_runs')
144
+ .whereIn('status', ['queued', 'running'])
145
+ .orderBy('id', 'asc');
146
+ return {
147
+ configured: this.configured,
148
+ destinations,
149
+ downloads: downloads.map(runFrom),
150
+ active: active.map(runFrom),
151
+ };
152
+ }
153
+ /** Starts an OAuth connection: the caller keeps state and verifier in the server session. */
154
+ beginConnect(provider, redirectUri) {
155
+ const client = this.provider(provider);
156
+ const state = randomBytes(32).toString('base64url');
157
+ const { verifier, challenge } = pkcePair();
158
+ return {
159
+ url: client.authorizeUrl({ state, codeChallenge: challenge, redirectUri }),
160
+ state,
161
+ verifier,
162
+ };
163
+ }
164
+ async completeConnect(provider, input, actorId) {
165
+ const client = this.provider(provider);
166
+ let result;
167
+ try {
168
+ result = await client.exchange(input);
169
+ }
170
+ catch (error) {
171
+ await this.connectFailed(provider, 'exchange', actorId);
172
+ throw new AdulaError(502, 'E_BACKUP_CONNECT', error instanceof BackupProviderError
173
+ ? `تعذر ربط الوجهة: ${failureMessage(error.category)}`
174
+ : 'تعذر ربط الوجهة');
175
+ }
176
+ const sealed = this.options.box.seal(result.refreshToken);
177
+ const [row] = await this.db('backup_connections')
178
+ .insert({
179
+ provider,
180
+ status: 'connected',
181
+ account_label: result.accountLabel,
182
+ refresh_token: sealed,
183
+ connected_by: actorId,
184
+ connected_at: this.now(),
185
+ updated_at: this.now(),
186
+ })
187
+ .onConflict('provider')
188
+ .merge([
189
+ 'status',
190
+ 'account_label',
191
+ 'refresh_token',
192
+ 'connected_by',
193
+ 'connected_at',
194
+ 'updated_at',
195
+ ])
196
+ .returning('id');
197
+ await logActivity(this.db, {
198
+ resource: 'core.backups',
199
+ recordId: Number(row.id ?? row),
200
+ actorId,
201
+ action: 'connected',
202
+ changes: { provider },
203
+ });
204
+ }
205
+ /** Records a refused connection attempt (bad state, provider error or failed exchange). */
206
+ async connectFailed(provider, reason, actorId) {
207
+ await logActivity(this.db, {
208
+ resource: 'core.backups',
209
+ recordId: 0,
210
+ actorId,
211
+ action: 'connect_failed',
212
+ changes: { provider: String(provider).slice(0, 20), reason },
213
+ });
214
+ }
215
+ async disconnect(provider, actorId) {
216
+ if (!PROVIDERS.includes(provider))
217
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الوجهة غير موجودة');
218
+ const row = await this.db('backup_connections').where({ provider }).first();
219
+ if (!row)
220
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الوجهة غير متصلة');
221
+ const client = this.options.providers[provider];
222
+ const token = this.options.box.open(row.refresh_token);
223
+ if (client?.revoke && token) {
224
+ try {
225
+ await client.revoke(token);
226
+ }
227
+ catch {
228
+ // The local token is deleted either way; the provider may already have revoked it.
229
+ }
230
+ }
231
+ await this.db.transaction(async (trx) => {
232
+ await trx('backup_runs')
233
+ .where({ connection_id: row.id, status: 'queued' })
234
+ .update({
235
+ status: 'failed',
236
+ error_category: 'connection',
237
+ error_message: failureMessage('connection'),
238
+ finished_at: this.now(),
239
+ });
240
+ await trx('backup_connections').where({ id: row.id }).delete();
241
+ await logActivity(trx, {
242
+ resource: 'core.backups',
243
+ recordId: Number(row.id),
244
+ actorId,
245
+ action: 'disconnected',
246
+ changes: { provider },
247
+ });
248
+ });
249
+ }
250
+ async setSchedule(provider, schedule, actorId) {
251
+ if (!SCHEDULES.includes(schedule))
252
+ throw new AdulaError(422, 'E_VALIDATION', 'اختر جدولًا صحيحًا');
253
+ const row = await this.db('backup_connections').where({ provider }).first();
254
+ if (!row)
255
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الوجهة غير متصلة');
256
+ await this.db('backup_connections')
257
+ .where({ id: row.id })
258
+ .update({ schedule, updated_at: this.now() });
259
+ await logActivity(this.db, {
260
+ resource: 'core.backups',
261
+ recordId: Number(row.id),
262
+ actorId,
263
+ action: 'scheduled',
264
+ changes: { provider, schedule },
265
+ });
266
+ }
267
+ /** Queues a backup run; one queued or running run per destination. */
268
+ async queue(kind, actorId, trigger = 'manual') {
269
+ if (!KINDS.includes(kind))
270
+ throw new AdulaError(422, 'E_VALIDATION', 'اختر وجهة صحيحة');
271
+ if (!this.configured)
272
+ throw notConfigured();
273
+ let connectionId = null;
274
+ if (kind !== 'download') {
275
+ this.provider(kind);
276
+ const connection = await this.db('backup_connections').where({ provider: kind }).first();
277
+ if (!connection || connection.status !== 'connected')
278
+ throw new AdulaError(409, 'E_BACKUP_NOT_CONNECTED', 'الوجهة غير متصلة. أعد ربطها');
279
+ connectionId = connection.id;
280
+ }
281
+ let id;
282
+ try {
283
+ const [row] = await this.db('backup_runs')
284
+ .insert({
285
+ kind,
286
+ connection_id: connectionId,
287
+ trigger,
288
+ status: 'queued',
289
+ requested_by: actorId,
290
+ // The scheduler compares created_at with this clock (queueDue), not the database's.
291
+ created_at: this.now(),
292
+ })
293
+ .returning('id');
294
+ id = Number(row.id ?? row);
295
+ }
296
+ catch (error) {
297
+ if (error.code === '23505')
298
+ throw new AdulaError(409, 'E_BACKUP_BUSY', 'توجد نسخة احتياطية قيد التنفيذ لهذه الوجهة');
299
+ throw error;
300
+ }
301
+ await logActivity(this.db, {
302
+ resource: 'core.backups',
303
+ recordId: id,
304
+ actorId,
305
+ action: 'queued',
306
+ changes: { kind, trigger },
307
+ });
308
+ return id;
309
+ }
310
+ /**
311
+ * Queues the scheduled runs that are due: one per connected destination and period. A
312
+ * destination whose connecting administrator lost that role gets one failed run per period.
313
+ */
314
+ async queueDue() {
315
+ if (!this.configured)
316
+ return 0;
317
+ const now = this.now();
318
+ let queued = 0;
319
+ const connections = await this.db('backup_connections')
320
+ .where({ status: 'connected' })
321
+ .whereNot({ schedule: 'off' });
322
+ for (const connection of connections) {
323
+ if (!this.options.providers[connection.provider])
324
+ continue;
325
+ const due = lastDueTime(connection.schedule, now);
326
+ if (!due)
327
+ continue;
328
+ const since = due > new Date(connection.connected_at) ? due : new Date(connection.connected_at);
329
+ const recent = await this.db('backup_runs')
330
+ .where({ kind: connection.provider })
331
+ .where('created_at', '>=', since)
332
+ .first();
333
+ if (recent)
334
+ continue;
335
+ if (!(await this.options.isAdministrator(Number(connection.connected_by)))) {
336
+ const [row] = await this.db('backup_runs')
337
+ .insert({
338
+ kind: connection.provider,
339
+ connection_id: connection.id,
340
+ trigger: 'schedule',
341
+ status: 'failed',
342
+ requested_by: connection.connected_by,
343
+ error_category: 'actor',
344
+ error_message: failureMessage('actor'),
345
+ created_at: now,
346
+ finished_at: now,
347
+ })
348
+ .returning('id');
349
+ await this.audit(Number(row.id ?? row), Number(connection.connected_by), 'failed', {
350
+ kind: connection.provider,
351
+ trigger: 'schedule',
352
+ errorCategory: 'actor',
353
+ });
354
+ continue;
355
+ }
356
+ try {
357
+ await this.queue(connection.provider, Number(connection.connected_by), 'schedule');
358
+ queued++;
359
+ }
360
+ catch (error) {
361
+ if (!(error instanceof AdulaError) || error.code !== 'E_BACKUP_BUSY')
362
+ throw error;
363
+ }
364
+ }
365
+ return queued;
366
+ }
367
+ async audit(id, actorId, action, changes) {
368
+ await logActivity(this.db, { resource: 'core.backups', recordId: id, actorId, action, changes });
369
+ }
370
+ /** Claims the oldest queued run; only one backup runs in the whole system at a time. */
371
+ async claim() {
372
+ return this.db.transaction(async (trx) => {
373
+ await trx.raw('SELECT pg_advisory_xact_lock(?)', [CLAIM_LOCK]);
374
+ const running = await trx('backup_runs').where({ status: 'running' }).first();
375
+ if (running)
376
+ return null;
377
+ const row = await trx('backup_runs')
378
+ .where({ status: 'queued' })
379
+ .orderBy('id', 'asc')
380
+ .forUpdate()
381
+ .skipLocked()
382
+ .first();
383
+ if (!row)
384
+ return null;
385
+ const [claimed] = await trx('backup_runs')
386
+ .where({ id: row.id })
387
+ .update({ status: 'running', started_at: this.now() })
388
+ .returning('*');
389
+ return claimed;
390
+ });
391
+ }
392
+ async privateDirectory() {
393
+ const root = resolve(this.options.directory);
394
+ if (within(resolve(tmpdir()), root) || /[\\/]public([\\/]|$)/.test(root))
395
+ throw new Error('The backup directory must not be inside public or temporary paths');
396
+ await mkdir(join(root, 'files'), { recursive: true, mode: 0o700 });
397
+ await chmod(root, 0o700).catch(() => { });
398
+ await chmod(join(root, 'files'), 0o700).catch(() => { });
399
+ return root;
400
+ }
401
+ /** Runs the next queued backup; returns its id, or null when nothing ran. */
402
+ async runNext(signal) {
403
+ const run = await this.claim();
404
+ if (!run)
405
+ return null;
406
+ const id = Number(run.id);
407
+ const actorId = Number(run.requested_by);
408
+ const changes = { kind: run.kind, trigger: run.trigger };
409
+ let local = null;
410
+ try {
411
+ if (!this.options.key)
412
+ throw new CategorizedFailure('not-configured');
413
+ let client;
414
+ let connection;
415
+ if (run.kind !== 'download') {
416
+ client = this.options.providers[run.kind];
417
+ connection = await this.db('backup_connections').where({ provider: run.kind }).first();
418
+ if (!client || !connection || connection.status !== 'connected')
419
+ throw new CategorizedFailure('connection');
420
+ }
421
+ if (!(await this.options.isAdministrator(actorId)))
422
+ throw new CategorizedFailure('actor');
423
+ const root = await this.privateDirectory();
424
+ const sealed = await this.sealSnapshot(root, id);
425
+ local = sealed.path;
426
+ if (run.kind === 'download') {
427
+ await this.db('backup_runs')
428
+ .where({ id })
429
+ .update({
430
+ status: 'succeeded',
431
+ file_name: sealed.stored,
432
+ size_bytes: sealed.size,
433
+ sha256: sealed.sha256,
434
+ expires_at: new Date(this.now().getTime() + this.downloadTtlMs),
435
+ finished_at: this.now(),
436
+ });
437
+ local = null;
438
+ await this.audit(id, actorId, 'succeeded', {
439
+ ...changes,
440
+ size: sealed.size,
441
+ sha256: sealed.sha256,
442
+ });
443
+ return id;
444
+ }
445
+ const token = this.options.box.open(connection.refresh_token);
446
+ if (!token)
447
+ throw new CategorizedFailure('revoked');
448
+ const access = await client.refresh(token);
449
+ if (access.refreshToken && access.refreshToken !== token)
450
+ await this.db('backup_connections')
451
+ .where({ id: connection.id })
452
+ .update({
453
+ refresh_token: this.options.box.seal(access.refreshToken),
454
+ updated_at: this.now(),
455
+ });
456
+ const uploaded = await client.upload({
457
+ file: sealed.path,
458
+ name: downloadName(run),
459
+ size: sealed.size,
460
+ sha256: sealed.sha256,
461
+ accessToken: access.accessToken,
462
+ signal: AbortSignal.any([AbortSignal.timeout(this.timeoutMs), ...(signal ? [signal] : [])]),
463
+ });
464
+ await this.db('backup_runs')
465
+ .where({ id })
466
+ .update({
467
+ status: 'succeeded',
468
+ size_bytes: sealed.size,
469
+ sha256: sealed.sha256,
470
+ remote_id: uploaded.remoteId.slice(0, 500),
471
+ finished_at: this.now(),
472
+ });
473
+ await this.audit(id, actorId, 'succeeded', {
474
+ ...changes,
475
+ size: sealed.size,
476
+ sha256: sealed.sha256,
477
+ remoteId: uploaded.remoteId.slice(0, 500),
478
+ });
479
+ return id;
480
+ }
481
+ catch (error) {
482
+ const category = failureCategory(error);
483
+ await this.db('backup_runs')
484
+ .where({ id })
485
+ .update({
486
+ status: 'failed',
487
+ error_category: category,
488
+ error_message: failureMessage(category),
489
+ finished_at: this.now(),
490
+ });
491
+ if (category === 'revoked' && run.kind !== 'download')
492
+ await this.db('backup_connections')
493
+ .where({ provider: run.kind })
494
+ .update({ status: 'revoked', updated_at: this.now() });
495
+ await this.audit(id, actorId, 'failed', { ...changes, errorCategory: category });
496
+ return id;
497
+ }
498
+ finally {
499
+ if (local)
500
+ await rm(local, { force: true });
501
+ }
502
+ }
503
+ /** Snapshot → sealed archive. The plaintext working directory is removed in every case. */
504
+ async sealSnapshot(root, id) {
505
+ const work = await mkdtemp(join(root, 'work-'));
506
+ const stored = `${id}-${randomUUID()}${BACKUP_ARCHIVE_EXTENSION}`;
507
+ const path = join(root, 'files', stored);
508
+ const part = `${path}.part`;
509
+ try {
510
+ await chmod(work, 0o700).catch(() => { });
511
+ const snapshot = join(work, 'snapshot');
512
+ try {
513
+ await this.options.createSnapshot(snapshot, { workDirectory: work });
514
+ await writeFile(join(snapshot, 'COMPLETE'), '', { mode: 0o600 });
515
+ }
516
+ catch (error) {
517
+ throw new CategorizedFailure('snapshot', error);
518
+ }
519
+ let sealed;
520
+ try {
521
+ sealed = await sealBackupArchive(snapshot, part, this.options.key);
522
+ }
523
+ catch (error) {
524
+ throw new CategorizedFailure('archive', error);
525
+ }
526
+ await rename(part, path);
527
+ return { path, stored, ...sealed };
528
+ }
529
+ catch (error) {
530
+ await rm(part, { force: true });
531
+ throw error;
532
+ }
533
+ finally {
534
+ await rm(work, { recursive: true, force: true });
535
+ }
536
+ }
537
+ /**
538
+ * A ready download for an administrator: the stored path and the name to send. The access
539
+ * is audited. Missing, expired, failed and non-download runs are not found.
540
+ */
541
+ async download(runId, actorId) {
542
+ if (!Number.isSafeInteger(runId) || runId < 1)
543
+ throw new AdulaError(404, 'E_NOT_FOUND', 'النسخة الاحتياطية غير موجودة');
544
+ const row = await this.db('backup_runs')
545
+ .where({ id: runId, kind: 'download', status: 'succeeded' })
546
+ .where('expires_at', '>', this.now())
547
+ .first();
548
+ if (!row || !row.file_name || !STORED_FILE.test(row.file_name))
549
+ throw new AdulaError(404, 'E_NOT_FOUND', 'النسخة الاحتياطية غير موجودة أو انتهت صلاحيتها');
550
+ const path = join(resolve(this.options.directory), 'files', row.file_name);
551
+ try {
552
+ await stat(path);
553
+ }
554
+ catch {
555
+ throw new AdulaError(404, 'E_NOT_FOUND', 'النسخة الاحتياطية غير موجودة أو انتهت صلاحيتها');
556
+ }
557
+ await this.audit(runId, actorId, 'downloaded', {
558
+ size: Number(row.size_bytes),
559
+ sha256: row.sha256,
560
+ });
561
+ return { path, fileName: downloadName(row), size: Number(row.size_bytes) };
562
+ }
563
+ /** Marks runs that a stopped worker left running as failed. */
564
+ async recoverStale() {
565
+ const cutoff = new Date(this.now().getTime() - this.timeoutMs);
566
+ const rows = await this.db('backup_runs')
567
+ .where({ status: 'running' })
568
+ .where('started_at', '<', cutoff)
569
+ .update({
570
+ status: 'failed',
571
+ error_category: 'interrupted',
572
+ error_message: failureMessage('interrupted'),
573
+ finished_at: this.now(),
574
+ })
575
+ .returning(['id', 'requested_by', 'kind', 'trigger']);
576
+ for (const row of rows)
577
+ await this.audit(Number(row.id), Number(row.requested_by), 'failed', {
578
+ kind: row.kind,
579
+ trigger: row.trigger,
580
+ errorCategory: 'interrupted',
581
+ });
582
+ return rows.length;
583
+ }
584
+ /**
585
+ * Deletes expired downloads and leftovers of interrupted runs. Only this class's own names
586
+ * under the backup directory are touched: `files/<id>-<uuid>.adulabackup[.part]` and `work-*`.
587
+ */
588
+ async pruneExpired() {
589
+ const now = this.now();
590
+ const root = resolve(this.options.directory);
591
+ const expired = await this.db('backup_runs')
592
+ .where({ kind: 'download', status: 'succeeded' })
593
+ .where('expires_at', '<=', now);
594
+ for (const row of expired) {
595
+ if (row.file_name && STORED_FILE.test(row.file_name))
596
+ await rm(join(root, 'files', row.file_name), { force: true });
597
+ await this.db('backup_runs').where({ id: row.id }).update({ status: 'expired' });
598
+ }
599
+ const kept = await this.db('backup_runs')
600
+ .where({ kind: 'download', status: 'succeeded' })
601
+ .whereNotNull('file_name')
602
+ .select('file_name');
603
+ const keep = new Set(kept.map((row) => row.file_name));
604
+ const stale = now.getTime() - this.timeoutMs;
605
+ const entries = async (path) => {
606
+ try {
607
+ return await readdir(path, { withFileTypes: true });
608
+ }
609
+ catch {
610
+ return [];
611
+ }
612
+ };
613
+ for (const entry of await entries(join(root, 'files'))) {
614
+ if (!entry.isFile() || !STORED_FILE.test(entry.name) || keep.has(entry.name))
615
+ continue;
616
+ const path = join(root, 'files', entry.name);
617
+ const info = await stat(path).catch(() => null);
618
+ if (info && info.mtimeMs < stale)
619
+ await rm(path, { force: true });
620
+ }
621
+ for (const entry of await entries(root)) {
622
+ if (!entry.isDirectory() || !entry.name.startsWith('work-'))
623
+ continue;
624
+ const path = join(root, entry.name);
625
+ const info = await stat(path).catch(() => null);
626
+ if (info && info.mtimeMs < stale)
627
+ await rm(path, { recursive: true, force: true });
628
+ }
629
+ return expired.length;
630
+ }
631
+ }
632
+ class CategorizedFailure extends Error {
633
+ category;
634
+ constructor(category, cause) {
635
+ super(category, { cause });
636
+ this.category = category;
637
+ }
638
+ }
639
+ function failureCategory(error) {
640
+ if (error instanceof CategorizedFailure)
641
+ return error.category;
642
+ if (error instanceof BackupProviderError)
643
+ return error.category;
644
+ if (error instanceof BackupArchiveError)
645
+ return 'archive';
646
+ const name = error?.name;
647
+ if (name === 'TimeoutError' || name === 'AbortError')
648
+ return 'timeout';
649
+ return 'snapshot';
650
+ }
@@ -0,0 +1,7 @@
1
+ import type { Finding } from '../commands/doctor.js';
2
+ /**
3
+ * Readiness of downloadable and cloud backups (ADR 051). Every part is optional: a missing key
4
+ * or OAuth client is reported as not configured, never as a failure. A malformed key or a
5
+ * half-configured client is a failure, because the deployment meant to set it.
6
+ */
7
+ export declare function diagnoseCloudBackups(env: Record<string, string | undefined>): Finding[];