save.ts

8.6 KB · raw

1import { detectHomograph, extractDomain } from "../shared/domain";2import { ACCENT_COLORS } from "../shared/types";3import type { SaveCredentialCheckResult } from "../shared/types";45let accentHex = "#E8956D";6chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (resp: { ok: boolean; data?: { accentColor?: string } } | undefined) => {7  const name = resp?.data?.accentColor ?? "peach";8  accentHex = ACCENT_COLORS.find(c => c.name === name)?.hex ?? "#E8956D";9});1011let currentBanner: (() => void) | null = null;1213interface DetectedCredential {14  username: string;15  password: string;16  url: string;17  domain: string;18}1920async function checkCredential(credential: DetectedCredential): Promise<SaveCredentialCheckResult | null> {21  let timeout: ReturnType<typeof setTimeout> | undefined;22  try {23    const response: unknown = await Promise.race([24      chrome.runtime.sendMessage({ type: "CHECK_SAVE_CREDENTIAL", payload: { username: credential.username, password: credential.password } }),25      new Promise<null>(resolve => { timeout = setTimeout(() => resolve(null), 5_000); }),26    ]);27    if (!response || typeof response !== "object" || !("ok" in response) || response.ok !== true || !("data" in response)) return null;28    const data = response.data;29    if (!data || typeof data !== "object" || !("status" in data)) return null;30    if ((data.status === "new" || data.status === "same" || data.status === "ambiguous") && Object.keys(data).length === 1) return { status: data.status };31    if (data.status === "changed" && Object.keys(data).length === 2 && "id" in data && typeof data.id === "string" && data.id) return { status: "changed", id: data.id };32    return null;33  } catch {34    return null;35  } finally {36    clearTimeout(timeout);37  }38}3940async function saveEntry(41  username: string,42  password: string,43  url: string44): Promise<void> {45  await chrome.runtime.sendMessage({46    type: "ADD_ENTRY",47    payload: { title: new URL(url).hostname, username, password, url },48  });49}5051async function updateEntryPassword(52  id: string,53  password: string54): Promise<void> {55  await chrome.runtime.sendMessage({56    type: "UPDATE_ENTRY",57    payload: { id, patch: { password } },58  });59}6061function showBanner(62  credential: DetectedCredential,63  existingId: string | null,64  onPrimaryAction: () => Promise<void>,65  onDismiss: () => void66): () => void {67  const host = document.createElement("div");68  host.style.cssText = `69    position: fixed; top: 16px; right: 16px; z-index: 2147483647;70    font-family: Inter, sans-serif;71  `;72  host.style.setProperty("--peach-accent", accentHex);73  const shadow = host.attachShadow({ mode: "closed" });7475  const isUpdate = existingId !== null;76  const title = isUpdate ? "Update password?" : "Save password?";77  const subtitle = isUpdate78    ? `Update password for ${credential.domain}?`79    : `Save password for ${credential.domain}?`;8081  const style = shadow.appendChild(document.createElement("style"));82  style.textContent = `83    :host { all: initial; }84    .banner {85      background:86        radial-gradient(120% 80% at 0% 0%, color-mix(in srgb, var(--peach-accent) 10%, transparent) 0%, transparent 65%),87        radial-gradient(85% 100% at 100% 100%, color-mix(in srgb, var(--peach-accent) 6%, transparent) 0%, transparent 70%),88        #0C0A06;89      border: 1px solid rgba(240,232,216,0.10);90      border-radius: 14px;91      padding: 14px 16px;92      box-shadow: 0 18px 48px rgba(0,0,0,0.45);93      width: 296px;94      font-family: Inter, sans-serif;95    }96    .banner-title {97      font-family: "Cormorant Garamond", Georgia, serif;98      font-size: 22px;99      font-style: italic;100      line-height: 0.95;101      color: #F0E8D8;102      margin: 0 0 6px;103    }104    .banner-sub {105      font-family: "IBM Plex Mono", "SFMono-Regular", monospace;106      font-size: 10px;107      letter-spacing: 0.08em;108      color: rgba(240,232,216,0.42);109      margin: 0 0 12px;110    }111    .banner-warn {112      font-family: "IBM Plex Mono", "SFMono-Regular", monospace;113      font-size: 10px;114      line-height: 1.4;115      color: #C8A840;116      margin: 0 0 12px;117    }118    .banner-actions {119      display: flex;120      gap: 8px;121    }122    .btn-save {123      flex: 1;124      background: var(--peach-accent);125      color: rgba(0,0,0,0.75);126      border: none;127      border-radius: 10px;128      padding: 8px 12px;129      font-size: 10px;130      letter-spacing: 0.08em;131      text-transform: uppercase;132      font-weight: 500;133      cursor: pointer;134      font-family: Inter, sans-serif;135    }136    .btn-save:hover { opacity: 0.88; }137    .btn-dismiss {138      flex: 1;139      background: rgba(240,232,216,0.06);140      color: rgba(240,232,216,0.6);141      border: 1px solid rgba(240,232,216,0.1);142      border-radius: 10px;143      padding: 8px 12px;144      font-size: 10px;145      letter-spacing: 0.08em;146      text-transform: uppercase;147      cursor: pointer;148      font-family: Inter, sans-serif;149    }150    .btn-dismiss:hover { background: rgba(240,232,216,0.1); }151  `;152153  const banner = shadow.appendChild(document.createElement("div"));154  banner.className = "banner";155156  const titleEl = banner.appendChild(document.createElement("p"));157  titleEl.className = "banner-title";158  titleEl.textContent = title;159160  const subEl = banner.appendChild(document.createElement("p"));161  subEl.className = "banner-sub";162  subEl.textContent = subtitle;163164  // UI-8 / LV-2: non-blocking homograph warning when the page's own address165  // is non-ASCII or punycode — never blocks saving.166  if (detectHomograph(location.hostname)) {167    const warnEl = banner.appendChild(document.createElement("p"));168    warnEl.className = "banner-warn";169    warnEl.textContent =170      "⚠ This site's address contains non-ASCII or punycode characters. Verify it's the site you intend.";171  }172173  const actionsEl = banner.appendChild(document.createElement("div"));174  actionsEl.className = "banner-actions";175176  const saveBtn = actionsEl.appendChild(document.createElement("button"));177  saveBtn.className = "btn-save";178  saveBtn.textContent = isUpdate ? "Update" : "Save";179180  const dismissBtn = actionsEl.appendChild(document.createElement("button"));181  dismissBtn.className = "btn-dismiss";182  dismissBtn.textContent = "Dismiss";183184  saveBtn.addEventListener("click", async () => {185    saveBtn.disabled = true;186    saveBtn.textContent = isUpdate ? "Updating..." : "Saving...";187    try {188      await onPrimaryAction();189      host.remove();190    } finally {191      saveBtn.disabled = false;192      saveBtn.textContent = isUpdate ? "Update" : "Save";193    }194  });195196  dismissBtn.addEventListener("click", () => {197    onDismiss();198    host.remove();199  });200201  document.body.appendChild(host);202203  return () => {204    host.remove();205  };206}207208async function checkForNewCredentials(209  credential: DetectedCredential210): Promise<void> {211  if (currentBanner) {212    currentBanner();213    currentBanner = null;214  }215216  const result = await checkCredential(credential);217  if (!result || (result.status !== "new" && result.status !== "changed") || location.href !== credential.url) return;218  const existingId = result.status === "changed" ? result.id : null;219220  currentBanner = showBanner(221    credential,222    existingId,223    async () => {224      if (existingId) {225        await updateEntryPassword(existingId, credential.password);226      } else {227        await saveEntry(credential.username, credential.password, credential.url);228      }229      currentBanner = null;230    },231    () => {232      currentBanner = null;233    }234  );235}236237export function setupSaveDetection(): void {238  // PCH-01-026 #1: removed a dead no-op URL-tracking MutationObserver that ran239  // on every DOM mutation only to update a `lastUrl` variable nothing consumed.240  document.addEventListener("submit", async (e) => {241    const form = e.target as HTMLFormElement;242    if (!form) return;243244    const inputs = Array.from(form.querySelectorAll("input"));245    let username = "";246    let password = "";247248    for (const input of inputs) {249      const type = input.type.toLowerCase();250      const name = (input.name + input.id + input.autocomplete).toLowerCase();251252      if (type === "password" && input.value) {253        password = input.value;254      } else if (255        !username &&256        (type === "text" || type === "email" || type === "tel") &&257        (name.includes("user") ||258          name.includes("email") ||259          name.includes("login") ||260          name.includes("name") ||261          input.autocomplete === "username" ||262          input.autocomplete === "email")263      ) {264        username = input.value;265      }266    }267268    if (!password) return;269270    const domain = extractDomain(location.href) ?? location.hostname;271    const credential: DetectedCredential = {272      username,273      password,274      url: location.href,275      domain,276    };277278    await checkForNewCredentials(credential);279  });280}