mdenc 0.1.2 → 0.1.5

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.js CHANGED
@@ -1,26 +1,55 @@
1
- // src/types.ts
2
- var DEFAULT_SCRYPT_PARAMS = {
3
- N: 16384,
4
- r: 8,
5
- p: 1
6
- };
7
- var SCRYPT_BOUNDS = {
8
- N: { min: 1024, max: 1048576 },
9
- // 2^10 – 2^20
10
- r: { min: 1, max: 64 },
11
- p: { min: 1, max: 16 }
12
- };
13
- var ChunkingStrategy = /* @__PURE__ */ ((ChunkingStrategy2) => {
14
- ChunkingStrategy2["Paragraph"] = "paragraph";
15
- ChunkingStrategy2["FixedSize"] = "fixed-size";
16
- return ChunkingStrategy2;
17
- })(ChunkingStrategy || {});
18
-
19
- // src/encrypt.ts
1
+ // src/crypto/encrypt.ts
20
2
  import { hmac as hmac3 } from "@noble/hashes/hmac";
21
3
  import { sha256 as sha2564 } from "@noble/hashes/sha256";
22
4
 
23
- // src/chunking.ts
5
+ // src/crypto/aead.ts
6
+ import { xchacha20poly1305 } from "@noble/ciphers/chacha";
7
+ import { hmac } from "@noble/hashes/hmac";
8
+ import { sha256 } from "@noble/hashes/sha256";
9
+ var NONCE_LENGTH = 24;
10
+ function buildAAD(fileId) {
11
+ const fileIdHex = bytesToHex(fileId);
12
+ const aadString = `mdenc:v1
13
+ ${fileIdHex}`;
14
+ return new TextEncoder().encode(aadString);
15
+ }
16
+ function deriveNonce(nonceKey, plaintext) {
17
+ const full = hmac(sha256, nonceKey, plaintext);
18
+ return full.slice(0, NONCE_LENGTH);
19
+ }
20
+ function encryptChunk(encKey, nonceKey, plaintext, fileId) {
21
+ const nonce = deriveNonce(nonceKey, plaintext);
22
+ const aad = buildAAD(fileId);
23
+ const cipher = xchacha20poly1305(encKey, nonce, aad);
24
+ const ciphertext = cipher.encrypt(plaintext);
25
+ const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);
26
+ result.set(nonce, 0);
27
+ result.set(ciphertext, NONCE_LENGTH);
28
+ return result;
29
+ }
30
+ function decryptChunk(encKey, payload, fileId) {
31
+ if (payload.length < NONCE_LENGTH + 16) {
32
+ throw new Error("Chunk payload too short");
33
+ }
34
+ const nonce = payload.slice(0, NONCE_LENGTH);
35
+ const ciphertext = payload.slice(NONCE_LENGTH);
36
+ const aad = buildAAD(fileId);
37
+ const cipher = xchacha20poly1305(encKey, nonce, aad);
38
+ try {
39
+ return cipher.decrypt(ciphertext);
40
+ } catch {
41
+ throw new Error("Chunk authentication failed");
42
+ }
43
+ }
44
+ function bytesToHex(bytes) {
45
+ let hex = "";
46
+ for (let i = 0; i < bytes.length; i++) {
47
+ hex += bytes[i].toString(16).padStart(2, "0");
48
+ }
49
+ return hex;
50
+ }
51
+
52
+ // src/crypto/chunking.ts
24
53
  var DEFAULT_MAX_CHUNK_SIZE = 65536;
