Encryption keys

This commit is contained in:
2026-10-29 17:29:25 -03:00
parent 5c5490a36a
commit bf00317e95
11 changed files with 609 additions and 3 deletions
+3
View File
@@ -1,11 +1,14 @@
import { Database } from "@paulaboks/boksy";
import { DATABASE_PATH } from "@/src/server_constants.ts";
import type { PassphraseBackup } from "@/src/keys.ts";
export interface User extends Record<string, unknown> {
name: string;
code: string;
admin: boolean;
key_check?: string;
passphrase_backup?: PassphraseBackup;
}
type Schema = {
+37
View File
@@ -0,0 +1,37 @@
const DB_NAME = "vces";
const STORE_NAME = "master_keys";
function open_key_store(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => request.result.createObjectStore(STORE_NAME);
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
// Resolves once the transaction commits, not just when the request succeeds
async function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
const database = await open_key_store();
try {
return await new Promise((resolve, reject) => {
const transaction = database.transaction(STORE_NAME, mode);
const request = fn(transaction.objectStore(STORE_NAME));
transaction.oncomplete = () => resolve(request.result);
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
} finally {
database.close();
}
}
export function load_master_key(user_id: string): Promise<CryptoKey | undefined> {
return run("readonly", (store) => store.get(user_id));
}
export async function save_master_key(user_id: string, key: CryptoKey) {
await run("readwrite", (store) => store.put(key, user_id));
// Asks the browser not to evict the key under storage pressure
await navigator.storage.persist().catch(() => false);
}
+143
View File
@@ -0,0 +1,143 @@
export interface PassphraseBackup {
wrapped_key: string;
salt: string;
iterations: number;
}
export interface GetKeyResponse {
user_id: string;
key_check: string | null;
passphrase_backup: PassphraseBackup | null;
}
const KEY_TEXT_PREFIX = "vces-key-v1:";
const KEY_CHECK_PLAINTEXT = new TextEncoder().encode("vces-key-check-v1");
const PBKDF2_ITERATIONS = 600_000;
const IV_LENGTH = 12;
const MASTER_KEY_USAGES: KeyUsage[] = ["encrypt", "decrypt", "wrapKey", "unwrapKey"];
function to_base64(bytes: Uint8Array) {
return btoa(String.fromCharCode(...bytes));
}
function from_base64(text: string) {
return Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
}
function concat(a: Uint8Array, b: Uint8Array) {
const result = new Uint8Array(a.length + b.length);
result.set(a);
result.set(b, a.length);
return result;
}
export function generate_master_key() {
return crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, MASTER_KEY_USAGES);
}
export async function export_key_text(key: CryptoKey) {
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key));
const base64url = to_base64(raw).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
raw.fill(0);
return KEY_TEXT_PREFIX + base64url;
}
// Throws if the text isn't a key, imports it as non-extractable
export async function import_key_text(text: string) {
const not_a_key = new Error("That doesn't look like a VCES key");
const trimmed = text.trim();
if (!trimmed.startsWith(KEY_TEXT_PREFIX)) {
throw not_a_key;
}
let raw: Uint8Array<ArrayBuffer>;
try {
raw = from_base64(trimmed.slice(KEY_TEXT_PREFIX.length).replaceAll("-", "+").replaceAll("_", "/"));
} catch {
throw not_a_key;
}
if (raw.length !== 32) {
throw not_a_key;
}
const key = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, MASTER_KEY_USAGES);
raw.fill(0);
return key;
}
export async function to_non_extractable(key: CryptoKey) {
const raw = new Uint8Array(await crypto.subtle.exportKey("raw", key));
const locked = await crypto.subtle.importKey("raw", raw, "AES-GCM", false, MASTER_KEY_USAGES);
raw.fill(0);
return locked;
}
// Stored on the server so a key can be checked before it's used, IV goes in front of the ciphertext
export async function make_key_check(key: CryptoKey) {
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const ciphertext = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, KEY_CHECK_PLAINTEXT);
return to_base64(concat(iv, new Uint8Array(ciphertext)));
}
export async function verify_key_check(key: CryptoKey, key_check: string) {
const bytes = from_base64(key_check);
try {
await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: bytes.slice(0, IV_LENGTH) },
key,
bytes.slice(IV_LENGTH),
);
return true;
} catch {
return false;
}
}
async function derive_wrapping_key(passphrase: string, salt: Uint8Array<ArrayBuffer>, iterations: number) {
const base = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(passphrase.normalize("NFC")),
"PBKDF2",
false,
["deriveKey"],
);
return crypto.subtle.deriveKey(
{ name: "PBKDF2", hash: "SHA-256", salt, iterations },
base,
{ name: "AES-GCM", length: 256 },
false,
["wrapKey", "unwrapKey"],
);
}
// The key must be extractable to be wrapped
export async function wrap_with_passphrase(key: CryptoKey, passphrase: string): Promise<PassphraseBackup> {
const salt = crypto.getRandomValues(new Uint8Array(16));
const wrapping_key = await derive_wrapping_key(passphrase, salt, PBKDF2_ITERATIONS);
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
const wrapped = await crypto.subtle.wrapKey("raw", key, wrapping_key, { name: "AES-GCM", iv });
return {
wrapped_key: to_base64(concat(iv, new Uint8Array(wrapped))),
salt: to_base64(salt),
iterations: PBKDF2_ITERATIONS,
};
}
// Throws if the passphrase is wrong, the unwrapped key is non-extractable
export async function unwrap_with_passphrase(backup: PassphraseBackup, passphrase: string) {
const wrapping_key = await derive_wrapping_key(passphrase, from_base64(backup.salt), backup.iterations);
const wrapped = from_base64(backup.wrapped_key);
try {
return await crypto.subtle.unwrapKey(
"raw",
wrapped.slice(IV_LENGTH),
wrapping_key,
{ name: "AES-GCM", iv: wrapped.slice(0, IV_LENGTH) },
"AES-GCM",
false,
MASTER_KEY_USAGES,
);
} catch {
throw new Error("Wrong passphrase");
}
}
+1
View File
@@ -1 +1,2 @@
export const DATABASE_PATH = Deno.env.get("DATABASE_PATH");
export const FILE_UPLOAD_PATH = Deno.env.get("FILE_UPLOAD_PATH");