feat(ext/content): closed Shadow DOM + textContent for capture prompt

Previously the capture prompt was a normal <div> appended to document.body
with innerHTML assembly. Any page script could find it via
document.querySelector('#relicario-capture-prompt') and either scrape
values or rewrite the buttons — and the innerHTML pattern meant hostname
interpolation was a latent XSS path (escapeForHtml helped but one mistake
would break it).

- Add content/shadow.ts — createShadowHost() with mode: 'closed', host.style.all = 'initial'.
- Rewrite capture.ts to mount inside the shadow root, build DOM via
  createElement + textContent only, never innerHTML.
- Drop the `url` field from check_credential / blacklist_site — the router
  now derives origin from sender.tab.url (Slice 3 contract).
- Update add_entry / update_entry calls to add_item / update_item with the
  new typed Item + LoginCore shape.
- Swap RelicarioSettings → DeviceSettings.
- Remove @ts-nocheck — the file type-checks clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
adlee-was-taken
2026-04-20 20:35:36 -04:00
parent fbb64729ce
commit 8cc1e777be
2 changed files with 159 additions and 94 deletions

View File

@@ -1,16 +1,22 @@
// @ts-nocheck — transitional: downstream files updated in Slice 6 (item-* rewrites) / Slice 4 (vitest setup) / Slice 5 (content + setup rewires)
/// Credential capture module. /// Credential capture module.
/// ///
/// Detects login form submissions and prompts the user to save or update /// Detects login form submissions and prompts the user to save or update
/// credentials in the vault. Supports bar and toast prompt styles. /// credentials in the vault. Supports bar and toast prompt styles.
///
/// The prompt renders inside a closed Shadow DOM so the host page cannot
/// read overlay contents via document.querySelector or rewrite them via
/// insertAdjacentHTML. All caller-supplied strings (hostname, username)
/// are applied via textContent, never innerHTML.
import type { Request, Response } from '../shared/messages'; import type { Request, Response } from '../shared/messages';
import type { RelicarioSettings } from '../shared/types'; import type { DeviceSettings, Item, LoginCore } from '../shared/types';
import { createShadowHost, type ShadowSurface } from './shadow';
// --- State --- // --- State ---
const hookedForms = new WeakSet<HTMLFormElement>(); const hookedForms = new WeakSet<HTMLFormElement>();
const hookedButtons = new WeakSet<HTMLElement>(); const hookedButtons = new WeakSet<HTMLElement>();
let currentPrompt: ShadowSurface | null = null;
// --- Messaging --- // --- Messaging ---
@@ -74,11 +80,10 @@ async function onFormSubmit(pwField: HTMLInputElement): Promise<void> {
if (!password) return; if (!password) return;
const username = findUsernameValue(pwField); const username = findUsernameValue(pwField);
const url = window.location.href;
// Note: `url` is NOT sent — router derives origin from sender.tab.url.
const resp = await sendMessage({ const resp = await sendMessage({
type: 'check_credential', type: 'check_credential',
url,
username, username,
password, password,
}); });
@@ -90,58 +95,64 @@ async function onFormSubmit(pwField: HTMLInputElement): Promise<void> {
// Fetch settings for prompt style // Fetch settings for prompt style
const settingsResp = await sendMessage({ type: 'get_settings' }); const settingsResp = await sendMessage({ type: 'get_settings' });
const settings: RelicarioSettings = settingsResp.ok const defaults: DeviceSettings = { captureEnabled: true, captureStyle: 'bar' };
? (settingsResp.data as { settings: RelicarioSettings }).settings const settings: DeviceSettings = settingsResp.ok
: { captureEnabled: true, captureStyle: 'bar' }; ? ((settingsResp.data as { settings: DeviceSettings }).settings ?? defaults)
: defaults;
showPrompt(settings.captureStyle, data.action, url, username, password, data.entryId); showPrompt(settings.captureStyle, data.action, username, password, data.entryId);
} }
// --- Prompt UI --- // --- Prompt UI ---
function removeExistingPrompt(): void { function removeExistingPrompt(): void {
const existing = document.getElementById('relicario-capture-prompt'); if (currentPrompt) {
if (existing) existing.remove(); currentPrompt.destroy();
currentPrompt = null;
}
} }
function showPrompt( function showPrompt(
style: 'bar' | 'toast', style: 'bar' | 'toast',
action: string, action: string,
url: string,
username: string, username: string,
password: string, password: string,
entryId?: string, entryId?: string,
): void { ): void {
removeExistingPrompt(); removeExistingPrompt();
let hostname: string; const hostname = (() => {
try { try { return new URL(window.location.href).hostname; } catch { return window.location.href; }
hostname = new URL(url).hostname; })();
} catch { const url = window.location.href;
hostname = url;
const surface = createShadowHost();
currentPrompt = surface;
const { host, root } = surface;
// Position the host on the page; all further styling lives inside the
// shadow root so the page's CSS can't reach us.
const baseHostStyles = 'z-index: 2147483647; position: fixed;';
if (style === 'bar') {
host.style.cssText = `${baseHostStyles} top:0; left:0; right:0;`;
} else {
host.style.cssText = `${baseHostStyles} bottom:16px; right:16px;`;
} }
const container = document.createElement('div'); // --- Build prompt DOM via createElement / textContent only ---
container.id = 'relicario-capture-prompt';
// Common styles const container = document.createElement('div');
const baseStyles = [ const containerBase = [
'font-family: "SF Mono", "Fira Code", "Cascadia Code", monospace', 'font-family: "SF Mono", "Fira Code", "Cascadia Code", monospace',
'font-size: 13px', 'font-size: 13px',
'color: #c9d1d9', 'color: #c9d1d9',
'background: #161b22', 'background: #161b22',
'z-index: 2147483647',
'box-sizing: border-box', 'box-sizing: border-box',
'line-height: 1.4', 'line-height: 1.4',
]; ];
if (style === 'bar') { if (style === 'bar') {
container.style.cssText = [ container.style.cssText = [
...baseStyles, ...containerBase,
'position: fixed',
'top: 0',
'left: 0',
'right: 0',
'padding: 10px 16px', 'padding: 10px 16px',
'display: flex', 'display: flex',
'align-items: center', 'align-items: center',
@@ -153,10 +164,7 @@ function showPrompt(
].join('; '); ].join('; ');
} else { } else {
container.style.cssText = [ container.style.cssText = [
...baseStyles, ...containerBase,
'position: fixed',
'bottom: 16px',
'right: 16px',
'padding: 12px 16px', 'padding: 12px 16px',
'border-radius: 4px', 'border-radius: 4px',
'border: 1px solid #30363d', 'border: 1px solid #30363d',
@@ -168,30 +176,46 @@ function showPrompt(
} }
const actionLabel = action === 'update' ? 'Update' : 'Save'; const actionLabel = action === 'update' ? 'Update' : 'Save';
const displayUser = username ? ` (${username})` : '';
container.innerHTML = ` // Message span: "<actionLabel> login for <hostname>(<username>)?"
<span style="flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;"> const msgSpan = document.createElement('span');
${actionLabel} login for <strong style="color:#58a6ff">${escapeForHtml(hostname)}</strong>${escapeForHtml(displayUser)}? msgSpan.style.cssText = 'flex:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;';
</span> msgSpan.appendChild(document.createTextNode(`${actionLabel} login for `));
<button id="relicario-save-btn" style=" const hostStrong = document.createElement('strong');
background:#1f6feb; color:#fff; border:none; padding:5px 14px; hostStrong.style.color = '#58a6ff';
border-radius:3px; cursor:pointer; font-family:inherit; font-size:12px; hostStrong.textContent = hostname;
white-space:nowrap; msgSpan.appendChild(hostStrong);
">${actionLabel}</button> if (username) {
<button id="relicario-never-btn" style=" msgSpan.appendChild(document.createTextNode(` (${username})`));
background:transparent; color:#8b949e; border:1px solid #30363d; }
padding:5px 10px; border-radius:3px; cursor:pointer; msgSpan.appendChild(document.createTextNode('?'));
font-family:inherit; font-size:12px; white-space:nowrap;
">Never</button>
<button id="relicario-close-btn" style="
background:transparent; color:#8b949e; border:none;
cursor:pointer; font-size:16px; padding:2px 6px;
font-family:inherit; line-height:1;
">\u2715</button>
`;
document.body.appendChild(container); const saveBtn = document.createElement('button');
saveBtn.textContent = actionLabel;
saveBtn.style.cssText = [
'background:#1f6feb', 'color:#fff', 'border:none', 'padding:5px 14px',
'border-radius:3px', 'cursor:pointer', 'font-family:inherit', 'font-size:12px',
'white-space:nowrap',
].join('; ');
const neverBtn = document.createElement('button');
neverBtn.textContent = 'Never';
neverBtn.style.cssText = [
'background:transparent', 'color:#8b949e', 'border:1px solid #30363d',
'padding:5px 10px', 'border-radius:3px', 'cursor:pointer',
'font-family:inherit', 'font-size:12px', 'white-space:nowrap',
].join('; ');
const closeBtn = document.createElement('button');
closeBtn.textContent = '✕';
closeBtn.style.cssText = [
'background:transparent', 'color:#8b949e', 'border:none',
'cursor:pointer', 'font-size:16px', 'padding:2px 6px',
'font-family:inherit', 'line-height:1',
].join('; ');
container.append(msgSpan, saveBtn, neverBtn, closeBtn);
root.appendChild(container);
// Animate in // Animate in
requestAnimationFrame(() => { requestAnimationFrame(() => {
@@ -213,67 +237,71 @@ function showPrompt(
}; };
// Save button // Save button
container.querySelector('#relicario-save-btn')?.addEventListener('click', async () => { saveBtn.addEventListener('click', async () => {
clearAutoDismiss(); clearAutoDismiss();
const now = new Date().toISOString(); const now = Math.floor(Date.now() / 1000);
const loginCore: LoginCore & { type: 'login' } = {
type: 'login',
username,
password,
url,
};
if (action === 'update' && entryId) { if (action === 'update' && entryId) {
await sendMessage({ // For update we need a valid Item — fetch the existing one, merge the
type: 'update_entry', // updated login fields, and write it back. The router's update_item
id: entryId, // expects a full Item. We fall back to a minimal item if fetch fails.
entry: { const getResp = await sendMessage({ type: 'get_item', id: entryId });
name: hostname, if (getResp.ok) {
url, const existing = (getResp.data as { item: Item }).item;
username, const updated: Item = {
password, ...existing,
created_at: now, title: existing.title || hostname,
updated_at: now, modified: now,
}, core: { ...existing.core, ...loginCore },
}); };
await sendMessage({ type: 'update_item', id: entryId, item: updated });
}
} else { } else {
await sendMessage({ // New item — SW will assign the id; we just pass an empty string.
type: 'add_entry', const item: Item = {
entry: { id: '',
name: hostname, title: hostname,
url, type: 'login',
username, tags: [],
password, favorite: false,
created_at: now, created: now,
updated_at: now, modified: now,
}, core: loginCore,
}); sections: [],
attachments: [],
field_history: {},
};
await sendMessage({ type: 'add_item', item });
} }
// Show confirmation // Show confirmation
const span = container.querySelector('span'); msgSpan.textContent = '✓ Saved';
if (span) span.textContent = '\u2713 Saved'; saveBtn.style.display = 'none';
const saveBtn = container.querySelector('#relicario-save-btn') as HTMLElement | null; neverBtn.style.display = 'none';
const neverBtn = container.querySelector('#relicario-never-btn') as HTMLElement | null;
if (saveBtn) saveBtn.style.display = 'none';
if (neverBtn) neverBtn.style.display = 'none';
setTimeout(() => removeExistingPrompt(), 1500); setTimeout(() => removeExistingPrompt(), 1500);
}); });
// Never button // Never button: router derives hostname from sender.tab.url (no `hostname` field)
container.querySelector('#relicario-never-btn')?.addEventListener('click', async () => { neverBtn.addEventListener('click', async () => {
clearAutoDismiss(); clearAutoDismiss();
await sendMessage({ type: 'blacklist_site', hostname }); await sendMessage({ type: 'blacklist_site' });
removeExistingPrompt(); removeExistingPrompt();
}); });
// Close button // Close button
container.querySelector('#relicario-close-btn')?.addEventListener('click', () => { closeBtn.addEventListener('click', () => {
clearAutoDismiss(); clearAutoDismiss();
removeExistingPrompt(); removeExistingPrompt();
}); });
} }
function escapeForHtml(str: string): string {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// --- Form hooking --- // --- Form hooking ---
export function hookForms(): void { export function hookForms(): void {

View File

@@ -0,0 +1,37 @@
/// Closed Shadow DOM host helper.
///
/// All in-page UI (capture prompt, autofill icon, candidate picker, TOFU
/// banner) mounts into a closed-mode ShadowRoot so the host page cannot
/// read or mutate the overlay via document.querySelector / DOM APIs. The
/// returned ShadowSurface provides {host, root, destroy} for callers that
/// want to populate the root, position the host, and tear everything down.
export interface ShadowSurface {
/// The host <div> that's appended to document.body. Style/position this
/// from the caller (position: fixed, z-index, transform, etc.).
host: HTMLDivElement;
/// Closed-mode ShadowRoot. Populate via textContent / appendChild —
/// NEVER innerHTML, NEVER insertAdjacentHTML. Treat any caller-supplied
/// string (hostname, username) as untrusted.
root: ShadowRoot;
/// Remove the host from the DOM and drop all references.
destroy: () => void;
}
/// Create a closed Shadow DOM host attached to document.body.
///
/// Callers are responsible for positioning `host` and filling `root`.
export function createShadowHost(): ShadowSurface {
const host = document.createElement('div');
// Reset host-side styling so page CSS cannot leak in/out via inheritance.
host.style.all = 'initial';
const root = host.attachShadow({ mode: 'closed' });
document.body.appendChild(host);
return {
host,
root,
destroy: () => {
host.remove();
},
};
}