adula 0.0.0 → 2.1.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 (210) hide show
  1. package/LICENSE.md +10 -0
  2. package/README.md +38 -2
  3. package/build/agent/AGENTS.template.md +28 -0
  4. package/build/agent/capabilities.md +60 -0
  5. package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
  6. package/build/agent/skills/idea-review/SKILL.md +31 -0
  7. package/build/agent/skills/module-review/SKILL.md +22 -0
  8. package/build/agent/skills/perf-review/SKILL.md +24 -0
  9. package/build/agent/skills/schema-review/SKILL.md +22 -0
  10. package/build/agent/skills/security-review/SKILL.md +24 -0
  11. package/build/agent/skills/ui-review/SKILL.md +22 -0
  12. package/build/commands/capabilities.d.ts +10 -0
  13. package/build/commands/capabilities.js +40 -0
  14. package/build/commands/doctor.d.ts +9 -0
  15. package/build/commands/doctor.js +72 -0
  16. package/build/commands/gaps.d.ts +12 -0
  17. package/build/commands/gaps.js +62 -0
  18. package/build/commands/install.d.ts +9 -0
  19. package/build/commands/install.js +105 -0
  20. package/build/commands/main.d.ts +8 -0
  21. package/build/commands/main.js +33 -0
  22. package/build/commands/module_add.d.ts +8 -0
  23. package/build/commands/module_add.js +57 -0
  24. package/build/commands/module_remove.d.ts +10 -0
  25. package/build/commands/module_remove.js +94 -0
  26. package/build/commands/resource.d.ts +8 -0
  27. package/build/commands/resource.js +29 -0
  28. package/build/commands/resource_snapshot.d.ts +15 -0
  29. package/build/commands/resource_snapshot.js +61 -0
  30. package/build/commands/storage_migrate.d.ts +12 -0
  31. package/build/commands/storage_migrate.js +39 -0
  32. package/build/commands/ui.d.ts +11 -0
  33. package/build/commands/ui.js +210 -0
  34. package/build/commands/upgrade.d.ts +15 -0
  35. package/build/commands/upgrade.js +34 -0
  36. package/build/configure.d.ts +2 -0
  37. package/build/configure.js +79 -0
  38. package/build/database/migrations/1770000000000_core.d.ts +5 -0
  39. package/build/database/migrations/1770000000000_core.js +10 -0
  40. package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
  41. package/build/database/migrations/1770000000001_attachments.js +10 -0
  42. package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
  43. package/build/database/migrations/1770000000002_saved_views.js +10 -0
  44. package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
  45. package/build/database/migrations/1770000000003_user_invitations.js +18 -0
  46. package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
  47. package/build/database/migrations/1770000000004_collaboration.js +10 -0
  48. package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
  49. package/build/database/migrations/1770000000005_assignments.js +10 -0
  50. package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
  51. package/build/database/migrations/1770000000006_messaging.js +10 -0
  52. package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
  53. package/build/database/migrations/1770000000007_webhooks.js +10 -0
  54. package/build/database/migrations/1770000000008_imports.d.ts +5 -0
  55. package/build/database/migrations/1770000000008_imports.js +10 -0
  56. package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
  57. package/build/database/migrations/1770000000010_workflows.js +10 -0
  58. package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
  59. package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
  60. package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
  61. package/build/database/migrations/1770000000012_role_keys.js +10 -0
  62. package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
  63. package/build/database/migrations/1770000000013_notification_targets.js +10 -0
  64. package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
  65. package/build/database/migrations/1770000000014_upload_grants.js +10 -0
  66. package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
  67. package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
  68. package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
  69. package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
  70. package/build/index.d.ts +80 -0
  71. package/build/index.js +49 -0
  72. package/build/providers/adula_provider.d.ts +6 -0
  73. package/build/providers/adula_provider.js +10 -0
  74. package/build/src/admin/contracts.d.ts +19 -0
  75. package/build/src/admin/contracts.js +115 -0
  76. package/build/src/admin/controller.d.ts +32 -0
  77. package/build/src/admin/controller.js +167 -0
  78. package/build/src/admin/errors.d.ts +5 -0
  79. package/build/src/admin/errors.js +9 -0
  80. package/build/src/admin/presentation.d.ts +28 -0
  81. package/build/src/admin/presentation.js +1 -0
  82. package/build/src/admin/record_title.d.ts +14 -0
  83. package/build/src/admin/record_title.js +50 -0
  84. package/build/src/admin/resource_service.d.ts +376 -0
  85. package/build/src/admin/resource_service.js +1448 -0
  86. package/build/src/attachments/attachment_service.d.ts +100 -0
  87. package/build/src/attachments/attachment_service.js +270 -0
  88. package/build/src/attachments/doctor.d.ts +4 -0
  89. package/build/src/attachments/doctor.js +28 -0
  90. package/build/src/attachments/storage_migrate.d.ts +39 -0
  91. package/build/src/attachments/storage_migrate.js +64 -0
  92. package/build/src/attachments/upload_grants.d.ts +44 -0
  93. package/build/src/attachments/upload_grants.js +105 -0
  94. package/build/src/auth/ability.d.ts +24 -0
  95. package/build/src/auth/ability.js +34 -0
  96. package/build/src/auth/actor_store.d.ts +14 -0
  97. package/build/src/auth/actor_store.js +70 -0
  98. package/build/src/auth/conditions.d.ts +26 -0
  99. package/build/src/auth/conditions.js +117 -0
  100. package/build/src/auth/packed_rules.d.ts +4 -0
  101. package/build/src/auth/packed_rules.js +13 -0
  102. package/build/src/auth/sql.d.ts +11 -0
  103. package/build/src/auth/sql.js +118 -0
  104. package/build/src/collaboration/assignments.d.ts +129 -0
  105. package/build/src/collaboration/assignments.js +333 -0
  106. package/build/src/collaboration/record_collaboration.d.ts +86 -0
  107. package/build/src/collaboration/record_collaboration.js +348 -0
  108. package/build/src/commands/agent_assets.d.ts +7 -0
  109. package/build/src/commands/agent_assets.js +66 -0
  110. package/build/src/commands/capabilities.d.ts +19 -0
  111. package/build/src/commands/capabilities.js +179 -0
  112. package/build/src/commands/doctor.d.ts +42 -0
  113. package/build/src/commands/doctor.js +375 -0
  114. package/build/src/commands/gap_report.d.ts +56 -0
  115. package/build/src/commands/gap_report.js +110 -0
  116. package/build/src/commands/generator.d.ts +1 -0
  117. package/build/src/commands/generator.js +70 -0
  118. package/build/src/commands/snapshot.d.ts +28 -0
  119. package/build/src/commands/snapshot.js +48 -0
  120. package/build/src/commands/source_markers.d.ts +11 -0
  121. package/build/src/commands/source_markers.js +41 -0
  122. package/build/src/core/activity.d.ts +43 -0
  123. package/build/src/core/activity.js +77 -0
  124. package/build/src/core/administration_guard.d.ts +3 -0
  125. package/build/src/core/administration_guard.js +39 -0
  126. package/build/src/core/health.d.ts +42 -0
  127. package/build/src/core/health.js +44 -0
  128. package/build/src/core/mail_test.d.ts +18 -0
  129. package/build/src/core/mail_test.js +88 -0
  130. package/build/src/core/message_templates.d.ts +83 -0
  131. package/build/src/core/message_templates.js +293 -0
  132. package/build/src/core/module_seed.d.ts +15 -0
  133. package/build/src/core/module_seed.js +31 -0
  134. package/build/src/core/notifications.d.ts +42 -0
  135. package/build/src/core/notifications.js +91 -0
  136. package/build/src/core/org_units.d.ts +30 -0
  137. package/build/src/core/org_units.js +123 -0
  138. package/build/src/core/roles.d.ts +98 -0
  139. package/build/src/core/roles.js +447 -0
  140. package/build/src/core/saved_views.d.ts +37 -0
  141. package/build/src/core/saved_views.js +164 -0
  142. package/build/src/core/settings.d.ts +29 -0
  143. package/build/src/core/settings.js +113 -0
  144. package/build/src/core/setup.d.ts +14 -0
  145. package/build/src/core/setup.js +89 -0
  146. package/build/src/core/ui_preferences.d.ts +12 -0
  147. package/build/src/core/ui_preferences.js +30 -0
  148. package/build/src/core/user_invitations.d.ts +23 -0
  149. package/build/src/core/user_invitations.js +144 -0
  150. package/build/src/core/users.d.ts +44 -0
  151. package/build/src/core/users.js +182 -0
  152. package/build/src/database/configure.d.ts +3 -0
  153. package/build/src/database/configure.js +41 -0
  154. package/build/src/database/schema.d.ts +52 -0
  155. package/build/src/database/schema.js +538 -0
  156. package/build/src/eslint/index.d.ts +3 -0
  157. package/build/src/eslint/index.js +90 -0
  158. package/build/src/events/adonis_jobs.d.ts +9 -0
  159. package/build/src/events/adonis_jobs.js +13 -0
  160. package/build/src/events/outbox.d.ts +19 -0
  161. package/build/src/events/outbox.js +33 -0
  162. package/build/src/events/record_mutation.d.ts +24 -0
  163. package/build/src/events/record_mutation.js +62 -0
  164. package/build/src/integrations/imports.d.ts +74 -0
  165. package/build/src/integrations/imports.js +333 -0
  166. package/build/src/integrations/inbound_webhooks.d.ts +94 -0
  167. package/build/src/integrations/inbound_webhooks.js +276 -0
  168. package/build/src/integrations/openapi.d.ts +39 -0
  169. package/build/src/integrations/openapi.js +323 -0
  170. package/build/src/integrations/print.d.ts +37 -0
  171. package/build/src/integrations/print.js +124 -0
  172. package/build/src/integrations/webhooks.d.ts +98 -0
  173. package/build/src/integrations/webhooks.js +298 -0
  174. package/build/src/mcp/tools.d.ts +8 -0
  175. package/build/src/mcp/tools.js +156 -0
  176. package/build/src/org/org_service.d.ts +2 -0
  177. package/build/src/org/org_service.js +16 -0
  178. package/build/src/resource/define_resource.d.ts +5 -0
  179. package/build/src/resource/define_resource.js +68 -0
  180. package/build/src/resource/registry.d.ts +12 -0
  181. package/build/src/resource/registry.js +101 -0
  182. package/build/src/resource/types.d.ts +155 -0
  183. package/build/src/resource/types.js +1 -0
  184. package/build/src/resource/values.d.ts +5 -0
  185. package/build/src/resource/values.js +88 -0
  186. package/build/src/services/backup.d.ts +14 -0
  187. package/build/src/services/backup.js +59 -0
  188. package/build/src/services/settings.d.ts +21 -0
  189. package/build/src/services/settings.js +30 -0
  190. package/build/src/upgrade/legacy.d.ts +27 -0
  191. package/build/src/upgrade/legacy.js +58 -0
  192. package/build/src/upgrade/rename.d.ts +17 -0
  193. package/build/src/upgrade/rename.js +94 -0
  194. package/build/src/version.d.ts +1 -0
  195. package/build/src/version.js +2 -0
  196. package/build/src/workflows/define_workflow.d.ts +124 -0
  197. package/build/src/workflows/define_workflow.js +123 -0
  198. package/build/src/workflows/engine.d.ts +141 -0
  199. package/build/src/workflows/engine.js +752 -0
  200. package/build/stubs/README.md +6 -0
  201. package/build/stubs/controller.stub +8 -0
  202. package/build/stubs/main.d.ts +5 -0
  203. package/build/stubs/main.js +5 -0
  204. package/build/stubs/main.ts +5 -0
  205. package/build/stubs/modules.stub +6 -0
  206. package/build/stubs/resource_contract.stub +1 -0
  207. package/build/stubs/resource_contract.txt +452 -0
  208. package/build/stubs/routes.stub +16 -0
  209. package/build/stubs/service.stub +9 -0
  210. package/package.json +95 -6
