04/20 Update extension UI and functions: add item, form filler

This commit is contained in:
2026-04-20 08:15:49 -04:00
parent 0320e4f8eb
commit bb000e0aff
5 changed files with 672 additions and 212 deletions
+26 -1
View File
@@ -83,6 +83,16 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
return false; return false;
} }
// Content script requests navigating the popup to the generator view.
if (msg.type === "OPEN_GENERATOR") {
chrome.storage.session.set({ popup_nav: "generator" });
chrome.action.openPopup().catch(() => {
// openPopup() requires user gesture in some Chrome versions — fallback is a no-op.
});
sendResponse({ ok: true });
return false;
}
// No-op ping from popup — keeps the service worker alive while the browser // No-op ping from popup — keeps the service worker alive while the browser
// is open so chrome.storage.session is not wiped between popup openings. // is open so chrome.storage.session is not wiped between popup openings.
if (msg.type === "KEEPALIVE") { if (msg.type === "KEEPALIVE") {
@@ -90,9 +100,24 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
return false; return false;
} }
// Popup signals vault cache was refreshed → re-check all tab badges. // Popup signals vault cache was refreshed → re-check badges AND forward
// the decrypted items directly to all content scripts (avoids storage read).
if (msg.type === "VAULT_UPDATED") { if (msg.type === "VAULT_UPDATED") {
refreshAllBadges(); refreshAllBadges();
const payload = {
type: "VAULT_UPDATED",
vault_items: msg.vault_items || [],
};
chrome.tabs.query({}, function (tabs) {
tabs.forEach(function (tab) {
if (
tab.url &&
(tab.url.startsWith("http://") || tab.url.startsWith("https://"))
) {
chrome.tabs.sendMessage(tab.id, payload).catch(function () {});
}
});
});
sendResponse({ ok: true }); sendResponse({ ok: true });
return false; return false;
} }
+517 -195
View File
@@ -2,23 +2,28 @@
* extension/content/content.js — PassKeeper content script. * extension/content/content.js — PassKeeper content script.
* *
* 1. Detects login forms → notifies background (badge count). * 1. Detects login forms → notifies background (badge count).
* 2. Injects a PassKeeper icon button into username AND password fields. * 2. Injects a PassKeeper icon button OUTSIDE the DOM (position:fixed, tracked
* Focusing either field (or clicking the icon) shows a suggestion dropdown * to the field via scroll/resize) into username AND password fields.
* anchored below the field, matching the browser-native autofill style. * This avoids breaking site layouts (flex/grid parents, React-controlled inputs).
* 3. Listens for DO_AUTOFILL from the popup → fills fields. * 3. Clicking the icon OR focusing a decorated field shows a suggestion dropdown.
* 4. Watches form submissions shows save-credentials banner. * 4. "More options…" shows a second panel with vault/generator actions.
* 5. Listens for DO_AUTOFILL from the popup → fills fields.
* 6. Watches form submissions → shows save-credentials banner.
*/ */
(() => { (() => {
"use strict"; "use strict";
const PK_ATTR = "data-pk-decorated"; const PK_ATTR = "data-pk-decorated";
const PK_BTN_CLASS = "__pk_autofill_btn__"; const PK_BTN_CLASS = "__pk_btn__";
const PK_DROPDOWN_ID = "__pk_dropdown__"; const PK_DROPDOWN_ID = "__pk_dropdown__";
const VAULT_URL = "https://pwkeeper.ngodanguyen.tech/vault";
let _bannerEl = null; let _bannerEl = null;
let _hasNotifiedForm = false; let _hasNotifiedForm = false;
let _formObserver = null; let _formObserver = null;
let _matchingItems = []; // cached matching vault items for the current page let _matchingItems = [];
// Map from field element → its fixed-position icon button element
const _fieldBtnMap = new WeakMap();
// ── Helpers ────────────────────────────────────────────────────────────────── // ── Helpers ──────────────────────────────────────────────────────────────────
@@ -29,31 +34,62 @@
.replace(/>/g, ">"); .replace(/>/g, ">");
} }
/**
* More robust visibility check than offsetParent (which fails for
* position:fixed elements and some modern layouts).
*/
function isVisible(el) {
if (!el || !el.getBoundingClientRect) return false;
if (el.disabled) return false;
const rect = el.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) return false;
const style = window.getComputedStyle(el);
if (
style.display === "none" ||
style.visibility === "hidden" ||
style.opacity === "0"
)
return false;
return true;
}
function visiblePasswordFields() { function visiblePasswordFields() {
return Array.from( return Array.from(
document.querySelectorAll('input[type="password"]'), document.querySelectorAll('input[type="password"]'),
).filter((el) => el.offsetParent !== null && !el.disabled); ).filter((el) => isVisible(el) && !el.disabled);
} }
function findUsernameField(pwField) { function findUsernameField(pwField) {
// 1. Walk backwards through all inputs in DOM order.
const all = Array.from(document.querySelectorAll("input")); const all = Array.from(document.querySelectorAll("input"));
const idx = all.indexOf(pwField); const idx = all.indexOf(pwField);
for (let i = idx - 1; i >= 0; i--) { for (let i = idx - 1; i >= 0; i--) {
const el = all[i]; const el = all[i];
if (!el.offsetParent || el.disabled) continue; if (!isVisible(el) || el.disabled) continue;
if (["email", "text", "tel"].includes(el.type)) return el; if (["email", "text", "tel"].includes(el.type)) return el;
} }
// 2. Fallback: search within the same form/ancestor container.
const container =
pwField.closest("form") ||
pwField.closest('[role="form"]') ||
pwField.parentElement;
if (container) {
const candidate = container.querySelector(
'input[type="email"]:not([disabled]), input[type="text"]:not([disabled]), input[type="tel"]:not([disabled])',
);
if (candidate && isVisible(candidate)) return candidate;
}
return null; return null;
} }
// ── Framework-compatible fill ───────────────────────────────────────────────── // ── Framework-compatible fill ─────────────────────────────────────────────────
function fillField(el, value) { function fillField(el, value) {
const setter = Object.getOwnPropertyDescriptor( const nativeSet = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, HTMLInputElement.prototype,
"value", "value",
)?.set; )?.set;
if (setter) setter.call(el, value); if (nativeSet) nativeSet.call(el, value);
else el.value = value; else el.value = value;
el.dispatchEvent(new Event("input", { bubbles: true })); el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true })); el.dispatchEvent(new Event("change", { bubbles: true }));
@@ -66,34 +102,142 @@
const usernameField = findUsernameField(pwField); const usernameField = findUsernameField(pwField);
if (usernameField && username) fillField(usernameField, username); if (usernameField && username) fillField(usernameField, username);
if (password) fillField(pwField, password); if (password) fillField(pwField, password);
[usernameField, pwField].filter(Boolean).forEach((el) => { [usernameField, pwField].filter(Boolean).forEach((el) => {
el.style.outline = "2px solid #1a73e8"; el.style.outline = "2px solid #c0392b";
setTimeout(() => { setTimeout(() => {
el.style.outline = ""; el.style.outline = "";
}, 1500); }, 1500);
}); });
} }
// ── Icon button (fixed-position, outside the DOM tree of the field) ───────────
/**
* Position the icon button over the right edge of `field` using fixed coords.
* This never touches the field's parent, so it can't break any layout.
*/
function positionBtn(btn, field) {
const rect = field.getBoundingClientRect();
if (rect.width === 0) {
btn.style.display = "none";
return;
}
btn.style.display = "flex";
btn.style.top = rect.top + rect.height / 2 - 13 + "px";
btn.style.left = rect.right - 30 + "px";
}
// createIconBtn is defined in the Field decoration section below.
// ── Suggestion dropdown ─────────────────────────────────────────────────────── // ── Suggestion dropdown ───────────────────────────────────────────────────────
function removeDropdown() { function removeDropdown() {
const existing = document.getElementById(PK_DROPDOWN_ID); const el = document.getElementById(PK_DROPDOWN_ID);
if (existing) existing.remove(); if (el) el.remove();
} }
/** /**
* Build and show the suggestion dropdown anchored directly below anchorField. * Build the dropdown anchored below `anchorField`.
* * Uses _matchingItems which is kept fresh via storage.onChanged listener.
* @param {HTMLInputElement} anchorField - field the dropdown is anchored to * `panel` is either 'credentials' (main list) or 'more' (options menu).
* @param {HTMLInputElement} pwField - associated password field to fill
* @param {object[]} items - matching vault items for this site
* @param {string} filterText - current field value used to filter
*/ */
function showDropdown(anchorField, pwField, items, filterText) { async function showDropdown(anchorField, pwField, filterText, panel) {
removeDropdown(); removeDropdown();
// Filter by what the user has already typed. // Use module-level _matchingItems (kept fresh by storage.onChanged).
// If still empty, try a direct storage read as last resort.
var freshItems = _matchingItems;
if (!freshItems.length) {
try {
var result = await chrome.storage.local.get("vault_items_cs");
var all = (result && result.vault_items_cs) || [];
freshItems = _filterForHost(all);
if (freshItems.length) _matchingItems = freshItems;
} catch (e) {}
}
const rect = anchorField.getBoundingClientRect();
const dropWidth = Math.max(260, rect.width);
const dropdown = document.createElement("div");
dropdown.id = PK_DROPDOWN_ID;
Object.assign(dropdown.style, {
position: "fixed",
top: rect.bottom + 4 + "px",
left: rect.left + "px",
width: dropWidth + "px",
background: "#fff",
border: "1px solid #dadce0",
borderRadius: "10px",
boxShadow: "0 6px 24px rgba(0,0,0,0.18)",
zIndex: "2147483647",
fontFamily:
"-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
fontSize: "13px",
overflow: "hidden",
});
if (panel === "more") {
buildMorePanel(dropdown, anchorField, pwField, freshItems, filterText);
} else {
buildCredentialsPanel(
dropdown,
anchorField,
pwField,
freshItems,
filterText,
);
}
document.body.appendChild(dropdown);
// Reposition on scroll/resize so it stays under the field.
function reposition() {
const r = anchorField.getBoundingClientRect();
dropdown.style.top = r.bottom + 4 + "px";
dropdown.style.left = r.left + "px";
}
window.addEventListener("scroll", reposition, {
passive: true,
capture: true,
});
window.addEventListener("resize", reposition, { passive: true });
// Close on outside mousedown or Escape.
function onOutside(e) {
const btn = _fieldBtnMap.get(anchorField);
if (
dropdown.contains(e.target) ||
e.target === anchorField ||
(btn && btn.contains(e.target))
)
return;
removeDropdown();
document.removeEventListener("mousedown", onOutside, true);
document.removeEventListener("keydown", onEscape, true);
}
function onEscape(e) {
if (e.key === "Escape") {
removeDropdown();
document.removeEventListener("mousedown", onOutside, true);
document.removeEventListener("keydown", onEscape, true);
}
}
setTimeout(function () {
document.addEventListener("mousedown", onOutside, true);
document.addEventListener("keydown", onEscape, true);
}, 0);
}
// ── Credentials panel (main list) ────────────────────────────────────────────
function buildCredentialsPanel(
dropdown,
anchorField,
pwField,
items,
filterText,
) {
const q = (filterText || "").trim().toLowerCase(); const q = (filterText || "").trim().toLowerCase();
const filtered = q const filtered = q
? items.filter(function (item) { ? items.filter(function (item) {
@@ -105,47 +249,22 @@
}) })
: items; : items;
// Don't show an empty dropdown while the user is actively typing and nothing matches.
if (!filtered.length && q) return;
const dropdown = document.createElement("div");
dropdown.id = PK_DROPDOWN_ID;
// Anchor below the field, same left edge, at least 260 px wide.
const rect = anchorField.getBoundingClientRect();
const dropWidth = Math.max(260, rect.width);
Object.assign(dropdown.style, {
position: "fixed",
top: rect.bottom + 2 + "px",
left: rect.left + "px",
width: dropWidth + "px",
background: "#fff",
border: "1px solid #dadce0",
borderRadius: "8px",
boxShadow: "0 4px 20px rgba(0,0,0,0.18)",
zIndex: "2147483647",
fontFamily:
"-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif",
fontSize: "13px",
overflow: "hidden",
});
// The username field to fill.
const usernameField = const usernameField =
anchorField.type === "password" anchorField.type === "password"
? findUsernameField(anchorField) ? findUsernameField(anchorField)
: anchorField; : anchorField;
if (filtered.length === 0) { if (filtered.length === 0) {
// No items at all for this site. // No saved passwords — show a minimal "no items" row + More options.
const empty = document.createElement("div"); const empty = document.createElement("div");
Object.assign(empty.style, { Object.assign(empty.style, {
padding: "12px 14px", padding: "12px 14px",
color: "#5f6368", color: "#5f6368",
fontSize: "12px", fontSize: "12px",
}); });
empty.textContent = "No saved passwords for this site."; empty.textContent = q
? "No matches found."
: "No saved passwords for this site.";
dropdown.appendChild(empty); dropdown.appendChild(empty);
} else { } else {
filtered.forEach(function (item) { filtered.forEach(function (item) {
@@ -154,7 +273,7 @@
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
gap: "10px", gap: "10px",
padding: "9px 12px", padding: "10px 14px",
cursor: "pointer", cursor: "pointer",
transition: "background 0.1s", transition: "background 0.1s",
}); });
@@ -165,7 +284,7 @@
row.style.background = ""; row.style.background = "";
}; };
// Derive display hostname from stored URL. // Derive display hostname.
var siteHost = item.name; var siteHost = item.name;
if (item.plain && item.plain.url) { if (item.plain && item.plain.url) {
try { try {
@@ -176,13 +295,13 @@
var username = escHtml((item.plain && item.plain.username) || ""); var username = escHtml((item.plain && item.plain.username) || "");
var site = escHtml(siteHost); var site = escHtml(siteHost);
// Lock icon avatar. // Lock icon avatar — filled dark circle like the screenshot.
var avatar = document.createElement("div"); var avatar = document.createElement("div");
Object.assign(avatar.style, { Object.assign(avatar.style, {
width: "32px", width: "34px",
height: "32px", height: "34px",
borderRadius: "50%", borderRadius: "50%",
background: "#e8eaed", background: "#1a1a2e",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
justifyContent: "center", justifyContent: "center",
@@ -190,30 +309,30 @@
}); });
avatar.innerHTML = avatar.innerHTML =
'<svg width="16" height="16" viewBox="0 0 24 24" fill="none">' + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none">' +
'<rect x="3" y="10" width="18" height="12" rx="2" fill="#5f6368"/>' + '<rect x="3" y="10" width="18" height="12" rx="2" fill="#fff"/>' +
'<path d="M8 10V7a4 4 0 018 0v3" stroke="#5f6368" stroke-width="2" stroke-linecap="round" fill="none"/>' + '<path d="M8 10V7a4 4 0 018 0v3" stroke="#fff" stroke-width="2" stroke-linecap="round" fill="none"/>' +
"</svg>"; "</svg>";
// Text block: site name + username. // Text.
var text = document.createElement("div"); var text = document.createElement("div");
text.style.cssText = "flex:1;min-width:0;"; text.style.cssText = "flex:1;min-width:0;";
text.innerHTML = text.innerHTML =
'<div style="font-size:12px;color:#202124;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + '<div style="font-size:13px;color:#202124;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' +
site + site +
"</div>" + "</div>" +
(username (username
? '<div style="font-size:11px;color:#5f6368;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + ? '<div style="font-size:11px;color:#5f6368;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:1px;">' +
username + username +
"</div>" "</div>"
: ""); : "");
// Edit (pencil) icon. // Edit pencil.
var editBtn = document.createElement("button"); var editBtn = document.createElement("button");
Object.assign(editBtn.style, { Object.assign(editBtn.style, {
background: "none", background: "none",
border: "none", border: "none",
cursor: "pointer", cursor: "pointer",
padding: "4px", padding: "5px",
color: "#1a73e8", color: "#1a73e8",
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
@@ -222,9 +341,9 @@
}); });
editBtn.title = "Edit in PassKeeper"; editBtn.title = "Edit in PassKeeper";
editBtn.innerHTML = editBtn.innerHTML =
'<svg width="15" height="15" viewBox="0 0 24 24" fill="none">' + '<svg width="16" height="16" viewBox="0 0 24 24" fill="none">' +
'<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="#1a73e8" stroke-width="2" stroke-linecap="round"/>' + '<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="#1a73e8" stroke-width="1.8" stroke-linecap="round"/>' +
'<path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="#1a73e8" stroke-width="2" stroke-linejoin="round"/>' + '<path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="#1a73e8" stroke-width="1.8" stroke-linejoin="round"/>' +
"</svg>"; "</svg>";
editBtn.addEventListener("mousedown", function (e) { editBtn.addEventListener("mousedown", function (e) {
e.preventDefault(); e.preventDefault();
@@ -239,7 +358,6 @@
row.appendChild(text); row.appendChild(text);
row.appendChild(editBtn); row.appendChild(editBtn);
// Clicking the row fills both fields.
row.addEventListener("mousedown", function (e) { row.addEventListener("mousedown", function (e) {
if (e.target === editBtn || editBtn.contains(e.target)) return; if (e.target === editBtn || editBtn.contains(e.target)) return;
e.preventDefault(); e.preventDefault();
@@ -257,157 +375,339 @@
dropdown.appendChild(row); dropdown.appendChild(row);
}); });
}
// "More options…" footer row. // Divider + "More options…" footer — always shown.
var divider = document.createElement("div"); var divider = document.createElement("div");
divider.style.cssText = "height:1px;background:#e8eaed;margin:0 12px;"; divider.style.cssText = "height:1px;background:#e8eaed;";
dropdown.appendChild(divider); dropdown.appendChild(divider);
var more = document.createElement("div"); var more = document.createElement("div");
Object.assign(more.style, { Object.assign(more.style, {
display: "flex",
alignItems: "center",
gap: "10px",
padding: "10px 14px",
cursor: "pointer",
color: "#202124",
fontSize: "13px",
transition: "background 0.1s",
});
more.onmouseenter = function () {
more.style.background = "#f1f3f4";
};
more.onmouseleave = function () {
more.style.background = "";
};
more.innerHTML =
'<svg width="16" height="16" viewBox="0 0 24 24" fill="none">' +
'<circle cx="5" cy="12" r="1.8" fill="#5f6368"/>' +
'<circle cx="12" cy="12" r="1.8" fill="#5f6368"/>' +
'<circle cx="19" cy="12" r="1.8" fill="#5f6368"/>' +
"</svg>" +
'<span style="flex:1;">More options\u2026</span>';
more.addEventListener("mousedown", function (e) {
e.preventDefault();
showDropdown(anchorField, pwField, filterText, "more");
});
dropdown.appendChild(more);
}
// ── More options panel ────────────────────────────────────────────────────────
function buildMorePanel(dropdown, anchorField, pwField, items, filterText) {
// Back header.
var backRow = document.createElement("div");
Object.assign(backRow.style, {
display: "flex",
alignItems: "center",
gap: "6px",
padding: "10px 14px",
cursor: "pointer",
color: "#1a73e8",
fontSize: "13px",
fontWeight: "600",
borderBottom: "1px solid #e8eaed",
transition: "background 0.1s",
});
backRow.onmouseenter = function () {
backRow.style.background = "#f1f3f4";
};
backRow.onmouseleave = function () {
backRow.style.background = "";
};
backRow.innerHTML =
'<svg width="16" height="16" viewBox="0 0 24 24" fill="none">' +
'<path d="M15 18l-6-6 6-6" stroke="#1a73e8" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
"</svg> Back";
backRow.addEventListener("mousedown", function (e) {
e.preventDefault();
showDropdown(anchorField, pwField, filterText, "credentials");
});
dropdown.appendChild(backRow);
// Menu items matching the screenshot.
var menuItems = [
{
icon: '<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" stroke="#5f6368" stroke-width="1.8" fill="none"/><line x1="12" y1="9" x2="12" y2="13" stroke="#5f6368" stroke-width="1.8" stroke-linecap="round"/><line x1="12" y1="17" x2="12.01" y2="17" stroke="#5f6368" stroke-width="2" stroke-linecap="round"/>',
label: "Report a problem",
action: function () {
chrome.runtime
.sendMessage({ type: "OPEN_VAULT" })
.catch(function () {});
removeDropdown();
},
},
{
icon: '<rect x="3" y="9" width="18" height="12" rx="2" stroke="#5f6368" stroke-width="1.8" fill="none"/><path d="M8 9V6a4 4 0 018 0v3" stroke="#5f6368" stroke-width="1.8" stroke-linecap="round" fill="none"/><circle cx="12" cy="15" r="1.5" fill="#5f6368"/>',
label: "Generate a password",
chevron: true,
action: function () {
chrome.runtime
.sendMessage({ type: "OPEN_GENERATOR" })
.catch(function () {});
removeDropdown();
},
},
{
icon: '<rect x="2" y="3" width="20" height="14" rx="2" stroke="#5f6368" stroke-width="1.8" fill="none"/><path d="M8 21h8M12 17v4" stroke="#5f6368" stroke-width="1.8" stroke-linecap="round"/>',
label: "Open my vault",
action: function () {
chrome.runtime
.sendMessage({ type: "OPEN_VAULT" })
.catch(function () {});
removeDropdown();
},
},
];
menuItems.forEach(function (item) {
var row = document.createElement("div");
Object.assign(row.style, {
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
gap: "8px", gap: "12px",
padding: "9px 12px", padding: "11px 14px",
cursor: "pointer", cursor: "pointer",
color: "#1a73e8", color: "#202124",
fontSize: "12px", fontSize: "13px",
fontWeight: "500",
transition: "background 0.1s", transition: "background 0.1s",
borderBottom: "1px solid #f3f4f6",
}); });
more.onmouseenter = function () { row.onmouseenter = function () {
more.style.background = "#f1f3f4"; row.style.background = "#f1f3f4";
}; };
more.onmouseleave = function () { row.onmouseleave = function () {
more.style.background = ""; row.style.background = "";
}; };
more.innerHTML =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none">' + var iconWrap = document.createElement("div");
'<circle cx="5" cy="12" r="1.5" fill="#1a73e8"/>' + iconWrap.style.cssText =
'<circle cx="12" cy="12" r="1.5" fill="#1a73e8"/>' + "width:18px;height:18px;display:flex;align-items:center;justify-content:center;flex-shrink:0;";
'<circle cx="19" cy="12" r="1.5" fill="#1a73e8"/>' + iconWrap.innerHTML =
"</svg> More options\u2026"; '<svg width="18" height="18" viewBox="0 0 24 24">' +
more.addEventListener("mousedown", function (e) { item.icon +
"</svg>";
var label = document.createElement("span");
label.style.cssText = "flex:1;";
label.textContent = item.label;
row.appendChild(iconWrap);
row.appendChild(label);
if (item.chevron) {
var chev = document.createElement("div");
chev.innerHTML =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none">' +
'<path d="M9 18l6-6-6-6" stroke="#5f6368" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
"</svg>";
row.appendChild(chev);
} else {
var extIcon = document.createElement("div");
extIcon.innerHTML =
'<svg width="14" height="14" viewBox="0 0 24 24" fill="none">' +
'<path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6" stroke="#5f6368" stroke-width="1.8" stroke-linecap="round"/>' +
'<path d="M15 3h6v6M10 14L21 3" stroke="#5f6368" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>' +
"</svg>";
row.appendChild(extIcon);
}
row.addEventListener("mousedown", function (e) {
e.preventDefault(); e.preventDefault();
chrome.runtime item.action();
.sendMessage({ type: "OPEN_VAULT" })
.catch(function () {});
removeDropdown();
}); });
dropdown.appendChild(more);
}
document.body.appendChild(dropdown); dropdown.appendChild(row);
});
// Close on outside mousedown or Escape key.
function onOutside(e) {
if (!dropdown.contains(e.target) && e.target !== anchorField) {
removeDropdown();
document.removeEventListener("mousedown", onOutside, true);
document.removeEventListener("keydown", onEscape, true);
}
}
function onEscape(e) {
if (e.key === "Escape") {
removeDropdown();
document.removeEventListener("mousedown", onOutside, true);
document.removeEventListener("keydown", onEscape, true);
}
}
setTimeout(function () {
document.addEventListener("mousedown", onOutside, true);
document.addEventListener("keydown", onEscape, true);
}, 0);
} }
// ── Field decoration ────────────────────────────────────────────────────────── // ── Field decoration ──────────────────────────────────────────────────────────
/** // Map from field element → AbortController so we can cancel its listeners on re-decoration.
* Inject the PassKeeper icon button into a field and wire focus/input events. const _fieldAbortMap = new WeakMap();
*
* @param {HTMLInputElement} field - field to decorate (username OR password) function decorateField(field, pwField) {
* @param {HTMLInputElement} pwField - associated password field if (field.getAttribute(PK_ATTR)) return;
* @param {object[]} items - matching vault items for this site
*/
function decorateField(field, pwField, items) {
if (field.getAttribute(PK_ATTR)) return; // already decorated
field.setAttribute(PK_ATTR, "1"); field.setAttribute(PK_ATTR, "1");
// Wrap the field so the icon button can be positioned absolutely inside it. // Cancel any previous listeners on this field.
var wrap = document.createElement("div"); const prevAC = _fieldAbortMap.get(field);
wrap.style.cssText = "position:relative;display:inline-block;width:100%;"; if (prevAC) prevAC.abort();
field.parentNode.insertBefore(wrap, field); const ac = new AbortController();
wrap.appendChild(field); _fieldAbortMap.set(field, ac);
const sig = ac.signal;
// Prevent typed text from sliding under the icon. createIconBtn(field, pwField, sig);
field.style.paddingRight = "34px"; }
// PassKeeper icon button inside the right edge of the field. function createIconBtn(field, pwField, abortSignal) {
var btn = document.createElement("button"); const btn = document.createElement("button");
btn.type = "button"; btn.type = "button";
btn.className = PK_BTN_CLASS; btn.className = PK_BTN_CLASS;
btn.title = "Autofill with PassKeeper"; btn.title = "PassKeeper autofill";
btn.setAttribute("aria-label", "Autofill with PassKeeper"); btn.setAttribute("aria-label", "Autofill with PassKeeper");
btn.style.cssText = [ btn.style.cssText = [
"position:absolute", "position:fixed",
"right:6px", "width:26px",
"top:50%", "height:26px",
"transform:translateY(-50%)", "background:#c0392b",
"background:none",
"border:none", "border:none",
"border-radius:5px",
"cursor:pointer", "cursor:pointer",
"padding:3px",
"display:flex", "display:flex",
"align-items:center", "align-items:center",
"justify-content:center", "justify-content:center",
"z-index:2147483646", "z-index:2147483646",
"padding:0",
"box-shadow:0 1px 4px rgba(0,0,0,0.3)",
"transition:background 0.15s",
].join(";"); ].join(";");
btn.innerHTML = btn.innerHTML =
'<svg width="18" height="18" viewBox="0 0 24 24" fill="none">' + '<svg width="14" height="14" viewBox="0 0 24 24" fill="none">' +
'<rect x="3" y="9" width="18" height="12" rx="2" stroke="#c0392b" stroke-width="1.8"/>' + '<rect x="3" y="9" width="18" height="12" rx="2" stroke="#fff" stroke-width="2"/>' +
'<path d="M8 9V6a4 4 0 018 0v3" stroke="#c0392b" stroke-width="1.8" stroke-linecap="round"/>' + '<path d="M8 9V6a4 4 0 018 0v3" stroke="#fff" stroke-width="2" stroke-linecap="round"/>' +
'<circle cx="12" cy="15" r="1.5" fill="#c0392b"/>' + '<circle cx="12" cy="15" r="1.5" fill="#fff"/>' +
"</svg>"; "</svg>";
wrap.appendChild(btn); btn.addEventListener("mouseenter", function () {
btn.style.background = "#a93226";
// Show dropdown when the field gains focus.
field.addEventListener("focus", function () {
showDropdown(field, pwField, items, field.value);
}); });
btn.addEventListener("mouseleave", function () {
btn.style.background = "#c0392b";
});
positionBtn(btn, field);
document.body.appendChild(btn);
_fieldBtnMap.set(field, btn);
// Remove the button when the AbortController fires (re-decoration).
abortSignal.addEventListener("abort", function () {
btn.remove();
_fieldBtnMap.delete(field);
});
// Keep button tracked as page scrolls/resizes.
function reposition() {
if (document.body.contains(btn)) positionBtn(btn, field);
}
window.addEventListener("scroll", reposition, {
passive: true,
signal: abortSignal,
});
window.addEventListener("resize", reposition, {
passive: true,
signal: abortSignal,
});
// ── All event handlers read _matchingItems at call time, never from closure ──
// Show dropdown on focus — reads vault_items fresh from storage each time.
field.addEventListener(
"focus",
function () {
showDropdown(field, pwField, field.value, "credentials");
},
{ signal: abortSignal },
);
// Re-filter as user types. // Re-filter as user types.
field.addEventListener("input", function () { field.addEventListener(
showDropdown(field, pwField, items, field.value); "input",
}); function () {
showDropdown(field, pwField, field.value, "credentials");
},
{ signal: abortSignal },
);
// Icon button toggles the dropdown. // Dim button when field loses focus and no dropdown is open.
field.addEventListener(
"blur",
function () {
setTimeout(function () {
if (!document.getElementById(PK_DROPDOWN_ID))
btn.style.opacity = "0.4";
}, 150);
},
{ signal: abortSignal },
);
field.addEventListener(
"focus",
function () {
btn.style.opacity = "1";
},
{ signal: abortSignal },
);
// Icon click: toggle dropdown.
btn.addEventListener("mousedown", function (e) { btn.addEventListener("mousedown", function (e) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
var existing = document.getElementById(PK_DROPDOWN_ID); if (document.getElementById(PK_DROPDOWN_ID)) {
if (existing) {
removeDropdown(); removeDropdown();
} else { } else {
showDropdown(field, pwField, items, field.value); showDropdown(field, pwField, field.value, "credentials");
} }
}); });
return btn;
} }
async function decorateFields() { async function decorateFields() {
// Get cached vault items from session storage. // Read from chrome.storage.local — reliable across all Chrome versions and
var result; // does not depend on message delivery from the service worker.
var all = [];
try { try {
result = await chrome.storage.session.get("vault_items"); var result = await chrome.storage.local.get("vault_items_cs");
} catch (e) { all = (result && result.vault_items_cs) || [];
return; } catch (e) {}
}
var vault_items = result && result.vault_items;
if (!vault_items || !vault_items.length) return;
_matchingItems = _filterForHost(all);
console.log(
"[PassKeeper] decorateFields: host=" +
location.hostname.replace(/^www\./, "") +
", matched=" +
_matchingItems.length +
" of " +
all.length +
" items",
);
// Decorate every visible password field and its paired username field.
visiblePasswordFields().forEach(function (pwField) {
var usernameField = findUsernameField(pwField);
if (usernameField) decorateField(usernameField, pwField);
decorateField(pwField, pwField);
});
}
// ── Vault item helpers ────────────────────────────────────────────────────────
function _filterForHost(items) {
var host = location.hostname.replace(/^www\./, ""); var host = location.hostname.replace(/^www\./, "");
_matchingItems = vault_items.filter(function (item) { return (items || []).filter(function (item) {
if (item.item_type !== "password" || !(item.plain && item.plain.url)) if (item.item_type !== "password" || !(item.plain && item.plain.url))
return false; return false;
try { try {
@@ -417,13 +717,6 @@
return false; return false;
} }
}); });
// Decorate every visible password field and its paired username field.
visiblePasswordFields().forEach(function (pwField) {
var usernameField = findUsernameField(pwField);
if (usernameField) decorateField(usernameField, pwField, _matchingItems);
decorateField(pwField, pwField, _matchingItems);
});
} }
// ── Form detection ──────────────────────────────────────────────────────────── // ── Form detection ────────────────────────────────────────────────────────────
@@ -440,27 +733,16 @@
// ── Duplicate detection ─────────────────────────────────────────────────────── // ── Duplicate detection ───────────────────────────────────────────────────────
async function classifyCredentials(username, password) { async function classifyCredentials(username, password) {
var result; var all = [];
try { try {
result = await chrome.storage.session.get("vault_items"); var result = await chrome.storage.local.get("vault_items_cs");
all = (result && result.vault_items_cs) || [];
} catch (e) { } catch (e) {
return "new"; return "new";
} }
var vault_items = result && result.vault_items; if (!all.length) return "new";
if (!vault_items || !vault_items.length) return "new";
var host = location.hostname.replace(/^www\./, "");
var siteItems = vault_items.filter(function (item) {
if (item.item_type !== "password" || !(item.plain && item.plain.url))
return false;
try {
var h = new URL(item.plain.url).hostname.replace(/^www\./, "");
return h === host || h.endsWith("." + host) || host.endsWith("." + h);
} catch (e) {
return false;
}
});
var siteItems = _filterForHost(all);
if (!siteItems.length) return "new"; if (!siteItems.length) return "new";
var exactMatch = siteItems.some(function (item) { var exactMatch = siteItems.some(function (item) {
return ( return (
@@ -506,7 +788,7 @@
banner.innerHTML = banner.innerHTML =
'<div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;">' + '<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>' + '<svg width="18" height="18" viewBox="0 0 24 24" fill="none"><rect x="3" y="9" width="18" height="12" rx="2" stroke="#c0392b" stroke-width="1.8"/><path d="M8 9V6a4 4 0 018 0v3" stroke="#c0392b" stroke-width="1.8" stroke-linecap="round"/></svg>' +
'<strong style="flex:1;font-size:13px;color:#111827;">' + '<strong style="flex:1;font-size:13px;color:#111827;">' +
escHtml(title) + escHtml(title) +
"</strong>" + "</strong>" +
@@ -520,7 +802,7 @@
"</strong>" + "</strong>" +
"</p>" + "</p>" +
'<div style="display:flex;gap:8px;">' + '<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_save__" style="flex:1;padding:7px 0;background:#c0392b;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>' + '<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>"; "</div>";
@@ -575,7 +857,6 @@
var username = var username =
(userField && userField.value && userField.value.trim()) || ""; (userField && userField.value && userField.value.trim()) || "";
var password = pwField.value; var password = pwField.value;
if (!username || !password) return; if (!username || !password) return;
removeDropdown(); removeDropdown();
@@ -587,7 +868,6 @@
"\u2192", "\u2192",
credentialState, credentialState,
); );
if (credentialState === "same") return; if (credentialState === "same") return;
setTimeout(function () { setTimeout(function () {
@@ -606,7 +886,22 @@
sendResponse({ ok: true }); sendResponse({ ok: true });
} }
if (msg.type === "VAULT_UPDATED") { if (msg.type === "VAULT_UPDATED") {
// Items may arrive in the message payload (best-effort), but the source
// of truth is now chrome.storage.local which was already written by the popup.
var allItems = msg.vault_items || [];
if (allItems.length) {
_matchingItems = _filterForHost(allItems);
console.log(
"[PassKeeper] VAULT_UPDATED (message): matched=" +
_matchingItems.length +
" of " +
allItems.length,
);
}
// Always re-decorate (also re-reads storage if message had no items).
document.querySelectorAll("[" + PK_ATTR + "]").forEach(function (el) { document.querySelectorAll("[" + PK_ATTR + "]").forEach(function (el) {
var ac = _fieldAbortMap.get(el);
if (ac) ac.abort();
el.removeAttribute(PK_ATTR); el.removeAttribute(PK_ATTR);
}); });
document.querySelectorAll("." + PK_BTN_CLASS).forEach(function (el) { document.querySelectorAll("." + PK_BTN_CLASS).forEach(function (el) {
@@ -625,6 +920,33 @@
decorateFields(); decorateFields();
watchSubmissions(); watchSubmissions();
// React instantly when the popup writes fresh vault data to local storage.
// This fires in the same tick as the write — no message delivery required.
chrome.storage.onChanged.addListener(function (changes, area) {
if (area === "local" && changes.vault_items_cs) {
var allItems = changes.vault_items_cs.newValue || [];
_matchingItems = _filterForHost(allItems);
console.log(
"[PassKeeper] storage.onChanged: matched=" +
_matchingItems.length +
" of " +
allItems.length +
" items",
);
// Re-decorate all fields with the fresh items.
document.querySelectorAll("[" + PK_ATTR + "]").forEach(function (el) {
var ac = _fieldAbortMap.get(el);
if (ac) ac.abort();
el.removeAttribute(PK_ATTR);
});
document.querySelectorAll("." + PK_BTN_CLASS).forEach(function (el) {
el.remove();
});
removeDropdown();
decorateFields();
}
});
_formObserver = new MutationObserver(function () { _formObserver = new MutationObserver(function () {
_hasNotifiedForm = false; _hasNotifiedForm = false;
notifyFormDetected(); notifyFormDetected();
+32 -6
View File
@@ -432,9 +432,11 @@ body {
inset: 0; inset: 0;
background: rgba(0, 0, 0, 0.45); background: rgba(0, 0, 0, 0.45);
display: flex; display: flex;
align-items: center; align-items: flex-start; /* anchor to top so card is never cut off */
justify-content: center; justify-content: center;
z-index: 9999; z-index: 9999;
overflow-y: auto; /* allow scrolling if popup height is small */
padding: 16px 14px; /* breathing room from top/bottom edges */
} }
.save-overlay.hidden { .save-overlay.hidden {
display: none; display: none;
@@ -442,24 +444,27 @@ body {
.save-modal { .save-modal {
background: #fff; background: #fff;
border-radius: 12px; border-radius: 12px;
padding: 20px 18px 16px; padding: 18px 16px 14px;
width: 272px; width: 100%; /* fill the overlay width minus its padding */
max-width: 288px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22); box-shadow: 0 12px 40px rgba(0, 0, 0, 0.22);
flex-shrink: 0; /* never crush the card */
} }
.save-modal-header { .save-modal-header {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
font-size: 14px; font-size: 13px;
font-weight: 700; font-weight: 700;
color: #1a1a2e; color: #1a1a2e;
margin-bottom: 6px; margin-bottom: 5px;
} }
.save-modal-sub { .save-modal-sub {
font-size: 11px; font-size: 11px;
color: #6b7280; color: #6b7280;
margin-bottom: 12px; margin-bottom: 10px;
word-break: break-all; word-break: break-all;
line-height: 1.4;
} }
.save-modal-actions { .save-modal-actions {
display: flex; display: flex;
@@ -473,6 +478,27 @@ body {
margin-top: 0; margin-top: 0;
} }
/* Folder select inside the save modal */
.save-folder-select {
width: 100%;
padding: 7px 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 13px;
color: #1a1a2e;
background: #fff;
outline: none;
cursor: pointer;
transition:
border-color 0.15s,
box-shadow 0.15s;
appearance: auto;
}
.save-folder-select:focus {
border-color: #c0392b;
box-shadow: 0 0 0 2px rgba(192, 57, 43, 0.12);
}
/* ── Generator view ──────────────────────────────────────────────── */ /* ── Generator view ──────────────────────────────────────────────── */
.gen-suggestion { .gen-suggestion {
background: #e8f5f0; background: #e8f5f0;
+6
View File
@@ -313,6 +313,12 @@
placeholder="username or email" placeholder="username or email"
/> />
</div> </div>
<div class="form-group">
<label for="save-folder">Folder</label>
<select id="save-folder" class="save-folder-select">
<option value="">— No folder —</option>
</select>
</div>
<div class="save-modal-actions"> <div class="save-modal-actions">
<button id="btn-save-yes" class="btn-primary btn-sm">Save</button> <button id="btn-save-yes" class="btn-primary btn-sm">Save</button>
<button id="btn-save-no" class="btn-ghost btn-sm">Not now</button> <button id="btn-save-no" class="btn-ghost btn-sm">Not now</button>
+91 -10
View File
@@ -341,7 +341,11 @@ async function signOut() {
} }
} catch {} } catch {}
await chrome.storage.session.clear(); await chrome.storage.session.clear();
await chrome.storage.local.remove(["refresh_token", "enc_key_salt"]); await chrome.storage.local.remove([
"refresh_token",
"enc_key_salt",
"vault_items_cs",
]);
_vaultKey = null; _vaultKey = null;
_items = []; _items = [];
showView("login"); showView("login");
@@ -411,8 +415,27 @@ async function fetchAndDecryptVault() {
}), }),
); );
// Write to session for the popup's own use (badge, rendering).
await chrome.storage.session.set({ vault_items: _items }); await chrome.storage.session.set({ vault_items: _items });
chrome.runtime.sendMessage({ type: "VAULT_UPDATED" }).catch(() => {});
// Write a lightweight copy to local storage — this is what content scripts
// read, since chrome.storage.local works reliably across all Chrome versions
// and does not require message delivery from the background service worker.
const itemsForContentScript = _items.map((item) => ({
id: item.id,
name: item.name,
item_type: item.item_type,
plain: item.plain,
}));
await chrome.storage.local.set({ vault_items_cs: itemsForContentScript });
// Notify background to refresh badges and forward to content scripts.
chrome.runtime
.sendMessage({
type: "VAULT_UPDATED",
vault_items: itemsForContentScript,
})
.catch(() => {});
} catch (err) { } catch (err) {
console.error("fetchAndDecryptVault:", err); console.error("fetchAndDecryptVault:", err);
} finally { } finally {
@@ -581,6 +604,30 @@ function initTabs() {
// ── Save-prompt modal ───────────────────────────────────────────────────────── // ── Save-prompt modal ─────────────────────────────────────────────────────────
/**
* Populate the folder <select> inside the save modal.
* Fetches /api/folders and rebuilds the option list.
* The first option ("— No folder —") with value "" is always kept.
*/
async function loadFoldersIntoSaveModal() {
const select = $("save-folder");
// Reset to just the placeholder option.
select.innerHTML = '<option value="">— No folder —</option>';
try {
const res = await apiFetch("/api/folders");
if (!res?.ok) return;
const folders = await res.json();
folders.forEach((f) => {
const opt = document.createElement("option");
opt.value = f.id;
opt.textContent = f.name;
select.appendChild(opt);
});
} catch (err) {
console.error("[PassKeeper] loadFoldersIntoSaveModal failed:", err);
}
}
/** /**
* Show the save-prompt overlay. It is a blocking modal — no backdrop click, * Show the save-prompt overlay. It is a blocking modal — no backdrop click,
* no ✕ button — so the user MUST click "Save" or "Not now". * no ✕ button — so the user MUST click "Save" or "Not now".
@@ -602,6 +649,10 @@ async function checkPendingSave() {
? "Update in PassKeeper?" ? "Update in PassKeeper?"
: "Save to PassKeeper?"; : "Save to PassKeeper?";
// Load folders (non-blocking — modal shows immediately, folders populate async).
$("save-folder").value = "";
loadFoldersIntoSaveModal();
// Show the overlay. // Show the overlay.
$("save-prompt-overlay").classList.remove("hidden"); $("save-prompt-overlay").classList.remove("hidden");
$("save-name").focus(); $("save-name").focus();
@@ -635,6 +686,9 @@ async function saveCredential(data) {
notes: "", notes: "",
}; };
const name = $("save-name").value.trim() || data.siteName || "Untitled"; const name = $("save-name").value.trim() || data.siteName || "Untitled";
// Read selected folder — empty string means no folder (null).
const folderVal = $("save-folder").value;
const folder_id = folderVal ? parseInt(folderVal, 10) : null;
const { enc_data, iv } = await ExtCrypto.encryptItem(_vaultKey, plain); const { enc_data, iv } = await ExtCrypto.encryptItem(_vaultKey, plain);
try { try {
const res = await apiFetch("/api/vault", { const res = await apiFetch("/api/vault", {
@@ -642,12 +696,16 @@ async function saveCredential(data) {
body: JSON.stringify({ body: JSON.stringify({
name, name,
item_type: "password", item_type: "password",
folder_id: null, folder_id,
enc_data, enc_data,
iv, iv,
}), }),
}); });
if (res?.ok) { if (res?.ok) {
console.log(
"[PassKeeper] Credential saved to vault, folder_id:",
folder_id,
);
await fetchAndDecryptVault(); await fetchAndDecryptVault();
renderList(); renderList();
} }
@@ -821,14 +879,37 @@ async function init() {
const sessionState = await restoreSessionIfAvailable(); const sessionState = await restoreSessionIfAvailable();
if (sessionState === "vault") { if (sessionState === "vault") {
showView("vault"); // Check whether the content script requested a specific view (e.g. generator).
await checkPendingSave(); const { popup_nav } = await chrome.storage.session.get("popup_nav");
if (_items.length) { if (popup_nav) {
renderList(); await chrome.storage.session.remove("popup_nav");
fetchAndDecryptVault().then(() => renderList()); if (popup_nav === "generator") {
showView("generator");
initGenerator();
// Still load vault data in background so the Vault tab is ready.
fetchAndDecryptVault().then(() => {});
// Wire event listeners below, then return early from vault-specific setup.
} else {
showView("vault");
await checkPendingSave();
if (_items.length) {
renderList();
fetchAndDecryptVault().then(() => renderList());
} else {
await fetchAndDecryptVault();
renderList();
}
}
} else { } else {
await fetchAndDecryptVault(); showView("vault");
renderList(); await checkPendingSave();
if (_items.length) {
renderList();
fetchAndDecryptVault().then(() => renderList());
} else {
await fetchAndDecryptVault();
renderList();
}
} }
} else if (sessionState === "unlock") { } else if (sessionState === "unlock") {
showView("unlock"); showView("unlock");