Repository Public
1// URL matching for credential filling: Public Suffix List (tldts), IDN handling and lookalike warnings.2import { parse } from "tldts";3import type { Item, ItemUrl } from "./items.ts";45export interface Origin { scheme: string; host: string; port: string; domain: string | null; display: string; mixedScript: boolean }67const CONFUSABLE: Record<string, string> = {8 "0": "o", "1": "l", "3": "e", "5": "s", "а": "a", "е": "e", "о": "o", "р": "p", "с": "c", "х": "x", "у": "y", "і": "i", "ѕ": "s", "ԁ": "d",9 "ɡ": "g", "ⅼ": "l", "ı": "i", "ο": "o", "α": "a", "ν": "v", "τ": "t", "κ": "k", "ρ": "p", "ε": "e", "ι": "i", "ј": "j", "һ": "h", "ԛ": "q", "ԝ": "w",10};1112function scripts(s: string): Set<string> {13 const out = new Set<string>();14 for (const ch of s) {15 if (/\p{Script=Latin}/u.test(ch)) out.add("Latin");16 else if (/\p{Script=Cyrillic}/u.test(ch)) out.add("Cyrillic");17 else if (/\p{Script=Greek}/u.test(ch)) out.add("Greek");18 else if (/\p{L}/u.test(ch)) out.add("Other");19 }20 return out;21}2223/** Parses a URL (or bare host) the way a browser would; the host is the ASCII (punycode) form. */24export function parseOrigin(input: string): Origin | null {25 let s = input.trim();26 if (!s) return null;27 if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = "https://" + s;28 let u: URL;29 try { u = new URL(s); } catch { return null; }30 if (u.protocol !== "https:" && u.protocol !== "http:") return null;31 if (u.username || u.password) return null; // "https://bank.com@evil.example" style tricks are never matched32 const host = u.hostname.toLowerCase().replace(/\.$/, "");33 const info = parse(host, { allowPrivateDomains: true });34 const unicode = host.split(".").map((l) => (l.startsWith("xn--") ? decodePuny(l.slice(4)) : l)).join(".");35 const mixed = unicode.split(".").some((label) => scripts(label).size > 1);36 return {37 scheme: u.protocol.slice(0, -1), host, port: u.port, domain: info.isIp ? host : info.domain ?? (host.includes(".") ? null : host),38 display: mixed || unicode === host ? host : `${unicode} (${host})`, mixedScript: mixed,39 };40}4142function decodePuny(input: string): string {43 // RFC 3492 decoder (display only; matching is always done on the ASCII form)44 const base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700;45 let n = 128, i = 0, bias = 72;46 const out: number[] = [];47 const d = input.lastIndexOf("-");48 for (let j = 0; j < Math.max(d, 0); j++) out.push(input.charCodeAt(j));49 for (let idx = d > 0 ? d + 1 : 0; idx < input.length;) {50 const oldi = i;51 for (let w = 1, k = base; ; k += base) {52 if (idx >= input.length) return "xn--" + input;53 const c = input.charCodeAt(idx++);54 const digit = c >= 48 && c < 58 ? c - 22 : c >= 65 && c < 91 ? c - 65 : c >= 97 && c < 123 ? c - 97 : base;55 if (digit >= base) return "xn--" + input;56 i += digit * w;57 const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;58 if (digit < t) break;59 w *= base - t;60 }61 const len = out.length + 1;62 let delta = oldi === 0 ? Math.floor((i - oldi) / damp) : (i - oldi) >> 1;63 delta += Math.floor(delta / len);64 let k = 0;65 for (; delta > ((base - tMin) * tMax) >> 1; k += base) delta = Math.floor(delta / (base - tMin));66 bias = k + Math.floor(((base - tMin + 1) * delta) / (delta + skew));67 n += Math.floor(i / len); i %= len;68 out.splice(i++, 0, n);69 }70 if (out.some((cp) => !Number.isInteger(cp) || cp < 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) || cp < 0x20)) return "xn--" + input; // invalid label: show it raw71 return String.fromCodePoint(...out);72}7374/** Skeleton used to detect lookalikes: confusable folding on the Unicode form, diacritics stripped. */75export function skeleton(domain: string): string {76 const uni = domain.split(".").map((l) => (l.startsWith("xn--") ? decodePuny(l.slice(4)) : l)).join(".");77 return [...uni.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase()].map((c) => CONFUSABLE[c] ?? c).join("").replace(/rn/g, "m").replace(/vv/g, "w");78}7980function editDistance1(a: string, b: string): boolean {81 if (a === b || Math.abs(a.length - b.length) > 1) return false;82 let i = 0, j = 0, edits = 0;83 while (i < a.length && j < b.length) {84 if (a[i] === b[j]) { i++; j++; continue; }85 if (++edits > 1) return false;86 if (a.length > b.length) i++; else if (a.length < b.length) j++; else { i++; j++; }87 }88 return edits + (a.length - i) + (b.length - j) <= 1;89}9091export type MatchResult = "match" | "insecure" | "no";9293/** Does a saved URL rule allow filling on `page`? Never matches across schemes downward (saved https → page http). */94export function matchUrl(saved: ItemUrl, pageUrl: string): MatchResult {95 if (saved.match === "never") return "no";96 const s = parseOrigin(saved.url), p = parseOrigin(pageUrl);97 if (!s || !p) return "no";98 let ok: boolean;99 if (saved.match === "exact") {100 try { const a = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(saved.url) ? saved.url : "https://" + saved.url), b = new URL(pageUrl); ok = a.origin === b.origin && a.pathname.replace(/\/$/, "") === b.pathname.replace(/\/$/, ""); } catch { ok = false; }101 } else if (saved.match === "host") ok = s.host === p.host && s.port === p.port;102 else ok = s.domain !== null && s.domain === p.domain;103 if (!ok) return "no";104 if (p.scheme === "http" && !(p.host === "localhost" || p.host === "127.0.0.1" || p.host === "[::1]")) return s.scheme === "http" ? "insecure" : "no";105 return "match";106}107108export interface FillCandidate<T> { ref: T; item: Item; insecure: boolean }109110export function candidatesFor<T>(items: { ref: T; item: Item }[], pageUrl: string): FillCandidate<T>[] {111 const out: FillCandidate<T>[] = [];112 for (const it of items) {113 if (it.item.type !== "login" || it.item.trashedAt) continue;114 const results = it.item.urls.map((u) => matchUrl(u, pageUrl));115 if (results.includes("match")) out.push({ ...it, insecure: false });116 else if (results.includes("insecure")) out.push({ ...it, insecure: true });117 }118 return out;119}120121export interface LookalikeWarning { page: string; resembles: string; reason: "confusable" | "near" | "mixed-script" }122123/** Warns when the page's domain is not a saved domain but looks like one. */124export function lookalike(pageUrl: string, savedDomains: Iterable<string>): LookalikeWarning | null {125 const p = parseOrigin(pageUrl);126 if (!p?.domain) return null;127 const saved = new Set(savedDomains);128 if (saved.has(p.domain)) return null;129 const sk = skeleton(p.domain);130 for (const d of saved) {131 if (skeleton(d) === sk) return { page: p.domain, resembles: d, reason: "confusable" };132 }133 for (const d of saved) {134 const a = p.domain.split(".")[0]!, b = d.split(".")[0]!;135 if (b.length >= 5 && (editDistance1(a, b) || (a === b && p.domain !== d))) return { page: p.domain, resembles: d, reason: "near" };136 }137 if (p.mixedScript) return { page: p.domain, resembles: "", reason: "mixed-script" };138 return null;139}140141export function savedDomains(items: Item[]): Set<string> {142 const out = new Set<string>();143 for (const it of items) for (const u of it.urls) { const o = parseOrigin(u.url); if (o?.domain) out.add(o.domain); }144 return out;145}146