04/16 Upload codebase
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* auth.js — Register and Login flows (including TOTP MFA step)
|
||||
*
|
||||
* Master password never leaves the browser. Only the PBKDF2-derived authHash
|
||||
* is sent to the server for authentication.
|
||||
*/
|
||||
|
||||
const Auth = (() => {
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function csrfToken() {
|
||||
const meta = document.querySelector('meta[name="csrf-token"]');
|
||||
return meta ? meta.content : '';
|
||||
}
|
||||
|
||||
function showError(formEl, message) {
|
||||
let el = formEl.querySelector('.form-error');
|
||||
if (!el) {
|
||||
el = document.createElement('p');
|
||||
el.className = 'form-error';
|
||||
formEl.prepend(el);
|
||||
}
|
||||
el.textContent = message;
|
||||
el.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function setLoading(btn, loading) {
|
||||
btn.disabled = loading;
|
||||
btn.textContent = loading ? btn.dataset.loadingText || 'Please wait…' : btn.dataset.originalText;
|
||||
}
|
||||
|
||||
// ── Register ─────────────────────────────────────────────────────────────
|
||||
|
||||
async function handleRegister(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
|
||||
const email = form.email.value.trim().toLowerCase();
|
||||
const password = form.password.value;
|
||||
const confirm = form.confirm_password.value;
|
||||
|
||||
if (password !== confirm) { showError(form, 'Passwords do not match.'); return; }
|
||||
if (password.length < 12) { showError(form, 'Master password must be at least 12 characters.'); return; }
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const authHash = await Crypto.deriveAuthHash(password, email);
|
||||
const enc_key_salt = Crypto.generateSalt(16);
|
||||
|
||||
const res = await fetch('/api/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ email, auth_hash: authHash, enc_key_salt }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError(form, data.error || 'Registration failed.'); return; }
|
||||
window.location.href = '/login?registered=1';
|
||||
} catch (err) {
|
||||
showError(form, 'An unexpected error occurred. Please try again.');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Login ─────────────────────────────────────────────────────────────────
|
||||
|
||||
// Temporarily held between Step 1 and Step 2
|
||||
let _pendingMfaToken = null;
|
||||
let _pendingEncKeySalt = null;
|
||||
let _pendingPassword = null;
|
||||
|
||||
async function handleLogin(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
|
||||
const email = form.email.value.trim().toLowerCase();
|
||||
const password = form.password.value;
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const authHash = await Crypto.deriveAuthHash(password, email);
|
||||
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ email, auth_hash: authHash }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError(form, data.error || 'Invalid email or password.'); return; }
|
||||
|
||||
if (data.mfa_required) {
|
||||
// Step 2: collect TOTP code
|
||||
_pendingMfaToken = data.mfa_token;
|
||||
_pendingEncKeySalt = data.enc_key_salt;
|
||||
_pendingPassword = password;
|
||||
sessionStorage.setItem('enc_key_salt', data.enc_key_salt);
|
||||
showMfaStep();
|
||||
return;
|
||||
}
|
||||
|
||||
await completeLogin(password, data);
|
||||
} catch (err) {
|
||||
showError(form, 'An unexpected error occurred. Please try again.');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMfaVerify(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const btn = form.querySelector('[type="submit"]');
|
||||
btn.dataset.originalText = btn.textContent;
|
||||
const errEl = document.getElementById('mfa-error');
|
||||
errEl.classList.add('hidden');
|
||||
|
||||
const totp_code = document.getElementById('mfa-code').value.trim();
|
||||
if (!totp_code) return;
|
||||
|
||||
setLoading(btn, true);
|
||||
try {
|
||||
const res = await fetch('/api/auth/mfa/verify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken() },
|
||||
body: JSON.stringify({ mfa_token: _pendingMfaToken, totp_code }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { errEl.classList.remove('hidden'); return; }
|
||||
|
||||
await completeLogin(_pendingPassword, {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
enc_key_salt: _pendingEncKeySalt,
|
||||
});
|
||||
} catch (err) {
|
||||
errEl.classList.remove('hidden');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(btn, false);
|
||||
}
|
||||
}
|
||||
|
||||
async function completeLogin(password, data) {
|
||||
sessionStorage.setItem('access_token', data.access_token);
|
||||
localStorage.setItem('refresh_token', data.refresh_token);
|
||||
sessionStorage.setItem('enc_key_salt', data.enc_key_salt);
|
||||
|
||||
// Notify the browser extension (if installed) so it can share the session
|
||||
window.dispatchEvent(new CustomEvent('passkeeper:session', {
|
||||
detail: {
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
enc_key_salt: data.enc_key_salt,
|
||||
},
|
||||
}));
|
||||
|
||||
const vaultKey = await Crypto.deriveVaultKey(password, data.enc_key_salt);
|
||||
VaultSession.setKey(vaultKey);
|
||||
|
||||
window.location.href = '/vault';
|
||||
}
|
||||
|
||||
function showMfaStep() {
|
||||
document.getElementById('login-step-1').classList.add('hidden');
|
||||
document.getElementById('login-step-2').classList.remove('hidden');
|
||||
document.getElementById('mfa-code').focus();
|
||||
}
|
||||
|
||||
function hideMfaStep() {
|
||||
document.getElementById('login-step-2').classList.add('hidden');
|
||||
document.getElementById('login-step-1').classList.remove('hidden');
|
||||
document.getElementById('mfa-code').value = '';
|
||||
document.getElementById('mfa-error').classList.add('hidden');
|
||||
_pendingMfaToken = null;
|
||||
_pendingEncKeySalt = null;
|
||||
_pendingPassword = null;
|
||||
}
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function initPasswordToggle(btnId, inputId) {
|
||||
const btn = document.getElementById(btnId);
|
||||
const input = document.getElementById(inputId);
|
||||
if (btn && input) {
|
||||
btn.addEventListener('click', () => {
|
||||
input.type = input.type === 'password' ? 'text' : 'password';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function initStrengthMeter() {
|
||||
const input = document.getElementById('password');
|
||||
const bar = document.getElementById('strength-bar');
|
||||
if (!input || !bar) return;
|
||||
input.addEventListener('input', function () {
|
||||
const v = this.value;
|
||||
let score = 0;
|
||||
if (v.length >= 12) score++;
|
||||
if (v.length >= 16) score++;
|
||||
if (/[A-Z]/.test(v)) score++;
|
||||
if (/[0-9]/.test(v)) score++;
|
||||
if (/[^A-Za-z0-9]/.test(v)) score++;
|
||||
const labels = ['', 'Very weak', 'Weak', 'Fair', 'Strong', 'Very strong'];
|
||||
const classes = ['', 'strength-1', 'strength-2', 'strength-3', 'strength-4', 'strength-5'];
|
||||
bar.textContent = v ? labels[score] : '';
|
||||
bar.className = 'password-strength ' + (v ? classes[score] : '');
|
||||
});
|
||||
}
|
||||
|
||||
function init() {
|
||||
const registerForm = document.getElementById('register-form');
|
||||
if (registerForm) registerForm.addEventListener('submit', handleRegister);
|
||||
|
||||
const loginForm = document.getElementById('login-form');
|
||||
if (loginForm) loginForm.addEventListener('submit', handleLogin);
|
||||
|
||||
const mfaForm = document.getElementById('mfa-form');
|
||||
if (mfaForm) mfaForm.addEventListener('submit', handleMfaVerify);
|
||||
|
||||
document.getElementById('btn-back-to-password')?.addEventListener('click', hideMfaStep);
|
||||
|
||||
initPasswordToggle('toggle-login-pass', 'password');
|
||||
initPasswordToggle('toggle-reg-pass', 'password');
|
||||
initStrengthMeter();
|
||||
|
||||
if (window.location.search.includes('registered=1')) {
|
||||
const notice = document.getElementById('register-notice');
|
||||
if (notice) notice.classList.remove('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
return { init };
|
||||
})();
|
||||
|
||||
document.addEventListener('DOMContentLoaded', Auth.init);
|
||||
|
||||
// ── VaultSession — holds the vault key for the lifetime of the browser tab ──
|
||||
const VaultSession = (() => {
|
||||
let _vaultKey = null;
|
||||
function setKey(key) { _vaultKey = key; }
|
||||
function getKey() { return _vaultKey; }
|
||||
function clear() { _vaultKey = null; }
|
||||
return { setKey, getKey, clear };
|
||||
})();
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* crypto.js — Zero-knowledge cryptography layer
|
||||
*
|
||||
* All encryption/decryption runs in the browser using the Web Crypto API.
|
||||
* The vault key (AES-256-GCM) is derived from the master password client-side
|
||||
* and is NEVER sent to the server. The server only stores encrypted blobs.
|
||||
*
|
||||
* Key derivation chain:
|
||||
* authHash = PBKDF2(masterPassword, email, 100_000 iter, SHA-256) → sent to server for auth
|
||||
* vaultKey = PBKDF2(masterPassword, enc_key_salt, 600_000 iter, SHA-256) → stays in memory only
|
||||
*/
|
||||
|
||||
const Crypto = (() => {
|
||||
const subtle = window.crypto.subtle;
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
function strToBytes(str) {
|
||||
return new TextEncoder().encode(str);
|
||||
}
|
||||
|
||||
function base64ToBytes(b64) {
|
||||
const bin = atob(b64);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
let bin = '';
|
||||
bytes.forEach(b => (bin += String.fromCharCode(b)));
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
// ── PBKDF2 key import ────────────────────────────────────────────────────
|
||||
|
||||
async function importPbkdf2Key(masterPassword) {
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
strToBytes(masterPassword),
|
||||
'PBKDF2',
|
||||
false, // not extractable
|
||||
['deriveBits', 'deriveKey']
|
||||
);
|
||||
}
|
||||
|
||||
// ── Auth hash (sent to server) ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive an auth token from the master password.
|
||||
* Used ONLY for server-side authentication — never for encryption.
|
||||
* Returns a base64 string safe to POST to /api/auth/login|register.
|
||||
*/
|
||||
async function deriveAuthHash(masterPassword, email) {
|
||||
const baseKey = await importPbkdf2Key(masterPassword);
|
||||
const bits = await subtle.deriveBits(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: strToBytes(email.toLowerCase()),
|
||||
iterations: 100_000,
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
baseKey,
|
||||
256
|
||||
);
|
||||
return bytesToBase64(new Uint8Array(bits));
|
||||
}
|
||||
|
||||
// ── Vault key (stays in memory) ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive the AES-256-GCM vault key from the master password.
|
||||
* enc_key_salt is the base64-encoded 16-byte salt returned by the server on login.
|
||||
* The returned CryptoKey is marked extractable:false — raw bytes cannot be read back.
|
||||
*/
|
||||
async function deriveVaultKey(masterPassword, enc_key_salt) {
|
||||
const baseKey = await importPbkdf2Key(masterPassword);
|
||||
return subtle.deriveKey(
|
||||
{
|
||||
name: 'PBKDF2',
|
||||
salt: base64ToBytes(enc_key_salt),
|
||||
iterations: 600_000,
|
||||
hash: 'SHA-256',
|
||||
},
|
||||
baseKey,
|
||||
{ name: 'AES-GCM', length: 256 },
|
||||
false, // extractable:false — key material cannot be exported
|
||||
['encrypt', 'decrypt']
|
||||
);
|
||||
}
|
||||
|
||||
// ── Encrypt / Decrypt ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Encrypt a plain JS object with the vault key.
|
||||
* A fresh random 12-byte IV is generated for every call (required for GCM).
|
||||
* Returns { enc_data: base64, iv: base64 }
|
||||
*/
|
||||
async function encryptItem(vaultKey, plaintextObject) {
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = strToBytes(JSON.stringify(plaintextObject));
|
||||
const ciphertext = await subtle.encrypt(
|
||||
{ name: 'AES-GCM', iv },
|
||||
vaultKey,
|
||||
plaintext
|
||||
);
|
||||
return {
|
||||
enc_data: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt an encrypted vault item back to a JS object.
|
||||
* enc_data and iv must be the base64 strings stored on the server.
|
||||
*/
|
||||
async function decryptItem(vaultKey, enc_data, iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(iv) },
|
||||
vaultKey,
|
||||
base64ToBytes(enc_data)
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plaintext));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cryptographically random base64 string (for enc_key_salt).
|
||||
* byteLength defaults to 16 (128-bit salt).
|
||||
*/
|
||||
function generateSalt(byteLength = 16) {
|
||||
return bytesToBase64(window.crypto.getRandomValues(new Uint8Array(byteLength)));
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────────
|
||||
|
||||
return { deriveAuthHash, deriveVaultKey, encryptItem, decryptItem, generateSalt };
|
||||
})();
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* sharing.js — ECDH P-256 cryptography for zero-knowledge item sharing
|
||||
*
|
||||
* Each user has a P-256 keypair:
|
||||
* - Public key : stored on server as base64 raw bytes (65-byte uncompressed point)
|
||||
* - Private key : stored on server as JWK, AES-256-GCM encrypted with the user's vault key
|
||||
*
|
||||
* When Alice shares with Bob:
|
||||
* 1. Alice fetches Bob's public key from the server
|
||||
* 2. Alice derives an ECDH shared secret: ECDH(Alice_priv, Bob_pub)
|
||||
* 3. Alice imports that shared secret as an AES-256-GCM key
|
||||
* 4. Alice encrypts the item's plaintext → (enc_data, iv)
|
||||
* 5. Alice POST /api/sharing with the ciphertext — server stores the blob
|
||||
*
|
||||
* When Bob decrypts:
|
||||
* 1. Bob fetches Alice's public key from the server (returned in inbox response)
|
||||
* 2. Bob derives the same ECDH shared secret: ECDH(Bob_priv, Alice_pub) ← commutative!
|
||||
* 3. Bob decrypts enc_data with the derived key
|
||||
*
|
||||
* The server only ever sees ciphertext. Zero-knowledge.
|
||||
*/
|
||||
|
||||
const SharingCrypto = (() => {
|
||||
const subtle = window.crypto.subtle;
|
||||
|
||||
// ── Helpers (same encoding as crypto.js) ─────────────────────────────────
|
||||
|
||||
function base64ToBytes(b64) {
|
||||
const bin = atob(b64);
|
||||
const bytes = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function bytesToBase64(bytes) {
|
||||
let bin = '';
|
||||
bytes.forEach(b => (bin += String.fromCharCode(b)));
|
||||
return btoa(bin);
|
||||
}
|
||||
|
||||
// ── Key generation ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a fresh ECDH P-256 keypair.
|
||||
* Both keys are extractable so they can be exported/stored.
|
||||
*/
|
||||
async function generateKeyPair() {
|
||||
return subtle.generateKey(
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
true,
|
||||
['deriveBits'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export the public key as raw bytes (uncompressed point, 65 bytes) → base64.
|
||||
* This is what gets stored on the server and shared with other users.
|
||||
*/
|
||||
async function exportPublicKey(publicKey) {
|
||||
const raw = await subtle.exportKey('raw', publicKey);
|
||||
return bytesToBase64(new Uint8Array(raw));
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt the private key JWK with the user's vault key (AES-256-GCM).
|
||||
* The resulting ciphertext is stored on the server — only the user can decrypt it.
|
||||
*/
|
||||
async function encryptPrivateKey(vaultKey, privateKey) {
|
||||
const jwk = await subtle.exportKey('jwk', privateKey);
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(JSON.stringify(jwk));
|
||||
const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv }, vaultKey, plaintext);
|
||||
return {
|
||||
private_key_enc: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
private_key_iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt the private key JWK (fetched from server) using the user's vault key.
|
||||
* Returns a CryptoKey usable for ECDH deriveBits.
|
||||
*/
|
||||
async function decryptPrivateKey(vaultKey, private_key_enc, private_key_iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(private_key_iv) },
|
||||
vaultKey,
|
||||
base64ToBytes(private_key_enc),
|
||||
);
|
||||
const jwk = JSON.parse(new TextDecoder().decode(plaintext));
|
||||
return subtle.importKey(
|
||||
'jwk',
|
||||
jwk,
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
false,
|
||||
['deriveBits'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a remote user's public key from its base64 raw representation.
|
||||
*/
|
||||
async function importPublicKey(base64Raw) {
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
base64ToBytes(base64Raw),
|
||||
{ name: 'ECDH', namedCurve: 'P-256' },
|
||||
false,
|
||||
[], // public keys have no usages in WebCrypto ECDH
|
||||
);
|
||||
}
|
||||
|
||||
// ── Shared-secret derivation ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Derive an AES-256-GCM CryptoKey from the ECDH shared secret.
|
||||
* ECDH is commutative: ECDH(A_priv, B_pub) === ECDH(B_priv, A_pub).
|
||||
*/
|
||||
async function deriveSharedKey(myPrivateKey, theirPublicKey) {
|
||||
const bits = await subtle.deriveBits(
|
||||
{ name: 'ECDH', public: theirPublicKey },
|
||||
myPrivateKey,
|
||||
256,
|
||||
);
|
||||
return subtle.importKey(
|
||||
'raw',
|
||||
bits,
|
||||
{ name: 'AES-GCM' },
|
||||
false,
|
||||
['encrypt', 'decrypt'],
|
||||
);
|
||||
}
|
||||
|
||||
// ── Encrypt / Decrypt with shared key ────────────────────────────────────
|
||||
|
||||
async function encryptForShare(sharedKey, plaintextObject) {
|
||||
const iv = window.crypto.getRandomValues(new Uint8Array(12));
|
||||
const plaintext = new TextEncoder().encode(JSON.stringify(plaintextObject));
|
||||
const ciphertext = await subtle.encrypt({ name: 'AES-GCM', iv }, sharedKey, plaintext);
|
||||
return {
|
||||
enc_data: bytesToBase64(new Uint8Array(ciphertext)),
|
||||
iv: bytesToBase64(iv),
|
||||
};
|
||||
}
|
||||
|
||||
async function decryptShare(sharedKey, enc_data, iv) {
|
||||
const plaintext = await subtle.decrypt(
|
||||
{ name: 'AES-GCM', iv: base64ToBytes(iv) },
|
||||
sharedKey,
|
||||
base64ToBytes(enc_data),
|
||||
);
|
||||
return JSON.parse(new TextDecoder().decode(plaintext));
|
||||
}
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────
|
||||
|
||||
return {
|
||||
generateKeyPair,
|
||||
exportPublicKey,
|
||||
encryptPrivateKey,
|
||||
decryptPrivateKey,
|
||||
importPublicKey,
|
||||
deriveSharedKey,
|
||||
encryptForShare,
|
||||
decryptShare,
|
||||
};
|
||||
})();
|
||||
|
||||
/**
|
||||
* SharingSession — holds the decrypted ECDH private key for the tab lifetime.
|
||||
* Similar to VaultSession; cleared on sign-out.
|
||||
*/
|
||||
const SharingSession = (() => {
|
||||
let _privateKey = null;
|
||||
|
||||
function setKey(key) { _privateKey = key; }
|
||||
function getKey() { return _privateKey; }
|
||||
function clear() { _privateKey = null; }
|
||||
function isReady() { return _privateKey !== null; }
|
||||
|
||||
return { setKey, getKey, clear, isReady };
|
||||
})();
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user