adula 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +1 -1
  2. package/build/agent/capabilities.md +2 -3
  3. package/build/agent/skills/adula-frontend-design/SKILL.md +5 -3
  4. package/build/commands/adula_assistant_prune.d.ts +10 -0
  5. package/build/commands/adula_assistant_prune.js +12 -0
  6. package/build/commands/backup_open.d.ts +16 -0
  7. package/build/commands/backup_open.js +48 -0
  8. package/build/commands/backup_restore_test.js +3 -0
  9. package/build/commands/backup_seal.d.ts +12 -0
  10. package/build/commands/backup_seal.js +36 -0
  11. package/build/commands/backup_services.d.ts +3 -1
  12. package/build/commands/doctor.js +18 -1
  13. package/build/commands/install.js +6 -0
  14. package/build/commands/main.d.ts +2 -2
  15. package/build/commands/main.js +6 -0
  16. package/build/commands/resource_migration.js +12 -3
  17. package/build/commands/resource_snapshot.js +18 -4
  18. package/build/database/migrations/1770000000051_comment_notifications.d.ts +5 -0
  19. package/build/database/migrations/1770000000051_comment_notifications.js +10 -0
  20. package/build/database/migrations/1770000000054_cloud_backups.d.ts +5 -0
  21. package/build/database/migrations/1770000000054_cloud_backups.js +10 -0
  22. package/build/database/migrations/1770000000055_ai_assistant.d.ts +5 -0
  23. package/build/database/migrations/1770000000055_ai_assistant.js +10 -0
  24. package/build/database/migrations/1770000000056_appearance.d.ts +5 -0
  25. package/build/database/migrations/1770000000056_appearance.js +10 -0
  26. package/build/index.d.ts +36 -6
  27. package/build/index.js +18 -3
  28. package/build/src/admin/controller.js +18 -4
  29. package/build/src/admin/resource/editor.d.ts +1 -0
  30. package/build/src/admin/resource/editor.js +26 -4
  31. package/build/src/admin/resource/export.d.ts +21 -4
  32. package/build/src/admin/resource/export.js +117 -36
  33. package/build/src/admin/resource/lifecycle.d.ts +2 -0
  34. package/build/src/admin/resource/query.d.ts +14 -3
  35. package/build/src/admin/resource/query.js +98 -11
  36. package/build/src/admin/resource/read.d.ts +3 -0
  37. package/build/src/admin/resource/read.js +75 -14
  38. package/build/src/admin/resource/shared.d.ts +16 -0
  39. package/build/src/admin/resource/shared.js +47 -4
  40. package/build/src/admin/resource/write.js +37 -8
  41. package/build/src/admin/resource_service.d.ts +17 -3
  42. package/build/src/admin/resource_service.js +16 -2
  43. package/build/src/admin/resource_tools.d.ts +111 -0
  44. package/build/src/admin/resource_tools.js +139 -0
  45. package/build/src/ai/assistant.d.ts +100 -0
  46. package/build/src/ai/assistant.js +487 -0
  47. package/build/src/ai/client.d.ts +49 -0
  48. package/build/src/ai/client.js +85 -0
  49. package/build/src/ai/prompt.d.ts +23 -0
  50. package/build/src/ai/prompt.js +83 -0
  51. package/build/src/ai/settings.d.ts +56 -0
  52. package/build/src/ai/settings.js +214 -0
  53. package/build/src/ai/usage.d.ts +16 -0
  54. package/build/src/ai/usage.js +33 -0
  55. package/build/src/appearance/appearance.d.ts +134 -0
  56. package/build/src/appearance/appearance.js +461 -0
  57. package/build/src/appearance/colors.d.ts +43 -0
  58. package/build/src/appearance/colors.js +99 -0
  59. package/build/src/appearance/logo.d.ts +32 -0
  60. package/build/src/appearance/logo.js +112 -0
  61. package/build/src/auth/actor_store.d.ts +5 -1
  62. package/build/src/auth/actor_store.js +8 -4
  63. package/build/src/backups/archive.d.ts +52 -0
  64. package/build/src/backups/archive.js +362 -0
  65. package/build/src/backups/cloud_backups.d.ts +133 -0
  66. package/build/src/backups/cloud_backups.js +650 -0
  67. package/build/src/backups/doctor.d.ts +7 -0
  68. package/build/src/backups/doctor.js +55 -0
  69. package/build/src/backups/providers.d.ts +81 -0
  70. package/build/src/backups/providers.js +470 -0
  71. package/build/src/collaboration/assignments.d.ts +24 -2
  72. package/build/src/collaboration/assignments.js +88 -32
  73. package/build/src/collaboration/record_collaboration.d.ts +19 -1
  74. package/build/src/collaboration/record_collaboration.js +109 -37
  75. package/build/src/collaboration/shared.d.ts +10 -2
  76. package/build/src/collaboration/shared.js +14 -1
  77. package/build/src/commands/capabilities.js +1 -1
  78. package/build/src/commands/doctor.d.ts +10 -0
  79. package/build/src/commands/doctor.js +31 -1
  80. package/build/src/commands/snapshot.d.ts +14 -0
  81. package/build/src/commands/snapshot.js +23 -0
  82. package/build/src/core/administrators.js +19 -3
  83. package/build/src/core/avatar_image.d.ts +33 -0
  84. package/build/src/core/avatar_image.js +278 -0
  85. package/build/src/core/mail_settings.d.ts +83 -0
  86. package/build/src/core/mail_settings.js +274 -0
  87. package/build/src/core/mail_test.d.ts +16 -0
  88. package/build/src/core/mail_test.js +81 -6
  89. package/build/src/core/message_templates.d.ts +8 -0
  90. package/build/src/core/message_templates.js +12 -3
  91. package/build/src/core/roles.js +24 -7
  92. package/build/src/core/saved_views.js +55 -24
  93. package/build/src/core/settings.d.ts +2 -2
  94. package/build/src/core/settings.js +15 -4
  95. package/build/src/core/ui_preferences.d.ts +6 -0
  96. package/build/src/core/ui_preferences.js +12 -1
  97. package/build/src/core/user_avatars.d.ts +79 -0
  98. package/build/src/core/user_avatars.js +186 -0
  99. package/build/src/core/user_preferences.d.ts +36 -0
  100. package/build/src/core/user_preferences.js +125 -0
  101. package/build/src/core/users.d.ts +2 -0
  102. package/build/src/core/users.js +4 -2
  103. package/build/src/database/schema.d.ts +46 -0
  104. package/build/src/database/schema.js +182 -0
  105. package/build/src/database/schema_diff.d.ts +16 -2
  106. package/build/src/database/schema_diff.js +40 -7
  107. package/build/src/integrations/api_client.js +18 -3
  108. package/build/src/integrations/imports.d.ts +16 -4
  109. package/build/src/integrations/imports.js +36 -8
  110. package/build/src/integrations/openapi.js +15 -4
  111. package/build/src/integrations/outbound.d.ts +43 -0
  112. package/build/src/integrations/outbound.js +98 -17
  113. package/build/src/integrations/print.d.ts +2 -1
  114. package/build/src/integrations/print.js +7 -3
  115. package/build/src/integrations/print_templates.js +3 -1
  116. package/build/src/integrations/xlsx.d.ts +41 -0
  117. package/build/src/integrations/xlsx.js +519 -0
  118. package/build/src/languages/ar.js +22 -0
  119. package/build/src/languages/ar_ui.d.ts +143 -14
  120. package/build/src/languages/ar_ui.js +145 -14
  121. package/build/src/languages/en.js +22 -0
  122. package/build/src/languages/en_ui.js +144 -14
  123. package/build/src/lists/dashboards.d.ts +42 -0
  124. package/build/src/lists/dashboards.js +49 -0
  125. package/build/src/mcp/tools.js +9 -104
  126. package/build/src/resource/define_resource.js +7 -0
  127. package/build/src/resource/types.d.ts +9 -0
  128. package/build/src/workflows/delegations.d.ts +15 -1
  129. package/build/src/workflows/delegations.js +49 -10
  130. package/build/src/workflows/engine.d.ts +11 -0
  131. package/build/src/workflows/engine.js +29 -7
  132. package/package.json +5 -1
@@ -330,7 +330,7 @@ export function diagnoseResourceSnapshots(pending, resource) {
330
330
  check: 'resources.snapshots',
331
331
  status: drift.length ? 'warn' : 'pass',
332
332
  message: drift.length
333
- ? `Pending create-migrations differ from their resource definitions; run node ace adula:resource:snapshot <name> (or update the embedded definition) before migration:run: ${drift.join(' | ')}`
333
+ ? `Pending create-migrations differ from their resource definitions; run node ace adula:resource:snapshot <name> (or update the embedded definition) before migration:run; a relation to a table created by a later migration is refused, add it afterwards with node ace adula:resource:migration <name>: ${drift.join(' | ')}`
334
334
  : 'Pending resource migrations match their definitions',
335
335
  };
336
336
  }
@@ -377,6 +377,36 @@ export function diagnoseWorkflowRoles(workflows, roles) {
377
377
  : 'Every role addressed by a workflow step exists',
378
378
  };
379
379
  }
380
+ /**
381
+ * A child declared with `scope: { from }` takes its unit from its parent, so creating or
382
+ * updating it needs `view` on the parent (ADR 029). List roles that may write such a child
383
+ * but have no rule that lets them view the parent: every create and update refuses them (#140).
384
+ */
385
+ export function diagnoseScopeParentRoles(resources, roles) {
386
+ const grants = (rules, subject, wanted) => rules.some((rule) => {
387
+ const actions = Array.isArray(rule.action) ? rule.action : [rule.action];
388
+ return (!rule.inverted &&
389
+ (rule.subject === subject || rule.subject === 'all') &&
390
+ actions.some((action) => action === 'manage' || wanted.includes(action)));
391
+ });
392
+ const problems = [];
393
+ for (const child of resources) {
394
+ const field = child.scope ? child.fields[child.scope.from] : undefined;
395
+ if (!child.scope || field?.type !== 'belongsTo')
396
+ continue;
397
+ for (const role of roles)
398
+ if (grants(role.rules, child.name, ['create', 'update']) &&
399
+ !grants(role.rules, field.resource, ['view']))
400
+ problems.push(`role "${role.name}": create/update on ${child.name} needs view on ${field.resource} (scope.from ${child.scope.from})`);
401
+ }
402
+ return {
403
+ check: 'roles.scope_parents',
404
+ status: problems.length ? 'warn' : 'pass',
405
+ message: problems.length
406
+ ? `Roles may write scope-inheriting records without viewing their parent; those creates and updates are refused: ${problems.join(', ')}`
407
+ : 'Every role that writes a scope-inheriting record may view its parent',
408
+ };
409
+ }
380
410
  /** Events wait in the outbox until a worker publishes them; a stale backlog means none runs (#50). */
381
411
  export function diagnoseOutbox(health) {
382
412
  const { backlog, oldestAgeMs } = health.outbox;
@@ -19,6 +19,20 @@ export declare function resourceSnapshot(resource: Pick<Resource, 'name' | 'scop
19
19
  name: string;
20
20
  scoped: boolean;
21
21
  };
22
+ /**
23
+ * The relations of a snapshot whose target table is created by a generated
24
+ * create-migration that runs after `file` (the migration runner's order): their foreign
25
+ * keys would fail on a fresh database (#99). Targets without a generated create-migration
26
+ * (core tables, hand-written ones), earlier ones and self-references are fine.
27
+ */
28
+ export declare function laterRelationTargets(snapshot: ReturnType<typeof resourceSnapshot>, file: string, migrations: readonly {
29
+ name: string;
30
+ resource?: string;
31
+ }[]): {
32
+ field: string;
33
+ target: string;
34
+ migration: string;
35
+ }[];
22
36
  /** The resource name embedded in a generated create-migration, if the source is one. */
23
37
  export declare function embeddedResource(source: string): string | undefined;
24
38
  /** Replaces the embedded definition of a generated create-migration (#20). */
@@ -10,6 +10,8 @@ export function fieldSnapshot(field) {
10
10
  type: field.type,
11
11
  label: field.label,
12
12
  ...('resource' in field && field.type !== 'hasMany' ? { resource: field.resource } : {}),
13
+ // Required by the lookup Field type: without it the generated migration fails tsc (#98).
14
+ ...(field.type === 'lookup' ? { group: field.group } : {}),
13
15
  ...(field.type === 'manyToMany' && field.table ? { table: field.table } : {}),
14
16
  ...(field.column ? { column: field.column } : {}),
15
17
  ...(field.required ? { required: true } : {}),
@@ -44,6 +46,27 @@ export function resourceSnapshot(resource) {
44
46
  .map(([key, field]) => [key, fieldSnapshot(field)])),
45
47
  };
46
48
  }
49
+ /**
50
+ * The relations of a snapshot whose target table is created by a generated
51
+ * create-migration that runs after `file` (the migration runner's order): their foreign
52
+ * keys would fail on a fresh database (#99). Targets without a generated create-migration
53
+ * (core tables, hand-written ones), earlier ones and self-references are fine.
54
+ */
55
+ export function laterRelationTargets(snapshot, file, migrations) {
56
+ const position = migrations.findIndex((migration) => migration.name === file);
57
+ const later = [];
58
+ for (const [key, field] of Object.entries(snapshot.fields)) {
59
+ if ((field.type !== 'belongsTo' && field.type !== 'manyToMany') || !('resource' in field))
60
+ continue;
61
+ const target = field.resource;
62
+ if (target === snapshot.name)
63
+ continue;
64
+ const index = migrations.findIndex((migration) => migration.resource === target);
65
+ if (index > position)
66
+ later.push({ field: key, target, migration: migrations[index].name });
67
+ }
68
+ return later;
69
+ }
47
70
  /** The resource name embedded in a generated create-migration, if the source is one. */
