mdenc 0.1.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -28,29 +28,58 @@ __export(index_exports, {
28
28
  });
29
29
  module.exports = __toCommonJS(index_exports);
30
30
 
31
- // src/types.ts
32
- var DEFAULT_SCRYPT_PARAMS = {
33
- N: 16384,
34
- r: 8,
35
- p: 1
36
- };
37
- var SCRYPT_BOUNDS = {
38
- N: { min: 1024, max: 1048576 },
39
- // 2^10 – 2^20
40
- r: { min: 1, max: 64 },
41
- p: { min: 1, max: 16 }
42
- };
43
- var ChunkingStrategy = /* @__PURE__ */ ((ChunkingStrategy2) => {
44
- ChunkingStrategy2["Paragraph"] = "paragraph";
45
- ChunkingStrategy2["FixedSize"] = "fixed-size";
46
- return ChunkingStrategy2;
47
- })(ChunkingStrategy || {});
48
-
49
- // src/encrypt.ts
31
+ // src/crypto/encrypt.ts
50
32
  var import_hmac3 = require("@noble/hashes/hmac");
51
33
  var import_sha2564 = require("@noble/hashes/sha256");
52
34
 
53
- // src/chunking.ts
35
+ // src/crypto/aead.ts
36
+ var import_chacha = require("@noble/ciphers/chacha");
37
+ var import_hmac = require("@noble/hashes/hmac");
38
+ var import_sha256 = require("@noble/hashes/sha256");
39
+ var NONCE_LENGTH = 24;
40
+ function buildAAD(fileId) {
41
+ const fileIdHex = bytesToHex(fileId);
42
+ const aadString = `mdenc:v1
43
+ ${fileIdHex}`;
44
+ return new TextEncoder().encode(aadString);
45
+ }
46
+ function deriveNonce(nonceKey, plaintext) {
47
+ const full = (0, import_hmac.hmac)(import_sha256.sha256, nonceKey, plaintext);
48
+ return full.slice(0, NONCE_LENGTH);
49
+ }
50
+ function encryptChunk(encKey, nonceKey, plaintext, fileId) {
51
+ const nonce = deriveNonce(nonceKey, plaintext);
52
+ const aad = buildAAD(fileId);
53
+ const cipher = (0, import_chacha.xchacha20poly1305)(encKey, nonce, aad);
54
+ const ciphertext = cipher.encrypt(plaintext);
55
+ const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);
56
+ result.set(nonce, 0);
57
+ result.set(ciphertext, NONCE_LENGTH);
58
+ return result;
59
+ }
60
+ function decryptChunk(encKey, payload, fileId) {
61
+ if (payload.length < NONCE_LENGTH + 16) {
62
+ throw new Error("Chunk payload too short");
63
+ }
64
+ const nonce = payload.slice(0, NONCE_LENGTH);
65
+ const ciphertext = payload.slice(NONCE_LENGTH);
66
+ const aad = buildAAD(fileId);
67
+ const cipher = (0, import_chacha.xchacha20poly1305)(encKey, nonce, aad);
68
+ try {
69
+ return cipher.decrypt(ciphertext);
70
+ } catch {
71
+ throw new Error("Chunk authentication failed");
72
+ }
73
+ }
74
+ function bytesToHex(bytes) {
75
+ let hex = "";
76
+ for (let i = 0; i < bytes.length; i++) {
77
+ hex += bytes[i].toString(16).padStart(2, "0");
78
+ }
79
+ return hex;
80
+ }
81
+
82
+ // src/crypto/chunking.ts
54
83
  var DEFAULT_MAX_CHUNK_SIZE = 65536;
55
84
  function chunkByParagraph(text, maxSize = DEFAULT_MAX_CHUNK_SIZE) {
56
85
  const normalized = text.replace(/\r\n/g, "\n");
@@ -127,12 +156,7 @@ function splitAtByteLimit(text, maxSize) {
127
156
  return parts;
128
157
  }
129
158
 
130
- // src/kdf.ts
131
- var import_hkdf = require("@noble/hashes/hkdf");
132
- var import_sha256 = require("@noble/hashes/sha256");
133
- var import_scrypt = require("@noble/hashes/scrypt");
134
-
135
- // src/crypto-utils.ts
159
+ // src/crypto/crypto-utils.ts
136
160
  function constantTimeEqual(a, b) {
137
161
  if (a.length !== b.length) return false;
138
162
  let diff = 0;
@@ -147,85 +171,30 @@ function zeroize(...arrays) {
147
171
  }
148
172
  }
149
173
 
150
- // src/kdf.ts
151
- var ENC_INFO = new TextEncoder().encode("mdenc-v1-enc");
152
- var HDR_INFO = new TextEncoder().encode("mdenc-v1-hdr");
153
- var NONCE_INFO = new TextEncoder().encode("mdenc-v1-nonce");
154
- function normalizePassword(password) {
155
- const normalized = password.normalize("NFKC");
156
- return new TextEncoder().encode(normalized);
157
- }
158
- function deriveMasterKey(password, salt, params = DEFAULT_SCRYPT_PARAMS) {
159
- const passwordBytes = normalizePassword(password);
160
- try {
161
- return (0, import_scrypt.scrypt)(passwordBytes, salt, {
162
- N: params.N,
163
- r: params.r,
164
- p: params.p,
165
- dkLen: 32
166
- });
167
- } finally {
168
- zeroize(passwordBytes);
169
- }
170
- }
171
- function deriveKeys(masterKey) {
172
- const encKey = (0, import_hkdf.hkdf)(import_sha256.sha256, masterKey, void 0, ENC_INFO, 32);
173
- const headerKey = (0, import_hkdf.hkdf)(import_sha256.sha256, masterKey, void 0, HDR_INFO, 32);
174
- const nonceKey = (0, import_hkdf.hkdf)(import_sha256.sha256, masterKey, void 0, NONCE_INFO, 32);
175
- return { encKey, headerKey, nonceKey };
176
- }
177
-
178
- // src/aead.ts
179
- var import_chacha = require("@noble/ciphers/chacha");
180
- var import_hmac = require("@noble/hashes/hmac");
174
+ // src/crypto/header.ts
175
+ var import_webcrypto = require("@noble/ciphers/webcrypto");
176
+ var import_hmac2 = require("@noble/hashes/hmac");
181
177
  var import_sha2562 = require("@noble/hashes/sha256");
182
- var NONCE_LENGTH = 24;
183
- function buildAAD(fileId) {
184
- const fileIdHex = bytesToHex(fileId);
185
- const aadString = `mdenc:v1
186
- ${fileIdHex}`;
187
- return new TextEncoder().encode(aadString);
188
- }
189
- function deriveNonce(nonceKey, plaintext) {
190
- const full = (0, import_hmac.hmac)(import_sha2562.sha256, nonceKey, plaintext);
191
- return full.slice(0, NONCE_LENGTH);
192
- }
193
- function encryptChunk(encKey, nonceKey, plaintext, fileId) {
194
- const nonce = deriveNonce(nonceKey, plaintext);
195
- const aad = buildAAD(fileId);
196
- const cipher = (0, import_chacha.xchacha20poly1305)(encKey, nonce, aad);
197
- const ciphertext = cipher.encrypt(plaintext);
198
- const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);
199
- result.set(nonce, 0);
200
- result.set(ciphertext, NONCE_LENGTH);
201
- return result;
202
- }
203
- function decryptChunk(encKey, payload, fileId) {
204
- if (payload.length < NONCE_LENGTH + 16) {
205
- throw new Error("Chunk payload too short");
206
- }
207
- const nonce = payload.slice(0, NONCE_LENGTH);
208
- const ciphertext = payload.slice(NONCE_LENGTH);
209
- const aad = buildAAD(fileId);
210
- const cipher = (0, import_chacha.xchacha20poly1305)(encKey, nonce, aad);
211
- try {
212
- return cipher.decrypt(ciphertext);
213
- } catch {
214
- throw new Error("Chunk authentication failed");
215
- }
216
- }
217
- function bytesToHex(bytes) {
218
- let hex = "";
219
- for (let i = 0; i < bytes.length; i++) {
220
- hex += bytes[i].toString(16).padStart(2, "0");
221
- }
222
- return hex;
223
- }
224
178
 
225
- // src/header.ts
226
- var import_hmac2 = require("@noble/hashes/hmac");
227
- var import_sha2563 = require("@noble/hashes/sha256");
228
- var import_webcrypto = require("@noble/ciphers/webcrypto");
179
+ // src/crypto/types.ts
180
+ var DEFAULT_SCRYPT_PARAMS = {
181
+ N: 16384,
182
+ r: 8,
183
+ p: 1
184
+ };
185
+ var SCRYPT_BOUNDS = {
186
+ N: { min: 1024, max: 1048576 },
187
+ // 2^10 – 2^20
188
+ r: { min: 1, max: 64 },
189
+ p: { min: 1, max: 16 }
190
+ };
191
+ var ChunkingStrategy = /* @__PURE__ */ ((ChunkingStrategy2) => {
192
+ ChunkingStrategy2["Paragraph"] = "paragraph";
193
+ ChunkingStrategy2["FixedSize"] = "fixed-size";
194
+ return ChunkingStrategy2;
195
+ })(ChunkingStrategy || {});
196
+
197
+ // src/crypto/header.ts
229
198
  function generateSalt() {
230
199
  return (0, import_webcrypto.randomBytes)(16);
231
200
  }
@@ -243,15 +212,16 @@ function parseHeader(line) {
243
212
  throw new Error("Invalid header: missing mdenc:v1 prefix");
244
213
  }
245
214
  const saltMatch = line.match(/salt_b64=([A-Za-z0-9+/=]+)/);
246
- if (!saltMatch) throw new Error("Invalid header: missing salt_b64");
215
+ if (!saltMatch?.[1]) throw new Error("Invalid header: missing salt_b64");
247
216
  const salt = fromBase64(saltMatch[1]);
248
217
  if (salt.length !== 16) throw new Error("Invalid header: salt must be 16 bytes");
249
218
  const fileIdMatch = line.match(/file_id_b64=([A-Za-z0-9+/=]+)/);
250
- if (!fileIdMatch) throw new Error("Invalid header: missing file_id_b64");
219
+ if (!fileIdMatch?.[1]) throw new Error("Invalid header: missing file_id_b64");
251
220
  const fileId = fromBase64(fileIdMatch[1]);
252
221
  if (fileId.length !== 16) throw new Error("Invalid header: file_id must be 16 bytes");
253
222
  const scryptMatch = line.match(/scrypt=N=(\d+),r=(\d+),p=(\d+)/);
254
- if (!scryptMatch) throw new Error("Invalid header: missing scrypt parameters");
223
+ if (!scryptMatch?.[1] || !scryptMatch[2] || !scryptMatch[3])
224
+ throw new Error("Invalid header: missing scrypt parameters");
255
225
  const scryptParams = {
256
226
  N: parseInt(scryptMatch[1], 10),
257
227
  r: parseInt(scryptMatch[2], 10),
@@ -277,20 +247,60 @@ function validateScryptParams(params) {
277
247
  }
278
248
  function authenticateHeader(headerKey, headerLine) {
279
249
  const headerBytes = new TextEncoder().encode(headerLine);
280
- return (0, import_hmac2.hmac)(import_sha2563.sha256, headerKey, headerBytes);
250
+ return (0, import_hmac2.hmac)(import_sha2562.sha256, headerKey, headerBytes);
281
251
  }
282
252
  function verifyHeader(headerKey, headerLine, hmacBytes) {
283
253
  const computed = authenticateHeader(headerKey, headerLine);
284
254
  return constantTimeEqual(computed, hmacBytes);
285
255
  }
286
256
  function toBase64(bytes) {
287
- return Buffer.from(bytes).toString("base64");
257
+ let binary = "";
258
+ for (let i = 0; i < bytes.length; i++) {
259
+ binary += String.fromCharCode(bytes[i]);
260
+ }
261
+ return btoa(binary);
288
262
  }
289
263
  function fromBase64(b64) {
290
- return new Uint8Array(Buffer.from(b64, "base64"));
264
+ const binary = atob(b64);
265
+ const bytes = new Uint8Array(binary.length);
266
+ for (let i = 0; i < binary.length; i++) {
267
+ bytes[i] = binary.charCodeAt(i);
268
+ }
269
+ return bytes;
270
+ }
271
+
272
+ // src/crypto/kdf.ts
273
+ var import_hkdf = require("@noble/hashes/hkdf");
274
+ var import_scrypt = require("@noble/hashes/scrypt");
275
+ var import_sha2563 = require("@noble/hashes/sha256");
276
+ var ENC_INFO = new TextEncoder().encode("mdenc-v1-enc");
277
+ var HDR_INFO = new TextEncoder().encode("mdenc-v1-hdr");
278
+ var NONCE_INFO = new TextEncoder().encode("mdenc-v1-nonce");
279
+ function normalizePassword(password) {
280
+ const normalized = password.normalize("NFKC");
281
+ return new TextEncoder().encode(normalized);
282
+ }
283
+ function deriveMasterKey(password, salt, params = DEFAULT_SCRYPT_PARAMS) {
284
+ const passwordBytes = normalizePassword(password);
285
+ try {
286
+ return (0, import_scrypt.scrypt)(passwordBytes, salt, {
287
+ N: params.N,
288
+ r: params.r,
289
+ p: params.p,
290
+ dkLen: 32
291
+ });
292
+ } finally {
293
+ zeroize(passwordBytes);
294
+ }
295
+ }
296
+ function deriveKeys(masterKey) {
297
+ const encKey = (0, import_hkdf.hkdf)(import_sha2563.sha256, masterKey, void 0, ENC_INFO, 32);
298
+ const headerKey = (0, import_hkdf.hkdf)(import_sha2563.sha256, masterKey, void 0, HDR_INFO, 32);
299
+ const nonceKey = (0, import_hkdf.hkdf)(import_sha2563.sha256, masterKey, void 0, NONCE_INFO, 32);
300
+ return { encKey, headerKey, nonceKey };
291
301
  }
292
302
 
293
- // src/encrypt.ts
303
+ // src/crypto/encrypt.ts
294
304
  async function encrypt(plaintext, password, options) {
295
305
  const chunking = options?.chunking ?? "paragraph" /* Paragraph */;
296
306
  const maxChunkSize = options?.maxChunkSize ?? 65536;
@@ -327,7 +337,9 @@ async function encrypt(plaintext, password, options) {
327
337
  const payload = encryptChunk(encKey, nonceKey, chunkBytes, fileId);
328
338
  chunkLines.push(toBase64(payload));
329
339
  }
330
- const sealInput = headerLine + "\n" + headerAuthLine + "\n" + chunkLines.join("\n");
340
+ const sealInput = `${headerLine}
341
+ ${headerAuthLine}
342
+ ${chunkLines.join("\n")}`;
331
343
  const sealData = new TextEncoder().encode(sealInput);
332
344
  const sealHmac = (0, import_hmac3.hmac)(import_sha2564.sha256, headerKey, sealData);
333
345
  const sealLine = `seal_b64=${toBase64(sealHmac)}`;
@@ -348,7 +360,7 @@ async function decrypt(fileContent, password) {
348
360
  const header = parseHeader(headerLine);
349
361
  const authLine = lines[1];
350
362
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
351
- if (!authMatch) {
363
+ if (!authMatch?.[1]) {
352
364
  throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
353
365
  }
354
366
  const headerHmac = fromBase64(authMatch[1]);
@@ -367,10 +379,13 @@ async function decrypt(fileContent, password) {
367
379
  if (chunkLines.length === 0) {
368
380
  throw new Error("Invalid mdenc file: no chunk lines");
369
381
  }
370
- const sealMatch = remaining[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
371
- if (!sealMatch) throw new Error("Invalid mdenc file: malformed seal line");
382
+ const sealLine = remaining[sealIndex];
383
+ const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
384
+ if (!sealMatch?.[1]) throw new Error("Invalid mdenc file: malformed seal line");
372
385
  const storedSealHmac = fromBase64(sealMatch[1]);
373
- const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
386
+ const sealInput = `${headerLine}
387
+ ${authLine}
388
+ ${chunkLines.join("\n")}`;
374
389
  const sealData = new TextEncoder().encode(sealInput);
375
390
  const computedSealHmac = (0, import_hmac3.hmac)(import_sha2564.sha256, headerKey, sealData);
376
391
  if (!constantTimeEqual(computedSealHmac, storedSealHmac)) {
@@ -396,22 +411,22 @@ function parsePreviousFileHeader(fileContent, password) {
396
411
  const header = parseHeader(headerLine);
397
412
  const authLine = lines[1];
398
413
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
399
- if (!authMatch) return void 0;
414
+ if (!authMatch?.[1]) return void 0;
400
415
  const headerHmac = fromBase64(authMatch[1]);
401
416
  const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
402
- const { headerKey } = deriveKeys(masterKey);
417
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
403
418
  if (!verifyHeader(headerKey, headerLine, headerHmac)) {
404
- zeroize(masterKey, headerKey);
419
+ zeroize(masterKey, encKey, headerKey, nonceKey);
405
420
  return void 0;
406
421
  }
407
- zeroize(headerKey);
422
+ zeroize(encKey, headerKey, nonceKey);
408
423
  return { salt: header.salt, fileId: header.fileId, masterKey };
409
424
  } catch {
410
425
  return void 0;
411
426
  }
412
427
  }
413
428
 
414
- // src/seal.ts
429
+ // src/crypto/seal.ts
415
430
  var import_hmac4 = require("@noble/hashes/hmac");
416
431
  var import_sha2565 = require("@noble/hashes/sha256");
417
432
  async function verifySeal(fileContent, password) {
@@ -422,10 +437,10 @@ async function verifySeal(fileContent, password) {
422
437
  const header = parseHeader(headerLine);
423
438
  const authLine = lines[1];
424
439
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
425
- if (!authMatch) throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
440
+ if (!authMatch?.[1]) throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
426
441
  const headerHmac = fromBase64(authMatch[1]);
427
442
  const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
428
- const { headerKey, nonceKey } = deriveKeys(masterKey);
443
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
429
444
  try {
430
445
  if (!verifyHeader(headerKey, headerLine, headerHmac)) {
431
446
  throw new Error("Header authentication failed");
@@ -436,15 +451,18 @@ async function verifySeal(fileContent, password) {
436
451
  throw new Error("File is not sealed: no seal_b64 line found");
437
452
  }
438
453
  const chunkLines = chunkAndSealLines.slice(0, sealIndex);
439
- const sealMatch = chunkAndSealLines[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
440
- if (!sealMatch) throw new Error("Invalid seal line");
454
+ const sealLine = chunkAndSealLines[sealIndex];
455
+ const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
456
+ if (!sealMatch?.[1]) throw new Error("Invalid seal line");
441
457
  const storedHmac = fromBase64(sealMatch[1]);
442
- const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
458
+ const sealInput = `${headerLine}
459
+ ${authLine}
460
+ ${chunkLines.join("\n")}`;
443
461
  const sealData = new TextEncoder().encode(sealInput);
444
462
  const computed = (0, import_hmac4.hmac)(import_sha2565.sha256, headerKey, sealData);
445
463
  return constantTimeEqual(computed, storedHmac);
446
464
  } finally {
447
- zeroize(masterKey, headerKey, nonceKey);
465
+ zeroize(masterKey, encKey, headerKey, nonceKey);
448
466
  }
449
467
  }
450
468
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/encrypt.ts","../src/chunking.ts","../src/kdf.ts","../src/crypto-utils.ts","../src/aead.ts","../src/header.ts","../src/seal.ts"],"sourcesContent":["export type {\n ScryptParams,\n MdencHeader,\n MdencChunk,\n MdencFile,\n EncryptOptions,\n DecryptOptions,\n} from './types.js';\nexport { DEFAULT_SCRYPT_PARAMS, ChunkingStrategy } from './types.js';\nexport { encrypt, decrypt } from './encrypt.js';\nexport { verifySeal } from './seal.js';\n","export interface ScryptParams {\n N: number; // CPU/memory cost (default 16384 = 2^14, ~16 MiB with r=8)\n r: number; // block size (default 8)\n p: number; // parallelism (default 1)\n}\n\nexport const DEFAULT_SCRYPT_PARAMS: ScryptParams = {\n N: 16384,\n r: 8,\n p: 1,\n};\n\nexport const SCRYPT_BOUNDS = {\n N: { min: 1024, max: 1048576 }, // 2^10 – 2^20\n r: { min: 1, max: 64 },\n p: { min: 1, max: 16 },\n} as const;\n\nexport interface MdencHeader {\n version: 'v1';\n salt: Uint8Array; // 16 bytes\n fileId: Uint8Array; // 16 bytes\n scrypt: ScryptParams;\n}\n\nexport interface MdencChunk {\n payload: Uint8Array; // nonce || ciphertext || tag\n}\n\nexport interface MdencFile {\n header: MdencHeader;\n headerLine: string;\n headerHmac: Uint8Array;\n chunks: MdencChunk[];\n sealHmac: Uint8Array; // file-level HMAC\n}\n\nexport enum ChunkingStrategy {\n Paragraph = 'paragraph',\n FixedSize = 'fixed-size',\n}\n\nexport interface EncryptOptions {\n chunking?: ChunkingStrategy;\n maxChunkSize?: number; // bytes, default 65536 (64 KiB)\n fixedChunkSize?: number; // bytes, for fixed-size chunking\n scrypt?: ScryptParams;\n previousFile?: string; // previous encrypted file content for ciphertext reuse\n}\n\nexport interface DecryptOptions {\n // Reserved for future options\n}\n","import { hmac } from '@noble/hashes/hmac';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { chunkByParagraph, chunkByFixedSize } from './chunking.js';\nimport { deriveMasterKey, deriveKeys } from './kdf.js';\nimport { encryptChunk, decryptChunk } from './aead.js';\nimport {\n serializeHeader,\n parseHeader,\n authenticateHeader,\n verifyHeader,\n generateSalt,\n generateFileId,\n toBase64,\n fromBase64,\n} from './header.js';\nimport { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS } from './types.js';\nimport type { EncryptOptions, MdencHeader } from './types.js';\nimport { constantTimeEqual, zeroize } from './crypto-utils.js';\n\nexport async function encrypt(\n plaintext: string,\n password: string,\n options?: EncryptOptions,\n): Promise<string> {\n const chunking = options?.chunking ?? ChunkingStrategy.Paragraph;\n const maxChunkSize = options?.maxChunkSize ?? 65536;\n const scryptParams = options?.scrypt ?? DEFAULT_SCRYPT_PARAMS;\n\n // Chunk the plaintext\n let chunks: string[];\n if (chunking === ChunkingStrategy.FixedSize) {\n const fixedSize = options?.fixedChunkSize ?? 4096;\n chunks = chunkByFixedSize(plaintext, fixedSize);\n } else {\n chunks = chunkByParagraph(plaintext, maxChunkSize);\n }\n\n // If previousFile provided, extract salt/fileId/keys from its header to avoid\n // deriving the same master key twice (same password + same salt).\n let salt: Uint8Array;\n let fileId: Uint8Array;\n let masterKey: Uint8Array;\n\n const prev = options?.previousFile\n ? parsePreviousFileHeader(options.previousFile, password)\n : undefined;\n\n if (prev) {\n salt = prev.salt;\n fileId = prev.fileId;\n masterKey = prev.masterKey;\n } else {\n salt = generateSalt();\n fileId = generateFileId();\n masterKey = deriveMasterKey(password, salt, scryptParams);\n }\n\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Build header\n const header: MdencHeader = { version: 'v1', salt, fileId, scrypt: scryptParams };\n const headerLine = serializeHeader(header);\n const headerHmac = authenticateHeader(headerKey, headerLine);\n const headerAuthLine = `hdrauth_b64=${toBase64(headerHmac)}`;\n\n // Encrypt chunks — deterministic encryption handles reuse automatically\n const chunkLines: string[] = [];\n for (const chunkText of chunks) {\n const chunkBytes = new TextEncoder().encode(chunkText);\n const payload = encryptChunk(encKey, nonceKey, chunkBytes, fileId);\n chunkLines.push(toBase64(payload));\n }\n\n // Compute seal HMAC over header + auth + chunk lines\n const sealInput = headerLine + '\\n' + headerAuthLine + '\\n' + chunkLines.join('\\n');\n const sealData = new TextEncoder().encode(sealInput);\n const sealHmac = hmac(sha256, headerKey, sealData);\n const sealLine = `seal_b64=${toBase64(sealHmac)}`;\n\n return [headerLine, headerAuthLine, ...chunkLines, sealLine, ''].join('\\n');\n } finally {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n }\n}\n\nexport async function decrypt(\n fileContent: string,\n password: string,\n): Promise<string> {\n const lines = fileContent.split('\\n');\n\n // Remove trailing empty line if present\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n if (lines.length < 3) {\n throw new Error('Invalid mdenc file: too few lines');\n }\n\n // Parse header\n const headerLine = lines[0];\n const header = parseHeader(headerLine);\n\n // Parse header auth\n const authLine = lines[1];\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch) {\n throw new Error('Invalid mdenc file: missing hdrauth_b64 line');\n }\n const headerHmac = fromBase64(authMatch[1]);\n\n // Derive keys\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Verify header HMAC\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n throw new Error('Header authentication failed (wrong password or tampered header)');\n }\n\n // Collect chunk lines and seal line\n const remaining = lines.slice(2);\n const sealIndex = remaining.findIndex(l => l.startsWith('seal_b64='));\n if (sealIndex < 0) {\n throw new Error('Invalid mdenc file: missing seal');\n }\n\n const chunkLines = remaining.slice(0, sealIndex);\n if (chunkLines.length === 0) {\n throw new Error('Invalid mdenc file: no chunk lines');\n }\n\n // Verify seal HMAC\n const sealMatch = remaining[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);\n if (!sealMatch) throw new Error('Invalid mdenc file: malformed seal line');\n const storedSealHmac = fromBase64(sealMatch[1]);\n\n const sealInput = headerLine + '\\n' + authLine + '\\n' + chunkLines.join('\\n');\n const sealData = new TextEncoder().encode(sealInput);\n const computedSealHmac = hmac(sha256, headerKey, sealData);\n if (!constantTimeEqual(computedSealHmac, storedSealHmac)) {\n throw new Error('Seal verification failed (file tampered or chunks reordered)');\n }\n\n // Decrypt chunks\n const plaintextParts: string[] = [];\n for (const line of chunkLines) {\n const payload = fromBase64(line);\n const decrypted = decryptChunk(encKey, payload, header.fileId);\n plaintextParts.push(new TextDecoder().decode(decrypted));\n }\n\n return plaintextParts.join('');\n } finally {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n }\n}\n\nfunction parsePreviousFileHeader(\n fileContent: string,\n password: string,\n): { salt: Uint8Array; fileId: Uint8Array; masterKey: Uint8Array } | undefined {\n try {\n const lines = fileContent.split('\\n');\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n if (lines.length < 3) return undefined;\n\n const headerLine = lines[0];\n const header = parseHeader(headerLine);\n\n // Parse and verify header HMAC before trusting\n const authLine = lines[1];\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch) return undefined;\n const headerHmac = fromBase64(authMatch[1]);\n\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { headerKey } = deriveKeys(masterKey);\n\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n zeroize(masterKey, headerKey);\n return undefined;\n }\n\n zeroize(headerKey);\n // Return masterKey for reuse — same password + same salt produces the same key,\n // so the caller can skip a redundant scrypt derivation.\n return { salt: header.salt, fileId: header.fileId, masterKey };\n } catch {\n return undefined;\n }\n}\n","const DEFAULT_MAX_CHUNK_SIZE = 65536; // 64 KiB\n\nexport function chunkByParagraph(text: string, maxSize = DEFAULT_MAX_CHUNK_SIZE): string[] {\n // Normalize line endings\n const normalized = text.replace(/\\r\\n/g, '\\n');\n\n if (normalized.length === 0) {\n return [''];\n }\n\n // Split on runs of 2+ newlines, attaching each boundary to the preceding chunk\n const chunks: string[] = [];\n const boundary = /\\n{2,}/g;\n let lastEnd = 0;\n let match: RegExpExecArray | null;\n\n while ((match = boundary.exec(normalized)) !== null) {\n // Content up to and including the boundary goes to the preceding chunk\n const chunkEnd = match.index + match[0].length;\n chunks.push(normalized.slice(lastEnd, chunkEnd));\n lastEnd = chunkEnd;\n }\n\n // Remaining content after the last boundary (or the entire string if no boundary)\n if (lastEnd < normalized.length) {\n chunks.push(normalized.slice(lastEnd));\n } else if (chunks.length === 0) {\n // No boundaries found and nothing remaining — shouldn't happen since we checked length > 0\n chunks.push(normalized);\n }\n\n // Split any oversized chunks at byte boundaries\n const result: string[] = [];\n for (const chunk of chunks) {\n if (byteLength(chunk) <= maxSize) {\n result.push(chunk);\n } else {\n result.push(...splitAtByteLimit(chunk, maxSize));\n }\n }\n\n return result;\n}\n\nexport function chunkByFixedSize(text: string, size: number): string[] {\n const normalized = text.replace(/\\r\\n/g, '\\n');\n\n if (normalized.length === 0) {\n return [''];\n }\n\n const bytes = new TextEncoder().encode(normalized);\n if (bytes.length <= size) {\n return [normalized];\n }\n\n const chunks: string[] = [];\n const decoder = new TextDecoder();\n let offset = 0;\n while (offset < bytes.length) {\n const end = Math.min(offset + size, bytes.length);\n // Avoid splitting in the middle of a multi-byte UTF-8 character\n let adjusted = end;\n if (adjusted < bytes.length) {\n while (adjusted > offset && (bytes[adjusted] & 0xc0) === 0x80) {\n adjusted--;\n }\n }\n chunks.push(decoder.decode(bytes.slice(offset, adjusted)));\n offset = adjusted;\n }\n\n return chunks;\n}\n\nfunction byteLength(s: string): number {\n return new TextEncoder().encode(s).length;\n}\n\nfunction splitAtByteLimit(text: string, maxSize: number): string[] {\n const bytes = new TextEncoder().encode(text);\n const decoder = new TextDecoder();\n const parts: string[] = [];\n let offset = 0;\n while (offset < bytes.length) {\n let end = Math.min(offset + maxSize, bytes.length);\n // Avoid splitting multi-byte characters\n if (end < bytes.length) {\n while (end > offset && (bytes[end] & 0xc0) === 0x80) {\n end--;\n }\n }\n parts.push(decoder.decode(bytes.slice(offset, end)));\n offset = end;\n }\n return parts;\n}\n","import { hkdf } from '@noble/hashes/hkdf';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { scrypt } from '@noble/hashes/scrypt';\nimport type { ScryptParams } from './types.js';\nimport { DEFAULT_SCRYPT_PARAMS } from './types.js';\nimport { zeroize } from './crypto-utils.js';\n\nconst ENC_INFO = new TextEncoder().encode('mdenc-v1-enc');\nconst HDR_INFO = new TextEncoder().encode('mdenc-v1-hdr');\nconst NONCE_INFO = new TextEncoder().encode('mdenc-v1-nonce');\n\nexport function normalizePassword(password: string): Uint8Array {\n const normalized = password.normalize('NFKC');\n return new TextEncoder().encode(normalized);\n}\n\nexport function deriveMasterKey(\n password: string,\n salt: Uint8Array,\n params: ScryptParams = DEFAULT_SCRYPT_PARAMS,\n): Uint8Array {\n const passwordBytes = normalizePassword(password);\n try {\n return scrypt(passwordBytes, salt, {\n N: params.N,\n r: params.r,\n p: params.p,\n dkLen: 32,\n });\n } finally {\n zeroize(passwordBytes);\n }\n}\n\nexport function deriveKeys(masterKey: Uint8Array): { encKey: Uint8Array; headerKey: Uint8Array; nonceKey: Uint8Array } {\n const encKey = hkdf(sha256, masterKey, undefined, ENC_INFO, 32);\n const headerKey = hkdf(sha256, masterKey, undefined, HDR_INFO, 32);\n const nonceKey = hkdf(sha256, masterKey, undefined, NONCE_INFO, 32);\n return { encKey, headerKey, nonceKey };\n}\n","export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a[i] ^ b[i];\n }\n return diff === 0;\n}\n\nexport function zeroize(...arrays: Uint8Array[]): void {\n for (const arr of arrays) {\n arr.fill(0);\n }\n}\n","import { xchacha20poly1305 } from '@noble/ciphers/chacha';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha256 } from '@noble/hashes/sha256';\n\nconst NONCE_LENGTH = 24;\n\nexport function buildAAD(fileId: Uint8Array): Uint8Array {\n const fileIdHex = bytesToHex(fileId);\n const aadString = `mdenc:v1\\n${fileIdHex}`;\n return new TextEncoder().encode(aadString);\n}\n\nexport function deriveNonce(nonceKey: Uint8Array, plaintext: Uint8Array): Uint8Array {\n const full = hmac(sha256, nonceKey, plaintext);\n return full.slice(0, NONCE_LENGTH);\n}\n\nexport function encryptChunk(\n encKey: Uint8Array,\n nonceKey: Uint8Array,\n plaintext: Uint8Array,\n fileId: Uint8Array,\n): Uint8Array {\n const nonce = deriveNonce(nonceKey, plaintext);\n const aad = buildAAD(fileId);\n const cipher = xchacha20poly1305(encKey, nonce, aad);\n const ciphertext = cipher.encrypt(plaintext);\n // Output: nonce || ciphertext || tag (tag is appended by noble)\n const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);\n result.set(nonce, 0);\n result.set(ciphertext, NONCE_LENGTH);\n return result;\n}\n\nexport function decryptChunk(\n encKey: Uint8Array,\n payload: Uint8Array,\n fileId: Uint8Array,\n): Uint8Array {\n if (payload.length < NONCE_LENGTH + 16) {\n throw new Error('Chunk payload too short');\n }\n const nonce = payload.slice(0, NONCE_LENGTH);\n const ciphertext = payload.slice(NONCE_LENGTH);\n const aad = buildAAD(fileId);\n const cipher = xchacha20poly1305(encKey, nonce, aad);\n try {\n return cipher.decrypt(ciphertext);\n } catch {\n throw new Error('Chunk authentication failed');\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i].toString(16).padStart(2, '0');\n }\n return hex;\n}\n","import { hmac } from '@noble/hashes/hmac';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport type { MdencHeader, ScryptParams } from './types.js';\nimport { SCRYPT_BOUNDS } from './types.js';\nimport { constantTimeEqual } from './crypto-utils.js';\n\nexport function generateSalt(): Uint8Array {\n return randomBytes(16);\n}\n\nexport function generateFileId(): Uint8Array {\n return randomBytes(16);\n}\n\nexport function serializeHeader(header: MdencHeader): string {\n const saltB64 = toBase64(header.salt);\n const fileIdB64 = toBase64(header.fileId);\n const { N, r, p } = header.scrypt;\n return `mdenc:v1 salt_b64=${saltB64} file_id_b64=${fileIdB64} scrypt=N=${N},r=${r},p=${p}`;\n}\n\nexport function parseHeader(line: string): MdencHeader {\n if (!line.startsWith('mdenc:v1 ')) {\n throw new Error('Invalid header: missing mdenc:v1 prefix');\n }\n\n const saltMatch = line.match(/salt_b64=([A-Za-z0-9+/=]+)/);\n if (!saltMatch) throw new Error('Invalid header: missing salt_b64');\n const salt = fromBase64(saltMatch[1]);\n if (salt.length !== 16) throw new Error('Invalid header: salt must be 16 bytes');\n\n const fileIdMatch = line.match(/file_id_b64=([A-Za-z0-9+/=]+)/);\n if (!fileIdMatch) throw new Error('Invalid header: missing file_id_b64');\n const fileId = fromBase64(fileIdMatch[1]);\n if (fileId.length !== 16) throw new Error('Invalid header: file_id must be 16 bytes');\n\n const scryptMatch = line.match(/scrypt=N=(\\d+),r=(\\d+),p=(\\d+)/);\n if (!scryptMatch) throw new Error('Invalid header: missing scrypt parameters');\n const scryptParams: ScryptParams = {\n N: parseInt(scryptMatch[1], 10),\n r: parseInt(scryptMatch[2], 10),\n p: parseInt(scryptMatch[3], 10),\n };\n\n validateScryptParams(scryptParams);\n\n return { version: 'v1', salt, fileId, scrypt: scryptParams };\n}\n\nexport function validateScryptParams(params: ScryptParams): void {\n const { N, r, p } = SCRYPT_BOUNDS;\n if (params.N < N.min || params.N > N.max) {\n throw new Error(`Invalid scrypt N: ${params.N} (must be ${N.min}–${N.max})`);\n }\n if ((params.N & (params.N - 1)) !== 0) {\n throw new Error(`Invalid scrypt N: ${params.N} (must be a power of 2)`);\n }\n if (params.r < r.min || params.r > r.max) {\n throw new Error(`Invalid scrypt r: ${params.r} (must be ${r.min}–${r.max})`);\n }\n if (params.p < p.min || params.p > p.max) {\n throw new Error(`Invalid scrypt p: ${params.p} (must be ${p.min}–${p.max})`);\n }\n}\n\nexport function authenticateHeader(headerKey: Uint8Array, headerLine: string): Uint8Array {\n const headerBytes = new TextEncoder().encode(headerLine);\n return hmac(sha256, headerKey, headerBytes);\n}\n\nexport function verifyHeader(\n headerKey: Uint8Array,\n headerLine: string,\n hmacBytes: Uint8Array,\n): boolean {\n const computed = authenticateHeader(headerKey, headerLine);\n return constantTimeEqual(computed, hmacBytes);\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\nexport function fromBase64(b64: string): Uint8Array {\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n","import { hmac } from '@noble/hashes/hmac';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { deriveMasterKey, deriveKeys } from './kdf.js';\nimport {\n parseHeader,\n verifyHeader,\n fromBase64,\n} from './header.js';\nimport { constantTimeEqual, zeroize } from './crypto-utils.js';\n\nexport async function verifySeal(\n fileContent: string,\n password: string,\n): Promise<boolean> {\n const lines = fileContent.split('\\n');\n if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();\n if (lines.length < 3) throw new Error('Invalid mdenc file: too few lines');\n\n const headerLine = lines[0];\n const header = parseHeader(headerLine);\n\n // Parse header auth\n const authLine = lines[1];\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch) throw new Error('Invalid mdenc file: missing hdrauth_b64 line');\n const headerHmac = fromBase64(authMatch[1]);\n\n // Derive keys\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Verify header\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n throw new Error('Header authentication failed');\n }\n\n // Find seal line\n const chunkAndSealLines = lines.slice(2);\n const sealIndex = chunkAndSealLines.findIndex(l => l.startsWith('seal_b64='));\n if (sealIndex < 0) {\n throw new Error('File is not sealed: no seal_b64 line found');\n }\n\n const chunkLines = chunkAndSealLines.slice(0, sealIndex);\n const sealMatch = chunkAndSealLines[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);\n if (!sealMatch) throw new Error('Invalid seal line');\n const storedHmac = fromBase64(sealMatch[1]);\n\n // Verify seal HMAC (covers header + auth + chunk lines)\n const sealInput = headerLine + '\\n' + authLine + '\\n' + chunkLines.join('\\n');\n const sealData = new TextEncoder().encode(sealInput);\n const computed = hmac(sha256, headerKey, sealData);\n\n return constantTimeEqual(computed, storedHmac);\n } finally {\n zeroize(masterKey, headerKey, nonceKey);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACMO,IAAM,wBAAsC;AAAA,EACjD,GAAG;AAAA,EACH,GAAG;AAAA,EACH,GAAG;AACL;AAEO,IAAM,gBAAgB;AAAA,EAC3B,GAAG,EAAE,KAAK,MAAM,KAAK,QAAQ;AAAA;AAAA,EAC7B,GAAG,EAAE,KAAK,GAAG,KAAK,GAAG;AAAA,EACrB,GAAG,EAAE,KAAK,GAAG,KAAK,GAAG;AACvB;AAq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AW,UAAU,CAAC,CAAC;AAG1C,QAAM,YAAY,gBAAgB,UAAU,OAAO,MAAM,OAAO,MAAM;AACtE,QAAM,EAAE,WAAW,SAAS,IAAI,WAAW,SAAS;AAEpD,MAAI;AAEF,QAAI,CAAC,aAAa,WAAW,YAAY,UAAU,GAAG;AACpD,YAAM,IAAI,MAAM,8BAA8B;AAAA,IAChD;AAGA,UAAM,oBAAoB,MAAM,MAAM,CAAC;AACvC,UAAM,YAAY,kBAAkB,UAAU,OAAK,EAAE,WAAW,WAAW,CAAC;AAC5E,QAAI,YAAY,GAAG;AACjB,YAAM,IAAI,MAAM,4CAA4C;AAAA,IAC9D;AAEA,UAAM,aAAa,kBAAkB,MAAM,GAAG,SAAS;AACvD,UAAM,YAAY,kBAAkB,SAAS,EAAE,MAAM,8BAA8B;AACnF,QAAI,CAAC,UAAW,OAAM,IAAI,MAAM,mBAAmB;AACnD,UAAM,aAAa,WAAW,UAAU,CAAC,CAAC;AAG1C,UAAM,YAAY,aAAa,OAAO,WAAW,OAAO,WAAW,KAAK,IAAI;AAC5E,UAAM,WAAW,IAAI,YAAY,EAAE,OAAO,SAAS;AACnD,UAAM,eAAW,mBAAK,uBAAQ,WAAW,QAAQ;AAEjD,WAAO,kBAAkB,UAAU,UAAU;AAAA,EAC/C,UAAE;AACA,YAAQ,WAAW,WAAW,QAAQ;AAAA,EACxC;AACF;","names":["ChunkingStrategy","import_hmac","import_sha256","import_sha256","import_hmac","import_sha256","import_hmac","import_sha256"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/crypto/encrypt.ts","../src/crypto/aead.ts","../src/crypto/chunking.ts","../src/crypto/crypto-utils.ts","../src/crypto/header.ts","../src/crypto/types.ts","../src/crypto/kdf.ts","../src/crypto/seal.ts"],"sourcesContent":["export * from \"./crypto/index.js\";\n","import { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { decryptChunk, encryptChunk } from \"./aead.js\";\nimport { chunkByFixedSize, chunkByParagraph } from \"./chunking.js\";\nimport { constantTimeEqual, zeroize } from \"./crypto-utils.js\";\nimport {\n authenticateHeader,\n fromBase64,\n generateFileId,\n generateSalt,\n parseHeader,\n serializeHeader,\n toBase64,\n verifyHeader,\n} from \"./header.js\";\nimport { deriveKeys, deriveMasterKey } from \"./kdf.js\";\nimport type { EncryptOptions, MdencHeader } from \"./types.js\";\nimport { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS } from \"./types.js\";\n\nexport async function encrypt(\n plaintext: string,\n password: string,\n options?: EncryptOptions,\n): Promise<string> {\n const chunking = options?.chunking ?? ChunkingStrategy.Paragraph;\n const maxChunkSize = options?.maxChunkSize ?? 65536;\n const scryptParams = options?.scrypt ?? DEFAULT_SCRYPT_PARAMS;\n\n // Chunk the plaintext\n let chunks: string[];\n if (chunking === ChunkingStrategy.FixedSize) {\n const fixedSize = options?.fixedChunkSize ?? 4096;\n chunks = chunkByFixedSize(plaintext, fixedSize);\n } else {\n chunks = chunkByParagraph(plaintext, maxChunkSize);\n }\n\n // If previousFile provided, extract salt/fileId/keys from its header to avoid\n // deriving the same master key twice (same password + same salt).\n let salt: Uint8Array;\n let fileId: Uint8Array;\n let masterKey: Uint8Array;\n\n const prev = options?.previousFile\n ? parsePreviousFileHeader(options.previousFile, password)\n : undefined;\n\n if (prev) {\n salt = prev.salt;\n fileId = prev.fileId;\n masterKey = prev.masterKey;\n } else {\n salt = generateSalt();\n fileId = generateFileId();\n masterKey = deriveMasterKey(password, salt, scryptParams);\n }\n\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Build header\n const header: MdencHeader = { version: \"v1\", salt, fileId, scrypt: scryptParams };\n const headerLine = serializeHeader(header);\n const headerHmac = authenticateHeader(headerKey, headerLine);\n const headerAuthLine = `hdrauth_b64=${toBase64(headerHmac)}`;\n\n // Encrypt chunks — deterministic encryption handles reuse automatically\n const chunkLines: string[] = [];\n for (const chunkText of chunks) {\n const chunkBytes = new TextEncoder().encode(chunkText);\n const payload = encryptChunk(encKey, nonceKey, chunkBytes, fileId);\n chunkLines.push(toBase64(payload));\n }\n\n // Compute seal HMAC over header + auth + chunk lines\n const sealInput = `${headerLine}\\n${headerAuthLine}\\n${chunkLines.join(\"\\n\")}`;\n const sealData = new TextEncoder().encode(sealInput);\n const sealHmac = hmac(sha256, headerKey, sealData);\n const sealLine = `seal_b64=${toBase64(sealHmac)}`;\n\n return [headerLine, headerAuthLine, ...chunkLines, sealLine, \"\"].join(\"\\n\");\n } finally {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n }\n}\n\nexport async function decrypt(fileContent: string, password: string): Promise<string> {\n const lines = fileContent.split(\"\\n\");\n\n // Remove trailing empty line if present\n if (lines.length > 0 && lines[lines.length - 1] === \"\") {\n lines.pop();\n }\n\n if (lines.length < 3) {\n throw new Error(\"Invalid mdenc file: too few lines\");\n }\n\n // Parse header\n const headerLine = lines[0]!;\n const header = parseHeader(headerLine);\n\n // Parse header auth\n const authLine = lines[1]!;\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch?.[1]) {\n throw new Error(\"Invalid mdenc file: missing hdrauth_b64 line\");\n }\n const headerHmac = fromBase64(authMatch[1]);\n\n // Derive keys\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Verify header HMAC\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n throw new Error(\"Header authentication failed (wrong password or tampered header)\");\n }\n\n // Collect chunk lines and seal line\n const remaining = lines.slice(2);\n const sealIndex = remaining.findIndex((l) => l.startsWith(\"seal_b64=\"));\n if (sealIndex < 0) {\n throw new Error(\"Invalid mdenc file: missing seal\");\n }\n\n const chunkLines = remaining.slice(0, sealIndex);\n if (chunkLines.length === 0) {\n throw new Error(\"Invalid mdenc file: no chunk lines\");\n }\n\n // Verify seal HMAC\n const sealLine = remaining[sealIndex]!;\n const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);\n if (!sealMatch?.[1]) throw new Error(\"Invalid mdenc file: malformed seal line\");\n const storedSealHmac = fromBase64(sealMatch[1]);\n\n const sealInput = `${headerLine}\\n${authLine}\\n${chunkLines.join(\"\\n\")}`;\n const sealData = new TextEncoder().encode(sealInput);\n const computedSealHmac = hmac(sha256, headerKey, sealData);\n if (!constantTimeEqual(computedSealHmac, storedSealHmac)) {\n throw new Error(\"Seal verification failed (file tampered or chunks reordered)\");\n }\n\n // Decrypt chunks\n const plaintextParts: string[] = [];\n for (const line of chunkLines) {\n const payload = fromBase64(line);\n const decrypted = decryptChunk(encKey, payload, header.fileId);\n plaintextParts.push(new TextDecoder().decode(decrypted));\n }\n\n return plaintextParts.join(\"\");\n } finally {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n }\n}\n\nfunction parsePreviousFileHeader(\n fileContent: string,\n password: string,\n): { salt: Uint8Array; fileId: Uint8Array; masterKey: Uint8Array } | undefined {\n try {\n const lines = fileContent.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n if (lines.length < 3) return undefined;\n\n const headerLine = lines[0]!;\n const header = parseHeader(headerLine);\n\n // Parse and verify header HMAC before trusting\n const authLine = lines[1]!;\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch?.[1]) return undefined;\n const headerHmac = fromBase64(authMatch[1]);\n\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n return undefined;\n }\n\n zeroize(encKey, headerKey, nonceKey);\n // Return masterKey for reuse — same password + same salt produces the same key,\n // so the caller can skip a redundant scrypt derivation.\n return { salt: header.salt, fileId: header.fileId, masterKey };\n } catch {\n return undefined;\n }\n}\n","import { xchacha20poly1305 } from \"@noble/ciphers/chacha\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 } from \"@noble/hashes/sha256\";\n\nconst NONCE_LENGTH = 24;\n\nexport function buildAAD(fileId: Uint8Array): Uint8Array {\n const fileIdHex = bytesToHex(fileId);\n const aadString = `mdenc:v1\\n${fileIdHex}`;\n return new TextEncoder().encode(aadString);\n}\n\nexport function deriveNonce(nonceKey: Uint8Array, plaintext: Uint8Array): Uint8Array {\n const full = hmac(sha256, nonceKey, plaintext);\n return full.slice(0, NONCE_LENGTH);\n}\n\nexport function encryptChunk(\n encKey: Uint8Array,\n nonceKey: Uint8Array,\n plaintext: Uint8Array,\n fileId: Uint8Array,\n): Uint8Array {\n const nonce = deriveNonce(nonceKey, plaintext);\n const aad = buildAAD(fileId);\n const cipher = xchacha20poly1305(encKey, nonce, aad);\n const ciphertext = cipher.encrypt(plaintext);\n // Output: nonce || ciphertext || tag (tag is appended by noble)\n const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);\n result.set(nonce, 0);\n result.set(ciphertext, NONCE_LENGTH);\n return result;\n}\n\nexport function decryptChunk(\n encKey: Uint8Array,\n payload: Uint8Array,\n fileId: Uint8Array,\n): Uint8Array {\n if (payload.length < NONCE_LENGTH + 16) {\n throw new Error(\"Chunk payload too short\");\n }\n const nonce = payload.slice(0, NONCE_LENGTH);\n const ciphertext = payload.slice(NONCE_LENGTH);\n const aad = buildAAD(fileId);\n const cipher = xchacha20poly1305(encKey, nonce, aad);\n try {\n return cipher.decrypt(ciphertext);\n } catch {\n throw new Error(\"Chunk authentication failed\");\n }\n}\n\nfunction bytesToHex(bytes: Uint8Array): string {\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n","const DEFAULT_MAX_CHUNK_SIZE = 65536; // 64 KiB\n\nexport function chunkByParagraph(text: string, maxSize = DEFAULT_MAX_CHUNK_SIZE): string[] {\n // Normalize line endings\n const normalized = text.replace(/\\r\\n/g, \"\\n\");\n\n if (normalized.length === 0) {\n return [\"\"];\n }\n\n // Split on runs of 2+ newlines, attaching each boundary to the preceding chunk\n const chunks: string[] = [];\n const boundary = /\\n{2,}/g;\n let lastEnd = 0;\n let match: RegExpExecArray | null;\n\n while ((match = boundary.exec(normalized)) !== null) {\n // Content up to and including the boundary goes to the preceding chunk\n const chunkEnd = match.index + match[0].length;\n chunks.push(normalized.slice(lastEnd, chunkEnd));\n lastEnd = chunkEnd;\n }\n\n // Remaining content after the last boundary (or the entire string if no boundary)\n if (lastEnd < normalized.length) {\n chunks.push(normalized.slice(lastEnd));\n } else if (chunks.length === 0) {\n // No boundaries found and nothing remaining — shouldn't happen since we checked length > 0\n chunks.push(normalized);\n }\n\n // Split any oversized chunks at byte boundaries\n const result: string[] = [];\n for (const chunk of chunks) {\n if (byteLength(chunk) <= maxSize) {\n result.push(chunk);\n } else {\n result.push(...splitAtByteLimit(chunk, maxSize));\n }\n }\n\n return result;\n}\n\nexport function chunkByFixedSize(text: string, size: number): string[] {\n const normalized = text.replace(/\\r\\n/g, \"\\n\");\n\n if (normalized.length === 0) {\n return [\"\"];\n }\n\n const bytes = new TextEncoder().encode(normalized);\n if (bytes.length <= size) {\n return [normalized];\n }\n\n const chunks: string[] = [];\n const decoder = new TextDecoder();\n let offset = 0;\n while (offset < bytes.length) {\n const end = Math.min(offset + size, bytes.length);\n // Avoid splitting in the middle of a multi-byte UTF-8 character\n let adjusted = end;\n if (adjusted < bytes.length) {\n while (adjusted > offset && (bytes[adjusted]! & 0xc0) === 0x80) {\n adjusted--;\n }\n }\n chunks.push(decoder.decode(bytes.slice(offset, adjusted)));\n offset = adjusted;\n }\n\n return chunks;\n}\n\nfunction byteLength(s: string): number {\n return new TextEncoder().encode(s).length;\n}\n\nfunction splitAtByteLimit(text: string, maxSize: number): string[] {\n const bytes = new TextEncoder().encode(text);\n const decoder = new TextDecoder();\n const parts: string[] = [];\n let offset = 0;\n while (offset < bytes.length) {\n let end = Math.min(offset + maxSize, bytes.length);\n // Avoid splitting multi-byte characters\n if (end < bytes.length) {\n while (end > offset && (bytes[end]! & 0xc0) === 0x80) {\n end--;\n }\n }\n parts.push(decoder.decode(bytes.slice(offset, end)));\n offset = end;\n }\n return parts;\n}\n","export function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) {\n diff |= a[i]! ^ b[i]!;\n }\n return diff === 0;\n}\n\nexport function zeroize(...arrays: Uint8Array[]): void {\n for (const arr of arrays) {\n arr.fill(0);\n }\n}\n","import { randomBytes } from \"@noble/ciphers/webcrypto\";\nimport { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { constantTimeEqual } from \"./crypto-utils.js\";\nimport type { MdencHeader, ScryptParams } from \"./types.js\";\nimport { SCRYPT_BOUNDS } from \"./types.js\";\n\nexport function generateSalt(): Uint8Array {\n return randomBytes(16);\n}\n\nexport function generateFileId(): Uint8Array {\n return randomBytes(16);\n}\n\nexport function serializeHeader(header: MdencHeader): string {\n const saltB64 = toBase64(header.salt);\n const fileIdB64 = toBase64(header.fileId);\n const { N, r, p } = header.scrypt;\n return `mdenc:v1 salt_b64=${saltB64} file_id_b64=${fileIdB64} scrypt=N=${N},r=${r},p=${p}`;\n}\n\nexport function parseHeader(line: string): MdencHeader {\n if (!line.startsWith(\"mdenc:v1 \")) {\n throw new Error(\"Invalid header: missing mdenc:v1 prefix\");\n }\n\n const saltMatch = line.match(/salt_b64=([A-Za-z0-9+/=]+)/);\n if (!saltMatch?.[1]) throw new Error(\"Invalid header: missing salt_b64\");\n const salt = fromBase64(saltMatch[1]);\n if (salt.length !== 16) throw new Error(\"Invalid header: salt must be 16 bytes\");\n\n const fileIdMatch = line.match(/file_id_b64=([A-Za-z0-9+/=]+)/);\n if (!fileIdMatch?.[1]) throw new Error(\"Invalid header: missing file_id_b64\");\n const fileId = fromBase64(fileIdMatch[1]);\n if (fileId.length !== 16) throw new Error(\"Invalid header: file_id must be 16 bytes\");\n\n const scryptMatch = line.match(/scrypt=N=(\\d+),r=(\\d+),p=(\\d+)/);\n if (!scryptMatch?.[1] || !scryptMatch[2] || !scryptMatch[3])\n throw new Error(\"Invalid header: missing scrypt parameters\");\n const scryptParams: ScryptParams = {\n N: parseInt(scryptMatch[1], 10),\n r: parseInt(scryptMatch[2], 10),\n p: parseInt(scryptMatch[3], 10),\n };\n\n validateScryptParams(scryptParams);\n\n return { version: \"v1\", salt, fileId, scrypt: scryptParams };\n}\n\nexport function validateScryptParams(params: ScryptParams): void {\n const { N, r, p } = SCRYPT_BOUNDS;\n if (params.N < N.min || params.N > N.max) {\n throw new Error(`Invalid scrypt N: ${params.N} (must be ${N.min}–${N.max})`);\n }\n if ((params.N & (params.N - 1)) !== 0) {\n throw new Error(`Invalid scrypt N: ${params.N} (must be a power of 2)`);\n }\n if (params.r < r.min || params.r > r.max) {\n throw new Error(`Invalid scrypt r: ${params.r} (must be ${r.min}–${r.max})`);\n }\n if (params.p < p.min || params.p > p.max) {\n throw new Error(`Invalid scrypt p: ${params.p} (must be ${p.min}–${p.max})`);\n }\n}\n\nexport function authenticateHeader(headerKey: Uint8Array, headerLine: string): Uint8Array {\n const headerBytes = new TextEncoder().encode(headerLine);\n return hmac(sha256, headerKey, headerBytes);\n}\n\nexport function verifyHeader(\n headerKey: Uint8Array,\n headerLine: string,\n hmacBytes: Uint8Array,\n): boolean {\n const computed = authenticateHeader(headerKey, headerLine);\n return constantTimeEqual(computed, hmacBytes);\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary);\n}\n\nexport function fromBase64(b64: string): Uint8Array {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n","export interface ScryptParams {\n N: number; // CPU/memory cost (default 16384 = 2^14, ~16 MiB with r=8)\n r: number; // block size (default 8)\n p: number; // parallelism (default 1)\n}\n\nexport const DEFAULT_SCRYPT_PARAMS: ScryptParams = {\n N: 16384,\n r: 8,\n p: 1,\n};\n\nexport const SCRYPT_BOUNDS = {\n N: { min: 1024, max: 1048576 }, // 2^10 – 2^20\n r: { min: 1, max: 64 },\n p: { min: 1, max: 16 },\n} as const;\n\nexport interface MdencHeader {\n version: \"v1\";\n salt: Uint8Array; // 16 bytes\n fileId: Uint8Array; // 16 bytes\n scrypt: ScryptParams;\n}\n\nexport interface MdencChunk {\n payload: Uint8Array; // nonce || ciphertext || tag\n}\n\nexport interface MdencFile {\n header: MdencHeader;\n headerLine: string;\n headerHmac: Uint8Array;\n chunks: MdencChunk[];\n sealHmac: Uint8Array; // file-level HMAC\n}\n\nexport enum ChunkingStrategy {\n Paragraph = \"paragraph\",\n FixedSize = \"fixed-size\",\n}\n\nexport interface EncryptOptions {\n chunking?: ChunkingStrategy;\n maxChunkSize?: number; // bytes, default 65536 (64 KiB)\n fixedChunkSize?: number; // bytes, for fixed-size chunking\n scrypt?: ScryptParams;\n previousFile?: string; // previous encrypted file content for ciphertext reuse\n}\n","import { hkdf } from \"@noble/hashes/hkdf\";\nimport { scrypt } from \"@noble/hashes/scrypt\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { zeroize } from \"./crypto-utils.js\";\nimport type { ScryptParams } from \"./types.js\";\nimport { DEFAULT_SCRYPT_PARAMS } from \"./types.js\";\n\nconst ENC_INFO = new TextEncoder().encode(\"mdenc-v1-enc\");\nconst HDR_INFO = new TextEncoder().encode(\"mdenc-v1-hdr\");\nconst NONCE_INFO = new TextEncoder().encode(\"mdenc-v1-nonce\");\n\nexport function normalizePassword(password: string): Uint8Array {\n const normalized = password.normalize(\"NFKC\");\n return new TextEncoder().encode(normalized);\n}\n\nexport function deriveMasterKey(\n password: string,\n salt: Uint8Array,\n params: ScryptParams = DEFAULT_SCRYPT_PARAMS,\n): Uint8Array {\n const passwordBytes = normalizePassword(password);\n try {\n return scrypt(passwordBytes, salt, {\n N: params.N,\n r: params.r,\n p: params.p,\n dkLen: 32,\n });\n } finally {\n zeroize(passwordBytes);\n }\n}\n\nexport function deriveKeys(masterKey: Uint8Array): {\n encKey: Uint8Array;\n headerKey: Uint8Array;\n nonceKey: Uint8Array;\n} {\n const encKey = hkdf(sha256, masterKey, undefined, ENC_INFO, 32);\n const headerKey = hkdf(sha256, masterKey, undefined, HDR_INFO, 32);\n const nonceKey = hkdf(sha256, masterKey, undefined, NONCE_INFO, 32);\n return { encKey, headerKey, nonceKey };\n}\n","import { hmac } from \"@noble/hashes/hmac\";\nimport { sha256 } from \"@noble/hashes/sha256\";\nimport { constantTimeEqual, zeroize } from \"./crypto-utils.js\";\nimport { fromBase64, parseHeader, verifyHeader } from \"./header.js\";\nimport { deriveKeys, deriveMasterKey } from \"./kdf.js\";\n\nexport async function verifySeal(fileContent: string, password: string): Promise<boolean> {\n const lines = fileContent.split(\"\\n\");\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n if (lines.length < 3) throw new Error(\"Invalid mdenc file: too few lines\");\n\n const headerLine = lines[0]!;\n const header = parseHeader(headerLine);\n\n // Parse header auth\n const authLine = lines[1]!;\n const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);\n if (!authMatch?.[1]) throw new Error(\"Invalid mdenc file: missing hdrauth_b64 line\");\n const headerHmac = fromBase64(authMatch[1]);\n\n // Derive keys\n const masterKey = deriveMasterKey(password, header.salt, header.scrypt);\n const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);\n\n try {\n // Verify header\n if (!verifyHeader(headerKey, headerLine, headerHmac)) {\n throw new Error(\"Header authentication failed\");\n }\n\n // Find seal line\n const chunkAndSealLines = lines.slice(2);\n const sealIndex = chunkAndSealLines.findIndex((l) => l.startsWith(\"seal_b64=\"));\n if (sealIndex < 0) {\n throw new Error(\"File is not sealed: no seal_b64 line found\");\n }\n\n const chunkLines = chunkAndSealLines.slice(0, sealIndex);\n const sealLine = chunkAndSealLines[sealIndex]!;\n const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);\n if (!sealMatch?.[1]) throw new Error(\"Invalid seal line\");\n const storedHmac = fromBase64(sealMatch[1]);\n\n // Verify seal HMAC (covers header + auth + chunk lines)\n const sealInput = `${headerLine}\\n${authLine}\\n${chunkLines.join(\"\\n\")}`;\n const sealData = new TextEncoder().encode(sealInput);\n const computed = hmac(sha256, headerKey, sealData);\n\n return constantTimeEqual(computed, storedHmac);\n } finally {\n zeroize(masterKey, encKey, headerKey, nonceKey);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAAqB;AACrB,IAAAC,iBAAuB;;;ACDvB,oBAAkC;AAClC,kBAAqB;AACrB,oBAAuB;AAEvB,IAAM,eAAe;AAEd,SAAS,SAAS,QAAgC;AACvD,QAAM,YAAY,WAAW,MAAM;AACnC,QAAM,YAAY;AAAA,EAAa,SAAS;AACxC,SAAO,IAAI,YAAY,EAAE,OAAO,SAAS;AAC3C;AAEO,SAAS,YAAY,UAAsB,WAAmC;AACnF,QAAM,WAAO,kBAAK,sBAAQ,UAAU,SAAS;AAC7C,SAAO,KAAK,MAAM,GAAG,YAAY;AACnC;AAEO,SAAS,aACd,QACA,UACA,WACA,QACY;AACZ,QAAM,QAAQ,YAAY,UAAU,SAAS;AAC7C,QAAM,MAAM,SAAS,MAAM;AAC3B,QAAM,aAAS,iCAAkB,QAAQ,OAAO,GAAG;AACnD,QAAM,aAAa,OAAO,QAAQ,SAAS;AAE3C,QAAM,SAAS,IAAI,WAAW,eAAe,WAAW,MAAM;AAC9D,SAAO,IAAI,OAAO,CAAC;AACnB,SAAO,IAAI,YAAY,YAAY;AACnC,SAAO;AACT;AAEO,SAAS,aACd,QACA,SACA,QACY;AACZ,MAAI,QA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M,aAAa,WAAW,UAAU,CAAC,CAAC;AAG1C,QAAM,YAAY,gBAAgB,UAAU,OAAO,MAAM,OAAO,MAAM;AACtE,QAAM,EAAE,QAAQ,WAAW,SAAS,IAAI,WAAW,SAAS;AAE5D,MAAI;AAEF,QAAI,CAAC,aAAa,WAAW,YAAY,UAAU,GAAG;AACpD,YAAM,IAAI,MAAM,8BAA8B;AAAA,IAChD;AAGA,UAAM,oBAAoB,MAAM,MAAM,CAAC;AACvC,UAAM,YAAY,kBAAkB,UAAU,CAAC,MAAM,EAAE,WAAW,WAAW,CAAC;AAC9E,QAAI,YAAY,GAAG;AACjB,YAAM,IAAI,MAAM,4CAA4C;AAAA,IAC9D;AAEA,UAAM,aAAa,kBAAkB,MAAM,GAAG,SAAS;AACvD,UAAM,WAAW,kBAAkB,SAAS;AAC5C,UAAM,YAAY,SAAS,MAAM,8BAA8B;AAC/D,QAAI,CAAC,YAAY,CAAC,EAAG,OAAM,IAAI,MAAM,mBAAmB;AACxD,UAAM,aAAa,WAAW,UAAU,CAAC,CAAC;AAG1C,UAAM,YAAY,GAAG,UAAU;AAAA,EAAK,QAAQ;AAAA,EAAK,WAAW,KAAK,IAAI,CAAC;AACtE,UAAM,WAAW,IAAI,YAAY,EAAE,OAAO,SAAS;AACnD,UAAM,eAAW,mBAAK,uBAAQ,WAAW,QAAQ;AAEjD,WAAO,kBAAkB,UAAU,UAAU;AAAA,EAC/C,UAAE;AACA,YAAQ,WAAW,QAAQ,WAAW,QAAQ;AAAA,EAChD;AACF;","names":["import_hmac","import_sha256","import_hmac","import_sha256","ChunkingStrategy","import_sha256","import_hmac","import_sha256"]}
package/dist/index.d.cts CHANGED
@@ -5,7 +5,7 @@ interface ScryptParams {
5
5
  }
6
6
  declare const DEFAULT_SCRYPT_PARAMS: ScryptParams;
7
7
  interface MdencHeader {
8
- version: 'v1';
8
+ version: "v1";
9
9
  salt: Uint8Array;
10
10
  fileId: Uint8Array;
11
11
  scrypt: ScryptParams;
@@ -31,12 +31,10 @@ interface EncryptOptions {
31
31
  scrypt?: ScryptParams;
32
32
  previousFile?: string;
33
33
  }
34
- interface DecryptOptions {
35
- }
36
34
 
37
35
  declare function encrypt(plaintext: string, password: string, options?: EncryptOptions): Promise<string>;
38
36
  declare function decrypt(fileContent: string, password: string): Promise<string>;
39
37
 
40
38
  declare function verifySeal(fileContent: string, password: string): Promise<boolean>;
41
39
 
42
- export { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS, type DecryptOptions, type EncryptOptions, type MdencChunk, type MdencFile, type MdencHeader, type ScryptParams, decrypt, encrypt, verifySeal };
40
+ export { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS, type EncryptOptions, type MdencChunk, type MdencFile, type MdencHeader, type ScryptParams, decrypt, encrypt, verifySeal };
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ interface ScryptParams {
5
5
  }
6
6
  declare const DEFAULT_SCRYPT_PARAMS: ScryptParams;
7
7
  interface MdencHeader {
8
- version: 'v1';
8
+ version: "v1";
9
9
  salt: Uint8Array;
10
10
  fileId: Uint8Array;
11
11
  scrypt: ScryptParams;
@@ -31,12 +31,10 @@ interface EncryptOptions {
31
31
  scrypt?: ScryptParams;
32
32
  previousFile?: string;
33
33
  }
34
- interface DecryptOptions {
35
- }
36
34
 
37
35
  declare function encrypt(plaintext: string, password: string, options?: EncryptOptions): Promise<string>;
38
36
  declare function decrypt(fileContent: string, password: string): Promise<string>;
39
37
 
40
38
  declare function verifySeal(fileContent: string, password: string): Promise<boolean>;
41
39
 
42
- export { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS, type DecryptOptions, type EncryptOptions, type MdencChunk, type MdencFile, type MdencHeader, type ScryptParams, decrypt, encrypt, verifySeal };
40
+ export { ChunkingStrategy, DEFAULT_SCRYPT_PARAMS, type EncryptOptions, type MdencChunk, type MdencFile, type MdencHeader, type ScryptParams, decrypt, encrypt, verifySeal };