adula 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (214) hide show
  1. package/README.md +149 -18
  2. package/build/agent/AGENTS.template.md +4 -4
  3. package/build/agent/capabilities.md +22 -11
  4. package/build/agent/skills/adula-frontend-design/SKILL.md +1 -1
  5. package/build/agent/skills/idea-review/SKILL.md +2 -2
  6. package/build/commands/adula_outbox.d.ts +10 -0
  7. package/build/commands/adula_outbox.js +11 -0
  8. package/build/commands/adula_restore_reconcile.d.ts +10 -0
  9. package/build/commands/adula_restore_reconcile.js +34 -0
  10. package/build/commands/adula_runtime_health.d.ts +10 -0
  11. package/build/commands/adula_runtime_health.js +27 -0
  12. package/build/commands/adula_uploads_prune.d.ts +10 -0
  13. package/build/commands/adula_uploads_prune.js +16 -0
  14. package/build/commands/app.d.ts +10 -0
  15. package/build/commands/app.js +64 -0
  16. package/build/commands/backup_create.d.ts +11 -0
  17. package/build/commands/backup_create.js +99 -0
  18. package/build/commands/backup_restore_files.d.ts +11 -0
  19. package/build/commands/backup_restore_files.js +44 -0
  20. package/build/commands/backup_restore_test.d.ts +12 -0
  21. package/build/commands/backup_restore_test.js +185 -0
  22. package/build/commands/backup_services.d.ts +31 -0
  23. package/build/commands/backup_services.js +6 -0
  24. package/build/commands/backup_verify.d.ts +9 -0
  25. package/build/commands/backup_verify.js +59 -0
  26. package/build/commands/backup_verify_snapshot.d.ts +10 -0
  27. package/build/commands/backup_verify_snapshot.js +37 -0
  28. package/build/commands/client.d.ts +16 -0
  29. package/build/commands/client.js +71 -0
  30. package/build/commands/doctor.js +4 -1
  31. package/build/commands/install.d.ts +8 -0
  32. package/build/commands/install.js +63 -45
  33. package/build/commands/main.d.ts +3 -2
  34. package/build/commands/main.js +26 -0
  35. package/build/commands/module_add.js +4 -20
  36. package/build/commands/resource.d.ts +2 -0
  37. package/build/commands/resource.js +12 -3
  38. package/build/commands/resource_migration.d.ts +15 -0
  39. package/build/commands/resource_migration.js +72 -0
  40. package/build/commands/resource_snapshot.d.ts +2 -0
  41. package/build/commands/resource_snapshot.js +3 -0
  42. package/build/commands/sla_evaluate.d.ts +14 -0
  43. package/build/commands/sla_evaluate.js +16 -0
  44. package/build/commands/ui.js +5 -3
  45. package/build/commands/ui_css.d.ts +9 -0
  46. package/build/commands/ui_css.js +19 -0
  47. package/build/commands/upgrade.d.ts +1 -1
  48. package/build/commands/upgrade.js +1 -1
  49. package/build/configure.js +1 -1
  50. package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
  51. package/build/database/migrations/1770000000020_two_factor.js +10 -0
  52. package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
  53. package/build/database/migrations/1770000000041_import_modes.js +10 -0
  54. package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
  55. package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
  56. package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
  57. package/build/database/migrations/1770000000043_notification_channels.js +10 -0
  58. package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
  59. package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
  60. package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
  61. package/build/database/migrations/1770000000045_import_leases.js +10 -0
  62. package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
  63. package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
  64. package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
  65. package/build/database/migrations/1770000000049_print_templates.js +10 -0
  66. package/build/index.d.ts +56 -10
  67. package/build/index.js +34 -6
  68. package/build/providers/adula_provider.d.ts +2 -0
  69. package/build/providers/adula_provider.js +7 -0
  70. package/build/src/admin/contracts.js +1 -1
  71. package/build/src/admin/controller.d.ts +14 -1
  72. package/build/src/admin/controller.js +77 -13
  73. package/build/src/admin/errors.d.ts +32 -0
  74. package/build/src/admin/errors.js +63 -1
  75. package/build/src/admin/presentation.d.ts +21 -2
  76. package/build/src/admin/resource/editor.d.ts +59 -0
  77. package/build/src/admin/resource/editor.js +323 -0
  78. package/build/src/admin/resource/export.d.ts +37 -0
  79. package/build/src/admin/resource/export.js +181 -0
  80. package/build/src/admin/resource/lifecycle.d.ts +21 -0
  81. package/build/src/admin/resource/lifecycle.js +91 -0
  82. package/build/src/admin/resource/query.d.ts +100 -0
  83. package/build/src/admin/resource/query.js +508 -0
  84. package/build/src/admin/resource/read.d.ts +106 -0
  85. package/build/src/admin/resource/read.js +327 -0
  86. package/build/src/admin/resource/shared.d.ts +77 -0
  87. package/build/src/admin/resource/shared.js +222 -0
  88. package/build/src/admin/resource/trash.d.ts +10 -0
  89. package/build/src/admin/resource/trash.js +56 -0
  90. package/build/src/admin/resource/write.d.ts +57 -0
  91. package/build/src/admin/resource/write.js +574 -0
  92. package/build/src/admin/resource_service.d.ts +66 -193
  93. package/build/src/admin/resource_service.js +69 -1345
  94. package/build/src/attachments/attachment_service.d.ts +46 -2
  95. package/build/src/attachments/attachment_service.js +96 -4
  96. package/build/src/auth/conditions.d.ts +5 -0
  97. package/build/src/auth/conditions.js +26 -3
  98. package/build/src/auth/sql.js +17 -5
  99. package/build/src/auth/two_factor.d.ts +96 -0
  100. package/build/src/auth/two_factor.js +259 -0
  101. package/build/src/collaboration/assignments.d.ts +36 -1
  102. package/build/src/collaboration/assignments.js +132 -66
  103. package/build/src/collaboration/record_collaboration.d.ts +2 -3
  104. package/build/src/collaboration/record_collaboration.js +19 -16
  105. package/build/src/collaboration/shared.d.ts +16 -0
  106. package/build/src/collaboration/shared.js +21 -0
  107. package/build/src/commands/app_scaffold.d.ts +72 -0
  108. package/build/src/commands/app_scaffold.js +285 -0
  109. package/build/src/commands/capabilities.js +34 -8
  110. package/build/src/commands/doctor.d.ts +14 -2
  111. package/build/src/commands/doctor.js +50 -5
  112. package/build/src/commands/gap_report.d.ts +1 -1
  113. package/build/src/commands/gap_report.js +2 -2
  114. package/build/src/commands/generator.d.ts +37 -1
  115. package/build/src/commands/generator.js +61 -18
  116. package/build/src/commands/snapshot.d.ts +10 -13
  117. package/build/src/commands/snapshot.js +31 -14
  118. package/build/src/commands/source_markers.d.ts +10 -0
  119. package/build/src/commands/source_markers.js +29 -0
  120. package/build/src/core/activity.d.ts +2 -0
  121. package/build/src/core/activity.js +7 -1
  122. package/build/src/core/administrators.d.ts +38 -0
  123. package/build/src/core/administrators.js +129 -0
  124. package/build/src/core/html_sanitizer.d.ts +20 -0
  125. package/build/src/core/html_sanitizer.js +261 -0
  126. package/build/src/core/like.d.ts +5 -0
  127. package/build/src/core/like.js +5 -0
  128. package/build/src/core/lookups.d.ts +80 -0
  129. package/build/src/core/lookups.js +319 -0
  130. package/build/src/core/message_templates.d.ts +7 -2
  131. package/build/src/core/message_templates.js +72 -11
  132. package/build/src/core/module_seed.js +2 -1
  133. package/build/src/core/notification_channels.d.ts +235 -0
  134. package/build/src/core/notification_channels.js +660 -0
  135. package/build/src/core/roles.js +2 -2
  136. package/build/src/core/saved_views.d.ts +8 -1
  137. package/build/src/core/saved_views.js +36 -2
  138. package/build/src/core/sequences.d.ts +32 -0
  139. package/build/src/core/sequences.js +97 -0
  140. package/build/src/core/settings.d.ts +5 -0
  141. package/build/src/core/settings.js +19 -2
  142. package/build/src/core/template_language.d.ts +61 -0
  143. package/build/src/core/template_language.js +141 -0
  144. package/build/src/core/ui_preferences.d.ts +4 -0
  145. package/build/src/core/ui_preferences.js +4 -1
  146. package/build/src/core/user_invitations.d.ts +5 -1
  147. package/build/src/core/user_invitations.js +7 -1
  148. package/build/src/core/users.js +1 -1
  149. package/build/src/database/calendar_days.d.ts +19 -0
  150. package/build/src/database/calendar_days.js +36 -0
  151. package/build/src/database/schema.d.ts +155 -2
  152. package/build/src/database/schema.js +531 -59
  153. package/build/src/database/schema_diff.d.ts +56 -0
  154. package/build/src/database/schema_diff.js +157 -0
  155. package/build/src/events/record_mutation.d.ts +2 -1
  156. package/build/src/events/record_mutation.js +1 -0
  157. package/build/src/integrations/api_client.d.ts +37 -0
  158. package/build/src/integrations/api_client.js +552 -0
  159. package/build/src/integrations/import_adapters.d.ts +37 -0
  160. package/build/src/integrations/import_adapters.js +35 -0
  161. package/build/src/integrations/imports.d.ts +118 -16
  162. package/build/src/integrations/imports.js +406 -73
  163. package/build/src/integrations/openapi.d.ts +3 -1
  164. package/build/src/integrations/openapi.js +454 -31
  165. package/build/src/integrations/outbound.d.ts +51 -0
  166. package/build/src/integrations/outbound.js +195 -0
  167. package/build/src/integrations/print.d.ts +21 -1
  168. package/build/src/integrations/print.js +63 -21
  169. package/build/src/integrations/print_templates.d.ts +216 -0
  170. package/build/src/integrations/print_templates.js +1015 -0
  171. package/build/src/integrations/sync_jobs.d.ts +139 -0
  172. package/build/src/integrations/sync_jobs.js +416 -0
  173. package/build/src/integrations/webhooks.d.ts +12 -12
  174. package/build/src/integrations/webhooks.js +34 -43
  175. package/build/src/languages/ar.d.ts +11 -0
  176. package/build/src/languages/ar.js +336 -0
  177. package/build/src/languages/ar_ui.d.ts +332 -0
  178. package/build/src/languages/ar_ui.js +333 -0
  179. package/build/src/languages/catalog.d.ts +66 -0
  180. package/build/src/languages/catalog.js +152 -0
  181. package/build/src/languages/en.d.ts +7 -0
  182. package/build/src/languages/en.js +330 -0
  183. package/build/src/languages/en_ui.d.ts +3 -0
  184. package/build/src/languages/en_ui.js +328 -0
  185. package/build/src/languages/validation.d.ts +26 -0
  186. package/build/src/languages/validation.js +60 -0
  187. package/build/src/lists/bulk_actions.d.ts +89 -0
  188. package/build/src/lists/bulk_actions.js +268 -0
  189. package/build/src/lists/dashboards.d.ts +96 -0
  190. package/build/src/lists/dashboards.js +241 -0
  191. package/build/src/mcp/tools.js +1 -1
  192. package/build/src/resource/define_resource.d.ts +18 -1
  193. package/build/src/resource/define_resource.js +205 -18
  194. package/build/src/resource/definition.d.ts +44 -0
  195. package/build/src/resource/definition.js +171 -0
  196. package/build/src/resource/registry.js +15 -4
  197. package/build/src/resource/types.d.ts +304 -16
  198. package/build/src/resource/values.d.ts +56 -1
  199. package/build/src/resource/values.js +237 -5
  200. package/build/src/services/settings.d.ts +2 -0
  201. package/build/src/services/settings.js +5 -1
  202. package/build/src/upgrade/legacy.js +2 -2
  203. package/build/src/workflows/calendar.d.ts +9 -0
  204. package/build/src/workflows/calendar.js +44 -0
  205. package/build/src/workflows/define_workflow.d.ts +48 -3
  206. package/build/src/workflows/define_workflow.js +57 -13
  207. package/build/src/workflows/delegations.d.ts +93 -0
  208. package/build/src/workflows/delegations.js +287 -0
  209. package/build/src/workflows/engine.d.ts +69 -4
  210. package/build/src/workflows/engine.js +441 -83
  211. package/build/src/workflows/sla.d.ts +15 -0
  212. package/build/src/workflows/sla.js +8 -0
  213. package/build/stubs/resource_contract.txt +12 -1
  214. package/package.json +5 -2
@@ -0,0 +1,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
+ }
@@ -1,7 +1,8 @@
1
1
  import type { Knex } from 'knex';
2
2
  import type { Actor } from '../auth/ability.js';
3
3
  import type { ResourceService } from '../admin/resource_service.js';
4
- import type { ActorLoader } from './record_collaboration.js';
4
+ import { type ActorLoader } from './shared.js';
5
+ import { type SlaState } from '../workflows/sla.js';
5
6
  export type AssignmentStatus = 'open' | 'done' | 'cancelled';
6
7
  export type Assignment = {
7
8
  id: number;
@@ -34,6 +35,18 @@ export type Assignment = {
34
35
  canCancel: boolean;
35
36
  /** An open approval step waiting for this user's decision (WorkflowEngine.decide). 1.2; optional for compatibility. */
36
37
  canDecide?: boolean;
38
+ /**
39
+ * The approver the viewer acts for through a delegation (ADR 044): the delegator of an
40
+ * approval routed to the viewer, or a delegator's own pending approval. Null otherwise.
41
+ */
42
+ onBehalfOf?: {
43
+ id: number;
44
+ name: string | null;
45
+ } | null;
46
+ /** The SLA deadline of an approval with one (ISO time); dueOn stays its calendar date. */
47
+ dueAt?: string | null;
48
+ /** The SLA state of an open approval with a deadline. */
49
+ sla?: SlaState | null;
37
50
  };
38
51
  export type AssignmentPage = {
39
52
  data: Assignment[];
@@ -51,6 +64,10 @@ export type AssignmentPage = {
51
64
  export type CloseNotePolicy = 'optional' | 'required';
52
65
  export type AssignmentOptions = {
53
66
  closeNote?: CloseNotePolicy;
67
+ /** Test hook: the clock for delegation dates and SLA states. */
68
+ now?: () => Date;
69
+ /** The system time zone whose calendar days delegation ranges use (default UTC). */
70
+ timeZone?: string;
54
71
  };
55
72
  /**
56
73
  * Assignments put a record on someone's "my tasks" list. Assigning needs update
@@ -90,6 +107,13 @@ export declare class Assignments {
90
107
  * assignee cannot mark it done; module code closes it with close() (#51).
91
108
  */
92
109
  managed?: boolean;
110
+ /** Workflow approvals routed to a delegate keep the original approver (ADR 044). */
111
+ onBehalfOf?: number | null;
112
+ delegationId?: number | null;
113
+ /** SLA deadline and its due-soon reminder time; escalatedAt marks a reassignment. */
114
+ dueAt?: Date | null;
115
+ dueSoonAt?: Date | null;
116
+ escalatedAt?: Date | null;
93
117
  }): Promise<any>;
94
118
  /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
95
119
  mine(actor: Actor, options?: {
@@ -119,10 +143,21 @@ export declare class Assignments {
119
143
  reason?: string;
120
144
  trx?: Knex.Transaction;
121
145
  }): Promise<number>;
146
+ /**
147
+ * Closes one locked open assignment row for complete() (by hand) and close() (by
148
+ * module code, `system`): records the outcome, writes the record's activity entry
149
+ * when the task is managed or closed by the system, and notifies the other party —
150
+ * the assigner when done, the assignee when cancelled — unless that is the closer.
151
+ */
152
+ private finish;
122
153
  private query;
123
154
  private present;
124
155
  /** Adds record titles in one read per resource, under the viewer's field access. */
125
156
  private titled;
157
+ /** The delegations in force today that make the user act for someone else. */
158
+ private scope;
159
+ private now;
160
+ private today;
126
161
  private closeNote;
127
162
  private label;
128
163
  private canView;
@@ -1,5 +1,10 @@
1
1
  import { AdulaError } from '../admin/errors.js';
2
2
  import { notifyWithTemplate } from '../core/message_templates.js';
3
+ import { canView, resourceLabel } from './shared.js';
4
+ import { actionableBy, delegationActive } from '../workflows/delegations.js';
5
+ import { assertTimeZone, calendarDate } from '../workflows/calendar.js';
6
+ import { slaState } from '../workflows/sla.js';
7
+ const NO_DELEGATION = { delegations: new Set(), delegators: new Set() };
3
8
  const TITLE_LIMIT = 200;
4
9
  const NOTE_LIMIT = 2000;
5
10
  const REASON_LIMIT = 500;
@@ -26,6 +31,8 @@ export class Assignments {
26
31
  this.resources = resources;
27
32
  this.actors = actors;
28
33
  this.options = options;
34
+ if (options.timeZone)
35
+ assertTimeZone(options.timeZone);
29
36
  }
30
37
  async forRecord(name, id, actor) {
31
38
  await this.resources.access(name, id, actor);
@@ -33,7 +40,8 @@ export class Assignments {
33
40
  .where({ 'a.resource': name, 'a.record_id': id })
34
41
  .orderByRaw("(a.status = 'open') DESC, a.id DESC")
35
42
  .limit(100);
36
- return this.titled(rows.map((row) => this.present(row, actor)), actor);
43
+ const scope = await this.scope(actor.id);
44
+ return this.titled(rows.map((row) => this.present(row, actor, scope)), actor);
37
45
  }
38
46
  async assign(name, id, actor, input) {
39
47
  await this.resources.access(name, id, actor, 'update');
@@ -90,6 +98,12 @@ export class Assignments {
90
98
  workflow_run_id: input.workflowRunId ?? null,
91
99
  workflow_step: input.workflowStep ?? null,
92
100
  managed: input.managed ?? false,
101
+ on_behalf_of: input.onBehalfOf ?? null,
102
+ delegation_id: input.delegationId ?? null,
103
+ due_at: input.dueAt ?? null,
104
+ due_soon_at: input.dueSoonAt ?? null,
105
+ escalated_at: input.escalatedAt ?? null,
106
+ reminded_at: input.escalatedAt ?? null,
93
107
  })
94
108
  .returning('id');
95
109
  await notifyWithTemplate(trx, input.assigneeId, input.kind === 'approval' ? 'assignment.approval' : 'assignment.created', {
@@ -106,9 +120,16 @@ export class Assignments {
106
120
  async mine(actor, options = {}) {
107
121
  const status = options.status === 'done' || options.status === 'all' ? options.status : 'open';
108
122
  const limit = Math.max(1, Math.min(100, Math.floor(Number(options.limit) || 50)));
109
- const query = this.query().where('a.assignee_id', actor.id).orderBy('a.id', 'desc');
123
+ const query = this.query().orderBy('a.id', 'desc');
124
+ // Open items include approvals held through a delegation in force today (ADR 044);
125
+ // closed ones are the user's own, those decided for them and those they decided.
110
126
  if (status === 'open')
111
- query.where('a.status', 'open');
127
+ query.where('a.status', 'open').modify(actionableBy(this.db, actor.id, this.today()));
128
+ else
129
+ query.where((own) => own
130
+ .where('a.assignee_id', actor.id)
131
+ .orWhere('a.on_behalf_of', actor.id)
132
+ .orWhere('a.completed_by', actor.id));
112
133
  if (status === 'done')
113
134
  query.whereNot('a.status', 'open');
114
135
  if (options.kind === 'approval')
@@ -122,6 +143,7 @@ export class Assignments {
122
143
  throw new AdulaError(422, 'E_CURSOR', 'مؤشر الصفحة غير صالح');
123
144
  }
124
145
  const data = [];
146
+ const scope = await this.scope(actor.id);
125
147
  let more = true;
126
148
  // Access is re-checked per record; scan bounded batches to fill the page.
127
149
  for (let round = 0; round < 10 && more && data.length < limit; round++) {
@@ -140,17 +162,31 @@ export class Assignments {
140
162
  }
141
163
  last = Number(row.id);
142
164
  if (await this.resources.permits(row.resource, Number(row.record_id), actor))
143
- data.push(this.present(row, actor));
165
+ data.push(this.present(row, actor, scope));
144
166
  }
145
167
  }
168
+ // The user's own open items are counted in SQL, as before. Items held only through
169
+ // a delegation are counted after the same record check as the list (ADR 044), so the
170
+ // badge never reveals approvals on records the delegate cannot open.
146
171
  const [{ count, approvals }] = await this.db('assignments')
147
172
  .where({ assignee_id: actor.id, status: 'open' })
173
+ .whereNull('delegation_id')
148
174
  .select(this.db.raw('count(*) as count'), this.db.raw('count(workflow_run_id) as approvals'));
175
+ let held = 0;
176
+ const borrowed = await this.db('assignments as a')
177
+ .where('a.status', 'open')
178
+ .modify(actionableBy(this.db, actor.id, this.today()))
179
+ .where((q) => q.whereNot('a.assignee_id', actor.id).orWhereNotNull('a.delegation_id'))
180
+ .limit(200)
181
+ .select('a.resource', 'a.record_id');
182
+ for (const row of borrowed)
183
+ if (await this.resources.permits(row.resource, Number(row.record_id), actor))
184
+ held++;
149
185
  return {
150
186
  data: await this.titled(data, actor),
151
187
  nextCursor: more && last !== null ? String(last) : null,
152
- open: Number(count),
153
- approvals: Number(approvals),
188
+ open: Number(count) + held,
189
+ approvals: Number(approvals) + held,
154
190
  };
155
191
  }
156
192
  /**
@@ -183,31 +219,8 @@ export class Assignments {
183
219
  throw new AdulaError(409, 'E_ASSIGNMENT_CLOSED', 'المهمة مغلقة بالفعل');
184
220
  if (!note && this.closeNote(row) === 'required')
185
221
  throw new AdulaError(422, 'E_ASSIGNMENT_NOTE', 'اكتب ملاحظة الإغلاق قبل إغلاق المهمة');
186
- await trx('assignments')
187
- .where('id', id)
188
- .update({
189
- status: outcome,
190
- completed_at: trx.fn.now(),
191
- completed_by: actor.id,
192
- close_reason: note || null,
193
- });
194
222
  // A managed task closed by hand leaves the note in the record's history.
195
- if (row.managed)
196
- await trx('activities').insert({
197
- resource: row.resource,
198
- record_id: row.record_id,
199
- actor_id: actor.id,
200
- action: 'assignment_closed',
201
- changes: JSON.stringify({
202
- fields: [],
203
- assignmentId: id,
204
- outcome,
205
- reason: note,
206
- }),
207
- });
208
- const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
209
- if (notify && notify !== actor.id)
210
- await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
223
+ await this.finish(trx, row, actor.id, outcome, note, false);
211
224
  });
212
225
  }
213
226
  /**
@@ -231,43 +244,79 @@ export class Assignments {
231
244
  .whereNull('workflow_run_id')
232
245
  .forUpdate()
233
246
  .orderBy('id');
234
- for (const row of rows) {
235
- await trx('assignments').where('id', row.id).update({
236
- status: outcome,
237
- completed_at: trx.fn.now(),
238
- completed_by: options.actorId,
239
- close_reason: reason,
240
- });
241
- await trx('activities').insert({
242
- resource,
243
- record_id: recordId,
244
- actor_id: options.actorId,
245
- action: 'assignment_closed',
246
- changes: JSON.stringify({
247
+ for (const row of rows)
248
+ await this.finish(trx, row, options.actorId, outcome, reason, true);
249
+ return rows.length;
250
+ };
251
+ return options.trx ? run(options.trx) : this.db.transaction(run);
252
+ }
253
+ /**
254
+ * Closes one locked open assignment row for complete() (by hand) and close() (by
255
+ * module code, `system`): records the outcome, writes the record's activity entry
256
+ * when the task is managed or closed by the system, and notifies the other party —
257
+ * the assigner when done, the assignee when cancelled — unless that is the closer.
258
+ */
259
+ async finish(trx, row, actorId, outcome, reason, system) {
260
+ await trx('assignments')
261
+ .where('id', row.id)
262
+ .update({
263
+ status: outcome,
264
+ completed_at: trx.fn.now(),
265
+ completed_by: actorId,
266
+ close_reason: reason || null,
267
+ });
268
+ if (system || row.managed)
269
+ await trx('activities').insert({
270
+ resource: row.resource,
271
+ record_id: row.record_id,
272
+ actor_id: actorId,
273
+ action: 'assignment_closed',
274
+ changes: JSON.stringify(system
275
+ ? {
247
276
  fields: [],
248
277
  system: true,
249
278
  assignmentId: Number(row.id),
250
279
  outcome,
251
280
  ...(reason ? { reason } : {}),
252
- }),
253
- });
254
- const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
255
- if (notify && notify !== options.actorId)
256
- await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
257
- }
258
- return rows.length;
259
- };
260
- return options.trx ? run(options.trx) : this.db.transaction(run);
281
+ }
282
+ : { fields: [], assignmentId: Number(row.id), outcome, reason: reason ?? '' }),
283
+ });
284
+ const notify = outcome === 'done' ? row.assigned_by : row.assignee_id;
285
+ if (notify && notify !== actorId)
286
+ await notifyWithTemplate(trx, notify, outcome === 'done' ? 'assignment.done' : 'assignment.cancelled', { title: row.title, resource: this.label(row.resource), id: row.record_id }, undefined, { resource: String(row.resource), recordId: Number(row.record_id) });
261
287
  }
