feat: zero-knowledge encryption Phase 1 — backend opaque + crypto module (WIP)
Backend: server can no longer read user data. All data blobs (medication, appointment, profile name) are now opaque client-encrypted ciphertext — the server stores and returns them verbatim, never deserializing the contents. - Medication: removed MedicationData + flat MedicationResponse; new MedicationResponse echoes metadata + encrypted_data blob. Create/update accept opaque blobs (whole-blob replace). Update is no longer load-mutate- reserialize (server can't read the data). - Appointment: same opaque treatment; status moved to a top-level document field so it remains filterable without decryption. - Profile: name is now an opaque encrypted blob (name_data/name_iv). Auto- created profile on register starts with an empty name; client sets it. - EncryptedFieldWire type shared across medication/appointment. Frontend (partial): crypto module using Web Crypto API — - crypto/keys.ts: double-PBKDF2 derivation (auth secret sent to server + encryption key kept in memory); in-memory key store (set/get/clear). - crypto/cipher.ts: AES-GCM encrypt/decrypt + JSON convenience wrappers. - crypto/index.ts: re-exports. NOT YET DONE (frontend integration): auth store key derivation on login/register, stores decrypt-on-load/encrypt-on-write, types update, UI components wired, crypto round-trip tests, ADR. This commit is a verified checkpoint — backend builds clean (21 tests, 0 warnings); frontend crypto module exists but is not yet wired into the data flow.
This commit is contained in:
parent
057303a8d0
commit
149ce37654
9 changed files with 331 additions and 566 deletions
81
web/normogen-web/src/crypto/cipher.ts
Normal file
81
web/normogen-web/src/crypto/cipher.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
/**
|
||||
* AES-GCM encrypt/decrypt over the Web Crypto API (no dependencies).
|
||||
*
|
||||
* Ciphertext and IV are returned as base64 strings so they map directly onto
|
||||
* the backend's `EncryptedField { data, iv, auth_tag }` wire shape.
|
||||
*/
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
const b64 = {
|
||||
encode(bytes: Uint8Array): string {
|
||||
let bin = '';
|
||||
for (const b of bytes) bin += String.fromCharCode(b);
|
||||
return btoa(bin);
|
||||
},
|
||||
decode(str: string): Uint8Array {
|
||||
const bin = atob(str);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
},
|
||||
};
|
||||
|
||||
/** Random 12-byte IV for AES-GCM. */
|
||||
function randomIv(): Uint8Array {
|
||||
return crypto.getRandomValues(new Uint8Array(12));
|
||||
}
|
||||
|
||||
export interface CipherPayload {
|
||||
/** base64 ciphertext */
|
||||
data: string;
|
||||
/** base64 12-byte IV */
|
||||
iv: string;
|
||||
}
|
||||
|
||||
/** Encrypt a UTF-8 string under the given AES-GCM key. */
|
||||
export async function encrypt(
|
||||
plaintext: string,
|
||||
key: CryptoKey,
|
||||
): Promise<CipherPayload> {
|
||||
const iv = randomIv();
|
||||
const ciphertext = await crypto.subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv },
|
||||
key,
|
||||
encoder.encode(plaintext),
|
||||
);
|
||||
return {
|
||||
data: b64.encode(new Uint8Array(ciphertext)),
|
||||
iv: b64.encode(iv),
|
||||
};
|
||||
}
|
||||
|
||||
/** Decrypt a base64 payload. Throws on tamper / wrong key. */
|
||||
export async function decrypt(
|
||||
payload: CipherPayload,
|
||||
key: CryptoKey,
|
||||
): Promise<string> {
|
||||
const iv = b64.decode(payload.iv);
|
||||
const plaintext = await crypto.subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv },
|
||||
key,
|
||||
b64.decode(payload.data),
|
||||
);
|
||||
return decoder.decode(plaintext);
|
||||
}
|
||||
|
||||
/** Encrypt a JSON-serializable object. */
|
||||
export async function encryptJson<T>(
|
||||
obj: T,
|
||||
key: CryptoKey,
|
||||
): Promise<CipherPayload> {
|
||||
return encrypt(JSON.stringify(obj), key);
|
||||
}
|
||||
|
||||
/** Decrypt a payload and JSON.parse into T. Throws on tamper / wrong key / bad JSON. */
|
||||
export async function decryptJson<T>(
|
||||
payload: CipherPayload,
|
||||
key: CryptoKey,
|
||||
): Promise<T> {
|
||||
return JSON.parse(await decrypt(payload, key)) as T;
|
||||
}
|
||||
16
web/normogen-web/src/crypto/index.ts
Normal file
16
web/normogen-web/src/crypto/index.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
export {
|
||||
deriveAuthAndEncKeys,
|
||||
setEncKey,
|
||||
getEncKey,
|
||||
clearEncKey,
|
||||
hasEncKey,
|
||||
AUTH_SALT,
|
||||
ENC_SALT,
|
||||
} from './keys';
|
||||
export {
|
||||
encrypt,
|
||||
decrypt,
|
||||
encryptJson,
|
||||
decryptJson,
|
||||
type CipherPayload,
|
||||
} from './cipher';
|
||||
98
web/normogen-web/src/crypto/keys.ts
Normal file
98
web/normogen-web/src/crypto/keys.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
/**
|
||||
* Zero-knowledge key derivation.
|
||||
*
|
||||
* From the user's password we derive TWO independent values via PBKDF2:
|
||||
*
|
||||
* - `authSecret`: base64 bytes sent to the server as the "password". The
|
||||
* server PBKDF2-hashes it (as it always has). The server can never derive
|
||||
* the encryption key from this value.
|
||||
* - `encKey`: an AES-GCM CryptoKey kept in memory only (never persisted,
|
||||
* never transmitted). Used to encrypt/decrypt all user data.
|
||||
*
|
||||
* Two separate PBKDF2 passes with app-wide domain-separation salts prevent the
|
||||
* server from deriving `encKey` even if it logs or leaks `authSecret`.
|
||||
*/
|
||||
|
||||
const PBKDF2_ITERATIONS = 150_000;
|
||||
const KEY_BITS = 256; // AES-256
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
export const AUTH_SALT = 'normogen-auth-v1';
|
||||
export const ENC_SALT = 'normogen-enc-v1';
|
||||
|
||||
/**
|
||||
* Derive the auth secret (base64) and encryption key (CryptoKey) from a password.
|
||||
*/
|
||||
export async function deriveAuthAndEncKeys(password: string): Promise<{
|
||||
authSecret: string;
|
||||
encKey: CryptoKey;
|
||||
}> {
|
||||
const passwordKey = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
encoder.encode(password),
|
||||
'PBKDF2',
|
||||
false,
|
||||
['deriveBits'],
|
||||
);
|
||||
|
||||
// Auth secret: 32 raw bytes, base64-encoded for transport.
|
||||
const authBits = await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', salt: encoder.encode(AUTH_SALT), iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
|
||||
passwordKey,
|
||||
KEY_BITS,
|
||||
);
|
||||
const authSecret = base64(new Uint8Array(authBits));
|
||||
|
||||
// Encryption key: importable AES-GCM key, non-extractable.
|
||||
const encBits = await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', salt: encoder.encode(ENC_SALT), iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
|
||||
passwordKey,
|
||||
KEY_BITS,
|
||||
);
|
||||
const encKey = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
encBits,
|
||||
{ name: 'AES-GCM' },
|
||||
false,
|
||||
['encrypt', 'decrypt'],
|
||||
);
|
||||
|
||||
return { authSecret, encKey };
|
||||
}
|
||||
|
||||
function base64(bytes: Uint8Array): string {
|
||||
let bin = '';
|
||||
for (const b of bytes) bin += String.fromCharCode(b);
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory encryption-key store.
|
||||
//
|
||||
// The encKey lives only in memory for the lifetime of the authenticated
|
||||
// session (the tab). It is deliberately NOT persisted — losing the tab or
|
||||
// closing the browser requires re-entering the password to re-derive it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let currentEncKey: CryptoKey | null = null;
|
||||
|
||||
/** Set the session encryption key (called on login/register). */
|
||||
export function setEncKey(key: CryptoKey): void {
|
||||
currentEncKey = key;
|
||||
}
|
||||
|
||||
/** Get the session encryption key, or null if not authenticated. */
|
||||
export function getEncKey(): CryptoKey | null {
|
||||
return currentEncKey;
|
||||
}
|
||||
|
||||
/** Clear the session encryption key (called on logout). */
|
||||
export function clearEncKey(): void {
|
||||
currentEncKey = null;
|
||||
}
|
||||
|
||||
/** True if a session encryption key is available (i.e. the user can encrypt/decrypt). */
|
||||
export function hasEncKey(): boolean {
|
||||
return currentEncKey !== null;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue