04/16 Upload codebase

This commit is contained in:
2026-04-16 08:27:07 -04:00
parent 91be5c1f5c
commit 457016b8d4
43 changed files with 6241 additions and 0 deletions
+555
View File
@@ -0,0 +1,555 @@
/* ── Reset & base ──────────────────────────────────────────────────── */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--color-bg: #f4f5f7;
--color-surface: #ffffff;
--color-primary: #d0021b;
--color-primary-dark: #a80016;
--color-text: #1a1a2e;
--color-text-muted: #6b7280;
--color-border: #e2e4e9;
--color-sidebar-bg: #1e2235;
--color-sidebar-text: #c8ccd8;
--color-sidebar-hover: #2d3250;
--color-sidebar-active: #d0021b;
--radius: 8px;
--shadow: 0 1px 4px rgba(0,0,0,.08), 0 2px 12px rgba(0,0,0,.05);
--transition: 150ms ease;
}
html, body { height: 100%; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; color: var(--color-text); background: var(--color-bg); }
a { color: var(--color-primary); text-decoration: none; }
a:hover { text-decoration: underline; }
button { cursor: pointer; font: inherit; border: none; background: none; }
input, select, textarea { font: inherit; }
ul { list-style: none; }
/* ── Utilities ───────────────────────────────────────────────────── */
.hidden { display: none !important; }
/* ── Auth pages ──────────────────────────────────────────────────── */
.auth-page { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: var(--color-bg); }
.auth-container { width: 100%; max-width: 420px; padding: 16px; }
.auth-card {
background: var(--color-surface);
border-radius: var(--radius);
box-shadow: var(--shadow);
padding: 40px 36px;
}
.auth-logo { display: flex; align-items: center; gap: 8px; margin-bottom: 28px; }
.auth-logo .logo-icon { font-size: 28px; }
.auth-logo .logo-text { font-size: 20px; font-weight: 700; color: var(--color-text); }
.auth-title { font-size: 22px; font-weight: 600; margin-bottom: 24px; }
.auth-footer { margin-top: 20px; text-align: center; color: var(--color-text-muted); }
/* ── Form elements ──────────────────────────────────────────────── */
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 500; color: var(--color-text); }
.form-group label .hint { font-weight: 400; color: var(--color-text-muted); font-size: 12px; }
.form-group input,
.form-group select,
.form-group textarea {
width: 100%;
padding: 9px 12px;
border: 1px solid var(--color-border);
border-radius: var(--radius);
background: var(--color-surface);
color: var(--color-text);
transition: border-color var(--transition);
}
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(208,2,27,.12);
}
.input-with-toggle { position: relative; }
.input-with-toggle input { padding-right: 40px; }
.btn-show-pass {
position: absolute; right: 10px; top: 50%; transform: translateY(-50%);
background: none; border: none; cursor: pointer; font-size: 16px; opacity: .6;
transition: opacity var(--transition);
}
.btn-show-pass:hover { opacity: 1; }
.form-error { color: #c00; background: #fff0f0; border: 1px solid #fcc; border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; font-size: 13px; }
/* Buttons */
.btn-primary {
display: inline-flex; align-items: center; justify-content: center;
background: var(--color-primary); color: #fff;
padding: 10px 20px; border-radius: var(--radius); font-weight: 600;
transition: background var(--transition);
}
.btn-primary:hover { background: var(--color-primary-dark); }
.btn-primary:disabled { opacity: .6; cursor: not-allowed; }
.btn-full { width: 100%; }
.btn-secondary {
display: inline-flex; align-items: center; justify-content: center;
background: var(--color-border); color: var(--color-text);
padding: 10px 20px; border-radius: var(--radius); font-weight: 500;
transition: background var(--transition);
}
.btn-secondary:hover { background: #d1d5dc; }
.btn-text { background: none; border: none; color: inherit; padding: 0; }
/* Notices */
.notice-success { background: #e8f5e9; border: 1px solid #a5d6a7; color: #2e7d32; border-radius: var(--radius); padding: 10px 14px; margin-bottom: 16px; font-size: 13px; }
.notice-info { background: #e3f2fd; border: 1px solid #90caf9; color: #1565c0; border-radius: var(--radius); padding: 10px 14px; margin-bottom: 16px; font-size: 13px; }
/* Password strength */
.password-strength { margin-top: 6px; font-size: 12px; font-weight: 500; }
.strength-1 { color: #c62828; }
.strength-2 { color: #e65100; }
.strength-3 { color: #f57f17; }
.strength-4 { color: #2e7d32; }
.strength-5 { color: #1b5e20; }
/* ── App layout (vault) ──────────────────────────────────────────── */
.vault-page { height: 100vh; overflow: hidden; }
.app-layout { display: flex; height: 100vh; }
/* ── Sidebar ─────────────────────────────────────────────────────── */
.sidebar {
width: 220px;
flex-shrink: 0;
background: var(--color-sidebar-bg);
color: var(--color-sidebar-text);
display: flex;
flex-direction: column;
overflow-y: auto;
}
.sidebar-header {
display: flex;
align-items: center;
gap: 8px;
padding: 18px 16px;
border-bottom: 1px solid rgba(255,255,255,.08);
}
.sidebar-header .logo-icon { font-size: 22px; }
.sidebar-header .logo-text { font-size: 16px; font-weight: 700; color: #fff; }
.sidebar-nav { flex: 1; padding: 8px 0; }
.sidebar-section-header {
padding: 12px 16px 4px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: .08em;
color: rgba(255,255,255,.35);
}
.sidebar-item {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 16px;
border-radius: 0;
color: var(--color-sidebar-text);
cursor: pointer;
transition: background var(--transition);
font-size: 14px;
width: 100%;
text-align: left;
}
.sidebar-item:hover { background: var(--color-sidebar-hover); }
.sidebar-item.active { background: var(--color-sidebar-active); color: #fff; }
.sidebar-icon { font-size: 16px; flex-shrink: 0; }
.sidebar-footer { padding: 12px 0; border-top: 1px solid rgba(255,255,255,.08); }
.folder-item { justify-content: space-between; }
.folder-label { display: flex; align-items: center; gap: 10px; flex: 1; cursor: pointer; }
.btn-delete-folder {
background: none; border: none; cursor: pointer;
font-size: 13px; opacity: 0; color: rgba(255,255,255,.6);
transition: opacity var(--transition), color var(--transition);
padding: 2px 4px; border-radius: 4px; flex-shrink: 0;
}
.folder-item:hover .btn-delete-folder { opacity: 1; }
.btn-delete-folder:hover { color: #ff6b6b; }
.btn-new-folder {
float: right; margin-right: 4px;
background: none; border: none; color: rgba(255,255,255,.5);
font-size: 16px; line-height: 1; cursor: pointer; padding: 0 4px;
transition: color var(--transition);
}
.btn-new-folder:hover { color: #fff; }
.new-folder-row { padding: 4px 10px 4px 16px; }
.new-folder-row form { display: flex; align-items: center; gap: 4px; }
.new-folder-row input {
flex: 1; padding: 5px 8px; border-radius: 4px; border: 1px solid rgba(255,255,255,.2);
background: rgba(255,255,255,.1); color: #fff; font-size: 13px;
}
.new-folder-row input::placeholder { color: rgba(255,255,255,.4); }
.new-folder-row input:focus { outline: none; border-color: rgba(255,255,255,.5); }
.new-folder-row .btn-icon { color: rgba(255,255,255,.7); font-size: 14px; }
.new-folder-row .btn-icon:hover { color: #fff; background: rgba(255,255,255,.1); }
/* ── Vault main ──────────────────────────────────────────────────── */
.vault-main {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--color-bg);
}
#view-vault, #view-security {
display: flex;
flex-direction: column;
flex: 1;
overflow: hidden;
min-height: 0;
position: relative;
}
#view-vault.hidden, #view-security.hidden { display: none; }
.vault-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 24px;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
gap: 16px;
}
.vault-title { font-size: 18px; font-weight: 600; white-space: nowrap; }
.vault-toolbar { display: flex; align-items: center; gap: 12px; flex: 1; justify-content: flex-end; }
.search-wrapper {
display: flex; align-items: center;
background: var(--color-bg); border: 1px solid var(--color-border);
border-radius: 20px; padding: 6px 14px; gap: 8px; flex: 1; max-width: 360px;
}
.search-icon { color: var(--color-text-muted); }
#search-input { border: none; background: none; outline: none; flex: 1; font-size: 14px; }
.btn-fab {
width: 40px; height: 40px; border-radius: 50%;
background: var(--color-primary); color: #fff;
font-size: 24px; font-weight: 300;
display: flex; align-items: center; justify-content: center;
box-shadow: 0 2px 8px rgba(208,2,27,.35);
transition: background var(--transition), box-shadow var(--transition);
flex-shrink: 0;
}
.btn-fab:hover { background: var(--color-primary-dark); box-shadow: 0 4px 14px rgba(208,2,27,.45); }
/* ── Vault list ──────────────────────────────────────────────────── */
.vault-list { flex: 1; overflow-y: auto; padding: 12px 24px 24px; }
.vault-group-header {
font-size: 12px; font-weight: 600; text-transform: uppercase;
letter-spacing: .06em; color: var(--color-text-muted);
padding: 16px 0 6px; border-bottom: 1px solid var(--color-border);
margin-bottom: 4px;
}
.vault-empty {
text-align: center; color: var(--color-text-muted); padding: 60px 0; font-size: 15px;
}
.vault-item {
display: flex; align-items: center; gap: 12px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: 12px 14px;
margin-bottom: 6px;
cursor: pointer;
transition: box-shadow var(--transition), border-color var(--transition);
}
.vault-item:hover { box-shadow: var(--shadow); border-color: #c9ccd4; }
.item-icon { font-size: 22px; flex-shrink: 0; }
.item-info { flex: 1; min-width: 0; }
.item-name { display: block; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item-sub { display: block; font-size: 12px; color: var(--color-text-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item-actions { display: flex; gap: 4px; opacity: 0; transition: opacity var(--transition); }
.vault-item:hover .item-actions { opacity: 1; }
.btn-icon {
width: 30px; height: 30px; border-radius: 6px;
display: flex; align-items: center; justify-content: center;
font-size: 15px; color: var(--color-text-muted);
transition: background var(--transition), color var(--transition);
}
.btn-icon:hover { background: var(--color-bg); color: var(--color-text); }
/* ── Spinner ─────────────────────────────────────────────────────── */
.spinner-overlay {
position: absolute; inset: 0;
display: flex; align-items: center; justify-content: center;
background: rgba(255,255,255,.7);
z-index: 10;
}
.spinner-overlay.hidden { display: none; }
.spinner {
width: 36px; height: 36px;
border: 3px solid var(--color-border);
border-top-color: var(--color-primary);
border-radius: 50%;
animation: spin .7s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* ── Modal ───────────────────────────────────────────────────────── */
.modal-overlay {
position: fixed; inset: 0;
background: rgba(0,0,0,.45);
display: none; align-items: center; justify-content: center;
z-index: 100;
padding: 16px;
}
.modal-overlay.open { display: flex; }
.modal {
background: var(--color-surface);
border-radius: var(--radius);
box-shadow: 0 8px 40px rgba(0,0,0,.2);
width: 100%; max-width: 480px;
max-height: 90vh;
overflow-y: auto;
padding: 28px;
}
.modal-header {
display: flex; align-items: center; justify-content: space-between;
margin-bottom: 20px;
}
.modal-header h3 { font-size: 18px; font-weight: 600; }
.btn-close { font-size: 18px; color: var(--color-text-muted); padding: 4px; border-radius: 4px; }
.btn-close:hover { background: var(--color-bg); color: var(--color-text); }
.modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
.required { color: var(--color-primary); }
/* ── Toast ───────────────────────────────────────────────────────── */
.toast {
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%) translateY(20px);
background: #1a1a2e; color: #fff;
padding: 10px 20px; border-radius: 20px;
font-size: 14px; font-weight: 500;
opacity: 0; transition: opacity .25s, transform .25s;
pointer-events: none; z-index: 200; white-space: nowrap;
}
.toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
.toast.toast-error { background: #c00; }
/* ── Unlock overlay ──────────────────────────────────────────────── */
.modal-unlock { max-width: 380px; }
.unlock-logo { margin-bottom: 16px; }
.unlock-title { margin-bottom: 4px; }
.unlock-subtitle { color: var(--color-text-muted); font-size: 13px; margin-bottom: 20px; }
.btn-link { padding: 10px 20px; border-radius: var(--radius); text-decoration: none; }
/* ── Auth step hint ─────────────────────────────────────────────── */
.auth-step-hint { color: var(--color-text-muted); font-size: 13px; margin-bottom: 16px; }
#mfa-code { font-size: 22px; letter-spacing: .2em; text-align: center; }
/* ── Panel body (sharing / emergency) ───────────────────────────── */
.panel-body { flex: 1; overflow-y: auto; padding: 20px 24px; }
/* ── Tabs ────────────────────────────────────────────────────────── */
.panel-tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 2px solid var(--color-border); padding-bottom: 0; }
.tab-btn {
padding: 8px 16px; border-radius: 6px 6px 0 0; font-size: 13px;
font-weight: 500; color: var(--color-text-muted);
border-bottom: 2px solid transparent; margin-bottom: -2px;
transition: color var(--transition), border-color var(--transition);
}
.tab-btn:hover { color: var(--color-text); }
.tab-btn.active { color: var(--color-primary); border-bottom-color: var(--color-primary); }
/* ── Share / Emergency lists ────────────────────────────────────── */
.share-list { display: flex; flex-direction: column; gap: 8px; }
.share-item {
display: flex; align-items: center; gap: 12px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius); padding: 12px 14px;
}
.share-icon { font-size: 22px; flex-shrink: 0; }
.share-info { flex: 1; min-width: 0; }
.share-name { display: block; font-weight: 500; }
.share-meta { display: block; font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
.share-actions { display: flex; gap: 6px; align-items: center; flex-shrink: 0; }
/* ── Badges ──────────────────────────────────────────────────────── */
.badge { display: inline-block; padding: 3px 8px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.badge-warn { background: #fff8e1; color: #e65100; border: 1px solid #ffb74d; }
.badge-info { background: #e3f2fd; color: #1565c0; border: 1px solid #90caf9; }
/* ── Settings modal ──────────────────────────────────────────────── */
.modal-settings { max-width: 520px; }
.settings-section { padding: 16px 0; border-bottom: 1px solid var(--color-border); }
.settings-section:last-child { border-bottom: none; }
.settings-section-title { font-size: 15px; font-weight: 600; margin-bottom: 8px; }
.settings-desc { font-size: 13px; color: var(--color-text-muted); margin-bottom: 10px; line-height: 1.5; }
.mfa-qr { display: block; margin: 12px auto; max-width: 180px; border: 1px solid var(--color-border); border-radius: 4px; }
.mfa-secret-text { font-family: monospace; font-size: 12px; }
.mfa-secret-text code { background: var(--color-bg); padding: 2px 6px; border-radius: 4px; user-select: all; }
/* ── Sort control ────────────────────────────────────────────────── */
.sort-wrapper select {
padding: 6px 10px;
border: 1px solid var(--color-border);
border-radius: 20px;
background: var(--color-bg);
color: var(--color-text);
font-size: 13px;
cursor: pointer;
outline: none;
}
.sort-wrapper select:focus { border-color: var(--color-primary); }
/* ── Modal item (wider for address/card forms) ───────────────────── */
.modal-item { max-width: 540px; }
/* ── Multi-column form rows ──────────────────────────────────────── */
.form-row { display: flex; gap: 12px; }
.form-row .form-group { flex: 1; }
/* ── Btn small ───────────────────────────────────────────────────── */
.btn-sm { padding: 5px 12px; font-size: 12px; border-radius: 6px; }
/* ── Security dashboard ──────────────────────────────────────────── */
.security-dashboard {
flex: 1; overflow-y: auto;
padding: 24px;
display: flex;
flex-direction: column;
gap: 24px;
}
.sec-notice {
text-align: center; color: var(--color-text-muted);
padding: 40px 0; font-size: 15px;
}
.security-summary {
display: flex;
gap: 20px;
align-items: center;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: 24px;
flex-wrap: wrap;
}
.sec-score-card { text-align: center; flex-shrink: 0; }
.sec-score {
font-size: 56px; font-weight: 700; line-height: 1;
}
.sec-score.score-good { color: #2e7d32; }
.sec-score.score-fair { color: #e65100; }
.sec-score.score-poor { color: #c62828; }
.sec-score-label { font-size: 16px; font-weight: 600; margin-top: 4px; }
.sec-score-desc { font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
.sec-stats { display: flex; gap: 16px; flex-wrap: wrap; }
.sec-stat {
text-align: center;
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: var(--radius);
padding: 12px 20px;
min-width: 80px;
}
.sec-stat-warn { border-color: #ffb74d; background: #fff8e1; }
.sec-stat-info { border-color: #90caf9; background: #e3f2fd; }
.sec-stat-ok { border-color: #a5d6a7; background: #e8f5e9; }
.sec-stat-num { display: block; font-size: 28px; font-weight: 700; }
.sec-stat-label { display: block; font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
.sec-section {
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
overflow: hidden;
}
.sec-section-header {
display: flex; align-items: flex-start; gap: 12px;
padding: 16px 20px;
border-bottom: 1px solid var(--color-border);
background: var(--color-bg);
}
.sec-section-icon { font-size: 20px; flex-shrink: 0; }
.sec-section-title { font-weight: 600; font-size: 15px; }
.sec-section-desc { font-size: 12px; color: var(--color-text-muted); margin-top: 2px; }
.sec-item-list { padding: 0; }
.sec-item {
display: flex; align-items: center; gap: 12px;
padding: 10px 20px;
border-bottom: 1px solid var(--color-border);
}
.sec-item:last-child { border-bottom: none; }
.sec-item-name { font-weight: 500; flex: 1; }
.sec-item-sub { font-size: 12px; color: var(--color-text-muted); flex: 1; }
/* ── Item Detail Modal ───────────────────────────────────────────── */
.modal-detail { max-height: 80vh; display: flex; flex-direction: column; }
.detail-body { flex: 1; overflow-y: auto; padding: 4px 0; }
.detail-field { display: flex; align-items: flex-start; gap: 12px; padding: 10px 0; border-bottom: 1px solid var(--color-border); }
.detail-field:last-child { border-bottom: none; }
.detail-label { font-size: 12px; color: var(--color-text-muted); width: 140px; flex-shrink: 0; padding-top: 4px; }
.detail-val-row { display: flex; align-items: center; gap: 6px; flex: 1; flex-wrap: wrap; }
.detail-val { font-size: 14px; word-break: break-all; }
.detail-sensitive { display: inline-flex; align-items: center; font-family: monospace; font-size: 14px; }
.detail-masked { letter-spacing: 2px; }
.detail-actual { word-break: break-all; }
.btn-reveal, .btn-copy-field { background: none; border: none; cursor: pointer; padding: 2px 4px; font-size: 14px; color: var(--color-text-muted); flex-shrink: 0; }
.btn-reveal:hover, .btn-copy-field:hover { color: var(--color-primary); }
/* ── Emergency Vault Panel ───────────────────────────────────────── */
.em-vault-panel { padding: 8px 0; }
.em-vault-header { display: flex; align-items: center; justify-content: space-between; padding: 4px 0 16px; border-bottom: 2px solid var(--color-border); margin-bottom: 8px; }
.em-vault-header h4 { margin: 0; font-size: 15px; font-weight: 600; }
.em-vault-list { list-style: none; padding: 0; margin: 0; }
.em-vault-item { border-bottom: 1px solid var(--color-border); }
.em-vault-item:last-child { border-bottom: none; }
.em-vault-item-header { display: flex; align-items: center; gap: 10px; width: 100%; background: none; border: none; padding: 12px 4px; cursor: pointer; text-align: left; }
.em-vault-item-header:hover { background: var(--color-sidebar-hover); border-radius: var(--radius); }
.em-vault-icon { font-size: 18px; flex-shrink: 0; }
.em-vault-name { font-weight: 500; flex: 1; }
.em-vault-type { font-size: 12px; color: var(--color-text-muted); }
.em-vault-chevron { font-size: 12px; color: var(--color-text-muted); flex-shrink: 0; }
.em-vault-item-body { padding: 0 8px 12px 36px; }
.em-detail-body .detail-field { padding: 8px 0; }
/* ── Responsive ──────────────────────────────────────────────────── */
@media (max-width: 640px) {
.sidebar { width: 60px; }
.sidebar-header .logo-text,
.sidebar-label,
.sidebar-section-header { display: none; }
.sidebar-item { justify-content: center; padding: 12px 0; }
.vault-header { padding: 12px 16px; }
.vault-list { padding: 8px 16px 16px; }
.sort-wrapper { display: none; }
.form-row { flex-direction: column; gap: 0; }
}
+250
View File
@@ -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 };
})();
+137
View File
@@ -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 };
})();
+181
View File
@@ -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