mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
fix browser session origin and cleanup behavior
This commit is contained in:
parent
43610220bd
commit
ff5dc06074
7 changed files with 179 additions and 70 deletions
|
|
@ -143,6 +143,19 @@ impl BrowserSession {
|
|||
}
|
||||
}
|
||||
|
||||
/// localStorage belongs to an exact origin, including scheme and port.
|
||||
/// Media shorthands have no page origin to seed.
|
||||
pub fn storage_applies_to(&self, locator: &str) -> bool {
|
||||
let Ok(session_url) = reqwest::Url::parse(&self.url) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(target_url) = reqwest::Url::parse(locator) else {
|
||||
return false;
|
||||
};
|
||||
matches!(target_url.scheme(), "http" | "https")
|
||||
&& session_url.origin() == target_url.origin()
|
||||
}
|
||||
|
||||
/// Returns the ASCII-serialized origin of `url`, e.g. `"https://www.example.com"`.
|
||||
pub fn storage_origin(&self) -> Option<String> {
|
||||
reqwest::Url::parse(&self.url)
|
||||
|
|
@ -207,6 +220,15 @@ mod tests {
|
|||
assert!(s.applies_to("https://www.example.com/b"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn storage_requires_the_same_origin_not_just_host() {
|
||||
let s = make_session("https://example.com:8443/a");
|
||||
assert!(s.storage_applies_to("https://example.com:8443/b"));
|
||||
assert!(!s.storage_applies_to("https://example.com/b"));
|
||||
assert!(!s.storage_applies_to("http://example.com:8443/b"));
|
||||
assert!(!s.storage_applies_to("tweet:123456789012345678"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applies_to_different_subdomain_is_false() {
|
||||
let s = make_session("https://www.example.com/a");
|
||||
|
|
|
|||
|
|
@ -638,23 +638,21 @@ fn save_with(
|
|||
.collect();
|
||||
let browser_args = format!("[{}]", quoted.join(","));
|
||||
|
||||
// Write cookie file (secrets must never appear in process args).
|
||||
let cookie_file: Option<PathBuf> = if !cookies.is_empty() {
|
||||
let cf = temp_dir.join("cookies.json");
|
||||
let domain = domain_from_url(url);
|
||||
write_json_cookie_file(cookies, &domain, url, &cf)
|
||||
.context("failed to write single-file cookie file")?;
|
||||
Some(cf)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Write localStorage seed script (secrets must never appear in process args).
|
||||
// It runs as the first --browser-script so localStorage is set before page
|
||||
// scripts execute.
|
||||
let storage_script_file: Option<PathBuf> = match &local_storage {
|
||||
Some(seed) if !seed.items.is_empty() => {
|
||||
let sf = temp_dir.join("sf-local-storage.js");
|
||||
// Construct both secret paths before writing either one. Every fallible
|
||||
// write and the subprocess run stay inside this scope so cleanup also runs
|
||||
// when the second write fails after the first file has been created.
|
||||
let cookie_file = (!cookies.is_empty()).then(|| temp_dir.join("cookies.json"));
|
||||
let storage_script_file = local_storage
|
||||
.as_ref()
|
||||
.filter(|seed| !seed.items.is_empty())
|
||||
.map(|_| temp_dir.join("sf-local-storage.js"));
|
||||
let sf_result = (|| -> Result<std::process::Output> {
|
||||
if let Some(cf) = &cookie_file {
|
||||
let domain = domain_from_url(url);
|
||||
write_json_cookie_file(cookies, &domain, url, cf)
|
||||
.context("failed to write single-file cookie file")?;
|
||||
}
|
||||
if let (Some(sf), Some(seed)) = (&storage_script_file, &local_storage) {
|
||||
let script = local_storage_seed_script(seed);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
|
|
@ -664,45 +662,42 @@ fn save_with(
|
|||
.create(true)
|
||||
.truncate(true)
|
||||
.mode(0o600)
|
||||
.open(&sf)
|
||||
.and_then(|mut f| { use std::io::Write; f.write_all(script.as_bytes()) })
|
||||
.open(sf)
|
||||
.and_then(|mut f| {
|
||||
use std::io::Write;
|
||||
f.write_all(script.as_bytes())
|
||||
})
|
||||
.context("failed to write localStorage seed script")?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
std::fs::write(&sf, &script).context("failed to write localStorage seed script")?;
|
||||
Some(sf)
|
||||
std::fs::write(sf, &script).context("failed to write localStorage seed script")?;
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// localStorage seed runs FIRST so it executes before any page scripts.
|
||||
let mut scripts: Vec<&Path> = Vec::new();
|
||||
if let Some(sf) = &storage_script_file {
|
||||
scripts.push(sf.as_path());
|
||||
// localStorage seed runs FIRST so it executes before any page scripts.
|
||||
let mut scripts: Vec<&Path> = Vec::new();
|
||||
if let Some(sf) = &storage_script_file {
|
||||
scripts.push(sf.as_path());
|
||||
}
|
||||
scripts.push(strip_scripts_path.as_path());
|
||||
scripts.extend(extra_browser_scripts.iter().map(|p| p.as_path()));
|
||||
run_single_file_standalone(
|
||||
url,
|
||||
&out_file,
|
||||
single_file,
|
||||
chrome,
|
||||
&browser_args,
|
||||
&scripts,
|
||||
cookie_file.as_deref(),
|
||||
)
|
||||
.with_context(|| format!("failed to spawn single-file ({single_file})"))
|
||||
})();
|
||||
for path in [cookie_file.as_ref(), storage_script_file.as_ref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
scripts.push(strip_scripts_path.as_path());
|
||||
scripts.extend(extra_browser_scripts.iter().map(|p| p.as_path()));
|
||||
|
||||
// Run single-file; always delete secret files afterwards, even on spawn failure.
|
||||
let sf_result = run_single_file_standalone(
|
||||
url,
|
||||
&out_file,
|
||||
single_file,
|
||||
chrome,
|
||||
&browser_args,
|
||||
&scripts,
|
||||
cookie_file.as_deref(),
|
||||
);
|
||||
// Delete cookie file and localStorage seed unconditionally — including on
|
||||
// failure — so secrets are never left in store/temp when the capture fails.
|
||||
if let Some(cf) = &cookie_file {
|
||||
let _ = std::fs::remove_file(cf);
|
||||
}
|
||||
if let Some(sf) = &storage_script_file {
|
||||
let _ = std::fs::remove_file(sf);
|
||||
}
|
||||
let sf_output = sf_result
|
||||
.with_context(|| format!("failed to spawn single-file ({single_file})"))?;
|
||||
let sf_output = sf_result?;
|
||||
|
||||
if !sf_output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&sf_output.stderr);
|
||||
|
|
@ -1188,6 +1183,36 @@ mod tests {
|
|||
assert!(!storage_path.exists(), "sf-local-storage.js was not deleted: {}", storage_path.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_with_storage_write_failure_removes_cookie_file() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let temp_dir = tmp.path().join("temp/test-ts");
|
||||
std::fs::create_dir_all(temp_dir.join("sf-local-storage.js")).unwrap();
|
||||
let mut cookies = HashMap::new();
|
||||
cookies.insert("session".to_string(), "secret".to_string());
|
||||
let mut items = HashMap::new();
|
||||
items.insert("pref".to_string(), "dark".to_string());
|
||||
let result = save_with(
|
||||
"https://example.com",
|
||||
tmp.path(),
|
||||
"test-ts",
|
||||
"/nonexistent/single-file",
|
||||
"chromium",
|
||||
&cookies,
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
Some(LocalStorageSeed {
|
||||
origin: "https://example.com",
|
||||
items: &items,
|
||||
}),
|
||||
);
|
||||
assert!(result.unwrap_err().to_string().contains("localStorage seed script"));
|
||||
assert!(!temp_dir.join("cookies.json").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_with_both_extensions_uses_comma_joined_flags() {
|
||||
use std::path::Path;
|
||||
|
|
|
|||
|
|
@ -1747,6 +1747,11 @@ async fn capture_handler(
|
|||
"browser_session.url must be on the same site as the locator",
|
||||
));
|
||||
}
|
||||
if !session.local_storage.is_empty() && !session.storage_applies_to(body.locator.trim()) {
|
||||
return Err(ApiError::bad_request(
|
||||
"browser_session.local_storage requires the same origin as the locator",
|
||||
));
|
||||
}
|
||||
}
|
||||
// per_item_quality semantics (enforced in capture.rs):
|
||||
// - Absent or empty map: all playlist items are downloaded; quality is the
|
||||
|
|
@ -6497,6 +6502,41 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capture_browser_session_storage_requires_same_origin() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let (registry, _, auth_path) = make_test_registry(&dir);
|
||||
let session_cookie = make_test_session(&auth_path);
|
||||
let body = serde_json::json!({
|
||||
"locator": "https://example.com:8443/a",
|
||||
"browser_session": {
|
||||
"url": "https://example.com/a",
|
||||
"cookies": { "session": "abc" },
|
||||
"local_storage": { "pref": "dark" }
|
||||
}
|
||||
});
|
||||
let response = app(registry, auth_path)
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/api/archives/test/captures")
|
||||
.header("content-type", "application/json")
|
||||
.header("cookie", &session_cookie)
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||
let resp_bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let json: serde_json::Value = serde_json::from_slice(&resp_bytes).unwrap();
|
||||
assert!(json["error"]
|
||||
.as_str()
|
||||
.is_some_and(|e| e.contains("same origin")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capture_browser_session_invalid_cookie_name_is_rejected() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -44,13 +44,11 @@ export function toRows(list, keyField) {
|
|||
* @returns {Object<string,string>}
|
||||
*/
|
||||
export function rowsToMap(rows) {
|
||||
const map = {}
|
||||
for (const row of rows) {
|
||||
if (row.included && row.name !== '') {
|
||||
map[row.name] = row.value
|
||||
}
|
||||
}
|
||||
return map
|
||||
// Object.fromEntries creates an own property for names such as "__proto__".
|
||||
// Assignment into {} silently drops that valid cookie/localStorage key.
|
||||
return Object.fromEntries(rows
|
||||
.filter(row => row.included && row.name !== '')
|
||||
.map(row => [row.name, row.value]))
|
||||
}
|
||||
|
||||
/** @param {string} s */
|
||||
|
|
|
|||
|
|
@ -31,6 +31,12 @@ describe('rowsToMap', () => {
|
|||
expect(Object.keys(map)).toEqual(['a'])
|
||||
expect(map.a).toBe('x')
|
||||
})
|
||||
|
||||
test('preserves a localStorage key named __proto__', () => {
|
||||
const map = rowsToMap([{ id: 1, name: '__proto__', value: 'saved', included: true }])
|
||||
expect(Object.keys(map)).toEqual(['__proto__'])
|
||||
expect(map.__proto__).toBe('saved')
|
||||
})
|
||||
})
|
||||
|
||||
describe('validateBrowserData', () => {
|
||||
|
|
|
|||
|
|
@ -76,6 +76,7 @@ export function BrowserDataSection({
|
|||
setBrowserData,
|
||||
effectiveUseCookies,
|
||||
includeStorage,
|
||||
storageApplicable,
|
||||
setIncludeStorage,
|
||||
browserDataError,
|
||||
}) {
|
||||
|
|
@ -131,12 +132,17 @@ export function BrowserDataSection({
|
|||
<label className="capture-ext-row" style={{ marginTop: 8 }}>
|
||||
<span className="capture-ext-label">
|
||||
<span className="capture-ext-name">Include localStorage</span>
|
||||
<span className="capture-ext-desc">Seed this site's localStorage in the archiving browser (page captures only)</span>
|
||||
<span className="capture-ext-desc">
|
||||
{storageApplicable
|
||||
? 'Seed this site\'s localStorage in the archiving browser (page captures only)'
|
||||
: 'Available only for URLs on this page\'s exact origin (scheme, host, and port)'}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={includeStorage}
|
||||
disabled={!storageApplicable}
|
||||
className={`ext-toggle ext-toggle--sm${includeStorage ? ' ext-toggle--on' : ''}`}
|
||||
onClick={() => setIncludeStorage(v => !v)}
|
||||
aria-label="Toggle localStorage for this capture"
|
||||
|
|
|
|||
|
|
@ -363,6 +363,8 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
const [browserData, setBrowserData] = useState({
|
||||
status: 'idle', cookieAccess: null, cookieRows: [], storageRows: [],
|
||||
})
|
||||
const cookieAccessRef = useRef(browserData.cookieAccess)
|
||||
cookieAccessRef.current = browserData.cookieAccess
|
||||
const [useCookies, setUseCookies] = useState(browserSession?.defaults?.cookies ?? false)
|
||||
const [includeStorage, setIncludeStorage] = useState(browserSession?.defaults?.localStorage ?? false)
|
||||
|
||||
|
|
@ -390,7 +392,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
load()
|
||||
// Re-check when tab regains focus (user may have granted access in the settings tab)
|
||||
function onVisibility() {
|
||||
if (document.visibilityState === 'visible' && browserData.cookieAccess === 'missing') {
|
||||
if (document.visibilityState === 'visible' && cookieAccessRef.current === 'missing') {
|
||||
load()
|
||||
}
|
||||
}
|
||||
|
|
@ -619,7 +621,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
|
||||
function handleArchive() {
|
||||
if (!archiveIdRef.current) return
|
||||
if (browserDataError) return
|
||||
if (browserDataError || browserDataLoading) return
|
||||
// Guard against the Enter-key shortcut in CaptureRow bypassing the
|
||||
// disabled button — uploads must be complete before archiving starts.
|
||||
if (items.some(it => it.kind === 'file' && it.uploadStatus === 'uploading')) return
|
||||
|
|
@ -641,10 +643,6 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
if (batchId) {
|
||||
batchRef.current.set(batchId, { total: toSubmit.length, archived: 0, warnings: 0, failed: 0, failedLocators: [], warningLocators: [] })
|
||||
}
|
||||
// Build browser session payload before state changes (snapshot current state).
|
||||
const sessionPayload = browserApplicable
|
||||
? buildBrowserSessionPayload({ pageUrl: browserSession.pageUrl, useCookies: effectiveUseCookies, includeStorage, cookieRows: browserData.cookieRows, storageRows: browserData.storageRows })
|
||||
: null
|
||||
// Capture all submission data before any state changes
|
||||
const submissions = toSubmit.map(it => {
|
||||
if (it.kind === 'file') {
|
||||
|
|
@ -654,9 +652,17 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
return { type: 'text', title: it.title.trim(), body: it.body, mime: it.mime }
|
||||
}
|
||||
const locator = it.locator.trim()
|
||||
const browserSessionExt = (sessionPayload && browserSession?.appliesTo(locator))
|
||||
? { browser_session: sessionPayload }
|
||||
: {}
|
||||
// Cookies are host-scoped; localStorage is scoped to the exact origin.
|
||||
const sessionPayload = browserSession?.appliesTo(locator)
|
||||
? buildBrowserSessionPayload({
|
||||
pageUrl: browserSession.pageUrl,
|
||||
useCookies: effectiveUseCookies,
|
||||
includeStorage: effectiveIncludeStorage && !!browserSession.storageAppliesTo?.(locator),
|
||||
cookieRows: browserData.cookieRows,
|
||||
storageRows: browserData.storageRows,
|
||||
})
|
||||
: null
|
||||
const browserSessionExt = sessionPayload ? { browser_session: sessionPayload } : {}
|
||||
return {
|
||||
type: 'url',
|
||||
locator,
|
||||
|
|
@ -922,10 +928,15 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
const browserApplicable = !!browserSession && items.some(
|
||||
it => it.kind !== 'text' && it.kind !== 'file' && it.locator.trim() && browserSession.appliesTo(it.locator.trim())
|
||||
)
|
||||
const storageApplicable = !!browserSession && items.some(
|
||||
it => it.kind !== 'text' && it.kind !== 'file' && it.locator.trim() && browserSession.storageAppliesTo?.(it.locator.trim())
|
||||
)
|
||||
const effectiveIncludeStorage = includeStorage && storageApplicable
|
||||
const effectiveUseCookies = useCookies && browserData.cookieAccess === 'granted'
|
||||
const browserDataError = browserApplicable
|
||||
? validateBrowserData({ useCookies: effectiveUseCookies, includeStorage, cookieRows: browserData.cookieRows, storageRows: browserData.storageRows })
|
||||
? validateBrowserData({ useCookies: effectiveUseCookies, includeStorage: effectiveIncludeStorage, cookieRows: browserData.cookieRows, storageRows: browserData.storageRows })
|
||||
: null
|
||||
const browserDataLoading = browserApplicable && (browserData.status === 'idle' || browserData.status === 'loading')
|
||||
|
||||
return (
|
||||
<dialog
|
||||
|
|
@ -1161,7 +1172,8 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
browserData={browserData}
|
||||
setBrowserData={setBrowserData}
|
||||
effectiveUseCookies={effectiveUseCookies}
|
||||
includeStorage={includeStorage}
|
||||
includeStorage={effectiveIncludeStorage}
|
||||
storageApplicable={storageApplicable}
|
||||
setIncludeStorage={setIncludeStorage}
|
||||
browserDataError={browserDataError}
|
||||
/>
|
||||
|
|
@ -1176,7 +1188,7 @@ export default function CaptureDialog({ open, archiveId, onClose, onCaptured, on
|
|||
type="button"
|
||||
className="capture-submit"
|
||||
onClick={handleArchive}
|
||||
disabled={!archiveId || pendingCount === 0 || anyConflict || anyProbing || anyEmptyPlaylist || anyUploading || !!browserDataError}
|
||||
disabled={!archiveId || pendingCount === 0 || anyConflict || anyProbing || anyEmptyPlaylist || anyUploading || browserDataLoading || !!browserDataError}
|
||||
>
|
||||
{pendingCount > 1 ? `Archive ${pendingCount}` : 'Archive'}
|
||||
</button>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue