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
@@ -1,11 +1,25 @@
1
1
  import type { Knex } from 'knex';
2
2
  import type { Field, JsonValue } from '../resource/types.js';
3
+ /** How a file can be previewed inline (ADR 047); every other file only downloads. */
4
+ export type AttachmentPreview = 'image' | 'pdf' | 'text';
3
5
  export type AttachmentSummary = {
4
6
  id: number;
5
7
  name: string;
6
8
  size: number;
7
9
  mimeType: string;
8
10
  url: string;
11
+ /**
12
+ * Set for allow-listed images, PDF and plain text: `${url}?preview=1` renders inline.
13
+ * Missing or null means the file only downloads.
14
+ */
15
+ preview?: AttachmentPreview | null;
16
+ };
17
+ /**
18
+ * Deployment settings of attachment previews (ADR 047). `pdfPreview` (default true) turns
19
+ * inline PDF previews off: PDFs then report no preview and `?preview=1` downloads them.
20
+ */
21
+ export type AttachmentPreviewOptions = {
22
+ pdfPreview?: boolean;
9
23
  };
10
24
  export type AttachmentRecord = {
11
25
  id: number;
@@ -35,6 +49,8 @@ export type UploadInput = {
35
49
  extname: string;
36
50
  data: Record<string, unknown>;
37
51
  uploadedBy: number;
52
+ /** The administrator impersonating uploadedBy, recorded with the upload and its activity. */
53
+ impersonatorId?: number | null;
38
54
  orgUnitId?: number | null;
39
55
  resource?: string | null;
40
56
  field?: string | null;
@@ -81,20 +97,48 @@ export declare function staleUploads(db: Knex, olderThan: Date, limit?: number):
81
97
  /** Deletes the row of an upload that is still unbound; the host removes the file first. */
82
98
  export declare function forgetUpload(db: Knex, id: number): Promise<boolean>;
83
99
  export declare function attachmentUrl(id: number): string;
100
+ /** How a stored file previews inline, or null when it can only be downloaded. */
101
+ export declare function attachmentPreview(file: {
102
+ extname: string;
103
+ mimeType: string;
104
+ }, options?: AttachmentPreviewOptions): AttachmentPreview | null;
105
+ /**
106
+ * Response headers of an authorized download. With `preview`, an allow-listed file is
107
+ * served inline with its listed type and may be framed by this origin only (the preview
108
+ * dialog); any other file is still sent as a download. Every response forbids sniffing and
109
+ * script: images and text are sandboxed, PDFs are not (browsers refuse to show sandboxed
110
+ * PDFs) but may run no page script either.
111
+ */
112
+ export declare function attachmentHeaders(file: Pick<AttachmentRecord, 'originalName' | 'mimeType' | 'extname' | 'size'>, options?: {
113
+ preview?: boolean;
114
+ } & AttachmentPreviewOptions): Record<string, string>;
84
115
  export declare function isAttachmentId(value: unknown): value is number;
85
116
  /** Disk keys stay relative and slash-separated so files move between disks unchanged. */
86
117
  export declare function isRelativeDiskPath(path: unknown): path is string;
87
- export declare function summarizeAttachment(row: Record<string, unknown>): AttachmentSummary;
118
+ export declare function summarizeAttachment(row: Record<string, unknown>, options?: AttachmentPreviewOptions): AttachmentSummary;
88
119
  /** Records a stored file. The host performs the Drive write; AdulaJS only keeps verified metadata. */
89
120
  export declare function registerUpload(db: Knex, input: UploadInput): Promise<AttachmentRecord>;
90
121
  export declare function findAttachment(db: Knex, id: unknown): Promise<AttachmentRecord | undefined>;
91
122
  /** 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>>;
123
+ export declare function loadAttachments(db: Knex, ids: readonly number[], options?: AttachmentPreviewOptions): Promise<Map<number, AttachmentSummary>>;
93
124
  /**
94
125
  * Ownership is decided inside the caller's transaction: a rejected claim rolls
95
126
  * the whole record write back. Only the uploader may bind an upload, and an
96
127
  * upload binds to exactly one record field.
97
128
  */
98
129
  export declare function claimAttachment(trx: Knex.Transaction, input: ClaimInput): Promise<AttachmentRecord>;
130
+ /**
131
+ * Moves a file the record already holds to the record's new organization unit, inside the
132
+ * record write's transaction. Unlike claimAttachment there is no uploader check: the file
133
+ * is bound to exactly this record field already, and the record's own move was authorized.
134
+ * Anything else (unbound, released, another record or field) is refused.
135
+ */
136
+ export declare function rebindAttachment(trx: Knex.Transaction, input: {
137
+ attachmentId: number;
138
+ resource: string;
139
+ field: string;
140
+ recordId: number;
141
+ orgUnitId: number;
142
+ }): Promise<void>;
99
143
  /** Unbinding keeps the file and its metadata for restore drills; only the row is soft-deleted. */
100
144
  export declare function releaseAttachment(db: Knex, id: number): Promise<boolean>;
@@ -68,6 +68,70 @@ export async function forgetUpload(db, id) {
68
68
  export function attachmentUrl(id) {
69
69
  return `/attachments/${id}`;
70
70
  }
71
+ /**
72
+ * Files that may render inline, by extension: the stored content type must be the listed
73
+ * one too, and the response then carries the listed type, never the uploader's. SVG, HTML
74
+ * and every other type can run script or be mistaken for a page, so they only download.
75
+ */
76
+ const PREVIEWABLE = Object.freeze({
77
+ png: { preview: 'image', contentType: 'image/png', mimeTypes: ['image/png'] },
78
+ jpg: { preview: 'image', contentType: 'image/jpeg', mimeTypes: ['image/jpeg'] },
79
+ jpeg: { preview: 'image', contentType: 'image/jpeg', mimeTypes: ['image/jpeg'] },
80
+ gif: { preview: 'image', contentType: 'image/gif', mimeTypes: ['image/gif'] },
81
+ webp: { preview: 'image', contentType: 'image/webp', mimeTypes: ['image/webp'] },
82
+ pdf: { preview: 'pdf', contentType: 'application/pdf', mimeTypes: ['application/pdf'] },
83
+ txt: { preview: 'text', contentType: 'text/plain; charset=utf-8', mimeTypes: ['text/plain'] },
84
+ });
85
+ function previewEntry(file, options = {}) {
86
+ const extname = String(file.extname).toLowerCase();
87
+ const entry = Object.hasOwn(PREVIEWABLE, extname) ? PREVIEWABLE[extname] : undefined;
88
+ const mimeType = String(file.mimeType).split(';')[0].trim().toLowerCase();
89
+ if (!entry || !entry.mimeTypes.includes(mimeType))
90
+ return undefined;
91
+ return entry.preview === 'pdf' && options.pdfPreview === false ? undefined : entry;
92
+ }
93
+ /** How a stored file previews inline, or null when it can only be downloaded. */
94
+ export function attachmentPreview(file, options = {}) {
95
+ return previewEntry(file, options)?.preview ?? null;
96
+ }
97
+ /** RFC 5987: an ASCII fallback plus the UTF-8 name so Arabic titles survive every browser. */
98
+ function disposition(kind, name) {
99
+ const fallback = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_') || 'file';
100
+ const encoded = encodeURIComponent(name).replace(/[!'()*]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
101
+ return `${kind}; filename="${fallback}"; filename*=UTF-8''${encoded}`;
102
+ }
103
+ /**
104
+ * Response headers of an authorized download. With `preview`, an allow-listed file is
105
+ * served inline with its listed type and may be framed by this origin only (the preview
106
+ * dialog); any other file is still sent as a download. Every response forbids sniffing and
107
+ * script: images and text are sandboxed, PDFs are not (browsers refuse to show sandboxed
108
+ * PDFs) but may run no page script either.
109
+ */
110
+ export function attachmentHeaders(file, options = {}) {
111
+ const entry = options.preview ? previewEntry(file, options) : undefined;
112
+ const common = {
113
+ 'Content-Length': String(file.size),
114
+ 'X-Content-Type-Options': 'nosniff',
115
+ 'Cache-Control': 'private, no-store',
116
+ };
117
+ if (!entry)
118
+ return {
119
+ ...common,
120
+ 'Content-Type': file.mimeType || 'application/octet-stream',
121
+ 'Content-Disposition': disposition('attachment', file.originalName),
122
+ 'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'; sandbox",
123
+ 'X-Frame-Options': 'DENY',
124
+ };
125
+ return {
126
+ ...common,
127
+ 'Content-Type': entry.contentType,
128
+ 'Content-Disposition': disposition('inline', file.originalName),
129
+ 'Content-Security-Policy': entry.preview === 'pdf'
130
+ ? "default-src 'none'; object-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'self'"
131
+ : "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; frame-ancestors 'self'; sandbox",
132
+ 'X-Frame-Options': 'SAMEORIGIN',
133
+ };
134
+ }
71
135
  export function isAttachmentId(value) {
72
136
  return Number.isSafeInteger(value) && Number(value) >= 1 && Number(value) <= MAX_ID;
73
137
  }
@@ -85,13 +149,14 @@ export function isRelativeDiskPath(path) {
85
149
  function text(value, max) {
86
150
  return (typeof value === 'string' && value.length > 0 && value.length <= max && !value.includes('\0'));
87
151
  }
88
- export function summarizeAttachment(row) {
152
+ export function summarizeAttachment(row, options = {}) {
89
153
  return {
90
154
  id: Number(row.id),
91
155
  name: String(row.original_name),
92
156
  size: Number(row.size),
93
157
  mimeType: String(row.mime_type),
94
158
  url: attachmentUrl(Number(row.id)),
159
+ preview: attachmentPreview({ extname: String(row.extname ?? ''), mimeType: String(row.mime_type) }, options),
95
160
  };
96
161
  }
97
162
  function fromRow(row) {
@@ -141,6 +206,10 @@ export async function registerUpload(db, input) {
141
206
  throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Attachment data must be an object');
142
207
  if (!isAttachmentId(input.uploadedBy))
143
208
  throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid uploader');
209
+ if (input.impersonatorId !== undefined &&
210
+ input.impersonatorId !== null &&
211
+ !isAttachmentId(input.impersonatorId))
212
+ throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid impersonator');
144
213
  if (input.orgUnitId !== undefined && input.orgUnitId !== null && !isAttachmentId(input.orgUnitId))
145
214
  throw new AdulaError(422, 'E_ATTACHMENT_INPUT', 'Invalid organization unit');
146
215
  for (const key of ['resource', 'field']) {
@@ -162,8 +231,11 @@ export async function registerUpload(db, input) {
162
231
  // Only a redeemed grant may mark an upload as granted.
163
232
  const data = { ...input.data };
164
233
  delete data.uploadGrant;
234
+ delete data.impersonatedBy;
165
235
  if (grant)
166
236
  data.uploadGrant = { id: grant.id, recordId: grant.recordId };
237
+ if (input.impersonatorId)
238
+ data.impersonatedBy = input.impersonatorId;
167
239
  const [row] = await db('attachments')
168
240
  .insert({
169
241
  disk: input.disk,
@@ -185,6 +257,7 @@ export async function registerUpload(db, input) {
185
257
  resource: grant.resource,
186
258
  recordId: grant.recordId,
187
259
  actorId: input.uploadedBy,
260
+ impersonatorId: input.impersonatorId,
188
261
  action: 'upload_via_grant',
189
262
  changes: { field: grant.field, attachmentId: Number(row.id), grantId: grant.id },
190
263
  });
@@ -197,7 +270,7 @@ export async function findAttachment(db, id) {
197
270
  return row ? fromRow(row) : undefined;
198
271
  }
199
272
  /** One query per resource page: callers collect every attachment id first. */
200
- export async function loadAttachments(db, ids) {
273
+ export async function loadAttachments(db, ids, options = {}) {
201
274
  const summaries = new Map();
202
275
  const valid = [...new Set(ids.filter(isAttachmentId))];
203
276
  if (!valid.length)
@@ -205,9 +278,9 @@ export async function loadAttachments(db, ids) {
205
278
  const rows = await db('attachments')
206
279
  .whereIn('id', valid)
207
280
  .whereNull('deleted_at')
208
- .select('id', 'original_name', 'size', 'mime_type');
281
+ .select('id', 'original_name', 'size', 'mime_type', 'extname');
209
282
  for (const row of rows)
210
- summaries.set(Number(row.id), summarizeAttachment(row));
283
+ summaries.set(Number(row.id), summarizeAttachment(row, options));
211
284
  return summaries;
212
285
  }
213
286
  /**
@@ -258,6 +331,25 @@ export async function claimAttachment(trx, input) {
258
331
  .returning('*');
259
332
  return fromRow(updated);
260
333
  }
334
+ /**
335
+ * Moves a file the record already holds to the record's new organization unit, inside the
336
+ * record write's transaction. Unlike claimAttachment there is no uploader check: the file
337
+ * is bound to exactly this record field already, and the record's own move was authorized.
338
+ * Anything else (unbound, released, another record or field) is refused.
339
+ */
340
+ export async function rebindAttachment(trx, input) {
341
+ if (!isAttachmentId(input.attachmentId))
342
+ throw new AdulaError(422, 'E_ATTACHMENT', REJECTED);
343
+ const row = await trx('attachments').where('id', input.attachmentId).forUpdate().first();
344
+ if (!row ||
345
+ row.deleted_at !== null ||
346
+ row.resource !== input.resource ||
347
+ row.field !== input.field ||
348
+ row.record_id === null ||
349
+ Number(row.record_id) !== Number(input.recordId))
350
+ throw new AdulaError(422, 'E_ATTACHMENT', 'المرفق مرتبط بسجل آخر');
351
+ await trx('attachments').where('id', input.attachmentId).update({ org_unit_id: input.orgUnitId });
352
+ }
261
353
  /** Unbinding keeps the file and its metadata for restore drills; only the row is soft-deleted. */
262
354
  export async function releaseAttachment(db, id) {
263
355
  if (!isAttachmentId(id))
@@ -23,4 +23,9 @@ export declare function actorConditionField(resource: Pick<Resource, 'fields'> |
23
23
  export declare function usesActor(conditions: Conditions | undefined | null): boolean;
24
24
  export declare function predicates(conditions?: Conditions, fields?: Set<string>): Predicate[];
25
25
  export declare function likePattern(value: string): RegExp;
26
+ /**
27
+ * Compares two decimal strings by value (-1, 0, 1), or undefined when either is not a
28
+ * plain decimal string. Fractions are aligned, so '12.5' equals '12.50'.
29
+ */
30
+ export declare function decimalCompare(left: unknown, right: unknown): -1 | 0 | 1 | undefined;
26
31
  export declare function conditionsMatcher(conditions: Conditions, schemas?: readonly Pick<Resource, 'name' | 'fields'>[]): (record: RecordData) => boolean;
@@ -66,6 +66,22 @@ export function predicates(conditions = {}, fields) {
66
66
  export function likePattern(value) {
67
67
  return new RegExp(`^${[...value].map((c) => (c === '%' ? '[\\s\\S]*' : c === '_' ? '[\\s\\S]' : c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('')}$`, 'u');
68
68
  }
69
+ /**
70
+ * Compares two decimal strings by value (-1, 0, 1), or undefined when either is not a
71
+ * plain decimal string. Fractions are aligned, so '12.5' equals '12.50'.
72
+ */
73
+ export function decimalCompare(left, right) {
74
+ const pattern = /^(-?)(\d+)(?:\.(\d+))?$/;
75
+ const a = typeof left === 'string' ? pattern.exec(left) : null;
76
+ const b = typeof right === 'string' ? pattern.exec(right) : null;
77
+ if (!a || !b)
78
+ return undefined;
79
+ const digits = Math.max(a[3]?.length ?? 0, b[3]?.length ?? 0);
80
+ const scaled = (match) => BigInt(`${match[1]}${match[2]}${(match[3] ?? '').padEnd(digits, '0')}`);
81
+ const x = scaled(a);
82
+ const y = scaled(b);
83
+ return x < y ? -1 : x > y ? 1 : 0;
84
+ }
69
85
  // This matcher is used exclusively by CASL. SQL compilation shares the validated AST.
70
86
  export function conditionsMatcher(conditions, schemas = []) {
71
87
  const parts = predicates(conditions);
@@ -73,6 +89,9 @@ export function conditionsMatcher(conditions, schemas = []) {
73
89
  const actual = record[field] ?? null;
74
90
  const type = schemas.find((schema) => schema.name === record.__caslSubjectType__)?.fields[field]?.type;
75
91
  const compare = () => {
92
+ // Decimals compare by value like PostgreSQL numeric, never as text ('9.5' < '10').
93
+ if (type === 'decimal' || type === 'percent')
94
+ return decimalCompare(actual, value);
76
95
  if (type === 'money') {
77
96
  if (typeof actual !== 'string' ||
78
97
  typeof value !== 'string' ||
@@ -99,13 +118,17 @@ export function conditionsMatcher(conditions, schemas = []) {
99
118
  ? 1
100
119
  : 0;
101
120
  };
121
+ const decimal = type === 'decimal' || type === 'percent';
122
+ const same = (operand) => decimal && actual !== null && operand !== null
123
+ ? decimalCompare(actual, operand) === 0
124
+ : actual === operand;
102
125
  switch (operator) {
103
126
  case '$eq':
104
- return actual === value;
127
+ return same(value);
105
128
  case '$ne':
106
- return actual !== value;
129
+ return !same(value);
107
130
  case '$in':
108
- return value.includes(actual);
131
+ return value.some(same);
109
132
  case '$lt':
110
133
  return compare() === -1;
111
134
  case '$gt':
@@ -1,7 +1,7 @@
1
1
  import { abilitySchemas } from './ability.js';
2
2
  import { predicates, usesActor } from './conditions.js';
3
3
  import { columnName } from '../resource/define_resource.js';
4
- import { canonicalDate, canonicalMoney } from '../resource/values.js';
4
+ import { canonicalDate, canonicalDecimal, canonicalMoney, decimalShape, } from '../resource/values.js';
5
5
  export function conditionSql(conditions, resource) {
6
6
  const allowed = new Set([
7
7
  ...Object.keys(resource.fields),
@@ -21,7 +21,7 @@ export function conditionSql(conditions, resource) {
21
21
  const text = parts
22
22
  .map(({ field, operator, value }) => {
23
23
  const column = field === 'orgPath' ? 'ou.path' : `r.${resource.fields[field]?.column ?? columnName(field)}`;
24
- if (resource.fields[field]?.type === 'hasMany')
24
+ if (['hasMany', 'manyToMany', 'multiSelect'].includes(resource.fields[field]?.type ?? ''))
25
25
  throw new Error('Conditions on collections are unsupported');
26
26
  const type = resource.fields[field]?.type;
27
27
  if (type === 'json' || type === 'attachment')
@@ -42,6 +42,17 @@ export function conditionSql(conditions, resource) {
42
42
  throw new Error('Integer conditions require safe integers');
43
43
  if (type === 'money' && operand !== null && !canonicalMoney(operand))
44
44
  throw new Error('Money conditions require canonical integer strings');
45
+ if ((type === 'decimal' || type === 'percent') && operand !== null) {
46
+ const { precision, scale } = decimalShape(resource.fields[field]);
47
+ let canonical;
48
+ try {
49
+ canonical = canonicalDecimal(operand, precision, scale);
50
+ }
51
+ catch { }
52
+ // The stored form ("12.50"), so in-memory equality agrees with PostgreSQL.
53
+ if (canonical !== operand)
54
+ throw new Error(`Decimal conditions require canonical decimal strings with ${scale} decimals`);
55
+ }
45
56
  if ((type === 'date' || type === 'datetime') && operand !== null) {
46
57
  if (!canonicalDate(operand, type))
47
58
  throw new Error('Date conditions require a valid ISO date or canonical UTC timestamp');
@@ -86,12 +97,13 @@ export function authorizationSql(ability, action, resource, field) {
86
97
  const bindings = [];
87
98
  const branches = rules.map((rule) => {
88
99
  for (const predicate of predicates(rule.conditions)) {
89
- if (resource.fields[predicate.field]?.type === 'money' &&
100
+ if (['money', 'decimal', 'percent'].includes(resource.fields[predicate.field]?.type ?? '') &&
90
101
  ['$lt', '$gt'].includes(predicate.operator) &&
91
102
  !abilitySchemas
92
103
  .get(ability)
93
- ?.some((schema) => schema.name === resource.name && schema.fields[predicate.field]?.type === 'money'))
94
- throw new Error('Ordered money rules require buildAbility(rules, resourceSchemas)');
104
+ ?.some((schema) => schema.name === resource.name &&
105
+ schema.fields[predicate.field]?.type === resource.fields[predicate.field]?.type))
106
+ throw new Error('Ordered money and decimal rules require buildAbility(rules, resourceSchemas)');
95
107
  }
96
108
  const where = conditionSql(rule.conditions, resource);
97
109
  bindings.push(...where.bindings);
@@ -0,0 +1,96 @@
1
+ import type { Knex } from 'knex';
2
+ import type { SecretBox } from '../integrations/webhooks.js';
3
+ /** Two-factor state of one user as shown to the user or an administrator; never secrets. */
4
+ export type TwoFactorStatus = {
5
+ enabled: boolean;
6
+ /** Enrolment begun but not yet confirmed with a code. */
7
+ pending: boolean;
8
+ enabledAt: string | null;
9
+ /** Unused recovery codes; zero while disabled. */
10
+ recoveryRemaining: number;
11
+ };
12
+ /** What the authenticator application needs; returned once by `begin`. */
13
+ export type TwoFactorEnrolment = {
14
+ otpauthUrl: string;
15
+ /** Base32 secret for manual entry. */
16
+ secret: string;
17
+ issuer: string;
18
+ account: string;
19
+ };
20
+ /** How a second factor was proven, or false. */
21
+ export type TwoFactorResult = 'totp' | 'recovery' | false;
22
+ export type TwoFactorOptions = {
23
+ /** Clock in milliseconds; tests pass a fixed one. */
24
+ now?: () => number;
25
+ };
26
+ export type TwoFactorVerifyOptions = {
27
+ /** Accept a recovery code as well as a TOTP code (default true). */
28
+ allowRecovery?: boolean;
29
+ };
30
+ /** RFC 6238 parameters understood by every common authenticator application. */
31
+ export declare const TWO_FACTOR_PERIOD = 30;
32
+ export declare const TWO_FACTOR_DIGITS = 6;
33
+ export declare const TWO_FACTOR_WINDOW = 1;
34
+ export declare const RECOVERY_CODE_COUNT = 10;
35
+ /** Error code when the stored secret cannot be opened with the current encryption keys. */
36
+ export declare const TWO_FACTOR_UNREADABLE = "E_TWO_FACTOR_UNREADABLE";
37
+ /** Strips separators and maps look-alike characters the way Crockford base32 does. */
38
+ export declare function normalizeRecoveryCode(code: string): string;
39
+ /**
40
+ * TOTP two-factor authentication (RFC 6238: SHA-1, 6 digits, 30 s, ±1 step) with
41
+ * single-use recovery codes.
42
+ *
43
+ * - The shared secret is sealed at rest through the host's encryption service.
44
+ * - A time step is accepted at most once, and never one older than the last accepted
45
+ * one, under a row lock: an observed code cannot be replayed.
46
+ * - Recovery codes carry 100 bits of entropy, are stored as SHA-256 over a unique
47
+ * 16-byte salt and the normalised code, compared in constant time, and consumed
48
+ * atomically (`used_at is null` guard), so each works once.
49
+ *
50
+ * Hosts rate-limit and lock verification, require the password before disabling,
51
+ * and audit every change.
52
+ */
53
+ export declare class TwoFactor {
54
+ private db;
55
+ private secrets;
56
+ private issuer;
57
+ private now;
58
+ constructor(db: Knex, secrets: SecretBox, issuer: string, options?: TwoFactorOptions);
59
+ status(userId: number): Promise<TwoFactorStatus>;
60
+ isEnabled(userId: number): Promise<boolean>;
61
+ recoveryRemaining(userId: number, client?: Knex): Promise<number>;
62
+ /** Starts (or restarts) a pending enrolment with a fresh secret; refused while enabled. */
63
+ begin(userId: number, account: string): Promise<TwoFactorEnrolment>;
64
+ /** Confirms a pending enrolment with a current code; returns the recovery codes once. */
65
+ confirm(userId: number, code: unknown): Promise<string[]>;
66
+ /**
67
+ * Verifies a TOTP code, or consumes a recovery code when allowed. Returns how the
68
+ * factor was proven, or false for anything else (disabled, malformed, wrong, replayed).
69
+ */
70
+ verify(userId: number, code: unknown, options?: TwoFactorVerifyOptions): Promise<TwoFactorResult>;
71
+ /** Replaces every recovery code; callers verify a current code first. */
72
+ regenerateRecoveryCodes(userId: number): Promise<string[]>;
73
+ /**
74
+ * Removes the authenticator and every recovery code (self-service disable or an
75
+ * administrator's reset). Returns what was removed.
76
+ */
77
+ disable(userId: number): Promise<{
78
+ removed: boolean;
79
+ recoveryCodes: number;
80
+ }>;
81
+ /** Alias of `disable` for administrative resets. */
82
+ reset(userId: number): Promise<{
83
+ removed: boolean;
84
+ recoveryCodes: number;
85
+ }>;
86
+ private replaceRecoveryCodes;
87
+ private consumeRecoveryCode;
88
+ private totp;
89
+ /**
90
+ * A secret sealed under a key the host no longer holds (an APP_KEY rotated without
91
+ * keeping the old one) is a handled refusal, never a crash and never a match.
92
+ */
93
+ private open;
94
+ /** The absolute time step of a valid code within the window, or null. */
95
+ private match;
96
+ }