YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
Preserve Windows acquisition attribution through ordinary installation (#7856)
screenpipe-windows-development[bot]5341def4e1fd
diff --git a/.github/scripts/release-workflows.test.ts b/.github/scripts/release-workflows.test.tsindex dabf3ddf7..7adc4b039 100644--- a/.github/scripts/release-workflows.test.ts+++ b/.github/scripts/release-workflows.test.ts@@ -47,6 +47,46 @@ test("Linux carrier preparation preserves recovery of older app revisions", () =}});+test("Windows builds prepare and upload legacy plus certificate attribution carriers", () => {+ const steps = app.jobs["publish-tauri"].steps;+ const prepare = steps.find((step: any) => step.name === "Prepare Windows certificate download carrier");+ expect(prepare.if).toBe("matrix.os_type == 'windows'");+ expect(prepare.run).toContain("--platform $platform --release $version");+ expect(prepare.run).toContain("--windows-release-carriers");+ expect(prepare.run.match(/python scripts\/package-attribution-carrier\.py/g)).toHaveLength(1);+ expect(prepare.run).toContain("screenpipe-attribution-windows.exe");+ expect(prepare.run).toContain("aarch64-pc-windows-msvc");+ const dryRun = steps.find((step: any) => step.name === "Upload Windows dry-run artifacts");+ expect(dryRun.with.path).toContain("bundle/attribution/*");+ const upload = steps.find((step: any) => step.name === "Upload to Cloudflare R2 (Windows)");+ expect(upload.run).toContain('"${BUNDLE_DIR}"/attribution/*');+});++test("Windows carrier orchestration recovers old sources and surfaces Python failure", () => {+ const step = app.jobs["publish-tauri"].steps.find((item: any) => item.name === "Prepare Windows certificate download carrier");+ const script = step.run.replaceAll("${{ matrix.target }}", "x86_64-pc-windows-msvc");+ for (const revision of ["missing", "legacy", "failing"] as const) {+ const fixture = mkdtempSync(join(tmpdir(), "screenpipe-windows-release-"));+ try {+ const bundle = join(fixture, "apps/screenpipe-app-tauri/src-tauri/target/x86_64-pc-windows-msvc/release/bundle");+ mkdirSync(join(bundle, "nsis"), { recursive: true });+ mkdirSync(join(fixture, "scripts"));+ writeFileSync(join(fixture, "apps/screenpipe-app-tauri/src-tauri/Cargo.toml"),+ '# screenpipe — AI that knows everything you\'ve seen, said, or heard\n# https://screenpipe.com\nversion = "1.2.3"\n');+ const installer = Buffer.from("ordinary signed installer fixture");+ writeFileSync(join(bundle, "nsis/screenpipe_1.2.3_x64-setup.exe"), installer);+ if (revision !== "missing") writeFileSync(join(fixture, "scripts/package-attribution-carrier.py"), revision === "legacy"+ ? '# screenpipe — AI that knows everything you\'ve seen, said, or heard\n# https://screenpipe.com\n# legacy option: --windows-certificate\nraise RuntimeError("old packager must not run")\n'+ : '# screenpipe — AI that knows everything you\'ve seen, said, or heard\n# https://screenpipe.com\n# --windows-release-carriers\nraise SystemExit(23)\n');+ const result = Bun.spawnSync(["pwsh", "-NoProfile", "-Command", script], { cwd: fixture, stdout: "pipe", stderr: "pipe" });+ expect(result.exitCode === 0).toBe(revision !== "failing");+ if (revision === "failing") expect(new TextDecoder().decode(result.stderr)).toContain("failed with exit 23");+ expect(readFileSync(join(bundle, "nsis/screenpipe_1.2.3_x64-setup.exe"))).toEqual(installer);+ expect(existsSync(join(bundle, "attribution"))).toBe(false);+ } finally { rmSync(fixture, { recursive: true, force: true }); }+ }+});+function api(dispatchFails = false) {const calls: { method: string; args: any }[] = [];const github = { rest: {diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex dff6247d0..8eb066f5a 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -1659,6 +1659,27 @@ jobs:--output "$BUNDLE_DIR/attribution" --platform linux --release "$VERSION" --linux-xattrdone+ - name: Prepare Windows certificate download carrier+ if: matrix.os_type == 'windows'+ shell: pwsh+ run: |+ if (-not (Test-Path scripts/package-attribution-carrier.py) -or+ -not (Select-String -Quiet -LiteralPath scripts/package-attribution-carrier.py -Pattern '--windows-release-carriers' -SimpleMatch)) {+ Write-Host 'Windows app revision predates certificate carriers; retaining ordinary installer'+ exit 0+ }+ $bundle = "apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle"+ $version = (Select-String '^version = "(.*)"' apps/screenpipe-app-tauri/src-tauri/Cargo.toml).Matches[0].Groups[1].Value+ $platform = if ('${{ matrix.target }}' -eq 'aarch64-pc-windows-msvc') { 'windows-arm' } else { 'windows' }+ $installer = Get-ChildItem "$bundle/nsis/*.exe" -ErrorAction Stop | Select-Object -First 1+ python scripts/package-attribution-carrier.py --artifact $installer.FullName `+ --output "$bundle/attribution" --platform $platform --release $version --windows-release-carriers+ if ($LASTEXITCODE -ne 0) { throw "Windows attribution preparation failed with exit $LASTEXITCODE" }+ $prepared = Get-Item "$bundle/attribution/screenpipe-attribution-windows.exe"+ if ((Get-AuthenticodeSignature $prepared.FullName).Status -ne 'Valid') {+ throw 'prepared Windows attribution installer lost its Authenticode validity'+ }+- name: Upload Linux dry-run artifactsif: matrix.os_type == 'linux' && github.event.inputs.dry_run == 'true'uses: actions/upload-artifact@v4@@ -1691,6 +1712,7 @@ jobs:path: |apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle/nsis/*.exeapps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle/nsis/*.sig+ apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle/attribution/*if-no-files-found: errorcompression-level: 0@@ -1723,7 +1745,8 @@ jobs:.github/scripts/upload-release-artifacts.sh consumer "$VERSION" "$TARGET" \"${BUNDLE_DIR}"/nsis/*.exe \"${BUNDLE_DIR}"/nsis/*.nsis.zip \- "${BUNDLE_DIR}"/nsis/*.sig+ "${BUNDLE_DIR}"/nsis/*.sig \+ "${BUNDLE_DIR}"/attribution/*- name: Upload to Cloudflare R2 (Linux)if: matrix.os_type == 'linux' && github.event.inputs.dry_run != 'true'diff --git a/apps/screenpipe-app-tauri/src-tauri/src/acquisition_handoff.rs b/apps/screenpipe-app-tauri/src-tauri/src/acquisition_handoff.rsindex 79bca763f..cf0c64435 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/acquisition_handoff.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/acquisition_handoff.rs@@ -164,6 +164,7 @@ fn carrier() -> Option<String> {#[cfg(target_os = "windows")]fn carrier_from(directory: &std::path::Path) -> Option<String> {+ report_windows_installer_diagnostic(directory);// The installer writes this once. Keep the read bounded so an untrusted or// corrupt install directory cannot turn startup into an unbounded read.let path = directory.join("acquisition-grant");@@ -177,6 +178,146 @@ fn carrier_from(directory: &std::path::Path) -> Option<String> {uuid4(&grant).then_some(grant)}+#[cfg(target_os = "windows")]+fn report_windows_installer_diagnostic(directory: &std::path::Path) {+ let path = directory.join("acquisition-grant-diagnostic");+ // This maximum is derived from the closed v1 grammar below: longest cause,+ // u32 measurement, longest unit-labelled expectation, source and outcome.+ // Open once and read at most one byte beyond it; unknown user-writable data+ // is discarded without ever entering a log message.+ const MAX_RECORD: usize = "v1;embedded-duplicate;actual-extensions=4294967295;expected-extensions=1;fallback=certificate;persistence=not-attempted".len();+ use std::io::Read;+ let record = std::fs::File::open(&path).ok().and_then(|file| {+ let mut bytes = Vec::with_capacity(MAX_RECORD + 1);+ file.take((MAX_RECORD + 1) as u64).read_to_end(&mut bytes).ok()?;+ (bytes.len() <= MAX_RECORD).then(|| String::from_utf8(bytes).ok()).flatten()+ });+ if let Some(record) = record.as_deref().and_then(parse_windows_installer_diagnostic) {+ tracing::warn!(+ cause = record.cause,+ fallback = record.fallback,+ persistence = record.persistence,+ windows_error = record.windows_error,+ actual_chars = record.actual_chars,+ threshold_chars = record.threshold_chars,+ actual_bytes = record.actual_bytes,+ expected_bytes = record.expected_bytes,+ actual_extensions = record.actual_extensions,+ expected_extensions = record.expected_extensions,+ "Windows acquisition origin metadata unavailable; installer attribution fallback completed"+ );+ }+ // A valid record is single-use; unknown data is also discarded silently.+ let _ = std::fs::remove_file(path);+}++#[cfg(target_os = "windows")]+struct WindowsInstallerDiagnostic<'a> {+ cause: &'a str,+ fallback: &'a str,+ persistence: &'a str,+ windows_error: Option<u32>,+ actual_chars: Option<u32>,+ threshold_chars: Option<u32>,+ actual_bytes: Option<u32>,+ expected_bytes: Option<u32>,+ actual_extensions: Option<u32>,+ expected_extensions: Option<u32>,+}++#[cfg(target_os = "windows")]+fn parse_windows_installer_diagnostic(record: &str) -> Option<WindowsInstallerDiagnostic<'_>> {+ let fields: Vec<_> = record.split(';').collect();+ let common = |fallback: &str, persistence: &str| {+ matches!(fallback, "certificate" | "origin" | "filename" | "none")+ && matches!(persistence, "saved" | "failed" | "not-attempted")+ };+ match fields.as_slice() {+ ["v1", cause @ ("duplicate-host-url" | "malformed-host-url"), fallback, persistence] => {+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ common(fallback, persistence).then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: None,+ actual_chars: None, threshold_chars: None,+ actual_bytes: None, expected_bytes: None,+ actual_extensions: None, expected_extensions: None,+ })+ }+ ["v1", cause @ ("origin-open-failed" | "origin-read-failed"), error, fallback, persistence] => {+ let windows_error = error.strip_prefix("windows-error=")?.parse().ok()?;+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ common(fallback, persistence).then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: Some(windows_error),+ actual_chars: None, threshold_chars: None,+ actual_bytes: None, expected_bytes: None,+ actual_extensions: None, expected_extensions: None,+ })+ }+ ["v1", cause @ "host-url-overflow", actual, threshold, fallback, persistence] => {+ let actual_chars = actual.strip_prefix("actual-chars=")?.parse().ok()?;+ let threshold_chars = threshold.strip_prefix("threshold-chars=")?.parse().ok()?;+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ (common(fallback, persistence) && actual_chars > threshold_chars && threshold_chars == 1023)+ .then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: None,+ actual_chars: Some(actual_chars), threshold_chars: Some(threshold_chars),+ actual_bytes: None, expected_bytes: None,+ actual_extensions: None, expected_extensions: None,+ })+ }+ ["v1", cause @ "embedded-length", actual, expected, fallback, persistence] => {+ let actual_bytes = actual.strip_prefix("actual-bytes=")?.parse().ok()?;+ let expected_bytes = expected.strip_prefix("expected-bytes=")?.parse().ok()?;+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ (common(fallback, persistence) && actual_bytes != expected_bytes && expected_bytes == 71)+ .then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: None,+ actual_chars: None, threshold_chars: None,+ actual_bytes: Some(actual_bytes), expected_bytes: Some(expected_bytes),+ actual_extensions: None, expected_extensions: None,+ })+ }+ ["v1", cause @ "embedded-duplicate", actual, expected, fallback, persistence] => {+ let actual_extensions = actual.strip_prefix("actual-extensions=")?.parse().ok()?;+ let expected_extensions = expected.strip_prefix("expected-extensions=")?.parse().ok()?;+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ (common(fallback, persistence) && actual_extensions > 1 && expected_extensions == 1)+ .then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: None,+ actual_chars: None, threshold_chars: None,+ actual_bytes: None, expected_bytes: None,+ actual_extensions: Some(actual_extensions), expected_extensions: Some(expected_extensions),+ })+ }+ ["v1", cause @ ("embedded-critical" | "embedded-der" | "embedded-marker" | "embedded-grant"), fallback, persistence] => {+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ common(fallback, persistence).then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: None,+ actual_chars: None, threshold_chars: None,+ actual_bytes: None, expected_bytes: None,+ actual_extensions: None, expected_extensions: None,+ })+ }+ ["v1", cause @ "embedded-decode", error, fallback, persistence] => {+ let windows_error = error.strip_prefix("windows-error=")?.parse().ok()?;+ let fallback = fallback.strip_prefix("fallback=")?;+ let persistence = persistence.strip_prefix("persistence=")?;+ common(fallback, persistence).then_some(WindowsInstallerDiagnostic {+ cause, fallback, persistence, windows_error: Some(windows_error),+ actual_chars: None, threshold_chars: None,+ actual_bytes: None, expected_bytes: None,+ actual_extensions: None, expected_extensions: None,+ })+ }+ _ => None,+ }+}+#[cfg(target_os = "linux")]fn carrier() -> Option<String> {// AppImages execute from a temporary mount; APPIMAGE is the original file.@@ -505,6 +646,216 @@ mod tests {assert!(carrier_from(dir.path()).is_none());}+ #[cfg(target_os = "windows")]+ #[test]+ fn windows_diagnostic_protocol_is_closed_and_requires_boundary_facts() {+ for valid in [+ "v1;duplicate-host-url;fallback=filename;persistence=saved",+ "v1;malformed-host-url;fallback=none;persistence=not-attempted",+ "v1;origin-open-failed;windows-error=5;fallback=filename;persistence=failed",+ "v1;origin-read-failed;windows-error=23;fallback=none;persistence=not-attempted",+ "v1;host-url-overflow;actual-chars=1024;threshold-chars=1023;fallback=filename;persistence=saved",+ "v1;embedded-length;actual-bytes=70;expected-bytes=71;fallback=none;persistence=not-attempted",+ "v1;embedded-length;actual-bytes=72;expected-bytes=71;fallback=origin;persistence=saved",+ "v1;embedded-duplicate;actual-extensions=2;expected-extensions=1;fallback=filename;persistence=saved",+ "v1;embedded-critical;fallback=none;persistence=not-attempted",+ "v1;embedded-decode;windows-error=13;fallback=origin;persistence=saved",+ ] {+ assert!(parse_windows_installer_diagnostic(valid).is_some(), "rejected {valid}");+ }+ for invalid in [+ "invalid-origin-metadata",+ "v1;host-url-overflow;fallback=filename;persistence=saved",+ "v1;host-url-overflow;actual-chars=1023;threshold-chars=1023;fallback=filename;persistence=saved",+ "v1;origin-read-failed;windows-error=private-path;fallback=none;persistence=not-attempted",+ "v1;malformed-host-url;fallback=filename;persistence=saved\nforged log line",+ "v1;arbitrary-marker;fallback=filename;persistence=saved",+ "v1;embedded-length;actual-bytes=71;expected-bytes=71;fallback=none;persistence=not-attempted",+ "v1;embedded-duplicate;actual-extensions=1;expected-extensions=1;fallback=none;persistence=not-attempted",+ ] {+ assert!(parse_windows_installer_diagnostic(invalid).is_none(), "accepted {invalid}");+ }+ }++ #[cfg(target_os = "windows")]+ #[tokio::test]+ async fn windows_ads_failure_survives_support_rotation_without_private_data() {+ let dir = tempfile::tempdir().unwrap();+ let fixture = dir.path().join("fixture.nsi");+ let hooks = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("windows/hooks.nsh");+ let hooks = hooks.display().to_string().replace('/', "\\");+ std::fs::write(+ &fixture,+ format!(+ r#"; screenpipe — AI that knows everything you've seen, said, or heard+; https://screenpipe.com+Unicode true+SilentInstall silent+RequestExecutionLevel user+!include "{}"+Name "Screenpipe acquisition diagnostic fixture"+OutFile "fixture.exe"+InstallDir "$TEMP\screenpipe-acquisition-diagnostic-fixture"+Section+ CreateDirectory "$INSTDIR"+ !insertmacro _SP_SaveAcquisitionGrant+SectionEnd+"#,+ hooks+ ),+ )+ .unwrap();+ let compiled = std::process::Command::new("makensis.exe")+ .args(["/V2", fixture.to_str().unwrap()])+ .current_dir(dir.path())+ .status()+ .expect("makensis.exe is required by the Windows native fixture");+ assert!(compiled.success());++ let current = dir.path().join("screenpipe-app.2026-11-02.log");+ let grant = "12345678-1234-4234-8234-123456789012";+ let installer = dir.path().join(format!("screenpipe-{grant}.exe"));+ std::fs::copy(dir.path().join("fixture.exe"), &installer).unwrap();+ let private_grant = "abcdefab-cdef-4abc-9def-abcdefabcdef";+ let prefix = "HostUrl=https://downloads.test/private/";+ let suffix = format!("/screenpipe-{private_grant}.exe");+ let host_url = format!("{prefix}{}{suffix}", "x".repeat(1024 - prefix.len() - suffix.len()));+ std::fs::write(+ format!("{}:Zone.Identifier", installer.display()),+ format!("[ZoneTransfer]\r\nZoneId=3\r\n{host_url}\r\n"),+ )+ .unwrap();+ let installed = dir.path().join("installed");+ let status = std::process::Command::new(&installer)+ .args(["/S", &format!("/D={}", installed.display())])+ .status()+ .unwrap();+ assert!(status.success());+ assert_eq!(std::fs::read_to_string(installed.join("acquisition-grant")).unwrap(), grant);+ assert!(std::fs::read_to_string(installed.join("acquisition-grant-diagnostic"))+ .unwrap().starts_with("v1;host-url-overflow;actual-chars=1024;threshold-chars=1023;"));++ // Build signed producer fixtures from this checkout and replace only+ // the appended untrusted carrier certificate for each boundary case.+ let evidence = dir.path().join("final-producer");+ let repository = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))+ .ancestors().nth(3).unwrap();+ let prepared = std::process::Command::new("pwsh.exe")+ .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"])+ .arg(repository.join("scripts/test_windows_browser_ads.ps1"))+ .arg("-EvidenceDirectory").arg(&evidence).arg("-PrepareOnly")+ .status().expect("PowerShell is required by the Windows producer fixture");+ assert!(prepared.success());+ let signed = evidence.join("signed-carrier-template.exe");+ let oid = "2.25.190389607246623950780965390285594181377";+ let marker = "urn:screenpipe:acquisition-grant:";+ let certificates = dir.path().join("certificates");+ std::fs::create_dir(&certificates).unwrap();+ for (length, value) in [(35, &grant[..35]), (36, grant),+ (37, "12345678-1234-4234-8234-123456789012x")] {+ let certificate = certificates.join(format!("grant-{length}.der"));+ let key = certificates.join(format!("grant-{length}.key"));+ let generated = std::process::Command::new("openssl.exe")+ .args(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout"])+ .arg(&key).arg("-out").arg(&certificate)+ .args(["-outform", "DER", "-days", "1", "-subj",+ "/CN=Screenpipe attribution fixture", "-addext"])+ .arg(format!("{oid}=ASN1:UTF8String:{marker}{value}"))+ .status().expect("OpenSSL is required by the Windows producer fixture");+ assert!(generated.success());+ std::fs::write(&key, []).unwrap();+ }+ let finalizer = dir.path().join("finalize_fixture.py");+ std::fs::write(&finalizer, r#"# screenpipe — AI that knows everything you've seen, said, or heard+# https://screenpipe.com+import importlib.util, pathlib, struct, sys+spec = importlib.util.spec_from_file_location('carrier', sys.argv[1])+c = importlib.util.module_from_spec(spec); spec.loader.exec_module(c)+source, cert, value, output = map(pathlib.Path, sys.argv[2:]); extra = cert.read_bytes()+def insert(pkcs7):+ _, ov, oe = c._der_tlv(pkcs7); outer=[]; cursor=ov+ while cursor < oe:+ child=c._der_tlv(pkcs7,cursor); outer.append(pkcs7[cursor:child[2]]); cursor=child[2]+ _, ev, ee=c._der_tlv(outer[1]); signed=outer[1][ev:ee]+ _, sv, se=c._der_tlv(signed); children=[]; cursor=sv+ while cursor < se:+ child=c._der_tlv(signed,cursor); children.append(signed[cursor:child[2]]); cursor=child[2]+ indexes=[i for i,x in enumerate(children) if x[0] == 0xa0]+ if len(indexes) != 1: raise ValueError('PKCS7 certificate set')+ i=indexes[0]; _, cv, ce=c._der_tlv(children[i]); certs=children[i][cv:ce]+ kept=[]; cursor=0+ while cursor < len(certs):+ item=c._der_tlv(certs,cursor); encoded=certs[cursor:item[2]]+ if not c._matching_extensions(encoded): kept.append(encoded)+ cursor=item[2]+ children[i]=c._der_wrap(0xa0,b''.join(sorted(kept+[extra])))+ return c._der_wrap(0x30,outer[0]+c._der_wrap(0xa0,c._der_wrap(0x30,b''.join(children))))+c.WINDOWS_DUMMY_CERT=extra; c.PLACEHOLDER=value.read_text(); c._insert_dummy_certificate=insert+with source.open('rb') as stream:+ offset,size_offset,table,_=c._prepare_windows_certificate(stream,source.stat().st_size)+ stream.seek(0); prefix=bytearray(stream.read(offset))+struct.pack_into('<I',prefix,size_offset,len(table)); output.write_bytes(prefix+table)+"#).unwrap();+ let packager = repository.join("scripts/package-attribution-carrier.py");+ let mut produced = Vec::new();+ for length in [35, 36, 37] {+ let value = dir.path().join(format!("value-{length}"));+ std::fs::write(&value, match length { 35 => &grant[..35], 36 => grant,+ _ => "12345678-1234-4234-8234-123456789012x" }).unwrap();+ let output = dir.path().join(format!("grant-{length}.exe"));+ let finalized = std::process::Command::new("python.exe").arg(&finalizer)+ .arg(&packager).arg(&signed)+ .arg(certificates.join(format!("grant-{length}.der")))+ .arg(&value).arg(&output).status().unwrap();+ assert!(finalized.success());+ let destination = dir.path().join(format!("installed-{length}"));+ let status = std::process::Command::new(&output)+ .args(["/S", &format!("/D={}", destination.display())]).status().unwrap();+ assert!(status.success());+ assert_eq!(std::fs::read_to_string(destination.join("caller-state")).unwrap(),+ "c0|c1|c2|c3|c4|c5|c6|c7|c8|c9|r0|r1|r2|r3|r4|r5|r6|r7|1");+ println!("producer {length}: {}", std::fs::read_to_string(+ destination.join("acquisition-grant-diagnostic")+ ).unwrap_or_else(|_| "accepted".into()));+ produced.push((length, destination));+ }++ let subscriber = tracing_subscriber::fmt()+ .with_ansi(false)+ .with_writer(std::fs::File::create(¤t).unwrap())+ .finish();+ tracing::subscriber::with_default(subscriber, || {+ assert_eq!(carrier_from(&installed), Some(grant.into()));+ assert!(carrier_from(&produced[0].1).is_none());+ assert_eq!(carrier_from(&produced[1].1), Some(grant.into()));+ assert!(carrier_from(&produced[2].1).is_none());+ });+ assert!(!installed.join("acquisition-grant-diagnostic").exists());+ std::fs::rename(+ ¤t,+ dir.path().join("screenpipe-app.2026-11-02.1.log"),+ )+ .unwrap();+ std::fs::write(¤t, b"after rotation\n").unwrap();+ let report = crate::diagnostic_logs::collect_redacted_from_dirs_at_root(+ &[dir.path().to_path_buf()],+ dir.path().to_path_buf(),+ )+ .await+ .unwrap();+ println!("redacted Windows acquisition installer report:\n{report}");+ for expected in ["cause=\"host-url-overflow\"", "fallback=\"filename\"",+ "persistence=\"saved\"", "actual_chars=1024",+ "threshold_chars=1023", "cause=\"embedded-length\"",+ "actual_bytes=70", "actual_bytes=72", "expected_bytes=71"] {+ assert!(report.contains(expected), "missing {expected}: {report}");+ }+ for private in [grant, private_grant, "https://downloads.test/private", "user_private", "acquisition-grant"] {+ assert!(!report.contains(private), "support report leaked {private}: {report}");+ }+ }+#[tokio::test]async fn credential_store_preserves_proof_and_retirement_across_restart() {let dir = tempfile::tempdir().unwrap();diff --git a/apps/screenpipe-app-tauri/src-tauri/windows/hooks.nsh b/apps/screenpipe-app-tauri/src-tauri/windows/hooks.nshindex 7b8cec871..603d761c3 100644--- a/apps/screenpipe-app-tauri/src-tauri/windows/hooks.nsh+++ b/apps/screenpipe-app-tauri/src-tauri/windows/hooks.nsh@@ -9,82 +9,690 @@!include "x64.nsh"!include "LogicLib.nsh"-; Save a filename-carried acquisition grant once. This is deliberately a pure-; NSIS parser: attribution is optional and never launches a shell or blocks an-; install. Expected filename: screenpipe-<lowercase canonical UUID v4>.exe.+; Decode one definite-length DER TLV using offsets relative to a bounded buffer.+; Every byte is checked against ParentEnd before it is read. Valid is set to 1+; only when Tag, Value, and End describe a complete minimally encoded DER TLV.+!macro _SP_DerTlv Base Cursor ParentEnd Tag Value End Valid ScratchA ScratchB ScratchC ScratchD+ !define _SP_DER_INVALID sp_der_invalid_${__LINE__}+ !define _SP_DER_SHORT sp_der_short_${__LINE__}+ !define _SP_DER_LONG_LOOP sp_der_long_loop_${__LINE__}+ !define _SP_DER_LONG_NEXT sp_der_long_next_${__LINE__}+ !define _SP_DER_FINISH sp_der_finish_${__LINE__}+ !define _SP_DER_DONE sp_der_done_${__LINE__}+ StrCpy ${Valid} 0+ StrCpy ${Tag} 0+ StrCpy ${Value} 0+ StrCpy ${End} 0+ IntCmp ${Cursor} 0 0 ${_SP_DER_INVALID} 0+ IntOp ${ScratchA} ${ParentEnd} - ${Cursor}+ IntCmp ${ScratchA} 2 0 ${_SP_DER_INVALID} 0+ IntOp ${ScratchB} ${Base} + ${Cursor}+ System::Call '*${ScratchB}(&i1.r2)'+ StrCpy ${Tag} $2+ IntOp ${ScratchB} ${ScratchB} + 1+ System::Call '*${ScratchB}(&i1.r2)'+ StrCpy ${ScratchC} $2+ IntOp ${Value} ${Cursor} + 2+ IntOp ${ScratchA} ${ScratchC} & 0x80+ ${If} ${ScratchA} == 0+ StrCpy ${ScratchD} ${ScratchC}+ Goto ${_SP_DER_FINISH}+ ${EndIf}+ IntOp ${ScratchA} ${ScratchC} & 0x7f+ ; A 32-bit process can represent at most four DER length octets. This is a+ ; representation check, not a certificate-size policy cap.+ IntCmp ${ScratchA} 1 0 ${_SP_DER_INVALID} 0+ IntCmp ${ScratchA} 4 0 0 ${_SP_DER_INVALID}+ IntOp ${ScratchB} ${ParentEnd} - ${Value}+ IntCmp ${ScratchB} ${ScratchA} 0 ${_SP_DER_INVALID} 0+ IntOp ${ScratchB} ${Base} + ${Value}+ System::Call '*${ScratchB}(&i1.r6)'+ StrCpy ${ScratchC} $6+ ${If} ${ScratchC} == 0+ Goto ${_SP_DER_INVALID}+ ${EndIf}+ StrCpy ${ScratchD} 0+ StrCpy ${ScratchC} 0+ ${_SP_DER_LONG_LOOP}:+ ; Refuse a shift that would overflow signed offset arithmetic.+ IntCmp ${ScratchD} 0x007fffff 0 0 ${_SP_DER_INVALID}+ IntOp ${ScratchD} ${ScratchD} << 8+ IntOp ${ScratchB} ${Base} + ${Value}+ IntOp ${ScratchB} ${ScratchB} + ${ScratchC}+ System::Call '*${ScratchB}(&i1.r6)'+ IntOp ${ScratchD} ${ScratchD} | $6+ IntOp ${ScratchC} ${ScratchC} + 1+ IntCmp ${ScratchC} ${ScratchA} ${_SP_DER_LONG_NEXT} ${_SP_DER_LONG_LOOP} ${_SP_DER_INVALID}+ ${_SP_DER_LONG_NEXT}:+ IntOp ${Value} ${Value} + ${ScratchA}+ ; DER requires short form for values below 128.+ IntCmp ${ScratchD} 128 0 ${_SP_DER_INVALID} 0+ ${_SP_DER_FINISH}:+ IntOp ${ScratchA} ${ParentEnd} - ${Value}+ IntCmp ${ScratchA} ${ScratchD} 0 ${_SP_DER_INVALID} 0+ IntOp ${End} ${Value} + ${ScratchD}+ StrCpy ${Valid} 1+ Goto ${_SP_DER_DONE}+ ${_SP_DER_INVALID}:+ StrCpy ${Valid} 0+ ${_SP_DER_DONE}:+ !undef _SP_DER_DONE+ !undef _SP_DER_FINISH+ !undef _SP_DER_LONG_NEXT+ !undef _SP_DER_LONG_LOOP+ !undef _SP_DER_SHORT+ !undef _SP_DER_INVALID+!macroend++; Keep the parser's four scratch registers transparent to its caller. Parser+; outputs must not alias Base, Cursor, ParentEnd, or these scratch registers.+!macro _SP_ReadDer Base Cursor ParentEnd Tag Value End Valid+ Push $2+ Push $6+ Push $R2+ Push $R3+ !insertmacro _SP_DerTlv ${Base} ${Cursor} ${ParentEnd} ${Tag} ${Value} ${End} ${Valid} $2 $6 $R2 $R3+ Pop $R3+ Pop $R2+ Pop $6+ Pop $2+!macroend++; Validate the one acquisition filename shape shared by the browser origin+; metadata and the legacy installer filename. Input and output may be the same+; register. Invalid input produces an empty output.+!macro _SP_ValidateAcquisitionFilename Input Output ScratchA ScratchB ScratchC+ !define _SP_UUID_LOOP sp_uuid_loop_${__LINE__}+ !define _SP_UUID_HEX sp_uuid_hex_${__LINE__}+ !define _SP_UUID_NEXT sp_uuid_next_${__LINE__}+ !define _SP_UUID_ADVANCE sp_uuid_advance_${__LINE__}+ !define _SP_UUID_VALID sp_uuid_valid_${__LINE__}+ !define _SP_UUID_INVALID sp_uuid_invalid_${__LINE__}+ !define _SP_UUID_DONE sp_uuid_done_${__LINE__}+ StrCpy ${Output} ""+ StrLen ${ScratchA} ${Input}+ IntCmp ${ScratchA} 51 0 ${_SP_UUID_INVALID} ${_SP_UUID_INVALID}+ StrCpy ${ScratchA} ${Input} 11 0+ StrCmp ${ScratchA} "screenpipe-" 0 ${_SP_UUID_INVALID}+ StrCpy ${ScratchA} ${Input} 4 47+ StrCmp ${ScratchA} ".exe" 0 ${_SP_UUID_INVALID}+ StrCpy ${ScratchA} ${Input} 36 11+ StrCmpS ${ScratchA} "00000000-0000-4000-8000-000000000000" ${_SP_UUID_INVALID} 0+ StrCpy ${ScratchB} ${ScratchA} 1 14+ StrCmpS ${ScratchB} "4" 0 ${_SP_UUID_INVALID}+ StrCpy ${ScratchB} ${ScratchA} 1 19+ StrCmpS ${ScratchB} "8" ${_SP_UUID_VALID} 0+ StrCmpS ${ScratchB} "9" ${_SP_UUID_VALID} 0+ StrCmpS ${ScratchB} "a" ${_SP_UUID_VALID} 0+ StrCmpS ${ScratchB} "b" ${_SP_UUID_VALID} ${_SP_UUID_INVALID}++ ${_SP_UUID_VALID}:+ StrCpy ${ScratchB} 0+ ${_SP_UUID_LOOP}:+ StrCpy ${ScratchC} ${ScratchA} 1 ${ScratchB}+ ${If} ${ScratchB} == 8+ ${OrIf} ${ScratchB} == 13+ ${OrIf} ${ScratchB} == 18+ ${OrIf} ${ScratchB} == 23+ Goto ${_SP_UUID_NEXT}+ ${EndIf}+ Goto ${_SP_UUID_HEX}+ ${_SP_UUID_NEXT}:+ StrCmpS ${ScratchC} "-" 0 ${_SP_UUID_INVALID}+ Goto ${_SP_UUID_ADVANCE}+ ${_SP_UUID_HEX}:+ StrCmpS ${ScratchC} "0" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "1" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "2" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "3" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "4" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "5" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "6" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "7" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "8" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "9" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "a" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "b" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "c" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "d" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "e" ${_SP_UUID_ADVANCE} 0+ StrCmpS ${ScratchC} "f" ${_SP_UUID_ADVANCE} ${_SP_UUID_INVALID}+ ${_SP_UUID_ADVANCE}:+ IntOp ${ScratchB} ${ScratchB} + 1+ IntCmp ${ScratchB} 36 0 ${_SP_UUID_LOOP} ${_SP_UUID_INVALID}+ StrCpy ${Output} ${ScratchA}+ Goto ${_SP_UUID_DONE}+ ${_SP_UUID_INVALID}:+ StrCpy ${Output} ""+ ${_SP_UUID_DONE}:+ !undef _SP_UUID_DONE+ !undef _SP_UUID_INVALID+ !undef _SP_UUID_VALID+ !undef _SP_UUID_NEXT+ !undef _SP_UUID_ADVANCE+ !undef _SP_UUID_HEX+ !undef _SP_UUID_LOOP+!macroend++; Save an embedded-certificate, browser-origin, or filename-carried grant once.+; Attribution is optional and never launches a shell or blocks installation.!macro _SP_SaveAcquisitionGrantPush $0Push $1Push $2Push $3+ Push $4+ Push $5+ Push $6+ Push $7+ Push $8+ Push $9+ Push $R0+ Push $R1+ Push $R2+ Push $R3+ Push $R4+ Push $R5+ Push $R6+ Push $R7+ StrCpy $R7 0+ IfErrors 0 +2+ StrCpy $R7 1+ Push $R7${IfNot} ${FileExists} "$INSTDIR\acquisition-grant"- StrLen $0 $EXEFILE- ${If} $0 == 51- StrCpy $1 $EXEFILE 11 0- StrCpy $2 $EXEFILE 4 47- ${If} $1 == "screenpipe-"- ${AndIf} $2 == ".exe"- StrCpy $1 $EXEFILE 36 11- ${If} $1 != "00000000-0000-4000-8000-000000000000"- StrCpy $2 $1 1 14- ${If} $2 == "4"- StrCpy $2 $1 1 19- ${If} $2 == "8"- ${OrIf} $2 == "9"- ${OrIf} $2 == "a"- ${OrIf} $2 == "b"- StrCpy $0 0- StrCpy $3 1- ${Do}- StrCpy $2 $1 1 $0- ${If} $0 == 8- ${OrIf} $0 == 13- ${OrIf} $0 == 18- ${OrIf} $0 == 23- ${If} $2 != "-"- StrCpy $3 0- ${ExitDo}- ${EndIf}+ !insertmacro _SP_ValidateAcquisitionFilename "$EXEFILE" $4 $0 $1 $2+ StrCpy $R0 "" ; fixed diagnostic cause+ StrCpy $R1 0 ; measured chars or Win32 error+ StrCpy $R2 0 ; current logical line continues from an earlier read+ StrCpy $R3 0 ; current logical line length in NSIS characters+ StrCpy $R4 0 ; current logical line is HostUrl+ StrCpy $R5 "none" ; fallback actually selected+ StrCpy $R6 "not-attempted" ; acquisition-grant persistence outcome+ StrCpy $7 0 ; inside [ZoneTransfer]+ StrCpy $8 0 ; HostUrl count+ StrCpy $9 "" ; valid ADS grant+ ; CryptoAPI bounds the embedded SignedData and its X.509 certificates. The+ ; value must be one exact DER UTF8String containing the 33-byte marker plus+ ; 36-byte grant under the agreed noncritical UUID-derived 2.25 extension.+ ; The carrier is capability data, not a signer identity assertion.+ StrCpy $8 0 ; exact OID extension count across every certificate+ StrCpy $9 "" ; sole valid embedded grant+ StrCpy $0 0+ System::Call 'kernel32::CreateFileW(w "$EXEPATH", i 0x80000000, i 7, p 0, i 3, i 0x80, p 0)p.r5'+ ${If} $5 != -1+ System::Call 'imagehlp::ImageEnumerateCertificates(p r5, i 255, *i .r0, p 0, i 0)i.r1'+ System::Call 'kernel32::CloseHandle(p r5)'+ ${EndIf}+ ; A zero certificate count is normal: embedded attribution is optional.+ ${If} $0 > 0+ System::Call 'crypt32::CryptQueryObject(i 1, w "$EXEPATH", i 0x400, i 2, i 0, *i .r0, *i .r1, *i .r2, *p .r5, p 0, p 0)i.r3'+ ${If} $3 != 0+ StrCpy $R3 $5+ ; CryptoAPI accepts the certificate but its OID decoder omits this very+ ; large UUID arc. Parse bounded DER inside each enumerated certificate+ ; instead of changing the protocol or scanning arbitrary file bytes.+ System::Alloc 22+ Pop $2+ System::Call '*$2(&i1 0x06)'+ IntOp $3 $2 + 1+ System::Call '*$3(&i1 0x14)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x69)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x82)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x9e)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xbb)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xda)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x97)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xd5)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xd0)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xc6)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x86)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xc1)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x8e)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xa6)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xaf)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x8a)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xd3)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xdf)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x90)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0xfe)'+ IntOp $3 $3 + 1+ System::Call '*$3(&i1 0x01)'+ StrCpy $6 0+ ${Do}+ System::Call 'crypt32::CertEnumCertificatesInStore(p $R3, p r6)p.r6'+ ${If} $6 == 0+ ${ExitDo}+ ${EndIf}+ ; CERT_CONTEXT is native 32-bit because NSIS is a 32-bit process.+ System::Call '*$6(i, p.r1, i.r3, p)'+ StrCpy $R7 $1 ; certificate base+ StrCpy $R4 $3 ; current parent end offset+ StrCpy $0 0+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 48+ ${OrIf} $4 != $R4+ StrCpy $R0 "embedded-der"+ ${Continue}+ ${EndIf}+ ; Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm,+ ; signatureValue }. Only the direct TBSCertificate child can own [3].+ StrCpy $0 $3+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 48+ StrCpy $R0 "embedded-der"+ ${Continue}+ ${EndIf}+ StrCpy $0 $3+ StrCpy $R4 $4+ ${Do}+ ${If} $0 >= $R4+ ${ExitDo}+ ${EndIf}+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ StrCpy $R0 "embedded-der"+ ${ExitDo}+ ${EndIf}+ StrCpy $0 $4+ ${If} $1 != 163+ ${Continue}+ ${EndIf}+ ; [3] EXPLICIT Extensions must contain exactly one SEQUENCE.+ Push $0 ; next TBSCertificate sibling+ Push $R4+ StrCpy $0 $3+ StrCpy $R4 $4+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 48+ ${OrIf} $4 != $R4+ StrCpy $R0 "embedded-der"+ Pop $R4+ Pop $0+ ${ExitDo}+ ${EndIf}+ ; Extensions ::= SEQUENCE OF Extension.+ StrCpy $0 $3+ StrCpy $R4 $4+ !define _SP_EXTENSION_DONE sp_extension_done_${__LINE__}+ ${Do}+ ${If} $0 >= $R4+ ${ExitDo}+ ${EndIf}+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 48+ StrCpy $R0 "embedded-der"+ ${ExitDo}+ ${EndIf}+ Push $R4 ; Extensions end+ Push $4 ; next Extension+ StrCpy $0 $3+ StrCpy $R4 $4+ ; extnID OBJECT IDENTIFIER is the first Extension child.+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 6+ StrCpy $R0 "embedded-der"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $5 $4 - $3+ ${If} $5 != 20+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $5 $R7 + $3+ IntOp $1 $2 + 2+ System::Call 'msvcrt::memcmp(p r5, p r1, i 20)i.r5'+ ${If} $5 != 0+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $8 $8 + 1+ StrCpy $0 $4+ ; critical BOOLEAN is optional. Explicit FALSE is noncritical;+ ; any other encoding or TRUE value is rejected.+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ StrCpy $R0 "embedded-der"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ ${If} $1 == 1+ IntOp $5 $4 - $3+ ${If} $5 != 1+ StrCpy $R0 "embedded-der"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $5 $R7 + $3+ System::Call '*$5(&i1.r5)'+ ${If} $5 != 0+ StrCpy $R0 "embedded-critical"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ StrCpy $0 $4+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${EndIf}+ ${If} $5 == 0+ ${OrIf} $1 != 4+ ${OrIf} $4 != $R4+ StrCpy $R0 "embedded-der"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ ; extnValue contains exactly one 71-byte DER UTF8String.+ StrCpy $0 $3+ StrCpy $R4 $4+ !insertmacro _SP_ReadDer $R7 $0 $R4 $1 $3 $4 $5+ ${If} $5 == 0+ ${OrIf} $1 != 12+ ${OrIf} $4 != $R4+ StrCpy $R0 "embedded-der"+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $5 $4 - $3+ ${If} $5 != 69+ StrCpy $R0 "embedded-length"+ IntOp $R1 $5 + 2+ Goto ${_SP_EXTENSION_DONE}+ ${EndIf}+ IntOp $5 $R7 + $3+ System::Call '*$5(&m69.r7)'+ StrCpy $1 $7 33 0+ ${If} $1 != "urn:screenpipe:acquisition-grant:"+ StrCpy $R0 "embedded-marker"+ ${Else}+ StrCpy $1 $7 36 33+ StrCpy $3 "screenpipe-$1.exe"+ !insertmacro _SP_ValidateAcquisitionFilename "$3" $1 $4 $5 $7+ ${If} $1 == ""+ StrCpy $R0 "embedded-grant"${Else}- ${If} $2 != "0"- ${AndIf} $2 != "1"- ${AndIf} $2 != "2"- ${AndIf} $2 != "3"- ${AndIf} $2 != "4"- ${AndIf} $2 != "5"- ${AndIf} $2 != "6"- ${AndIf} $2 != "7"- ${AndIf} $2 != "8"- ${AndIf} $2 != "9"- ${AndIf} $2 != "a"- ${AndIf} $2 != "b"- ${AndIf} $2 != "c"- ${AndIf} $2 != "d"- ${AndIf} $2 != "e"- ${AndIf} $2 != "f"- StrCpy $3 0- ${ExitDo}- ${EndIf}+ StrCpy $9 $1${EndIf}- IntOp $0 $0 + 1- ${If} $0 >= 36- ${ExitDo}+ ${EndIf}+ ${_SP_EXTENSION_DONE}:+ Pop $0+ Pop $R4+ ${Loop}+ !undef _SP_EXTENSION_DONE+ Pop $R4+ Pop $0+ ; DER TBSCertificate has at most one [3] extensions field.+ ${ExitDo}+ ${Loop}+ ${Loop}+ System::Free $2+ System::Call 'crypt32::CertCloseStore(p $R3, i 0)'+ ${If} $8 > 1+ StrCpy $R0 "embedded-duplicate"+ StrCpy $R1 $8+ StrCpy $9 ""+ ${ElseIf} $8 == 1+ ${AndIf} $9 != ""+ StrCpy $4 $9+ StrCpy $R5 "certificate"+ ${EndIf}+ ${Else}+ System::Call 'kernel32::GetLastError()i.r1'+ StrCpy $R0 "embedded-decode"+ StrCpy $R1 $1+ ${EndIf}+ ${EndIf}+ ${If} $R5 != "certificate"+ Push $R0 ; retain the originating embedded cause across fallback parsing+ Push $R1+ ; Parser scratch must never become a filename fallback candidate.+ !insertmacro _SP_ValidateAcquisitionFilename "$EXEFILE" $4 $0 $1 $2+ StrCpy $8 0+ StrCpy $R2 0+ StrCpy $R3 0+ ClearErrors+ ; NSIS validates ordinary FileOpen paths and rejects the second colon in an+ ; ADS name. Open only this stream on the running installer with CreateFileW;+ ; FileRead/FileClose use the same native HANDLE representation.+ System::Call 'kernel32::CreateFileW(w "$EXEPATH:Zone.Identifier", i 0x80000000, i 7, p 0, i 3, i 0x80, p 0)p.r5'+ ${If} $5 != -1+ ${AndIf} $5 != ""+ ${Do}+ StrCpy $6 ""+ ClearErrors+ System::Call 'kernel32::SetLastError(i 0)'+ FileRead $5 $6+ ${If} ${Errors}+ ; EOF is ordinary and distinct from a failed stream read. FileRead+ ; may report either zero or ERROR_HANDLE_EOF after the final bytes.+ System::Call 'kernel32::GetLastError()i.r1'+ ${If} $1 != 0+ ${AndIf} $1 != 38+ ${AndIf} $1 != 80+ StrCpy $R0 "origin-read-failed"+ StrCpy $R1 $1+ StrCpy $9 ""+ ${EndIf}+ ${ExitDo}+ ${EndIf}++ ; Strip the line ending before measuring. A line exactly 1023 chars+ ; followed by a newline can produce an empty continuation read and is+ ; still complete; one additional content char is a real overflow.+ StrLen $0 $6+ StrCpy $R7 0 ; this read ends the logical line+ ${If} $0 > 0+ IntOp $1 $0 - 1+ StrCpy $2 $6 1 $1+ ${If} $2 == "$\n"+ StrCpy $R7 1+ StrCpy $6 $6 $1+ StrLen $0 $6+ ${If} $0 > 0+ IntOp $1 $0 - 1+ StrCpy $2 $6 1 $1+ ${If} $2 == "$\r"+ StrCpy $6 $6 $1+ ${EndIf}+ ${EndIf}+ ${EndIf}+ ${EndIf}+ StrLen $0 $6+ IntOp $R3 $R3 + $0++ ${If} $R2 == 1+ ; Continuations of unrelated fields are discarded incrementally.+ ; A HostUrl continuation invalidates the tentative first chunk and+ ; records the actual logical length once its end is known.+ ${If} $R4 == 1+ ${AndIf} $0 > 0+ StrCpy $9 ""+ StrCpy $R0 "host-url-overflow"+ ${EndIf}+ ${Else}+ StrCpy $0 $6 1 0+ ${If} $0 == "["+ ${If} $6 == "[ZoneTransfer]"+ StrCpy $7 1+ ${Else}+ StrCpy $7 0+ ${EndIf}+ ${ElseIf} $7 == 1+ StrCpy $0 $6 8 0+ ${If} $0 == "HostUrl="+ StrCpy $R4 1+ IntOp $8 $8 + 1+ ${If} $8 > 1+ StrCpy $R0 "duplicate-host-url"+ StrCpy $9 ""+ ${Else}+ StrCpy $0 $6 "" 8+ StrCpy $1 $0 8 0+ StrLen $2 $0+ ${If} $1 == "https://"+ ${AndIf} $2 >= 61+ StrCpy $1 $0 1 8+ ${If} $1 != "/"+ ; Query/fragment text and backslashes are not URL paths.+ StrCpy $3 8+ ${Do}+ StrCpy $1 $0 1 $3+ ${If} $1 == "?"+ ${OrIf} $1 == "#"+ ${OrIf} $1 == "\"+ StrCpy $3 -1+ ${ExitDo}+ ${EndIf}+ IntOp $3 $3 + 1+ ${If} $3 >= $2+ ${ExitDo}+ ${EndIf}+ ${Loop}+ ${If} $3 >= 0+ StrCpy $1 $0 52 -52+ StrCpy $2 $1 1 0+ ${If} $2 == "/"+ StrCpy $1 $1 "" 1+ !insertmacro _SP_ValidateAcquisitionFilename "$1" $9 $0 $2 $3+ ${EndIf}+ ${EndIf}+ ${EndIf}${EndIf}- ${Loop}- ${If} $3 == 1- ClearErrors- FileOpen $0 "$INSTDIR\acquisition-grant" w- ${IfNot} ${Errors}- FileWrite $0 $1- FileClose $0+ ${If} $9 == ""+ StrCpy $R0 "malformed-host-url"${EndIf}${EndIf}${EndIf}${EndIf}${EndIf}++ ${If} $R7 == 1+ ${If} $R4 == 1+ ${AndIf} $R3 > 1023+ StrCpy $R0 "host-url-overflow"+ StrCpy $R1 $R3+ StrCpy $9 ""+ ${EndIf}+ StrCpy $R2 0+ StrCpy $R3 0+ StrCpy $R4 0+ ${Else}+ StrCpy $R2 1+ ${EndIf}+ ${Loop}+ FileClose $5+ ${If} $R0 == "host-url-overflow"+ ${AndIf} $R1 == 0+ StrCpy $R1 $R3+ ${EndIf}+ ${Else}+ System::Call 'kernel32::GetLastError()i.r1'+ ; ERROR_FILE_NOT_FOUND / ERROR_PATH_NOT_FOUND means no ADS, not failed I/O.+ ${If} $1 != 2+ ${AndIf} $1 != 3+ ${If} $R0 == ""+ StrCpy $R0 "origin-open-failed"+ StrCpy $R1 $1+ ${EndIf}${EndIf}${EndIf}+ Pop $6+ Pop $5+ ${If} $5 != ""+ StrCpy $R0 $5+ StrCpy $R1 $6+ ${EndIf}+ ${EndIf}+ StrCpy $7 0 ; accepted ADS outcome+ ${If} $8 == 1+ ${AndIf} $9 != ""+ StrCpy $4 $9+ StrCpy $7 1+ ${If} $R5 != "certificate"+ StrCpy $R5 "origin"+ ${EndIf}+ ${EndIf}+ ${If} $7 == 0+ ${AndIf} $4 != ""+ ${AndIf} $R5 != "certificate"+ StrCpy $R5 "filename"+ ${EndIf}+ ${If} $4 != ""+ StrCpy $R6 "failed"+ ClearErrors+ FileOpen $0 "$INSTDIR\acquisition-grant" w+ ${IfNot} ${Errors}+ StrCpy $1 0+ FileWrite $0 $4+ ${IfNot} ${Errors}+ StrCpy $1 1+ ${EndIf}+ ClearErrors+ FileClose $0+ ${IfNot} ${Errors}+ ${AndIf} $1 == 1+ StrCpy $R6 "saved"+ ${EndIf}+ ${EndIf}+ ${EndIf}+ ${If} $R0 != ""+ ; Persist a closed, privacy-safe protocol only after the fallback write,+ ; so support logs retain both the cause and the actual outcome.+ StrCpy $6 "v1;$R0"+ ${If} $R0 == "host-url-overflow"+ StrCpy $6 "$6;actual-chars=$R1;threshold-chars=1023"+ ${ElseIf} $R0 == "embedded-length"+ StrCpy $6 "$6;actual-bytes=$R1;expected-bytes=71"+ ${ElseIf} $R0 == "embedded-duplicate"+ StrCpy $6 "$6;actual-extensions=$R1;expected-extensions=1"+ ${ElseIf} $R0 == "origin-open-failed"+ ${OrIf} $R0 == "origin-read-failed"+ ${OrIf} $R0 == "embedded-decode"+ StrCpy $6 "$6;windows-error=$R1"+ ${EndIf}+ StrCpy $6 "$6;fallback=$R5;persistence=$R6"+ ClearErrors+ FileOpen $0 "$INSTDIR\acquisition-grant-diagnostic" w+ ${IfNot} ${Errors}+ FileWrite $0 $6+ FileClose $0+ ${EndIf}+ ${EndIf}+ ${EndIf}+ Pop $R7+ ${If} $R7 == 1+ SetErrors+ ${Else}+ ClearErrors${EndIf}+ Pop $R7+ Pop $R6+ Pop $R5+ Pop $R4+ Pop $R3+ Pop $R2+ Pop $R1+ Pop $R0+ Pop $9+ Pop $8+ Pop $7+ Pop $6+ Pop $5+ Pop $4Pop $3Pop $2Pop $1diff --git a/docs/macos-acquisition-handoff.md b/docs/macos-acquisition-handoff.mdindex 4c48a0f72..2a1b7e4c2 100644--- a/docs/macos-acquisition-handoff.md+++ b/docs/macos-acquisition-handoff.md@@ -16,7 +16,8 @@ retry, account-boundary, and retirement protocol.signed/notarized app -> unsigned DMG template -> Worker personalizes app xattr and DMG checksums-> Finder copies app -> existing native proof -> claim -> authenticated bind-signed screenpipe-<UUID>.exe -> NSIS validates filename -> installed token+signed EXE -> untrusted certificate extension -> Worker patches fixed UUID bytes+ -> ordinary browser EXE download -> renamed installer -> installed token-> Windows credential-store proof -> claim -> authenticated bindsigned screenpipe-<UUID>.AppImage -> APPIMAGE filename -> credential-store proof@@ -82,6 +83,25 @@ Windows host and checks Authenticode, version metadata, and architecture evidencin the versioned release filename. The NSIS bootstrap PE machine is not treatedas payload architecture. Filename personalization preserves the signed bytes.Use `--platform windows` for x86_64 and `--platform windows-arm` for ARM64.+The release job additionally prepares `screenpipe-attribution-windows.exe` and+schema-4 `screenpipe-attribution-windows.json` with `--windows-certificate`.+The EXE contains a fixed placeholder in a noncritical extension of an extra+untrusted certificate under UUID-derived OID+`2.25.190389607246623950780965390285594181377`. The original signed image digest,+signer, code and NSIS payload remain unchanged; whole-file SHA-256 changes when+the website patches only the manifest's 36-byte range. The installer validates+that embedded UUID first, so ordinary browser download, rename, SmartScreen+handoff and normal installation require no additional user step.++Legacy browser `HostUrl` and canonical filename carriers remain fallbacks for+already prepared releases. Windows may consume `Zone.Identifier` before NSIS+starts, so origin metadata is not considered durable. The incremental parser+still rejects malformed, duplicated, oversized, query-like, or non-HTTPS origin+metadata. A closed, privacy-safe diagnostic records the fixed cause,+measured boundary or Windows I/O error when applicable, and the actual fallback+and persistence outcome; the app validates that protocol before logging it and+never logs the URL, grant, installer path, or marker text. `ZoneId` is not+authorization, and the installed app never searches download directories.For Linux xattr downloads, use the same versioned AppImage with `--linux-xattr`:@@ -121,8 +141,10 @@ proof, consent, account and retirement rules are unchanged.The script never uploads artifacts or changes publication pointers. Productionactivation and versioned-artifact publication have not been performed. Humanpublication remains required. An ordinary, unpersonalized download installs and-runs normally without optional attribution. Renaming a personalized Windows or-raw Linux download before its first install/launch can lose attribution.+runs normally without optional attribution. A same-volume rename preserves+Windows attribution when the browser attached a valid origin stream; filesystems+or transfer tools that strip the stream fall back to the renamed filename. Renaming+a personalized raw Linux download before its first launch can lose attribution.The signature-exempt xattr and ZIP extraction behavior are documented by[Apple Developer Technical Support](https://developer.apple.com/forums/thread/796303).diff --git a/infra/release-artifact-uploader/src/index.js b/infra/release-artifact-uploader/src/index.jsindex 329d10f85..67ccd04dc 100644--- a/infra/release-artifact-uploader/src/index.js+++ b/infra/release-artifact-uploader/src/index.js@@ -60,10 +60,14 @@ export function artifactKey(scope, version, target, filename) {throw new Error("invalid version");}if (!TARGETS.has(target)) throw new Error("unsupported target");+ const windowsTarget = target.endsWith("-pc-windows-msvc");+ const reservedWindowsCarrier = ["screenpipe-attribution-windows.exe", "screenpipe-attribution-windows.json"].includes(filename);const carrierArtifact = scope === "consumer" && (- (target.endsWith("-apple-darwin") && filename === "screenpipe-attribution.json") ||+ ((target.endsWith("-apple-darwin") || windowsTarget) &&+ filename === "screenpipe-attribution.json") ||(target === "x86_64-unknown-linux-gnu" &&- ["screenpipe-attribution.tar", "screenpipe-attribution-linux.json"].includes(filename))+ ["screenpipe-attribution.tar", "screenpipe-attribution-linux.json"].includes(filename)) ||+ (windowsTarget && reservedWindowsCarrier));if (!filename ||@@ -73,7 +77,7 @@ export function artifactKey(scope, version, target, filename) {filename.includes("/") ||filename.includes("\\") ||filename.includes("\0") ||- (!carrierArtifact && !ARTIFACT_SUFFIXES.some((suffix) => filename.endsWith(suffix)))+ (!carrierArtifact && (reservedWindowsCarrier || !ARTIFACT_SUFFIXES.some((suffix) => filename.endsWith(suffix))))) {throw new Error("invalid artifact filename");}diff --git a/infra/release-artifact-uploader/src/index.test.js b/infra/release-artifact-uploader/src/index.test.jsindex 911e5121c..333863505 100644--- a/infra/release-artifact-uploader/src/index.test.js+++ b/infra/release-artifact-uploader/src/index.test.js@@ -20,15 +20,80 @@ describe("release artifact capability boundary", () => {}});- test("admits only the consumer Mac carrier manifest alongside ordinary artifacts", () => {- for (const target of ["aarch64-apple-darwin", "x86_64-apple-darwin"]) {+ test("admits the filename carrier manifest only for consumer Mac and Windows", () => {+ for (const target of ["aarch64-apple-darwin", "x86_64-apple-darwin", "x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"]) {expect(artifactKey("consumer", "2.7.130", target, "screenpipe-attribution.json")).toBe(`releases/2.7.130/${target}/screenpipe-attribution.json`);}- expect(() => artifactKey("consumer", "2.7.130", "x86_64-pc-windows-msvc", "screenpipe-attribution.json")).toThrow();+ expect(() => artifactKey("consumer", "2.7.130", "x86_64-unknown-linux-gnu", "screenpipe-attribution.json")).toThrow();+ expect(() => artifactKey("enterprise", "2.7.130", "x86_64-pc-windows-msvc", "screenpipe-attribution.json")).toThrow();expect(() => artifactKey("enterprise", "2.7.130", "aarch64-apple-darwin", "screenpipe-attribution.json")).toThrow();expect(() => artifactKey("consumer", "2.7.130", "aarch64-apple-darwin", "latest.json")).toThrow();});+ test("starts uploads for every prepared Windows carrier file through the authorized handler", async () => {+ const uploads = [];+ const env = {+ UPLOAD_TOKEN: "fixture-token",+ RELEASES_BUCKET: {+ async createMultipartUpload(key, options) {+ uploads.push({ key, options });+ return { uploadId: "fixture-upload" };+ },+ },+ };+ for (const target of ["x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"]) {+ for (const filename of ["screenpipe-attribution.exe", "screenpipe-attribution.json", "screenpipe-attribution-windows.exe", "screenpipe-attribution-windows.json"]) {+ const key = `releases/2.7.130/${target}/${filename}`;+ const response = await handleRequest(new Request(`https://example.com/v1/uploads/consumer/2.7.130/${target}`, {+ method: "POST",+ headers: { authorization: "Bearer fixture-token", "x-artifact-name": filename },+ }), env);+ expect(response.status).toBe(201);+ expect(await response.json()).toEqual({ uploadId: "fixture-upload", key });+ expect(uploads.at(-1)).toEqual({ key, options: {+ httpMetadata: { contentType: filename.endsWith(".json") ? "application/json" : "application/octet-stream" },+ customMetadata: { publicationAccess: "false" },+ } });+ }+ }+ expect(uploads).toHaveLength(8);+ });+ test("rejects carrier uploads outside their scope before accessing storage", async () => {+ const env = {+ UPLOAD_TOKEN: "fixture-token",+ RELEASES_BUCKET: { createMultipartUpload() { throw new Error("storage must not be reached"); } },+ };+ for (const [scope, target, filename] of [+ ["enterprise", "x86_64-pc-windows-msvc", "screenpipe-attribution.json"],+ ["enterprise", "aarch64-pc-windows-msvc", "screenpipe-attribution-windows.json"],+ ["enterprise", "x86_64-pc-windows-msvc", "screenpipe-attribution-windows.exe"],+ ["consumer", "x86_64-unknown-linux-gnu", "screenpipe-attribution.json"],+ ["consumer", "aarch64-apple-darwin", "screenpipe-attribution-windows.exe"],+ ["consumer", "x86_64-pc-windows-msvc", "unknown.json"],+ ["consumer", "x86_64-pc-windows-msvc", "latest.json"],+ ["consumer", "x86_64-pc-windows-msvc", "beta/latest.json"],+ ["consumer", "x86_64-pc-windows-msvc", "published.json"],+ ]) {+ const response = await handleRequest(new Request(`https://example.com/v1/uploads/${scope}/2.7.130/${target}`, {+ method: "POST",+ headers: { authorization: "Bearer fixture-token", "x-artifact-name": filename },+ }), env);+ expect(response.status).toBe(400);+ }+ });+ test("admits only exact consumer Windows certificate carrier artifacts", () => {+ const targets = ["x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"];+ const files = ["screenpipe-attribution-windows.exe", "screenpipe-attribution-windows.json"];+ for (const target of targets) for (const filename of files) {+ expect(artifactKey("consumer", "2.7.130", target, filename))+ .toBe(`releases/2.7.130/${target}/${filename}`);+ expect(() => artifactKey("enterprise", "2.7.130", target, filename)).toThrow();+ }+ for (const filename of ["screenpipe-attribution-windows-other.json", "latest.json", "published.json"]) {+ for (const target of targets) expect(() => artifactKey("consumer", "2.7.130", target, filename)).toThrow();+ }+ expect(() => artifactKey("consumer", "2.7.130", "x86_64-unknown-linux-gnu", files[1])).toThrow();+ });test("allows only versioned consumer and enterprise artifact keys", () => {expect(artifactKey(diff --git a/scripts/package-attribution-carrier.py b/scripts/package-attribution-carrier.pyindex 0bc713fd5..5b77792f8 100644--- a/scripts/package-attribution-carrier.py+++ b/scripts/package-attribution-carrier.py@@ -3,6 +3,7 @@# https://screenpipe.com"""Prepare a versioned download carrier from a release artifact. Never uploads/publishes."""import argparse+import base64import hashlibimport jsonfrom pathlib import Path@@ -19,6 +20,241 @@ import zipfilePLACEHOLDER = '00000000-0000-4000-8000-000000000000'LINUX_XATTR = 'user.screenpipe.acquisition-grant'+WINDOWS_OID = '2.25.190389607246623950780965390285594181377'+WINDOWS_MARKER = b'urn:screenpipe:acquisition-grant:'+LEGACY_SCHEMA1_STREAMING_MAX = 2147483647+# Self-signed, deliberately untrusted certificate used only as an Authenticode+# SignedData container. Its noncritical 2.25 UUID-derived extension is not an+# identity assertion and does not alter the original signer or signed image.+WINDOWS_DUMMY_CERT = base64.b64decode(+ 'MIIDljCCAn6gAwIBAgIUPuLEEsjs5wDqHEi7isxK/wpeHw8wDQYJKoZIhvcNAQELBQAwKTEnMCUGA1UEAwweU2NyZWVucGlwZSBhdHRyaWJ1dGlvbiBjYXJyaWVyMB4XDTI2MTEwMjE3MTkwNVoXDTM2MTAzMDE3MTkwNVowKTEnMCUGA1UEAwweU2NyZWVucGlwZSBhdHRyaWJ1dGlvbiBjYXJyaWVyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqut+44LX4uLU8IykjHF8C3+g0krw4dsGvsEUbs+UFjG2HjxUJ5POy0lKEAFtaqNKpx1D6LrRWKxdqLp8EqjLFNAvblrtvxmGmZvE/3qWs1KsLOkzR3GEA9R2baDSX4KF7NZ0rSeRmJl4Y1q8wH29K3uFzUA9qdx8Mkx5RK6VmxMLXHEt6nd6hYj1GY9J4Tsjt/AsAeu8RiIgDHNyUZI7OkXOUSckgqz1UBrQOjyyB2EAl3+PcvPg8PbH7gEtOd8mYaHDDGNfw+aL1bil5JRk3sbNxLn+9zas5+ToVaF7GcUCiJBiHAJHIuykdMIScQPci/UVSAokF7Prf52AOsUPdQIDAQABo4G1MIGyMB0GA1UdDgQWBBQnzI1S5fhoX0c2cFPRa6qx7SgHJDAfBgNVHSMEGDAWgBQnzI1S5fhoX0c2cFPRa6qx7SgHJDAPBgNVHRMBAf8EBTADAQH/MF8GFGmCnrval9XQxobBjqavitPfkP4BBEcMRXVybjpzY3JlZW5waXBlOmFjcXVpc2l0aW9uLWdyYW50OjAwMDAwMDAwLTAwMDAtNDAwMC04MDAwLTAwMDAwMDAwMDAwMDANBgkqhkiG9w0BAQsFAAOCAQEAnoEOjwNe93RAoUikX+67BMbaXYRmppYN+vzr42kwG86FVPP6l4Js7zvCLc+B/4cJA5h82pzbO9kIMLnPf+ScJvZDJZQXBM2cEHqXydvj0pvJXLI7QpY/dLlzx6KXSDUvnN+OHsRJS8JjLsedgvu5fqfXHlgIoP++gzpk4ahFdAl5hnYjOFupQGpVjS6J8MNFF+6HtYKv6jgI9iXwLMy2N1/Ul1MTutCn1y9MIG1K6VKNKrPdHusGS5pKDuUUhPitRxU9nzUZbsLO03UCYOT61B27lg0+ShiMr31TCkQfPzmaRWTyOsUIkt9afAGspkTO/dmA2hVGRwb7kkgR01PP9w=='+)+++def _sha256_path(path):+ digest = hashlib.sha256()+ with Path(path).open('rb') as source:+ for block in iter(lambda: source.read(1024 * 1024), b''):+ digest.update(block)+ return digest.hexdigest()+++def _der_length(length):+ if length < 128:+ return bytes([length])+ encoded = length.to_bytes((length.bit_length() + 7) // 8, 'big')+ return bytes([0x80 | len(encoded)]) + encoded+++def _der_tlv(data, offset=0):+ if offset + 2 > len(data):+ raise ValueError('truncated DER object')+ tag, first = data[offset], data[offset + 1]+ if first < 128:+ length, header = first, 2+ else:+ count = first & 0x7f+ if not count or offset + 2 + count > len(data):+ raise ValueError('invalid DER length')+ length, header = int.from_bytes(data[offset + 2:offset + 2 + count], 'big'), 2 + count+ end = offset + header + length+ if end > len(data):+ raise ValueError('truncated DER value')+ return tag, offset + header, end+++def _der_wrap(tag, value):+ return bytes([tag]) + _der_length(len(value)) + value+++def _der_oid(oid):+ arcs = [int(part) for part in oid.split('.')]+ encoded = bytearray([40 * arcs[0] + arcs[1]])+ for arc in arcs[2:]:+ groups = [arc & 0x7f]+ arc >>= 7+ while arc:+ groups.append(0x80 | (arc & 0x7f))+ arc >>= 7+ encoded.extend(reversed(groups))+ return _der_wrap(0x06, bytes(encoded))+++def _certificate_extensions(certificate):+ """Yield structurally parsed (OID TLV, critical, extnValue contents)."""+ tag, cert_value, cert_end = _der_tlv(certificate)+ if tag != 0x30 or cert_end != len(certificate):+ raise ValueError('invalid X.509 certificate')+ tag, tbs_value, tbs_end = _der_tlv(certificate, cert_value)+ if tag != 0x30:+ raise ValueError('invalid X.509 TBSCertificate')+ cursor = tbs_value+ while cursor < tbs_end:+ child = _der_tlv(certificate, cursor)+ if child[0] == 0xa3:+ tag, extensions_value, extensions_end = _der_tlv(certificate, child[1])+ if tag != 0x30 or extensions_end != child[2]:+ raise ValueError('invalid X.509 extensions')+ extension = extensions_value+ while extension < extensions_end:+ tag, value, end = _der_tlv(certificate, extension)+ if tag != 0x30:+ raise ValueError('invalid X.509 extension')+ oid = _der_tlv(certificate, value)+ oid_tlv = certificate[value:oid[2]]+ field = oid[2]+ critical = False+ next_field = _der_tlv(certificate, field)+ if next_field[0] == 0x01:+ critical = certificate[next_field[1]:next_field[2]] != b'\0'+ field = next_field[2]+ next_field = _der_tlv(certificate, field)+ if next_field[0] != 0x04 or next_field[2] != end:+ raise ValueError('invalid X.509 extension value')+ yield oid_tlv, critical, certificate[next_field[1]:next_field[2]]+ extension = end+ return+ cursor = child[2]+++def _matching_extensions(certs):+ wanted = _der_oid(WINDOWS_OID)+ matches = []+ cursor = 0+ while cursor < len(certs):+ cert = _der_tlv(certs, cursor)+ if cert[0] != 0x30:+ raise ValueError('unsupported certificate choice')+ matches.extend((critical, value) for oid, critical, value in+ _certificate_extensions(certs[cursor:cert[2]]) if oid == wanted)+ cursor = cert[2]+ return matches+++def _insert_dummy_certificate(pkcs7):+ # ContentInfo SEQUENCE -> [0] EXPLICIT -> SignedData SEQUENCE. Preserve all+ # primitive bytes and only rebuild the enclosing lengths and certificate SET.+ tag, outer_value, outer_end = _der_tlv(pkcs7)+ if tag != 0x30 or any(pkcs7[outer_end:]):+ raise ValueError('invalid PKCS7 ContentInfo')+ pkcs7 = pkcs7[:outer_end]+ outer_children = []+ cursor = outer_value+ while cursor < outer_end:+ child = _der_tlv(pkcs7, cursor)+ outer_children.append(pkcs7[cursor:child[2]])+ cursor = child[2]+ if len(outer_children) != 2 or outer_children[1][0] != 0xa0:+ raise ValueError('PKCS7 is not explicit SignedData')+ _, explicit_value, explicit_end = _der_tlv(outer_children[1])+ signed = outer_children[1][explicit_value:explicit_end]+ _, signed_value, signed_end = _der_tlv(signed)+ children, cursor = [], signed_value+ while cursor < signed_end:+ child = _der_tlv(signed, cursor)+ children.append(signed[cursor:child[2]])+ cursor = child[2]+ cert_indexes = [i for i, child in enumerate(children) if child[0] == 0xa0]+ if len(cert_indexes) != 1:+ raise ValueError('PKCS7 must contain one certificate set')+ index = cert_indexes[0]+ _, cert_value, cert_end = _der_tlv(children[index])+ certs = children[index][cert_value:cert_end]+ if _matching_extensions(certs):+ raise ValueError('Windows carrier certificate already present')+ encoded_certificates = []+ cursor = 0+ while cursor < len(certs):+ certificate = _der_tlv(certs, cursor)+ encoded_certificates.append(certs[cursor:certificate[2]])+ cursor = certificate[2]+ encoded_certificates.append(WINDOWS_DUMMY_CERT)+ canonical_certificates = b''.join(sorted(encoded_certificates))+ children[index] = _der_wrap(0xa0, canonical_certificates)+ matches = _matching_extensions(canonical_certificates)+ expected = _der_wrap(0x0c, WINDOWS_MARKER + PLACEHOLDER.encode())+ if matches != [(False, expected)]:+ raise ValueError('invalid Windows carrier extension contract')+ rebuilt_signed = _der_wrap(0x30, b''.join(children))+ rebuilt_explicit = _der_wrap(0xa0, rebuilt_signed)+ return _der_wrap(0x30, outer_children[0] + rebuilt_explicit)+++def _prepare_windows_certificate(source, source_size):+ """Return (certificate offset, replacement table, grant offset in table)."""+ def read_exact_at(offset, length, description):+ if offset < 0 or length < 0 or offset > source_size or length > source_size - offset:+ raise ValueError(f'{description} is outside installer')+ source.seek(offset)+ value = source.read(length)+ if len(value) != length:+ raise ValueError('installer changed while reading ' + description)+ return value++ dos = read_exact_at(0, 0x40, 'DOS header') if source_size >= 0x40 else b''+ if len(dos) != 0x40 or dos[:2] != b'MZ':+ raise ValueError('invalid PE installer')+ pe = struct.unpack_from('<I', dos, 0x3c)[0]+ coff = read_exact_at(pe, 24, 'PE header')+ if coff[:4] != b'PE\0\0':+ raise ValueError('invalid PE header')+ optional_size = struct.unpack_from('<H', coff, 20)[0]+ optional_offset = pe + 24+ optional = read_exact_at(optional_offset, optional_size, 'PE optional header')+ if len(optional) < 2:+ raise ValueError('PE has no valid certificate directory')+ magic = struct.unpack_from('<H', optional)[0]+ directory = 112 if magic == 0x20b else 96 if magic == 0x10b else -1+ if directory < 0 or directory + 8 * 5 > len(optional):+ raise ValueError('PE has no valid certificate directory')+ size_offset = optional_offset + directory + 8 * 4 + 4+ cert_offset, cert_size = struct.unpack_from('<II', optional, directory + 8 * 4)+ if (cert_offset % 8 or cert_size < 8 or cert_offset > source_size or+ cert_size != source_size - cert_offset):+ raise ValueError('certificate table must be aligned and end the PE')+ win_header = read_exact_at(cert_offset, 8, 'WIN_CERTIFICATE header')+ win_length, revision, cert_type = struct.unpack('<IHH', win_header)+ if win_length > cert_size or revision != 0x200 or cert_type != 2:+ raise ValueError('unsupported WIN_CERTIFICATE')+ pkcs7_size = win_length - 8+ if pkcs7_size < 2:+ raise ValueError('unsupported WIN_CERTIFICATE')+ # Allocate the SignedData's actual DER length, not the certificate table's+ # declared size. Padding is checked incrementally below.+ der_prefix = read_exact_at(cert_offset + 8, min(6, pkcs7_size), 'PKCS7 header')+ first_length = 2 if der_prefix[1] < 0x80 else 2 + (der_prefix[1] & 0x7f)+ if first_length > len(der_prefix):+ raise ValueError('invalid PKCS7 length')+ if der_prefix[1] < 0x80:+ encoded_size = 2 + der_prefix[1]+ else:+ count = der_prefix[1] & 0x7f+ if count == 0 or count > 4 or der_prefix[2] == 0:+ raise ValueError('invalid PKCS7 length')+ encoded_size = first_length + int.from_bytes(der_prefix[2:first_length], 'big')+ if encoded_size > pkcs7_size:+ raise ValueError('WIN_CERTIFICATE length does not match PKCS7')+ pkcs7 = read_exact_at(cert_offset + 8, encoded_size, 'PKCS7 SignedData')+ # signtool may include the record's alignment zeros in dwLength. Treat+ # both that representation and padding after dwLength identically: every+ # byte between the DER object and the table end must be zero.+ source.seek(cert_offset + 8 + encoded_size)+ padding = cert_size - 8 - encoded_size+ while padding:+ block = source.read(min(1024 * 1024, padding))+ if not block or any(block):+ raise ValueError('nonzero or truncated certificate padding')+ padding -= len(block)+ rebuilt = _insert_dummy_certificate(pkcs7)+ win_length = 8 + len(rebuilt)+ padded_size = (win_length + 7) & ~7+ certificate = struct.pack('<IHH', win_length, revision, cert_type) + rebuilt+ certificate += b'\0' * (padded_size - win_length)+ # The size field is before cert_offset and is patched while streaming.+ marker = WINDOWS_MARKER + PLACEHOLDER.encode()+ if certificate.count(marker) != 1:+ raise ValueError('ambiguous Windows carrier marker')+ return cert_offset, size_offset, certificate, certificate.index(marker) + len(WINDOWS_MARKER)def package(app, output, platform, release):@@ -138,7 +374,7 @@ def package_filename(artifact, output, platform, release):artifact, output = Path(artifact).resolve(), Path(output).resolve()validate_artifact(artifact, platform, release)size = artifact.stat().st_size- if not 100 <= size <= 2147483647:+ if not 100 <= size <= LEGACY_SCHEMA1_STREAMING_MAX:raise ValueError('carrier size outside streaming limit')output.mkdir(parents=True, exist_ok=True)target = output / ('screenpipe-attribution.exe' if platform.startswith('windows')@@ -163,6 +399,133 @@ def package_filename(artifact, output, platform, release):return target, manifest+def package_windows_release_carriers(artifact, output, platform, release):+ """Prepare schema 4 and, where Website schema 1 supports it, compatibility output."""+ artifact, output = Path(artifact).resolve(), Path(output).resolve()+ output.mkdir(parents=True, exist_ok=True)+ if any(output.iterdir()):+ raise ValueError('refusing to overwrite prepared artifacts')+ with tempfile.TemporaryDirectory(prefix='.screenpipe-windows-carriers-', dir=output.parent) as staging:+ staging = Path(staging)+ package_windows_certificate(artifact, staging, platform, release)+ source_size = artifact.stat().st_size+ if source_size <= LEGACY_SCHEMA1_STREAMING_MAX:+ package_filename(artifact, staging, platform, release)+ else:+ print(f'legacy schema 1 filename carrier omitted: source size {source_size} bytes exceeds '+ f'Website schema 1 streaming limit {LEGACY_SCHEMA1_STREAMING_MAX} bytes; '+ 'schema 4 Windows certificate carrier prepared',+ file=sys.stderr)+ prepared = tuple(staging.iterdir())+ published = []+ try:+ for item in prepared:+ destination = output / item.name+ os.link(item, destination)+ published.append(destination)+ item.unlink()+ except Exception:+ for destination in published:+ destination.unlink(missing_ok=True)+ raise+ return tuple(output / item.name for item in prepared)+++def package_windows_certificate(artifact, output, platform, release):+ """Add a patchable untrusted certificate extension without changing signed image bytes."""+ if platform not in ('windows', 'windows-arm'):+ raise ValueError('Windows certificate carrier requires a Windows platform')+ artifact, output = Path(artifact).resolve(), Path(output).resolve()+ validate_artifact(artifact, platform, release)+ output.mkdir(parents=True, exist_ok=True)+ target = output / 'screenpipe-attribution-windows.exe'+ manifest = output / 'screenpipe-attribution-windows.json'+ if target.exists() or manifest.exists():+ if manifest.exists():+ raise ValueError('refusing to overwrite prepared artifacts')+ before = artifact.stat()+ digest = hashlib.sha256()+ temporary = None+ manifest_name = None+ target_created = False+ try:+ with artifact.open('rb') as source:+ cert_offset, size_offset, certificate, relative_grant = _prepare_windows_certificate(source, before.st_size)+ grant_offset = cert_offset + relative_grant+ fd, temporary_name = tempfile.mkstemp(prefix='.screenpipe-attribution-windows-', suffix='.tmp', dir=output)+ os.close(fd)+ temporary = Path(temporary_name)+ with temporary.open('wb') as destination:+ def copy_bytes(length):+ while length:+ block = source.read(min(1024 * 1024, length))+ if not block:+ raise ValueError('installer changed during streaming copy')+ destination.write(block)+ digest.update(block)+ length -= len(block)++ source.seek(0)+ copy_bytes(size_offset)+ replacement = struct.pack('<I', len(certificate))+ destination.write(replacement)+ digest.update(replacement)+ source.seek(size_offset + 4)+ copy_bytes(cert_offset - size_offset - 4)+ destination.write(certificate)+ digest.update(certificate)+ after = artifact.stat()+ if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):+ raise ValueError('installer changed during streaming copy')+ try:+ os.link(temporary, target)+ target_created = True+ temporary.unlink()+ temporary = None+ except FileExistsError:+ # A killed preparation may have published the complete executable+ # immediately before committing its manifest. Resume only when the+ # bytes prove that this is precisely our deterministic output.+ if (target.stat().st_size != temporary.stat().st_size or+ _sha256_path(target) != digest.hexdigest()):+ raise ValueError('refusing to overwrite prepared artifacts')+ temporary.unlink()+ temporary = None+ except Exception:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+ raise+ prepared_size = target.stat().st_size+ with target.open('rb') as prepared:+ prepared.seek(grant_offset)+ if prepared.read(36) != PLACEHOLDER.encode():+ raise ValueError('Windows grant patch location is invalid')+ result = dict(+ schema=4, carrier='windows-certificate', platform=platform, release=release,+ size=prepared_size, sha256=digest.hexdigest(),+ patch=dict(offset=grant_offset, length=36, placeholder=PLACEHOLDER),+ certificate=dict(oid=WINDOWS_OID, critical=False,+ marker=WINDOWS_MARKER.decode(), table_at_end=True),+ )+ try:+ fd, manifest_name = tempfile.mkstemp(prefix='.screenpipe-attribution-windows-', suffix='.json.tmp', dir=output)+ with os.fdopen(fd, 'w') as destination:+ json.dump(result, destination, indent=2)+ destination.write('\n')+ destination.flush()+ os.fsync(destination.fileno())+ os.link(manifest_name, manifest)+ Path(manifest_name).unlink()+ manifest_name = None+ except Exception:+ if manifest_name is not None:+ Path(manifest_name).unlink(missing_ok=True)+ if target_created:+ target.unlink(missing_ok=True)+ raise+ return target, manifest++def package_linux_xattr(artifact, output, platform, release):"""PAX metadata personalizes the file's xattr without changing AppImage bytes."""if platform != 'linux':@@ -219,7 +582,9 @@ def windows_metadata(artifact):"""Read signature and version using Windows' supported PowerShell APIs."""if sys.platform != 'win32':raise ValueError('Windows packaging requires a Windows host')- script = ("$ErrorActionPreference='Stop';$p=$env:SCREENPIPE_ATTRIBUTION_ARTIFACT;"+ script = ("$ErrorActionPreference='Stop';"+ "Import-Module ($env:WINDIR+'\\System32\\WindowsPowerShell\\v1.0\\Modules\\Microsoft.PowerShell.Security\\Microsoft.PowerShell.Security.psd1');"+ "$p=$env:SCREENPIPE_ATTRIBUTION_ARTIFACT;""$s=Get-AuthenticodeSignature -LiteralPath $p;""$v=[Diagnostics.FileVersionInfo]::GetVersionInfo($p);""@{Status=[string]$s.Status;ProductVersion=$v.ProductVersion;"@@ -239,9 +604,22 @@ if __name__ == '__main__':parser.add_argument('--platform', choices=['macos-arm', 'macos-intel', 'linux', 'windows', 'windows-arm'], required=True)parser.add_argument('--release', required=True)parser.add_argument('--linux-xattr', action='store_true', help='prepare a Linux PAX tar xattr carrier')+ parser.add_argument('--windows-certificate', action='store_true', help='prepare a Windows certificate carrier')+ parser.add_argument('--windows-release-carriers', action='store_true',+ help='prepare schema 4 plus supported schema 1 Windows compatibility output')args = parser.parse_args()if args.linux_xattr and (not args.artifact or args.platform != 'linux'):parser.error('--linux-xattr requires --artifact and --platform linux')- prepare = package_linux_xattr if args.linux_xattr else package if args.app else package_filename+ if args.windows_certificate and (not args.artifact or not args.platform.startswith('windows')):+ parser.error('--windows-certificate requires a Windows --artifact')+ if args.windows_certificate and args.linux_xattr:+ parser.error('carrier modes are mutually exclusive')+ if args.windows_release_carriers and (not args.artifact or not args.platform.startswith('windows')):+ parser.error('--windows-release-carriers requires a Windows --artifact')+ if sum((args.windows_certificate, args.windows_release_carriers, args.linux_xattr)) > 1:+ parser.error('carrier modes are mutually exclusive')+ prepare = (package_windows_release_carriers if args.windows_release_carriers else+ package_windows_certificate if args.windows_certificate else+ package_linux_xattr if args.linux_xattr else package if args.app else package_filename)for artifact in prepare(args.app or args.artifact, args.output, args.platform, args.release):print(artifact)diff --git a/scripts/test_attribution_carrier.py b/scripts/test_attribution_carrier.pyindex 0338ec91b..b2d421d9c 100644--- a/scripts/test_attribution_carrier.py+++ b/scripts/test_attribution_carrier.py@@ -3,12 +3,14 @@"""Local attribution-carrier packaging regressions; never publish artifacts."""import importlib.utilimport hashlib+import ioimport jsonimport osimport sysfrom pathlib import Pathimport plistlibimport shutil+import structimport subprocessimport tempfileimport tarfile@@ -21,6 +23,90 @@ spec.loader.exec_module(carrier)class CarrierTest(unittest.TestCase):+ @staticmethod+ def _sparse_pe(path, pe_offset=64 * 1024 * 1024):+ optional = bytearray(112 + 8 * 5)+ struct.pack_into('<H', optional, 0, 0x20b)+ cert_offset = (pe_offset + 24 + len(optional) + 7) & ~7+ pkcs7 = b'0\x03\x02\x01\x01'+ win_length = 8 + len(pkcs7)+ certificate = struct.pack('<IHH', win_length, 0x200, 2) + pkcs7+ certificate += bytes((8 - len(certificate) % 8) % 8)+ struct.pack_into('<II', optional, 112 + 8 * 4, cert_offset, len(certificate))+ with path.open('wb') as stream:+ dos = bytearray(64)+ dos[:2] = b'MZ'+ struct.pack_into('<I', dos, 0x3c, pe_offset)+ stream.write(dos)+ stream.seek(pe_offset)+ stream.write(b'PE\0\0' + bytes(16) + struct.pack('<H', len(optional)) + bytes(2))+ stream.write(optional)+ stream.seek(cert_offset)+ stream.write(certificate)+ return cert_offset++ def test_windows_pe_headers_are_seeked_and_read_bounded(self):+ with tempfile.TemporaryDirectory() as tmp:+ artifact = Path(tmp) / 'distant.exe'+ cert_offset = self._sparse_pe(artifact)++ class RecordingReader:+ def __init__(self, source):+ self.source, self.requests = source, []+ def seek(self, *args):+ return self.source.seek(*args)+ def read(self, size):+ self.requests.append(size)+ return self.source.read(size)++ with artifact.open('rb') as raw:+ source = RecordingReader(raw)+ rebuilt = carrier.WINDOWS_MARKER + carrier.PLACEHOLDER.encode()+ with mock.patch.object(carrier, '_insert_dummy_certificate', return_value=rebuilt):+ found, _, _, _ = carrier._prepare_windows_certificate(source, artifact.stat().st_size)+ self.assertEqual(found, cert_offset)+ self.assertLessEqual(max(source.requests), 1024 * 1024)+ self.assertNotIn(64 * 1024 * 1024, source.requests)++ def test_windows_release_orchestration_schema1_boundary(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ for delta, expects_legacy in [(-1, True), (0, True), (1, False)]:+ artifact = root / f'screenpipe_1.2.3_x64-{delta}-setup.exe'+ artifact.write_bytes(b'fixture')+ output = root / f'out-{delta}'++ def certificate(_artifact, staging, _platform, _release):+ first = Path(staging) / 'screenpipe-attribution-windows.exe'+ second = Path(staging) / 'screenpipe-attribution-windows.json'+ first.write_bytes(b'certificate')+ second.write_text('{}')+ return first, second++ def legacy(_artifact, staging, _platform, _release):+ first = Path(staging) / 'screenpipe-attribution.exe'+ second = Path(staging) / 'screenpipe-attribution.json'+ first.write_bytes(b'legacy')+ second.write_text('{}')+ return first, second++ with mock.patch.object(carrier, 'package_windows_certificate', side_effect=certificate), \+ mock.patch.object(carrier, 'package_filename', side_effect=legacy) as legacy_call, \+ mock.patch.object(carrier.Path, 'stat') as stat, \+ mock.patch.object(carrier.sys, 'stderr', new_callable=io.StringIO) as diagnostics:+ stat.return_value.st_size = carrier.LEGACY_SCHEMA1_STREAMING_MAX + delta+ produced = carrier.package_windows_release_carriers(+ artifact, output, 'windows', '1.2.3')+ self.assertEqual(legacy_call.called, expects_legacy)+ self.assertTrue((output / 'screenpipe-attribution-windows.exe').is_file())+ self.assertEqual(len(produced), 4 if expects_legacy else 2)+ if expects_legacy:+ self.assertEqual(diagnostics.getvalue(), '')+ else:+ self.assertIn(f'source size {carrier.LEGACY_SCHEMA1_STREAMING_MAX + delta} bytes', diagnostics.getvalue())+ self.assertIn(f'limit {carrier.LEGACY_SCHEMA1_STREAMING_MAX} bytes', diagnostics.getvalue())+ self.assertIn('schema 4 Windows certificate carrier prepared', diagnostics.getvalue())+def test_linux_xattr_tar_preserves_appimage_and_exact_patch_location(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)@@ -165,6 +251,71 @@ class CarrierTest(unittest.TestCase):with self.assertRaisesRegex(ValueError, 'version metadata'):carrier.package_filename(artifact, root / f'version-{platform}', platform, '1.2.3')+ def test_windows_certificate_manifest_contract_for_both_targets(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ placeholder_bytes = b'prefix' + carrier.PLACEHOLDER.encode() + b'suffix'+ for platform, arch in [('windows', 'x64'), ('windows-arm', 'arm64')]:+ artifact = root / f'screenpipe_1.2.3_{arch}-setup.exe'+ artifact.write_bytes(b'MZ' + bytes(126))+ output = root / f'certificate-{platform}'+ metadata = dict(Status='Valid', ProductVersion='1.2.3', FileVersion='1.2.3')+ with mock.patch.object(carrier, 'windows_metadata', return_value=metadata), \+ mock.patch.object(carrier, '_prepare_windows_certificate',+ return_value=(100, 64, placeholder_bytes, 6)):+ prepared, manifest = carrier.package_windows_certificate(+ artifact, output, platform, '1.2.3')+ expected_bytes = (artifact.read_bytes()[:64] + struct.pack('<I', len(placeholder_bytes))+ + artifact.read_bytes()[68:100] + placeholder_bytes)+ data = json.loads(manifest.read_text())+ self.assertEqual(prepared.name, 'screenpipe-attribution-windows.exe')+ self.assertEqual(manifest.name, 'screenpipe-attribution-windows.json')+ self.assertEqual(data['schema'], 4)+ self.assertEqual(data['carrier'], 'windows-certificate')+ self.assertEqual(data['platform'], platform)+ self.assertEqual(data['patch'], dict(+ offset=106, length=36, placeholder=carrier.PLACEHOLDER))+ self.assertEqual(data['certificate'], dict(+ oid=carrier.WINDOWS_OID, critical=False,+ marker=carrier.WINDOWS_MARKER.decode(), table_at_end=True))+ self.assertEqual(data['sha256'], hashlib.sha256(expected_bytes).hexdigest())++ def test_windows_certificate_patch_crosses_copy_boundary_and_recovers_owned_output(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ artifact = root / 'screenpipe_1.2.3_x64-setup.exe'+ artifact.write_bytes(b'MZ' + bytes(1024 * 1024 + 126))+ output = root / 'out'+ output.mkdir()+ target = output / 'screenpipe-attribution-windows.exe'+ target.write_bytes(b'unrelated-builder-output')+ certificate = carrier.WINDOWS_MARKER + carrier.PLACEHOLDER.encode()+ size_offset = 1024 * 1024 - 2+ cert_offset = 1024 * 1024 + 64+ metadata = dict(Status='Valid', ProductVersion='1.2.3', FileVersion='1.2.3')+ with mock.patch.object(carrier, 'windows_metadata', return_value=metadata), \+ mock.patch.object(carrier, '_prepare_windows_certificate',+ return_value=(cert_offset, size_offset, certificate, 33)):+ with self.assertRaisesRegex(ValueError, 'refusing to overwrite'):+ carrier.package_windows_certificate(artifact, output, 'windows', '1.2.3')+ self.assertEqual(target.read_bytes(), b'unrelated-builder-output')+ target.unlink()+ prepared, manifest = carrier.package_windows_certificate(+ artifact, output, 'windows', '1.2.3')+ data = prepared.read_bytes()+ self.assertEqual(struct.unpack_from('<I', data, size_offset)[0], len(certificate))+ self.assertEqual(data[cert_offset:cert_offset + len(certificate)], certificate)+ self.assertTrue(manifest.is_file())+ expected = prepared.read_bytes()+ manifest.unlink()+ with mock.patch.object(carrier, 'windows_metadata', return_value=metadata), \+ mock.patch.object(carrier, '_prepare_windows_certificate',+ return_value=(cert_offset, size_offset, certificate, 33)):+ prepared, manifest = carrier.package_windows_certificate(+ artifact, output, 'windows', '1.2.3')+ self.assertEqual(prepared.read_bytes(), expected)+ self.assertTrue(manifest.is_file())+@unittest.skipUnless(sys.platform == 'win32', 'requires Windows NSIS')def test_actual_nsis_filename_grant_fixture(self):makensis = shutil.which('makensis') or shutil.which('makensis.exe')@@ -178,11 +329,23 @@ class CarrierTest(unittest.TestCase):'; https://screenpipe.com\n''Unicode true\nSilentInstall silent\nRequestExecutionLevel user\n'f'!include "{hooks}"\n'- 'Name "Screenpipe attribution fixture"\nOutFile "fixture.exe"\nInstallDir "$TEMP\\screenpipe-attribution-fixture"\n'+ 'Name "Screenpipe attribution fixture"\n!ifndef OUTFILE\n!define OUTFILE "fixture.exe"\n!endif\n'+ 'OutFile "${OUTFILE}"\nInstallDir "$TEMP\\screenpipe-attribution-fixture"\n''Section\nCreateDirectory "$INSTDIR"\nFileOpen $0 "$INSTDIR\\installed" w\nFileWrite $0 "ok"\nFileClose $0\n'- '!insertmacro _SP_SaveAcquisitionGrant\nSectionEnd\n',+ 'StrCpy $0 "c0"\nStrCpy $1 "c1"\nStrCpy $2 "c2"\nStrCpy $3 "c3"\nStrCpy $4 "c4"\n'+ 'StrCpy $5 "c5"\nStrCpy $6 "c6"\nStrCpy $7 "c7"\nStrCpy $8 "c8"\nStrCpy $9 "c9"\n'+ 'StrCpy $R0 "r0"\nStrCpy $R1 "r1"\nStrCpy $R2 "r2"\nStrCpy $R3 "r3"\n'+ 'StrCpy $R4 "r4"\nStrCpy $R5 "r5"\nStrCpy $R6 "r6"\nStrCpy $R7 "r7"\n'+ '!ifdef INITIAL_ERROR\nSetErrors\n!else\nClearErrors\n!endif\n'+ '!insertmacro _SP_SaveAcquisitionGrant\n'+ 'StrCpy $R8 "0"\nIfErrors 0 +2\nStrCpy $R8 "1"\n'+ 'FileOpen $R9 "$INSTDIR\\caller-state" w\n'+ 'FileWrite $R9 "$0|$1|$2|$3|$4|$5|$6|$7|$8|$9|$R0|$R1|$R2|$R3|$R4|$R5|$R6|$R7|$R8"\n'+ 'FileClose $R9\nSectionEnd\n',encoding='utf-8')subprocess.run([makensis, '/V2', str(fixture)], cwd=root, check=True)+ subprocess.run([makensis, '/V2', '/DOUTFILE=fixture-error.exe',+ '/DINITIAL_ERROR=1', str(fixture)], cwd=root, check=True)# Exercise the real PowerShell adapter, including a path whose# spaces and metacharacters must remain data, never command text.@@ -193,21 +356,139 @@ class CarrierTest(unittest.TestCase):first = '12345678-1234-4234-8234-123456789012'second = 'abcdefab-cdef-4abc-9def-abcdefabcdef'- def install(filename, directory):+ expected_canaries = ('c0|c1|c2|c3|c4|c5|c6|c7|c8|c9|'+ 'r0|r1|r2|r3|r4|r5|r6|r7')++ def install(filename, directory, zone_identifier=None,+ source='fixture.exe', initial_error='0'):installer = root / filename- shutil.copyfile(root / 'fixture.exe', installer)+ shutil.copyfile(root / source, installer)+ if zone_identifier is not None:+ Path(str(installer) + ':Zone.Identifier').write_text(+ zone_identifier, encoding='ascii', newline='')+ with Path(str(installer) + ':Zone.Identifier').open(+ encoding='ascii', newline='') as stream:+ self.assertEqual(stream.read(), zone_identifier)subprocess.run([str(installer), '/S', f'/D={directory}'], check=True)self.assertEqual((directory / 'installed').read_text(), 'ok')+ self.assertEqual((directory / 'caller-state').read_text(),+ f'{expected_canaries}|{initial_error}')valid_dir = root / 'valid'install(f'screenpipe-{first}.exe', valid_dir)self.assertEqual((valid_dir / 'acquisition-grant').read_text(), first)install(f'screenpipe-{second}.exe', valid_dir)self.assertEqual((valid_dir / 'acquisition-grant').read_text(), first)+ mixed_case_dir = root / 'mixed-case'+ install(f'ScreenPipe-{first}.EXE', mixed_case_dir)+ self.assertEqual((mixed_case_dir / 'acquisition-grant').read_text(), first)++ ads = ('[ZoneTransfer]\r\nZoneId=3\r\n'+ f'HostUrl=https://downloads.test/download/ticket/screenpipe-{second}.exe\r\n')+ ads_dir = root / 'ads-renamed'+ install('renamed.exe', ads_dir, ads)+ self.assertTrue((ads_dir / 'acquisition-grant').is_file(),+ [(p.name, p.read_text(errors='replace')) for p in ads_dir.iterdir()])+ self.assertEqual((ads_dir / 'acquisition-grant').read_text(), second)+ # A valid browser origin is preferred over a conflicting legacy+ # filename, while a previous install remains first-grant wins.+ conflict_dir = root / 'ads-conflict'+ install(f'screenpipe-{first}.exe', conflict_dir, ads)+ self.assertEqual((conflict_dir / 'acquisition-grant').read_text(), second)+ install('renamed-again.exe', conflict_dir,+ ads.replace(second, '11111111-1111-4111-8111-111111111111'))+ self.assertEqual((conflict_dir / 'acquisition-grant').read_text(), second)++ # Both incoming error states survive the absent, invalid, fallback,+ # and existing-grant branches while ordinary installation continues.+ for label, filename, zone, existing in [+ ('absent', 'renamed.exe', None, False),+ ('invalid', 'screenpipe-NOT-A-GRANT.exe',+ '[ZoneTransfer]\r\nHostUrl=http://invalid.test/x\r\n', False),+ ('fallback', f'screenpipe-{first}.exe', None, False),+ ('existing', f'screenpipe-{second}.exe', None, True)]:+ for initial_error in ('0', '1'):+ directory = root / f'canary-{label}-{initial_error}'+ if existing:+ directory.mkdir()+ (directory / 'acquisition-grant').write_text(first)+ install(filename, directory, zone, 'fixture-error.exe'+ if initial_error == '1' else 'fixture.exe', initial_error)+ if existing:+ self.assertEqual((directory / 'acquisition-grant').read_text(), first)++ host_prefix = 'HostUrl=https://downloads.test/download/'+ host_suffix = f'/screenpipe-{second}.exe'+ for logical_length, newline in [(1022, ''), (1023, ''), (1023, '\r\n')]:+ boundary_ads = ('[ZoneTransfer]\r\n' + host_prefix+ + ('x' * (logical_length - len(host_prefix) - len(host_suffix)))+ + host_suffix + newline)+ directory = root / f'ads-boundary-{logical_length}-{len(newline)}'+ install('renamed.exe', directory, boundary_ads)+ self.assertEqual((directory / 'acquisition-grant').read_text(), second)+ self.assertFalse((directory / 'acquisition-grant-diagnostic').exists(),+ (directory / 'acquisition-grant-diagnostic').read_text()+ if (directory / 'acquisition-grant-diagnostic').exists() else '')++ # An unrelated field may span as many fixed NSIS reads as the ADS+ # actually contains. It must not hide a later complete HostUrl.+ unrelated = ('[ZoneTransfer]\r\nReferrerUrl=https://referrer.test/'+ + ('r' * 2500) + '\r\n' + host_prefix + host_suffix + '\r\n')+ unrelated_dir = root / 'ads-overlong-referrer'+ install('renamed.exe', unrelated_dir, unrelated)+ self.assertEqual((unrelated_dir / 'acquisition-grant').read_text(), second)+ self.assertFalse((unrelated_dir / 'acquisition-grant-diagnostic').exists())++ overflow_length = 1024+ overflow_ads = ('[ZoneTransfer]\r\n' + host_prefix+ + ('x' * (overflow_length - len(host_prefix) - len(host_suffix)))+ + host_suffix + '\r\n')+ overflow_dir = root / 'ads-host-overflow'+ install(f'screenpipe-{first}.exe', overflow_dir, overflow_ads)+ self.assertEqual((overflow_dir / 'acquisition-grant').read_text(), first)+ self.assertEqual(+ (overflow_dir / 'acquisition-grant-diagnostic').read_text(),+ 'v1;host-url-overflow;actual-chars=1024;threshold-chars=1023;'+ 'fallback=filename;persistence=saved')++ fallback_cases = [+ '[ZoneTransfer]\r\nZoneId=3\r\n',+ '[ZoneTransfer]\r\nHostUrl=http://downloads.test/'+ f'screenpipe-{second}.exe\r\n',+ '[ZoneTransfer]\r\nHostUrl=https://downloads.test/?next=/'+ f'screenpipe-{second}.exe\r\n',+ '[ZoneTransfer]\r\nHostUrl=https://downloads.test/download/'+ f'screenpipe-{second}.exe\r\nHostUrl=https://downloads.test/download/'+ f'screenpipe-{second}.exe\r\n',+ '[Other]\r\nHostUrl=https://downloads.test/download/'+ f'screenpipe-{second}.exe\r\n',+ '[ZoneTransfer]\r\nHostUrl=https://downloads.test/download/'+ 'screenpipe-12345678-1234-4234-C234-123456789012.exe\r\n',+ '[ZoneTransfer]\r\nHostUrl=https://downloads.test/download/'+ 'screenpipe-ABCDEFAB-cdef-4abc-9def-abcdefabcdef.exe\r\n',+ '[ZoneTransfer]\r\nHostUrl=https://downloads.test/download/'+ 'screenpipe-abcdefab-cdef-4abc-Bdef-abcdefabcdef.exe\r\n',+ ]+ for index, malformed_ads in enumerate(fallback_cases):+ directory = root / f'ads-fallback-{index}'+ install(f'screenpipe-{first}.exe', directory, malformed_ads)+ self.assertEqual((directory / 'acquisition-grant').read_text(), first)+ diagnostic = directory / 'acquisition-grant-diagnostic'+ if index in {1, 2, 3, 5, 6, 7}:+ cause = ('duplicate-host-url' if index == 3 else 'malformed-host-url')+ self.assertEqual(+ diagnostic.read_text(),+ f'v1;{cause};fallback=filename;persistence=saved')+ self.assertNotIn(first, diagnostic.read_text())+ self.assertNotIn(second, diagnostic.read_text())+ else:+ self.assertFalse(diagnostic.exists())for index, name in enumerate([f'screenpipe-{carrier.PLACEHOLDER}.exe','screenpipe-12345678-1234-4234-7234-123456789012.exe','screenpipe-12345678-1234-4234-C234-123456789012.exe',+ 'screenpipe-ABCDEFAB-cdef-4abc-9def-abcdefabcdef.exe',+ 'screenpipe-abcdefab-cdef-4abc-Bdef-abcdefabcdef.exe','screenpipe.exe',]):directory = root / f'invalid-{index}'diff --git a/scripts/test_windows_browser_ads.ps1 b/scripts/test_windows_browser_ads.ps1new file mode 100644index 000000000..59d3255b9--- /dev/null+++ b/scripts/test_windows_browser_ads.ps1@@ -0,0 +1,446 @@+# screenpipe — AI that knows everything you've seen, said, or heard+# https://screenpipe.com+<#+.SYNOPSIS+Runs the Windows browser attribution acceptance path with actual Microsoft Edge.++.DESCRIPTION+Creates trusted, VM-local HTTPS and Authenticode fixture certificates, serves a+signed NSIS installer at the personalized download path, lets Edge download it,+renames it on NTFS, installs it, and verifies the acquisition grant. It does not+disable SmartScreen, attachment services, or zone metadata. Test certificates,+HTTP.sys bindings, browser data, downloads, and fixture files are removed.+#>+[CmdletBinding()]+param(+ [string]$OutputJson,+ [string]$EvidenceDirectory,+ [switch]$PrepareOnly+)++$ErrorActionPreference = 'Stop'+Set-StrictMode -Version Latest++Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type -AssemblyName System.Drawing+Add-Type -AssemblyName System.Windows.Forms++function Save-DesktopScreenshot([string]$Path) {+ if (-not $Path) { return }+ $bounds = [Windows.Forms.Screen]::PrimaryScreen.Bounds+ $bitmap = [Drawing.Bitmap]::new($bounds.Width, $bounds.Height)+ $graphics = [Drawing.Graphics]::FromImage($bitmap)+ try {+ $graphics.CopyFromScreen($bounds.Location, [Drawing.Point]::Empty, $bounds.Size)+ $bitmap.Save($Path)+ } finally {+ $graphics.Dispose()+ $bitmap.Dispose()+ }+}++function Wait-AutomationElement([Windows.Automation.ControlType]$Type, [string]$Name, [int]$Seconds = 60) {+ $rootElement = [Windows.Automation.AutomationElement]::RootElement+ $typeCondition = [Windows.Automation.PropertyCondition]::new(+ [Windows.Automation.AutomationElement]::ControlTypeProperty, $Type)+ $deadline = (Get-Date).AddSeconds($Seconds)+ while ((Get-Date) -lt $deadline) {+ $elements = $rootElement.FindAll([Windows.Automation.TreeScope]::Descendants, $typeCondition)+ foreach ($element in $elements) {+ if ($element.Current.Name -like $Name) { return $element }+ }+ Start-Sleep -Milliseconds 250+ }+ throw "Edge UI element did not appear: $Type $Name"+}++function Invoke-AutomationElement([Windows.Automation.AutomationElement]$Element) {+ $pattern = $Element.GetCurrentPattern([Windows.Automation.InvokePattern]::Pattern)+ $pattern.Invoke()+}++function Confirm-UncommonDownload([string]$Filename, [string]$EvidenceRoot, [string]$Label) {+ $warning = Wait-AutomationElement ([Windows.Automation.ControlType]::ListItem) `+ "$Filename isn't commonly downloaded*"+ $warningPath = $null+ if ($EvidenceRoot) { $warningPath = Join-Path $EvidenceRoot "$Label-warning.png" }+ Save-DesktopScreenshot $warningPath+ $warning.SetFocus()+ [Windows.Forms.SendKeys]::SendWait('+{F10}')+ Invoke-AutomationElement (Wait-AutomationElement ([Windows.Automation.ControlType]::MenuItem) 'Keep' 10)++ $confirmation = Wait-AutomationElement ([Windows.Automation.ControlType]::Window) `+ "Make sure you trust $Filename before you open it" 10+ $confirmationPath = $null+ if ($EvidenceRoot) { $confirmationPath = Join-Path $EvidenceRoot "$Label-confirmation.png" }+ Save-DesktopScreenshot $confirmationPath+ $deleteMenu = Wait-AutomationElement ([Windows.Automation.ControlType]::Button) 'Delete Open menu' 10+ $deleteMenu.SetFocus()+ [Windows.Forms.SendKeys]::SendWait('%{DOWN}')+ Invoke-AutomationElement (Wait-AutomationElement ([Windows.Automation.ControlType]::MenuItem) 'Keep anyway' 10)+}++function Resolve-Tool([string[]]$Candidates) {+ foreach ($candidate in $Candidates) {+ $command = Get-Command $candidate -ErrorAction SilentlyContinue+ if ($command) { return $command.Source }+ if (Test-Path -LiteralPath $candidate) { return $candidate }+ }+ throw "required tool not found: $($Candidates -join ', ')"+}++$edge = Resolve-Tool @('C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe')+$makensis = Resolve-Tool @('makensis.exe', 'C:\Program Files (x86)\NSIS\makensis.exe')+$signtool = Resolve-Tool @(+ 'signtool.exe',+ 'C:\Program Files (x86)\Windows Kits\10\bin\10.0.26100.0\x64\signtool.exe'+)+$root = Join-Path ([IO.Path]::GetTempPath()) ("screenpipe-edge-ads-" + [guid]::NewGuid())+$profile = Join-Path $root 'edge-profile'+$install = Join-Path $root 'installed'+$download = Join-Path ([Environment]::GetFolderPath('UserProfile')) 'Downloads'+$grant = [guid]::NewGuid().ToString().ToLowerInvariant()+$secondGrant = [guid]::NewGuid().ToString().ToLowerInvariant()+$filename = "screenpipe-$grant.exe"+$secondFilename = "screenpipe-$secondGrant.exe"+$downloaded = Join-Path $download $filename+$secondDownloaded = Join-Path $download $secondFilename+$existingPartials = @(Get-ChildItem -LiteralPath $download -Filter 'Unconfirmed *.crdownload' `+ -ErrorAction SilentlyContinue | ForEach-Object FullName)+$renamed = Join-Path $root 'renamed-installer.exe'+$secondRoot = Join-Path $root 'second-rename'+$secondRenamed = Join-Path $secondRoot 'renamed-installer.exe'+$port = Get-Random -Minimum 41000 -Maximum 49000+$fixtureHost = 'screenpipe-download.127.0.0.1.nip.io'+$ticket = 'eyJhbGciOiJFUzI1NiIsImtpZCI6ImZpeHR1cmUifQ.eyJwdXJwb3NlIjoiZG93bmxvYWQifQ.fixture-signature'+$url = "https://$fixtureHost`:$port/download/$ticket/$filename"+$secondUrl = "https://$fixtureHost`:$port/download/$ticket/$secondFilename"+$ordinaryUrl = "https://$fixtureHost`:$port/download?ticket=$ticket"+$appid = '{' + [guid]::NewGuid().ToString() + '}'+$serverCert = $null+$signingCert = $null+$serverJob = $null+$edgeProcess = $null+$recorder = $null+$urlAcl = "https://$fixtureHost`:$port/"++try {+ New-Item -ItemType Directory -Path $root,$profile,$install,$secondRoot -Force | Out-Null+ if ($EvidenceDirectory) { New-Item -ItemType Directory -Path $EvidenceDirectory -Force | Out-Null }+ Remove-Item -LiteralPath $downloaded,$secondDownloaded -Force -ErrorAction SilentlyContinue++ $fixture = Join-Path $root 'fixture.nsi'+ $hooks = (Resolve-Path (Join-Path $PSScriptRoot '..\apps\screenpipe-app-tauri\src-tauri\windows\hooks.nsh')).Path+ @"+; screenpipe — AI that knows everything you've seen, said, or heard+; https://screenpipe.com+Unicode true+SilentInstall silent+RequestExecutionLevel user+!include "$hooks"+Name "Screenpipe browser ADS fixture"+VIProductVersion "2.7.135.0"+VIAddVersionKey /LANG=1033 "ProductVersion" "2.7.135"+VIAddVersionKey /LANG=1033 "FileVersion" "2.7.135"+OutFile "fixture.exe"+InstallDir "`$TEMP\screenpipe-browser-ads-fixture"+Section+ CreateDirectory "`$INSTDIR"+ FileOpen `$0 "`$INSTDIR\installed" w+ FileWrite `$0 "ok"+ FileClose `$0+ StrCpy `$0 "c0"+ StrCpy `$1 "c1"+ StrCpy `$2 "c2"+ StrCpy `$3 "c3"+ StrCpy `$4 "c4"+ StrCpy `$5 "c5"+ StrCpy `$6 "c6"+ StrCpy `$7 "c7"+ StrCpy `$8 "c8"+ StrCpy `$9 "c9"+ StrCpy `$R0 "r0"+ StrCpy `$R1 "r1"+ StrCpy `$R2 "r2"+ StrCpy `$R3 "r3"+ StrCpy `$R4 "r4"+ StrCpy `$R5 "r5"+ StrCpy `$R6 "r6"+ StrCpy `$R7 "r7"+ SetErrors+ !insertmacro _SP_SaveAcquisitionGrant+ StrCpy `$R8 "0"+ IfErrors 0 +2+ StrCpy `$R8 "1"+ FileOpen `$R9 "`$INSTDIR\caller-state" w+ FileWrite `$R9 "`$0|`$1|`$2|`$3|`$4|`$5|`$6|`$7|`$8|`$9|`$R0|`$R1|`$R2|`$R3|`$R4|`$R5|`$R6|`$R7|`$R8"+ FileClose `$R9+SectionEnd+"@ | Set-Content -LiteralPath $fixture -Encoding utf8+ & $makensis '/V2' $fixture | Out-Null++ $serverCert = New-SelfSignedCertificate -DnsName $fixtureHost -CertStoreLocation 'Cert:\LocalMachine\My' `+ -FriendlyName 'Screenpipe browser ADS HTTPS fixture' -NotAfter (Get-Date).AddDays(1) `+ -TextExtension @('2.5.29.37={text}1.3.6.1.5.5.7.3.1')+ $signingCert = New-SelfSignedCertificate -Subject 'CN=Screenpipe browser ADS fixture' `+ -CertStoreLocation 'Cert:\LocalMachine\My' -FriendlyName 'Screenpipe browser ADS signing fixture' `+ -NotAfter (Get-Date).AddDays(1) -Type CodeSigningCert+ foreach ($cert in @($serverCert, $signingCert)) {+ $store = [Security.Cryptography.X509Certificates.X509Store]::new('Root', 'LocalMachine')+ $store.Open('ReadWrite'); $store.Add($cert); $store.Close()+ }+ $publisher = [Security.Cryptography.X509Certificates.X509Store]::new('TrustedPublisher', 'LocalMachine')+ $publisher.Open('ReadWrite'); $publisher.Add($signingCert); $publisher.Close()+ & $signtool sign /fd sha256 /sm /s My /sha1 $signingCert.Thumbprint (Join-Path $root 'fixture.exe') | Out-Null+ $signatureBefore = Get-AuthenticodeSignature -LiteralPath (Join-Path $root 'fixture.exe')+ if ($signatureBefore.Status -ne 'Valid') { throw "fixture signature is $($signatureBefore.Status)" }+ if ($EvidenceDirectory) {+ Copy-Item -LiteralPath (Join-Path $root 'fixture.exe') -Destination (Join-Path $EvidenceDirectory 'screenpipe_2.7.135_x64-setup.exe') -Force+ }+ $python = Resolve-Tool @('python.exe')+ $packager = (Resolve-Path (Join-Path $PSScriptRoot 'package-attribution-carrier.py')).Path+ $firstArtifact = Join-Path $root 'fixture-first.exe'+ $secondArtifact = Join-Path $root 'fixture-second.exe'+ $prepareScript = @'+import importlib.util, pathlib, struct, sys+spec = importlib.util.spec_from_file_location('carrier', sys.argv[1])+carrier = importlib.util.module_from_spec(spec); spec.loader.exec_module(carrier)+source_path = pathlib.Path(sys.argv[2])+with source_path.open('rb') as source:+ cert_offset, size_offset, certificate, relative_offset = carrier._prepare_windows_certificate(source, source_path.stat().st_size)+ source.seek(0); data = bytearray(source.read(cert_offset))+struct.pack_into('<I', data, size_offset, len(certificate))+data += certificate+offset = cert_offset + relative_offset+for grant, output in ((sys.argv[3], sys.argv[4]), (sys.argv[5], sys.argv[6])):+ patched = bytearray(data); patched[offset:offset+36] = grant.encode('ascii')+ pathlib.Path(output).write_bytes(patched)+'@+ & $python -c $prepareScript $packager (Join-Path $root 'fixture.exe') $grant $firstArtifact $secondGrant $secondArtifact+ if ($LASTEXITCODE -ne 0) { throw 'failed to prepare embedded certificate fixtures' }+ $fixtureHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $firstArtifact).Hash.ToLowerInvariant()+ $secondFixtureHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $secondArtifact).Hash.ToLowerInvariant()+ if ($EvidenceDirectory) {+ Copy-Item -LiteralPath $firstArtifact -Destination (Join-Path $EvidenceDirectory 'signed-carrier-template.exe') -Force+ Copy-Item -LiteralPath $secondArtifact -Destination (Join-Path $EvidenceDirectory 'signed-carrier-second.exe') -Force+ }+ if ($PrepareOnly) { return }++ & netsh.exe http add urlacl url=$urlAcl 'user=Everyone' | Out-Null+ & netsh.exe http add sslcert "ipport=0.0.0.0:$port" "certhash=$($serverCert.Thumbprint)" "appid=$appid" | Out-Null+ $serverJob = Start-Job -ArgumentList $urlAcl,$firstArtifact,$secondArtifact,$ordinaryUrl,$url,$secondUrl,$filename,$secondFilename -ScriptBlock {+ param($Prefix, $FirstArtifact, $SecondArtifact, $OrdinaryUrl, $FinalUrl, $SecondUrl, $Filename, $SecondFilename)+ $listener = [Net.HttpListener]::new()+ $listener.Prefixes.Add($Prefix)+ $listener.Start()+ try {+ foreach ($expected in @($OrdinaryUrl, $FinalUrl, $SecondUrl)) {+ $context = $listener.GetContext()+ if ($context.Request.Url.AbsoluteUri -ne $expected) {+ $context.Response.StatusCode = 404+ $context.Response.Close()+ throw "unexpected browser request path"+ }+ if ($expected -eq $OrdinaryUrl) {+ $context.Response.StatusCode = 302+ $context.Response.RedirectLocation = $FinalUrl+ $context.Response.Close()+ continue+ }+ $artifact = if ($expected -eq $FinalUrl) { $FirstArtifact } else { $SecondArtifact }+ $bytes = [IO.File]::ReadAllBytes($artifact)+ $servedFilename = if ($expected -eq $FinalUrl) { $Filename } else { $SecondFilename }+ $context.Response.StatusCode = 200+ $context.Response.ContentType = 'application/vnd.microsoft.portable-executable'+ $context.Response.Headers['Content-Disposition'] = "attachment; filename=`"$servedFilename`""+ $context.Response.ContentLength64 = $bytes.Length+ $context.Response.OutputStream.Write($bytes, 0, $bytes.Length)+ $context.Response.OutputStream.Close()+ }+ } finally {+ $listener.Stop()+ }+ }+ Start-Sleep -Seconds 2++ if ($EvidenceDirectory) {+ $recorderInfo = [Diagnostics.ProcessStartInfo]::new()+ $recorderInfo.FileName = 'ffmpeg.exe'+ $recorderInfo.Arguments = "-y -loglevel error -f gdigrab -framerate 15 -draw_mouse 1 -i desktop -c:v libx264 -preset ultrafast -pix_fmt yuv420p `"$(Join-Path $EvidenceDirectory 'edge-acceptance.mp4')`""+ $recorderInfo.UseShellExecute = $false+ $recorderInfo.RedirectStandardInput = $true+ $recorderInfo.CreateNoWindow = $true+ $recorder = [Diagnostics.Process]::new()+ $recorder.StartInfo = $recorderInfo+ if (-not $recorder.Start()) { throw 'short evidence recorder did not start' }+ Start-Sleep -Seconds 2+ }++ $edgeProcess = Start-Process -FilePath $edge -ArgumentList @(+ "--user-data-dir=$profile", '--no-first-run', '--disable-features=msEdgeFirstRunExperience', $ordinaryUrl+ ) -PassThru+ [void](Wait-AutomationElement ([Windows.Automation.ControlType]::ListItem) "$filename isn't commonly downloaded*" 60)+ Confirm-UncommonDownload $filename $EvidenceDirectory 'redirect-download'+ $deadline = (Get-Date).AddSeconds(90)+ while ((Get-Date) -lt $deadline -and -not (Test-Path -LiteralPath $downloaded)) {+ Start-Sleep -Milliseconds 500+ }+ if (-not (Test-Path -LiteralPath $downloaded)) {+ throw 'Edge did not complete the fixture download after normal visible confirmation'+ }+ # Edge may expose the final pathname briefly before its reputation scan has+ # finished the atomic replacement that attaches Zone.Identifier. Wait for a+ # stable file instead of racing that last browser-owned rename.+ $lastLength = -1+ do {+ $length = (Get-Item -LiteralPath $downloaded).Length+ Start-Sleep -Milliseconds 500+ $stable = $length -eq $lastLength -and -not (Test-Path -LiteralPath "$downloaded.crdownload")+ $lastLength = $length+ } while (-not $stable)+ $downloadHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $downloaded).Hash.ToLowerInvariant()+ if ($downloadHash -ne $fixtureHash) { throw 'Edge download SHA-256 differs from the signed fixture' }+ $zonePath = "$downloaded`:Zone.Identifier"+ if (-not (Test-Path -LiteralPath $zonePath)) { throw 'Edge download has no Zone.Identifier stream' }+ $zone = [IO.File]::ReadAllText($zonePath)+ $hostUrl = ($zone -split "`r?`n" | Where-Object { $_ -like 'HostUrl=*' } | Select-Object -First 1) -replace '^HostUrl=', ''+ if ($hostUrl -ne $url) { throw 'Edge HostUrl did not preserve the requested personalized URL' }+ $zoneId = ($zone -split "`r?`n" | Where-Object { $_ -like 'ZoneId=*' } | Select-Object -First 1) -replace '^ZoneId=', ''++ Move-Item -LiteralPath $downloaded -Destination $renamed+ if (-not (Test-Path -LiteralPath "$renamed`:Zone.Identifier")) {+ throw 'Zone.Identifier did not survive same-volume rename'+ }+ $signatureAfter = Get-AuthenticodeSignature -LiteralPath $renamed+ if ($signatureAfter.Status -ne 'Valid') { throw "renamed signature is $($signatureAfter.Status)" }+ if ([IO.File]::ReadAllText("$renamed`:Zone.Identifier") -ne $zone) {+ throw 'Zone.Identifier changed during same-volume rename'+ }+ if ($EvidenceDirectory) {+ [ordered]@{+ edge_version = [Diagnostics.FileVersionInfo]::GetVersionInfo($edge).ProductVersion+ architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()+ entry_url = $ordinaryUrl+ redirect_status = 302+ final_source = $url+ completed_filename = $filename+ fixture_sha256 = $fixtureHash+ edge_download_sha256 = $downloadHash+ authenticode_before = [string]$signatureBefore.Status+ authenticode_after_rename = [string]$signatureAfter.Status+ zone_id = $zoneId+ same_volume_ntfs_rename_preserved_zone_identifier = $true+ policies_changed = $false+ } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $EvidenceDirectory 'preinstall-facts.json') -Encoding utf8+ }+ $installer = Start-Process -FilePath $renamed -ArgumentList @('/S', "/D=$install") -Wait -PassThru+ if ($installer.ExitCode -ne 0) { throw "fixture installer exited $($installer.ExitCode)" }+ $zonePresentAfterExecution = Test-Path -LiteralPath "$renamed`:Zone.Identifier"+ $grantPath = Join-Path $install 'acquisition-grant'+ if (-not (Test-Path -LiteralPath $grantPath)) {+ $diagnosticPath = Join-Path $install 'acquisition-grant-diagnostic'+ $diagnostic = if (Test-Path -LiteralPath $diagnosticPath) { [IO.File]::ReadAllText($diagnosticPath) } else { 'missing' }+ throw "normal Windows execution consumed Zone.Identifier and the embedded certificate carrier did not preserve attribution: $diagnostic"+ }+ $received = [IO.File]::ReadAllText($grantPath)+ if ($received -ne $grant) { throw 'installed grant did not match the Edge HostUrl suffix' }+ $expectedCallerState = 'c0|c1|c2|c3|c4|c5|c6|c7|c8|c9|r0|r1|r2|r3|r4|r5|r6|r7|1'+ if ([IO.File]::ReadAllText((Join-Path $install 'caller-state')) -ne $expectedCallerState) {+ throw 'signed certificate path changed caller registers, stack, or initial error flag'+ }++ Start-Process -FilePath $edge -ArgumentList @("--user-data-dir=$profile", $secondUrl) | Out-Null+ [void](Wait-AutomationElement ([Windows.Automation.ControlType]::ListItem) "$secondFilename isn't commonly downloaded*" 60)+ Confirm-UncommonDownload $secondFilename $EvidenceDirectory 'direct-download'+ $deadline = (Get-Date).AddSeconds(90)+ while ((Get-Date) -lt $deadline -and -not (Test-Path -LiteralPath $secondDownloaded)) {+ Start-Sleep -Milliseconds 500+ }+ if (-not (Test-Path -LiteralPath $secondDownloaded)) {+ throw 'Edge did not complete the direct final-URL fixture download after confirmation'+ }+ $lastLength = -1+ do {+ $length = (Get-Item -LiteralPath $secondDownloaded).Length+ Start-Sleep -Milliseconds 500+ $stable = $length -eq $lastLength -and -not (Test-Path -LiteralPath "$secondDownloaded.crdownload")+ $lastLength = $length+ } while (-not $stable)+ if ((Get-FileHash -Algorithm SHA256 -LiteralPath $secondDownloaded).Hash.ToLowerInvariant() -ne $secondFixtureHash) {+ throw 'second Edge download SHA-256 differs from the signed fixture'+ }+ $secondZone = [IO.File]::ReadAllText("$secondDownloaded`:Zone.Identifier")+ $secondHostUrl = ($secondZone -split "`r?`n" | Where-Object { $_ -like 'HostUrl=*' } | Select-Object -First 1) -replace '^HostUrl=', ''+ if ($secondHostUrl -ne $secondUrl) { throw 'second Edge HostUrl did not preserve the direct final URL' }+ Move-Item -LiteralPath $secondDownloaded -Destination $secondRenamed+ $secondSignature = Get-AuthenticodeSignature -LiteralPath $secondRenamed+ if ($secondSignature.Status -ne 'Valid') { throw "second renamed signature is $($secondSignature.Status)" }+ $secondInstaller = Start-Process -FilePath $secondRenamed -ArgumentList @('/S', "/D=$install") -Wait -PassThru+ if ($secondInstaller.ExitCode -ne 0) { throw "second fixture installer exited $($secondInstaller.ExitCode)" }+ if ([IO.File]::ReadAllText((Join-Path $install 'acquisition-grant')) -ne $grant) {+ throw 'a later valid browser grant replaced the installed first grant'+ }+ if ([IO.File]::ReadAllText((Join-Path $install 'caller-state')) -ne $expectedCallerState) {+ throw 'existing-grant path changed caller registers, stack, or initial error flag'+ }+ $readback = (& pwsh.exe -NoProfile -Command "[IO.File]::ReadAllText('$($install.Replace("'", "''"))\acquisition-grant')")+ if ($LASTEXITCODE -ne 0 -or $readback -ne $grant) { throw 'fresh-process grant readback failed' }+ $installedScreenshot = $null+ if ($EvidenceDirectory) { $installedScreenshot = Join-Path $EvidenceDirectory 'installed-first-grant.png' }+ Save-DesktopScreenshot $installedScreenshot++ $result = [ordered]@{+ edge_version = [Diagnostics.FileVersionInfo]::GetVersionInfo($edge).ProductVersion+ windows = [Environment]::OSVersion.VersionString+ architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()+ filesystem = (Get-Volume -DriveLetter ([IO.Path]::GetPathRoot($root).Substring(0,1))).FileSystem+ entry_redirect_status = 302+ redirect_final_host_url_preserved = $true+ direct_final_host_url_preserved = $true+ completed_filename = $filename+ fixture_sha256 = $fixtureHash+ edge_download_sha256 = $downloadHash+ zone_stream = 'Zone.Identifier'+ zone_id = $zoneId+ host_url_preserved = $true+ same_volume_rename_preserved_stream = $true+ renamed_to_noncanonical_filename = ($renamed -notlike "*$filename")+ zone_identifier_present_after_normal_execution = $zonePresentAfterExecution+ embedded_certificate_carrier_after_execution = (-not $zonePresentAfterExecution)+ authenticode_before = [string]$signatureBefore.Status+ authenticode_after_rename = [string]$signatureAfter.Status+ installed_grant_matches_url_suffix = $true+ later_valid_grant_preserved_first = $true+ fresh_process_readback_preserved_first = $true+ visible_uncommon_download_confirmations = 2+ smartscreen_or_attachment_policy_disabled = $false+ }+ $json = $result | ConvertTo-Json -Depth 3+ if ($OutputJson) { $json | Set-Content -LiteralPath $OutputJson -Encoding utf8 }+ $json+} finally {+ if ($recorder -and -not $recorder.HasExited) {+ $recorder.StandardInput.WriteLine('q')+ if (-not $recorder.WaitForExit(10000)) { $recorder.Kill() }+ $recorder.Dispose()+ }+ if ($edgeProcess -and -not $edgeProcess.HasExited) {+ Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like "*$profile*" } |+ ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }+ }+ if ($serverJob) { Remove-Job $serverJob -Force -ErrorAction SilentlyContinue }+ & netsh.exe http delete sslcert "ipport=0.0.0.0:$port" 2>$null | Out-Null+ & netsh.exe http delete urlacl url=$urlAcl 2>$null | Out-Null+ foreach ($pair in @(@('TrustedPublisher',$signingCert), @('Root',$signingCert), @('Root',$serverCert), @('My',$signingCert), @('My',$serverCert))) {+ if ($pair[1]) {+ $store = [Security.Cryptography.X509Certificates.X509Store]::new($pair[0], 'LocalMachine')+ $store.Open('ReadWrite'); $store.Remove($pair[1]); $store.Close()+ }+ }+ Remove-Item -LiteralPath $downloaded,$secondDownloaded -Force -ErrorAction SilentlyContinue+ Get-ChildItem -LiteralPath $download -Filter 'Unconfirmed *.crdownload' -ErrorAction SilentlyContinue |+ Where-Object { $_.FullName -notin $existingPartials } |+ Remove-Item -Force -ErrorAction SilentlyContinue+ Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue+}