169 lines
5.6 KiB
TypeScript
169 lines
5.6 KiB
TypeScript
import { concat, from_base64, to_base64 } from "./keys.ts";
|
|
|
|
// Plaintext bytes per encrypted chunk, every chunk gets its own 16 byte tag
|
|
const CHUNK_SIZE = 1024 * 1024;
|
|
const TAG_LENGTH = 16;
|
|
const IV_LENGTH = 12;
|
|
const METADATA_VERSION = 1;
|
|
const METADATA_AAD = new TextEncoder().encode("vces-file-metadata-v1");
|
|
|
|
export interface FileMetadata {
|
|
name: string;
|
|
type: string;
|
|
size: number;
|
|
chunk_size: number;
|
|
key: CryptoKey;
|
|
}
|
|
|
|
export interface EncryptedFile {
|
|
metadata: string;
|
|
body: Blob;
|
|
}
|
|
|
|
// Each file has its own key, so the chunk index works as the IV. The last byte marks the final chunk
|
|
// so a truncated file fails to decrypt
|
|
function chunk_iv(index: number, last: boolean) {
|
|
const iv = new Uint8Array(IV_LENGTH);
|
|
new DataView(iv.buffer).setUint32(7, index);
|
|
iv[11] = last ? 1 : 0;
|
|
return iv;
|
|
}
|
|
|
|
// Encrypts with a random IV, which goes in front of the ciphertext
|
|
export async function seal(key: CryptoKey, plaintext: Uint8Array<ArrayBuffer>, aad: Uint8Array<ArrayBuffer>) {
|
|
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
|
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: aad }, key, plaintext);
|
|
return to_base64(concat(iv, new Uint8Array(ciphertext)));
|
|
}
|
|
|
|
// Throws if it wasn't sealed with this key and aad
|
|
export async function unseal(key: CryptoKey, sealed: string, aad: Uint8Array<ArrayBuffer>) {
|
|
const bytes = from_base64(sealed);
|
|
const plaintext = await crypto.subtle.decrypt(
|
|
{ name: "AES-GCM", iv: bytes.slice(0, IV_LENGTH), additionalData: aad },
|
|
key,
|
|
bytes.slice(IV_LENGTH),
|
|
);
|
|
return new Uint8Array(plaintext);
|
|
}
|
|
|
|
// Throws if the metadata wasn't encrypted with this master key
|
|
export async function decrypt_metadata(master_key: CryptoKey, metadata: string) {
|
|
return await parse_metadata(await unseal(master_key, metadata, METADATA_AAD));
|
|
}
|
|
|
|
// The file metadata decrypted as is, so it can be encrypted again for a share link
|
|
export function unseal_metadata(master_key: CryptoKey, metadata: string) {
|
|
return unseal(master_key, metadata, METADATA_AAD);
|
|
}
|
|
|
|
// Throws if the plaintext isn't valid metadata
|
|
export async function parse_metadata(plaintext: Uint8Array): Promise<FileMetadata> {
|
|
const data = JSON.parse(new TextDecoder().decode(plaintext));
|
|
if (
|
|
data.version !== METADATA_VERSION || typeof data.name !== "string" || typeof data.type !== "string" ||
|
|
!Number.isSafeInteger(data.size) || !Number.isSafeInteger(data.chunk_size) || typeof data.key !== "string"
|
|
) {
|
|
throw new Error("Unsupported file metadata");
|
|
}
|
|
|
|
const raw_key = from_base64(data.key);
|
|
const key = await crypto.subtle.importKey("raw", raw_key, "AES-GCM", false, ["decrypt"]);
|
|
raw_key.fill(0);
|
|
return { name: data.name, type: data.type, size: data.size, chunk_size: data.chunk_size, key };
|
|
}
|
|
|
|
export async function encrypt_file(
|
|
master_key: CryptoKey,
|
|
file: File,
|
|
on_progress?: (ratio: number) => void,
|
|
): Promise<EncryptedFile> {
|
|
const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]);
|
|
const raw_key = new Uint8Array(await crypto.subtle.exportKey("raw", key));
|
|
const plaintext = new TextEncoder().encode(JSON.stringify({
|
|
version: METADATA_VERSION,
|
|
name: file.name,
|
|
type: file.type,
|
|
size: file.size,
|
|
chunk_size: CHUNK_SIZE,
|
|
key: to_base64(raw_key),
|
|
}));
|
|
const metadata = await seal(master_key, plaintext, METADATA_AAD);
|
|
plaintext.fill(0);
|
|
raw_key.fill(0);
|
|
|
|
// Empty files still get one chunk, so the last chunk flag is always checked
|
|
const parts: ArrayBuffer[] = [];
|
|
for (let index = 0, start = 0;; index++, start += CHUNK_SIZE) {
|
|
const end = Math.min(start + CHUNK_SIZE, file.size);
|
|
const last = end >= file.size;
|
|
const plaintext = await file.slice(start, end).arrayBuffer();
|
|
parts.push(await crypto.subtle.encrypt({ name: "AES-GCM", iv: chunk_iv(index, last) }, key, plaintext));
|
|
on_progress?.(file.size ? end / file.size : 1);
|
|
if (last) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
return { metadata, body: new Blob(parts, { type: "application/octet-stream" }) };
|
|
}
|
|
|
|
function join(chunks: Uint8Array[], length: number) {
|
|
const joined = new Uint8Array(length);
|
|
let offset = 0;
|
|
for (const chunk of chunks) {
|
|
joined.set(chunk, offset);
|
|
offset += chunk.length;
|
|
}
|
|
return joined;
|
|
}
|
|
|
|
// Throws if the file was modified, truncated or doesn't match its metadata
|
|
export async function decrypt_file(metadata: FileMetadata, body: ReadableStream<Uint8Array>): Promise<Blob> {
|
|
const encrypted_chunk_size = metadata.chunk_size + TAG_LENGTH;
|
|
const parts: ArrayBuffer[] = [];
|
|
let index = 0;
|
|
let size = 0;
|
|
|
|
async function decrypt_chunk(chunk: Uint8Array<ArrayBuffer>, last: boolean) {
|
|
try {
|
|
const plaintext = await crypto.subtle.decrypt(
|
|
{ name: "AES-GCM", iv: chunk_iv(index, last) },
|
|
metadata.key,
|
|
chunk,
|
|
);
|
|
parts.push(plaintext);
|
|
size += plaintext.byteLength;
|
|
index++;
|
|
} catch {
|
|
throw new Error("The file is damaged or was tampered with");
|
|
}
|
|
}
|
|
|
|
// A chunk is only known to be the last one once the stream ends, so the final one is held back
|
|
let pending: Uint8Array[] = [];
|
|
let pending_length = 0;
|
|
for await (const value of body) {
|
|
pending.push(value);
|
|
pending_length += value.length;
|
|
if (pending_length <= encrypted_chunk_size) {
|
|
continue;
|
|
}
|
|
|
|
const joined = join(pending, pending_length);
|
|
let offset = 0;
|
|
while (joined.length - offset > encrypted_chunk_size) {
|
|
await decrypt_chunk(joined.subarray(offset, offset + encrypted_chunk_size), false);
|
|
offset += encrypted_chunk_size;
|
|
}
|
|
pending = [joined.subarray(offset)];
|
|
pending_length = joined.length - offset;
|
|
}
|
|
await decrypt_chunk(join(pending, pending_length), true);
|
|
|
|
if (size !== metadata.size) {
|
|
throw new Error("The file is damaged or was tampered with");
|
|
}
|
|
return new Blob(parts, { type: metadata.type });
|
|
}
|