04/16 Upload codebase
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
/* PassKeeper Extension Popup */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
width: 320px;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 13px;
|
||||
color: #1a1a2e;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.view { display: flex; flex-direction: column; min-height: 0; }
|
||||
.view.hidden { display: none; }
|
||||
|
||||
/* ── Login ───────────────────────────────────────────────────────── */
|
||||
.login-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 28px 20px 18px;
|
||||
background: linear-gradient(135deg, #c0392b, #922b21);
|
||||
color: #fff;
|
||||
}
|
||||
.login-logo { font-size: 36px; margin-bottom: 8px; }
|
||||
.login-header h1 { font-size: 18px; font-weight: 600; letter-spacing: 0.3px; }
|
||||
|
||||
.login-body { padding: 18px 20px 20px; }
|
||||
.pk-hint { font-size: 12px; color: #666; margin-bottom: 12px; text-align: center; }
|
||||
|
||||
.form-group { margin-bottom: 11px; }
|
||||
.form-group label { display: block; font-size: 11px; color: #555; font-weight: 500; margin-bottom: 3px; }
|
||||
.form-group input {
|
||||
width: 100%; padding: 8px 11px;
|
||||
border: 1px solid #ddd; border-radius: 6px;
|
||||
font-size: 13px; outline: none; background: #fff; color: #1a1a2e;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.form-group input:focus { border-color: #c0392b; box-shadow: 0 0 0 2px rgba(192,57,43,0.12); }
|
||||
|
||||
/* ── Buttons ─────────────────────────────────────────────────────── */
|
||||
.btn-primary {
|
||||
display: block; width: 100%; padding: 9px;
|
||||
background: #c0392b; color: #fff;
|
||||
border: none; border-radius: 6px;
|
||||
font-size: 13px; font-weight: 600; cursor: pointer;
|
||||
margin-top: 10px; transition: background 0.15s;
|
||||
}
|
||||
.btn-primary:hover { background: #a93226; }
|
||||
.btn-primary:disabled { background: #e8a49e; cursor: default; }
|
||||
.btn-sm { width: auto; padding: 6px 16px; margin-top: 8px; }
|
||||
|
||||
.btn-ghost {
|
||||
display: block; width: 100%; padding: 9px;
|
||||
background: transparent; color: #c0392b;
|
||||
border: 1px solid #e5c0bb; border-radius: 6px;
|
||||
font-size: 13px; font-weight: 500; cursor: pointer;
|
||||
margin-top: 6px; transition: background 0.15s;
|
||||
}
|
||||
.btn-ghost:hover { background: #fdf2f1; }
|
||||
|
||||
/* ── Vault top bar ───────────────────────────────────────────────── */
|
||||
.vault-topbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 10px 10px 8px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
}
|
||||
|
||||
.search-wrap {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #f3f4f6;
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
gap: 7px;
|
||||
}
|
||||
.search-icon { flex-shrink: 0; opacity: 0.6; }
|
||||
#vault-search {
|
||||
flex: 1; border: none; background: transparent;
|
||||
font-size: 13px; outline: none; color: #1a1a2e;
|
||||
}
|
||||
#vault-search::placeholder { color: #9ca3af; }
|
||||
|
||||
.btn-vault-link {
|
||||
display: inline-flex; align-items: center; gap: 5px;
|
||||
padding: 6px 10px;
|
||||
background: #1a1a2e; color: #fff;
|
||||
border: none; border-radius: 7px;
|
||||
font-size: 12px; font-weight: 600; cursor: pointer;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
transition: background 0.15s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.btn-vault-link:hover { background: #2d2d4e; }
|
||||
|
||||
.btn-add {
|
||||
width: 32px; height: 32px;
|
||||
background: #f3f4f6; color: #1a1a2e;
|
||||
border: none; border-radius: 7px;
|
||||
font-size: 20px; line-height: 1; cursor: pointer;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
flex-shrink: 0;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.btn-add:hover { background: #e5e7eb; }
|
||||
|
||||
/* ── Save prompt ─────────────────────────────────────────────────── */
|
||||
.save-prompt {
|
||||
background: #fef9f0;
|
||||
border-bottom: 2px solid #f59e0b;
|
||||
padding: 10px 14px 12px;
|
||||
}
|
||||
.save-prompt.hidden { display: none; }
|
||||
.save-prompt-title {
|
||||
display: flex; align-items: center; gap: 6px;
|
||||
font-size: 12px; font-weight: 600; color: #92400e;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.save-dismiss {
|
||||
margin-left: auto; background: none; border: none;
|
||||
cursor: pointer; color: #92400e; font-size: 14px; line-height: 1;
|
||||
}
|
||||
.save-prompt .form-group { margin-bottom: 6px; }
|
||||
|
||||
/* ── Tabs ────────────────────────────────────────────────────────── */
|
||||
.vault-tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
padding: 8px 10px 0;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
background: #fff;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.vault-tabs::-webkit-scrollbar { display: none; }
|
||||
|
||||
.tab-btn {
|
||||
padding: 6px 12px 8px;
|
||||
background: none; border: none;
|
||||
font-size: 12px; font-weight: 500;
|
||||
color: #6b7280; cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
white-space: nowrap;
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
.tab-btn:hover { color: #1a1a2e; }
|
||||
.tab-btn.active { color: #1a1a2e; border-bottom-color: #1a1a2e; font-weight: 600; }
|
||||
|
||||
/* ── Vault list ──────────────────────────────────────────────────── */
|
||||
.vault-list {
|
||||
max-height: 280px;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: #e5e7eb transparent;
|
||||
}
|
||||
.vault-list::-webkit-scrollbar { width: 4px; }
|
||||
.vault-list::-webkit-scrollbar-thumb { background: #e5e7eb; border-radius: 2px; }
|
||||
|
||||
.vault-item {
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 10px 14px;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
cursor: default;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.vault-item:hover { background: #f9fafb; }
|
||||
.vault-item:last-child { border-bottom: none; }
|
||||
|
||||
.item-avatar {
|
||||
width: 36px; height: 36px;
|
||||
border-radius: 8px;
|
||||
background: #1e2d5a;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
font-size: 17px;
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.item-avatar.color-red { background: #7f1d1d; }
|
||||
.item-avatar.color-green { background: #14532d; }
|
||||
.item-avatar.color-purple { background: #3b0764; }
|
||||
.item-avatar.color-teal { background: #134e4a; }
|
||||
|
||||
.item-avatar img { width: 22px; height: 22px; border-radius: 3px; }
|
||||
|
||||
.item-info { flex: 1; min-width: 0; }
|
||||
.item-site {
|
||||
font-size: 12px; font-weight: 600; color: #374151;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
}
|
||||
.item-name {
|
||||
font-size: 11px; color: #9ca3af;
|
||||
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.item-actions { display: flex; align-items: center; gap: 2px; flex-shrink: 0; }
|
||||
|
||||
.btn-item-action {
|
||||
background: none; border: none; cursor: pointer;
|
||||
padding: 4px 6px; border-radius: 5px; color: #6b7280;
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
transition: background 0.12s, color 0.12s;
|
||||
}
|
||||
.btn-item-action:hover { background: #f3f4f6; color: #1a1a2e; }
|
||||
.btn-item-action svg { width: 16px; height: 16px; }
|
||||
|
||||
.badge-match {
|
||||
display: inline-block;
|
||||
background: #dbeafe; color: #1d4ed8;
|
||||
font-size: 9px; font-weight: 700;
|
||||
padding: 1px 5px; border-radius: 8px;
|
||||
letter-spacing: 0.3px; margin-left: 4px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
/* ── States ──────────────────────────────────────────────────────── */
|
||||
.pk-error {
|
||||
font-size: 12px; color: #b91c1c;
|
||||
background: #fef2f2; border-radius: 5px;
|
||||
padding: 7px 10px; margin-bottom: 10px;
|
||||
}
|
||||
.pk-error.hidden { display: none; }
|
||||
|
||||
.pk-loading, .pk-empty {
|
||||
text-align: center; color: #9ca3af;
|
||||
padding: 28px 16px; font-size: 13px;
|
||||
}
|
||||
.pk-loading.hidden, .pk-empty.hidden { display: none; }
|
||||
|
||||
/* ── Bottom nav ──────────────────────────────────────────────────── */
|
||||
.bottom-nav {
|
||||
display: flex;
|
||||
border-top: 1px solid #f0f0f0;
|
||||
background: #fff;
|
||||
}
|
||||
.nav-btn {
|
||||
flex: 1;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 3px;
|
||||
padding: 8px 6px;
|
||||
background: none; border: none; cursor: pointer;
|
||||
color: #9ca3af;
|
||||
font-size: 10px; font-weight: 500;
|
||||
transition: color 0.15s;
|
||||
}
|
||||
.nav-btn:hover { color: #374151; }
|
||||
.nav-btn.active { color: #1a1a2e; }
|
||||
@@ -0,0 +1,144 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>PassKeeper</title>
|
||||
<link rel="stylesheet" href="popup.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">
|
||||
|
||||
<!-- ── Login view ──────────────────────────────────────────────────── -->
|
||||
<div id="view-login" class="view hidden">
|
||||
<div class="login-header">
|
||||
<span class="login-logo">🔒</span>
|
||||
<h1>PassKeeper</h1>
|
||||
</div>
|
||||
<div class="login-body">
|
||||
<p id="login-error" class="pk-error hidden"></p>
|
||||
<div class="form-group">
|
||||
<label for="login-email">Email</label>
|
||||
<input type="email" id="login-email" placeholder="you@example.com" autocomplete="email">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="login-password">Master Password</label>
|
||||
<input type="password" id="login-password" placeholder="Master password" autocomplete="current-password">
|
||||
</div>
|
||||
<button id="btn-login" class="btn-primary">Unlock Vault</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── MFA view ────────────────────────────────────────────────────── -->
|
||||
<div id="view-mfa" class="view hidden">
|
||||
<div class="login-header">
|
||||
<span class="login-logo">🔐</span>
|
||||
<h1>Two-Factor Auth</h1>
|
||||
</div>
|
||||
<div class="login-body">
|
||||
<p class="pk-hint">Enter your 6-digit authenticator code.</p>
|
||||
<p id="mfa-error" class="pk-error hidden"></p>
|
||||
<div class="form-group">
|
||||
<label for="mfa-code">Verification Code</label>
|
||||
<input type="text" id="mfa-code" inputmode="numeric" maxlength="6" placeholder="000000" autocomplete="one-time-code">
|
||||
</div>
|
||||
<button id="btn-mfa-verify" class="btn-primary">Verify</button>
|
||||
<button id="btn-mfa-back" class="btn-ghost">← Back</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Unlock-only view (tokens from web app, need vault key) ─────── -->
|
||||
<div id="view-unlock" class="view hidden">
|
||||
<div class="login-header">
|
||||
<span class="login-logo">🔓</span>
|
||||
<h1>PassKeeper</h1>
|
||||
<p style="font-size:12px;opacity:0.85;margin-top:4px;">Signed in via web app</p>
|
||||
</div>
|
||||
<div class="login-body">
|
||||
<p class="pk-hint">Enter your master password to unlock the vault.</p>
|
||||
<p id="unlock-error" class="pk-error hidden"></p>
|
||||
<div class="form-group">
|
||||
<label for="unlock-password">Master Password</label>
|
||||
<input type="password" id="unlock-password" placeholder="Master password" autocomplete="current-password">
|
||||
</div>
|
||||
<button id="btn-unlock" class="btn-primary">Unlock</button>
|
||||
<button id="btn-unlock-signout" class="btn-ghost">Sign out</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Vault view ──────────────────────────────────────────────────── -->
|
||||
<div id="view-vault" class="view hidden">
|
||||
|
||||
<!-- Top bar -->
|
||||
<div class="vault-topbar">
|
||||
<div class="search-wrap">
|
||||
<svg class="search-icon" viewBox="0 0 20 20" fill="none" width="15" height="15">
|
||||
<circle cx="8.5" cy="8.5" r="5.5" stroke="#999" stroke-width="1.6"/>
|
||||
<path d="M13 13l3.5 3.5" stroke="#999" stroke-width="1.6" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<input type="text" id="vault-search" placeholder="Search your vault" autocomplete="off">
|
||||
</div>
|
||||
<a id="btn-open-vault" class="btn-vault-link" title="Open vault" target="_blank">
|
||||
Vault
|
||||
<svg viewBox="0 0 16 16" fill="none" width="12" height="12">
|
||||
<path d="M6 3H3a1 1 0 00-1 1v9a1 1 0 001 1h9a1 1 0 001-1v-3" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
||||
<path d="M9 2h5v5M14 2L8 8" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
</a>
|
||||
<button id="btn-add-item" class="btn-add" title="Add item">+</button>
|
||||
</div>
|
||||
|
||||
<!-- Save prompt -->
|
||||
<div id="save-prompt" class="save-prompt hidden">
|
||||
<div class="save-prompt-title">
|
||||
<span>💾</span> Save new password?
|
||||
<button id="btn-save-no" class="save-dismiss">✕</button>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="save-name">Site name</label>
|
||||
<input type="text" id="save-name" placeholder="e.g. GitHub">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="save-username">Username</label>
|
||||
<input type="text" id="save-username" placeholder="username or email">
|
||||
</div>
|
||||
<button id="btn-save-yes" class="btn-primary btn-sm">Save</button>
|
||||
</div>
|
||||
|
||||
<!-- Tabs -->
|
||||
<div class="vault-tabs" id="vault-tabs">
|
||||
<button class="tab-btn active" data-tab="relevant">All relevant</button>
|
||||
<button class="tab-btn" data-tab="all">All items</button>
|
||||
<button class="tab-btn" data-tab="recents">Recents</button>
|
||||
</div>
|
||||
|
||||
<!-- List -->
|
||||
<div id="vault-spinner" class="pk-loading hidden">Loading vault…</div>
|
||||
<div id="vault-list" class="vault-list"></div>
|
||||
<div id="vault-empty" class="pk-empty hidden">No items found.</div>
|
||||
|
||||
<!-- Bottom nav -->
|
||||
<nav class="bottom-nav">
|
||||
<button class="nav-btn active" id="nav-vault">
|
||||
<svg viewBox="0 0 24 24" fill="none" width="20" height="20">
|
||||
<rect x="3" y="6" width="18" height="14" rx="2" stroke="currentColor" stroke-width="1.7"/>
|
||||
<circle cx="12" cy="13" r="2.5" stroke="currentColor" stroke-width="1.7"/>
|
||||
<path d="M8 6V5a4 4 0 018 0v1" stroke="currentColor" stroke-width="1.7"/>
|
||||
</svg>
|
||||
<span>Vault</span>
|
||||
</button>
|
||||
<button class="nav-btn" id="nav-account" title="Sign out">
|
||||
<svg viewBox="0 0 24 24" fill="none" width="20" height="20">
|
||||
<circle cx="12" cy="8" r="4" stroke="currentColor" stroke-width="1.7"/>
|
||||
<path d="M4 20c0-4 3.6-7 8-7s8 3 8 7" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/>
|
||||
</svg>
|
||||
<span>Sign out</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
</div><!-- /view-vault -->
|
||||
|
||||
</div><!-- /app -->
|
||||
<script src="../shared/crypto.js"></script>
|
||||
<script src="popup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* extension/popup/popup.js — PassKeeper popup UI
|
||||
*
|
||||
* Storage layout:
|
||||
* chrome.storage.session — access_token, vault_key_jwk, vault_items (cleared on browser close)
|
||||
* chrome.storage.local — refresh_token, enc_key_salt (persists across restarts)
|
||||
*
|
||||
* SSO flow (web app → extension):
|
||||
* bridge.js syncs tokens to background → background writes to chrome.storage.
|
||||
* On popup open: if session has no vault_key but local has enc_key_salt + refresh_token,
|
||||
* we refresh the access_token and show the unlock-only view (master password only).
|
||||
*/
|
||||
|
||||
const API_BASE = 'https://pwkeeper.ngodanguyen.tech';
|
||||
const VAULT_URL = 'https://pwkeeper.ngodanguyen.tech/vault';
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
let _vaultKey = null;
|
||||
let _items = [];
|
||||
let _mfaToken = null;
|
||||
let _currentUrl = '';
|
||||
let _activeTab = 'relevant';
|
||||
|
||||
// ── DOM helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
function showView(name) {
|
||||
['login', 'mfa', 'unlock', 'vault'].forEach(v =>
|
||||
$(`view-${v}`).classList.toggle('hidden', v !== name)
|
||||
);
|
||||
}
|
||||
|
||||
function showError(elId, msg) {
|
||||
const el = $(elId);
|
||||
el.textContent = msg;
|
||||
el.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function hideError(elId) { $(elId).classList.add('hidden'); }
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str ?? '')
|
||||
.replace(/&/g, '&').replace(/</g, '<')
|
||||
.replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
// ── Avatar helpers ────────────────────────────────────────────────────────────
|
||||
|
||||
const AVATAR_COLORS = ['', 'color-red', 'color-green', 'color-purple', 'color-teal'];
|
||||
|
||||
function avatarColor(str) {
|
||||
let h = 0;
|
||||
for (const c of str) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
||||
return AVATAR_COLORS[h % AVATAR_COLORS.length];
|
||||
}
|
||||
|
||||
function itemEmoji(type) {
|
||||
return { password: '🔑', note: '📝', card: '💳', bank: '🏦', address: '🏠', ssn: '🪪', passkey: '🔐' }[type] || '🔑';
|
||||
}
|
||||
|
||||
function siteLabel(item) {
|
||||
if (item.plain?.url) {
|
||||
try { return new URL(item.plain.url).hostname.replace(/^www\./, ''); } catch {}
|
||||
}
|
||||
return item.name;
|
||||
}
|
||||
|
||||
// ── Domain matching ───────────────────────────────────────────────────────────
|
||||
|
||||
function currentHostname() {
|
||||
if (!_currentUrl) return '';
|
||||
try { return new URL(_currentUrl).hostname.replace(/^www\./, ''); } catch { return ''; }
|
||||
}
|
||||
|
||||
function isMatch(item) {
|
||||
const host = currentHostname();
|
||||
if (!host || item.item_type !== 'password' || !item.plain?.url) return false;
|
||||
try {
|
||||
const h = new URL(item.plain.url).hostname.replace(/^www\./, '');
|
||||
return h === host || h.endsWith(`.${host}`) || host.endsWith(`.${h}`);
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
// ── API helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
async function apiFetch(path, options = {}) {
|
||||
const { access_token } = await chrome.storage.session.get('access_token');
|
||||
const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) };
|
||||
if (access_token) headers['Authorization'] = `Bearer ${access_token}`;
|
||||
|
||||
let res = await fetch(`${API_BASE}${path}`, { ...options, headers });
|
||||
|
||||
if (res.status === 401) {
|
||||
const refreshed = await tryRefreshToken();
|
||||
if (!refreshed) { signOut(); return null; }
|
||||
const { access_token: tok } = await chrome.storage.session.get('access_token');
|
||||
headers['Authorization'] = `Bearer ${tok}`;
|
||||
res = await fetch(`${API_BASE}${path}`, { ...options, headers });
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async function tryRefreshToken() {
|
||||
const { refresh_token } = await chrome.storage.local.get('refresh_token');
|
||||
if (!refresh_token) return false;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token }),
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const data = await res.json();
|
||||
await chrome.storage.session.set({ access_token: data.access_token });
|
||||
if (data.refresh_token) await chrome.storage.local.set({ refresh_token: data.refresh_token });
|
||||
return true;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function handleLogin() {
|
||||
const email = $('login-email').value.trim().toLowerCase();
|
||||
const password = $('login-password').value;
|
||||
hideError('login-error');
|
||||
if (!email || !password) { showError('login-error', 'Email and master password are required.'); return; }
|
||||
|
||||
const btn = $('btn-login');
|
||||
btn.disabled = true; btn.textContent = 'Unlocking…';
|
||||
try {
|
||||
const authHash = await ExtCrypto.deriveAuthHash(password, email);
|
||||
const res = await fetch(`${API_BASE}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, auth_hash: authHash }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError('login-error', data.error || 'Login failed.'); return; }
|
||||
|
||||
if (data.mfa_required) {
|
||||
_mfaToken = data.mfa_token;
|
||||
await chrome.storage.session.set({ _pending_enc_key_salt: data.enc_key_salt });
|
||||
handleMfaStage(password);
|
||||
showView('mfa');
|
||||
$('mfa-code').focus();
|
||||
return;
|
||||
}
|
||||
await completeLogin(data, password);
|
||||
} catch (err) {
|
||||
showError('login-error', 'Network error: ' + err.message);
|
||||
} finally {
|
||||
btn.disabled = false; btn.textContent = 'Unlock Vault';
|
||||
}
|
||||
}
|
||||
|
||||
function handleMfaStage(password) {
|
||||
$('btn-mfa-verify').onclick = async () => {
|
||||
const code = $('mfa-code').value.trim();
|
||||
hideError('mfa-error');
|
||||
if (code.length !== 6) { showError('mfa-error', 'Enter the 6-digit code.'); return; }
|
||||
$('btn-mfa-verify').disabled = true;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/auth/mfa/verify`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ mfa_token: _mfaToken, totp_code: code }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) { showError('mfa-error', data.error || 'Verification failed.'); return; }
|
||||
_mfaToken = null;
|
||||
const { _pending_enc_key_salt } = await chrome.storage.session.get('_pending_enc_key_salt');
|
||||
await completeLogin({ ...data, enc_key_salt: _pending_enc_key_salt }, password);
|
||||
} catch (err) {
|
||||
showError('mfa-error', 'Error: ' + err.message);
|
||||
} finally {
|
||||
$('btn-mfa-verify').disabled = false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function completeLogin(data, masterPassword) {
|
||||
await chrome.storage.session.set({ access_token: data.access_token, enc_key_salt: data.enc_key_salt });
|
||||
// enc_key_salt also persisted locally — not sensitive without the master password,
|
||||
// needed to show unlock-only view after browser restart.
|
||||
await chrome.storage.local.set({ refresh_token: data.refresh_token, enc_key_salt: data.enc_key_salt });
|
||||
|
||||
_vaultKey = await ExtCrypto.deriveVaultKey(masterPassword, data.enc_key_salt);
|
||||
const vaultKeyJwk = await ExtCrypto.exportVaultKey(_vaultKey);
|
||||
await chrome.storage.session.set({ vault_key_jwk: vaultKeyJwk });
|
||||
|
||||
// Push session to any open web app tabs so they don't need to re-login
|
||||
chrome.runtime.sendMessage({
|
||||
type: 'EXT_SESSION_SYNC',
|
||||
access_token: data.access_token,
|
||||
refresh_token: data.refresh_token,
|
||||
enc_key_salt: data.enc_key_salt,
|
||||
}).catch(() => {});
|
||||
|
||||
showView('vault');
|
||||
await checkPendingSave();
|
||||
await fetchAndDecryptVault();
|
||||
renderList();
|
||||
}
|
||||
|
||||
// ── Unlock-only (tokens from web app, just need master password) ──────────────
|
||||
|
||||
async function handleUnlockOnly() {
|
||||
const password = $('unlock-password').value;
|
||||
hideError('unlock-error');
|
||||
if (!password) { showError('unlock-error', 'Enter your master password.'); return; }
|
||||
|
||||
const btn = $('btn-unlock');
|
||||
btn.disabled = true; btn.textContent = 'Unlocking…';
|
||||
try {
|
||||
// enc_key_salt may be in session (fresh) or local (after browser restart)
|
||||
let { enc_key_salt } = await chrome.storage.session.get('enc_key_salt');
|
||||
if (!enc_key_salt) {
|
||||
const local = await chrome.storage.local.get('enc_key_salt');
|
||||
enc_key_salt = local.enc_key_salt;
|
||||
}
|
||||
if (!enc_key_salt) { showError('unlock-error', 'Session expired. Please log in again.'); return; }
|
||||
|
||||
_vaultKey = await ExtCrypto.deriveVaultKey(password, enc_key_salt);
|
||||
const vaultKeyJwk = await ExtCrypto.exportVaultKey(_vaultKey);
|
||||
await chrome.storage.session.set({ vault_key_jwk: vaultKeyJwk });
|
||||
|
||||
showView('vault');
|
||||
await checkPendingSave();
|
||||
await fetchAndDecryptVault();
|
||||
renderList();
|
||||
} catch {
|
||||
showError('unlock-error', 'Incorrect password or session expired.');
|
||||
} finally {
|
||||
btn.disabled = false; btn.textContent = 'Unlock';
|
||||
}
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
const { access_token } = await chrome.storage.session.get('access_token');
|
||||
const { refresh_token } = await chrome.storage.local.get('refresh_token');
|
||||
if (access_token) {
|
||||
fetch(`${API_BASE}/api/auth/logout`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${access_token}` },
|
||||
body: JSON.stringify({ refresh_token }),
|
||||
}).catch(() => {});
|
||||
}
|
||||
} catch {}
|
||||
await chrome.storage.session.clear();
|
||||
await chrome.storage.local.remove(['refresh_token', 'enc_key_salt']);
|
||||
_vaultKey = null; _items = [];
|
||||
showView('login');
|
||||
}
|
||||
|
||||
// ── Vault loading ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Returns:
|
||||
* 'vault' — fully unlocked session restored
|
||||
* 'unlock' — tokens exist (from web app SSO) but vault key needs deriving
|
||||
* false — no session, show login
|
||||
*/
|
||||
async function restoreSessionIfAvailable() {
|
||||
const data = await chrome.storage.session.get(['access_token', 'vault_key_jwk', 'vault_items', 'enc_key_salt']);
|
||||
|
||||
if (data.access_token) {
|
||||
if (data.vault_key_jwk) {
|
||||
_vaultKey = await ExtCrypto.importVaultKey(data.vault_key_jwk);
|
||||
_items = data.vault_items || [];
|
||||
return 'vault';
|
||||
}
|
||||
// Tokens exist (synced from web app) but vault key not yet derived
|
||||
if (data.enc_key_salt) return 'unlock';
|
||||
}
|
||||
|
||||
// Session cleared (e.g. browser restart) — try refreshing with persisted local tokens
|
||||
const local = await chrome.storage.local.get(['refresh_token', 'enc_key_salt']);
|
||||
if (local.refresh_token && local.enc_key_salt) {
|
||||
const refreshed = await tryRefreshToken();
|
||||
if (refreshed) {
|
||||
await chrome.storage.session.set({ enc_key_salt: local.enc_key_salt });
|
||||
return 'unlock';
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async function fetchAndDecryptVault() {
|
||||
$('vault-spinner').classList.remove('hidden');
|
||||
try {
|
||||
const res = await apiFetch('/api/vault');
|
||||
if (!res) return;
|
||||
const raw = await res.json();
|
||||
|
||||
_items = await Promise.all(raw.map(async item => {
|
||||
try {
|
||||
const plain = await ExtCrypto.decryptItem(_vaultKey, item.enc_data, item.iv);
|
||||
return { ...item, plain };
|
||||
} catch { return { ...item, plain: null }; }
|
||||
}));
|
||||
|
||||
await chrome.storage.session.set({ vault_items: _items });
|
||||
chrome.runtime.sendMessage({ type: 'VAULT_UPDATED' }).catch(() => {});
|
||||
} catch (err) {
|
||||
console.error('fetchAndDecryptVault:', err);
|
||||
} finally {
|
||||
$('vault-spinner').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rendering ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function getTabItems() {
|
||||
const q = $('vault-search').value.trim().toLowerCase();
|
||||
|
||||
let items = _items;
|
||||
|
||||
// Text filter
|
||||
if (q) {
|
||||
items = items.filter(i =>
|
||||
i.name.toLowerCase().includes(q) ||
|
||||
(i.plain?.username || '').toLowerCase().includes(q) ||
|
||||
(i.plain?.url || '').toLowerCase().includes(q)
|
||||
);
|
||||
}
|
||||
|
||||
if (_activeTab === 'relevant') {
|
||||
// Show matching items first, then others (only if there are matches or no query)
|
||||
const matches = items.filter(isMatch);
|
||||
const rest = items.filter(i => !isMatch(i));
|
||||
// If we have matches, show matches first; otherwise fall back to all
|
||||
items = matches.length ? [...matches, ...rest] : items;
|
||||
// Sort matched first by name, rest by name
|
||||
items = [
|
||||
...matches.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
...rest.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
];
|
||||
} else if (_activeTab === 'recents') {
|
||||
items = [...items].sort((a, b) => new Date(b.updated_at || b.created_at) - new Date(a.updated_at || a.created_at)).slice(0, 20);
|
||||
} else {
|
||||
items = [...items].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
function renderList() {
|
||||
const listEl = $('vault-list');
|
||||
const emptyEl = $('vault-empty');
|
||||
const items = getTabItems();
|
||||
|
||||
if (!items.length) {
|
||||
listEl.innerHTML = '';
|
||||
emptyEl.classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
emptyEl.classList.add('hidden');
|
||||
|
||||
// SVG icons for action buttons
|
||||
const svgCopy = `<svg viewBox="0 0 24 24" fill="none"><rect x="9" y="9" width="11" height="11" rx="2" stroke="currentColor" stroke-width="1.7"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke="currentColor" stroke-width="1.7"/></svg>`;
|
||||
const svgDots = `<svg viewBox="0 0 24 24" fill="currentColor"><circle cx="5" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="19" cy="12" r="1.5"/></svg>`;
|
||||
const svgFill = `<svg viewBox="0 0 24 24" fill="none"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/><path d="M17 3l4 4-9 9H8v-4l9-9z" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round"/></svg>`;
|
||||
|
||||
listEl.innerHTML = items.map(item => {
|
||||
const matched = isMatch(item);
|
||||
const site = escHtml(siteLabel(item));
|
||||
const name = escHtml(item.name);
|
||||
const badge = matched ? '<span class="badge-match">match</span>' : '';
|
||||
const color = avatarColor(item.name);
|
||||
const emoji = itemEmoji(item.item_type);
|
||||
const canFill = item.item_type === 'password' && item.plain?.username && item.plain?.password;
|
||||
const canCopy = item.item_type === 'password' && item.plain?.password;
|
||||
|
||||
return `<div class="vault-item" data-id="${item.id}">
|
||||
<div class="item-avatar ${color}">${emoji}</div>
|
||||
<div class="item-info">
|
||||
<div class="item-site">${site}${badge}</div>
|
||||
<div class="item-name">${name}</div>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
${canCopy ? `<button class="btn-item-action" data-copy-pass="${item.id}" title="Copy password">${svgCopy}</button>` : ''}
|
||||
${canFill ? `<button class="btn-item-action" data-autofill="${item.id}" title="Autofill">${svgFill}</button>` : ''}
|
||||
<button class="btn-item-action" data-menu="${item.id}" title="More">${svgDots}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
// Copy password
|
||||
listEl.querySelectorAll('[data-copy-pass]').forEach(btn =>
|
||||
btn.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
const item = _items.find(i => i.id === parseInt(btn.dataset.copyPass));
|
||||
if (item?.plain?.password) {
|
||||
navigator.clipboard.writeText(item.plain.password);
|
||||
btn.title = 'Copied!';
|
||||
setTimeout(() => { btn.title = 'Copy password'; }, 1500);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Autofill
|
||||
listEl.querySelectorAll('[data-autofill]').forEach(btn =>
|
||||
btn.addEventListener('click', async e => {
|
||||
e.stopPropagation();
|
||||
const item = _items.find(i => i.id === parseInt(btn.dataset.autofill));
|
||||
if (!item?.plain) return;
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
if (tab?.id) {
|
||||
chrome.tabs.sendMessage(tab.id, {
|
||||
type: 'DO_AUTOFILL',
|
||||
username: item.plain.username || '',
|
||||
password: item.plain.password || '',
|
||||
}).catch(() => {});
|
||||
}
|
||||
window.close();
|
||||
})
|
||||
);
|
||||
|
||||
// Three-dot menu: copy username
|
||||
listEl.querySelectorAll('[data-menu]').forEach(btn =>
|
||||
btn.addEventListener('click', e => {
|
||||
e.stopPropagation();
|
||||
const item = _items.find(i => i.id === parseInt(btn.dataset.menu));
|
||||
if (!item?.plain) return;
|
||||
// Simple: copy username on dots click (could be a dropdown in future)
|
||||
if (item.plain.username) {
|
||||
navigator.clipboard.writeText(item.plain.username);
|
||||
btn.title = 'Username copied!';
|
||||
setTimeout(() => { btn.title = 'More'; }, 1500);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tabs ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
function initTabs() {
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
_activeTab = btn.dataset.tab;
|
||||
document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b === btn));
|
||||
renderList();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── Auto-save prompt ──────────────────────────────────────────────────────────
|
||||
|
||||
async function checkPendingSave() {
|
||||
const { pending_save } = await chrome.storage.session.get('pending_save');
|
||||
if (!pending_save) return;
|
||||
|
||||
const prompt = $('save-prompt');
|
||||
$('save-name').value = pending_save.siteName || '';
|
||||
$('save-username').value = pending_save.username || '';
|
||||
prompt.classList.remove('hidden');
|
||||
|
||||
$('btn-save-yes').onclick = async () => {
|
||||
prompt.classList.add('hidden');
|
||||
await saveCredential(pending_save);
|
||||
await chrome.storage.session.remove('pending_save');
|
||||
};
|
||||
$('btn-save-no').onclick = async () => {
|
||||
prompt.classList.add('hidden');
|
||||
await chrome.storage.session.remove('pending_save');
|
||||
};
|
||||
}
|
||||
|
||||
async function saveCredential(data) {
|
||||
if (!_vaultKey) return;
|
||||
const plain = { url: data.url || '', username: data.username || '', password: data.password || '', notes: '' };
|
||||
const name = $('save-name').value.trim() || data.siteName || 'Untitled';
|
||||
const { enc_data, iv } = await ExtCrypto.encryptItem(_vaultKey, plain);
|
||||
try {
|
||||
const res = await apiFetch('/api/vault', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name, item_type: 'password', folder_id: null, enc_data, iv }),
|
||||
});
|
||||
if (res?.ok) { await fetchAndDecryptVault(); renderList(); }
|
||||
} catch (err) { console.error('saveCredential failed:', err); }
|
||||
}
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
_currentUrl = tab?.url || '';
|
||||
} catch {}
|
||||
|
||||
// Set vault link
|
||||
$('btn-open-vault').href = VAULT_URL;
|
||||
|
||||
const sessionState = await restoreSessionIfAvailable();
|
||||
|
||||
if (sessionState === 'vault') {
|
||||
showView('vault');
|
||||
await checkPendingSave();
|
||||
if (_items.length) {
|
||||
renderList();
|
||||
fetchAndDecryptVault().then(() => renderList());
|
||||
} else {
|
||||
await fetchAndDecryptVault();
|
||||
renderList();
|
||||
}
|
||||
} else if (sessionState === 'unlock') {
|
||||
showView('unlock');
|
||||
$('unlock-password').focus();
|
||||
} else {
|
||||
showView('login');
|
||||
}
|
||||
|
||||
// Login
|
||||
$('btn-login').addEventListener('click', handleLogin);
|
||||
$('login-password').addEventListener('keydown', e => { if (e.key === 'Enter') handleLogin(); });
|
||||
$('login-email').addEventListener('keydown', e => { if (e.key === 'Enter') $('login-password').focus(); });
|
||||
|
||||
// MFA
|
||||
$('btn-mfa-back').addEventListener('click', () => { _mfaToken = null; showView('login'); });
|
||||
$('mfa-code').addEventListener('keydown', e => { if (e.key === 'Enter') $('btn-mfa-verify')?.click(); });
|
||||
|
||||
// Unlock-only
|
||||
$('btn-unlock').addEventListener('click', handleUnlockOnly);
|
||||
$('unlock-password').addEventListener('keydown', e => { if (e.key === 'Enter') handleUnlockOnly(); });
|
||||
$('btn-unlock-signout').addEventListener('click', signOut);
|
||||
|
||||
// Vault actions
|
||||
$('btn-add-item').addEventListener('click', () => { chrome.tabs.create({ url: VAULT_URL }); });
|
||||
$('nav-account').addEventListener('click', signOut);
|
||||
|
||||
// Search
|
||||
$('vault-search').addEventListener('input', () => renderList());
|
||||
|
||||
// Tabs
|
||||
initTabs();
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
Reference in New Issue
Block a user