mirror of
https://github.com/whoswhip/Sharpbin.git
synced 2026-12-05 18:48:41 +00:00
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:
@@ -237,7 +237,10 @@
|
|||||||
}
|
}
|
||||||
</script>
|
</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="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<h2 class="text-lg font-semibold text-neutral-100">{comments.length} Comments</h2>
|
<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);
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
import { argon2id } from 'hash-wasm';
|
|
||||||
|
|
||||||
const BASE64_CHUNK_SIZE = 0x8000;
|
const BASE64_CHUNK_SIZE = 0x8000;
|
||||||
const SALT_LENGTH = 16;
|
const SALT_LENGTH = 16;
|
||||||
const IV_LENGTH = 12;
|
const IV_LENGTH = 12;
|
||||||
@@ -9,8 +7,58 @@ const ARGON2_PARALLELISM = 1;
|
|||||||
const ARGON2_HASH_LENGTH = 32;
|
const ARGON2_HASH_LENGTH = 32;
|
||||||
const AES_KEY_LENGTH = 256;
|
const AES_KEY_LENGTH = 256;
|
||||||
const ENCRYPTION_AAD = 'enc-v4';
|
const ENCRYPTION_AAD = 'enc-v4';
|
||||||
const ENCRYPTED_DATA_OVERHEAD = 60;
|
const ENCRYPTED_DATA_OVERHEAD = SALT_LENGTH + IV_LENGTH + 16;
|
||||||
const ENCRYPTED_METADATA_OVERHEAD = 150;
|
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 {
|
function toBase64(bytes: Uint8Array): string {
|
||||||
let binary = '';
|
let binary = '';
|
||||||
@@ -29,7 +77,21 @@ function fromBase64(data: string): Uint8Array {
|
|||||||
return bytes;
|
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> {
|
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 enc = new TextEncoder();
|
||||||
const salt = window.crypto.getRandomValues(new Uint8Array(SALT_LENGTH));
|
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',
|
name: 'AES-GCM',
|
||||||
iv,
|
iv,
|
||||||
additionalData: enc.encode(ENCRYPTION_AAD)
|
additionalData: enc.encode(JSON.stringify(ENCRYPTION_HEADER))
|
||||||
},
|
},
|
||||||
key,
|
key,
|
||||||
enc.encode(content)
|
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);
|
combined.set(new Uint8Array(encryptedContent), salt.byteLength + iv.byteLength);
|
||||||
|
|
||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
version: 4,
|
...ENCRYPTION_HEADER,
|
||||||
kdf: 'Argon2id',
|
|
||||||
memorySize: ARGON2_MEMORY_SIZE,
|
|
||||||
iterations: ARGON2_ITERATIONS,
|
|
||||||
parallelism: ARGON2_PARALLELISM,
|
|
||||||
algorithm: 'AES-GCM',
|
|
||||||
saltLength: salt.byteLength,
|
|
||||||
ivLength: iv.byteLength,
|
|
||||||
data: toBase64(combined)
|
data: toBase64(combined)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -84,17 +139,58 @@ export function estimateEncryptedSize(content: string): number {
|
|||||||
const rawSize = new TextEncoder().encode(content).length;
|
const rawSize = new TextEncoder().encode(content).length;
|
||||||
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
|
const combinedSize = rawSize + ENCRYPTED_DATA_OVERHEAD;
|
||||||
const b64Size = Math.ceil(combinedSize / 3) * 4;
|
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> {
|
export async function decryptAES(result: string, password: string): Promise<string | null> {
|
||||||
try {
|
try {
|
||||||
const enc = new TextEncoder();
|
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);
|
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 combined = fromBase64(parsed.data);
|
||||||
|
|
||||||
const saltLength = parsed.saltLength || SALT_LENGTH;
|
const saltLength = parsed.saltLength ?? SALT_LENGTH;
|
||||||
const ivLength = parsed.ivLength || IV_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 salt = combined.slice(0, saltLength);
|
||||||
const iv = combined.slice(saltLength, saltLength + ivLength);
|
const iv = combined.slice(saltLength, saltLength + ivLength);
|
||||||
const data = combined.slice(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',
|
name: 'AES-GCM',
|
||||||
iv,
|
iv,
|
||||||
additionalData: enc.encode(ENCRYPTION_AAD)
|
additionalData: enc.encode(
|
||||||
|
parsed.version === 5
|
||||||
|
? JSON.stringify(ENCRYPTION_HEADER)
|
||||||
|
: currentArgon2
|
||||||
|
? ENCRYPTION_AAD
|
||||||
|
: ''
|
||||||
|
)
|
||||||
},
|
},
|
||||||
key,
|
key,
|
||||||
data
|
data
|
||||||
);
|
);
|
||||||
|
|
||||||
return new TextDecoder().decode(decryptedContent);
|
return new TextDecoder().decode(decryptedContent);
|
||||||
} catch {
|
} catch (error) {
|
||||||
return null;
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
import { getToken } from '#lib/utils/auth';
|
import { getToken } from '#lib/utils/auth';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
import { fly, fade } from 'svelte/transition';
|
import { fly, fade } from 'svelte/transition';
|
||||||
import { encryptAES, estimateEncryptedSize } from '#lib/utils/encryption';
|
import { encryptAES, estimateEncryptedSize, encodePasswordFragment } from '#lib/utils/encryption';
|
||||||
import {
|
import {
|
||||||
formatBytes,
|
formatBytes,
|
||||||
formatNumber,
|
formatNumber,
|
||||||
@@ -162,7 +162,12 @@
|
|||||||
|
|
||||||
let body = content;
|
let body = content;
|
||||||
if (selectedVisibility === 2) {
|
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 (
|
if (
|
||||||
@@ -196,7 +201,7 @@
|
|||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const result = await response.json();
|
const result = await response.json();
|
||||||
if (selectedVisibility === 2) {
|
if (selectedVisibility === 2) {
|
||||||
const passwordBase64 = btoa(password);
|
const passwordBase64 = encodePasswordFragment(password);
|
||||||
window.location.href = `/${result.id}#${passwordBase64}`;
|
window.location.href = `/${result.id}#${passwordBase64}`;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@
|
|||||||
} from '#lib/utils/markdown';
|
} from '#lib/utils/markdown';
|
||||||
import { syntaxes, expiresOptions } from '#lib/consts';
|
import { syntaxes, expiresOptions } from '#lib/consts';
|
||||||
import { resolve } from '$app/paths';
|
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 { escapeHtml } from '#lib/utils/html';
|
||||||
import { fade } from 'svelte/transition';
|
import { fade } from 'svelte/transition';
|
||||||
import { getToken, hasRole } from '#lib/utils/auth';
|
import { getToken, hasRole } from '#lib/utils/auth';
|
||||||
@@ -359,8 +359,8 @@
|
|||||||
});
|
});
|
||||||
editMetadata = data.paste ? { ...data.paste } : null;
|
editMetadata = data.paste ? { ...data.paste } : null;
|
||||||
}
|
}
|
||||||
} catch {
|
} catch (cause) {
|
||||||
editError = 'An error occurred while updating.';
|
editError = cause instanceof Error ? cause.message : 'An error occurred while updating.';
|
||||||
} finally {
|
} finally {
|
||||||
editLoading = false;
|
editLoading = false;
|
||||||
editing = false;
|
editing = false;
|
||||||
@@ -517,8 +517,20 @@
|
|||||||
contentRendered = false;
|
contentRendered = false;
|
||||||
decryptStatus = 'Preparing decryption...';
|
decryptStatus = 'Preparing decryption...';
|
||||||
const urlHash = window.location.hash.slice(1);
|
const urlHash = window.location.hash.slice(1);
|
||||||
|
let passwordFromUrl: string | null = null;
|
||||||
if (urlHash) {
|
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...';
|
decryptStatus = 'Deriving key...';
|
||||||
decryptedContent = await decryptAES(data.content, passwordFromUrl);
|
decryptedContent = await decryptAES(data.content, passwordFromUrl);
|
||||||
if (decryptedContent === null) {
|
if (decryptedContent === null) {
|
||||||
@@ -528,11 +540,10 @@
|
|||||||
decryptStatus = 'Deriving key...';
|
decryptStatus = 'Deriving key...';
|
||||||
decryptedContent = await decryptAES(data.content, password);
|
decryptedContent = await decryptAES(data.content, password);
|
||||||
if (decryptedContent === null) {
|
if (decryptedContent === null) {
|
||||||
decryptError = 'Incorrect password. Please try again.';
|
decryptError = 'Wrong password or damaged encrypted paste.';
|
||||||
decryptStatus = 'Decryption failed.';
|
decryptStatus = decryptError;
|
||||||
} else {
|
} else {
|
||||||
await renderPaste();
|
await renderPaste();
|
||||||
history.replaceState(null, '', window.location.pathname + window.location.search);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
decryptStatus = 'Decryption canceled.';
|
decryptStatus = 'Decryption canceled.';
|
||||||
@@ -548,8 +559,8 @@
|
|||||||
decryptStatus = 'Deriving key...';
|
decryptStatus = 'Deriving key...';
|
||||||
decryptedContent = await decryptAES(data.content, password);
|
decryptedContent = await decryptAES(data.content, password);
|
||||||
if (decryptedContent === null) {
|
if (decryptedContent === null) {
|
||||||
decryptError = 'Incorrect password. Please try again.';
|
decryptError = 'Wrong password or damaged encrypted paste.';
|
||||||
decryptStatus = 'Decryption failed.';
|
decryptStatus = decryptError;
|
||||||
} else {
|
} else {
|
||||||
await renderPaste();
|
await renderPaste();
|
||||||
}
|
}
|
||||||
@@ -560,7 +571,12 @@
|
|||||||
decryptStatus = 'Rendering content...';
|
decryptStatus = 'Rendering content...';
|
||||||
await renderPaste();
|
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...';
|
decryptStatus = 'Rendering content...';
|
||||||
await renderPaste();
|
await renderPaste();
|
||||||
}
|
}
|
||||||
@@ -655,7 +671,7 @@
|
|||||||
{#if data.paste.author}
|
{#if data.paste.author}
|
||||||
<User class="inline-block h-4 w-4 text-neutral-400" />
|
<User class="inline-block h-4 w-4 text-neutral-400" />
|
||||||
<a
|
<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"
|
class="text-neutral-400 transition-colors duration-300 hover:text-neutral-500"
|
||||||
>{data.paste.author.username}</a
|
>{data.paste.author.username}</a
|
||||||
>
|
>
|
||||||
@@ -938,7 +954,7 @@
|
|||||||
</button>
|
</button>
|
||||||
|
|
||||||
<a
|
<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"
|
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" />
|
<File class="{iconsOnly ? '' : 'mr-1'} h-5 w-5 text-neutral-400" />
|
||||||
|
|||||||
Reference in New Issue
Block a user