refactor: improve encryption performance and safety

also fixed some issues i saw related to dynamic urls being resolved improperly
formatted via prettier
This commit is contained in:
2026-11-06 08:25:26 -05:00
parent 22c144e970
commit eed65b754e
5 changed files with 177 additions and 35 deletions
@@ -237,7 +237,10 @@
}
</script>
<section id="comments-section" class="w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4 mt-4">
<section
id="comments-section"
class="mt-4 w-[95%] max-w-7xl rounded border-2 border-neutral-800 bg-neutral-900 p-4"
>
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex items-center gap-2">
<h2 class="text-lg font-semibold text-neutral-100">{comments.length} Comments</h2>
@@ -0,0 +1,9 @@
import { argon2id } from 'hash-wasm';
self.onmessage = async (event: MessageEvent<Parameters<typeof argon2id>[0]>) => {
try {
self.postMessage(await argon2id(event.data));
} catch {
self.postMessage(null);
}
};
+128 -19
View File
@@ -1,5 +1,3 @@
import { argon2id } from 'hash-wasm';
const BASE64_CHUNK_SIZE = 0x8000;
const SALT_LENGTH = 16;
const IV_LENGTH = 12;
@@ -9,8 +7,58 @@ const ARGON2_PARALLELISM = 1;
const ARGON2_HASH_LENGTH = 32;
const AES_KEY_LENGTH = 256;
const ENCRYPTION_AAD = 'enc-v4';
const ENCRYPTED_DATA_OVERHEAD = 60;
const ENCRYPTED_METADATA_OVERHEAD = 150;
const ENCRYPTED_DATA_OVERHEAD = SALT_LENGTH + IV_LENGTH + 16;
const MAX_ENVELOPE_LENGTH = 16 * 1024 * 1024;
const ENCRYPTION_HEADER = {
version: 5,
kdf: 'Argon2id',
memorySize: ARGON2_MEMORY_SIZE,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM',
saltLength: SALT_LENGTH,
ivLength: IV_LENGTH
};
let derivingKey = false;
async function argon2id(
options: Parameters<typeof import('hash-wasm').argon2id>[0]
): Promise<Uint8Array<ArrayBuffer>> {
if (derivingKey) throw new Error('Another encryption operation is already running.');
derivingKey = true;
try {
return await new Promise((resolve, reject) => {
const worker = new Worker(new URL('./argon2.worker.ts', import.meta.url), { type: 'module' });
const finish = () => {
clearTimeout(timeout);
worker.terminate();
};
const timeout = setTimeout(() => {
finish();
reject(new Error('Key derivation timed out.'));
}, 60_000);
worker.onmessage = (event: MessageEvent<Uint8Array | null>) => {
finish();
if (event.data instanceof Uint8Array && event.data.length === ARGON2_HASH_LENGTH) {
resolve(new Uint8Array(event.data));
} else reject(new Error('Key derivation failed. The device may lack memory.'));
};
worker.onerror = (event) => {
event.preventDefault();
finish();
reject(new Error('Unable to run the encryption worker.'));
};
try {
worker.postMessage(options);
} catch (error) {
finish();
reject(error);
}
});
} finally {
derivingKey = false;
}
}
function toBase64(bytes: Uint8Array): string {
let binary = '';
@@ -29,7 +77,21 @@ function fromBase64(data: string): Uint8Array {
return bytes;
}
export function encodePasswordFragment(password: string): string {
return `u1.${toBase64(new TextEncoder().encode(password))}`;
}
export function decodePasswordFragment(fragment: string): string {
return fragment.startsWith('u1.')
? new TextDecoder('utf-8', { fatal: true }).decode(fromBase64(fragment.slice(3)))
: atob(fragment);
}
export async function encryptAES(content: string, password: string): Promise<string> {
if (!password) throw new Error('Password required for encryption.');
if (estimateEncryptedSize(content) > MAX_ENVELOPE_LENGTH) {
throw new Error('Encrypted paste exceeds the supported size limit.');
}
const enc = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
@@ -56,7 +118,7 @@ export async function encryptAES(content: string, password: string): Promise<str
{
name: 'AES-GCM',
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
additionalData: enc.encode(JSON.stringify(ENCRYPTION_HEADER))
},
key,
enc.encode(content)
@@ -68,14 +130,7 @@ export async function encryptAES(content: string, password: string): Promise<str
combined.set(new Uint8Array(encryptedContent), salt.byteLength + iv.byteLength);
return JSON.stringify({
version: 4,
kdf: 'Argon2id',
memorySize: ARGON2_MEMORY_SIZE,
iterations: ARGON2_ITERATIONS,
parallelism: ARGON2_PARALLELISM,
algorithm: 'AES-GCM',
saltLength: salt.byteLength,
ivLength: iv.byteLength,
...ENCRYPTION_HEADER,
data: toBase64(combined)
});
}
@@ -84,17 +139,58 @@ export function estimateEncryptedSize(content: string): number {
const rawSize = new TextEncoder().encode(content).length;
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
const b64Size = Math.ceil(combinedSize / 3) * 4;
return b64Size + ENCRYPTED_METADATA_OVERHEAD;
return b64Size + JSON.stringify({ ...ENCRYPTION_HEADER, data: '' }).length;
}
export async function decryptAES(result: string, password: string): Promise<string | null> {
try {
const enc = new TextEncoder();
if (result.length > MAX_ENVELOPE_LENGTH) {
throw new Error('Encrypted paste exceeds the supported size limit.');
}
const parsed = JSON.parse(result);
if (!parsed || typeof parsed !== 'object' || parsed.algorithm !== 'AES-GCM') {
throw new Error('Unsupported or malformed encrypted paste.');
}
const legacyPBKDF2 =
parsed.version === 1 &&
parsed.kdf === 'PBKDF2' &&
parsed.iterations === 100000 &&
parsed.hash === 'SHA-256' &&
(parsed.saltLength === undefined || parsed.saltLength === SALT_LENGTH) &&
(parsed.ivLength === undefined || parsed.ivLength === IV_LENGTH);
const legacyArgon2 =
parsed.version === 4 && parsed.memorySize === 65536 && parsed.saltLength === 32;
const currentArgon2 =
(parsed.version === 4 || parsed.version === 5) &&
parsed.memorySize === ARGON2_MEMORY_SIZE &&
parsed.saltLength === SALT_LENGTH;
if (
!legacyPBKDF2 &&
!(
parsed.kdf === 'Argon2id' &&
parsed.iterations === ARGON2_ITERATIONS &&
parsed.parallelism === ARGON2_PARALLELISM &&
parsed.ivLength === IV_LENGTH &&
(legacyArgon2 || currentArgon2)
)
)
throw new Error('Unsupported encryption profile.');
if (
typeof parsed.data !== 'string' ||
!parsed.data.length ||
parsed.data.length % 4 !== 0 ||
!/^[A-Za-z0-9+/]*={0,2}$/.test(parsed.data)
) {
throw new Error('Malformed encrypted-paste encoding.');
}
const combined = fromBase64(parsed.data);
const saltLength = parsed.saltLength || SALT_LENGTH;
const ivLength = parsed.ivLength || IV_LENGTH;
const saltLength = parsed.saltLength ?? SALT_LENGTH;
const ivLength = parsed.ivLength ?? IV_LENGTH;
if (combined.length < saltLength + ivLength + 16) {
throw new Error('Encrypted paste is truncated.');
}
const salt = combined.slice(0, saltLength);
const iv = combined.slice(saltLength, saltLength + ivLength);
const data = combined.slice(saltLength + ivLength);
@@ -146,14 +242,27 @@ export async function decryptAES(result: string, password: string): Promise<stri
{
name: 'AES-GCM',
iv,
additionalData: enc.encode(ENCRYPTION_AAD)
additionalData: enc.encode(
parsed.version === 5
? JSON.stringify(ENCRYPTION_HEADER)
: currentArgon2
? ENCRYPTION_AAD
: ''
)
},
key,
data
);
return new TextDecoder().decode(decryptedContent);
} catch {
return null;
} catch (error) {
if (error instanceof DOMException && error.name === 'OperationError') return null;
if (
error instanceof SyntaxError ||
(error instanceof DOMException && error.name === 'InvalidCharacterError')
) {
throw new Error('Malformed encrypted paste.');
}
throw error;
}
}
+8 -3
View File
@@ -5,7 +5,7 @@
import { getToken } from '#lib/utils/auth';
import { onMount } from 'svelte';
import { fly, fade } from 'svelte/transition';
import { encryptAES, estimateEncryptedSize } from '#lib/utils/encryption';
import { encryptAES, estimateEncryptedSize, encodePasswordFragment } from '#lib/utils/encryption';
import {
formatBytes,
formatNumber,
@@ -162,7 +162,12 @@
let body = content;
if (selectedVisibility === 2) {
body = await encryptAES(content, password);
try {
body = await encryptAES(content, password);
} catch (cause) {
error = cause instanceof Error ? cause.message : 'Encryption failed.';
return;
}
}
if (
@@ -196,7 +201,7 @@
if (response.ok) {
const result = await response.json();
if (selectedVisibility === 2) {
const passwordBase64 = btoa(password);
const passwordBase64 = encodePasswordFragment(password);
window.location.href = `/${result.id}#${passwordBase64}`;
return;
}
+28 -12
View File
@@ -44,7 +44,7 @@
} from '#lib/utils/markdown';
import { syntaxes, expiresOptions } from '#lib/consts';
import { resolve } from '$app/paths';
import { decryptAES, encryptAES } from '#lib/utils/encryption';
import { decryptAES, encryptAES, decodePasswordFragment } from '#lib/utils/encryption';
import { escapeHtml } from '#lib/utils/html';
import { fade } from 'svelte/transition';
import { getToken, hasRole } from '#lib/utils/auth';
@@ -359,8 +359,8 @@
});
editMetadata = data.paste ? { ...data.paste } : null;
}
} catch {
editError = 'An error occurred while updating.';
} catch (cause) {
editError = cause instanceof Error ? cause.message : 'An error occurred while updating.';
} finally {
editLoading = false;
editing = false;
@@ -517,8 +517,20 @@
contentRendered = false;
decryptStatus = 'Preparing decryption...';
const urlHash = window.location.hash.slice(1);
let passwordFromUrl: string | null = null;
if (urlHash) {
const passwordFromUrl = atob(urlHash);
history.replaceState(
history.state,
'',
window.location.pathname + window.location.search
);
try {
passwordFromUrl = decodePasswordFragment(urlHash);
} catch {
/* empty */
}
}
if (passwordFromUrl !== null) {
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, passwordFromUrl);
if (decryptedContent === null) {
@@ -528,11 +540,10 @@
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
decryptError = 'Wrong password or damaged encrypted paste.';
decryptStatus = decryptError;
} else {
await renderPaste();
history.replaceState(null, '', window.location.pathname + window.location.search);
}
} else {
decryptStatus = 'Decryption canceled.';
@@ -548,8 +559,8 @@
decryptStatus = 'Deriving key...';
decryptedContent = await decryptAES(data.content, password);
if (decryptedContent === null) {
decryptError = 'Incorrect password. Please try again.';
decryptStatus = 'Decryption failed.';
decryptError = 'Wrong password or damaged encrypted paste.';
decryptStatus = decryptError;
} else {
await renderPaste();
}
@@ -560,7 +571,12 @@
decryptStatus = 'Rendering content...';
await renderPaste();
}
} catch {
} catch (cause) {
if (data?.paste?.visibility === 2) {
decryptStatus = cause instanceof Error ? cause.message : 'Unable to decrypt this paste.';
contentRendered = false;
return;
}
decryptStatus = 'Rendering content...';
await renderPaste();
}
@@ -655,7 +671,7 @@
{#if data.paste.author}
<User class="inline-block h-4 w-4 text-neutral-400" />
<a
href={resolve(`/user/${data.paste.author.username}`)}
href={resolve(`/user/[username]`, { username: data.paste.author.username })}
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
>{data.paste.author.username}</a
>
@@ -938,7 +954,7 @@
</button>
<a
href={resolve(`/raw/${data.paste.id}`)}
href={resolve(`/raw/[id]`, { id: data.paste.id })}
class="flex cursor-pointer items-center rounded-md bg-neutral-700 px-2 py-0.5 text-sm hover:bg-neutral-600"
>
<File class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />