Open in a new tab

A passphrase derives the key (Argon2id, PBKDF2 fallback), each note is sealed with ChaCha20-Poly1305 before it reaches IndexedDB, and a wrong passphrase fails cleanly instead of showing garbage.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Data a user wants kept private on a shared or lost device: journal entries, drafts, credentials. What this recipe protects against: reading the stored bytes without the passphrase, and moving a sealed note to another id. What it does not protect against: a compromised page or extension (the key is in memory while unlocked), a weak passphrase (Argon2id slows guessing, it cannot stop it), and a device that keeps the page open.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js, vault.js and store.js next to each other and open index.html through that server. The .wasm for Argon2id loads from /vendor/fw/crypto/wasm/. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep the parameters: Argon2id 12 MiB / 3 passes / 32-byte key (as in fw/crypto-password), PBKDF2-HMAC-SHA256 600 000 iterations when WebAssembly is off; a 16-byte random salt per vault, a 12-byte random nonce per note.

What it shows

How it fits together

  • Key derivation comes from fw/crypto-password: the same wasmArgon2.hash parameters and the same PBKDF2 fallback, in vault.js. The slow key derivation runs once per unlock, also on the first one that creates the vault.
  • Sealing comes from fw/crypto-aead: chacha20poly1305.encrypt / decrypt with a fresh random nonce, the note id as associated data; null on a bad tag, never a wrong plaintext.
  • Storage comes from fw/dom-storage: indexedDB.open with an upgrade callback and two stores, in store.js; an in-memory store with the same four calls when IndexedDB is unavailable. Note ids start with their time, so the list keeps the writing order; fw's uuid makes them unique.
  • The vault record keeps the salt, the KDF and the parameters it actually applied, and every later unlock derives with exactly those: raising the parameters in vault.js changes new vaults only, and an Argon2id vault opened where WebAssembly is off says so instead of "wrong passphrase".
  • A sealed check value in the vault record is how a wrong passphrase is detected without decrypting a note; the key never touches the store.
  • A form whose action fails (adding a note while locked, for example) shows "not saved: …" (or "not unlocked: …") instead of leaving an unhandled rejection.

Code

main.js

javascriptApache-2.080 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { wasmArgon2 } from '@awacloud/fw/crypto/wasm/argon2.js';
import { pbkdf2 } from '@awacloud/fw/crypto/hash/pbkdf2.js';
import { chacha20poly1305 } from '@awacloud/fw/crypto/mode/chacha20poly1305.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';
import { uuid } from '@awacloud/fw/crypto/utils/uuid.js';
import { indexedDB } from '@awacloud/fw/dom/fs/indexedDB.js';
import { createVault } from './vault.js';
import { openStore } from './store.js';

fw.runtime.registerAllDeep([wasmArgon2, pbkdf2, chacha20poly1305, random, uuid, indexedDB]);
const UUID = fw.runtime.resolve('uuid');
const KDF_AND_AEAD = ['wasmArgon2', 'pbkdf2', 'bitArray', 'chacha20poly1305', 'random'];
export const vault = createVault(fw.runtime.resolveAll(KDF_AND_AEAD));

export const store = await openStore(fw.runtime.resolve('indexedDB'));

/** @type {Uint8Array | null} the derived key while unlocked; never stored */
let key = null;
const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));
const status = (/** @type {string} */ text) => { el('status').textContent = text; };

/**
 * The first unlock creates the vault: salt, the KDF and the parameters it
 * applied, and a sealed check value. Later unlocks derive with that stored KDF
 * and those parameters and must open the check value, which is how a wrong
 * passphrase is detected. The slow KDF runs once per unlock.
 * @param {string} passphrase
 * @param {object} [params] KDF parameters for a NEW vault (smaller ones in tests)
 */
export async function unlock(passphrase, params = {}) {
    const meta = await store.vault.get('meta');
    const salt = meta?.salt ?? vault.newSalt();
    const derived = await vault.deriveKey(passphrase, salt, meta?.params ?? params, meta?.kdf);
    if (!meta) {
        const check = vault.seal(derived.key, 'check', 'ok'); // opening it later proves the passphrase
        await store.vault.set('meta', { salt, kdf: derived.kdf, params: derived.params, check });
    } else if (vault.open(derived.key, 'check', meta.check) !== 'ok') {
        key = null;
        status('wrong passphrase');
        return false;
    }
    key = derived.key;
    status(`unlocked (${derived.kdf})`);
    await refresh();
    return true;
}
export function lock() { key = null; status('locked'); refresh(); }

/** @param {string} text @returns {Promise<string>} the note id: its time first, so ids sort in writing order */
export async function addNote(text) {
    if (!key) throw new Error('locked');
    const id = `note-${String(Date.now()).padStart(15, '0')}-${UUID.v4()}`;
    await store.notes.set(id, vault.seal(key, id, text));
    await refresh();
    return id;
}

/** @returns {Promise<string[]>} the decrypted notes, or [] while locked */
export async function refresh() {
    const ids = key ? await store.notes.getAllKeys() : [];
    const texts = [];
    for (const id of ids) texts.push(vault.open(key, String(id), await store.notes.get(id)) ?? '(cannot decrypt)');
    el('notes').replaceChildren(...texts.map((t) => Object.assign(document.createElement('li'), { textContent: t })));
    el('add').hidden = !key;
    /** @type {HTMLButtonElement} */ (el('lock')).disabled = !key;
    return texts;
}

/** A form's action, its failure shown. @type {(id: string, fail: string, action: () => Promise<unknown>) => void} */
const onSubmit = (id, fail, action) => el(id).addEventListener('submit', (event) => {
    event.preventDefault();
    action().catch((err) => status(`${fail}: ${/** @type {Error} */ (err).message}`));
});
el('storage').textContent = `storage: ${store.kind}`;
el('lock').addEventListener('click', lock);
onSubmit('unlock', 'not unlocked', () => unlock(/** @type {HTMLInputElement} */ (el('passphrase')).value));
const note = /** @type {HTMLInputElement} */ (el('note'));
onSubmit('add', 'not saved', () => addNote(note.value).then(() => { note.value = ''; }));

index.html

htmlApache-2.034 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Notes encrypted at rest with a passphrase</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Notes encrypted at rest with a passphrase</h1>
    <p id="storage" aria-live="polite"></p>
    <form id="unlock">
      <label for="passphrase">Passphrase</label>
      <input id="passphrase" type="password" autocomplete="current-password" required>
      <button type="submit">Unlock</button>
      <button id="lock" type="button" disabled>Lock</button>
    </form>
    <p id="status" aria-live="assertive"></p>
    <form id="add" hidden>
      <label for="note">New note</label>
      <input id="note" type="text" autocomplete="off" required>
      <button type="submit">Add</button>
    </form>
    <ol id="notes" aria-label="Notes"></ol>
  </main>
</body>
</html>

vault.js

javascriptApache-2.059 lines

// SPDX-License-Identifier: Apache-2.0
// The crypto half of the recipe: passphrase → key, seal / open of one note.
// Same Argon2id parameters as fw/crypto-password; PBKDF2 when WebAssembly is off.

export const ARGON2 = { timeCost: 3, memoryKiB: 12 * 1024, parallelism: 1, hashLen: 32 };
export const PBKDF2 = { iterations: 600000, bits: 256 };
const encoder = new TextEncoder();
const decoder = new TextDecoder();

/**
 * @param {{ wasmArgon2: any, pbkdf2: any, bitArray: any, chacha20poly1305: any, random: any }} m resolved fw modules
 * @returns {{ deriveKey: Function, seal: Function, open: Function, newSalt: () => Uint8Array }}
 */
