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
+1 -1
View File
@@ -12,7 +12,7 @@ export default function AskCode({ page }: AskCodeProps) {
const on_success = (data: { code: string }) => {
localStorage.setItem("code", data.code);
page.value = "keys";
page.value = "keysnew";
};
useSignalEffect(() => {
+157
View File
@@ -0,0 +1,157 @@
import { useComputed, useSignal } from "@preact/signals";
import { post_json } from "@/src/client.ts";
import { save_master_key } from "@/src/key_store.ts";
import {
export_key_text,
generate_master_key,
make_key_check,
to_non_extractable,
wrap_with_passphrase,
} from "@/src/keys.ts";
const MIN_PASSPHRASE_LENGTH = 14;
interface KeysCreateProps {
user_id: string;
on_done: () => void;
// The account got a key some other way, it has to be unlocked instead
on_needs_unlock: (message: string) => void;
}
export default function KeysCreate(props: KeysCreateProps) {
const step = useSignal<"create" | "backup" | "saving">("create");
const new_key = useSignal<CryptoKey | null>(null);
const key_text = useSignal("");
const saved_file = useSignal(false);
const passphrase = useSignal("");
const passphrase_confirm = useSignal("");
const error = useSignal("");
const passphrase_error = useComputed(() => {
if (!passphrase.value && !passphrase_confirm.value) {
return "";
}
if (passphrase.value.length < MIN_PASSPHRASE_LENGTH) {
return `The passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters`;
}
if (passphrase.value !== passphrase_confirm.value) {
return "The passphrases don't match";
}
return "";
});
const can_continue = useComputed(() => !passphrase_error.value && (saved_file.value || passphrase.value !== ""));
async function create() {
const key = await generate_master_key();
new_key.value = key;
key_text.value = await export_key_text(key);
step.value = "backup";
}
function download_key_file() {
const url = URL.createObjectURL(new Blob([key_text.value + "\n"], { type: "text/plain" }));
const link = document.createElement("a");
link.href = url;
link.download = "vces-key.txt";
link.click();
// Revoking right away can cancel the download in some browsers
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
async function finish(event: SubmitEvent) {
event.preventDefault();
const key = new_key.value;
const code = localStorage.getItem("code");
if (!key || !code || !can_continue.value) {
return;
}
step.value = "saving";
error.value = "";
try {
const key_check = await make_key_check(key);
const passphrase_backup = passphrase.value ? await wrap_with_passphrase(key, passphrase.value) : undefined;
const result = await post_json("/api/create_key", { code, key_check, passphrase_backup });
if (!result.ok) {
if (result.status === 409) {
props.on_needs_unlock(result.error);
return;
}
error.value = result.error;
step.value = "backup";
return;
}
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
step.value = "backup";
return;
}
try {
await save_master_key(props.user_id, await to_non_extractable(key));
} catch {
props.on_needs_unlock(
"Your key was registered but couldn't be saved in this browser. Unlock it with your backup.",
);
return;
}
props.on_done();
}
if (step.value === "create") {
return (
<div>
<p>Your files are encrypted in this browser with a key the server never sees.</p>
<button type="button" onClick={create}>Create encryption key</button>
</div>
);
}
return (
<form onSubmit={finish}>
<fieldset disabled={step.value === "saving"}>
<p>Back up your key. If you lose it, your files can't be recovered, not even by the server.</p>
<h2>Key file</h2>
<textarea readOnly value={key_text.value} />
<button type="button" onClick={download_key_file}>Download key file</button>
<label>
<input
type="checkbox"
checked={saved_file.value}
onChange={(event) => saved_file.value = event.currentTarget.checked}
/>
I saved my key file somewhere safe
</label>
<h2>Passphrase (optional)</h2>
<p>
Stores a copy of your key on the server, locked with this passphrase, so you can unlock other
devices with it. The key file is the stronger backup.
</p>
<input
type="password"
autoComplete="new-password"
placeholder="Passphrase"
value={passphrase.value}
onInput={(event) => passphrase.value = event.currentTarget.value}
/>
<input
type="password"
autoComplete="new-password"
placeholder="Confirm passphrase"
value={passphrase_confirm.value}
onInput={(event) => passphrase_confirm.value = event.currentTarget.value}
/>
{passphrase_error.value && <p role="alert">{passphrase_error.value}</p>}
<button type="submit" disabled={!can_continue.value}>
{step.value === "saving" ? "Saving..." : "Continue"}
</button>
</fieldset>
{error.value && <p role="alert">{error.value}</p>}
</form>
);
}
+74
View File
@@ -0,0 +1,74 @@
import { Signal, useSignal, useSignalEffect } from "@preact/signals";
import KeysCreate from "@/islands/KeysCreate.tsx";
import KeysUnlock from "@/islands/KeysUnlock.tsx";
import { post_json } from "@/src/client.ts";
import { load_master_key } from "@/src/key_store.ts";
import { type GetKeyResponse, verify_key_check } from "@/src/keys.ts";
interface KeysNewProps {
page: Signal<string>;
}
export default function KeysNew(props: KeysNewProps) {
const step = useSignal<"loading" | "create" | "unlock">("loading");
const account = useSignal<GetKeyResponse | null>(null);
const load_error = useSignal("");
const unlock_message = useSignal("");
async function load_account() {
step.value = "loading";
const code = localStorage.getItem("code");
if (!code) {
props.page.value = "askcode";
return;
}
const result = await post_json<GetKeyResponse>("/api/get_key", { code });
if (!result.ok) {
load_error.value = result.error;
return;
}
account.value = result.data;
const key_check = result.data.key_check;
if (!key_check) {
step.value = "create";
return;
}
const local_key = await load_master_key(result.data.user_id).catch(() => undefined);
if (local_key && await verify_key_check(local_key, key_check)) {
props.page.value = "hub";
} else {
step.value = "unlock";
}
}
useSignalEffect(() => {
load_account();
});
function go_to_hub() {
props.page.value = "hub";
}
if (step.value === "loading" || !account.value) {
return load_error.value ? <p role="alert">{load_error.value}</p> : <p>Loading...</p>;
}
if (step.value === "create") {
return (
<KeysCreate
user_id={account.value.user_id}
on_done={go_to_hub}
on_needs_unlock={(message) => {
unlock_message.value = message;
load_account();
}}
/>
);
}
return <KeysUnlock account={account.value} message={unlock_message.value} on_done={go_to_hub} />;
}
+107
View File
@@ -0,0 +1,107 @@
import { useSignal } from "@preact/signals";
import { save_master_key } from "@/src/key_store.ts";
import { type GetKeyResponse, import_key_text, unwrap_with_passphrase, verify_key_check } from "@/src/keys.ts";
const MAX_KEY_FILE_SIZE = 1024;
interface KeysUnlockProps {
account: GetKeyResponse;
message: string;
on_done: () => void;
}
export default function KeysUnlock(props: KeysUnlockProps) {
const passphrase = useSignal("");
const key_text = useSignal("");
const working = useSignal(false);
const error = useSignal(props.message);
async function unlock(get_key: () => Promise<CryptoKey>) {
working.value = true;
error.value = "";
try {
const key = await get_key();
if (!props.account.key_check || !(await verify_key_check(key, props.account.key_check))) {
error.value = "That key doesn't belong to this account";
return;
}
await save_master_key(props.account.user_id, key);
props.on_done();
} catch (err) {
error.value = err instanceof Error ? err.message : String(err);
} finally {
working.value = false;
}
}
function unlock_with_passphrase(event: SubmitEvent) {
event.preventDefault();
const backup = props.account.passphrase_backup;
if (backup && passphrase.value) {
unlock(() => unwrap_with_passphrase(backup, passphrase.value));
}
}
function unlock_with_key_text(event: SubmitEvent) {
event.preventDefault();
if (key_text.value) {
unlock(() => import_key_text(key_text.value));
}
}
async function unlock_with_key_file(event: Event) {
const input = event.currentTarget as HTMLInputElement;
const file = input.files?.[0];
input.value = "";
if (!file) {
return;
}
if (file.size > MAX_KEY_FILE_SIZE) {
error.value = "That doesn't look like a VCES key";
return;
}
const text = await file.text();
unlock(() => import_key_text(text));
}
return (
<div>
<p>This account already has an encryption key. Unlock it on this device with one of your backups.</p>
<fieldset disabled={working.value}>
{props.account.passphrase_backup && (
<form onSubmit={unlock_with_passphrase}>
<h2>Passphrase</h2>
<input
type="password"
autoComplete="current-password"
placeholder="Passphrase"
value={passphrase.value}
onInput={(event) => passphrase.value = event.currentTarget.value}
/>
<button type="submit">Unlock</button>
</form>
)}
<h2>Key file</h2>
<input type="file" accept=".txt,text/plain" onChange={unlock_with_key_file} />
<form onSubmit={unlock_with_key_text}>
<p>Or paste the key:</p>
<textarea
autoComplete="off"
spellcheck={false}
placeholder="vces-key-v1:..."
value={key_text.value}
onInput={(event) => key_text.value = event.currentTarget.value}
/>
<button type="submit">Unlock</button>
</form>
</fieldset>
{working.value && <p>Unlocking...</p>}
{error.value && <p role="alert">{error.value}</p>}
</div>
);
}
+5 -2
View File
@@ -1,14 +1,17 @@
import { useSignal } from "@preact/signals";
import AskCode from "./AskCode.tsx";
import KeysNew from "@/islands/KeysNew.tsx";
export default function MainIsland() {
const page = useSignal("askcode");
if (page.value === "askcode") {
return <AskCode page={page} />;
} else if (page.value === "keys") {
return localStorage.getItem("code");
} else if (page.value === "keysnew") {
return <KeysNew page={page} />;
} else if (page.value === "hub") {
return <p>TODO: hub</p>;
} else {
return "Error";
}
+49
View File
@@ -0,0 +1,49 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import { db } from "@/src/db.ts";
const CreateKeyBody = z.object({
code: z.string().min(1),
key_check: z.string().min(1).max(200),
passphrase_backup: z.object({
wrapped_key: z.string().min(1).max(200),
salt: z.string().min(1).max(100),
iterations: z.number().int().min(100_000).max(10_000_000),
}).optional(),
});
export const handler = define.handlers({
async POST(ctx) {
const body = CreateKeyBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const user = await db.get_entry_by_index("users", "code", body.data.code);
if (!user) {
return Response.json({ error: "Invalid code" }, { status: 401 });
}
const already_exists = Response.json({ error: "This account already has an encryption key" }, { status: 409 });
const entry = await db.get_entry_full("users", user.id);
if (!entry || entry.value.key_check) {
return already_exists;
}
// Checked against the versionstamp so two tabs can't both register a key
const result = await db.kv.atomic()
.check(entry)
.set(entry.key, {
...entry.value,
key_check: body.data.key_check,
passphrase_backup: body.data.passphrase_backup,
})
.commit();
if (!result.ok) {
return already_exists;
}
return new Response(null, { status: 204 });
},
});
+32
View File
@@ -0,0 +1,32 @@
import { z } from "@zod/zod";
import { define } from "@/utils.ts";
import { db, type User } from "@/src/db.ts";
import type { GetKeyResponse } from "@/src/keys.ts";
const GetKeyBody = z.object({
code: z.string().min(1),
});
export const handler = define.handlers({
async POST(ctx) {
const body = GetKeyBody.safeParse(await ctx.req.json().catch(() => null));
if (!body.success) {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const user = await db.get_entry_by_index("users", "code", body.data.code);
if (!user) {
return Response.json({ error: "Invalid code" }, { status: 401 });
}
const { key_check, passphrase_backup } = user as Partial<User>;
return Response.json(
{
user_id: user.id,
key_check: key_check ?? null,
passphrase_backup: passphrase_backup ?? null,
} satisfies GetKeyResponse,
);
},
});
+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");