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
@@ -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
+ }
@@ -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
- load(id: number): Promise<Actor>;
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
- async load(id) {
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 this.db('authorization_revision').where({ id: 1 }).first('version');
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 this.db('user_org_units as u')
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 this.db('user_roles as ur')
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')
@@ -0,0 +1,52 @@
1
+ import { Transform } from 'node:stream';
2
+ /**
3
+ * The encrypted backup archive (ADR 051). A `.adulabackup` file is a 48-byte header followed
4
+ * by AES-256-GCM frames over a small container of the snapshot files:
5
+ *
6
+ * header = "ADULABK\0" | version u8 | algorithm u8 | reserved u16 | chunkSize u32 BE |
7
+ * keyId 8 bytes | salt 16 bytes | reserved 8 bytes
8
+ * frame = final u8 | ciphertext length u32 BE | ciphertext | tag 16 bytes
9
+ * AAD = header | counter u64 BE | final u8
10
+ * nonce = 4 zero bytes | counter u64 BE
11
+ * key = HKDF-SHA256(masterKey, salt, "adulajs backup v1"), unique per file
12
+ *
13
+ * Exactly one frame is final and it is the last one, so truncation and appended data are
14
+ * detected. The plaintext container is a sequence of entries (name length u16 BE, UTF-8 name,
15
+ * size u64 BE, bytes) ended by a zero name length; names come from a fixed allow-list.
16
+ */
17
+ export declare const BACKUP_ARCHIVE_EXTENSION = ".adulabackup";
18
+ export declare const BACKUP_ARCHIVE_FILES: readonly ["database.dump", "uploads.tar.gz", "attachments.json", "SHA256SUMS", "COMPLETE"];
19
+ export type BackupArchiveErrorCode = 'E_BACKUP_KEY_INVALID' | 'E_BACKUP_FORMAT' | 'E_BACKUP_KEY' | 'E_BACKUP_TAMPERED' | 'E_BACKUP_TRUNCATED' | 'E_BACKUP_CONTENT' | 'E_BACKUP_TARGET';
20
+ /** A refusal while sealing or opening an archive; the message is Arabic and holds no secret. */
21
+ export declare class BackupArchiveError extends Error {
22
+ code: BackupArchiveErrorCode;
23
+ constructor(code: BackupArchiveErrorCode);
24
+ }
25
+ /** Decodes BACKUP_ENCRYPTION_KEY: base64 of exactly 32 bytes. */
26
+ export declare function parseBackupKey(value: string): Buffer;
27
+ /** Encrypts a byte stream into the archive format. */
28
+ export declare function createSealStream(master: Buffer, options?: {
29
+ chunkSize?: number;
30
+ }): Transform;
31
+ /**
32
+ * Decrypts the archive format. Each frame is authenticated before its bytes are released,
33
+ * but the stream as a whole is only trustworthy once it ends without an error: a missing
34
+ * final frame is reported at the end.
35
+ */
36
+ export declare function createOpenStream(master: Buffer): Transform;
37
+ /**
38
+ * Seals a snapshot directory into a new archive file (created exclusively, mode 0600).
39
+ * Returns the archive's size and SHA-256. A partial file is removed on failure.
40
+ */
41
+ export declare function sealBackupArchive(snapshotDirectory: string, outFile: string, master: Buffer, options?: {
42
+ chunkSize?: number;
43
+ }): Promise<{
44
+ size: number;
45
+ sha256: string;
46
+ }>;
47
+ /**
48
+ * Opens an archive into a new snapshot directory (mode 0700). The decrypted container is
49
+ * written next to the extracted files only until the archive's final frame verifies, then
50
+ * deleted. Nothing is left behind when the archive is wrong, tampered or truncated.
51
+ */
52
+ export declare function openBackupArchive(file: string, targetDirectory: string, master: Buffer): Promise<void>;
@@ -0,0 +1,362 @@
1
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual, } from 'node:crypto';
2
+ import { createReadStream, createWriteStream } from 'node:fs';
3
+ import { lstat, mkdir, open, rm } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { Readable, Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ /**
8
+ * The encrypted backup archive (ADR 051). A `.adulabackup` file is a 48-byte header followed
9
+ * by AES-256-GCM frames over a small container of the snapshot files:
10
+ *
11
+ * header = "ADULABK\0" | version u8 | algorithm u8 | reserved u16 | chunkSize u32 BE |
12
+ * keyId 8 bytes | salt 16 bytes | reserved 8 bytes
13
+ * frame = final u8 | ciphertext length u32 BE | ciphertext | tag 16 bytes
14
+ * AAD = header | counter u64 BE | final u8
15
+ * nonce = 4 zero bytes | counter u64 BE
16
+ * key = HKDF-SHA256(masterKey, salt, "adulajs backup v1"), unique per file
17
+ *
18
+ * Exactly one frame is final and it is the last one, so truncation and appended data are
19
+ * detected. The plaintext container is a sequence of entries (name length u16 BE, UTF-8 name,
20
+ * size u64 BE, bytes) ended by a zero name length; names come from a fixed allow-list.
21
+ */
22
+ export const BACKUP_ARCHIVE_EXTENSION = '.adulabackup';
23
+ export const BACKUP_ARCHIVE_FILES = [
24
+ 'database.dump',
25
+ 'uploads.tar.gz',
26
+ 'attachments.json',
27
+ 'SHA256SUMS',
28
+ 'COMPLETE',
29
+ ];
30
+ const MAGIC = Buffer.from('ADULABK\0', 'latin1');
31
+ const VERSION = 1;
32
+ const ALGORITHM = 1;
33
+ const HEADER_SIZE = 48;
34
+ const TAG_SIZE = 16;
35
+ const FRAME_HEADER = 5;
36
+ const DEFAULT_CHUNK = 1024 * 1024;
37
+ const MAX_CHUNK = 16 * 1024 * 1024;
38
+ const INFO = Buffer.from('adulajs backup v1');
39
+ const MESSAGES = {
40
+ E_BACKUP_KEY_INVALID: 'مفتاح تشفير النسخ الاحتياطية غير صالح: يجب أن يكون 32 بايتًا بترميز base64',
41
+ E_BACKUP_FORMAT: 'الملف ليس نسخة احتياطية مشفرة من AdulaJS أو إصداره غير مدعوم',
42
+ E_BACKUP_KEY: 'مفتاح التشفير لا يطابق هذه النسخة الاحتياطية',
43
+ E_BACKUP_TAMPERED: 'تعذر التحقق من سلامة النسخة الاحتياطية: الملف معدل أو تالف',
44
+ E_BACKUP_TRUNCATED: 'النسخة الاحتياطية ناقصة: انقطع الملف قبل نهايته',
45
+ E_BACKUP_CONTENT: 'محتوى النسخة الاحتياطية غير متوقع',
46
+ E_BACKUP_TARGET: 'مجلد الاستعادة موجود مسبقًا أو لا يمكن إنشاؤه',
47
+ };
48
+ /** A refusal while sealing or opening an archive; the message is Arabic and holds no secret. */
49
+ export class BackupArchiveError extends Error {
50
+ code;
51
+ constructor(code) {
52
+ super(MESSAGES[code]);
53
+ this.code = code;
54
+ }
55
+ }
56
+ /** Decodes BACKUP_ENCRYPTION_KEY: base64 of exactly 32 bytes. */
57
+ export function parseBackupKey(value) {
58
+ const text = value.trim();
59
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || text.length % 4 !== 0)
60
+ throw new BackupArchiveError('E_BACKUP_KEY_INVALID');
61
+ const key = Buffer.from(text, 'base64');
62
+ if (key.length !== 32)
63
+ throw new BackupArchiveError('E_BACKUP_KEY_INVALID');
64
+ return key;
65
+ }
66
+ function keyId(master) {
67
+ return createHmac('sha256', master).update('adula-backup-key-id').digest().subarray(0, 8);
68
+ }
69
+ function fileKey(master, salt) {
70
+ return Buffer.from(hkdfSync('sha256', master, salt, INFO, 32));
71
+ }
72
+ function nonce(counter) {
73
+ const value = Buffer.alloc(12);
74
+ value.writeBigUInt64BE(counter, 4);
75
+ return value;
76
+ }
77
+ function aad(header, counter, final) {
78
+ const tail = Buffer.alloc(9);
79
+ tail.writeBigUInt64BE(counter, 0);
80
+ tail[8] = final ? 1 : 0;
81
+ return Buffer.concat([header, tail]);
82
+ }
83
+ /** Encrypts a byte stream into the archive format. */
84
+ export function createSealStream(master, options = {}) {
85
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK;
86
+ if (!Number.isInteger(chunkSize) || chunkSize < 1 || chunkSize > MAX_CHUNK)
87
+ throw new RangeError('Invalid chunk size');
88
+ const salt = randomBytes(16);
89
+ const header = Buffer.alloc(HEADER_SIZE);
90
+ MAGIC.copy(header, 0);
91
+ header[8] = VERSION;
92
+ header[9] = ALGORITHM;
93
+ header.writeUInt32BE(chunkSize, 12);
94
+ keyId(master).copy(header, 16);
95
+ salt.copy(header, 24);
96
+ const key = fileKey(master, salt);
97
+ let counter = 0n;
98
+ let pending = [];
99
+ let pendingSize = 0;
100
+ let headerSent = false;
101
+ const frame = (plain, final) => {
102
+ const cipher = createCipheriv('aes-256-gcm', key, nonce(counter));
103
+ cipher.setAAD(aad(header, counter, final));
104
+ const encrypted = Buffer.concat([cipher.update(plain), cipher.final()]);
105
+ const prefix = Buffer.alloc(FRAME_HEADER);
106
+ prefix[0] = final ? 1 : 0;
107
+ prefix.writeUInt32BE(encrypted.length, 1);
108
+ counter++;
109
+ return Buffer.concat([prefix, encrypted, cipher.getAuthTag()]);
110
+ };
111
+ const start = (stream) => {
112
+ if (!headerSent) {
113
+ stream.push(header);
114
+ headerSent = true;
115
+ }
116
+ };
117
+ return new Transform({
118
+ transform(chunk, _encoding, callback) {
119
+ start(this);
120
+ pending.push(chunk);
121
+ pendingSize += chunk.length;
122
+ // Keep at least one byte back, so the final frame always carries the tail.
123
+ while (pendingSize > chunkSize) {
124
+ const joined = Buffer.concat(pending);
125
+ this.push(frame(joined.subarray(0, chunkSize), false));
126
+ pending = [joined.subarray(chunkSize)];
127
+ pendingSize = joined.length - chunkSize;
128
+ }
129
+ callback();
130
+ },
131
+ flush(callback) {
132
+ start(this);
133
+ this.push(frame(Buffer.concat(pending), true));
134
+ pending = [];
135
+ callback();
136
+ },
137
+ });
138
+ }
139
+ /**
140
+ * Decrypts the archive format. Each frame is authenticated before its bytes are released,
141
+ * but the stream as a whole is only trustworthy once it ends without an error: a missing
142
+ * final frame is reported at the end.
143
+ */
144
+ export function createOpenStream(master) {
145
+ let buffer = Buffer.alloc(0);
146
+ let header = null;
147
+ let key = null;
148
+ let chunkSize = 0;
149
+ let counter = 0n;
150
+ let finished = false;
151
+ const fail = (code) => new BackupArchiveError(code);
152
+ return new Transform({
153
+ transform(chunk, _encoding, callback) {
154
+ if (finished && chunk.length)
155
+ return callback(fail('E_BACKUP_TAMPERED'));
156
+ buffer = buffer.length ? Buffer.concat([buffer, chunk]) : chunk;
157
+ try {
158
+ if (!header) {
159
+ if (buffer.length < HEADER_SIZE)
160
+ return callback();
161
+ const candidate = buffer.subarray(0, HEADER_SIZE);
162
+ if (!candidate.subarray(0, 8).equals(MAGIC) || candidate[8] !== VERSION)
163
+ throw fail('E_BACKUP_FORMAT');
164
+ if (candidate[9] !== ALGORITHM)
165
+ throw fail('E_BACKUP_FORMAT');
166
+ chunkSize = candidate.readUInt32BE(12);
167
+ if (chunkSize < 1 || chunkSize > MAX_CHUNK)
168
+ throw fail('E_BACKUP_FORMAT');
169
+ if (!timingSafeEqual(candidate.subarray(16, 24), keyId(master)))
170
+ throw fail('E_BACKUP_KEY');
171
+ header = Buffer.from(candidate);
172
+ key = fileKey(master, header.subarray(24, 40));
173
+ buffer = buffer.subarray(HEADER_SIZE);
174
+ }
175
+ while (buffer.length >= FRAME_HEADER) {
176
+ if (finished)
177
+ throw fail('E_BACKUP_TAMPERED');
178
+ const flag = buffer[0];
179
+ const length = buffer.readUInt32BE(1);
180
+ if (flag > 1 || length > chunkSize)
181
+ throw fail('E_BACKUP_TAMPERED');
182
+ const total = FRAME_HEADER + length + TAG_SIZE;
183
+ if (buffer.length < total)
184
+ break;
185
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce(counter));
186
+ decipher.setAAD(aad(header, counter, flag === 1));
187
+ decipher.setAuthTag(buffer.subarray(FRAME_HEADER + length, total));
188
+ let plain;
189
+ try {
190
+ plain = Buffer.concat([
191
+ decipher.update(buffer.subarray(FRAME_HEADER, FRAME_HEADER + length)),
192
+ decipher.final(),
193
+ ]);
194
+ }
195
+ catch {
196
+ throw fail('E_BACKUP_TAMPERED');
197
+ }
198
+ counter++;
199
+ buffer = buffer.subarray(total);
200
+ if (flag === 1)
201
+ finished = true;
202
+ if (plain.length)
203
+ this.push(plain);
204
+ }
205
+ if (finished && buffer.length)
206
+ throw fail('E_BACKUP_TAMPERED');
207
+ callback();
208
+ }
209
+ catch (error) {
210
+ callback(error);
211
+ }
212
+ },
213
+ flush(callback) {
214
+ if (!header) {
215
+ const prefix = buffer.subarray(0, MAGIC.length);
216
+ const looksLikeArchive = buffer.length > 0 && MAGIC.subarray(0, prefix.length).equals(prefix);
217
+ return callback(fail(looksLikeArchive ? 'E_BACKUP_TRUNCATED' : 'E_BACKUP_FORMAT'));
218
+ }
219
+ if (!finished)
220
+ return callback(fail('E_BACKUP_TRUNCATED'));
221
+ callback();
222
+ },
223
+ });
224
+ }
225
+ async function* containerEntries(directory, names) {
226
+ for (const name of names) {
227
+ const path = join(directory, name);
228
+ const info = await lstat(path);
229
+ if (!info.isFile())
230
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
231
+ const nameBytes = Buffer.from(name, 'utf8');
232
+ const head = Buffer.alloc(2 + nameBytes.length + 8);
233
+ head.writeUInt16BE(nameBytes.length, 0);
234
+ nameBytes.copy(head, 2);
235
+ head.writeBigUInt64BE(BigInt(info.size), 2 + nameBytes.length);
236
+ yield head;
237
+ let written = 0;
238
+ for await (const chunk of createReadStream(path)) {
239
+ written += chunk.length;
240
+ yield chunk;
241
+ }
242
+ // The file changed while it was being sealed.
243
+ if (written !== info.size)
244
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
245
+ }
246
+ yield Buffer.alloc(2);
247
+ }
248
+ /** The snapshot files present in a directory, in archive order; database.dump is required. */
249
+ async function snapshotNames(directory) {
250
+ const present = [];
251
+ for (const name of BACKUP_ARCHIVE_FILES) {
252
+ try {
253
+ await lstat(join(directory, name));
254
+ present.push(name);
255
+ }
256
+ catch (error) {
257
+ if (error.code !== 'ENOENT')
258
+ throw error;
259
+ }
260
+ }
261
+ if (!present.includes('database.dump'))
262
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
263
+ return present;
264
+ }
265
+ /**
266
+ * Seals a snapshot directory into a new archive file (created exclusively, mode 0600).
267
+ * Returns the archive's size and SHA-256. A partial file is removed on failure.
268
+ */
269
+ export async function sealBackupArchive(snapshotDirectory, outFile, master, options = {}) {
270
+ const names = await snapshotNames(snapshotDirectory);
271
+ const hash = createHash('sha256');
272
+ let size = 0;
273
+ const tap = new Transform({
274
+ transform(chunk, _encoding, callback) {
275
+ hash.update(chunk);
276
+ size += chunk.length;
277
+ callback(null, chunk);
278
+ },
279
+ });
280
+ const output = createWriteStream(outFile, { flags: 'wx', mode: 0o600 });
281
+ try {
282
+ await pipeline(Readable.from(containerEntries(snapshotDirectory, names)), createSealStream(master, options), tap, output);
283
+ }
284
+ catch (error) {
285
+ if (error.code !== 'EEXIST')
286
+ await rm(outFile, { force: true });
287
+ throw error;
288
+ }
289
+ return { size, sha256: hash.digest('hex') };
290
+ }
291
+ /** Reads the decrypted container and writes each allow-listed entry into the target. */
292
+ async function extractContainer(container, target) {
293
+ const handle = await open(container, 'r');
294
+ try {
295
+ const { size: total } = await handle.stat();
296
+ let position = 0;
297
+ const read = async (length) => {
298
+ if (position + length > total)
299
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
300
+ const value = Buffer.alloc(length);
301
+ const { bytesRead } = await handle.read(value, 0, length, position);
302
+ if (bytesRead !== length)
303
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
304
+ position += length;
305
+ return value;
306
+ };
307
+ const seen = new Set();
308
+ for (;;) {
309
+ const lengthBytes = await read(2);
310
+ const nameLength = lengthBytes.readUInt16BE(0);
311
+ if (nameLength === 0)
312
+ break;
313
+ if (nameLength > 64)
314
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
315
+ const nameBytes = await read(nameLength);
316
+ const name = nameBytes.toString('utf8');
317
+ if (!BACKUP_ARCHIVE_FILES.includes(name) || seen.has(name))
318
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
319
+ seen.add(name);
320
+ const sizeBytes = await read(8);
321
+ const size = Number(sizeBytes.readBigUInt64BE(0));
322
+ if (!Number.isSafeInteger(size) || position + size > total)
323
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
324
+ const output = createWriteStream(join(target, name), { flags: 'wx', mode: 0o600 });
325
+ const input = size === 0
326
+ ? Readable.from([])
327
+ : createReadStream(container, { start: position, end: position + size - 1 });
328
+ await pipeline(input, output);
329
+ position += size;
330
+ }
331
+ if (position !== total || !seen.has('database.dump'))
332
+ throw new BackupArchiveError('E_BACKUP_CONTENT');
333
+ }
334
+ finally {
335
+ await handle.close();
336
+ }
337
+ }
338
+ /**
339
+ * Opens an archive into a new snapshot directory (mode 0700). The decrypted container is
340
+ * written next to the extracted files only until the archive's final frame verifies, then
341
+ * deleted. Nothing is left behind when the archive is wrong, tampered or truncated.
342
+ */
343
+ export async function openBackupArchive(file, targetDirectory, master) {
344
+ try {
345
+ await mkdir(targetDirectory, { mode: 0o700 });
346
+ }
347
+ catch {
348
+ throw new BackupArchiveError('E_BACKUP_TARGET');
349
+ }
350
+ const container = join(targetDirectory, '.archive.bin');
351
+ try {
352
+ await pipeline(createReadStream(file), createOpenStream(master), createWriteStream(container, { flags: 'wx', mode: 0o600 }));
353
+ await extractContainer(container, targetDirectory);
354
+ }
355
+ catch (error) {
356
+ await rm(targetDirectory, { recursive: true, force: true });
357
+ throw error;
358
+ }
359
+ finally {
360
+ await rm(container, { force: true });
361
+ }
362
+ }