25
54
  function chunkByParagraph(text, maxSize = DEFAULT_MAX_CHUNK_SIZE) {
26
55
  const normalized = text.replace(/\r\n/g, "\n");
@@ -97,12 +126,7 @@ function splitAtByteLimit(text, maxSize) {
97
126
  return parts;
98
127
  }
99
128
 
100
- // src/kdf.ts
101
- import { hkdf } from "@noble/hashes/hkdf";
102
- import { sha256 } from "@noble/hashes/sha256";
103
- import { scrypt } from "@noble/hashes/scrypt";
104
-
105
- // src/crypto-utils.ts
129
+ // src/crypto/crypto-utils.ts
106
130
  function constantTimeEqual(a, b) {
107
131
  if (a.length !== b.length) return false;
108
132
  let diff = 0;
@@ -117,85 +141,30 @@ function zeroize(...arrays) {
117
141
  }
118
142
  }
119
143
 
120
- // src/kdf.ts
121
- var ENC_INFO = new TextEncoder().encode("mdenc-v1-enc");
122
- var HDR_INFO = new TextEncoder().encode("mdenc-v1-hdr");
123
- var NONCE_INFO = new TextEncoder().encode("mdenc-v1-nonce");
124
- function normalizePassword(password) {
125
- const normalized = password.normalize("NFKC");
126
- return new TextEncoder().encode(normalized);
127
- }
128
- function deriveMasterKey(password, salt, params = DEFAULT_SCRYPT_PARAMS) {
129
- const passwordBytes = normalizePassword(password);
130
- try {
131
- return scrypt(passwordBytes, salt, {
132
- N: params.N,
133
- r: params.r,
134
- p: params.p,
135
- dkLen: 32
136
- });
137
- } finally {
138
- zeroize(passwordBytes);
139
- }
140
- }
141
- function deriveKeys(masterKey) {
142
- const encKey = hkdf(sha256, masterKey, void 0, ENC_INFO, 32);
143
- const headerKey = hkdf(sha256, masterKey, void 0, HDR_INFO, 32);
144
- const nonceKey = hkdf(sha256, masterKey, void 0, NONCE_INFO, 32);
145
- return { encKey, headerKey, nonceKey };
146
- }
147
-
148
- // src/aead.ts
149
- import { xchacha20poly1305 } from "@noble/ciphers/chacha";
150
- import { hmac } from "@noble/hashes/hmac";
144
+ // src/crypto/header.ts
145
+ import { randomBytes } from "@noble/ciphers/webcrypto";
146
+ import { hmac as hmac2 } from "@noble/hashes/hmac";
151
147
  import { sha256 as sha2562 } from "@noble/hashes/sha256";
152
- var NONCE_LENGTH = 24;
153
- function buildAAD(fileId) {
154
- const fileIdHex = bytesToHex(fileId);
155
- const aadString = `mdenc:v1
156
- ${fileIdHex}`;
157
- return new TextEncoder().encode(aadString);
158
- }
159
- function deriveNonce(nonceKey, plaintext) {
160
- const full = hmac(sha2562, nonceKey, plaintext);
161
- return full.slice(0, NONCE_LENGTH);
162
- }
163
- function encryptChunk(encKey, nonceKey, plaintext, fileId) {
164
- const nonce = deriveNonce(nonceKey, plaintext);
165
- const aad = buildAAD(fileId);
166
- const cipher = xchacha20poly1305(encKey, nonce, aad);
167
- const ciphertext = cipher.encrypt(plaintext);
168
- const result = new Uint8Array(NONCE_LENGTH + ciphertext.length);
169
- result.set(nonce, 0);
170
- result.set(ciphertext, NONCE_LENGTH);
171
- return result;
172
- }
173
- function decryptChunk(encKey, payload, fileId) {
174
- if (payload.length < NONCE_LENGTH + 16) {
175
- throw new Error("Chunk payload too short");
176
- }
177
- const nonce = payload.slice(0, NONCE_LENGTH);
178
- const ciphertext = payload.slice(NONCE_LENGTH);
179
- const aad = buildAAD(fileId);
180
- const cipher = xchacha20poly1305(encKey, nonce, aad);
181
- try {
182
- return cipher.decrypt(ciphertext);
183
- } catch {
184
- throw new Error("Chunk authentication failed");
185
- }
186
- }
187
- function bytesToHex(bytes) {
188
- let hex = "";
189
- for (let i = 0; i < bytes.length; i++) {
190
- hex += bytes[i].toString(16).padStart(2, "0");
191
- }
192
- return hex;
193
- }
194
148
 
195
- // src/header.ts
196
- import { hmac as hmac2 } from "@noble/hashes/hmac";
197
- import { sha256 as sha2563 } from "@noble/hashes/sha256";
198
- import { randomBytes } from "@noble/ciphers/webcrypto";
149
+ // src/crypto/types.ts
150
+ var DEFAULT_SCRYPT_PARAMS = {
151
+ N: 16384,
152
+ r: 8,
153
+ p: 1
154
+ };
155
+ var SCRYPT_BOUNDS = {
156
+ N: { min: 1024, max: 1048576 },
157
+ // 2^10 – 2^20
158
+ r: { min: 1, max: 64 },
159
+ p: { min: 1, max: 16 }
160
+ };
161
+ var ChunkingStrategy = /* @__PURE__ */ ((ChunkingStrategy2) => {
162
+ ChunkingStrategy2["Paragraph"] = "paragraph";
163
+ ChunkingStrategy2["FixedSize"] = "fixed-size";
164
+ return ChunkingStrategy2;
165
+ })(ChunkingStrategy || {});
166
+
167
+ // src/crypto/header.ts
199
168
  function generateSalt() {
200
169
  return randomBytes(16);
201
170
  }
@@ -213,15 +182,16 @@ function parseHeader(line) {
213
182
  throw new Error("Invalid header: missing mdenc:v1 prefix");
214
183
  }
215
184
  const saltMatch = line.match(/salt_b64=([A-Za-z0-9+/=]+)/);
216
- if (!saltMatch) throw new Error("Invalid header: missing salt_b64");
185
+ if (!saltMatch?.[1]) throw new Error("Invalid header: missing salt_b64");
217
186
  const salt = fromBase64(saltMatch[1]);
218
187
  if (salt.length !== 16) throw new Error("Invalid header: salt must be 16 bytes");
219
188
  const fileIdMatch = line.match(/file_id_b64=([A-Za-z0-9+/=]+)/);
220
- if (!fileIdMatch) throw new Error("Invalid header: missing file_id_b64");
189
+ if (!fileIdMatch?.[1]) throw new Error("Invalid header: missing file_id_b64");
221
190
  const fileId = fromBase64(fileIdMatch[1]);
222
191
  if (fileId.length !== 16) throw new Error("Invalid header: file_id must be 16 bytes");
223
192
  const scryptMatch = line.match(/scrypt=N=(\d+),r=(\d+),p=(\d+)/);
224
- if (!scryptMatch) throw new Error("Invalid header: missing scrypt parameters");
193
+ if (!scryptMatch?.[1] || !scryptMatch[2] || !scryptMatch[3])
194
+ throw new Error("Invalid header: missing scrypt parameters");
225
195
  const scryptParams = {
226
196
  N: parseInt(scryptMatch[1], 10),
227
197
  r: parseInt(scryptMatch[2], 10),
@@ -247,20 +217,60 @@ function validateScryptParams(params) {
247
217
  }
248
218
  function authenticateHeader(headerKey, headerLine) {
249
219
  const headerBytes = new TextEncoder().encode(headerLine);
250
- return hmac2(sha2563, headerKey, headerBytes);
220
+ return hmac2(sha2562, headerKey, headerBytes);
251
221
  }
252
222
  function verifyHeader(headerKey, headerLine, hmacBytes) {
253
223
  const computed = authenticateHeader(headerKey, headerLine);
254
224
  return constantTimeEqual(computed, hmacBytes);
255
225
  }
256
226
  function toBase64(bytes) {
257
- return Buffer.from(bytes).toString("base64");
227
+ let binary = "";
228
+ for (let i = 0; i < bytes.length; i++) {
229
+ binary += String.fromCharCode(bytes[i]);
230
+ }
231
+ return btoa(binary);
258
232
  }
259
233
  function fromBase64(b64) {
260
- return new Uint8Array(Buffer.from(b64, "base64"));
234
+ const binary = atob(b64);
235
+ const bytes = new Uint8Array(binary.length);
236
+ for (let i = 0; i < binary.length; i++) {
237
+ bytes[i] = binary.charCodeAt(i);
238
+ }
239
+ return bytes;
240
+ }
241
+
242
+ // src/crypto/kdf.ts
243
+ import { hkdf } from "@noble/hashes/hkdf";
244
+ import { scrypt } from "@noble/hashes/scrypt";
245
+ import { sha256 as sha2563 } from "@noble/hashes/sha256";
246
+ var ENC_INFO = new TextEncoder().encode("mdenc-v1-enc");
247
+ var HDR_INFO = new TextEncoder().encode("mdenc-v1-hdr");
248
+ var NONCE_INFO = new TextEncoder().encode("mdenc-v1-nonce");
249
+ function normalizePassword(password) {
250
+ const normalized = password.normalize("NFKC");
251
+ return new TextEncoder().encode(normalized);
252
+ }
253
+ function deriveMasterKey(password, salt, params = DEFAULT_SCRYPT_PARAMS) {
254
+ const passwordBytes = normalizePassword(password);
255
+ try {
256
+ return scrypt(passwordBytes, salt, {
257
+ N: params.N,
258
+ r: params.r,
259
+ p: params.p,
260
+ dkLen: 32
261
+ });
262
+ } finally {
263
+ zeroize(passwordBytes);
264
+ }
265
+ }
266
+ function deriveKeys(masterKey) {
267
+ const encKey = hkdf(sha2563, masterKey, void 0, ENC_INFO, 32);
268
+ const headerKey = hkdf(sha2563, masterKey, void 0, HDR_INFO, 32);
269
+ const nonceKey = hkdf(sha2563, masterKey, void 0, NONCE_INFO, 32);
270
+ return { encKey, headerKey, nonceKey };
261
271
  }
262
272
 
263
- // src/encrypt.ts
273
+ // src/crypto/encrypt.ts
264
274
  async function encrypt(plaintext, password, options) {
265
275
  const chunking = options?.chunking ?? "paragraph" /* Paragraph */;
266
276
  const maxChunkSize = options?.maxChunkSize ?? 65536;
@@ -297,7 +307,9 @@ async function encrypt(plaintext, password, options) {
297
307
  const payload = encryptChunk(encKey, nonceKey, chunkBytes, fileId);
298
308
  chunkLines.push(toBase64(payload));
299
309
  }
300
- const sealInput = headerLine + "\n" + headerAuthLine + "\n" + chunkLines.join("\n");
310
+ const sealInput = `${headerLine}
311
+ ${headerAuthLine}
312
+ ${chunkLines.join("\n")}`;
301
313
  const sealData = new TextEncoder().encode(sealInput);
302
314
  const sealHmac = hmac3(sha2564, headerKey, sealData);
303
315
  const sealLine = `seal_b64=${toBase64(sealHmac)}`;
@@ -318,7 +330,7 @@ async function decrypt(fileContent, password) {
318
330
  const header = parseHeader(headerLine);
319
331
  const authLine = lines[1];
320
332
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
321
- if (!authMatch) {
333
+ if (!authMatch?.[1]) {
322
334
  throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
323
335
  }
324
336
  const headerHmac = fromBase64(authMatch[1]);
@@ -337,10 +349,13 @@ async function decrypt(fileContent, password) {
337
349
  if (chunkLines.length === 0) {
338
350
  throw new Error("Invalid mdenc file: no chunk lines");
339
351
  }
340
- const sealMatch = remaining[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
341
- if (!sealMatch) throw new Error("Invalid mdenc file: malformed seal line");
352
+ const sealLine = remaining[sealIndex];
353
+ const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
354
+ if (!sealMatch?.[1]) throw new Error("Invalid mdenc file: malformed seal line");
342
355
  const storedSealHmac = fromBase64(sealMatch[1]);
343
- const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
356
+ const sealInput = `${headerLine}
357
+ ${authLine}
358
+ ${chunkLines.join("\n")}`;
344
359
  const sealData = new TextEncoder().encode(sealInput);
345
360
  const computedSealHmac = hmac3(sha2564, headerKey, sealData);
346
361
  if (!constantTimeEqual(computedSealHmac, storedSealHmac)) {
@@ -366,22 +381,22 @@ function parsePreviousFileHeader(fileContent, password) {
366
381
  const header = parseHeader(headerLine);
367
382
  const authLine = lines[1];
368
383
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
369
- if (!authMatch) return void 0;
384
+ if (!authMatch?.[1]) return void 0;
370
385
  const headerHmac = fromBase64(authMatch[1]);
371
386
  const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
372
- const { headerKey } = deriveKeys(masterKey);
387
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
373
388
  if (!verifyHeader(headerKey, headerLine, headerHmac)) {
374
- zeroize(masterKey, headerKey);
389
+ zeroize(masterKey, encKey, headerKey, nonceKey);
375
390
  return void 0;
376
391
  }
377
- zeroize(headerKey);
392
+ zeroize(encKey, headerKey, nonceKey);
378
393
  return { salt: header.salt, fileId: header.fileId, masterKey };
379
394
  } catch {
380
395
  return void 0;
381
396
  }
382
397
  }
383
398
 
384
- // src/seal.ts
399
+ // src/crypto/seal.ts
385
400
  import { hmac as hmac4 } from "@noble/hashes/hmac";
386
401
  import { sha256 as sha2565 } from "@noble/hashes/sha256";
387
402
  async function verifySeal(fileContent, password) {
@@ -392,10 +407,10 @@ async function verifySeal(fileContent, password) {
392
407
  const header = parseHeader(headerLine);
393
408
  const authLine = lines[1];
394
409
  const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
395
- if (!authMatch) throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
410
+ if (!authMatch?.[1]) throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
396
411
  const headerHmac = fromBase64(authMatch[1]);
397
412
  const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
398
- const { headerKey, nonceKey } = deriveKeys(masterKey);
413
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
399
414
  try {
400
415
  if (!verifyHeader(headerKey, headerLine, headerHmac)) {
401
416
  throw new Error("Header authentication failed");
@@ -406,15 +421,18 @@ async function verifySeal(fileContent, password) {
406
421
  throw new Error("File is not sealed: no seal_b64 line found");
407
422
  }
408
423
  const chunkLines = chunkAndSealLines.slice(0, sealIndex);
409
- const sealMatch = chunkAndSealLines[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
410
- if (!sealMatch) throw new Error("Invalid seal line");
424
+ const sealLine = chunkAndSealLines[sealIndex];
425
+ const sealMatch = sealLine.match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
426
+ if (!sealMatch?.[1]) throw new Error("Invalid seal line");
411
427
  const storedHmac = fromBase64(sealMatch[1]);
412
- const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
428
+ const sealInput = `${headerLine}
429
+ ${authLine}
430
+ ${chunkLines.join("\n")}`;
413
431
  const sealData = new TextEncoder().encode(sealInput);
414
432
  const computed = hmac4(sha2565, headerKey, sealData);
415
433
  return constantTimeEqual(computed, storedHmac);
416
434
  } finally {
417
- zeroize(masterKey, headerKey, nonceKey);
435
+ zeroize(masterKey, encKey, headerKey, nonceKey);
418
436
  }
419
437
  }
420
438
  export {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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 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":";AAMO,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;AAqBO,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,eAAY;AAFF,SAAAA;AAAA,GAAA;;;ACrCZ,SAAS,QAAAC,aAAY;AACrB,SAAS,UAAAC,eAAc;;;ACDvB,IAAM,yBAAyB;AAExB,SAAS,iBAAiB,MAAc,UAAU,wBAAkC;AAEzF,QAAM,aAAa,KAAK,QAAQ,SAAS,IAAI;AAE7C,MAAI,WAAW,WAAW,GAAG;AAC3B,WAAO,CAAC,EAAE;AAAA,EACZ;AAGA,QAAM,SAAmB,CAAC;AAC1B,QAAM,WAAW;AACjB,MAAI,UAAU;AACd,MAAI;AAEJ,UAAQ,QAAQ,SAAS,KAAK,UAAU,OAAO,MAAM;AAEnD,UAAM,WAAW,MAAM,QAAQ,MAAM,CAAC,EAAE;AACxC,WAAO,KAAK,WAAW,MAAM,SAAS,QAAQ,CAAC;AAC/C,cAAU;AAAA,EACZ;AAGA,MAAI,UAAU,WAAW,QAAQ;AAC/B,WAAO,KAA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1C,UAAM,YAAY,aAAa,OAAO,WAAW,OAAO,WAAW,KAAK,IAAI;AAC5E,UAAM,WAAW,IAAI,YAAY,EAAE,OAAO,SAAS;AACnD,UAAM,WAAWC,MAAKC,SAAQ,WAAW,QAAQ;AAEjD,WAAO,kBAAkB,UAAU,UAAU;AAAA,EAC/C,UAAE;AACA,YAAQ,WAAW,WAAW,QAAQ;AAAA,EACxC;AACF;","names":["ChunkingStrategy","hmac","sha256","sha256","hmac","sha256","hmac","sha256","hmac","sha256","hmac","sha256","hmac","sha256"]}
1
+ {"version":3,"sources":["../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":["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\nexport type DecryptOptions = Record<string, never>;\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,SAAS,QAAAA,aAAY;AACrB,SAAS,UAAAC,eAAc;;;ACDvB,SAAS,yBAAyB;AAClC,SAAS,YAAY;AACrB,SAAS,cAAc;AAEvB,IAAM,eAAe;AAEd,SAAS,SAAS,QAAgC;AACvD,QAAM,YAA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a,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,WAAWC,MAAKC,SAAQ,WAAW,QAAQ;AAEjD,WAAO,kBAAkB,UAAU,UAAU;AAAA,EAC/C,UAAE;AACA,YAAQ,WAAW,QAAQ,WAAW,QAAQ;AAAA,EAChD;AACF;","names":["hmac","sha256","hmac","sha256","ChunkingStrategy","hmac","sha256","sha256","sha256","hmac","sha256","hmac","sha256","hmac","sha256"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mdenc",
3
- "version": "0.1.2",
3
+ "version": "0.1.5",
4
4
  "description": "Diff-friendly encrypted Markdown format",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -28,7 +28,8 @@
28
28
  "build": "bun x tsup",
29
29
  "test": "bun test",
30
30
  "test:watch": "bun test --watch",
31
- "lint": "bun x tsc --noEmit",
31
+ "lint": "bun x tsc --noEmit && bun x biome check .",
32
+ "format": "bun x biome format --write .",
32
33
  "prepublishOnly": "bun run build",
33
34
  "release": "scripts/release.sh",
34
35
  "release:minor": "scripts/release.sh minor",
@@ -43,11 +44,11 @@
43
44
  ],
44
45
  "repository": {
45
46
  "type": "git",
46
- "url": "git+https://github.com/yogh-io/mdenc-v1.git"
47
+ "url": "git+https://github.com/yogh-io/mdenc.git"
47
48
  },
48
- "homepage": "https://github.com/yogh-io/mdenc-v1#readme",
49
+ "homepage": "https://github.com/yogh-io/mdenc#readme",
49
50
  "bugs": {
50
- "url": "https://github.com/yogh-io/mdenc-v1/issues"
51
+ "url": "https://github.com/yogh-io/mdenc/issues"
51
52
  },
52
53
  "engines": {
53
54
  "node": ">=18"
@@ -55,13 +56,13 @@
55
56
  "license": "ISC",
56
57
  "dependencies": {
57
58
  "@noble/ciphers": "^1.2.1",
58
- "@noble/hashes": "^1.7.1",
59
- "chokidar": "^5.0.0"
59
+ "@noble/hashes": "^1.7.1"
60
60
  },
61
61
  "devDependencies": {
62
+ "@biomejs/biome": "^2.4.4",
63
+ "@types/bun": "^1.2.4",
62
64
  "@types/node": "^25.3.3",
63
65
  "tsup": "^8.4.0",
64
- "typescript": "^5.7.3",
65
- "@types/bun": "^1.2.4"
66
+ "typescript": "^5.7.3"
66
67
  }
67
68
  }