@@ -0,0 +1,100 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Field, JsonValue } from '../resource/types.js';
3
+ export type AttachmentSummary = {
4
+ id: number;
5
+ name: string;
6
+ size: number;
7
+ mimeType: string;
8
+ url: string;
9
+ };
10
+ export type AttachmentRecord = {
11
+ id: number;
12
+ disk: string;
13
+ path: string;
14
+ name: string;
15
+ originalName: string;
16
+ size: number;
17
+ mimeType: string;
18
+ extname: string;
19
+ data: Record<string, JsonValue>;
20
+ uploadedBy: number;
21
+ orgUnitId: number | null;
22
+ resource: string | null;
23
+ recordId: number | null;
24
+ field: string | null;
25
+ createdAt: string;
26
+ deletedAt: string | null;
27
+ };
28
+ export type UploadInput = {
29
+ disk: string;
30
+ path: string;
31
+ name: string;
32
+ originalName: string;
33
+ size: number;
34
+ mimeType: string;
35
+ extname: string;
36
+ data: Record<string, unknown>;
37
+ uploadedBy: number;
38
+ orgUnitId?: number | null;
39
+ resource?: string | null;
40
+ field?: string | null;
41
+ /**
42
+ * The redeemed upload grant that authorized this upload instead of a role rule. The upload
43
+ * takes the grant's resource, field and unit, can bind to the granted record only, and is
44
+ * recorded in that record's activity log.
45
+ */
46
+ grant?: {
47
+ id: number;
48
+ resource: string;
49
+ recordId: number;
50
+ field: string;
51
+ orgUnitId: number | null;
52
+ } | null;
53
+ };
54
+ export type ClaimInput = {
55
+ attachmentId: number;
56
+ actor: {
57
+ id: number;
58
+ };
59
+ resource: string;
60
+ field: string;
61
+ /** Omitted while a record is being created: the upload is verified but not bound yet. */
62
+ recordId?: number;
63
+ orgUnitId?: number | null;
64
+ scoped: boolean;
65
+ };
66
+ /** Business documents, images and archives; a field widens or narrows it with `accept`. */
67
+ export declare const DEFAULT_ATTACHMENT_EXTENSIONS: readonly string[];
68
+ /** Unbound uploads one user may hold at once; each is removed by pruning after a day. */
69
+ export declare const PENDING_UPLOAD_LIMIT = 50;
70
+ /** Uploads never bound to a record are removed after this age. */
71
+ export declare const UNBOUND_UPLOAD_TTL_MS: number;
72
+ /** Upload constraints of an attachment field: accepted extensions (undefined = any) and size. */
73
+ export declare function attachmentPolicy(field: Field): {
74
+ extnames?: string[];
75
+ size: string;
76
+ };
77
+ /** Unbound uploads of one user; hosts refuse new uploads beyond PENDING_UPLOAD_LIMIT. */
78
+ export declare function pendingUploadCount(db: Knex, userId: number): Promise<number>;
79
+ /** Uploads that were never bound to a record and are older than the cutoff. */
80
+ export declare function staleUploads(db: Knex, olderThan: Date, limit?: number): Promise<AttachmentRecord[]>;
81
+ /** Deletes the row of an upload that is still unbound; the host removes the file first. */
82
+ export declare function forgetUpload(db: Knex, id: number): Promise<boolean>;
83
+ export declare function attachmentUrl(id: number): string;
84
+ export declare function isAttachmentId(value: unknown): value is number;
85
+ /** Disk keys stay relative and slash-separated so files move between disks unchanged. */
86
+ export declare function isRelativeDiskPath(path: unknown): path is string;
87
+ export declare function summarizeAttachment(row: Record<string, unknown>): AttachmentSummary;
88
+ /** Records a stored file. The host performs the Drive write; AdulaJS only keeps verified metadata. */
89
+ export declare function registerUpload(db: Knex, input: UploadInput): Promise<AttachmentRecord>;
90
+ export declare function findAttachment(db: Knex, id: unknown): Promise<AttachmentRecord | undefined>;
91
+ /** One query per resource page: callers collect every attachment id first. */
92
+ export declare function loadAttachments(db: Knex, ids: readonly number[]): Promise<Map<number, AttachmentSummary>>;
93
+ /**
94
+ * Ownership is decided inside the caller's transaction: a rejected claim rolls
95
+ * the whole record write back. Only the uploader may bind an upload, and an
96
+ * upload binds to exactly one record field.
97
+ */
98
+ export declare function claimAttachment(trx: Knex.Transaction, input: ClaimInput): Promise<AttachmentRecord>;
99
+ /** Unbinding keeps the file and its metadata for restore drills; only the row is soft-deleted. */
100
+ export declare function releaseAttachment(db: Knex, id: number): Promise<boolean>;
@@ -0,0 +1,270 @@
1
+ import { AdulaError } from '../admin/errors.js';
2
+ import { identifier } from '../resource/define_resource.js';
3
+ import { logActivity } from '../core/activity.js';
4
+ const MAX_ID = 2147483647;
5
+ const REJECTED = 'المرفق غير موجود أو لا يخصك';
6
+ /** Business documents, images and archives; a field widens or narrows it with `accept`. */
7
+ export const DEFAULT_ATTACHMENT_EXTENSIONS = Object.freeze([
8
+ 'pdf',
9
+ 'png',
10
+ 'jpg',
11
+ 'jpeg',
12
+ 'gif',
13
+ 'webp',
14
+ 'txt',
15
+ 'csv',
16
+ 'doc',
17
+ 'docx',
18
+ 'xls',
19
+ 'xlsx',
20
+ 'ppt',
21
+ 'pptx',
22
+ 'odt',
23
+ 'ods',
24
+ 'odp',
25
+ 'rtf',
26
+ 'zip',
27
+ ]);
28
+ /** Unbound uploads one user may hold at once; each is removed by pruning after a day. */
29
+ export const PENDING_UPLOAD_LIMIT = 50;
30
+ /** Uploads never bound to a record are removed after this age. */
31
+ export const UNBOUND_UPLOAD_TTL_MS = 24 * 60 * 60 * 1000;
32
+ /** Upload constraints of an attachment field: accepted extensions (undefined = any) and size. */
33
+ export function attachmentPolicy(field) {
34
+ if (field.type !== 'attachment')
35
+ throw new AdulaError(422, 'E_FIELD_INVALID', 'الحقل ليس حقل مرفقات');
36
+ const accept = field.accept ?? DEFAULT_ATTACHMENT_EXTENSIONS;
37
+ return {
38
+ extnames: accept === 'any'
39
+ ? undefined
40
+ : accept.map((extname) => extname.toLowerCase().replace(/^\./, '')),
41
+ size: field.maxSize ?? '20mb',
42
+ };
43
+ }
44
+ /** Unbound uploads of one user; hosts refuse new uploads beyond PENDING_UPLOAD_LIMIT. */
45
+ export async function pendingUploadCount(db, userId) {
46
+ const [{ count }] = await db('attachments')
47
+ .where('uploaded_by', userId)
48
+ .whereNull('record_id')
49
+ .whereNull('deleted_at')
50
+ .count('* as count');
51
+ return Number(count);
52
+ }
53
+ /** Uploads that were never bound to a record and are older than the cutoff. */
54
+ export async function staleUploads(db, olderThan, limit = 500) {
55
+ const rows = await db('attachments')
56
+ .whereNull('record_id')
57
+ .where('created_at', '<', olderThan)
58
+ .orderBy('id')
59
+ .limit(limit);
60
+ return rows.map(fromRow);
61
+ }
62
+ /** Deletes the row of an upload that is still unbound; the host removes the file first. */
63
+ export async function forgetUpload(db, id) {
64
+ if (!isAttachmentId(id))
65
+ return false;
66
+ return (await db('attachments').where('id', id).whereNull('record_id').delete()) > 0;
67
+ }
68
+ export function attachmentUrl(id) {
69
+ return `/attachments/${id}`;
70
+ }
71
+ export function isAttachmentId(value) {
72
+ return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= MAX_ID;
73
+ }
74
+ /** Disk keys stay relative and slash-separated so files move between disks unchanged. */
75
+ export function isRelativeDiskPath(path) {
76
+ return (typeof path === 'string' &&
77
+ path.length > 0 &&
78
+ path.length <= 1024 &&
79
+ !path.startsWith('/') &&
80
+ !path.includes('\\') &&
81
+ !path.includes('\0') &&
82
+ !/^[a-zA-Z]:/.test(path) &&
83
+ path.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..'));
84
+ }
85
+ function text(value, max) {
86
+ return (typeof value === 'string' && value.length > 0 && value.length <= max && !value.includes('\0'));
87
+ }
88
+ export function summarizeAttachment(row) {
89
+ return {
90
+ id: Number(row.id),
91
+ name: String(row.original_name),
92
+ size: Number(row.size),
93
+ mimeType: String(row.mime_type),
94
+ url: attachmentUrl(Number(row.id)),
95
+ };
96
+ }
97
+ function fromRow(row) {
98
+ const stamp = (value) => (value instanceof Date ? value.toISOString() : value);
99
+ return {
100
+ id: Number(row.id),
101
+ disk: String(row.disk),
102
+ path: String(row.path),
103
+ name: String(row.name),
104
+ originalName: String(row.original_name),
105
+ size: Number(row.size),
106
+ mimeType: String(row.mime_type),
107
+ extname: String(row.extname),
108
+ data: (row.data ?? {}),
109
+ uploadedBy: Number(row.uploaded_by),
110
+ orgUnitId: row.org_unit_id === null || row.org_unit_id === undefined ? null : Number(row.org_unit_id),
111
+ resource: row.resource === null || row.resource === undefined ? null : String(row.resource),
112
+ recordId: row.record_id === null || row.record_id === undefined ? null : Number(row.record_id),
113
+ field: row.field === null || row.field === undefined ? null : String(row.field),
114
+ createdAt: String(stamp(row.created_at)),
115
+ deletedAt: row.deleted_at === null || row.deleted_at === undefined
116
+ ? null
117
+ : String(stamp(row.deleted_at)),
118
+ };
119
+ }
120
+ /** Records a stored file. The host performs the Drive write; AdulaJS only keeps verified metadata. */
121
+ export async function registerUpload(db, input) {
122
+ if (!text(input.disk, 100) || !/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(input.disk))
123
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid disk name');
124
+ if (!isRelativeDiskPath(input.path))
125
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Attachment paths must be relative disk keys');
126
+ if (!text(input.name, 255) ||
127
+ input.name.includes('/') ||
128
+ input.name !== input.path.split('/').at(-1))
129
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Attachment name must be the last path segment');
130
+ if (!text(input.originalName, 255) || /[/\\]/.test(input.originalName))
131
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid original file name');
132
+ if (!Number.isSafeInteger(input.size) || input.size < 0)
133
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid file size');
134
+ if (typeof input.mimeType !== 'string' ||
135
+ input.mimeType.length > 255 ||
136
+ /[\r\n\0]/.test(input.mimeType))
137
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid content type');
138
+ if (typeof input.extname !== 'string' || !/^[a-z0-9]{0,32}$/.test(input.extname))
139
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid file extension');
140
+ if (!input.data || typeof input.data !== 'object' || Array.isArray(input.data))
141
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Attachment data must be an object');
142
+ if (!isAttachmentId(input.uploadedBy))
143
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid uploader');
144
+ if (input.orgUnitId !== undefined && input.orgUnitId !== null && !isAttachmentId(input.orgUnitId))
145
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid organization unit');
146
+ for (const key of ['resource', 'field']) {
147
+ const value = input[key];
148
+ if (value !== undefined &&
149
+ value !== null &&
150
+ (typeof value !== 'string' || !/^[a-zA-Z][a-zA-Z0-9_]*$/.test(value)))
151
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', `Invalid ${key}`);
152
+ }
153
+ if (input.resource)
154
+ identifier(input.resource);
155
+ const grant = input.grant;
156
+ if (grant &&
157
+ (!isAttachmentId(grant.id) ||
158
+ !isAttachmentId(grant.recordId) ||
159
+ grant.resource !== input.resource ||
160
+ grant.field !== input.field))
161
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'The upload grant names another field');
162
+ // Only a redeemed grant may mark an upload as granted.
163
+ const data = { ...input.data };
164
+ delete data.uploadGrant;
165
+ if (grant)
166
+ data.uploadGrant = { id: grant.id, recordId: grant.recordId };
167
+ const [row] = await db('attachments')
168
+ .insert({
169
+ disk: input.disk,
170
+ path: input.path,
171
+ name: input.name,
172
+ original_name: input.originalName,
173
+ size: input.size,
174
+ mime_type: input.mimeType || 'application/octet-stream',
175
+ extname: input.extname,
176
+ data: JSON.stringify(data),
177
+ uploaded_by: input.uploadedBy,
178
+ org_unit_id: grant ? grant.orgUnitId : (input.orgUnitId ?? null),
179
+ resource: input.resource ?? null,
180
+ field: input.field ?? null,
181
+ })
182
+ .returning('*');
183
+ if (grant)
184
+ await logActivity(db, {
185
+ resource: grant.resource,
186
+ recordId: grant.recordId,
187
+ actorId: input.uploadedBy,
188
+ action: 'upload_via_grant',
189
+ changes: { field: grant.field, attachmentId: Number(row.id), grantId: grant.id },
190
+ });
191
+ return fromRow(row);
192
+ }
193
+ export async function findAttachment(db, id) {
194
+ if (!isAttachmentId(id))
195
+ return undefined;
196
+ const row = await db('attachments').where('id', id).whereNull('deleted_at').first();
197
+ return row ? fromRow(row) : undefined;
198
+ }
199
+ /** One query per resource page: callers collect every attachment id first. */
200
+ export async function loadAttachments(db, ids) {
201
+ const summaries = new Map();
202
+ const valid = [...new Set(ids.filter(isAttachmentId))];
203
+ if (!valid.length)
204
+ return summaries;
205
+ const rows = await db('attachments')
206
+ .whereIn('id', valid)
207
+ .whereNull('deleted_at')
208
+ .select('id', 'original_name', 'size', 'mime_type');
209
+ for (const row of rows)
210
+ summaries.set(Number(row.id), summarizeAttachment(row));
211
+ return summaries;
212
+ }
213
+ /**
214
+ * Ownership is decided inside the caller's transaction: a rejected claim rolls
215
+ * the whole record write back. Only the uploader may bind an upload, and an
216
+ * upload binds to exactly one record field.
217
+ */
218
+ export async function claimAttachment(trx, input) {
219
+ if (!isAttachmentId(input.attachmentId))
220
+ throw new AdulaError(422, 'E_ATTACHMENT', REJECTED);
221
+ const row = await trx('attachments').where('id', input.attachmentId).forUpdate().first();
222
+ if (!row || row.deleted_at !== null || Number(row.uploaded_by) !== Number(input.actor.id))
223
+ throw new AdulaError(422, 'E_ATTACHMENT', REJECTED);
224
+ if ((row.resource !== null && row.resource !== input.resource) ||
225
+ (row.field !== null && row.field !== input.field))
226
+ throw new AdulaError(422, 'E_ATTACHMENT', 'المرفق مخصص لحقل آخر');
227
+ // An upload authorized by a grant binds to the granted record only, never to a new one.
228
+ const granted = row.data?.uploadGrant;
229
+ if (granted &&
230
+ (input.recordId === undefined || Number(granted.recordId) !== Number(input.recordId)))
231
+ throw new AdulaError(422, 'E_ATTACHMENT', 'المرفق مخصص لسجل آخر');
232
+ const bound = row.record_id !== null;
233
+ const sameRecord = bound &&
234
+ input.recordId !== undefined &&
235
+ Number(row.record_id) === Number(input.recordId) &&
236
+ row.resource === input.resource &&
237
+ row.field === input.field;
238
+ if (bound && !sameRecord)
239
+ throw new AdulaError(422, 'E_ATTACHMENT', 'المرفق مرتبط بسجل آخر');
240
+ const orgUnitId = input.scoped && input.orgUnitId !== undefined && input.orgUnitId !== null
241
+ ? Number(input.orgUnitId)
242
+ : null;
243
+ if (input.scoped &&
244
+ !sameRecord &&
245
+ row.org_unit_id !== null &&
246
+ (orgUnitId === null || Number(row.org_unit_id) !== orgUnitId))
247
+ throw new AdulaError(422, 'E_ATTACHMENT', 'المرفق يتبع وحدة تنظيمية أخرى');
248
+ if (input.recordId === undefined)
249
+ return fromRow(row);
250
+ const [updated] = await trx('attachments')
251
+ .where('id', input.attachmentId)
252
+ .update({
253
+ resource: input.resource,
254
+ field: input.field,
255
+ record_id: input.recordId,
256
+ org_unit_id: input.scoped ? orgUnitId : row.org_unit_id,
257
+ })
258
+ .returning('*');
259
+ return fromRow(updated);
260
+ }
261
+ /** Unbinding keeps the file and its metadata for restore drills; only the row is soft-deleted. */
262
+ export async function releaseAttachment(db, id) {
263
+ if (!isAttachmentId(id))
264
+ return false;
265
+ const changed = await db('attachments')
266
+ .where('id', id)
267
+ .whereNull('deleted_at')
268
+ .update({ deleted_at: db.fn.now() });
269
+ return changed > 0;
270
+ }
@@ -0,0 +1,4 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Finding } from '../commands/doctor.js';
3
+ /** Unbound uploads are files whose form was never saved; they are reported, never deleted here. */
4
+ export declare function diagnoseAttachments(db: Knex, now?: number): Promise<Finding>;
@@ -0,0 +1,28 @@
1
+ const STALE_UPLOAD_MS = 24 * 3600000;
2
+ /** Unbound uploads are files whose form was never saved; they are reported, never deleted here. */
3
+ export async function diagnoseAttachments(db, now = Date.now()) {
4
+ try {
5
+ const result = await db.raw(`SELECT
6
+ count(*) FILTER (WHERE record_id IS NOT NULL) AS bound,
7
+ count(*) FILTER (WHERE record_id IS NULL) AS unbound,
8
+ count(*) FILTER (WHERE record_id IS NULL AND created_at < ?) AS stale,
9
+ coalesce(sum(size), 0) AS bytes
10
+ FROM attachments WHERE deleted_at IS NULL`, [new Date(now - STALE_UPLOAD_MS).toISOString()]);
11
+ const row = result.rows[0];
12
+ const live = Number(row.bound) + Number(row.unbound);
13
+ return {
14
+ check: 'attachments',
15
+ status: 'info',
16
+ message: `${row.bound} bound attachments, ${row.unbound} unbound uploads (${row.stale} older than 24 hours), ${row.bytes} bytes in ${live} live files`,
17
+ };
18
+ }
19
+ catch (error) {
20
+ if (error.code === '42P01')
21
+ return {
22
+ check: 'attachments',
23
+ status: 'warn',
24
+ message: 'attachments table is missing; run migration:run',
25
+ };
26
+ throw error;
27
+ }
28
+ }
@@ -0,0 +1,39 @@
1
+ import type { Readable } from 'node:stream';
2
+ import type { Knex } from 'knex';
3
+ /** The subset of a Drive disk the migration needs; keeps AdulaJS independent of flydrive. */
4
+ export type StorageDisk = {
5
+ exists(key: string): Promise<boolean>;
6
+ getStream(key: string): Promise<Readable>;
7
+ putStream(key: string, contents: Readable): Promise<void>;
8
+ getMetaData(key: string): Promise<{
9
+ contentLength: number;
10
+ }>;
11
+ };
12
+ export type StorageMigrationOptions = {
13
+ from: string;
14
+ to: string;
15
+ disks: readonly string[];
16
+ use: (name: string) => StorageDisk;
17
+ dryRun?: boolean;
18
+ report?: (line: string) => void;
19
+ };
20
+ export type StorageMigrationResult = {
21
+ from: string;
22
+ to: string;
23
+ dryRun: boolean;
24
+ total: number;
25
+ copied: number;
26
+ skipped: number;
27
+ failed: {
28
+ id: number;
29
+ path: string;
30
+ reason: string;
31
+ }[];
32
+ remaining: number;
33
+ };
34
+ /**
35
+ * Copies every live attachment file to the target disk, verifies its size and
36
+ * repoints the row in its own statement. Rerunning after an interruption only
37
+ * touches rows still on the source disk; source files are never deleted here.
38
+ */
39
+ export declare function migrateStorage(db: Knex, options: StorageMigrationOptions): Promise<StorageMigrationResult>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Copies every live attachment file to the target disk, verifies its size and
3
+ * repoints the row in its own statement. Rerunning after an interruption only
4
+ * touches rows still on the source disk; source files are never deleted here.
5
+ */
6
+ export async function migrateStorage(db, options) {
7
+ for (const name of [options.from, options.to])
8
+ if (!options.disks.includes(name))
9
+ throw new Error(`Unknown disk: ${name}`);
10
+ if (options.from === options.to)
11
+ throw new Error('Source and target disks must differ');
12
+ const rows = await db('attachments')
13
+ .where('disk', options.from)
14
+ .whereNull('deleted_at')
15
+ .orderBy('id')
16
+ .select('id', 'path', 'size');
17
+ const result = {
18
+ from: options.from,
19
+ to: options.to,
20
+ dryRun: Boolean(options.dryRun),
21
+ total: rows.length,
22
+ copied: 0,
23
+ skipped: 0,
24
+ failed: [],
25
+ remaining: rows.length,
26
+ };
27
+ const report = options.report ?? (() => { });
28
+ if (options.dryRun) {
29
+ for (const row of rows)
30
+ report(`would copy #${row.id} ${row.path} (${row.size} bytes)`);
31
+ return result;
32
+ }
33
+ const source = options.use(options.from);
34
+ const target = options.use(options.to);
35
+ for (const row of rows) {
36
+ const size = Number(row.size);
37
+ try {
38
+ let present = false;
39
+ if (await target.exists(row.path)) {
40
+ const existing = await target.getMetaData(row.path);
41
+ present = existing.contentLength === size;
42
+ }
43
+ if (!present) {
44
+ await target.putStream(row.path, await source.getStream(row.path));
45
+ const written = await target.getMetaData(row.path);
46
+ if (written.contentLength !== size)
47
+ throw new Error(`size mismatch after copy: expected ${size}, found ${written.contentLength}`);
48
+ }
49
+ await db.transaction((trx) => trx('attachments').where({ id: row.id, disk: options.from }).update({ disk: options.to }));
50
+ if (present)
51
+ result.skipped++;
52
+ else
53
+ result.copied++;
54
+ result.remaining--;
55
+ report(`${present ? 'verified' : 'copied'} #${row.id} ${row.path}`);
56
+ }
57
+ catch (error) {
58
+ const reason = error instanceof Error ? error.message : String(error);
59
+ result.failed.push({ id: Number(row.id), path: row.path, reason });
60
+ report(`failed #${row.id} ${row.path}: ${reason}`);
61
+ }
62
+ }
63
+ return result;
64
+ }
@@ -0,0 +1,44 @@
1
+ import type { Knex } from 'knex';
2
+ import type { ResourceRegistry } from '../resource/registry.js';
3
+ /** Longest lifetime of an upload grant; module pages ask for one right before the upload. */
4
+ export declare const UPLOAD_GRANT_MAX_TTL_MS: number;
5
+ export type UploadGrantInput = {
6
+ resource: string;
7
+ recordId: number;
8
+ /** An attachment field of the resource. */
9
+ field: string;
10
+ /** The user who may upload with the grant. */
11
+ userId: number;
12
+ /** Who decided the grant (the module's signed-in user or a system actor); defaults to userId. */
13
+ actorId?: number;
14
+ /** Lifetime in milliseconds, at most one hour (default ten minutes). */
15
+ ttlMs?: number;
16
+ };
17
+ export type UploadGrant = {
18
+ token: string;
19
+ expiresAt: string;
20
+ };
21
+ export type RedeemedUploadGrant = {
22
+ id: number;
23
+ resource: string;
24
+ recordId: number;
25
+ field: string;
26
+ orgUnitId: number | null;
27
+ };
28
+ /**
29
+ * Lets one user upload a file for one attachment field of one existing record, when module
30
+ * code has authorized that user itself (for example the inspector of a visit) and the role
31
+ * rules grant no generic right. Only the token hash is stored. The grant replaces the
32
+ * upload's authorization (the role rule, the field's permission and hidden levels and form
33
+ * membership); type, size, the pending-upload limit, ownership and binding through the
34
+ * record write stay as for any upload, and the upload can bind to this record only. Issuing it is recorded in the record's activity log. Call it from module code after
35
+ * the module's own authorization, never on a user's word alone.
36
+ */
37
+ export declare function grantUpload(db: Knex, registry: Pick<ResourceRegistry, 'all' | 'get'>, input: UploadGrantInput): Promise<UploadGrant>;
38
+ /**
39
+ * The grant a token names, while it is unexpired, held by this user, and its record is still
40
+ * live and, for documents, a draft; otherwise null. The unit is the record's current unit.
41
+ */
42
+ export declare function redeemUploadGrant(db: Knex, registry: Pick<ResourceRegistry, 'all' | 'get'>, token: unknown, userId: number): Promise<RedeemedUploadGrant | null>;
43
+ /** Removes expired grants; the upload pruning schedule may call it. */
44
+ export declare function pruneUploadGrants(db: Knex): Promise<number>;
@@ -0,0 +1,105 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ import { logActivity } from '../core/activity.js';
4
+ import { isAttachmentId } from './attachment_service.js';
5
+ /** Longest lifetime of an upload grant; module pages ask for one right before the upload. */
6
+ export const UPLOAD_GRANT_MAX_TTL_MS = 60 * 60 * 1000;
7
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
8
+ const hash = (token) => createHash('sha256').update(token).digest('hex');
9
+ /**
10
+ * Lets one user upload a file for one attachment field of one existing record, when module
11
+ * code has authorized that user itself (for example the inspector of a visit) and the role
12
+ * rules grant no generic right. Only the token hash is stored. The grant replaces the
13
+ * upload's authorization (the role rule, the field's permission and hidden levels and form
14
+ * membership); type, size, the pending-upload limit, ownership and binding through the
15
+ * record write stay as for any upload, and the upload can bind to this record only. Issuing it is recorded in the record's activity log. Call it from module code after
16
+ * the module's own authorization, never on a user's word alone.
17
+ */
18
+ export async function grantUpload(db, registry, input) {
19
+ if (typeof input.resource !== 'string' ||
20
+ !registry.all().some((entry) => entry.name === input.resource))
21
+ throw new AdulaError(404, 'E_NOT_FOUND', 'الكيان غير موجود');
22
+ const resource = registry.get(input.resource);
23
+ const field = Object.hasOwn(resource.fields, input.field) ? resource.fields[input.field] : null;
24
+ if (!field || field.type !== 'attachment')
25
+ throw new AdulaError(422, 'E_FIELD_INVALID', 'الحقل ليس حقل مرفقات');
26
+ if (!isAttachmentId(input.recordId) || !isAttachmentId(input.userId))
27
+ throw new AdulaError(422, 'E_UPLOAD_GRANT', 'Invalid record or user');
28
+ if (input.actorId !== undefined && !isAttachmentId(input.actorId))
29
+ throw new AdulaError(422, 'E_UPLOAD_GRANT', 'Invalid actor');
30
+ const ttl = input.ttlMs ?? DEFAULT_TTL_MS;
31
+ if (!Number.isSafeInteger(ttl) || ttl < 1000 || ttl > UPLOAD_GRANT_MAX_TTL_MS)
32
+ throw new AdulaError(422, 'E_UPLOAD_GRANT', 'Grant lifetime must be between 1 second and 1 hour');
33
+ const record = await db(resource.name)
34
+ .where('id', input.recordId)
35
+ .whereNull('deleted_at')
36
+ .first([
37
+ 'id',
38
+ ...(resource.scoped ? ['org_unit_id'] : []),
39
+ ...(resource.submittable ? ['doc_status'] : []),
40
+ ]);
41
+ if (!record)
42
+ throw new AdulaError(404, 'E_NOT_FOUND', 'السجل غير موجود');
43
+ // A submitted or cancelled document is locked: no new evidence can be bound to it.
44
+ if (resource.submittable && Number(record.doc_status) !== 0)
45
+ throw new AdulaError(409, 'E_DOCUMENT_LOCKED', 'المستند معتمد أو ملغى ولا يقبل مرفقات جديدة');
46
+ // A disabled user cannot sign in, so cannot redeem the grant either.
47
+ if (!(await db('users').where('id', input.userId).first('id')))
48
+ throw new AdulaError(422, 'E_UPLOAD_GRANT', 'Unknown user');
49
+ const token = randomBytes(32).toString('base64url');
50
+ const expiresAt = new Date(Date.now() + ttl);
51
+ await db('upload_grants').insert({
52
+ token_hash: hash(token),
53
+ user_id: input.userId,
54
+ resource: resource.name,
55
+ record_id: input.recordId,
56
+ field: input.field,
57
+ org_unit_id: resource.scoped ? record.org_unit_id : null,
58
+ expires_at: expiresAt,
59
+ created_by: input.actorId ?? input.userId,
60
+ });
61
+ await logActivity(db, {
62
+ resource: resource.name,
63
+ recordId: input.recordId,
64
+ actorId: input.actorId ?? input.userId,
65
+ action: 'upload_granted',
66
+ changes: { field: input.field, userId: input.userId, expiresAt: expiresAt.toISOString() },
67
+ });
68
+ return { token, expiresAt: expiresAt.toISOString() };
69
+ }
70
+ /**
71
+ * The grant a token names, while it is unexpired, held by this user, and its record is still
72
+ * live and, for documents, a draft; otherwise null. The unit is the record's current unit.
73
+ */
74
+ export async function redeemUploadGrant(db, registry, token, userId) {
75
+ if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token))
76
+ return null;
77
+ const row = await db('upload_grants')
78
+ .where({ token_hash: hash(token), user_id: userId })
79
+ .where('expires_at', '>', db.fn.now())
80
+ .first();
81
+ if (!row || !registry.all().some((entry) => entry.name === row.resource))
82
+ return null;
83
+ const resource = registry.get(String(row.resource));
84
+ const record = await db(resource.name)
85
+ .where('id', row.record_id)
86
+ .whereNull('deleted_at')
87
+ .first([
88
+ 'id',
89
+ ...(resource.scoped ? ['org_unit_id'] : []),
90
+ ...(resource.submittable ? ['doc_status'] : []),
91
+ ]);
92
+ if (!record || (resource.submittable && Number(record.doc_status) !== 0))
93
+ return null;
94
+ return {
95
+ id: Number(row.id),
96
+ resource: resource.name,
97
+ recordId: Number(row.record_id),
98
+ field: String(row.field),
99
+ orgUnitId: resource.scoped && record.org_unit_id !== null ? Number(record.org_unit_id) : null,
100
+ };
101
+ }
102
+ /** Removes expired grants; the upload pruning schedule may call it. */
103
+ export async function pruneUploadGrants(db) {
104
+ return db('upload_grants').where('expires_at', '<=', db.fn.now()).delete();
105
+ }