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
+122
View File
@@ -0,0 +1,122 @@
/**
* extension/background.js — Manifest V3 service worker.
*
* Responsibilities:
* - Update the action badge (number of matching vault items) for the active tab.
* - Bridge SAVE_CREDENTIALS messages from content script → chrome.storage.session
* so the popup can pick them up as a save-prompt.
* - Re-update badges when the vault cache changes.
*/
// ── Badge helpers ────────────────────────────────────────────────────────────
async function updateBadgeForTab(tabId, url) {
try {
const { vault_items } = await chrome.storage.session.get('vault_items');
if (!vault_items?.length) {
chrome.action.setBadgeText({ text: '', tabId });
return;
}
let hostname;
try { hostname = new URL(url).hostname.replace(/^www\./, ''); }
catch { chrome.action.setBadgeText({ text: '', tabId }); return; }
const matches = vault_items.filter(item => {
if (item.item_type !== 'password' || !item.plain?.url) return false;
try {
const h = new URL(item.plain.url).hostname.replace(/^www\./, '');
return h === hostname || h.endsWith(`.${hostname}`) || hostname.endsWith(`.${h}`);
} catch { return false; }
});
if (matches.length > 0) {
chrome.action.setBadgeText({ text: String(matches.length), tabId });
chrome.action.setBadgeBackgroundColor({ color: '#1a73e8', tabId });
} else {
chrome.action.setBadgeText({ text: '', tabId });
}
} catch { /* tab may have closed */ }
}
async function refreshAllBadges() {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
if (tab.url?.startsWith('http')) updateBadgeForTab(tab.id, tab.url);
}
}
// ── Tab events ───────────────────────────────────────────────────────────────
chrome.tabs.onActivated.addListener(async ({ tabId }) => {
try {
const tab = await chrome.tabs.get(tabId);
if (tab.url?.startsWith('http')) updateBadgeForTab(tabId, tab.url);
} catch {}
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url?.startsWith('http')) {
updateBadgeForTab(tabId, tab.url);
}
});
// ── Message handler ──────────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// Popup signals vault cache was refreshed → re-check all tab badges.
if (msg.type === 'VAULT_UPDATED') {
refreshAllBadges();
sendResponse({ ok: true });
return false;
}
// Content script detected credentials on form submit → store for save-prompt.
if (msg.type === 'SAVE_CREDENTIALS') {
chrome.storage.session.set({ pending_save: msg.data });
sendResponse({ ok: true });
return false;
}
// Bridge: web app logged in → store tokens in extension storage.
if (msg.type === 'WEB_SESSION_SYNC') {
chrome.storage.session.set({
access_token: msg.access_token,
enc_key_salt: msg.enc_key_salt || '',
});
// Also persist enc_key_salt locally so the unlock-only view survives browser restarts
chrome.storage.local.set({
refresh_token: msg.refresh_token,
...(msg.enc_key_salt ? { enc_key_salt: msg.enc_key_salt } : {}),
});
sendResponse({ ok: true });
return false;
}
// Bridge: web app logged out → clear extension session.
if (msg.type === 'WEB_SESSION_CLEAR') {
chrome.storage.session.remove(['access_token', 'vault_key_jwk', 'vault_items', 'enc_key_salt']);
chrome.storage.local.remove('refresh_token');
sendResponse({ ok: true });
return false;
}
// Popup logged in via extension → inject session into open vault tabs.
if (msg.type === 'EXT_SESSION_SYNC') {
chrome.tabs.query({ url: 'https://pwkeeper.ngodanguyen.tech/*' }, tabs => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
type: 'INJECT_SESSION',
access_token: msg.access_token,
refresh_token: msg.refresh_token,
enc_key_salt: msg.enc_key_salt,
}).catch(() => {});
});
});
sendResponse({ ok: true });
return false;
}
return false;
});
+111
View File
@@ -0,0 +1,111 @@
/**
* extension/bridge/bridge.js
*
* Content script injected ONLY on pwkeeper.ngodanguyen.tech.
*
* Web app → Extension:
* Listens for the 'passkeeper:session' custom event dispatched by auth.js
* after login, and forwards access_token + refresh_token + enc_key_salt to
* the background service worker via chrome.runtime.sendMessage.
*
* Extension → Web app:
* Listens for INJECT_SESSION messages from the background (triggered when the
* user logs in through the popup). Writes tokens into the web app's storage
* and fires 'passkeeper:ext-login' so auth.js can unlock the vault overlay.
*/
(() => {
'use strict';
// ── Web app → Extension ────────────────────────────────────────────────────
function syncToExtension(access_token, refresh_token, enc_key_salt) {
if (!access_token || !refresh_token) return;
chrome.runtime.sendMessage({
type: 'WEB_SESSION_SYNC',
access_token,
refresh_token,
enc_key_salt: enc_key_salt || '',
}).catch(() => {});
}
// Fired by auth.js completeLogin
window.addEventListener('passkeeper:session', e => {
const { access_token, refresh_token, enc_key_salt } = e.detail || {};
syncToExtension(access_token, refresh_token, enc_key_salt);
});
// Fired by auth.js on logout / sign-out
window.addEventListener('passkeeper:logout', () => {
chrome.runtime.sendMessage({ type: 'WEB_SESSION_CLEAR' }).catch(() => {});
});
// On initial page load: sync in both directions
// Web → Extension: if the web app is already logged in, forward tokens to extension
const existing_token = sessionStorage.getItem('access_token');
const existing_refresh = localStorage.getItem('refresh_token');
const existing_salt = sessionStorage.getItem('enc_key_salt');
if (existing_token && existing_refresh) {
syncToExtension(existing_token, existing_refresh, existing_salt);
}
// Extension → Web: if the web app has no session but the extension does,
// refresh the access token first (so we inject a guaranteed-fresh pair) then
// fire passkeeper:ext-login so vault.js can proceed without hitting 401.
if (!existing_token) {
(async () => {
try {
const local = await chrome.storage.local.get(['refresh_token', 'enc_key_salt']);
const refresh = local.refresh_token;
const salt = local.enc_key_salt ||
(await chrome.storage.session.get('enc_key_salt')).enc_key_salt || '';
if (!refresh || !salt) return;
// Exchange the stored refresh token for a fresh access token
const res = await fetch(`${location.origin}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: refresh }),
});
if (!res.ok) return;
const data = await res.json();
const freshAccess = data.access_token;
const freshRefresh = data.refresh_token || refresh;
// Write fresh tokens into the page session so vault.js works immediately
sessionStorage.setItem('access_token', freshAccess);
localStorage.setItem('refresh_token', freshRefresh);
sessionStorage.setItem('enc_key_salt', salt);
// Keep extension storage in sync with the rotated tokens
chrome.storage.session.set({ access_token: freshAccess, enc_key_salt: salt });
chrome.storage.local.set({ refresh_token: freshRefresh, enc_key_salt: salt });
window.dispatchEvent(new CustomEvent('passkeeper:ext-login', {
detail: { enc_key_salt: salt },
}));
} catch {}
})();
}
// ── Extension → Web app ────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.type === 'INJECT_SESSION') {
// Write tokens so the web app is effectively logged in
sessionStorage.setItem('access_token', msg.access_token);
localStorage.setItem('refresh_token', msg.refresh_token);
if (msg.enc_key_salt) sessionStorage.setItem('enc_key_salt', msg.enc_key_salt);
// Tell the web app a session was injected — vault.js listens for this
// to dismiss the unlock overlay and load the vault
window.dispatchEvent(new CustomEvent('passkeeper:ext-login', {
detail: { enc_key_salt: msg.enc_key_salt },
}));
sendResponse({ ok: true });
}
return false;
});
})();
+345
View File
@@ -0,0 +1,345 @@
/**
* extension/content/content.js — PassKeeper content script.
*
* 1. Detects login forms → notifies background (badge count).
* 2. Injects a small autofill button next to password fields when vault
* has matching credentials for the current site.
* 3. Listens for DO_AUTOFILL from the popup → fills fields.
* 4. Watches form submissions → shows save-credentials banner.
*/
(() => {
'use strict';
const PK_ATTR = 'data-pk-decorated';
const PK_BTN_CLASS = '__pk_autofill_btn__';
let _bannerEl = null;
let _hasNotifiedForm = false;
let _formObserver = null;
// ── Helpers ──────────────────────────────────────────────────────────────────
function escHtml(str) {
return String(str ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function visiblePasswordFields() {
return Array.from(document.querySelectorAll('input[type="password"]'))
.filter(el => el.offsetParent !== null && !el.disabled);
}
function findUsernameField(pwField) {
const all = Array.from(document.querySelectorAll('input'));
const idx = all.indexOf(pwField);
for (let i = idx - 1; i >= 0; i--) {
const el = all[i];
if (!el.offsetParent || el.disabled) continue;
if (['email', 'text', 'tel'].includes(el.type)) return el;
}
return null;
}
// ── Framework-compatible fill ─────────────────────────────────────────────────
function fillField(el, value) {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
if (setter) setter.call(el, value);
else el.value = value;
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
}
function doAutofill(username, password) {
const pwFields = visiblePasswordFields();
if (!pwFields.length) return;
const pwField = pwFields[0];
const usernameField = findUsernameField(pwField);
if (usernameField && username) fillField(usernameField, username);
if (password) fillField(pwField, password);
[usernameField, pwField].filter(Boolean).forEach(el => {
el.style.outline = '2px solid #1a73e8';
setTimeout(() => { el.style.outline = ''; }, 1500);
});
}
// ── Inline autofill button ────────────────────────────────────────────────────
/**
* Inject a small PassKeeper icon button just inside the right edge of each
* password field. Clicking it opens a tiny dropdown listing matching items.
*/
function injectAutofillButtons(matchingItems) {
visiblePasswordFields().forEach(pwField => {
if (pwField.getAttribute(PK_ATTR)) return; // already decorated
pwField.setAttribute(PK_ATTR, '1');
// Wrap the field if it isn't already positioned
const wrap = document.createElement('div');
wrap.style.cssText = 'position:relative;display:inline-block;width:100%;';
pwField.parentNode.insertBefore(wrap, pwField);
wrap.appendChild(pwField);
// Add right-side padding so text doesn't overlap the button
pwField.style.paddingRight = '32px';
// The icon button
const btn = document.createElement('button');
btn.type = 'button';
btn.className = PK_BTN_CLASS;
btn.title = 'Autofill with PassKeeper';
btn.setAttribute('aria-label', 'Autofill with PassKeeper');
btn.style.cssText = [
'position:absolute',
'right:6px',
'top:50%',
'transform:translateY(-50%)',
'background:none',
'border:none',
'cursor:pointer',
'padding:3px',
'display:flex',
'align-items:center',
'justify-content:center',
'z-index:2147483646',
].join(';');
btn.innerHTML = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="3" y="9" width="18" height="12" rx="2" stroke="#1a73e8" stroke-width="1.8"/>
<path d="M8 9V6a4 4 0 018 0v3" stroke="#1a73e8" stroke-width="1.8" stroke-linecap="round"/>
<circle cx="12" cy="15" r="1.5" fill="#1a73e8"/>
</svg>`;
wrap.appendChild(btn);
btn.addEventListener('click', e => {
e.preventDefault();
e.stopPropagation();
toggleDropdown(btn, pwField, matchingItems);
});
});
}
// Dropdown showing matching credentials
function toggleDropdown(btn, pwField, items) {
// Remove any existing dropdown
const existing = document.getElementById('__pk_dropdown__');
if (existing) { existing.remove(); return; }
const usernameField = findUsernameField(pwField);
const dropdown = document.createElement('div');
dropdown.id = '__pk_dropdown__';
dropdown.style.cssText = [
'position:fixed',
'background:#fff',
'border:1px solid #e2e8f0',
'border-radius:10px',
'box-shadow:0 8px 30px rgba(0,0,0,0.15)',
'z-index:2147483647',
'min-width:240px',
'max-width:300px',
'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',
'font-size:13px',
'overflow:hidden',
].join(';');
// Position below the button
const rect = btn.getBoundingClientRect();
dropdown.style.top = (rect.bottom + 6) + 'px';
dropdown.style.left = Math.max(8, rect.right - 260) + 'px';
// Header
const header = document.createElement('div');
header.style.cssText = 'padding:9px 12px 8px;border-bottom:1px solid #f3f4f6;display:flex;align-items:center;gap:6px;';
header.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><rect x="3" y="9" width="18" height="12" rx="2" stroke="#1a73e8" stroke-width="2"/><path d="M8 9V6a4 4 0 018 0v3" stroke="#1a73e8" stroke-width="2" stroke-linecap="round"/></svg><span style="font-weight:600;color:#1a1a2e;font-size:12px;">PassKeeper</span>`;
dropdown.appendChild(header);
if (!items.length) {
const empty = document.createElement('div');
empty.style.cssText = 'padding:14px 12px;color:#9ca3af;font-size:12px;text-align:center;';
empty.textContent = 'No matching credentials';
dropdown.appendChild(empty);
} else {
items.forEach(item => {
const row = document.createElement('div');
row.style.cssText = 'display:flex;align-items:center;gap:9px;padding:9px 12px;cursor:pointer;transition:background 0.1s;';
row.onmouseenter = () => { row.style.background = '#f9fafb'; };
row.onmouseleave = () => { row.style.background = ''; };
const username = escHtml(item.plain?.username || '');
const name = escHtml(item.name);
row.innerHTML = `
<div style="width:30px;height:30px;border-radius:7px;background:#1e2d5a;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;">🔑</div>
<div style="flex:1;min-width:0;">
<div style="font-weight:600;color:#111827;font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${name}</div>
${username ? `<div style="font-size:11px;color:#6b7280;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${username}</div>` : ''}
</div>`;
row.addEventListener('click', () => {
if (usernameField && item.plain?.username) fillField(usernameField, item.plain.username);
if (item.plain?.password) fillField(pwField, item.plain.password);
dropdown.remove();
});
dropdown.appendChild(row);
});
}
document.body.appendChild(dropdown);
// Close on outside click
const close = e => {
if (!dropdown.contains(e.target) && e.target !== btn) {
dropdown.remove();
document.removeEventListener('click', close, true);
}
};
setTimeout(() => document.addEventListener('click', close, true), 0);
}
// ── Form detection ────────────────────────────────────────────────────────────
function notifyFormDetected() {
if (_hasNotifiedForm) return;
if (!visiblePasswordFields().length) return;
_hasNotifiedForm = true;
chrome.runtime.sendMessage({ type: 'FORMS_DETECTED' }).catch(() => {});
}
async function decorateFields() {
if (!visiblePasswordFields().length) return;
// Get cached vault items from session storage
const { vault_items } = await chrome.storage.session.get('vault_items').catch(() => ({}));
if (!vault_items?.length) return;
const host = location.hostname.replace(/^www\./, '');
const matching = vault_items.filter(item => {
if (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; }
});
injectAutofillButtons(matching);
}
// ── Auto-save banner ──────────────────────────────────────────────────────────
function showSaveBanner(username, password) {
if (_bannerEl) _bannerEl.remove();
const banner = document.createElement('div');
banner.id = '__pk_save_banner__';
Object.assign(banner.style, {
position: 'fixed',
top: '12px',
right: '12px',
zIndex: '2147483647',
background: '#ffffff',
border: '1px solid #e2e8f0',
borderRadius: '10px',
boxShadow: '0 8px 30px rgba(0,0,0,0.15)',
padding: '14px 16px 12px',
fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
fontSize: '13px',
color: '#1a1a2e',
maxWidth: '300px',
minWidth: '240px',
});
const site = escHtml(location.hostname);
const user = escHtml(username);
banner.innerHTML = `
<div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="9" width="18" height="12" rx="2" stroke="#1a73e8" stroke-width="1.8"/><path d="M8 9V6a4 4 0 018 0v3" stroke="#1a73e8" stroke-width="1.8" stroke-linecap="round"/></svg>
<strong style="flex:1;font-size:13px;color:#111827;">Save to PassKeeper?</strong>
<button id="__pk_close__" style="background:none;border:none;cursor:pointer;font-size:18px;color:#9ca3af;line-height:1;padding:0;">×</button>
</div>
<p style="color:#6b7280;font-size:12px;margin-bottom:10px;">
<strong style="color:#111827;">${user}</strong> on <strong style="color:#111827;">${site}</strong>
</p>
<div style="display:flex;gap:8px;">
<button id="__pk_save__" style="flex:1;padding:7px 0;background:#1a1a2e;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:12px;font-weight:600;">Save</button>
<button id="__pk_skip__" style="flex:1;padding:7px 0;background:transparent;color:#374151;border:1px solid #d1d5db;border-radius:6px;cursor:pointer;font-size:12px;">Not now</button>
</div>`;
document.body.appendChild(banner);
_bannerEl = banner;
const dismiss = () => { if (_bannerEl === banner) { banner.remove(); _bannerEl = null; } };
banner.querySelector('#__pk_close__').addEventListener('click', dismiss);
banner.querySelector('#__pk_skip__').addEventListener('click', dismiss);
banner.querySelector('#__pk_save__').addEventListener('click', () => {
chrome.runtime.sendMessage({
type: 'SAVE_CREDENTIALS',
data: { url: location.href, siteName: document.title || location.hostname, username, password },
}).catch(() => {});
dismiss();
});
setTimeout(dismiss, 20_000);
}
// ── Form submission watch ─────────────────────────────────────────────────────
function watchSubmissions() {
document.addEventListener('submit', e => {
const form = e.target;
const pwField = form.querySelector('input[type="password"]:not([disabled])');
if (!pwField?.value) return;
const userField = findUsernameField(pwField)
?? form.querySelector('input[type="email"]:not([disabled])')
?? form.querySelector('input[type="text"]:not([disabled])');
const username = userField?.value?.trim() || '';
const password = pwField.value;
if (username && password) {
setTimeout(() => showSaveBanner(username, password), 500);
}
}, true);
}
// ── Message listener ──────────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.type === 'DO_AUTOFILL') {
doAutofill(msg.username, msg.password);
sendResponse({ ok: true });
}
if (msg.type === 'VAULT_UPDATED') {
// Re-decorate fields with fresh data
document.querySelectorAll(`[${PK_ATTR}]`).forEach(el => el.removeAttribute(PK_ATTR));
document.querySelectorAll(`.${PK_BTN_CLASS}`).forEach(el => el.remove());
decorateFields();
}
return false;
});
// ── Init ──────────────────────────────────────────────────────────────────────
function init() {
notifyFormDetected();
decorateFields();
watchSubmissions();
_formObserver = new MutationObserver(() => {
_hasNotifiedForm = false;
notifyFormDetected();
decorateFields();
});
_formObserver.observe(document.body, { childList: true, subtree: true });
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 876 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 B

+93
View File
@@ -0,0 +1,93 @@
"""
Generate PassKeeper extension icons (16×16, 48×48, 128×128 PNG).
Requires Pillow (already a project dependency via qrcode[pil]):
python extension/make_icons.py
"""
import os
import math
from PIL import Image, ImageDraw
SIZES = [16, 48, 128]
OUT_DIR = os.path.join(os.path.dirname(__file__), 'icons')
BG_COLOR = '#1a73e8' # Google-blue background
FG_COLOR = '#ffffff' # White lock
def draw_icon(size: int) -> Image.Image:
img = Image.new('RGBA', (size, size), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Rounded-rectangle background
pad = max(1, size // 10)
draw.rounded_rectangle(
[pad, pad, size - pad - 1, size - pad - 1],
radius=max(2, size // 6),
fill=BG_COLOR,
)
# ── Lock body (rectangle with rounded bottom) ──────────────────────────
bx = size * 0.28
by = size * 0.50
bw = size * 0.44
bh = size * 0.36
draw.rounded_rectangle(
[bx, by, bx + bw, by + bh],
radius=max(1, int(size * 0.07)),
fill=FG_COLOR,
)
# Keyhole
kr = max(1, int(size * 0.07))
kx = size / 2
ky = by + bh * 0.40
draw.ellipse([kx - kr, ky - kr, kx + kr, ky + kr], fill=BG_COLOR)
# Small stem below the hole
stem_w = max(1, int(size * 0.06))
draw.rectangle(
[kx - stem_w, ky, kx + stem_w, ky + bh * 0.30],
fill=BG_COLOR,
)
# ── Shackle (arc) ──────────────────────────────────────────────────────
sw = max(1, int(size * 0.09)) # stroke width
slm = size * 0.28 # left margin of shackle oval
srm = size * 0.72 # right margin
st = size * 0.15 # top of shackle
sb = size * 0.58 # bottom of shackle (overlaps lock body top)
# Draw as thick arc by layering concentric arcs
for offset in range(sw):
f = offset / max(sw - 1, 1)
draw.arc(
[slm + offset, st + offset, srm - offset, sb - offset],
start=180, end=0,
fill=FG_COLOR,
width=1,
)
# Simpler approach: draw white arc with width parameter (Pillow 8+)
try:
draw.arc(
[slm, st, srm, sb],
start=180, end=0,
fill=FG_COLOR,
width=sw,
)
except TypeError:
pass # older Pillow — arcs from the loop above are sufficient
return img
def main():
os.makedirs(OUT_DIR, exist_ok=True)
for s in SIZES:
path = os.path.join(OUT_DIR, f'icon{s}.png')
draw_icon(s).save(path, 'PNG')
print(f' OK {path}')
print('Icons generated.')
if __name__ == '__main__':
main()
+44
View File
@@ -0,0 +1,44 @@
{
"manifest_version": 3,
"name": "PassKeeper",
"version": "1.0.0",
"description": "Autofill and manage your PassKeeper vault",
"permissions": ["storage", "activeTab", "tabs"],
"host_permissions": [
"https://pwkeeper.ngodanguyen.tech/*"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup/popup.html",
"default_title": "PassKeeper",
"default_icon": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["content/content.js"],
"run_at": "document_idle"
},
{
"matches": ["https://pwkeeper.ngodanguyen.tech/*"],
"js": ["bridge/bridge.js"],
"run_at": "document_idle"
}
],
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
}
}
+253
View File
@@ -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; }
+144
View File
@@ -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>
+542
View File
@@ -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, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
// ── 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);
+99
View File
@@ -0,0 +1,99 @@
/**
* extension/shared/crypto.js — Zero-knowledge cryptography for the extension.
*
* Mirrors the web app's crypto.js but:
* - Uses `crypto.subtle` (no `window.`) so it works in both popup and service worker.
* - deriveVaultKey uses extractable:true so the key can be serialised to
* chrome.storage.session (exportVaultKey / importVaultKey).
*/
const ExtCrypto = (() => {
const subtle = crypto.subtle;
// ── Helpers ─────────────────────────────────────────────────────────────────
function strToBytes(str) { return new TextEncoder().encode(str); }
function base64ToBytes(b64) {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function bytesToBase64(bytes) {
let bin = '';
bytes.forEach(b => (bin += String.fromCharCode(b)));
return btoa(bin);
}
// ── PBKDF2 base key ─────────────────────────────────────────────────────────
async function importPbkdf2Key(password) {
return subtle.importKey('raw', strToBytes(password), 'PBKDF2', false, ['deriveBits', 'deriveKey']);
}
// ── Auth hash (sent to server for login/register) ───────────────────────────
async function deriveAuthHash(password, email) {
const baseKey = await importPbkdf2Key(password);
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 (AES-256-GCM, extractable for session storage) ────────────────
async function deriveVaultKey(password, enc_key_salt) {
const baseKey = await importPbkdf2Key(password);
return subtle.deriveKey(
{ name: 'PBKDF2', salt: base64ToBytes(enc_key_salt), iterations: 600_000, hash: 'SHA-256' },
baseKey,
{ name: 'AES-GCM', length: 256 },
true, // extractable — needed to serialise into chrome.storage.session
['encrypt', 'decrypt']
);
}
/** Serialise a CryptoKey to a JSON string for chrome.storage.session. */
async function exportVaultKey(vaultKey) {
const jwk = await subtle.exportKey('jwk', vaultKey);
return JSON.stringify(jwk);
}
/** Deserialise a CryptoKey from chrome.storage.session. */
async function importVaultKey(jwkStr) {
const jwk = JSON.parse(jwkStr);
return subtle.importKey('jwk', jwk, { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']);
}
// ── Encrypt / Decrypt ────────────────────────────────────────────────────────
async function encryptItem(vaultKey, plainObj) {
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await subtle.encrypt(
{ name: 'AES-GCM', iv },
vaultKey,
strToBytes(JSON.stringify(plainObj))
);
return { enc_data: bytesToBase64(new Uint8Array(ct)), iv: bytesToBase64(iv) };
}
async function decryptItem(vaultKey, enc_data, iv) {
const pt = await subtle.decrypt(
{ name: 'AES-GCM', iv: base64ToBytes(iv) },
vaultKey,
base64ToBytes(enc_data)
);
return JSON.parse(new TextDecoder().decode(pt));
}
function generateSalt(byteLength = 16) {
return bytesToBase64(crypto.getRandomValues(new Uint8Array(byteLength)));
}
return { deriveAuthHash, deriveVaultKey, exportVaultKey, importVaultKey, encryptItem, decryptItem, generateSalt };
})();