mdenc 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts","../src/seal.ts","../src/git/init.ts","../src/git/mark.ts","../src/git/status.ts"],"sourcesContent":["import { readFileSync, writeFileSync } from 'node:fs';\nimport { encrypt, decrypt } from './encrypt.js';\nimport { verifySeal } from './seal.js';\nimport { initCommand, removeHooksCommand } from './git/init.js';\nimport { markCommand } from './git/mark.js';\nimport { statusCommand } from './git/status.js';\nimport {\n preCommitHook,\n postCheckoutHook,\n postMergeHook,\n postRewriteHook,\n} from './git/hooks.js';\n\nfunction readPasswordFromTTY(prompt: string): Promise<string> {\n return new Promise((resolve) => {\n if (!process.stdin.isTTY) {\n // Non-TTY fallback: read a line from stdin\n process.stderr.write(prompt);\n let data = '';\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', (chunk: string) => {\n const nlIdx = chunk.indexOf('\\n');\n if (nlIdx >= 0) {\n data += chunk.slice(0, nlIdx);\n process.stdin.pause();\n resolve(data);\n } else {\n data += chunk;\n }\n });\n process.stdin.on('end', () => resolve(data));\n process.stdin.resume();\n return;\n }\n\n process.stderr.write(prompt);\n const buf: string[] = [];\n\n process.stdin.setRawMode(true);\n process.stdin.setEncoding('utf-8');\n process.stdin.resume();\n\n const onData = (ch: string) => {\n if (ch === '\\u0003') {\n // Ctrl+C\n process.stderr.write('\\n');\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdin.removeListener('data', onData);\n process.exit(130);\n } else if (ch === '\\r' || ch === '\\n') {\n // Enter\n process.stderr.write('\\n');\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdin.removeListener('data', onData);\n resolve(buf.join(''));\n } else if (ch === '\\u007F' || ch === '\\b') {\n // Backspace\n buf.pop();\n } else if (ch === '\\u0004') {\n // Ctrl+D (EOF)\n process.stderr.write('\\n');\n process.stdin.setRawMode(false);\n process.stdin.pause();\n process.stdin.removeListener('data', onData);\n resolve(buf.join(''));\n } else if (ch >= ' ') {\n buf.push(ch);\n }\n };\n\n process.stdin.on('data', onData);\n });\n}\n\nasync function getPassword(prompt = 'Password: '): Promise<string> {\n const envPassword = process.env['MDENC_PASSWORD'];\n if (envPassword) return envPassword;\n\n return readPasswordFromTTY(prompt);\n}\n\nasync function getPasswordWithConfirmation(): Promise<string> {\n if (process.env['MDENC_PASSWORD']) return process.env['MDENC_PASSWORD'];\n\n const password = await readPasswordFromTTY('Password: ');\n const confirm = await readPasswordFromTTY('Confirm password: ');\n if (password !== confirm) {\n console.error('Error: passwords do not match');\n process.exit(1);\n }\n return password;\n}\n\nfunction usage(): never {\n console.error(`Usage:\n mdenc encrypt <file> [-o output] Encrypt a markdown file\n mdenc decrypt <file> [-o output] Decrypt an mdenc file\n mdenc verify <file> Verify file integrity\n\nGit integration:\n mdenc init Set up git hooks for automatic encryption\n mdenc mark <directory> Mark a directory for encryption\n mdenc status Show encryption status\n mdenc remove-hooks Remove mdenc git hooks`);\n process.exit(1);\n}\n\nasync function main(): Promise<void> {\n const args = process.argv.slice(2);\n\n if (args.length === 0) usage();\n\n const command = args[0];\n\n try {\n switch (command) {\n case 'encrypt': {\n if (!args[1]) usage();\n const inputFile = args[1];\n const outputIdx = args.indexOf('-o');\n const outputFile = outputIdx >= 0 ? args[outputIdx + 1] : undefined;\n const password = await getPasswordWithConfirmation();\n const plaintext = readFileSync(inputFile, 'utf-8');\n const encrypted = await encrypt(plaintext, password);\n if (outputFile) {\n writeFileSync(outputFile, encrypted);\n } else {\n process.stdout.write(encrypted);\n }\n break;\n }\n\n case 'decrypt': {\n if (!args[1]) usage();\n const inputFile = args[1];\n const outputIdx = args.indexOf('-o');\n const outputFile = outputIdx >= 0 ? args[outputIdx + 1] : undefined;\n const password = await getPassword();\n const fileContent = readFileSync(inputFile, 'utf-8');\n const decrypted = await decrypt(fileContent, password);\n if (outputFile) {\n writeFileSync(outputFile, decrypted);\n } else {\n process.stdout.write(decrypted);\n }\n break;\n }\n\n case 'verify': {\n if (!args[1]) usage();\n const inputFile = args[1];\n const password = await getPassword();\n const fileContent = readFileSync(inputFile, 'utf-8');\n const valid = await verifySeal(fileContent, password);\n if (valid) {\n console.error('Seal verified: OK');\n process.exit(0);\n } else {\n console.error('Seal verification FAILED');\n process.exit(1);\n }\n break;\n }\n\n case 'init':\n await initCommand();\n break;\n\n case 'mark': {\n if (!args[1]) {\n console.error('Usage: mdenc mark <directory>');\n process.exit(1);\n }\n markCommand(args[1]);\n break;\n }\n\n case 'status':\n statusCommand();\n break;\n\n case 'remove-hooks':\n removeHooksCommand();\n break;\n\n // Git hook handlers (called by hook scripts, not directly by user)\n case 'pre-commit':\n await preCommitHook();\n break;\n\n case 'post-checkout':\n await postCheckoutHook();\n break;\n\n case 'post-merge':\n await postMergeHook();\n break;\n\n case 'post-rewrite':\n await postRewriteHook();\n break;\n\n default:\n console.error(`Unknown command: ${command}`);\n usage();\n }\n } catch (err) {\n console.error(`Error: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n}\n\nmain();\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","import { readFileSync, writeFileSync, existsSync, chmodSync, unlinkSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { findGitRoot, getHooksDir } from './utils.js';\n\nconst MARKER = '# mdenc-hook-marker';\n\nconst HOOK_NAMES = [\n 'pre-commit',\n 'post-checkout',\n 'post-merge',\n 'post-rewrite',\n] as const;\n\nfunction hookBlock(hookName: string): string {\n return `\n${MARKER}\nif command -v mdenc >/dev/null 2>&1; then\n mdenc ${hookName}\nelif [ -x \"./node_modules/.bin/mdenc\" ]; then\n ./node_modules/.bin/mdenc ${hookName}\nelse\n echo \"mdenc: not found, skipping ${hookName} hook\" >&2\nfi`;\n}\n\nfunction newHookScript(hookName: string): string {\n return `#!/bin/sh${hookBlock(hookName)}\n`;\n}\n\nfunction isBinary(content: string): boolean {\n return content.slice(0, 512).includes('\\0');\n}\n\nfunction hasShellShebang(content: string): boolean {\n const firstLine = content.split('\\n')[0];\n return /^#!.*\\b(sh|bash|zsh|dash)\\b/.test(firstLine);\n}\n\nfunction looksLikeFrameworkHook(content: string): boolean {\n // Detect husky-style hooks that source/exec another script as their main logic\n const lines = content.split('\\n').filter(l => l.trim() && !l.startsWith('#'));\n if (lines.length <= 2) {\n // Very short hook that sources or execs something else\n return lines.some(l => /^\\.\\s+\"/.test(l.trim()) || /^exec\\s+/.test(l.trim()));\n }\n return false;\n}\n\nfunction printManualInstructions(hookName: string): void {\n process.stderr.write(\n `mdenc: ${hookName} hook exists but has an unrecognized format.\\n` +\n ` Add the following to your hook manually:\\n\\n` +\n ` ${MARKER}\\n` +\n ` if command -v mdenc >/dev/null 2>&1; then\\n` +\n ` mdenc ${hookName}\\n` +\n ` elif [ -x \"./node_modules/.bin/mdenc\" ]; then\\n` +\n ` ./node_modules/.bin/mdenc ${hookName}\\n` +\n ` fi\\n\\n`,\n );\n}\n\nexport async function initCommand(): Promise<void> {\n const repoRoot = findGitRoot();\n const hooksDir = getHooksDir();\n\n for (const hookName of HOOK_NAMES) {\n const hookPath = join(hooksDir, hookName);\n\n if (!existsSync(hookPath)) {\n writeFileSync(hookPath, newHookScript(hookName));\n chmodSync(hookPath, 0o755);\n console.log(`Installed ${hookName} hook`);\n continue;\n }\n\n const content = readFileSync(hookPath, 'utf-8');\n\n if (content.includes(MARKER)) {\n console.log(`${hookName} hook already installed (skipped)`);\n continue;\n }\n\n // Safety checks\n if (isBinary(content)) {\n process.stderr.write(\n `mdenc: ${hookName} hook appears to be a binary file. Skipping.\\n`,\n );\n printManualInstructions(hookName);\n continue;\n }\n\n if (!hasShellShebang(content)) {\n process.stderr.write(\n `mdenc: ${hookName} hook has no shell shebang. Skipping.\\n`,\n );\n printManualInstructions(hookName);\n continue;\n }\n\n if (looksLikeFrameworkHook(content)) {\n process.stderr.write(\n `mdenc: ${hookName} hook appears to be managed by a framework. Skipping.\\n`,\n );\n printManualInstructions(hookName);\n continue;\n }\n\n // Safe to append\n writeFileSync(hookPath, content.trimEnd() + '\\n' + hookBlock(hookName) + '\\n');\n chmodSync(hookPath, 0o755);\n console.log(`Appended mdenc to existing ${hookName} hook`);\n }\n\n // Add .mdenc-password to root .gitignore\n const gitignorePath = join(repoRoot, '.gitignore');\n const entry = '.mdenc-password';\n\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8');\n const lines = content.split('\\n').map(l => l.trim());\n if (!lines.includes(entry)) {\n writeFileSync(gitignorePath, content.trimEnd() + '\\n' + entry + '\\n');\n console.log('Added .mdenc-password to .gitignore');\n } else {\n console.log('.mdenc-password already in .gitignore (skipped)');\n }\n } else {\n writeFileSync(gitignorePath, entry + '\\n');\n console.log('Created .gitignore with .mdenc-password');\n }\n\n // Decrypt existing .mdenc files\n const { decryptAll } = await import('./hooks.js');\n const count = await decryptAll();\n if (count > 0) {\n console.log(`Decrypted ${count} existing file(s)`);\n }\n\n console.log('mdenc git integration initialized.');\n}\n\nexport function removeHooksCommand(): void {\n const hooksDir = getHooksDir();\n let removedCount = 0;\n\n for (const hookName of HOOK_NAMES) {\n const hookPath = join(hooksDir, hookName);\n\n if (!existsSync(hookPath)) continue;\n\n const content = readFileSync(hookPath, 'utf-8');\n if (!content.includes(MARKER)) {\n console.log(`${hookName}: no mdenc block found (skipped)`);\n continue;\n }\n\n // Remove the mdenc block: from the marker line through the matching fi\n const lines = content.split('\\n');\n const filtered: string[] = [];\n let inBlock = false;\n\n for (const line of lines) {\n if (line.trim() === MARKER) {\n inBlock = true;\n continue;\n }\n if (inBlock) {\n if (line.trim() === 'fi') {\n inBlock = false;\n continue;\n }\n continue;\n }\n filtered.push(line);\n }\n\n const result = filtered.join('\\n');\n const isEmpty = result.split('\\n').every(l => l.trim() === '' || l.startsWith('#!'));\n\n if (isEmpty) {\n unlinkSync(hookPath);\n console.log(`Removed ${hookName} hook (was mdenc-only)`);\n } else {\n writeFileSync(hookPath, result);\n console.log(`Removed mdenc block from ${hookName} hook`);\n }\n\n removedCount++;\n }\n\n if (removedCount === 0) {\n console.log('No mdenc hooks found to remove.');\n } else {\n console.log('mdenc hooks removed.');\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport {\n findGitRoot,\n getMdFilesInDir,\n gitAdd,\n gitRmCached,\n isFileTracked,\n} from './utils.js';\n\nconst MARKER_FILE = '.mdenc.conf';\nconst MARKER_CONTENT = '# mdenc: .md files in this directory are automatically encrypted\\n';\nconst GITIGNORE_PATTERN = '*.md';\n\nexport function markCommand(dirArg: string): void {\n const repoRoot = findGitRoot();\n const dir = resolve(dirArg);\n\n if (!existsSync(dir)) {\n console.error(`Error: directory \"${dirArg}\" does not exist`);\n process.exit(1);\n }\n\n const rel = relative(repoRoot, dir);\n if (rel.startsWith('..')) {\n console.error(`Error: directory \"${dirArg}\" is outside the git repository`);\n process.exit(1);\n }\n\n const relDir = rel || '.';\n\n // Create .mdenc.conf\n const confPath = join(dir, MARKER_FILE);\n if (!existsSync(confPath)) {\n writeFileSync(confPath, MARKER_CONTENT);\n console.log(`Created ${relDir}/${MARKER_FILE}`);\n } else {\n console.log(`${relDir}/${MARKER_FILE} already exists (skipped)`);\n }\n\n // Create/update .gitignore\n const gitignorePath = join(dir, '.gitignore');\n if (existsSync(gitignorePath)) {\n const content = readFileSync(gitignorePath, 'utf-8');\n const lines = content.split('\\n').map(l => l.trim());\n if (!lines.includes(GITIGNORE_PATTERN)) {\n writeFileSync(gitignorePath, content.trimEnd() + '\\n' + GITIGNORE_PATTERN + '\\n');\n console.log(`Updated ${relDir}/.gitignore (added ${GITIGNORE_PATTERN})`);\n } else {\n console.log(`${relDir}/.gitignore already has ${GITIGNORE_PATTERN} (skipped)`);\n }\n } else {\n writeFileSync(gitignorePath, GITIGNORE_PATTERN + '\\n');\n console.log(`Created ${relDir}/.gitignore with ${GITIGNORE_PATTERN}`);\n }\n\n // Untrack any currently-tracked .md files\n const mdFiles = getMdFilesInDir(dir);\n const trackedMd: string[] = [];\n for (const f of mdFiles) {\n const relPath = relative(repoRoot, join(dir, f));\n if (isFileTracked(repoRoot, relPath)) {\n trackedMd.push(relPath);\n }\n }\n\n if (trackedMd.length > 0) {\n gitRmCached(repoRoot, trackedMd);\n for (const f of trackedMd) {\n console.log(`Untracked ${f} from git (still exists locally)`);\n }\n }\n\n // Stage .mdenc.conf and .gitignore\n const toStage = [\n relative(repoRoot, confPath),\n relative(repoRoot, gitignorePath),\n ];\n gitAdd(repoRoot, toStage);\n\n console.log(`Marked ${relDir}/ for mdenc encryption`);\n}\n","import { existsSync, readFileSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { resolvePassword } from './password.js';\nimport {\n findGitRoot,\n findMarkedDirs,\n getHooksDir,\n getMdFilesInDir,\n getMdencFilesInDir,\n} from './utils.js';\n\nconst HOOK_NAMES = ['pre-commit', 'post-checkout', 'post-merge', 'post-rewrite'];\nconst MARKER = '# mdenc-hook-marker';\n\nexport function statusCommand(): void {\n const repoRoot = findGitRoot();\n const password = resolvePassword(repoRoot);\n const markedDirs = findMarkedDirs(repoRoot);\n\n if (markedDirs.length === 0) {\n console.log('No directories marked for mdenc encryption.');\n console.log('Use \"mdenc mark <directory>\" to designate a directory.');\n } else {\n console.log('Marked directories:\\n');\n\n for (const dir of markedDirs) {\n const relDir = relative(repoRoot, dir) || '.';\n console.log(` ${relDir}/`);\n\n const mdFiles = getMdFilesInDir(dir);\n const mdencFiles = getMdencFilesInDir(dir);\n\n const mdBases = new Set(mdFiles.map(f => f.replace(/\\.md$/, '')));\n const mdencBases = new Set(mdencFiles.map(f => f.replace(/\\.mdenc$/, '')));\n\n // Paired files (both .md and .mdenc exist)\n for (const base of mdBases) {\n if (mdencBases.has(base)) {\n const mdPath = join(dir, `${base}.md`);\n const mdencPath = join(dir, `${base}.mdenc`);\n const mdMtime = statSync(mdPath).mtimeMs;\n const mdencMtime = statSync(mdencPath).mtimeMs;\n\n if (mdMtime > mdencMtime) {\n console.log(` ${base}.md [needs re-encryption]`);\n } else {\n console.log(` ${base}.md [up to date]`);\n }\n } else {\n console.log(` ${base}.md [not yet encrypted]`);\n }\n }\n\n // Orphaned .mdenc files (no corresponding .md)\n for (const base of mdencBases) {\n if (!mdBases.has(base)) {\n console.log(` ${base}.mdenc [needs decryption]`);\n }\n }\n\n // Check .gitignore health\n const gitignorePath = join(dir, '.gitignore');\n if (!existsSync(gitignorePath)) {\n console.log(` WARNING: no .gitignore in this directory`);\n } else {\n const content = readFileSync(gitignorePath, 'utf-8');\n if (!content.split('\\n').some(l => l.trim() === '*.md')) {\n console.log(` WARNING: .gitignore missing *.md pattern`);\n }\n }\n\n console.log();\n }\n }\n\n // Password status\n if (!password) {\n console.log('Password: NOT AVAILABLE');\n console.log(' Set MDENC_PASSWORD env var or create .mdenc-password file');\n } else {\n console.log('Password: available');\n }\n\n // Hook status\n const hooksDir = getHooksDir();\n const missing: string[] = [];\n for (const name of HOOK_NAMES) {\n const hookPath = join(hooksDir, name);\n if (!existsSync(hookPath)) {\n missing.push(name);\n } else {\n const content = readFileSync(hookPath, 'utf-8');\n if (!content.includes(MARKER)) {\n missing.push(name);\n }\n }\n }\n\n if (missing.length > 0) {\n console.log(`Hooks: MISSING (${missing.join(', ')})`);\n console.log(' Run \"mdenc init\" to install hooks');\n } else {\n console.log('Hooks: all installed');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAAA,eAAc,iBAAAC,sBAAqB;;;ACA5C,SAAS,YAAY;AACrB,SAAS,cAAc;AASvB,eAAsB,WACpB,aACA,UACkB;AAClB,QAAM,QAAQ,YAAY,MAAM,IAAI;AACpC,MAAI,MAAM,SAAS,KAAK,MAAM,MAAM,SAAS,CAAC,MAAM,GAAI,OAAM,IAAI;AAClE,MAAI,MAAM,SAAS,EAAG,OAAM,IAAI,MAAM,mCAAmC;AAEzE,QAAM,aAAa,MAAM,CAAC;AAC1B,QAAM,SAAS,YAAY,UAAU;AAGrC,QAAM,WAAW,MAAM,CAAC;AACxB,QAAM,YAAY,SAAS,MAAM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Q,KAAK,CAAC;AAAA,QAChB;AACA;AAAA,MACF;AAAA,MAEA,KAAK;AACH,cAAM,YAAY;AAClB;AAAA,MAEF,KAAK,QAAQ;AACX,YAAI,CAAC,KAAK,CAAC,GAAG;AACZ,kBAAQ,MAAM,+BAA+B;AAC7C,kBAAQ,KAAK,CAAC;AAAA,QAChB;AACA,oBAAY,KAAK,CAAC,CAAC;AACnB;AAAA,MACF;AAAA,MAEA,KAAK;AACH,sBAAc;AACd;AAAA,MAEF,KAAK;AACH,2BAAmB;AACnB;AAAA;AAAA,MAGF,KAAK;AACH,cAAM,cAAc;AACpB;AAAA,MAEF,KAAK;AACH,cAAM,iBAAiB;AACvB;AAAA,MAEF,KAAK;AACH,cAAM,cAAc;AACpB;AAAA,MAEF,KAAK;AACH,cAAM,gBAAgB;AACtB;AAAA,MAEF;AACE,gBAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,cAAM;AAAA,IACV;AAAA,EACF,SAAS,KAAK;AACZ,YAAQ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,GAAG,EAAE;AAClE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,KAAK;","names":["readFileSync","writeFileSync","existsSync","readFileSync","writeFileSync","join","existsSync","join","writeFileSync","readFileSync","existsSync","readFileSync","join","relative","HOOK_NAMES","MARKER","relative","join","existsSync","readFileSync","resolve","readFileSync","writeFileSync"]}
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ decryptAll,
4
+ postCheckoutHook,
5
+ postMergeHook,
6
+ postRewriteHook,
7
+ preCommitHook
8
+ } from "./chunk-FFRUPAVV.js";
9
+ export {
10
+ decryptAll,
11
+ postCheckoutHook,
12
+ postMergeHook,
13
+ postRewriteHook,
14
+ preCommitHook
15
+ };
16
+ //# sourceMappingURL=hooks-ZO2DIE5U.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,455 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ChunkingStrategy: () => ChunkingStrategy,
24
+ DEFAULT_SCRYPT_PARAMS: () => DEFAULT_SCRYPT_PARAMS,
25
+ decrypt: () => decrypt,
26
+ encrypt: () => encrypt,
27
+ verifySeal: () => verifySeal
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
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
50
+ var import_hmac3 = require("@noble/hashes/hmac");
51
+ var import_sha2564 = require("@noble/hashes/sha256");
52
+
53
+ // src/chunking.ts
54
+ var DEFAULT_MAX_CHUNK_SIZE = 65536;
55
+ function chunkByParagraph(text, maxSize = DEFAULT_MAX_CHUNK_SIZE) {
56
+ const normalized = text.replace(/\r\n/g, "\n");
57
+ if (normalized.length === 0) {
58
+ return [""];
59
+ }
60
+ const chunks = [];
61
+ const boundary = /\n{2,}/g;
62
+ let lastEnd = 0;
63
+ let match;
64
+ while ((match = boundary.exec(normalized)) !== null) {
65
+ const chunkEnd = match.index + match[0].length;
66
+ chunks.push(normalized.slice(lastEnd, chunkEnd));
67
+ lastEnd = chunkEnd;
68
+ }
69
+ if (lastEnd < normalized.length) {
70
+ chunks.push(normalized.slice(lastEnd));
71
+ } else if (chunks.length === 0) {
72
+ chunks.push(normalized);
73
+ }
74
+ const result = [];
75
+ for (const chunk of chunks) {
76
+ if (byteLength(chunk) <= maxSize) {
77
+ result.push(chunk);
78
+ } else {
79
+ result.push(...splitAtByteLimit(chunk, maxSize));
80
+ }
81
+ }
82
+ return result;
83
+ }
84
+ function chunkByFixedSize(text, size) {
85
+ const normalized = text.replace(/\r\n/g, "\n");
86
+ if (normalized.length === 0) {
87
+ return [""];
88
+ }
89
+ const bytes = new TextEncoder().encode(normalized);
90
+ if (bytes.length <= size) {
91
+ return [normalized];
92
+ }
93
+ const chunks = [];
94
+ const decoder = new TextDecoder();
95
+ let offset = 0;
96
+ while (offset < bytes.length) {
97
+ const end = Math.min(offset + size, bytes.length);
98
+ let adjusted = end;
99
+ if (adjusted < bytes.length) {
100
+ while (adjusted > offset && (bytes[adjusted] & 192) === 128) {
101
+ adjusted--;
102
+ }
103
+ }
104
+ chunks.push(decoder.decode(bytes.slice(offset, adjusted)));
105
+ offset = adjusted;
106
+ }
107
+ return chunks;
108
+ }
109
+ function byteLength(s) {
110
+ return new TextEncoder().encode(s).length;
111
+ }
112
+ function splitAtByteLimit(text, maxSize) {
113
+ const bytes = new TextEncoder().encode(text);
114
+ const decoder = new TextDecoder();
115
+ const parts = [];
116
+ let offset = 0;
117
+ while (offset < bytes.length) {
118
+ let end = Math.min(offset + maxSize, bytes.length);
119
+ if (end < bytes.length) {
120
+ while (end > offset && (bytes[end] & 192) === 128) {
121
+ end--;
122
+ }
123
+ }
124
+ parts.push(decoder.decode(bytes.slice(offset, end)));
125
+ offset = end;
126
+ }
127
+ return parts;
128
+ }
129
+
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
136
+ function constantTimeEqual(a, b) {
137
+ if (a.length !== b.length) return false;
138
+ let diff = 0;
139
+ for (let i = 0; i < a.length; i++) {
140
+ diff |= a[i] ^ b[i];
141
+ }
142
+ return diff === 0;
143
+ }
144
+ function zeroize(...arrays) {
145
+ for (const arr of arrays) {
146
+ arr.fill(0);
147
+ }
148
+ }
149
+
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");
181
+ 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
+
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");
229
+ function generateSalt() {
230
+ return (0, import_webcrypto.randomBytes)(16);
231
+ }
232
+ function generateFileId() {
233
+ return (0, import_webcrypto.randomBytes)(16);
234
+ }
235
+ function serializeHeader(header) {
236
+ const saltB64 = toBase64(header.salt);
237
+ const fileIdB64 = toBase64(header.fileId);
238
+ const { N, r, p } = header.scrypt;
239
+ return `mdenc:v1 salt_b64=${saltB64} file_id_b64=${fileIdB64} scrypt=N=${N},r=${r},p=${p}`;
240
+ }
241
+ function parseHeader(line) {
242
+ if (!line.startsWith("mdenc:v1 ")) {
243
+ throw new Error("Invalid header: missing mdenc:v1 prefix");
244
+ }
245
+ const saltMatch = line.match(/salt_b64=([A-Za-z0-9+/=]+)/);
246
+ if (!saltMatch) throw new Error("Invalid header: missing salt_b64");
247
+ const salt = fromBase64(saltMatch[1]);
248
+ if (salt.length !== 16) throw new Error("Invalid header: salt must be 16 bytes");
249
+ const fileIdMatch = line.match(/file_id_b64=([A-Za-z0-9+/=]+)/);
250
+ if (!fileIdMatch) throw new Error("Invalid header: missing file_id_b64");
251
+ const fileId = fromBase64(fileIdMatch[1]);
252
+ if (fileId.length !== 16) throw new Error("Invalid header: file_id must be 16 bytes");
253
+ const scryptMatch = line.match(/scrypt=N=(\d+),r=(\d+),p=(\d+)/);
254
+ if (!scryptMatch) throw new Error("Invalid header: missing scrypt parameters");
255
+ const scryptParams = {
256
+ N: parseInt(scryptMatch[1], 10),
257
+ r: parseInt(scryptMatch[2], 10),
258
+ p: parseInt(scryptMatch[3], 10)
259
+ };
260
+ validateScryptParams(scryptParams);
261
+ return { version: "v1", salt, fileId, scrypt: scryptParams };
262
+ }
263
+ function validateScryptParams(params) {
264
+ const { N, r, p } = SCRYPT_BOUNDS;
265
+ if (params.N < N.min || params.N > N.max) {
266
+ throw new Error(`Invalid scrypt N: ${params.N} (must be ${N.min}\u2013${N.max})`);
267
+ }
268
+ if (params.r < r.min || params.r > r.max) {
269
+ throw new Error(`Invalid scrypt r: ${params.r} (must be ${r.min}\u2013${r.max})`);
270
+ }
271
+ if (params.p < p.min || params.p > p.max) {
272
+ throw new Error(`Invalid scrypt p: ${params.p} (must be ${p.min}\u2013${p.max})`);
273
+ }
274
+ }
275
+ function authenticateHeader(headerKey, headerLine) {
276
+ const headerBytes = new TextEncoder().encode(headerLine);
277
+ return (0, import_hmac2.hmac)(import_sha2563.sha256, headerKey, headerBytes);
278
+ }
279
+ function verifyHeader(headerKey, headerLine, hmacBytes) {
280
+ const computed = authenticateHeader(headerKey, headerLine);
281
+ return constantTimeEqual(computed, hmacBytes);
282
+ }
283
+ function toBase64(bytes) {
284
+ return Buffer.from(bytes).toString("base64");
285
+ }
286
+ function fromBase64(b64) {
287
+ return new Uint8Array(Buffer.from(b64, "base64"));
288
+ }
289
+
290
+ // src/encrypt.ts
291
+ async function encrypt(plaintext, password, options) {
292
+ const chunking = options?.chunking ?? "paragraph" /* Paragraph */;
293
+ const maxChunkSize = options?.maxChunkSize ?? 65536;
294
+ const scryptParams = options?.scrypt ?? DEFAULT_SCRYPT_PARAMS;
295
+ let chunks;
296
+ if (chunking === "fixed-size" /* FixedSize */) {
297
+ const fixedSize = options?.fixedChunkSize ?? 4096;
298
+ chunks = chunkByFixedSize(plaintext, fixedSize);
299
+ } else {
300
+ chunks = chunkByParagraph(plaintext, maxChunkSize);
301
+ }
302
+ let salt;
303
+ let fileId;
304
+ let masterKey;
305
+ const prev = options?.previousFile ? parsePreviousFileHeader(options.previousFile, password) : void 0;
306
+ if (prev) {
307
+ salt = prev.salt;
308
+ fileId = prev.fileId;
309
+ masterKey = prev.masterKey;
310
+ } else {
311
+ salt = generateSalt();
312
+ fileId = generateFileId();
313
+ masterKey = deriveMasterKey(password, salt, scryptParams);
314
+ }
315
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
316
+ try {
317
+ const header = { version: "v1", salt, fileId, scrypt: scryptParams };
318
+ const headerLine = serializeHeader(header);
319
+ const headerHmac = authenticateHeader(headerKey, headerLine);
320
+ const headerAuthLine = `hdrauth_b64=${toBase64(headerHmac)}`;
321
+ const chunkLines = [];
322
+ for (const chunkText of chunks) {
323
+ const chunkBytes = new TextEncoder().encode(chunkText);
324
+ const payload = encryptChunk(encKey, nonceKey, chunkBytes, fileId);
325
+ chunkLines.push(toBase64(payload));
326
+ }
327
+ const sealInput = headerLine + "\n" + headerAuthLine + "\n" + chunkLines.join("\n");
328
+ const sealData = new TextEncoder().encode(sealInput);
329
+ const sealHmac = (0, import_hmac3.hmac)(import_sha2564.sha256, headerKey, sealData);
330
+ const sealLine = `seal_b64=${toBase64(sealHmac)}`;
331
+ return [headerLine, headerAuthLine, ...chunkLines, sealLine, ""].join("\n");
332
+ } finally {
333
+ zeroize(masterKey, encKey, headerKey, nonceKey);
334
+ }
335
+ }
336
+ async function decrypt(fileContent, password) {
337
+ const lines = fileContent.split("\n");
338
+ if (lines.length > 0 && lines[lines.length - 1] === "") {
339
+ lines.pop();
340
+ }
341
+ if (lines.length < 3) {
342
+ throw new Error("Invalid mdenc file: too few lines");
343
+ }
344
+ const headerLine = lines[0];
345
+ const header = parseHeader(headerLine);
346
+ const authLine = lines[1];
347
+ const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
348
+ if (!authMatch) {
349
+ throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
350
+ }
351
+ const headerHmac = fromBase64(authMatch[1]);
352
+ const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
353
+ const { encKey, headerKey, nonceKey } = deriveKeys(masterKey);
354
+ try {
355
+ if (!verifyHeader(headerKey, headerLine, headerHmac)) {
356
+ throw new Error("Header authentication failed (wrong password or tampered header)");
357
+ }
358
+ const remaining = lines.slice(2);
359
+ const sealIndex = remaining.findIndex((l) => l.startsWith("seal_b64="));
360
+ if (sealIndex < 0) {
361
+ throw new Error("Invalid mdenc file: missing seal");
362
+ }
363
+ const chunkLines = remaining.slice(0, sealIndex);
364
+ if (chunkLines.length === 0) {
365
+ throw new Error("Invalid mdenc file: no chunk lines");
366
+ }
367
+ const sealMatch = remaining[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
368
+ if (!sealMatch) throw new Error("Invalid mdenc file: malformed seal line");
369
+ const storedSealHmac = fromBase64(sealMatch[1]);
370
+ const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
371
+ const sealData = new TextEncoder().encode(sealInput);
372
+ const computedSealHmac = (0, import_hmac3.hmac)(import_sha2564.sha256, headerKey, sealData);
373
+ if (!constantTimeEqual(computedSealHmac, storedSealHmac)) {
374
+ throw new Error("Seal verification failed (file tampered or chunks reordered)");
375
+ }
376
+ const plaintextParts = [];
377
+ for (const line of chunkLines) {
378
+ const payload = fromBase64(line);
379
+ const decrypted = decryptChunk(encKey, payload, header.fileId);
380
+ plaintextParts.push(new TextDecoder().decode(decrypted));
381
+ }
382
+ return plaintextParts.join("");
383
+ } finally {
384
+ zeroize(masterKey, encKey, headerKey, nonceKey);
385
+ }
386
+ }
387
+ function parsePreviousFileHeader(fileContent, password) {
388
+ try {
389
+ const lines = fileContent.split("\n");
390
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
391
+ if (lines.length < 3) return void 0;
392
+ const headerLine = lines[0];
393
+ const header = parseHeader(headerLine);
394
+ const authLine = lines[1];
395
+ const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
396
+ if (!authMatch) return void 0;
397
+ const headerHmac = fromBase64(authMatch[1]);
398
+ const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
399
+ const { headerKey } = deriveKeys(masterKey);
400
+ if (!verifyHeader(headerKey, headerLine, headerHmac)) {
401
+ zeroize(masterKey, headerKey);
402
+ return void 0;
403
+ }
404
+ zeroize(headerKey);
405
+ return { salt: header.salt, fileId: header.fileId, masterKey };
406
+ } catch {
407
+ return void 0;
408
+ }
409
+ }
410
+
411
+ // src/seal.ts
412
+ var import_hmac4 = require("@noble/hashes/hmac");
413
+ var import_sha2565 = require("@noble/hashes/sha256");
414
+ async function verifySeal(fileContent, password) {
415
+ const lines = fileContent.split("\n");
416
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
417
+ if (lines.length < 3) throw new Error("Invalid mdenc file: too few lines");
418
+ const headerLine = lines[0];
419
+ const header = parseHeader(headerLine);
420
+ const authLine = lines[1];
421
+ const authMatch = authLine.match(/^hdrauth_b64=([A-Za-z0-9+/=]+)$/);
422
+ if (!authMatch) throw new Error("Invalid mdenc file: missing hdrauth_b64 line");
423
+ const headerHmac = fromBase64(authMatch[1]);
424
+ const masterKey = deriveMasterKey(password, header.salt, header.scrypt);
425
+ const { headerKey, nonceKey } = deriveKeys(masterKey);
426
+ try {
427
+ if (!verifyHeader(headerKey, headerLine, headerHmac)) {
428
+ throw new Error("Header authentication failed");
429
+ }
430
+ const chunkAndSealLines = lines.slice(2);
431
+ const sealIndex = chunkAndSealLines.findIndex((l) => l.startsWith("seal_b64="));
432
+ if (sealIndex < 0) {
433
+ throw new Error("File is not sealed: no seal_b64 line found");
434
+ }
435
+ const chunkLines = chunkAndSealLines.slice(0, sealIndex);
436
+ const sealMatch = chunkAndSealLines[sealIndex].match(/^seal_b64=([A-Za-z0-9+/=]+)$/);
437
+ if (!sealMatch) throw new Error("Invalid seal line");
438
+ const storedHmac = fromBase64(sealMatch[1]);
439
+ const sealInput = headerLine + "\n" + authLine + "\n" + chunkLines.join("\n");
440
+ const sealData = new TextEncoder().encode(sealInput);
441
+ const computed = (0, import_hmac4.hmac)(import_sha2565.sha256, headerKey, sealData);
442
+ return constantTimeEqual(computed, storedHmac);
443
+ } finally {
444
+ zeroize(masterKey, headerKey, nonceKey);
445
+ }
446
+ }
447
+ // Annotate the CommonJS export names for ESM import in node:
448
+ 0 && (module.exports = {
449
+ ChunkingStrategy,
450
+ DEFAULT_SCRYPT_PARAMS,
451
+ decrypt,
452
+ encrypt,
453
+ verifySeal
454
+ });
455
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +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.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;AAqBO,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,eAAY;AAFF,SAAAA;AAAA,GAAA;;;ACrCZ,IAAAC,eAAqB;AACrB,IAAAC,iBAAuB;;;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,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