adula 2.1.0 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +149 -18
- package/build/agent/AGENTS.template.md +4 -4
- package/build/agent/capabilities.md +22 -12
- package/build/agent/skills/adula-frontend-design/SKILL.md +6 -4
- package/build/agent/skills/idea-review/SKILL.md +2 -2
- package/build/commands/adula_assistant_prune.d.ts +10 -0
- package/build/commands/adula_assistant_prune.js +12 -0
- package/build/commands/adula_outbox.d.ts +10 -0
- package/build/commands/adula_outbox.js +11 -0
- package/build/commands/adula_restore_reconcile.d.ts +10 -0
- package/build/commands/adula_restore_reconcile.js +34 -0
- package/build/commands/adula_runtime_health.d.ts +10 -0
- package/build/commands/adula_runtime_health.js +27 -0
- package/build/commands/adula_uploads_prune.d.ts +10 -0
- package/build/commands/adula_uploads_prune.js +16 -0
- package/build/commands/app.d.ts +10 -0
- package/build/commands/app.js +64 -0
- package/build/commands/backup_create.d.ts +11 -0
- package/build/commands/backup_create.js +99 -0
- package/build/commands/backup_open.d.ts +16 -0
- package/build/commands/backup_open.js +48 -0
- package/build/commands/backup_restore_files.d.ts +11 -0
- package/build/commands/backup_restore_files.js +44 -0
- package/build/commands/backup_restore_test.d.ts +12 -0
- package/build/commands/backup_restore_test.js +188 -0
- package/build/commands/backup_seal.d.ts +12 -0
- package/build/commands/backup_seal.js +36 -0
- package/build/commands/backup_services.d.ts +33 -0
- package/build/commands/backup_services.js +6 -0
- package/build/commands/backup_verify.d.ts +9 -0
- package/build/commands/backup_verify.js +59 -0
- package/build/commands/backup_verify_snapshot.d.ts +10 -0
- package/build/commands/backup_verify_snapshot.js +37 -0
- package/build/commands/client.d.ts +16 -0
- package/build/commands/client.js +71 -0
- package/build/commands/doctor.js +21 -1
- package/build/commands/install.d.ts +8 -0
- package/build/commands/install.js +69 -45
- package/build/commands/main.d.ts +3 -2
- package/build/commands/main.js +32 -0
- package/build/commands/module_add.js +4 -20
- package/build/commands/resource.d.ts +2 -0
- package/build/commands/resource.js +12 -3
- package/build/commands/resource_migration.d.ts +15 -0
- package/build/commands/resource_migration.js +81 -0
- package/build/commands/resource_snapshot.d.ts +2 -0
- package/build/commands/resource_snapshot.js +21 -4
- package/build/commands/sla_evaluate.d.ts +14 -0
- package/build/commands/sla_evaluate.js +16 -0
- package/build/commands/ui.js +4 -2
- package/build/commands/ui_css.d.ts +9 -0
- package/build/commands/ui_css.js +19 -0
- package/build/commands/upgrade.d.ts +1 -1
- package/build/commands/upgrade.js +1 -1
- package/build/configure.js +1 -1
- package/build/database/migrations/1770000000020_two_factor.d.ts +5 -0
- package/build/database/migrations/1770000000020_two_factor.js +10 -0
- package/build/database/migrations/1770000000041_import_modes.d.ts +5 -0
- package/build/database/migrations/1770000000041_import_modes.js +10 -0
- package/build/database/migrations/1770000000042_sync_jobs.d.ts +5 -0
- package/build/database/migrations/1770000000042_sync_jobs.js +10 -0
- package/build/database/migrations/1770000000043_notification_channels.d.ts +5 -0
- package/build/database/migrations/1770000000043_notification_channels.js +10 -0
- package/build/database/migrations/1770000000044_channel_confirmations.d.ts +5 -0
- package/build/database/migrations/1770000000044_channel_confirmations.js +10 -0
- package/build/database/migrations/1770000000045_import_leases.d.ts +5 -0
- package/build/database/migrations/1770000000045_import_leases.js +10 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.d.ts +5 -0
- package/build/database/migrations/1770000000046_workflow_delegation_sla.js +10 -0
- package/build/database/migrations/1770000000049_print_templates.d.ts +5 -0
- package/build/database/migrations/1770000000049_print_templates.js +10 -0
- package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
- package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
- package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
- package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
- package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
- package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
- package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
- package/build/database/migrations/1770000000056_appearance.js +10 -0
- package/build/index.d.ts +87 -11
- package/build/index.js +50 -7
- package/build/providers/adula_provider.d.ts +2 -0
- package/build/providers/adula_provider.js +7 -0
- package/build/src/admin/contracts.js +1 -1
- package/build/src/admin/controller.d.ts +14 -1
- package/build/src/admin/controller.js +91 -13
- package/build/src/admin/errors.d.ts +32 -0
- package/build/src/admin/errors.js +63 -1
- package/build/src/admin/presentation.d.ts +21 -2
- package/build/src/admin/resource/editor.d.ts +60 -0
- package/build/src/admin/resource/editor.js +345 -0
- package/build/src/admin/resource/export.d.ts +54 -0
- package/build/src/admin/resource/export.js +262 -0
- package/build/src/admin/resource/lifecycle.d.ts +23 -0
- package/build/src/admin/resource/lifecycle.js +91 -0
- package/build/src/admin/resource/query.d.ts +111 -0
- package/build/src/admin/resource/query.js +595 -0
- package/build/src/admin/resource/read.d.ts +109 -0
- package/build/src/admin/resource/read.js +388 -0
- package/build/src/admin/resource/shared.d.ts +93 -0
- package/build/src/admin/resource/shared.js +265 -0
- package/build/src/admin/resource/trash.d.ts +10 -0
- package/build/src/admin/resource/trash.js +56 -0
- package/build/src/admin/resource/write.d.ts +57 -0
- package/build/src/admin/resource/write.js +603 -0
- package/build/src/admin/resource_service.d.ts +80 -193
- package/build/src/admin/resource_service.js +81 -1343
- package/build/src/admin/resource_tools.d.ts +111 -0
- package/build/src/admin/resource_tools.js +139 -0
- package/build/src/ai/assistant.d.ts +100 -0
- package/build/src/ai/assistant.js +487 -0
- package/build/src/ai/client.d.ts +49 -0
- package/build/src/ai/client.js +85 -0
- package/build/src/ai/prompt.d.ts +23 -0
- package/build/src/ai/prompt.js +83 -0
- package/build/src/ai/settings.d.ts +56 -0
- package/build/src/ai/settings.js +214 -0
- package/build/src/ai/usage.d.ts +16 -0
- package/build/src/ai/usage.js +33 -0
- package/build/src/appearance/appearance.d.ts +134 -0
- package/build/src/appearance/appearance.js +461 -0
- package/build/src/appearance/colors.d.ts +43 -0
- package/build/src/appearance/colors.js +99 -0
- package/build/src/appearance/logo.d.ts +32 -0
- package/build/src/appearance/logo.js +112 -0
- package/build/src/attachments/attachment_service.d.ts +46 -2
- package/build/src/attachments/attachment_service.js +96 -4
- package/build/src/auth/actor_store.d.ts +5 -1
- package/build/src/auth/actor_store.js +8 -4
- package/build/src/auth/conditions.d.ts +5 -0
- package/build/src/auth/conditions.js +26 -3
- package/build/src/auth/sql.js +17 -5
- package/build/src/auth/two_factor.d.ts +96 -0
- package/build/src/auth/two_factor.js +259 -0
- package/build/src/backups/archive.d.ts +52 -0
- package/build/src/backups/archive.js +362 -0
- package/build/src/backups/cloud_backups.d.ts +133 -0
- package/build/src/backups/cloud_backups.js +650 -0
- package/build/src/backups/doctor.d.ts +7 -0
- package/build/src/backups/doctor.js +55 -0
- package/build/src/backups/providers.d.ts +81 -0
- package/build/src/backups/providers.js +470 -0
- package/build/src/collaboration/assignments.d.ts +59 -2
- package/build/src/collaboration/assignments.js +196 -74
- package/build/src/collaboration/record_collaboration.d.ts +21 -4
- package/build/src/collaboration/record_collaboration.js +126 -51
- package/build/src/collaboration/shared.d.ts +24 -0
- package/build/src/collaboration/shared.js +34 -0
- package/build/src/commands/app_scaffold.d.ts +72 -0
- package/build/src/commands/app_scaffold.js +285 -0
- package/build/src/commands/capabilities.js +35 -9
- package/build/src/commands/doctor.d.ts +24 -2
- package/build/src/commands/doctor.js +81 -6
- package/build/src/commands/gap_report.d.ts +1 -1
- package/build/src/commands/gap_report.js +2 -2
- package/build/src/commands/generator.d.ts +37 -1
- package/build/src/commands/generator.js +61 -18
- package/build/src/commands/snapshot.d.ts +24 -13
- package/build/src/commands/snapshot.js +54 -14
- package/build/src/commands/source_markers.d.ts +10 -0
- package/build/src/commands/source_markers.js +29 -0
- package/build/src/core/activity.d.ts +2 -0
- package/build/src/core/activity.js +7 -1
- package/build/src/core/administrators.d.ts +38 -0
- package/build/src/core/administrators.js +145 -0
- package/build/src/core/avatar_image.d.ts +33 -0
- package/build/src/core/avatar_image.js +278 -0
- package/build/src/core/html_sanitizer.d.ts +20 -0
- package/build/src/core/html_sanitizer.js +261 -0
- package/build/src/core/like.d.ts +5 -0
- package/build/src/core/like.js +5 -0
- package/build/src/core/lookups.d.ts +80 -0
- package/build/src/core/lookups.js +319 -0
- package/build/src/core/mail_settings.d.ts +83 -0
- package/build/src/core/mail_settings.js +274 -0
- package/build/src/core/mail_test.d.ts +16 -0
- package/build/src/core/mail_test.js +81 -6
- package/build/src/core/message_templates.d.ts +15 -2
- package/build/src/core/message_templates.js +81 -11
- package/build/src/core/module_seed.js +2 -1
- package/build/src/core/notification_channels.d.ts +235 -0
- package/build/src/core/notification_channels.js +660 -0
- package/build/src/core/roles.js +26 -9
- package/build/src/core/saved_views.d.ts +8 -1
- package/build/src/core/saved_views.js +91 -26
- package/build/src/core/sequences.d.ts +32 -0
- package/build/src/core/sequences.js +97 -0
- package/build/src/core/settings.d.ts +5 -0
- package/build/src/core/settings.js +31 -3
- package/build/src/core/template_language.d.ts +61 -0
- package/build/src/core/template_language.js +141 -0
- package/build/src/core/ui_preferences.d.ts +10 -0
- package/build/src/core/ui_preferences.js +15 -1
- package/build/src/core/user_avatars.d.ts +79 -0
- package/build/src/core/user_avatars.js +186 -0
- package/build/src/core/user_invitations.d.ts +5 -1
- package/build/src/core/user_invitations.js +7 -1
- package/build/src/core/user_preferences.d.ts +36 -0
- package/build/src/core/user_preferences.js +125 -0
- package/build/src/core/users.d.ts +2 -0
- package/build/src/core/users.js +5 -3
- package/build/src/database/calendar_days.d.ts +19 -0
- package/build/src/database/calendar_days.js +36 -0
- package/build/src/database/schema.d.ts +201 -2
- package/build/src/database/schema.js +713 -59
- package/build/src/database/schema_diff.d.ts +70 -0
- package/build/src/database/schema_diff.js +190 -0
- package/build/src/events/record_mutation.d.ts +2 -1
- package/build/src/events/record_mutation.js +1 -0
- package/build/src/integrations/api_client.d.ts +37 -0
- package/build/src/integrations/api_client.js +567 -0
- package/build/src/integrations/import_adapters.d.ts +37 -0
- package/build/src/integrations/import_adapters.js +35 -0
- package/build/src/integrations/imports.d.ts +130 -16
- package/build/src/integrations/imports.js +434 -73
- package/build/src/integrations/openapi.d.ts +3 -1
- package/build/src/integrations/openapi.js +465 -31
- package/build/src/integrations/outbound.d.ts +94 -0
- package/build/src/integrations/outbound.js +276 -0
- package/build/src/integrations/print.d.ts +22 -1
- package/build/src/integrations/print.js +68 -22
- package/build/src/integrations/print_templates.d.ts +216 -0
- package/build/src/integrations/print_templates.js +1017 -0
- package/build/src/integrations/sync_jobs.d.ts +139 -0
- package/build/src/integrations/sync_jobs.js +416 -0
- package/build/src/integrations/webhooks.d.ts +12 -12
- package/build/src/integrations/webhooks.js +34 -43
- package/build/src/integrations/xlsx.d.ts +41 -0
- package/build/src/integrations/xlsx.js +519 -0
- package/build/src/languages/ar.d.ts +11 -0
- package/build/src/languages/ar.js +358 -0
- package/build/src/languages/ar_ui.d.ts +461 -0
- package/build/src/languages/ar_ui.js +464 -0
- package/build/src/languages/catalog.d.ts +66 -0
- package/build/src/languages/catalog.js +152 -0
- package/build/src/languages/en.d.ts +7 -0
- package/build/src/languages/en.js +352 -0
- package/build/src/languages/en_ui.d.ts +3 -0
- package/build/src/languages/en_ui.js +458 -0
- package/build/src/languages/validation.d.ts +26 -0
- package/build/src/languages/validation.js +60 -0
- package/build/src/lists/bulk_actions.d.ts +89 -0
- package/build/src/lists/bulk_actions.js +268 -0
- package/build/src/lists/dashboards.d.ts +138 -0
- package/build/src/lists/dashboards.js +290 -0
- package/build/src/mcp/tools.js +9 -104
- package/build/src/resource/define_resource.d.ts +18 -1
- package/build/src/resource/define_resource.js +212 -18
- package/build/src/resource/definition.d.ts +44 -0
- package/build/src/resource/definition.js +171 -0
- package/build/src/resource/registry.js +15 -4
- package/build/src/resource/types.d.ts +313 -16
- package/build/src/resource/values.d.ts +56 -1
- package/build/src/resource/values.js +237 -5
- package/build/src/services/settings.d.ts +2 -0
- package/build/src/services/settings.js +5 -1
- package/build/src/upgrade/legacy.js +2 -2
- package/build/src/workflows/calendar.d.ts +9 -0
- package/build/src/workflows/calendar.js +44 -0
- package/build/src/workflows/define_workflow.d.ts +48 -3
- package/build/src/workflows/define_workflow.js +57 -13
- package/build/src/workflows/delegations.d.ts +107 -0
- package/build/src/workflows/delegations.js +326 -0
- package/build/src/workflows/engine.d.ts +80 -4
- package/build/src/workflows/engine.js +466 -86
- package/build/src/workflows/sla.d.ts +15 -0
- package/build/src/workflows/sla.js +8 -0
- package/build/stubs/resource_contract.txt +12 -1
- package/package.json +9 -2
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { AdulaError } from '../admin/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Logos (ADR 053) are untrusted bytes shown on public pages. Only PNG, JPEG and still WebP
|
|
4
|
+
* are accepted, recognised by their first bytes; SVG is refused because it can carry script.
|
|
5
|
+
* libvips decodes one frame within a pixel budget and re-encodes it in the same format,
|
|
6
|
+
* fitted inside 1024×512 without enlarging, so the stored file carries no metadata and no
|
|
7
|
+
* payload hidden in the original. The result is checked again before it is stored.
|
|
8
|
+
*/
|
|
9
|
+
export const LOGO_LIMITS = Object.freeze({
|
|
10
|
+
maxBytes: 1024 * 1024,
|
|
11
|
+
maxInputSide: 4096,
|
|
12
|
+
maxWidth: 1024,
|
|
13
|
+
maxHeight: 512,
|
|
14
|
+
minSide: 16,
|
|
15
|
+
});
|
|
16
|
+
const TYPE_MESSAGE = 'الشعار يجب أن يكون صورة PNG أو JPEG أو WebP';
|
|
17
|
+
const wrongType = () => new AdulaError(422, 'E_LOGO_TYPE', TYPE_MESSAGE);
|
|
18
|
+
const corrupt = () => new AdulaError(422, 'E_LOGO_CORRUPT', 'ملف الشعار تالف أو غير مكتمل');
|
|
19
|
+
const MIME = {
|
|
20
|
+
png: 'image/png',
|
|
21
|
+
jpeg: 'image/jpeg',
|
|
22
|
+
webp: 'image/webp',
|
|
23
|
+
};
|
|
24
|
+
const EXTNAME = { png: 'png', jpeg: 'jpg', webp: 'webp' };
|
|
25
|
+
/** The format named by the file's first bytes; the name and declared type are never trusted. */
|
|
26
|
+
export function detectLogoType(bytes) {
|
|
27
|
+
const b = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
28
|
+
if (b.length >= 8 &&
|
|
29
|
+
b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 13, 10, 26, 10])))
|
|
30
|
+
return 'png';
|
|
31
|
+
if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)
|
|
32
|
+
return 'jpeg';
|
|
33
|
+
if (b.length >= 12 &&
|
|
34
|
+
b.subarray(0, 4).toString('latin1') === 'RIFF' &&
|
|
35
|
+
b.subarray(8, 12).toString('latin1') === 'WEBP')
|
|
36
|
+
return 'webp';
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
/** The headers a stored logo is served with: its allow-listed type, no sniffing, no script. */
|
|
40
|
+
export function logoHeaders(logo) {
|
|
41
|
+
const type = Object.values(MIME).includes(logo.mimeType)
|
|
42
|
+
? logo.mimeType
|
|
43
|
+
: 'application/octet-stream';
|
|
44
|
+
return {
|
|
45
|
+
'Content-Type': type,
|
|
46
|
+
'Content-Length': String(logo.size),
|
|
47
|
+
'Content-Disposition': 'inline',
|
|
48
|
+
'X-Content-Type-Options': 'nosniff',
|
|
49
|
+
'Content-Security-Policy': "default-src 'none'; sandbox",
|
|
50
|
+
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
51
|
+
'ETag': `"logo-${logo.id}"`,
|
|
52
|
+
// A logo id never changes its bytes, but whether it is public does (an occasion ends,
|
|
53
|
+
// a logo is replaced), so caches keep it briefly and then revalidate with the ETag.
|
|
54
|
+
'Cache-Control': 'public, max-age=300, must-revalidate',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
export async function prepareLogoImage(input) {
|
|
58
|
+
if (input.byteLength > LOGO_LIMITS.maxBytes)
|
|
59
|
+
throw new AdulaError(422, 'E_LOGO_SIZE', 'حجم الشعار يتجاوز 1 ميغابايت');
|
|
60
|
+
const type = detectLogoType(input);
|
|
61
|
+
if (!type)
|
|
62
|
+
throw wrongType();
|
|
63
|
+
const { default: sharp } = await import('sharp');
|
|
64
|
+
const options = {
|
|
65
|
+
limitInputPixels: LOGO_LIMITS.maxInputSide * LOGO_LIMITS.maxInputSide,
|
|
66
|
+
animated: false,
|
|
67
|
+
failOn: 'error',
|
|
68
|
+
};
|
|
69
|
+
let bytes;
|
|
70
|
+
try {
|
|
71
|
+
const source = sharp(Buffer.from(input), options);
|
|
72
|
+
const metadata = await source.metadata();
|
|
73
|
+
// The decoder must agree with the first bytes, and a logo is one still frame.
|
|
74
|
+
if (metadata.format !== type)
|
|
75
|
+
throw wrongType();
|
|
76
|
+
if ((metadata.pages ?? 1) !== 1)
|
|
77
|
+
throw new AdulaError(422, 'E_LOGO_TYPE', 'الشعار يجب أن يكون صورة ثابتة');
|
|
78
|
+
const fitted = source.rotate().resize({
|
|
79
|
+
width: LOGO_LIMITS.maxWidth,
|
|
80
|
+
height: LOGO_LIMITS.maxHeight,
|
|
81
|
+
fit: 'inside',
|
|
82
|
+
withoutEnlargement: true,
|
|
83
|
+
});
|
|
84
|
+
bytes =
|
|
85
|
+
type === 'png'
|
|
86
|
+
? await fitted.png({ compressionLevel: 9, adaptiveFiltering: true }).toBuffer()
|
|
87
|
+
: type === 'jpeg'
|
|
88
|
+
? await fitted.jpeg({ quality: 90, mozjpeg: true }).toBuffer()
|
|
89
|
+
: await fitted.webp({ quality: 90, effort: 4 }).toBuffer();
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error instanceof AdulaError)
|
|
93
|
+
throw error;
|
|
94
|
+
throw corrupt();
|
|
95
|
+
}
|
|
96
|
+
const again = await sharp(bytes, options)
|
|
97
|
+
.metadata()
|
|
98
|
+
.catch(() => {
|
|
99
|
+
throw corrupt();
|
|
100
|
+
});
|
|
101
|
+
const width = again.width ?? 0;
|
|
102
|
+
const height = again.height ?? 0;
|
|
103
|
+
if (detectLogoType(bytes) !== type ||
|
|
104
|
+
width < LOGO_LIMITS.minSide ||
|
|
105
|
+
height < LOGO_LIMITS.minSide ||
|
|
106
|
+
width > LOGO_LIMITS.maxWidth ||
|
|
107
|
+
height > LOGO_LIMITS.maxHeight)
|
|
108
|
+
throw new AdulaError(422, 'E_LOGO_DIMENSIONS', 'أبعاد الشعار يجب ألا تقل عن 16 بكسل');
|
|
109
|
+
if (bytes.length > LOGO_LIMITS.maxBytes)
|
|
110
|
+
throw new AdulaError(422, 'E_LOGO_SIZE', 'حجم الشعار يتجاوز 1 ميغابايت');
|
|
111
|
+
return { type, mimeType: MIME[type], extname: EXTNAME[type], width, height, bytes };
|
|
112
|
+
}
|
|
@@ -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
|
|
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))
|
|
@@ -10,5 +10,9 @@ export declare class ActorStore {
|
|
|
10
10
|
private registry;
|
|
11
11
|
private cache?;
|
|
12
12
|
constructor(db: Knex, registry: ResourceRegistry, cache?: ActorCache | undefined);
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Loads a user's actor. A caller holding a transaction passes it as `db`, so the load
|
|
15
|
+
* never waits for a second pool connection while that transaction holds one.
|
|
16
|
+
*/
|
|
17
|
+
load(id: number, db?: Knex): Promise<Actor>;
|
|
14
18
|
}
|
|
@@ -8,18 +8,22 @@ export class ActorStore {
|
|
|
8
8
|
this.registry = registry;
|
|
9
9
|
this.cache = cache;
|
|
10
10
|
}
|
|
11
|
-
|
|
11
|
+
/**
|
|
12
|
+
* Loads a user's actor. A caller holding a transaction passes it as `db`, so the load
|
|
13
|
+
* never waits for a second pool connection while that transaction holds one.
|
|
14
|
+
*/
|
|
15
|
+
async load(id, db = this.db) {
|
|
12
16
|
// Revision is read on every request; DB triggers invalidate across workers and tree moves.
|
|
13
|
-
const { version } = await
|
|
17
|
+
const { version } = await db('authorization_revision').where({ id: 1 }).first('version');
|
|
14
18
|
const key = `ability:${id}:${version}`;
|
|
15
19
|
const cached = await this.cache?.get(key);
|
|
16
20
|
if (cached)
|
|
17
21
|
return cached;
|
|
18
|
-
const memberships = await
|
|
22
|
+
const memberships = await db('user_org_units as u')
|
|
19
23
|
.join('org_units as o', 'o.id', 'u.org_unit_id')
|
|
20
24
|
.where('u.user_id', id)
|
|
21
25
|
.select('o.path');
|
|
22
|
-
const assignments = await
|
|
26
|
+
const assignments = await db('user_roles as ur')
|
|
23
27
|
.join('roles as r', 'r.id', 'ur.role_id')
|
|
24
28
|
.leftJoin('org_units as o', 'o.id', 'ur.org_unit_id')
|
|
25
29
|
.join('role_rules as rr', 'rr.role_id', 'r.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
|
|
127
|
+
return same(value);
|
|
105
128
|
case '$ne':
|
|
106
|
-
return
|
|
129
|
+
return !same(value);
|
|
107
130
|
case '$in':
|
|
108
|
-
return value.
|
|
131
|
+
return value.some(same);
|
|
109
132
|
case '$lt':
|
|
110
133
|
return compare() === -1;
|
|
111
134
|
case '$gt':
|
package/build/src/auth/sql.js
CHANGED
|
@@ -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
|
|
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
|
|
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 &&
|
|
94
|
-
|
|
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
|
+
}
|