@majikah/majik-file 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,67 @@
1
+ Copyright (c) 2025 Josef Elijah Delos Santos Fabian
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ ---
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
26
+
27
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
28
+
29
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
32
+
33
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
34
+
35
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
40
+
41
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
42
+
43
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
44
+
45
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
46
+
47
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
48
+
49
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
50
+
51
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
52
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
53
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
54
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
55
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
56
+
57
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
58
+
59
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
60
+
61
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
62
+
63
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
64
+
65
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
66
+
67
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,310 @@
1
+ # Majik File
2
+
3
+ [![Developed by Zelijah](https://img.shields.io/badge/Developed%20by-Zelijah-red?logo=github&logoColor=white)](https://thezelijah.world) ![GitHub Sponsors](https://img.shields.io/github/sponsors/jedlsf?style=plastic&label=Sponsors&link=https%3A%2F%2Fgithub.com%2Fsponsors%2Fjedlsf)
4
+
5
+ **Majik File** is the core cryptographic engine for secure file handling in the [Majik Message](https://github.com/Majikah/majik-message) ecosystem. It provides a **post-quantum secure "MJKB" format** designed for file encryption, multi-recipient key encapsulation, and transparent compression using NIST-standardized algorithms.
6
+
7
+ ![npm](https://img.shields.io/npm/v/@majikah/majik-file) ![npm downloads](https://img.shields.io/npm/dm/@majikah/majik-file) ![npm bundle size](https://img.shields.io/bundlephobia/min/%40majikah%2Fmajik-file) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)
8
+
9
+
10
+ ---
11
+ - [Majik File](#majik-file)
12
+ - [Overview](#overview)
13
+ - [Key Features](#key-features)
14
+ - [Installation](#installation)
15
+ - [Usage Guide](#usage-guide)
16
+ - [Creating a MajikFile](#creating-a-majikfile)
17
+ - [Accessing metadata](#accessing-metadata)
18
+ - [Encrypting and exporting](#encrypting-and-exporting)
19
+ - [Decrypting a MajikFile](#decrypting-a-majikfile)
20
+ - [Sharing](#sharing)
21
+ - [Duplicate Detection](#duplicate-detection)
22
+ - [Stats](#stats)
23
+ - [Static Helpers](#static-helpers)
24
+ - [Notes](#notes)
25
+ - [Related Projects](#related-projects)
26
+ - [Majik Message](#majik-message)
27
+ - [Majik Key](#majik-key)
28
+ - [Majik Envelope](#majik-envelope)
29
+ - [Contributing](#contributing)
30
+ - [License](#license)
31
+ - [Author](#author)
32
+ - [About the Developer](#about-the-developer)
33
+ - [Contact](#contact)
34
+
35
+
36
+ ---
37
+
38
+ ## Overview
39
+
40
+ **Majik File** implements a **File Envelope Format**, which uses **ML-KEM-768 (FIPS-203)** for **post-quantum secure key encapsulation**.
41
+
42
+ It abstracts the complexity of:
43
+
44
+ - Managing shared secrets
45
+ - AES-GCM initialization vectors
46
+ - Multi-recipient key wrapping
47
+ - File compression/decompression
48
+
49
+ This allows developers to **securely encrypt and share files with minimal cryptographic overhead**.
50
+
51
+ ---
52
+
53
+ ### Key Features
54
+
55
+ - **Single-recipient encryption**: ML-KEM encapsulation → AES-256-GCM key → encrypted `.mjkb`.
56
+ - **Group encryption (2+ recipients)**:
57
+ - Random AES-256 key encrypts file once
58
+ - Per recipient: ML-KEM encapsulate → AES key XOR sharedSecret
59
+ - **Write-once immutability**: `.mjkb` binaries are never patched in-place.
60
+ - **Automatic deduplication**: Files are checked by SHA-256 hash before encryption.
61
+ - **Context-aware storage**:
62
+ - `user_upload`, `chat_attachment`, `chat_image`, `thread_attachment`
63
+ - **Optional image conversion**: Chat images/attachments converted to WebP for efficiency.
64
+ - **Compression**: Zstd at level 22 for compressible formats.
65
+ - **Expiry and sharing**:
66
+ - Temporary files with expiry date
67
+ - Shareable links with auto-generated tokens
68
+ - **Inline viewable MIME detection** and safe download filename derivation.
69
+
70
+ ---
71
+
72
+ ## Installation
73
+
74
+ ```bash
75
+ npm install @majikah/majik-file
76
+
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Usage Guide
82
+
83
+ ### Creating a MajikFile
84
+
85
+ The library automatically chooses between "Single" and "Group" logic based on the number of recipients.
86
+
87
+ ```ts
88
+ import { MajikFile } from "@majikah/majik-file";
89
+
90
+ const file = await MajikFile.create({
91
+ data: myFileBlob, // Blob, ArrayBuffer, or Uint8Array
92
+ identity: {
93
+ userId: "user_123",
94
+ fingerprint: "BASE64_FINGERPRINT",
95
+ mlKemPublicKey: publicKey // Uint8Array of length 1184 bytes
96
+ },
97
+ context: "user_upload", // or "chat_attachment", "chat_image", "thread_attachment"
98
+ originalName: "photo.png",
99
+ recipients: [ // Optional: for group encryption
100
+ {
101
+ fingerprint: "recipient_fingerprint",
102
+ mlKemPublicKey: recipientPublicKey
103
+ }
104
+ ],
105
+ isTemporary: true, // Optional
106
+ expiresAt: MajikFile.buildExpiryDate(15)
107
+ });
108
+
109
+
110
+ ```
111
+
112
+ ### Accessing metadata
113
+
114
+ For group messages, a senderFingerprint is required for metadata.
115
+
116
+ ```ts
117
+ console.log(file.id);
118
+ console.log(file.originalName);
119
+ console.log(file.sizeMB);
120
+ console.log(file.isGroup);
121
+ console.log(file.isExpired);
122
+ console.log(file.safeFilename);
123
+
124
+
125
+ ```
126
+
127
+
128
+ ### Encrypting and exporting
129
+
130
+
131
+ ```ts
132
+ // Export .mjkb binary for R2 upload
133
+ const mjkbBlob = file.toMJKB();
134
+
135
+ // Export raw Uint8Array
136
+ const rawBytes = file.toBinaryBytes();
137
+
138
+
139
+
140
+ ```
141
+
142
+ ### Decrypting a MajikFile
143
+
144
+ To decrypt, you simply provide the recipient's identity (their private ML-KEM key and fingerprint).
145
+
146
+ ```ts
147
+ import { MajikFile } from "@majikah/majik-file";
148
+
149
+ const decrypted = await MajikFile.decrypt(
150
+ mjkbBlob,
151
+ {
152
+ fingerprint: "BASE64_FINGERPRINT",
153
+ mlKemSecretKey: secretKey // Uint8Array of length 2400 bytes
154
+ }
155
+ );
156
+
157
+ // If you already loaded the binary into memory
158
+ await file.decryptBinary({
159
+ fingerprint: "BASE64_FINGERPRINT",
160
+ mlKemSecretKey: secretKey
161
+ });
162
+
163
+ ```
164
+
165
+ ### Sharing
166
+
167
+ Enable sharing (auto-generates token if not provided)
168
+
169
+ ```ts
170
+
171
+ const token = file.toggleSharing();
172
+
173
+ // Disable sharing
174
+ file.toggleSharing();
175
+
176
+ ```
177
+
178
+ ### Duplicate Detection
179
+
180
+ ```ts
181
+
182
+ if (file.isDuplicateOf(otherFile)) {
183
+ console.log("Duplicate file detected");
184
+ }
185
+
186
+ if (MajikFile.wouldBeDuplicate(newRawBytes, existingHash)) {
187
+ console.log("New data is a duplicate");
188
+ }
189
+
190
+
191
+ ```
192
+
193
+ ### Stats
194
+
195
+ ```ts
196
+
197
+ console.log(file.getStats());
198
+
199
+
200
+ ```
201
+
202
+
203
+ ### Static Helpers
204
+
205
+ ```ts
206
+ import { MajikFile } from "@majikah/majik-file";
207
+
208
+ MajikFile.buildExpiryDate(15); // ISO expiry date string
209
+ MajikFile.formatBytes(1024); // "1 KB"
210
+ MajikFile.inferMimeType("file.png"); // "image/png"
211
+ MajikFile.isMjkbCandidate(someBytes); // true/false
212
+ MajikFile.hasPublicKeyAccess(pubKey, ownerFingerprint); // true/false
213
+
214
+ ```
215
+
216
+
217
+ ---
218
+ ## Notes
219
+
220
+ .mjkb format:
221
+
222
+ ```
223
+ [4 magic "MJKB"]
224
+ [1 version]
225
+ [12 AES-GCM IV]
226
+ [4 payload JSON length (big-endian uint32)]
227
+ [N payload JSON — MjkbSinglePayload | MjkbGroupPayload]
228
+ [M AES-GCM ciphertext (Zstd-compressed file + 16-byte auth tag)]
229
+
230
+ ```
231
+
232
+ - Owner is always first recipient in group encryption.
233
+ - Files cannot be updated in place — delete + re-create for modifications.
234
+ - Chat images always use conversation-scoped R2 prefix.
235
+
236
+ ---
237
+
238
+ ## Related Projects
239
+
240
+ ### [Majik Message](https://message.majikah.solutions)
241
+ Secure messaging platform using Majik Keys
242
+
243
+ ![npm](https://img.shields.io/npm/v/@majikah/majik-message) ![npm downloads](https://img.shields.io/npm/dm/@majikah/majik-message) ![npm bundle size](https://img.shields.io/bundlephobia/min/%40majikah%2Fmajik-message) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)
244
+
245
+ [Read more about Majik Message here](https://majikah.solutions/products/majik-message)
246
+
247
+ [![Majik Message Thumbnail](https://github.com/user-attachments/assets/d433c6b8-1841-4fa1-a6da-b348029d1dbe)](https://message.majikah.solutions)
248
+
249
+ > Click the image to try Majik Message live.
250
+
251
+ [Read Docs](https://majikah.solutions/products/majik-message/docs)
252
+
253
+
254
+ Also available on [Microsoft Store](https://apps.microsoft.com/detail/9pmjgvzzjspn) for free.
255
+
256
+ [Official Repository](https://github.com/Majikah/majik-message)
257
+ [SDK Library](https://www.npmjs.com/package/@majikah/majik-message)
258
+
259
+ ---
260
+
261
+ ### [Majik Key](https://majikah.solutions/sdk/majik-key)
262
+ **Majik Key** is a seed phrase account library for creating, managing, and parsing mnemonic-based cryptographic accounts (Majik Keys). Generate deterministic key pairs from BIP39 seed phrases with simple, developer-friendly APIs. Now supports ML-KEM-768 post-quantum key derivation alongside X25519.
263
+
264
+ ![npm](https://img.shields.io/npm/v/@majikah/majik-key) ![npm downloads](https://img.shields.io/npm/dm/@majikah/majik-key) ![npm bundle size](https://img.shields.io/bundlephobia/min/%40majikah%2Fmajik-key) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)
265
+
266
+ [Read Docs](https://majikah.solutions/sdk/majik-key/docs)
267
+ [Official Repository](https://github.com/Majikah/majik-key)
268
+ [SDK Library](https://www.npmjs.com/package/@majikah/majik-key)
269
+
270
+ ---
271
+
272
+
273
+ ### [Majik Envelope](https://majikah.solutions/sdk/majik-envelope)
274
+ **Majik Envelope** is the core cryptographic engine of the [Majik Message](https://github.com/Majikah/majik-message) platform. It provides a post-quantum secure "envelope" format that handles message encryption, multi-recipient key encapsulation, and transparent compression using NIST-standardized algorithms.
275
+
276
+ ![npm](https://img.shields.io/npm/v/@majikah/majik-envelope) ![npm downloads](https://img.shields.io/npm/dm/@majikah/majik-envelope) ![npm bundle size](https://img.shields.io/bundlephobia/min/%40majikah%2Fmajik-envelope) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)
277
+
278
+ [Read Docs](https://majikah.solutions/sdk/majik-envelope/docs)
279
+ [Official Repository](https://github.com/Majikah/majik-envelope)
280
+ [SDK Library](https://www.npmjs.com/package/@majikah/majik-envelope)
281
+
282
+ ---
283
+
284
+ ## Contributing
285
+
286
+ If you want to contribute or help extend support to more platforms, reach out via email. All contributions are welcome!
287
+
288
+ ---
289
+
290
+ ## License
291
+
292
+ [Apache-2.0](LICENSE) — free for personal and commercial use.
293
+
294
+ ---
295
+ ## Author
296
+
297
+ Made with 💙 by [@thezelijah](https://github.com/jedlsf)
298
+
299
+ ## About the Developer
300
+
301
+ - **Developer**: Josef Elijah Fabian
302
+ - **GitHub**: [https://github.com/jedlsf](https://github.com/jedlsf)
303
+ - **Project Repository**: [https://github.com/Majikah/majik-file](https://github.com/Majikah/majik-file)
304
+
305
+ ---
306
+
307
+ ## Contact
308
+
309
+ - **Business Email**: [business@thezelijah.world](mailto:business@thezelijah.world)
310
+ - **Official Website**: [https://www.thezelijah.world](https://www.thezelijah.world)
@@ -0,0 +1,43 @@
1
+ /**
2
+ * majik-compressor.ts
3
+ *
4
+ * Zstd (WASM) compression provider for MajikFile.
5
+ * Uses @bokuweb/zstd-wasm exclusively — no gzip fallback.
6
+ *
7
+ * The WASM module is initialised lazily on first use and cached for the
8
+ * lifetime of the module. Subsequent calls are synchronous after the first
9
+ * await.
10
+ */
11
+ /**
12
+ * Ensure the Zstd WASM module is initialised.
13
+ * Safe to call concurrently — the second caller will await the same promise.
14
+ */
15
+ export declare function ensureZstd(): Promise<void>;
16
+ export declare class MajikCompressor {
17
+ /**
18
+ * Compress raw bytes using Zstd at the specified level.
19
+ *
20
+ * @param data Raw bytes to compress.
21
+ * @param level Compression level 1–22. Defaults to ZSTD_MAX_LEVEL (22).
22
+ * @returns Compressed bytes.
23
+ * @throws MajikFileError on failure.
24
+ */
25
+ static compress(data: Uint8Array, level?: number): Promise<Uint8Array>;
26
+ /**
27
+ * Decompress Zstd-compressed bytes.
28
+ *
29
+ * @param data Zstd-compressed bytes.
30
+ * @returns Decompressed bytes.
31
+ * @throws MajikFileError on failure or corrupt data.
32
+ */
33
+ static decompress(data: Uint8Array): Promise<Uint8Array>;
34
+ /**
35
+ * Returns the compression ratio as a percentage size reduction.
36
+ * e.g. 100 bytes → 30 bytes = 70.0% reduction.
37
+ *
38
+ * @param originalSize Size before compression (bytes).
39
+ * @param compressedSize Size after compression (bytes).
40
+ * @returns Reduction percentage (0–100), rounded to one decimal.
41
+ */
42
+ static compressionRatioPct(originalSize: number, compressedSize: number): number;
43
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * majik-compressor.ts
3
+ *
4
+ * Zstd (WASM) compression provider for MajikFile.
5
+ * Uses @bokuweb/zstd-wasm exclusively — no gzip fallback.
6
+ *
7
+ * The WASM module is initialised lazily on first use and cached for the
8
+ * lifetime of the module. Subsequent calls are synchronous after the first
9
+ * await.
10
+ */
11
+ import { init, compress as zstdCompress, decompress as zstdDecompress, } from "@bokuweb/zstd-wasm";
12
+ import { MajikFileError } from "../error";
13
+ import { ZSTD_MAX_LEVEL } from "../crypto/constants";
14
+ // ─── Init Guard ───────────────────────────────────────────────────────────────
15
+ let zstdReady = false;
16
+ /**
17
+ * Ensure the Zstd WASM module is initialised.
18
+ * Safe to call concurrently — the second caller will await the same promise.
19
+ */
20
+ export async function ensureZstd() {
21
+ if (!zstdReady) {
22
+ await init();
23
+ zstdReady = true;
24
+ }
25
+ }
26
+ // ─── MajikCompressor ──────────────────────────────────────────────────────────
27
+ export class MajikCompressor {
28
+ /**
29
+ * Compress raw bytes using Zstd at the specified level.
30
+ *
31
+ * @param data Raw bytes to compress.
32
+ * @param level Compression level 1–22. Defaults to ZSTD_MAX_LEVEL (22).
33
+ * @returns Compressed bytes.
34
+ * @throws MajikFileError on failure.
35
+ */
36
+ static async compress(data, level = ZSTD_MAX_LEVEL) {
37
+ if (!(data instanceof Uint8Array) || data.length === 0) {
38
+ throw MajikFileError.invalidInput("MajikCompressor.compress: data must be a non-empty Uint8Array");
39
+ }
40
+ if (!Number.isInteger(level) || level < 1 || level > 22) {
41
+ throw MajikFileError.invalidInput(`MajikCompressor.compress: level must be an integer between 1 and 22 (got ${level})`);
42
+ }
43
+ try {
44
+ await ensureZstd();
45
+ return zstdCompress(data, level);
46
+ }
47
+ catch (err) {
48
+ throw MajikFileError.compressionFailed(err);
49
+ }
50
+ }
51
+ /**
52
+ * Decompress Zstd-compressed bytes.
53
+ *
54
+ * @param data Zstd-compressed bytes.
55
+ * @returns Decompressed bytes.
56
+ * @throws MajikFileError on failure or corrupt data.
57
+ */
58
+ static async decompress(data) {
59
+ if (!(data instanceof Uint8Array) || data.length === 0) {
60
+ throw MajikFileError.invalidInput("MajikCompressor.decompress: data must be a non-empty Uint8Array");
61
+ }
62
+ try {
63
+ await ensureZstd();
64
+ return zstdDecompress(data);
65
+ }
66
+ catch (err) {
67
+ throw MajikFileError.decompressionFailed(err);
68
+ }
69
+ }
70
+ /**
71
+ * Returns the compression ratio as a percentage size reduction.
72
+ * e.g. 100 bytes → 30 bytes = 70.0% reduction.
73
+ *
74
+ * @param originalSize Size before compression (bytes).
75
+ * @param compressedSize Size after compression (bytes).
76
+ * @returns Reduction percentage (0–100), rounded to one decimal.
77
+ */
78
+ static compressionRatioPct(originalSize, compressedSize) {
79
+ if (originalSize <= 0)
80
+ return 0;
81
+ const reduction = ((originalSize - compressedSize) / originalSize) * 100;
82
+ return Math.max(0, Math.round(reduction * 10) / 10);
83
+ }
84
+ }
@@ -0,0 +1,93 @@
1
+ /** Current .mjkb binary format version. */
2
+ export declare const MJKB_VERSION: 1;
3
+ /**
4
+ * .mjkb magic bytes: ASCII "MJKB" (0x4D 0x4A 0x4B 0x42).
5
+ * Present at the very start of every .mjkb file for format identification.
6
+ */
7
+ export declare const MJKB_MAGIC: Uint8Array;
8
+ /**
9
+ * Fixed header size before the variable-length payload JSON section:
10
+ * 4 magic "MJKB"
11
+ * 1 version
12
+ * 12 AES-GCM IV
13
+ * 4 payload JSON length (big-endian uint32)
14
+ * = 21 bytes
15
+ *
16
+ * @deprecated Use MJKB_FIXED_HEADER in utils.ts — this constant is kept only
17
+ * for backwards-compatibility with any external code that referenced it.
18
+ */
19
+ export declare const MJKB_HEADER_SIZE: number;
20
+ /** ML-KEM-768 public key length in bytes. */
21
+ export declare const ML_KEM_PK_LEN = 1184;
22
+ /** ML-KEM-768 secret key length in bytes. */
23
+ export declare const ML_KEM_SK_LEN = 2400;
24
+ /** ML-KEM-768 ciphertext length in bytes. */
25
+ export declare const ML_KEM_CT_LEN = 1088;
26
+ /** AES-256-GCM key length in bytes. */
27
+ export declare const AES_KEY_LEN = 32;
28
+ /** AES-GCM IV length in bytes. */
29
+ export declare const IV_LENGTH = 12;
30
+ /** Maximum Zstd compression level (highest ratio, slowest). */
31
+ export declare const ZSTD_MAX_LEVEL = 22;
32
+ /** Default maximum file size: 100 MB in bytes. Bypassable via CreateOptions. */
33
+ export declare const MAX_FILE_SIZE_BYTES: number;
34
+ /**
35
+ * R2 bucket key prefixes.
36
+ *
37
+ * PERMANENT → files/user/<userId>/<fileHash>.mjkb
38
+ * Retained indefinitely. Scoped to the user's sub-directory.
39
+ *
40
+ * TEMPORARY → files/public/<userId>_<fileHash>.mjkb
41
+ * Auto-deleted after ~15 days by the bucket lifecycle policy
42
+ * targeting all objects under the `files/public/` prefix.
43
+ */
44
+ export declare const R2_PREFIX: {
45
+ readonly PERMANENT: "files/user";
46
+ readonly TEMPORARY: "files/public";
47
+ /**
48
+ * Encrypted WebP chat images.
49
+ * Structure: images/chats/<conversationId>/<userId>_<fileHash>.mjkb
50
+ *
51
+ * Scoped per conversation so all images in a conversation can be
52
+ * batch-deleted (e.g. when a conversation is removed).
53
+ * These files use temporary storage by default with the standard
54
+ * 15-day R2 lifecycle policy, but can be made permanent if needed.
55
+ */
56
+ readonly CHAT_IMAGE: "images/chats";
57
+ };
58
+ export type R2Prefix = (typeof R2_PREFIX)[keyof typeof R2_PREFIX];
59
+ /**
60
+ * MIME types that can be rendered inline in a modern browser without
61
+ * requiring a download. Used by MajikFile.isInlineViewable.
62
+ */
63
+ export declare const INLINE_VIEWABLE_MIME_TYPES: Set<string>;
64
+ /**
65
+ * Comprehensive MIME type registry for popular file formats.
66
+ * Used for validation, labelling, and icon selection in the UI.
67
+ * Organised by category.
68
+ */
69
+ export declare const KNOWN_MIME_TYPES: Set<string>;
70
+ /**
71
+ * Map from common file extension → canonical MIME type.
72
+ * Use this when a file is uploaded without a MIME type and you need to infer
73
+ * one from the filename extension.
74
+ */
75
+ export declare const EXTENSION_TO_MIME: Readonly<Record<string, string>>;
76
+ /**
77
+ * Maximum number of recipients for a group-encrypted file.
78
+ * Prevents pathological payload sizes (each recipient adds ~1.5 KB to the
79
+ * .mjkb binary: 1088-byte ML-KEM CT + 32-byte encrypted AES key in base64).
80
+ */
81
+ export declare const MAX_RECIPIENTS = 100;
82
+ /**
83
+ * MIME type prefixes and exact types that are already compressed at the
84
+ * codec level. Applying Zstd to these yields negligible savings and
85
+ * measurable CPU/memory overhead — especially on mobile.
86
+ */
87
+ export declare const INCOMPRESSIBLE_MIME_TYPES: Set<string>;
88
+ /**
89
+ * Image MIME types that can be re-encoded to WebP in the browser.
90
+ * Used by the chat attachment path to normalise all images to WebP before
91
+ * encryption, reducing payload size for non-WebP sources.
92
+ */
93
+ export declare const WEBP_CONVERTIBLE_IMAGE_TYPES: Set<string>;