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,259 @@
1
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
2
+ import { Secret, TOTP } from 'otpauth';
3
+ import { AdulaError } from '../admin/errors.js';
4
+ /** RFC 6238 parameters understood by every common authenticator application. */
5
+ export const TWO_FACTOR_PERIOD = 30;
6
+ export const TWO_FACTOR_DIGITS = 6;
7
+ export const TWO_FACTOR_WINDOW = 1;
8
+ /** 160-bit shared secret (RFC 4226 recommendation). */
9
+ const SECRET_BYTES = 20;
10
+ export const RECOVERY_CODE_COUNT = 10;
11
+ /** Crockford base32: no I, L, O or U, so codes read aloud and typed by hand stay unambiguous. */
12
+ const RECOVERY_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
13
+ /** 20 symbols of 5 bits each: 100 bits of entropy per code. */
14
+ const RECOVERY_LENGTH = 20;
15
+ const RECOVERY_GROUP = 5;
16
+ const SALT_BYTES = 16;
17
+ const MAX_INPUT = 64;
18
+ /** Error code when the stored secret cannot be opened with the current encryption keys. */
19
+ export const TWO_FACTOR_UNREADABLE = 'E_TWO_FACTOR_UNREADABLE';
20
+ const TOTP_FORMAT = new RegExp(`^\\d{${TWO_FACTOR_DIGITS}}$`);
21
+ /** Strips separators and maps look-alike characters the way Crockford base32 does. */
22
+ export function normalizeRecoveryCode(code) {
23
+ return code.toUpperCase().replace(/[\s-]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1');
24
+ }
25
+ function generateRecoveryCode() {
26
+ let raw = '';
27
+ for (let index = 0; index < RECOVERY_LENGTH; index++)
28
+ raw += RECOVERY_ALPHABET[randomInt(RECOVERY_ALPHABET.length)];
29
+ return raw.match(new RegExp(`.{${RECOVERY_GROUP}}`, 'g')).join('-');
30
+ }
31
+ const hashRecoveryCode = (salt, normalized) => createHash('sha256').update(salt).update(normalized, 'utf8').digest();
32
+ const iso = (value) => value instanceof Date ? value.toISOString() : value ? String(value) : null;
33
+ /**
34
+ * TOTP two-factor authentication (RFC 6238: SHA-1, 6 digits, 30 s, ±1 step) with
35
+ * single-use recovery codes.
36
+ *
37
+ * - The shared secret is sealed at rest through the host's encryption service.
38
+ * - A time step is accepted at most once, and never one older than the last accepted
39
+ * one, under a row lock: an observed code cannot be replayed.
40
+ * - Recovery codes carry 100 bits of entropy, are stored as SHA-256 over a unique
41
+ * 16-byte salt and the normalised code, compared in constant time, and consumed
42
+ * atomically (`used_at is null` guard), so each works once.
43
+ *
44
+ * Hosts rate-limit and lock verification, require the password before disabling,
45
+ * and audit every change.
46
+ */
47
+ export class TwoFactor {
48
+ db;
49
+ secrets;
50
+ issuer;
51
+ now;
52
+ constructor(db, secrets, issuer, options = {}) {
53
+ this.db = db;
54
+ this.secrets = secrets;
55
+ this.issuer = issuer;
56
+ this.now = options.now ?? Date.now;
57
+ }
58
+ async status(userId) {
59
+ const row = await this.db('user_two_factor').where('user_id', userId).first();
60
+ const enabled = Boolean(row?.enabled_at);
61
+ return {
62
+ enabled,
63
+ pending: Boolean(row && !row.enabled_at),
64
+ enabledAt: enabled ? iso(row.enabled_at) : null,
65
+ recoveryRemaining: enabled ? await this.recoveryRemaining(userId) : 0,
66
+ };
67
+ }
68
+ async isEnabled(userId) {
69
+ const row = await this.db('user_two_factor')
70
+ .where('user_id', userId)
71
+ .whereNotNull('enabled_at')
72
+ .first('user_id');
73
+ return Boolean(row);
74
+ }
75
+ async recoveryRemaining(userId, client = this.db) {
76
+ const [row] = await client('user_two_factor_recovery_codes')
77
+ .where('user_id', userId)
78
+ .whereNull('used_at')
79
+ .count('* as count');
80
+ return Number(row?.count ?? 0);
81
+ }
82
+ /** Starts (or restarts) a pending enrolment with a fresh secret; refused while enabled. */
83
+ async begin(userId, account) {
84
+ return this.db.transaction(async (trx) => {
85
+ const existing = await trx('user_two_factor').where('user_id', userId).forUpdate().first();
86
+ if (existing?.enabled_at)
87
+ throw new AdulaError(409, 'E_TWO_FACTOR_ENABLED', 'التحقق بخطوتين مفعّل بالفعل');
88
+ const secret = new Secret({ size: SECRET_BYTES }).base32;
89
+ await trx('user_two_factor')
90
+ .insert({ user_id: userId, secret: this.secrets.seal(secret) })
91
+ .onConflict('user_id')
92
+ .merge({
93
+ secret: this.secrets.seal(secret),
94
+ last_used_step: null,
95
+ enabled_at: null,
96
+ updated_at: trx.fn.now(),
97
+ });
98
+ await trx('user_two_factor_recovery_codes').where('user_id', userId).delete();
99
+ return {
100
+ otpauthUrl: this.totp(secret, account).toString(),
101
+ secret,
102
+ issuer: this.issuer,
103
+ account,
104
+ };
105
+ });
106
+ }
107
+ /** Confirms a pending enrolment with a current code; returns the recovery codes once. */
108
+ async confirm(userId, code) {
109
+ return this.db.transaction(async (trx) => {
110
+ const row = await trx('user_two_factor').where('user_id', userId).forUpdate().first();
111
+ if (!row || row.enabled_at)
112
+ throw new AdulaError(409, 'E_TWO_FACTOR_NOT_PENDING', 'ابدأ تفعيل التحقق بخطوتين أولاً');
113
+ const step = this.match(this.open(row.secret), code);
114
+ if (step === null)
115
+ throw new AdulaError(422, 'E_TWO_FACTOR_CODE', 'رمز التحقق غير صحيح');
116
+ await trx('user_two_factor').where('user_id', userId).update({
117
+ enabled_at: trx.fn.now(),
118
+ last_used_step: step,
119
+ updated_at: trx.fn.now(),
120
+ });
121
+ return this.replaceRecoveryCodes(trx, userId);
122
+ });
123
+ }
124
+ /**
125
+ * Verifies a TOTP code, or consumes a recovery code when allowed. Returns how the
126
+ * factor was proven, or false for anything else (disabled, malformed, wrong, replayed).
127
+ */
128
+ async verify(userId, code, options = {}) {
129
+ if (typeof code !== 'string' || code.length > MAX_INPUT)
130
+ return false;
131
+ return this.db.transaction(async (trx) => {
132
+ const row = await trx('user_two_factor').where('user_id', userId).forUpdate().first();
133
+ if (!row?.enabled_at)
134
+ return false;
135
+ const step = this.match(this.open(row.secret), code);
136
+ if (step !== null) {
137
+ const last = row.last_used_step === null ? null : Number(row.last_used_step);
138
+ if (last !== null && step <= last)
139
+ return false;
140
+ await trx('user_two_factor')
141
+ .where('user_id', userId)
142
+ .update({ last_used_step: step, updated_at: trx.fn.now() });
143
+ return 'totp';
144
+ }
145
+ if (options.allowRecovery === false)
146
+ return false;
147
+ return (await this.consumeRecoveryCode(trx, userId, code)) ? 'recovery' : false;
148
+ });
149
+ }
150
+ /** Replaces every recovery code; callers verify a current code first. */
151
+ async regenerateRecoveryCodes(userId) {
152
+ return this.db.transaction(async (trx) => {
153
+ const row = await trx('user_two_factor')
154
+ .where('user_id', userId)
155
+ .whereNotNull('enabled_at')
156
+ .forUpdate()
157
+ .first();
158
+ if (!row)
159
+ throw new AdulaError(409, 'E_TWO_FACTOR_NOT_ENABLED', 'التحقق بخطوتين غير مفعّل');
160
+ return this.replaceRecoveryCodes(trx, userId);
161
+ });
162
+ }
163
+ /**
164
+ * Removes the authenticator and every recovery code (self-service disable or an
165
+ * administrator's reset). Returns what was removed.
166
+ */
167
+ async disable(userId) {
168
+ return this.db.transaction(async (trx) => {
169
+ const removed = await trx('user_two_factor').where('user_id', userId).delete();
170
+ const codes = await trx('user_two_factor_recovery_codes').where('user_id', userId).delete();
171
+ return { removed: Number(removed) > 0, recoveryCodes: Number(codes) };
172
+ });
173
+ }
174
+ /** Alias of `disable` for administrative resets. */
175
+ reset(userId) {
176
+ return this.disable(userId);
177
+ }
178
+ async replaceRecoveryCodes(trx, userId) {
179
+ const codes = Array.from({ length: RECOVERY_CODE_COUNT }, generateRecoveryCode);
180
+ await trx('user_two_factor_recovery_codes').where('user_id', userId).delete();
181
+ await trx('user_two_factor_recovery_codes').insert(codes.map((code) => {
182
+ const salt = randomBytes(SALT_BYTES);
183
+ return {
184
+ user_id: userId,
185
+ salt: salt.toString('hex'),
186
+ code_hash: hashRecoveryCode(salt, normalizeRecoveryCode(code)).toString('hex'),
187
+ };
188
+ }));
189
+ return codes;
190
+ }
191
+ async consumeRecoveryCode(trx, userId, code) {
192
+ const normalized = normalizeRecoveryCode(code);
193
+ if (normalized.length !== RECOVERY_LENGTH)
194
+ return false;
195
+ const rows = await trx('user_two_factor_recovery_codes')
196
+ .where('user_id', userId)
197
+ .whereNull('used_at')
198
+ .select('id', 'salt', 'code_hash');
199
+ // Every unused code is compared, so timing does not reveal which one matched.
200
+ let matched = null;
201
+ for (const row of rows) {
202
+ const stored = Buffer.from(row.code_hash, 'hex');
203
+ const candidate = hashRecoveryCode(Buffer.from(row.salt, 'hex'), normalized);
204
+ if (stored.length === candidate.length && timingSafeEqual(stored, candidate))
205
+ matched = row.id;
206
+ }
207
+ if (matched === null)
208
+ return false;
209
+ const used = await trx('user_two_factor_recovery_codes')
210
+ .where({ id: matched })
211
+ .whereNull('used_at')
212
+ .update({ used_at: trx.fn.now() })
213
+ .returning('id');
214
+ return used.length === 1;
215
+ }
216
+ totp(secret, account) {
217
+ return new TOTP({
218
+ issuer: this.issuer,
219
+ label: account,
220
+ algorithm: 'SHA1',
221
+ digits: TWO_FACTOR_DIGITS,
222
+ period: TWO_FACTOR_PERIOD,
223
+ secret: Secret.fromBase32(secret),
224
+ });
225
+ }
226
+ /**
227
+ * A secret sealed under a key the host no longer holds (an APP_KEY rotated without
228
+ * keeping the old one) is a handled refusal, never a crash and never a match.
229
+ */
230
+ open(sealed) {
231
+ let secret = null;
232
+ try {
233
+ secret = this.secrets.open(sealed);
234
+ }
235
+ catch {
236
+ secret = null;
237
+ }
238
+ if (!secret)
239
+ throw new AdulaError(503, TWO_FACTOR_UNREADABLE, 'تعذّر قراءة إعداد التحقق بخطوتين لهذا الحساب. تواصل مع مدير النظام.');
240
+ return secret;
241
+ }
242
+ /** The absolute time step of a valid code within the window, or null. */
243
+ match(secret, code) {
244
+ if (typeof code !== 'string')
245
+ return null;
246
+ const token = code.replace(/\s/g, '');
247
+ if (!TOTP_FORMAT.test(token))
248
+ return null;
249
+ const timestamp = this.now();
250
+ const delta = this.totp(secret, 'account').validate({
251
+ token,
252
+ timestamp,
253
+ window: TWO_FACTOR_WINDOW,
254
+ });
255
+ if (delta === null)
256
+ return null;
257
+ return Math.floor(timestamp / 1000 / TWO_FACTOR_PERIOD) + delta;
258
+ }
259
+ }
@@ -0,0 +1,52 @@
1
+ import { Transform } from 'node:stream';
2
+ /**
3
+ * The encrypted backup archive (ADR 051). A `.adulabackup` file is a 48-byte header followed
4
+ * by AES-256-GCM frames over a small container of the snapshot files:
5
+ *
6
+ * header = "ADULABK\0" | version u8 | algorithm u8 | reserved u16 | chunkSize u32 BE |
7
+ * keyId 8 bytes | salt 16 bytes | reserved 8 bytes
8
+ * frame = final u8 | ciphertext length u32 BE | ciphertext | tag 16 bytes
9
+ * AAD = header | counter u64 BE | final u8
10
+ * nonce = 4 zero bytes | counter u64 BE
11
+ * key = HKDF-SHA256(masterKey, salt, "adulajs backup v1"), unique per file
12
+ *
13
+ * Exactly one frame is final and it is the last one, so truncation and appended data are
14
+ * detected. The plaintext container is a sequence of entries (name length u16 BE, UTF-8 name,
15
+ * size u64 BE, bytes) ended by a zero name length; names come from a fixed allow-list.
16
+ */
17
+ export declare const BACKUP_ARCHIVE_EXTENSION = ".adulabackup";
18
+ export declare const BACKUP_ARCHIVE_FILES: readonly ["database.dump", "uploads.tar.gz", "attachments.json", "SHA256SUMS", "COMPLETE"];
19
+ export type BackupArchiveErrorCode = 'E_BACKUP_KEY_INVALID' | 'E_BACKUP_FORMAT' | 'E_BACKUP_KEY' | 'E_BACKUP_TAMPERED' | 'E_BACKUP_TRUNCATED' | 'E_BACKUP_CONTENT' | 'E_BACKUP_TARGET';
20
+ /** A refusal while sealing or opening an archive; the message is Arabic and holds no secret. */
21
+ export declare class BackupArchiveError extends Error {
22
+ code: BackupArchiveErrorCode;
23
+ constructor(code: BackupArchiveErrorCode);
24
+ }
25
+ /** Decodes BACKUP_ENCRYPTION_KEY: base64 of exactly 32 bytes. */
26
+ export declare function parseBackupKey(value: string): Buffer;
27
+ /** Encrypts a byte stream into the archive format. */
28
+ export declare function createSealStream(master: Buffer, options?: {
29
+ chunkSize?: number;
30
+ }): Transform;
31
+ /**
32
+ * Decrypts the archive format. Each frame is authenticated before its bytes are released,
33
+ * but the stream as a whole is only trustworthy once it ends without an error: a missing
34
+ * final frame is reported at the end.
35
+ */
36
+ export declare function createOpenStream(master: Buffer): Transform;
37
+ /**
38
+ * Seals a snapshot directory into a new archive file (created exclusively, mode 0600).
39
+ * Returns the archive's size and SHA-256. A partial file is removed on failure.
40
+ */
41
+ export declare function sealBackupArchive(snapshotDirectory: string, outFile: string, master: Buffer, options?: {
42
+ chunkSize?: number;
43
+ }): Promise<{
44
+ size: number;
45
+ sha256: string;
46
+ }>;
47
+ /**
48
+ * Opens an archive into a new snapshot directory (mode 0700). The decrypted container is
49
+ * written next to the extracted files only until the archive's final frame verifies, then
50
+ * deleted. Nothing is left behind when the archive is wrong, tampered or truncated.
51
+ */
52
+ export declare function openBackupArchive(file: string, targetDirectory: string, master: Buffer): Promise<void>;
@@ -0,0 +1,362 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual, } from 'node:crypto';
2
+ import { createReadStream, createWriteStream } from 'node:fs';
3
+ import { lstat, mkdir, open, rm } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { Readable, Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ /**
8
+ * The encrypted backup archive (ADR 051). A `.adulabackup` file is a 48-byte header followed
9
+ * by AES-256-GCM frames over a small container of the snapshot files:
10
+ *
11
+ * header = "ADULABK\0" | version u8 | algorithm u8 | reserved u16 | chunkSize u32 BE |
12
+ * keyId 8 bytes | salt 16 bytes | reserved 8 bytes
13
+ * frame = final u8 | ciphertext length u32 BE | ciphertext | tag 16 bytes
14
+ * AAD = header | counter u64 BE | final u8
15
+ * nonce = 4 zero bytes | counter u64 BE
16
+ * key = HKDF-SHA256(masterKey, salt, "adulajs backup v1"), unique per file
17
+ *
18
+ * Exactly one frame is final and it is the last one, so truncation and appended data are
19
+ * detected. The plaintext container is a sequence of entries (name length u16 BE, UTF-8 name,
20
+ * size u64 BE, bytes) ended by a zero name length; names come from a fixed allow-list.
21
+ */
22
+ export const BACKUP_ARCHIVE_EXTENSION = '.adulabackup';
23
+ export const BACKUP_ARCHIVE_FILES = [
24
+ 'database.dump',
25
+ 'uploads.tar.gz',
26
+ 'attachments.json',
27
+ 'SHA256SUMS',
28
+ 'COMPLETE',
29
+ ];
30
+ const MAGIC = Buffer.from('ADULABK\0', 'latin1');
31
+ const VERSION = 1;
32
+ const ALGORITHM = 1;
33
+ const HEADER_SIZE = 48;
34
+ const TAG_SIZE = 16;
35
+ const FRAME_HEADER = 5;
36
+ const DEFAULT_CHUNK = 1024 * 1024;
37
+ const MAX_CHUNK = 16 * 1024 * 1024;
38
+ const INFO = Buffer.from('adulajs backup v1');
39
+ const MESSAGES = {
40
+ E_BACKUP_KEY_INVALID: 'مفتاح تشفير النسخ الاحتياطية غير صالح: يجب أن يكون 32 بايتًا بترميز base64',
41
+ E_BACKUP_FORMAT: 'الملف ليس نسخة احتياطية مشفرة من AdulaJS أو إصداره غير مدعوم',
42
+ E_BACKUP_KEY: 'مفتاح التشفير لا يطابق هذه النسخة الاحتياطية',
43
+ E_BACKUP_TAMPERED: 'تعذر التحقق من سلامة النسخة الاحتياطية: الملف معدل أو تالف',
44
+ E_BACKUP_TRUNCATED: 'النسخة الاحتياطية ناقصة: انقطع الملف قبل نهايته',
45
+ E_BACKUP_CONTENT: 'محتوى النسخة الاحتياطية غير متوقع',
46
+ E_BACKUP_TARGET: 'مجلد الاستعادة موجود مسبقًا أو لا يمكن إنشاؤه',
47
+ };
48
+ /** A refusal while sealing or opening an archive; the message is Arabic and holds no secret. */
49
+ export class BackupArchiveError extends Error {
50
+ code;
51
+ constructor(code) {
52
+ super(MESSAGES[code]);
53
+ this.code = code;
54
+ }
55
+ }
56
+ /** Decodes BACKUP_ENCRYPTION_KEY: base64 of exactly 32 bytes. */
57
+ export function parseBackupKey(value) {
58
+ const text = value.trim();
59
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || text.length % 4 !== 0)
60
+ throw new BackupArchiveError('E_BACKUP_KEY_INVALID');
61
+ const key = Buffer.from(text, 'base64');
62
+ if (key.length !== 32)
63
+ throw new BackupArchiveError('E_BACKUP_KEY_INVALID');
64
+ return key;
65
+ }
66
+ function keyId(master) {
67
+ return createHmac('sha256', master).update('adula-backup-key-id').digest().subarray(0, 8);
68
+ }
69
+ function fileKey(master, salt) {
70
+ return Buffer.from(hkdfSync('sha256', master, salt, INFO, 32));
71
+ }
72
+ function nonce(counter) {
73
+ const value = Buffer.alloc(12);
74
+ value.writeBigUInt64BE(counter, 4);
75
+ return value;
76
+ }
77
+ function aad(header, counter, final) {
78
+ const tail = Buffer.alloc(9);
79
+ tail.writeBigUInt64BE(counter, 0);
80
+ tail[8] = final ? 1 : 0;
81
+ return Buffer.concat([header, tail]);
82
+ }
83
+ /** Encrypts a byte stream into the archive format. */
84
+ export function createSealStream(master, options = {}) {
85
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK;
86
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > MAX_CHUNK)
87
+ throw new RangeError('Invalid chunk size');
88
+ const salt = randomBytes(16);
89
+ const header = Buffer.alloc(HEADER_SIZE);
90
+ MAGIC.copy(header, 0);
91
+ header[8] = VERSION;
92
+ header[9] = ALGORITHM;
93
+ header.writeUInt32BE(chunkSize, 12);
94
+ keyId(master).copy(header, 16);
95
+ salt.copy(header, 24);
96
+ const key = fileKey(master, salt);
97
+ let counter = 0n;
98
+ let pending = [];
99
+ let pendingSize = 0;
100
+ let headerSent = false;
101
+ const frame = (plain, final) => {
102
+ const cipher = createCipheriv('aes-256-gcm', key, nonce(counter));
103
+ cipher.setAAD(aad(header, counter, final));
104
+ const encrypted = Buffer.concat([cipher.update(plain), cipher.final()]);
105
+ const prefix = Buffer.alloc(FRAME_HEADER);
106
+ prefix[0] = final ? 1 : 0;
107
+ prefix.writeUInt32BE(encrypted.length, 1);
108
+ counter++;
109
+ return Buffer.concat([prefix, encrypted, cipher.getAuthTag()]);
110
+ };
111
+ const start = (stream) => {
112
+ if (!headerSent) {
113
+ stream.push(header);
114
+ headerSent = true;
115
+ }
116
+ };
117
+ return new Transform({
118
+ transform(chunk, _encoding, callback) {
119
+ start(this);
120
+ pending.push(chunk);
121
+ pendingSize += chunk.length;
122
+ // Keep at least one byte back, so the final frame always carries the tail.
123
+ while (pendingSize > chunkSize) {
124
+ const joined = Buffer.concat(pending);
125
+ this.push(frame(joined.subarray(0, chunkSize), false));
126
+ pending = [joined.subarray(chunkSize)];
127
+ pendingSize = joined.length - chunkSize;
128
+ }
129
+ callback();
130
+ },
131
+ flush(callback) {
132
+ start(this);
133
+ this.push(frame(Buffer.concat(pending), true));
134
+ pending = [];
135
+ callback();
136
+ },
137
+ });
138
+ }
139
+ /**
140
+ * Decrypts the archive format. Each frame is authenticated before its bytes are released,
141
+ * but the stream as a whole is only trustworthy once it ends without an error: a missing
142
+ * final frame is reported at the end.
143
+ */
144
+ export function createOpenStream(master) {
145
+ let buffer = Buffer.alloc(0);
146
+ let header = null;
147
+ let key = null;
148
+ let chunkSize = 0;
149
+ let counter = 0n;
150
+ let finished = false;
151
+ const fail = (code) => new BackupArchiveError(code);
152
+ return new Transform({
153
+ transform(chunk, _encoding, callback) {
154
+ if (finished && chunk.length)
155
+ return callback(fail('E_BACKUP_TAMPERED'));
156
+ buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
157
+ try {
158
+ if (!header) {
159
+ if (buffer.length < HEADER_SIZE)
160
+ return callback();
161
+ const candidate = buffer.subarray(0, HEADER_SIZE);
162
+ if (!candidate.subarray(0, 8).equals(MAGIC) || candidate[8] !== VERSION)
163
+ throw fail('E_BACKUP_FORMAT');
164
+ if (candidate[9] !== ALGORITHM)
165
+ throw fail('E_BACKUP_FORMAT');
166
+ chunkSize = candidate.readUInt32BE(12);
167
+ if (chunkSize < 1 || chunkSize > MAX_CHUNK)
168
+ throw fail('E_BACKUP_FORMAT');
169
+ if (!timingSafeEqual(candidate.subarray(16, 24), keyId(master)))
170
+ throw fail('E_BACKUP_KEY');
171
+ header = Buffer.from(candidate);
172
+ key = fileKey(master, header.subarray(24, 40));
173
+ buffer = buffer.subarray(HEADER_SIZE);
174
+ }
175
+ while (buffer.length >= FRAME_HEADER) {
176
+ if (finished)
177
+ throw fail('E_BACKUP_TAMPERED');
178
+ const flag = buffer[0];
179
+ const length = buffer.readUInt32BE(1);
180
+ if (flag > 1 || length > chunkSize)
181
+ throw fail('E_BACKUP_TAMPERED');
182
+ const total = FRAME_HEADER + length + TAG_SIZE;
183
+ if (buffer.length < total)
184
+ break;
185
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce(counter));
186
+ decipher.setAAD(aad(header, counter, flag === 1));
187
+ decipher.setAuthTag(buffer.subarray(FRAME_HEADER + length, total));
188
+ let plain;
189
+ try {
190
+ plain = Buffer.concat([
191
+ decipher.update(buffer.subarray(FRAME_HEADER, FRAME_HEADER + length)),
192
+ decipher.final(),
193
+ ]);
194
+ }
195
+ catch {
196
+ throw fail('E_BACKUP_TAMPERED');
197
+ }
198
+ counter++;
199
+ buffer = buffer.subarray(total);
200
+ if (flag === 1)
201
+ finished = true;
202
+ if (plain.length)
203
+ this.push(plain);
204
+ }
205
+ if (finished && buffer.length)
206
+ throw fail('E_BACKUP_TAMPERED');
207
+ callback();
208
+ }
209
+ catch (error) {
210
+ callback(error);
211
+ }
212
+ },
213
+ flush(callback) {
214
+ if (!header) {
215
+ const prefix = buffer.subarray(0, MAGIC.length);
216
+ const looksLikeArchive = buffer.length > 0 && MAGIC.subarray(0, prefix.length).equals(prefix);
217
+ return callback(fail(looksLikeArchive ? 'E_BACKUP_TRUNCATED' : 'E_BACKUP_FORMAT'));
218
+ }
219
+ if (!finished)
220
+ return callback(fail('E_BACKUP_TRUNCATED'));
221
+ callback();
222
+ },
223
+ });
224
+ }
225
+ async function* containerEntries(directory, names) {
226
+ for (const name of names) {
227
+ const path = join(directory, name);
228
+ const info = await lstat(path);
229
+ if (!info.isFile())
230
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
231
+ const nameBytes = Buffer.from(name, 'utf8');
232
+ const head = Buffer.alloc(2 + nameBytes.length + 8);
233
+ head.writeUInt16BE(nameBytes.length, 0);
234
+ nameBytes.copy(head, 2);
235
+ head.writeBigUInt64BE(BigInt(info.size), 2 + nameBytes.length);
236
+ yield head;
237
+ let written = 0;
238
+ for await (const chunk of createReadStream(path)) {
239
+ written += chunk.length;
240
+ yield chunk;
241
+ }
242
+ // The file changed while it was being sealed.
243
+ if (written !== info.size)
244
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
245
+ }
246
+ yield Buffer.alloc(2);
247
+ }
248
+ /** The snapshot files present in a directory, in archive order; database.dump is required. */
249
+ async function snapshotNames(directory) {
250
+ const present = [];
251
+ for (const name of BACKUP_ARCHIVE_FILES) {
252
+ try {
253
+ await lstat(join(directory, name));
254
+ present.push(name);
255
+ }
256
+ catch (error) {
257
+ if (error.code !== 'ENOENT')
258
+ throw error;
259
+ }
260
+ }
261
+ if (!present.includes('database.dump'))
262
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
263
+ return present;
264
+ }
265
+ /**
266
+ * Seals a snapshot directory into a new archive file (created exclusively, mode 0600).
267
+ * Returns the archive's size and SHA-256. A partial file is removed on failure.
268
+ */
269
+ export async function sealBackupArchive(snapshotDirectory, outFile, master, options = {}) {
270
+ const names = await snapshotNames(snapshotDirectory);
271
+ const hash = createHash('sha256');
272
+ let size = 0;
273
+ const tap = new Transform({
274
+ transform(chunk, _encoding, callback) {
275
+ hash.update(chunk);
276
+ size += chunk.length;
277
+ callback(null, chunk);
278
+ },
279
+ });
280
+ const output = createWriteStream(outFile, { flags: 'wx', mode: 0o600 });
281
+ try {
282
+ await pipeline(Readable.from(containerEntries(snapshotDirectory, names)), createSealStream(master, options), tap, output);
283
+ }
284
+ catch (error) {
285
+ if (error.code !== 'EEXIST')
286
+ await rm(outFile, { force: true });
287
+ throw error;
288
+ }
289
+ return { size, sha256: hash.digest('hex') };
290
+ }
291
+ /** Reads the decrypted container and writes each allow-listed entry into the target. */
292
+ async function extractContainer(container, target) {
293
+ const handle = await open(container, 'r');
294
+ try {
295
+ const { size: total } = await handle.stat();
296
+ let position = 0;
297
+ const read = async (length) => {
298
+ if (position + length > total)
299
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
300
+ const value = Buffer.alloc(length);
301
+ const { bytesRead } = await handle.read(value, 0, length, position);
302
+ if (bytesRead !== length)
303
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
304
+ position += length;
305
+ return value;
306
+ };
307
+ const seen = new Set();
308
+ for (;;) {
309
+ const lengthBytes = await read(2);
310
+ const nameLength = lengthBytes.readUInt16BE(0);
311
+ if (nameLength === 0)
312
+ break;
313
+ if (nameLength > 64)
314
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
315
+ const nameBytes = await read(nameLength);
316
+ const name = nameBytes.toString('utf8');
317
+ if (!BACKUP_ARCHIVE_FILES.includes(name) || seen.has(name))
318
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
319
+ seen.add(name);
320
+ const sizeBytes = await read(8);
321
+ const size = Number(sizeBytes.readBigUInt64BE(0));
322
+ if (!Number.isSafeInteger(size) || position + size > total)
323
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
324
+ const output = createWriteStream(join(target, name), { flags: 'wx', mode: 0o600 });
325
+ const input = size === 0
326
+ ? Readable.from([])
327
+ : createReadStream(container, { start: position, end: position + size - 1 });
328
+ await pipeline(input, output);
329
+ position += size;
330
+ }
331
+ if (position !== total || !seen.has('database.dump'))
332
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
333
+ }
334
+ finally {
335
+ await handle.close();
336
+ }
337
+ }
338
+ /**
339
+ * Opens an archive into a new snapshot directory (mode 0700). The decrypted container is
340
+ * written next to the extracted files only until the archive's final frame verifies, then
341
+ * deleted. Nothing is left behind when the archive is wrong, tampered or truncated.
342
+ */
343
+ export async function openBackupArchive(file, targetDirectory, master) {
344
+ try {
345
+ await mkdir(targetDirectory, { mode: 0o700 });
346
+ }
347
+ catch {
348
+ throw new BackupArchiveError('E_BACKUP_TARGET');
349
+ }
350
+ const container = join(targetDirectory, '.archive.bin');
351
+ try {
352
+ await pipeline(createReadStream(file), createOpenStream(master), createWriteStream(container, { flags: 'wx', mode: 0o600 }));
353
+ await extractContainer(container, targetDirectory);
354
+ }
355
+ catch (error) {
356
+ await rm(targetDirectory, { recursive: true, force: true });
357
+ throw error;
358
+ }
359
+ finally {
360
+ await rm(container, { force: true });
361
+ }
362
+ }