262
288
  query(db = this.db) {
263
289
  return db('assignments as a')
264
290
  .leftJoin('users as u', 'u.id', 'a.assignee_id')
265
291
  .leftJoin('users as b', 'b.id', 'a.assigned_by')
266
292
  .leftJoin('workflow_runs as wr', 'wr.id', 'a.workflow_run_id')
267
- .select('a.*', 'u.full_name as assignee_name', 'b.full_name as assigned_by_name', 'wr.status as run_status', 'wr.current_step as run_step');
293
+ .leftJoin('users as ob', 'ob.id', 'a.on_behalf_of')
294
+ .select('a.*', 'u.full_name as assignee_name', 'b.full_name as assigned_by_name', 'ob.full_name as on_behalf_of_name', 'wr.status as run_status', 'wr.current_step as run_step', 'wr.started_by as run_started_by', delegationActive(db, this.today()));
268
295
  }
269
- present(row, actor) {
296
+ present(row, actor, scope = NO_DELEGATION) {
270
297
  const open = row.status === 'open';
298
+ const assignee = Number(row.assignee_id);
299
+ // The same rules as actionableBy (ADR 044): a delegate never holds an approval of a
300
+ // run they started, and a row routed through an ended delegation follows its approver.
301
+ const routed = row.delegation_id !== null && row.delegation_id !== undefined;
302
+ const ownRun = row.run_started_by !== null && Number(row.run_started_by) === actor.id;
303
+ const own = assignee === actor.id &&
304
+ (!routed || (scope.delegations.has(Number(row.delegation_id)) && !ownRun));
305
+ const original = row.on_behalf_of !== null && Number(row.on_behalf_of) === actor.id;
306
+ const delegated = Boolean(row.workflow_run_id) &&
307
+ !ownRun &&
308
+ !original &&
309
+ (routed
310
+ ? !row.delegation_active && scope.delegators.has(Number(row.on_behalf_of))
311
+ : scope.delegators.has(assignee));
312
+ // Whose approval the viewer holds: the delegator of a routed one, or a delegator's own.
313
+ const behalf = own && row.on_behalf_of
314
+ ? { id: Number(row.on_behalf_of), name: row.on_behalf_of_name ?? null }
315
+ : delegated
316
+ ? routed
317
+ ? { id: Number(row.on_behalf_of), name: row.on_behalf_of_name ?? null }
318
+ : { id: assignee, name: row.assignee_name ? String(row.assignee_name) : null }
319
+ : null;
271
320
  return {
272
321
  id: Number(row.id),
273
322
  resource: String(row.resource),
@@ -297,7 +346,12 @@ export class Assignments {
297
346
  Boolean(row.workflow_run_id) &&
298
347
  row.run_status === 'waiting' &&
299
348
  row.run_step === row.workflow_step &&
300
- Number(row.assignee_id) === actor.id,
349
+ (own || original || delegated),
350
+ onBehalfOf: behalf,
351
+ dueAt: row.due_at ? new Date(row.due_at).toISOString() : null,
352
+ sla: open && row.due_at
353
+ ? slaState(new Date(row.due_at), row.due_soon_at ? new Date(row.due_soon_at) : null, this.now())
354
+ : null,
301
355
  };
302
356
  }
303
357
  /** Adds record titles in one read per resource, under the viewer's field access. */
@@ -313,21 +367,33 @@ export class Assignments {
313
367
  }
314
368
  return list;
315
369
  }
370
+ /** The delegations in force today that make the user act for someone else. */
371
+ async scope(actorId) {
372
+ const today = this.today();
373
+ const rows = await this.db('workflow_delegations')
374
+ .where('delegate_id', actorId)
375
+ .whereNull('revoked_at')
376
+ .where('starts_on', '<=', today)
377
+ .where('ends_on', '>=', today)
378
+ .select('id', 'delegator_id');
379
+ return {
380
+ delegations: new Set(rows.map((row) => Number(row.id))),
381
+ delegators: new Set(rows.map((row) => Number(row.delegator_id))),
382
+ };
383
+ }
384
+ now() {
385
+ return this.options.now?.() ?? new Date();
386
+ }
387
+ today() {
388
+ return calendarDate(this.now(), this.options.timeZone);
389
+ }
316
390
  closeNote(row) {
317
391
  return row.managed || this.options.closeNote === 'required' ? 'required' : 'optional';
318
392
  }
319
393
  label(name) {
320
- try {
321
- return this.resources.label(name);
322
- }
323
- catch {
324
- return name;
325
- }
394
+ return resourceLabel(this.resources, name);
326
395
  }
327
- async canView(name, id, userId) {
328
- const user = await this.db('users').where('id', userId).first('disabled_at');
329
- if (!user || user.disabled_at)
330
- return false;
331
- return this.resources.permits(name, id, await this.actors.load(userId));
396
+ canView(name, id, userId) {
397
+ return canView(this.db, this.resources, this.actors, name, id, userId);
332
398
  }
333
399
  }
@@ -3,9 +3,8 @@ import type { Actor } from '../auth/ability.js';
3
3
  import type { ResourceService } from '../admin/resource_service.js';
4
4
  import type { JsonValue, Resource } from '../resource/types.js';
5
5
  import type { Listener } from '../events/outbox.js';
6
- export type ActorLoader = {
7
- load(id: number): Promise<Actor>;
8
- };
6
+ import { type ActorLoader } from './shared.js';
7
+ export type { ActorLoader } from './shared.js';
9
8
  export type CommentEntry = {
10
9
  id: number;
11
10
  body: string;