48
71
  export function embeddedResource(source) {
49
72
  const embedded = EMBEDDED.exec(source)?.[2];
@@ -81,6 +81,8 @@ export async function resolveInstallAdministrator(knex, email, create, options =
81
81
  throw new Error('Administrator user does not exist. An administrator already exists, so adula:install only creates the first one; check the e-mail address.');
82
82
  return { id: await create(), created: true };
83
83
  }
84
+ /** The name a new installation gives the bootstrap role; its key stays `administrator`. */
85
+ const BOOTSTRAP_ROLE_NAME = 'مدير النظام';
84
86
  /**
85
87
  * Idempotently installs the root unit, the bootstrap `administrator` role with its
86
88
  * `manage all` grant, and assigns it to the user. A transaction-scoped advisory
@@ -99,14 +101,28 @@ export async function grantInstallAdministrator(knex, userId, version) {
99
101
  .update({ path: String(created.id) });
100
102
  root = created;
101
103
  }
102
- let role = await trx('roles').where('name', 'administrator').first();
104
+ // The bootstrap role is found by its fixed key, so administrators may rename it; a role
105
+ // installed before keys existed is found by its original name and keyed once.
106
+ let role = (await trx('roles').where('key', 'administrator').first()) ??
107
+ (await trx('roles').where('name', 'administrator').whereNull('key').first());
103
108
  if (!role) {
109
+ // Role names are unique: a project role already named either way keeps its name.
110
+ const taken = new Set(await trx('roles').whereIn('name', [BOOTSTRAP_ROLE_NAME, 'administrator']).pluck('name'));
111
+ const name = [
112
+ BOOTSTRAP_ROLE_NAME,
113
+ 'administrator',
114
+ `${BOOTSTRAP_ROLE_NAME} (administrator)`,
115
+ ].find((candidate) => !taken.has(candidate));
104
116
  const [created] = await trx('roles')
105
- .insert({ name: 'administrator', key: 'administrator', permission_level: 1 })
117
+ .insert({
118
+ name,
119
+ key: 'administrator',
120
+ permission_level: 1,
121
+ })
106
122
  .returning('*');
107
123
  role = created;
108
124
  }
109
- else if (!role.key && !(await trx('roles').where('key', 'administrator').first()))
125
+ else if (!role.key)
110
126
  await trx('roles').where('id', role.id).update({ key: 'administrator' });
111
127
  // Repair a missing bootstrap grant even when the role already exists.
112
128
  if (!(await trx('role_rules')
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Profile pictures (ADR 050) are untrusted bytes. The browser crops and re-encodes every
3
+ * picture to at most 512 px, so the server accepts only what that produces: PNG or still
4
+ * WebP within these bounds. Nothing here decodes pixel data; the container is checked and
5
+ * rewritten so that only the chunks a browser needs to draw the picture remain.
6
+ */
7
+ export declare const AVATAR_LIMITS: Readonly<{
8
+ maxBytes: number;
9
+ minSide: 32;
10
+ maxSide: 512;
11
+ }>;
12
+ export type AvatarImage = {
13
+ type: 'png' | 'webp';
14
+ mimeType: 'image/png' | 'image/webp';
15
+ extname: 'png' | 'webp';
16
+ width: number;
17
+ height: number;
18
+ bytes: Buffer;
19
+ };
20
+ /**
21
+ * Checks an uploaded profile picture by its first bytes (never its name or declared type),
22
+ * bounds its size and dimensions from the header, and returns a copy without metadata or
23
+ * trailing bytes. Anything else, including SVG, GIF, JPEG, HTML and animations, is refused.
24
+ */
25
+ export declare function sanitizeAvatarImage(input: Uint8Array): AvatarImage;
26
+ /**
27
+ * Prepares an uploaded profile picture for storage (ADR 050). `sanitizeAvatarImage` first
28
+ * checks the bytes without decoding them (type, size, header, dimensions, animation), so
29
+ * nothing unexpected reaches the decoder. libvips then decodes the single still frame
30
+ * within a pixel budget and re-encodes it, which drops every metadata chunk and any payload
31
+ * hidden inside the compressed pixel data. The result is checked again before it is stored.
32
+ */
33
+ export declare function prepareAvatarImage(input: Uint8Array): Promise<AvatarImage>;
@@ -0,0 +1,278 @@
1
+ import { crc32 } from 'node:zlib';
2
+ import { AdulaError } from '../admin/errors.js';
3
+ /**
4
+ * Profile pictures (ADR 050) are untrusted bytes. The browser crops and re-encodes every
5
+ * picture to at most 512 px, so the server accepts only what that produces: PNG or still
6
+ * WebP within these bounds. Nothing here decodes pixel data; the container is checked and
7
+ * rewritten so that only the chunks a browser needs to draw the picture remain.
8
+ */
9
+ export const AVATAR_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, minSide: 32, maxSide: 512 });
10
+ const TYPE_MESSAGE = 'الصورة الشخصية يجب أن تكون بصيغة PNG أو WebP';
11
+ const CORRUPT_MESSAGE = 'ملف الصورة تالف أو غير مكتمل';
12
+ const SIZE_MESSAGE = 'حجم الصورة الشخصية يتجاوز ١ ميغابايت';
13
+ const DIMENSIONS_MESSAGE = 'أبعاد الصورة الشخصية يجب أن تكون بين ٣٢ و٥١٢ بكسل';
14
+ const ANIMATED_MESSAGE = 'الصورة الشخصية يجب أن تكون صورة ثابتة';
15
+ const wrongType = () => new AdulaError(422, 'E_AVATAR_TYPE', TYPE_MESSAGE);
16
+ const corrupt = () => new AdulaError(422, 'E_AVATAR_CORRUPT', CORRUPT_MESSAGE);
17
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
18
+ /** Chunks a still PNG needs; text, EXIF, ICC, time and animation chunks are dropped. */
19
+ const PNG_KEEP = new Set(['IHDR', 'PLTE', 'tRNS', 'IDAT', 'IEND']);
20
+ /** Bit depths allowed for each PNG colour type (PNG specification, table 11.1). */
21
+ const PNG_DEPTHS = {
22
+ 0: [1, 2, 4, 8, 16],
23
+ 2: [8, 16],
24
+ 3: [1, 2, 4, 8],
25
+ 4: [8, 16],
26
+ 6: [8, 16],
27
+ };
28
+ function chunk(type, data) {
29
+ const head = Buffer.alloc(8);
30
+ head.writeUInt32BE(data.length, 0);
31
+ head.write(type, 4, 'latin1');
32
+ const crc = Buffer.alloc(4);
33
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
34
+ return Buffer.concat([head, data, crc]);
35
+ }
36
+ function png(bytes) {
37
+ let offset = PNG_SIGNATURE.length;
38
+ const kept = [PNG_SIGNATURE];
39
+ let width = 0;
40
+ let height = 0;
41
+ let colorType = -1;
42
+ let sawPalette = false;
43
+ let idat = 'none';
44
+ let first = true;
45
+ for (;;) {
46
+ if (offset + 12 > bytes.length)
47
+ throw corrupt();
48
+ const length = bytes.readUInt32BE(offset);
49
+ const type = bytes.toString('latin1', offset + 4, offset + 8);
50
+ if (length > 0x7fffffff || offset + 12 + length > bytes.length)
51
+ throw corrupt();
52
+ if (!/^[A-Za-z]{4}$/.test(type))
53
+ throw corrupt();
54
+ const data = bytes.subarray(offset + 8, offset + 8 + length);
55
+ const stored = bytes.readUInt32BE(offset + 8 + length);
56
+ if (crc32(bytes.subarray(offset + 4, offset + 8 + length)) >>> 0 !== stored)
57
+ throw corrupt();
58
+ offset += 12 + length;
59
+ if (first) {
60
+ if (type !== 'IHDR' || length !== 13)
61
+ throw corrupt();
62
+ first = false;
63
+ width = data.readUInt32BE(0);
64
+ height = data.readUInt32BE(4);
65
+ const depth = data[8];
66
+ colorType = data[9];
67
+ if (!PNG_DEPTHS[colorType]?.includes(depth) ||
68
+ data[10] !== 0 ||
69
+ data[11] !== 0 ||
70
+ (data[12] !== 0 && data[12] !== 1))
71
+ throw corrupt();
72
+ }
73
+ else if (type === 'IHDR')
74
+ throw corrupt();
75
+ // Animated PNG frames: a profile picture is a still image.
76
+ if (type === 'acTL' || type === 'fcTL' || type === 'fdAT')
77
+ throw new AdulaError(422, 'E_AVATAR_TYPE', ANIMATED_MESSAGE);
78
+ // An unknown critical chunk (upper-case first letter) cannot be skipped safely.
79
+ if (!PNG_KEEP.has(type) && type[0] === type[0].toUpperCase())
80
+ throw corrupt();
81
+ if (type === 'PLTE') {
82
+ if (idat !== 'none' || sawPalette || length % 3 !== 0 || length === 0)
83
+ throw corrupt();
84
+ sawPalette = true;
85
+ }
86
+ if (type === 'IDAT') {
87
+ if (idat === 'closed')
88
+ throw corrupt();
89
+ idat = 'open';
90
+ }
91
+ else if (idat === 'open')
92
+ idat = 'closed';
93
+ if (PNG_KEEP.has(type))
94
+ kept.push(chunk(type, Buffer.from(data)));
95
+ // Bytes after IEND (a polyglot tail) are not kept.
96
+ if (type === 'IEND')
97
+ break;
98
+ }
99
+ if (idat === 'none' || (colorType === 3 && !sawPalette))
100
+ throw corrupt();
101
+ return { width, height, bytes: Buffer.concat(kept) };
102
+ }
103
+ /** WebP flags (VP8X): ICC profile, EXIF and XMP metadata are cleared with their chunks. */
104
+ const VP8X_ANIMATION = 0x02;
105
+ const VP8X_METADATA = 0x04 | 0x08 | 0x20;
106
+ function webpFrame(type, data) {
107
+ if (type === 'VP8 ') {
108
+ if (data.length < 10 || data[3] !== 0x9d || data[4] !== 0x01 || data[5] !== 0x2a)
109
+ throw corrupt();
110
+ return { width: data.readUInt16LE(6) & 0x3fff, height: data.readUInt16LE(8) & 0x3fff };
111
+ }
112
+ if (data.length < 5 || data[0] !== 0x2f)
113
+ throw corrupt();
114
+ const bits = data.readUInt32LE(1);
115
+ if (bits >>> 29 !== 0)
116
+ throw corrupt();
117
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
118
+ }
119
+ function webp(bytes) {
120
+ if (bytes.length < 20)
121
+ throw corrupt();
122
+ const riff = bytes.readUInt32LE(4);
123
+ if (riff < 12 || riff % 2 !== 0 || riff + 8 > bytes.length)
124
+ throw corrupt();
125
+ const end = riff + 8;
126
+ let offset = 12;
127
+ const chunks = [];
128
+ while (offset < end) {
129
+ if (offset + 8 > end)
130
+ throw corrupt();
131
+ const type = bytes.toString('latin1', offset, offset + 4);
132
+ const length = bytes.readUInt32LE(offset + 4);
133
+ const padded = length + (length % 2);
134
+ if (offset + 8 + padded > end)
135
+ throw corrupt();
136
+ chunks.push({ type, data: bytes.subarray(offset + 8, offset + 8 + length) });
137
+ offset += 8 + padded;
138
+ }
139
+ if (!chunks.length)
140
+ throw corrupt();
141
+ if (chunks.some((entry) => entry.type === 'ANIM' || entry.type === 'ANMF'))
142
+ throw new AdulaError(422, 'E_AVATAR_TYPE', ANIMATED_MESSAGE);
143
+ const [head] = chunks;
144
+ let out;
145
+ let width;
146
+ let height;
147
+ if (head.type === 'VP8 ' || head.type === 'VP8L') {
148
+ if (chunks.length !== 1)
149
+ throw corrupt();
150
+ ({ width, height } = webpFrame(head.type, head.data));
151
+ out = [head];
152
+ }
153
+ else if (head.type === 'VP8X') {
154
+ if (head.data.length !== 10)
155
+ throw corrupt();
156
+ const flags = head.data[0];
157
+ if (flags & VP8X_ANIMATION)
158
+ throw new AdulaError(422, 'E_AVATAR_TYPE', ANIMATED_MESSAGE);
159
+ width = head.data.readUIntLE(4, 3) + 1;
160
+ height = head.data.readUIntLE(7, 3) + 1;
161
+ const rest = chunks.slice(1);
162
+ const frames = rest.filter((entry) => entry.type === 'VP8 ' || entry.type === 'VP8L');
163
+ if (frames.length !== 1)
164
+ throw corrupt();
165
+ const frame = webpFrame(frames[0].type, frames[0].data);
166
+ if (frame.width !== width || frame.height !== height)
167
+ throw corrupt();
168
+ const alpha = rest.filter((entry) => entry.type === 'ALPH');
169
+ if (alpha.length > 1 || (alpha.length && frames[0].type !== 'VP8 '))
170
+ throw corrupt();
171
+ const header = Buffer.from(head.data);
172
+ header[0] = flags & ~VP8X_METADATA;
173
+ // EXIF, XMP, ICCP and unknown chunks are dropped; ALPH must precede the frame.
174
+ out = [{ type: 'VP8X', data: header }, ...alpha, frames[0]];
175
+ }
176
+ else
177
+ throw corrupt();
178
+ const parts = [];
179
+ for (const entry of out) {
180
+ const head8 = Buffer.alloc(8);
181
+ head8.write(entry.type, 0, 'latin1');
182
+ head8.writeUInt32LE(entry.data.length, 4);
183
+ parts.push(head8, entry.data);
184
+ if (entry.data.length % 2)
185
+ parts.push(Buffer.alloc(1));
186
+ }
187
+ const body = Buffer.concat(parts);
188
+ const header = Buffer.alloc(12);
189
+ header.write('RIFF', 0, 'latin1');
190
+ header.writeUInt32LE(body.length + 4, 4);
191
+ header.write('WEBP', 8, 'latin1');
192
+ return { width, height, bytes: Buffer.concat([header, body]) };
193
+ }
194
+ function detect(bytes) {
195
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_SIGNATURE))
196
+ return 'png';
197
+ if (bytes.length >= 12 &&
198
+ bytes.toString('latin1', 0, 4) === 'RIFF' &&
199
+ bytes.toString('latin1', 8, 12) === 'WEBP')
200
+ return 'webp';
201
+ return null;
202
+ }
203
+ function parse(type, bytes) {
204
+ try {
205
+ return type === 'png' ? png(bytes) : webp(bytes);
206
+ }
207
+ catch (error) {
208
+ if (error instanceof AdulaError)
209
+ throw error;
210
+ // A read past a declared length means the file is truncated or forged.
211
+ throw corrupt();
212
+ }
213
+ }
214
+ /**
215
+ * Checks an uploaded profile picture by its first bytes (never its name or declared type),
216
+ * bounds its size and dimensions from the header, and returns a copy without metadata or
217
+ * trailing bytes. Anything else, including SVG, GIF, JPEG, HTML and animations, is refused.
218
+ */
219
+ export function sanitizeAvatarImage(input) {
220
+ const bytes = Buffer.from(input.buffer, input.byteOffset, input.byteLength);
221
+ if (bytes.length > AVATAR_LIMITS.maxBytes)
222
+ throw new AdulaError(422, 'E_AVATAR_SIZE', SIZE_MESSAGE);
223
+ const type = detect(bytes);
224
+ if (!type)
225
+ throw wrongType();
226
+ const parsed = parse(type, bytes);
227
+ const inBounds = (side) => side >= AVATAR_LIMITS.minSide && side <= AVATAR_LIMITS.maxSide;
228
+ if (!inBounds(parsed.width) || !inBounds(parsed.height))
229
+ throw new AdulaError(422, 'E_AVATAR_DIMENSIONS', DIMENSIONS_MESSAGE);
230
+ // The rewritten file must read back as the same picture.
231
+ const again = parse(type, parsed.bytes);
232
+ if (again.width !== parsed.width || again.height !== parsed.height)
233
+ throw corrupt();
234
+ return {
235
+ type,
236
+ mimeType: type === 'png' ? 'image/png' : 'image/webp',
237
+ extname: type,
238
+ width: parsed.width,
239
+ height: parsed.height,
240
+ bytes: again.bytes,
241
+ };
242
+ }
243
+ /**
244
+ * Prepares an uploaded profile picture for storage (ADR 050). `sanitizeAvatarImage` first
245
+ * checks the bytes without decoding them (type, size, header, dimensions, animation), so
246
+ * nothing unexpected reaches the decoder. libvips then decodes the single still frame
247
+ * within a pixel budget and re-encodes it, which drops every metadata chunk and any payload
248
+ * hidden inside the compressed pixel data. The result is checked again before it is stored.
249
+ */
250
+ export async function prepareAvatarImage(input) {
251
+ const checked = sanitizeAvatarImage(input);
252
+ const { default: sharp } = await import('sharp');
253
+ const options = {
254
+ limitInputPixels: AVATAR_LIMITS.maxSide * AVATAR_LIMITS.maxSide,
255
+ animated: false,
256
+ failOn: 'error',
257
+ };
258
+ let encoded;
259
+ try {
260
+ const image = sharp(checked.bytes, options);
261
+ const metadata = await image.metadata();
262
+ if ((metadata.pages ?? 1) !== 1)
263
+ throw new AdulaError(422, 'E_AVATAR_TYPE', ANIMATED_MESSAGE);
264
+ // Metadata is kept only when asked for (withMetadata), so the output carries none.
265
+ encoded =
266
+ checked.type === 'png'
267
+ ? await image.png({ compressionLevel: 9, adaptiveFiltering: true }).toBuffer()
268
+ : await image.webp({ quality: 90, effort: 4 }).toBuffer();
269
+ if (encoded.length > AVATAR_LIMITS.maxBytes && checked.type === 'png')
270
+ encoded = await sharp(checked.bytes, options).webp({ quality: 85, effort: 4 }).toBuffer();
271
+ }
272
+ catch (error) {
273
+ if (error instanceof AdulaError)
274
+ throw error;
275
+ throw corrupt();
276
+ }
277
+ return sanitizeAvatarImage(encoded);
278
+ }
@@ -0,0 +1,83 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Actor } from '../auth/ability.js';
3
+ import type { SecretBox } from '../integrations/webhooks.js';
4
+ import { type OutboundOptions, type OutboundTarget } from '../integrations/outbound.js';
5
+ export declare const MAIL_SETTINGS_KEY = "mail.smtp";
6
+ /** How the SMTP connection is protected: implicit TLS, STARTTLS upgrade, or none. */
7
+ export type MailSecurity = 'tls' | 'starttls' | 'none';
8
+ /** The stored SMTP configuration as the administration shows it; the password never leaves. */
9
+ export type MailSettingsView = {
10
+ configured: boolean;
11
+ preset: string;
12
+ host: string;
13
+ port: number;
14
+ security: MailSecurity;
15
+ username: string;
16
+ hasPassword: boolean;
17
+ /**
18
+ * A password is stored but cannot be opened (APP_KEY rotated, or the value is damaged).
19
+ * Nothing is sent until it is entered again; sending never falls back to no sign-in.
20
+ */
21
+ passwordUnreadable: boolean;
22
+ fromName: string;
23
+ fromAddress: string;
24
+ updatedAt: string | null;
25
+ };
26
+ export type MailSettingsInput = Partial<Pick<MailSettingsView, 'preset' | 'host' | 'port' | 'security' | 'username' | 'fromName' | 'fromAddress'>>;
27
+ /** What the sending process needs: the options and the opened password, server side only. */
28
+ export type MailRuntime = {
29
+ host: string;
30
+ port: number;
31
+ security: MailSecurity;
32
+ username: string;
33
+ password: string | null;
34
+ fromName: string;
35
+ fromAddress: string;
36
+ };
37
+ type Who = Pick<Actor, 'id' | 'impersonatorId'>;
38
+ /**
39
+ * The stored SMTP password cannot be opened. It carries a category only, never the sealed or
40
+ * the opened value, and classifies as `password_unreadable` (see classifyMailFailure).
41
+ */
42
+ export declare class MailPasswordUnreadableError extends Error {
43
+ readonly code = "E_MAIL_PASSWORD_UNREADABLE";
44
+ constructor();
45
+ }
46
+ /**
47
+ * SMTP settings kept in the system setting `mail.smtp` (ADR 020 amendment), so an administrator
48
+ * configures mail from the interface without editing the environment or restarting. The password
49
+ * is sealed like the assistant key, is never returned, and is cleared whenever the server
50
+ * changes, so a stored password cannot be sent to another host. The host must resolve outside
51
+ * private networks unless the outbound policy allows them.
52
+ */
53
+ export declare class MailSettings {
54
+ private db;
55
+ private secrets;
56
+ private options;
57
+ constructor(db: Knex, secrets: SecretBox, options?: OutboundOptions);
58
+ read(): Promise<MailSettingsView>;
59
+ /**
60
+ * The stored options with the opened password, or null while nothing is stored. A stored
61
+ * password that cannot be opened throws MailPasswordUnreadableError: the message is not sent
62
+ * without the sign-in the administrator configured.
63
+ */
64
+ runtime(): Promise<MailRuntime | null>;
65
+ /**
66
+ * The address a connection to `host` must use; refuses private targets per the policy. An
67
+ * unencrypted connection (`none`) is refused unless the address is internal, so the password
68
+ * and the messages never cross the internet in clear text.
69
+ */
70
+ target(host: string, security?: MailSecurity): Promise<OutboundTarget>;
71
+ /** The opened password, or null when it cannot be opened; never logged or returned. */
72
+ private open;
73
+ private present;
74
+ /** Saves everything except the password. Changing the server clears the stored password. */
75
+ save(actor: Who, input: unknown): Promise<MailSettingsView>;
76
+ /** Stores the SMTP password sealed; it is never returned. */
77
+ setPassword(actor: Who, value: unknown): Promise<MailSettingsView>;
78
+ clearPassword(actor: Who): Promise<MailSettingsView>;
79
+ private write;
80
+ private stored;
81
+ private assertTarget;
82
+ }
83
+ export {};