export function createVault(m) {
    /**
     * @param {string} passphrase
     * @param {Uint8Array} salt 16 bytes, stored with the vault
     * @param {{ argon2?: typeof ARGON2, pbkdf2?: typeof PBKDF2 }} [params] smaller ones for tests
     * @param {'argon2id' | 'pbkdf2-sha256'} [kdf] an existing vault's KDF; a new one takes Argon2id when it can
     * @returns {Promise<{ key: Uint8Array, kdf: string, params: object }>} `params`: the ones applied, to store
     */
    async function deriveKey(passphrase, salt, params = {}, kdf) {
        const argon2 = params.argon2 ?? ARGON2;
        if (kdf !== 'pbkdf2-sha256' && m.wasmArgon2.isAvailable()) {
            const key = await m.wasmArgon2.hash(encoder.encode(passphrase), salt, argon2);
            if (key) return { key, kdf: 'argon2id', params: { argon2 } };
        }
        if (kdf === 'argon2id') throw new Error('this vault uses Argon2id, which needs WebAssembly in this browser');
        const pbkdf2 = params.pbkdf2 ?? PBKDF2;
        const salted = m.bitArray.ui8_to_ba(salt);
        const bits = /** @type {number[]} */ (m.pbkdf2(passphrase, salted, pbkdf2.iterations, pbkdf2.bits));
        return { key: m.bitArray.ba_to_ui8(bits), kdf: 'pbkdf2-sha256', params: { pbkdf2 } };
    }

    /**
     * nonce (12) || ciphertext || tag (16); the note id is authenticated as AAD
     * so a sealed note cannot be moved to another id.
     * @param {Uint8Array} key @param {string} id @param {string} text
     * @returns {Uint8Array}
     */
    function seal(key, id, text) {
        const nonce = /** @type {Uint8Array} */ (m.random.bytes(12));
        const { ct, tag } = m.chacha20poly1305.encrypt(key, nonce, encoder.encode(text), encoder.encode(id));
        return new Uint8Array([...nonce, ...ct, ...tag]);
    }

    /**
     * @param {Uint8Array} key @param {string} id @param {Uint8Array} sealed
     * @returns {string | null} the note, or null when the key or the id is wrong
     */
    function open(key, id, sealed) {
        const plain = m.chacha20poly1305.decrypt(
            key, sealed.subarray(0, 12), sealed.subarray(12, -16), sealed.subarray(-16), encoder.encode(id),
        );
        return plain === false ? null : decoder.decode(plain);
    }

    return { deriveKey, seal, open, newSalt: () => /** @type {Uint8Array} */ (m.random.bytes(16)) };
}

store.js

javascriptApache-2.035 lines

// SPDX-License-Identifier: Apache-2.0
// The storage half of the recipe: where the vault record and the sealed
// notes live. Only ciphertext ever reaches it.

/** An in-memory store with the four calls the recipe uses. */
function memoryStore() {
    const map = new Map();
    return {
        get: async (/** @type {string} */ k) => map.get(k),
        set: async (/** @type {string} */ k, /** @type {unknown} */ v) => { map.set(k, v); },
        getAllKeys: async () => [...map.keys()],
        del: async (/** @type {string} */ k) => { map.delete(k); },
    };
}

/**
 * Persistent when IndexedDB exists, in memory otherwise: the same four calls
 * either way.
 * @param {any} idb fw's resolved `indexedDB` module
 */
export async function openStore(idb) {
    if (!idb.isSupported()) {
        return {
            kind: 'memory (IndexedDB unavailable: notes vanish with the page)',
            vault: memoryStore(),
            notes: memoryStore(),
        };
    }
    // The third argument is the upgrade callback, run once per version bump.
    const db = await idb.open('examples-encrypted-notes', 1, (/** @type {IDBDatabase} */ raw) => {
        raw.createObjectStore('vault');
        raw.createObjectStore('notes');
    });
    return { kind: 'IndexedDB', vault: db.store('vault'), notes: db.store('notes') };
}