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
fix(macos): recover manual updates from retained legacy search (#7518)
Ezra Ellette5713950a1937
diff --git a/.github/scripts/build-macos-update-recovery.sh b/.github/scripts/build-macos-update-recovery.shnew file mode 100644index 000000000..e016183b9--- /dev/null+++ b/.github/scripts/build-macos-update-recovery.sh@@ -0,0 +1,50 @@+#!/usr/bin/env bash+# screenpipe — AI that knows everything you've seen, said, or heard+# https://screenpipe.com+set -euo pipefail++app="${1:?expected signed Screenpipe app}"+output="${2:?expected companion output directory}"+identity="${APPLE_SIGNING_IDENTITY:?expected signing identity}"+script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+codesign --verify --deep --strict "$app"+requirement="$(codesign -d -r- "$app" 2>&1 | sed -n 's/^designated => //p')"+[[ -n "$requirement" ]] || { echo 'app has no designated signing requirement' >&2; exit 1; }+helper="$output/Open updated Screenpipe.app"+mkdir -p "$helper/Contents/MacOS"++python3 - "$app" "$helper" "$requirement" <<'PY'+import pathlib, plistlib, sys+app, helper = map(pathlib.Path, sys.argv[1:3])+source = plistlib.loads((app / 'Contents/Info.plist').read_bytes())+plist = {+ 'CFBundleIdentifier': source['CFBundleIdentifier'] + '.update-recovery',+ 'CFBundleName': 'Open updated Screenpipe',+ 'CFBundleExecutable': 'update-recovery',+ 'CFBundlePackageType': 'APPL',+ 'CFBundleVersion': source['CFBundleVersion'],+ 'CFBundleShortVersionString': source['CFBundleShortVersionString'],+ 'LSMinimumSystemVersion': '12.0',+ 'LSUIElement': True,+ 'ScreenpipeTargetRequirement': sys.argv[3],+ 'ScreenpipeTargetBundleName': app.name,+ 'ScreenpipeManualHandoffProtocol': source['ScreenpipeManualHandoffProtocol'],+}+(helper / 'Contents/Info.plist').write_bytes(plistlib.dumps(plist))+PY+executable="$(/usr/libexec/PlistBuddy -c 'Print :CFBundleExecutable' "$app/Contents/Info.plist")"+architectures="$(lipo -archs "$app/Contents/MacOS/$executable")"+objects=()+for architecture in $architectures; do+ object="$output/update-recovery-$architecture"+ xcrun swiftc -O -swift-version 5 -target "$architecture-apple-macos12.0" \+ "$script_dir/macos-update-recovery.swift" -o "$object"+ objects+=("$object")+done+lipo -create "${objects[@]}" -output "$helper/Contents/MacOS/update-recovery"+rm "${objects[@]}"+timestamp=(--timestamp)+# VM development certificates cannot obtain Apple's production timestamp.+[[ "${SCREENPIPE_RECOVERY_DEVELOPMENT:-0}" == 1 ]] && timestamp=(--timestamp=none)+codesign --force --options runtime "${timestamp[@]}" --sign "$identity" "$helper"+codesign --verify --deep --strict "$helper"diff --git a/.github/scripts/create-headless-dmg.sh b/.github/scripts/create-headless-dmg.shindex 6da4b2f43..23c811932 100755--- a/.github/scripts/create-headless-dmg.sh+++ b/.github/scripts/create-headless-dmg.sh@@ -5,14 +5,19 @@set -euo pipefail-if [[ $# -ne 3 ]]; then- echo "usage: create-headless-dmg.sh <app-path> <output-dmg> <volume-name>" >&2+if [[ $# -lt 3 || $# -gt 4 ]]; then+ echo "usage: create-headless-dmg.sh <app-path> <output-dmg> <volume-name> [recovery-app]" >&2exit 2fiapp_path="$1"output_dmg="$2"volume_name="$3"+recovery_path="${4:-}"+if [[ -n "$recovery_path" ]]; then+ [[ -d "$recovery_path" ]] || { echo "recovery launcher missing: $recovery_path" >&2; exit 1; }+ codesign --verify --deep --strict "$recovery_path"+fiscript_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"repo_root="$(cd "$script_dir/../.." && pwd)"background_path="$repo_root/apps/screenpipe-app-tauri/src-tauri/assets/dmg-background.png"@@ -30,5 +35,6 @@ dmgbuild \-s "$settings_path" \-D "app_path=$app_path" \-D "background_path=$background_path" \+ -D "recovery_path=$recovery_path" \"$volume_name" \"$output_dmg"diff --git a/.github/scripts/dmgbuild-settings b/.github/scripts/dmgbuild-settingsindex 0c2dee05b..381469a46 100644--- a/.github/scripts/dmgbuild-settings+++ b/.github/scripts/dmgbuild-settings@@ -21,6 +21,15 @@ icon_locations = {"Applications": (480, 170),}hide_extensions = [app_name]+recovery_path = defines.get("recovery_path")+if recovery_path:+ recovery = Path(recovery_path).resolve()+ files.append(str(recovery))+ icon_size = 96+ icon_locations[app_name] = (180, 140)+ icon_locations["Applications"] = (480, 140)+ icon_locations[recovery.name] = (330, 250)+ hide_extensions.append(recovery.name)show_status_bar = Falseshow_tab_view = Falseshow_toolbar = Falsediff --git a/.github/scripts/finalize-macos-updater.sh b/.github/scripts/finalize-macos-updater.shindex 17ef0691c..614cc04dd 100644--- a/.github/scripts/finalize-macos-updater.sh+++ b/.github/scripts/finalize-macos-updater.sh@@ -6,6 +6,8 @@set -euo pipefailMACOS_DIR="${1:?expected macOS bundle directory}"APP_PROJECT="${2:?expected Tauri project directory}"+mode="${3:-updater}"+[[ "$mode" == updater || "$mode" == --app-only ]] || { echo "invalid finalization mode: $mode" >&2; exit 2; }notary_auth=(--apple-id "$APPLE_ID"--password "$APPLE_PASSWORD"@@ -100,10 +102,18 @@ for app in "${apps[@]}"; docodesign --verify --deep --strict --verbose=2 "$app"spctl --assess --type execute --verbose "$app"+ # The recovery companion is shipped in the DMG, never as an updater payload.+ if [[ "$mode" == --app-only ]]; then+ continue+ fi+# Keep the offline Gatekeeper invariant from #5036: archive the validated# app and sign these exact bytes, even when Tauri supplied the ticket.echo "Rebuilding ${APP_NAME}.tar.gz from the finalized app"- ( cd "$MACOS_DIR" && tar czf "${APP_NAME}.tar.gz" "$APP_NAME" )+ # The in-app Rust extractor does not restore xattrs/AppleDouble metadata.+ # Signatures must live in Mach-O bytes or the sealed Resources directory;+ # the stapled application ticket remains in Contents/CodeResources.+ ( cd "$MACOS_DIR" && COPYFILE_DISABLE=1 tar --no-xattrs -czf "${APP_NAME}.tar.gz" "$APP_NAME" )rm -f "${TARBALL}.sig"( cd "${APP_PROJECT}" && bunx tauri signer sign "$TARBALL" )test -s "${TARBALL}.sig"@@ -112,7 +122,7 @@ for app in "${apps[@]}"; do# the gate that would have rejected enterprise v2.5.145 because its# archive contained an unsigned mlx.metallib.VERIFY_DIR="$(mktemp -d)"- tar xzf "$TARBALL" -C "$VERIFY_DIR"+ COPYFILE_DISABLE=1 tar --no-xattrs -xzf "$TARBALL" -C "$VERIFY_DIR"EXTRACTED_APP="${VERIFY_DIR}/${APP_NAME}"codesign --verify --deep --strict --verbose=2 "$EXTRACTED_APP"xcrun stapler validate "$EXTRACTED_APP"diff --git a/.github/scripts/macos-update-recovery.swift b/.github/scripts/macos-update-recovery.swiftnew file mode 100644index 000000000..1f098c2b9--- /dev/null+++ b/.github/scripts/macos-update-recovery.swift@@ -0,0 +1,149 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++import Cocoa+import Security+import UniformTypeIdentifiers++// This companion is deliberately a separate app: Finder may send Reopen only+// to the old Screenpipe process when its bundle was replaced at the same path.+// It never terminates that process. The selected app owns authenticated handoff.+private let validationFlags = SecCSFlags(rawValue: kSecCSStrictValidate | kSecCSCheckNestedCode)++private func checked(_ status: OSStatus, _ operation: String) throws {+ if status != errSecSuccess {+ let message = SecCopyErrorMessageString(status, nil) as String? ?? "Unknown signing error"+ throw NSError(domain: "ScreenpipeUpdateRecovery", code: Int(status),+ userInfo: [NSLocalizedDescriptionKey: "\(operation): \(message) (\(status))"])+ }+}++private func verifiedCode(_ url: URL, requirement: SecRequirement? = nil) throws -> SecStaticCode {+ var code: SecStaticCode?+ try checked(SecStaticCodeCreateWithPath(url as CFURL, [], &code), "Read app signature")+ guard let code else { throw CocoaError(.fileReadCorruptFile) }+ try checked(SecStaticCodeCheckValidity(code, validationFlags, requirement), "Verify app signature")+ return code+}++private func signingInfo(_ code: SecStaticCode) throws -> [String: Any] {+ var info: CFDictionary?+ try checked(SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info),+ "Read signed app identity")+ return info as? [String: Any] ?? [:]+}++final class RecoveryDelegate: NSObject, NSApplicationDelegate {+ private var target = "not_selected"+ private var targetHash = "unknown"+ private var targetVersion = "unknown"+ private var source = "unknown"+ private var stage = "recovery_validation"++ // One bounded receipt, replaced atomically. Support collection prioritizes+ // update-recovery.log alongside update-install.log, even after log rotation.+ private func record(_ outcome: String, _ detail: String) {+ let environment = ProcessInfo.processInfo.environment+ let root = environment["SCREENPIPE_DATA_DIR"].flatMap { $0.isEmpty ? nil : URL(fileURLWithPath: $0) }+ ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".screenpipe")+ let line = "\(ISO8601DateFormatter().string(from: Date())) manual_recovery: stage=\(stage); source=\(source); target=\(target); target_version=\(targetVersion); target_hash=\(targetHash); outcome=\(outcome); cause=\(detail)\n"+ do {+ try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true,+ attributes: [.posixPermissions: 0o700])+ let receipt = root.appendingPathComponent("update-recovery.log")+ // Atomic replacement cannot follow an existing receipt symlink.+ try Data(line.prefix(4096).utf8).write(to: receipt, options: .atomic)+ try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: receipt.path)+ } catch {+ NSLog("Screenpipe recovery diagnostic could not be saved: %@", error.localizedDescription)+ }+ }++ private func fail(_ error: Error) {+ record("selected_copy_not_started", error.localizedDescription)+ let alert = NSAlert()+ alert.messageText = "Couldn’t open this Screenpipe copy"+ alert.informativeText = error.localizedDescription+ alert.addButton(withTitle: "OK")+ alert.runModal()+ NSApp.terminate(nil)+ }++ func applicationDidFinishLaunching(_ notification: Notification) {+ NSApp.setActivationPolicy(.accessory)+ NSApp.activate(ignoringOtherApps: true)+ do {+ let own = try verifiedCode(Bundle.main.bundleURL)+ let ownInfo = try signingInfo(own)+ let sourceID = ownInfo[kSecCodeInfoIdentifier as String] as? String ?? "unknown"+ let sourceHash = (ownInfo[kSecCodeInfoUnique as String] as? Data)?.map { String(format: "%02x", $0) }.joined() ?? "unknown"+ source = "\(sourceID),version=\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "unknown"),hash=\(sourceHash)"+ // This requirement is sealed into the companion when it is built+ // from the signed app. It retains the app's edition and publisher.+ guard let requirementText = Bundle.main.object(forInfoDictionaryKey: "ScreenpipeTargetRequirement") as? String else {+ throw CocoaError(.fileReadCorruptFile)+ }+ var requirement: SecRequirement?+ try checked(SecRequirementCreateWithString(requirementText as CFString, [], &requirement),+ "Read expected Screenpipe signing identity")+ guard let requirement else { throw CocoaError(.fileReadCorruptFile) }++ let panel = NSOpenPanel()+ panel.title = "Open updated Screenpipe"+ panel.message = "Quit Screenpipe first, then choose the updated app. It will open from its current location."+ panel.prompt = "Open update"+ panel.allowedContentTypes = [.applicationBundle]+ panel.canChooseDirectories = false+ panel.allowsMultipleSelection = false+ panel.treatsFilePackagesAsDirectories = false+ let downloadDirectory = Bundle.main.bundleURL.deletingLastPathComponent()+ let bundleName = Bundle.main.object(forInfoDictionaryKey: "ScreenpipeTargetBundleName") as? String ?? "screenpipe.app"+ let bundledApp = downloadDirectory.appendingPathComponent(bundleName)+ panel.directoryURL = FileManager.default.fileExists(atPath: bundledApp.path)+ ? downloadDirectory : URL(fileURLWithPath: "/Applications")+ guard panel.runModal() == .OK, let selected = panel.url else {+ record("cancelled", "user_cancelled")+ NSApp.terminate(nil)+ return+ }+ let url = selected.resolvingSymlinksInPath()+ target = url.path+ let info = try signingInfo(verifiedCode(url, requirement: requirement))+ let signedPlist = info[kSecCodeInfoPList as String] as? [String: Any]+ targetVersion = signedPlist?["CFBundleShortVersionString"] as? String ?? "unknown"+ guard let protocolVersion = signedPlist?["ScreenpipeManualHandoffProtocol"] as? Int,+ protocolVersion == Bundle.main.object(forInfoDictionaryKey: "ScreenpipeManualHandoffProtocol") as? Int else {+ throw NSError(domain: "ScreenpipeUpdateRecovery", code: 1, userInfo: [+ NSLocalizedDescriptionKey: "This is an older Screenpipe copy. Choose the updated app included with this download."+ ])+ }+ guard let hash = info[kSecCodeInfoUnique as String] as? Data else {+ throw CocoaError(.fileReadCorruptFile)+ }+ targetHash = hash.map { String(format: "%02x", $0) }.joined()+ let configuration = NSWorkspace.OpenConfiguration()+ configuration.createsNewApplicationInstance = true+ configuration.activates = true+ // The selected process rechecks this hash before any ownership+ // transfer, closing replacement races after the chooser verified it.+ configuration.environment = ["SCREENPIPE_MANUAL_HANDOFF_BUILD": targetHash]+ if let dataDirectory = ProcessInfo.processInfo.environment["SCREENPIPE_DATA_DIR"], !dataDirectory.isEmpty {+ configuration.environment["SCREENPIPE_DATA_DIR"] = dataDirectory+ }+ stage = "recovery_launch"+ record("launch_requested", "none")+ NSWorkspace.shared.openApplication(at: url, configuration: configuration) { app, error in+ DispatchQueue.main.async {+ if let error { self.fail(error); return }+ self.record("process_started", "pid=\(app?.processIdentifier ?? 0); authenticated_handoff_pending")+ NSApp.terminate(nil)+ }+ }+ } catch { fail(error) }+ }+}++let application = NSApplication.shared+let delegate = RecoveryDelegate()+application.delegate = delegate+application.run()diff --git a/.github/scripts/release-performance.test.ts b/.github/scripts/release-performance.test.tsindex 0a587b169..1f99e446f 100644--- a/.github/scripts/release-performance.test.ts+++ b/.github/scripts/release-performance.test.ts@@ -108,6 +108,8 @@ test("release workflows retain the router gate and use helpers from the workflowconst checkout = job.steps.find((s: any) => s.name === "Checkout macOS release helpers");expect(checkout.with.ref).toBe("${{ github.workflow_sha }}");expect(checkout.with["sparse-checkout"]).toContain(".github/scripts");+ expect(checkout.with["sparse-checkout"]).toContain("apps/screenpipe-app-tauri/scripts");+ expect(job.steps.some((s: any) => s.run?.includes('.release-workflow/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.js "$TARGET" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri"'))).toBe(true);expect(job.steps.some((s: any) => s.run?.includes(".release-workflow/.github/scripts/finalize-macos-updater.sh"))).toBe(true);}const steps = app.jobs["publish-tauri"].steps;@@ -141,7 +143,7 @@ esacf.stub("codesign", 'if [[ "${REJECT_EXTRACTED:-}" == 1 && "${@: -1}" != "$ORIGINAL_APP" ]]; then exit 1; fi\n');f.stub("spctl", ":\n");f.stub("bunx", 'if [[ "${FAIL_SIGN:-}" == 1 ]]; then exit 1; fi\necho fixture-signature > "$4.sig"\n');- const run = (extra = {}) => f.run("finalize-macos-updater.sh", [join(f.root, "bundle"), f.root], {+ const run = (extra = {}, args: string[] = []) => f.run("finalize-macos-updater.sh", [join(f.root, "bundle"), f.root, ...args], {APPLE_ID: "fixture", APPLE_PASSWORD: "fixture", APPLE_TEAM_ID: "fixture", MODE: mode, ORIGINAL_APP: app, ...extra,});return { ...f, app, run };@@ -165,3 +167,47 @@ test("updater signing failure fails the gate", () => {test("an invalid extracted bundle fails the gate even when the original app validated", () => {const f = notarization("valid"); expect(f.run({ REJECT_EXTRACTED: "1" }).status).not.toBe(0);});++test("recovery companion is notarized and assessed without becoming an updater payload", () => {+ const f = notarization("missing");+ expect(f.run({}, ["--app-only"]).status).toBe(0);+ expect(f.calls()).toContain("notarytool submit");+ expect(f.calls()).toContain("stapler validate");+ expect(existsSync(`${f.app}.tar.gz`)).toBe(false);+ expect(existsSync(`${f.app}.tar.gz.sig`)).toBe(false);+ const rejected = notarization("rejected");+ expect(rejected.run({}, ["--app-only"]).status).not.toBe(0);+});++test("recovery companion is included in consumer and enterprise DMGs on every Mac runner", () => {+ for (const name of ["release-app.yml", "release-enterprise.yml"]) {+ const workflow = Bun.YAML.parse(readFileSync(join(scripts, "../workflows", name), "utf8")) as any;+ const jobs = Object.values(workflow.jobs) as any[];+ const steps = jobs.flatMap(job => job.steps ?? []);+ const recovery = steps.find(step => step.name === "Build and notarize update recovery launcher");+ expect(recovery.run).toContain(".release-workflow/.github/scripts/build-macos-update-recovery.sh");+ expect(recovery.run).toContain("--app-only");+ const dmg = steps.find(step => step.name?.startsWith("Create headless DMG"));+ expect(dmg.if ?? "").not.toContain("self-hosted");+ expect(dmg.run).toContain('"${RECOVERY_ARGS[@]}"');+ }+});++// Use real tar/xattr with the fixture signing services to match the updater's+// filesystem semantics, rather than BSD tar silently restoring code metadata.+test.skipIf(process.platform !== "darwin")("updater archive does not depend on detached signature metadata", () => {+ const f = notarization("valid");+ const resources = join(f.app, "Contents/Resources"); mkdirSync(resources, { recursive: true });+ const shader = join(resources, "mlx.metallib"); writeFileSync(shader, "shader bytes");+ expect(spawnSync("xattr", ["-w", "com.apple.cs.CodeDirectory", "fixture metadata", shader]).status).toBe(0);+ expect(f.run().status).toBe(0);+ const archive = `${f.app}.tar.gz`;+ const entries = spawnSync("tar", ["-tzf", archive], { encoding: "utf8" });+ expect(entries.status).toBe(0);+ expect(entries.stdout).not.toContain("._");+ const extracted = join(f.root, "extract"); mkdirSync(extracted);+ expect(spawnSync("tar", ["-xzf", archive, "-C", extracted]).status).toBe(0);+ const restored = join(extracted, "screenpipe enterprise.app/Contents/Resources/mlx.metallib");+ expect(readFileSync(restored, "utf8")).toBe("shader bytes");+ expect(spawnSync("xattr", ["-p", "com.apple.cs.CodeDirectory", restored]).status).not.toBe(0);+});diff --git a/.github/workflows/release-app.yml b/.github/workflows/release-app.ymlindex 7edf29cee..849bb1f20 100644--- a/.github/workflows/release-app.yml+++ b/.github/workflows/release-app.yml@@ -276,6 +276,8 @@ jobs:sparse-checkout: |.github/actions/setup-persistent-macos-cache.github/scripts+ apps/screenpipe-app-tauri/scripts+ apps/screenpipe-app-tauri/src-tauri/assets/dmg-background.png- name: Recover runaway macOS builder servicesif: runner.environment == 'self-hosted' && matrix.os_type == 'macos'@@ -868,28 +870,7 @@ jobs:run: |set -euo pipefailTARGET="${{ matrix.target }}"- node <<'NODE'- const fs = require("fs");- const path = "apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json";- const target = process.env.TARGET;- const config = JSON.parse(fs.readFileSync(path, "utf8"));- config.bundle ??= {};- config.bundle.macOS ??= {};- config.bundle.externalBin = [...new Set(config.bundle.externalBin ?? [])]- .filter((entry) => entry !== "mlx.metallib");- if (target === "aarch64-apple-darwin") {- config.bundle.macOS.files = {};- config.bundle.externalBin.push("mlx.metallib");- } else if (target === "x86_64-apple-darwin") {- config.bundle.macOS.files = {- "MacOS/libonnxruntime.dylib": "libonnxruntime.dylib",- };- } else {- throw new Error(`unknown macOS release target: ${target}`);- }- fs.writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);- console.log(`macOS bundle sidecars configured for ${target}`);- NODE+ bun .release-workflow/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.js "$TARGET" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri"env:TARGET: ${{ matrix.target }}@@ -1446,10 +1427,8 @@ jobs:ficd apps/screenpipe-app-tauri- BUNDLE_ARGS=()- if [[ "${{ runner.environment }}" == "self-hosted" ]]; then- BUNDLE_ARGS=(--bundles app)- fi+ # Build the styled DMG below, including the signed recovery companion.+ BUNDLE_ARGS=(--bundles app)if bunx tauri build -v $TAURI_ARGS "${BUNDLE_ARGS[@]}" 2>&1 | tee /tmp/tauri-build-$attempt.log; thenecho "✅ Build succeeded on attempt $attempt"cd ../..@@ -1506,8 +1485,28 @@ jobs:doneecho "all .app bundles pass codesign --verify --deep --strict"+ - name: Build and notarize update recovery launcher+ if: matrix.os_type == 'macos'+ shell: bash+ env:+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ APPLE_ID: ${{ secrets.APPLE_ID }}+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ run: |+ set -euo pipefail+ BUNDLE_DIR="apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle"+ APP_PATH="${BUNDLE_DIR}/macos/screenpipe.app"+ # Older selected source revisions predate authenticated handoff.+ rm -rf "${BUNDLE_DIR}/recovery"+ if /usr/libexec/PlistBuddy -c 'Print :ScreenpipeManualHandoffProtocol' "$APP_PATH/Contents/Info.plist" >/dev/null 2>&1; then+ bash .release-workflow/.github/scripts/build-macos-update-recovery.sh "$APP_PATH" "${BUNDLE_DIR}/recovery"+ bash .release-workflow/.github/scripts/finalize-macos-updater.sh \+ "${BUNDLE_DIR}/recovery" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri" --app-only+ fi+- name: Create headless DMG (macOS)- if: matrix.os_type == 'macos' && runner.environment == 'self-hosted'+ if: matrix.os_type == 'macos'shell: bashrun: |set -euo pipefail@@ -1525,7 +1524,11 @@ jobs:esacAPP_PATH="${BUNDLE_DIR}/macos/screenpipe.app"DMG_PATH="${BUNDLE_DIR}/dmg/screenpipe_${VERSION}_${PACKAGE_ARCH}.dmg"- .github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe"+ RECOVERY_ARGS=()+ if [[ -d "${BUNDLE_DIR}/recovery/Open updated Screenpipe.app" ]]; then+ RECOVERY_ARGS=("${BUNDLE_DIR}/recovery/Open updated Screenpipe.app")+ fi+ bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe" "${RECOVERY_ARGS[@]}"- name: Notarize and staple DMGs (macOS)if: matrix.os_type == 'macos'diff --git a/.github/workflows/release-enterprise.yml b/.github/workflows/release-enterprise.ymlindex be228a7b9..cd47ba56d 100644--- a/.github/workflows/release-enterprise.yml+++ b/.github/workflows/release-enterprise.yml@@ -904,6 +904,8 @@ jobs:sparse-checkout: |.github/actions/setup-persistent-macos-cache.github/scripts+ apps/screenpipe-app-tauri/scripts+ apps/screenpipe-app-tauri/src-tauri/assets/dmg-background.png- name: Recover runaway macOS builder servicesif: runner.environment == 'self-hosted'@@ -989,28 +991,7 @@ jobs:TARGET: ${{ matrix.target }}run: |set -euo pipefail- node <<'NODE'- const fs = require("fs");- const path = "apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json";- const target = process.env.TARGET;- const config = JSON.parse(fs.readFileSync(path, "utf8"));- config.bundle ??= {};- config.bundle.macOS ??= {};- config.bundle.externalBin = [...new Set(config.bundle.externalBin ?? [])]- .filter((entry) => entry !== "mlx.metallib");- if (target === "aarch64-apple-darwin") {- config.bundle.macOS.files = {};- config.bundle.externalBin.push("mlx.metallib");- } else if (target === "x86_64-apple-darwin") {- config.bundle.macOS.files = {- "MacOS/libonnxruntime.dylib": "libonnxruntime.dylib",- };- } else {- throw new Error(`unknown macOS release target: ${target}`);- }- fs.writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`);- console.log(`macOS bundle sidecars configured for ${target}`);- NODE+ bun .release-workflow/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.js "$TARGET" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri"- name: Import signing cert into build keychainshell: bash@@ -1143,10 +1124,8 @@ jobs:ficd apps/screenpipe-app-tauri- BUNDLE_ARGS=()- if [[ "${{ runner.environment }}" == "self-hosted" ]]; then- BUNDLE_ARGS=(--bundles app)- fi+ # Build the styled DMG below, including the signed recovery companion.+ BUNDLE_ARGS=(--bundles app)if bunx tauri build -v --target "$TARGET" --features "${{ matrix.features }}" "${BUNDLE_ARGS[@]}" 2>&1 | tee /tmp/tauri-build-$attempt.log; thenecho "Build succeeded on attempt $attempt"cd ../..@@ -1192,8 +1171,26 @@ jobs:doneecho "All enterprise .app bundles pass strict codesign verification"+ - name: Build and notarize update recovery launcher+ shell: bash+ env:+ APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}+ APPLE_ID: ${{ secrets.APPLE_ID }}+ APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}+ APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}+ run: |+ set -euo pipefail+ BUNDLE_DIR="apps/screenpipe-app-tauri/src-tauri/target/${{ matrix.target }}/release/bundle"+ APP_PATH="${BUNDLE_DIR}/macos/screenpipe enterprise.app"+ # Older selected source revisions predate authenticated handoff.+ rm -rf "${BUNDLE_DIR}/recovery"+ if /usr/libexec/PlistBuddy -c 'Print :ScreenpipeManualHandoffProtocol' "$APP_PATH/Contents/Info.plist" >/dev/null 2>&1; then+ bash .release-workflow/.github/scripts/build-macos-update-recovery.sh "$APP_PATH" "${BUNDLE_DIR}/recovery"+ bash .release-workflow/.github/scripts/finalize-macos-updater.sh \+ "${BUNDLE_DIR}/recovery" "$GITHUB_WORKSPACE/apps/screenpipe-app-tauri" --app-only+ fi+- name: Create headless DMG- if: runner.environment == 'self-hosted'shell: bashrun: |set -euo pipefail@@ -1206,7 +1203,11 @@ jobs:VERSION=$(sed -n 's/^version = "\([^"]*\)"/\1/p' apps/screenpipe-app-tauri/src-tauri/Cargo.toml | head -1)APP_PATH="${BUNDLE_DIR}/macos/screenpipe enterprise.app"DMG_PATH="${BUNDLE_DIR}/dmg/screenpipe enterprise_${VERSION}_${{ matrix.package_arch }}.dmg"- .github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe enterprise"+ RECOVERY_ARGS=()+ if [[ -d "${BUNDLE_DIR}/recovery/Open updated Screenpipe.app" ]]; then+ RECOVERY_ARGS=("${BUNDLE_DIR}/recovery/Open updated Screenpipe.app")+ fi+ bash .release-workflow/.github/scripts/create-headless-dmg.sh "$APP_PATH" "$DMG_PATH" "screenpipe enterprise" "${RECOVERY_ARGS[@]}"- name: Notarize and staple DMGenv:diff --git a/apps/screenpipe-app-tauri/.gitignore b/apps/screenpipe-app-tauri/.gitignoreindex 0da184e40..eea462544 100644--- a/apps/screenpipe-app-tauri/.gitignore+++ b/apps/screenpipe-app-tauri/.gitignore@@ -66,3 +66,5 @@ ffprobe*# E2E: local hosted-AI gateway request mirror (see e2e/wdio.conf.ts).e2e-gateway-requests.json++/.macos-sidecars/diff --git a/apps/screenpipe-app-tauri/e2e/mock-updates/packaged-update-restart.e2e.ts b/apps/screenpipe-app-tauri/e2e/mock-updates/packaged-update-restart.e2e.tsindex 87bf513cd..6e2aabeaa 100644--- a/apps/screenpipe-app-tauri/e2e/mock-updates/packaged-update-restart.e2e.ts+++ b/apps/screenpipe-app-tauri/e2e/mock-updates/packaged-update-restart.e2e.ts@@ -36,10 +36,10 @@** Run (builds two release-local bundles; slow the first time):* cd apps/screenpipe-app-tauri- * bun e2e/mock-updates/packaged-update-restart.e2e.ts+ * bun run test:e2e:packaged-updater:macos** Skip the builds on re-runs (reuse workdir bundles + artifacts):- * SP_PACKAGED_UPDATER_SKIP_BUILD=1 bun e2e/mock-updates/packaged-update-restart.e2e.ts+ * SP_PACKAGED_UPDATER_SKIP_BUILD=1 bun run test:e2e:packaged-updater:macos** Isolation: dedicated data dir + ports (3061 API / 11461 control), a seed* marker env so the app treats itself as isolated (no chat migration), and@@ -222,6 +222,7 @@ async function todayLog(): Promise<string> {function launchApp(): ReturnType<typeof Bun.spawn> {const bin = path.join(installedApp(), 'Contents', 'MacOS', 'screenpipe-app');must('installed app binary exists', existsSync(bin), bin);+ verifyBundleSignature(installedApp());return Bun.spawn([bin], {cwd: WORKDIR,env: {@@ -241,6 +242,13 @@ function launchApp(): ReturnType<typeof Bun.spawn> {});}+function verifyBundleSignature(bundle: string): void {+ const verified = Bun.spawnSync(['codesign', '--verify', '--deep', '--strict', bundle], {+ stdout: 'pipe', stderr: 'pipe',+ });+ must('bundle passes full signature verification', verified.exitCode === 0, verified.stderr.toString().trim() || bundle);+}+function installedBundleVersion(): string {const plist = path.join(installedApp(), 'Contents', 'Info.plist');const proc = Bun.spawnSync(@@ -384,10 +392,17 @@ async function main(): Promise<void> {await sleep(250);}check('click acknowledged (menu → Installing update…)', sawInstalling);- check('restart committed (gate passed from idle)', sawRestartStarted);// Old process must exit (this is where the pre-fix build sat forever).await waitFor('old process exit', 60_000, async () => (app.exitCode !== null || app.signalCode !== null ? true : null), 200);+ // The verified installer can block the control server until exit. Preserve+ // the assertion using its durable commit receipt when that transient flag+ // cannot be sampled over HTTP.+ const restartReceipt = await readFile(path.join(DATA_DIR, 'update-install.log'), 'utf8');+ check(+ 'restart committed (gate passed from idle)',+ sawRestartStarted || restartReceipt.includes(`restart_committed: from=${oldVersion} target=${NEW_VERSION} `),+ );const exitAt = Date.now();log(`old process exited ${((exitAt - clickAt) / 1000).toFixed(1)}s after click`);@@ -406,14 +421,19 @@ async function main(): Promise<void> {// The swap really happened on disk, not just in process state.check('installed bundle Info.plist is new version', installedBundleVersion() === NEW_VERSION, installedBundleVersion());+ verifyBundleSignature(installedApp());// Scenario 3 log assertions: verified installer used; marker written + consumed.- const logAfter = await waitFor('log contains verified install', 30_000, async () => {+ const logAfter = await waitFor('log contains verified install and replacement boot', 30_000, async () => {const l = await todayLog();- return /staged update v[^\n]+ installed in /.test(l) ? l : null;+ return /staged update v[^\n]+ installed in /.test(l)+ && l.includes(`previous update install applied: ${oldVersion} → ${NEW_VERSION}`) ? l : null;});check('log: custom rename fast path was not used', !logAfter.includes('pre-extracted fast path'));- check('log: idle gate proceeded (not deferred)', /engine idle \(never started\)[^\n]*proceeding/.test(logAfter));+ // restart_for_update now reserves RESTART_SAFETY directly; the old+ // await_restart_gate log is no longer on this path. Idle was observed+ // immediately before the click above, and this records its commit.+ check('log: idle gate proceeded (not deferred)', logAfter.includes('banner restart: gate passed, shutting down for update'));check('log: update attempt recorded',logAfter.includes(`update attempt recorded: ${oldVersion} → ${NEW_VERSION}`),@@ -435,7 +455,7 @@ async function main(): Promise<void> {});must('post-update capture start accepted', captureResponse.ok);const captureResult = (await captureResponse.json()) as { started: boolean; error: string | null };- must('post-update capture session constructed', captureResult.started, captureResult.error ?? undefined);+ must('native post-update capture start requested', captureResult.started, captureResult.error ?? undefined);const captureHealth = await waitFor('post-update ScreenCaptureKit frame', 45_000, async () => {const health = await fetchHealth();return health?.frame_status === 'ok' && (health.pipeline?.capture_attempts ?? 0) > 0@@ -480,14 +500,22 @@ async function main(): Promise<void> {}),);app = launchApp();- const failedBoot = await waitFor('app up after synthetic failed attempt', 60_000, fetchState);+ // The HTTP driver comes up before UpdatesManager is installed. An empty+ // menu is startup in progress, not the failed-attempt outcome.+ const failedBoot = await waitFor('updater initialized after synthetic failed attempt', 60_000, async () => {+ const s = await fetchState();+ return s && s.app_version === NEW_VERSION && s.menu_text !== '' ? s : null;+ });check('failed attempt surfaced in menu',failedBoot.menu_text === "Update didn't apply — click to retry",failedBoot.menu_text,);check('failed-attempt menu is clickable', failedBoot.menu_enabled);- const failLog = await todayLog();+ const failLog = await waitFor('failed-attempt log flushed', 10_000, async () => {+ const log = await todayLog();+ return log.includes('previous update install did NOT apply') ? log : null;+ });check('log: failed attempt detected', failLog.includes('previous update install did NOT apply'));check('marker consumed (single-shot)',diff --git a/apps/screenpipe-app-tauri/knip.json b/apps/screenpipe-app-tauri/knip.jsonindex 9dd7b9045..93d88a3e5 100644--- a/apps/screenpipe-app-tauri/knip.json+++ b/apps/screenpipe-app-tauri/knip.json@@ -9,6 +9,7 @@"e2e/tests/**/*.js","e2e/helpers/**/*.ts","e2e/search-only.e2e.ts",+ "e2e/mock-updates/packaged-update-restart.e2e.ts","e2e/mock-updates/windows-persistence-server.ts","e2e/scripts/verify-spotlight-exclusion.ts","scripts/timeline-parity-export.ts",diff --git a/apps/screenpipe-app-tauri/package.json b/apps/screenpipe-app-tauri/package.jsonindex 5605c6f95..d67259403 100644--- a/apps/screenpipe-app-tauri/package.json+++ b/apps/screenpipe-app-tauri/package.json@@ -32,7 +32,7 @@"updater-local:serve": "bun ./e2e/mock-updates/updater-harness.ts serve","updater-local:stage-last": "bun ./e2e/mock-updates/updater-harness.ts stage-last","mock-updates": "bun ./e2e/mock-updates/updater-harness.ts serve",- "test:e2e:packaged-updater:macos": "bun ./e2e/mock-updates/packaged-update-restart.e2e.ts",+ "test:e2e:packaged-updater:macos": "bun scripts/native-build-queue.ts packaged-updater","test:e2e": "bun run wdio run e2e/wdio.conf.ts","test:e2e:tray-recording-toggle:macos": "SCREENPIPE_E2E_SEED=onboarding,no-audio,ignore-disk-pressure SCREENPIPE_PORT=3052 bun run wdio run e2e/wdio.conf.ts --spec e2e/specs/tray-recording-toggle.spec.ts","test:e2e:local-ai-gateway:macos": "SCREENPIPE_E2E_LOCAL_AI_GATEWAY=true bun run wdio run e2e/wdio.conf.ts --spec e2e/specs/chat-local-ai-gateway.spec.ts --spec e2e/specs/pipe-local-ai-gateway.spec.ts",diff --git a/apps/screenpipe-app-tauri/scripts/build_macos.sh b/apps/screenpipe-app-tauri/scripts/build_macos.shindex 61ca0f0d8..686b55ed5 100755--- a/apps/screenpipe-app-tauri/scripts/build_macos.sh+++ b/apps/screenpipe-app-tauri/scripts/build_macos.sh@@ -23,10 +23,12 @@ xattr -cr "$APP_PATH"# Sign the app manuallyIDENTITY="${APPLE_SIGNING_IDENTITY:-Apple Development: Louis Beaumont (NJ372MT773)}"-# Metal library signatures use extended attributes cleared above.-if [ -f "$APP_PATH/Contents/MacOS/mlx.metallib" ]; then- codesign --force --sign "$IDENTITY" "$APP_PATH/Contents/MacOS/mlx.metallib"-ficodesign --force --options runtime --entitlements src-tauri/entitlements.plist --sign "$IDENTITY" "$APP_PATH"+codesign --verify --deep --strict "$APP_PATH"++APPLE_SIGNING_IDENTITY="$IDENTITY" SCREENPIPE_RECOVERY_DEVELOPMENT=1 \+ bash ../../.github/scripts/build-macos-update-recovery.sh "$APP_PATH" \+ src-tauri/target/debug-dev/bundle/recovery+echo "Build completed successfully!"diff --git a/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.js b/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.jsnew file mode 100644index 000000000..fcaa83185--- /dev/null+++ b/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.js@@ -0,0 +1,54 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++import fs from 'node:fs/promises'+import path from 'node:path'++// Metal shaders are data, not Mach-O executables. Seal their bytes as a bundle+// resource; detached code signatures in xattrs do not survive updater archives.+// MLX's existing colocated lookup follows a relative link made BEFORE signing.+export async function stageMlxBundleResources(directory, source) {+ const resources = path.join(directory, 'Resources')+ const binaries = path.join(directory, 'MacOS')+ await fs.mkdir(resources, { recursive: true })+ await fs.mkdir(binaries, { recursive: true })+ const resource = path.join(resources, 'mlx.metallib')+ const link = path.join(binaries, 'mlx.metallib')+ await fs.rm(link, { force: true })+ await fs.rm(resource, { force: true })+ if (!source) return+ await fs.copyFile(source, resource)+ await fs.chmod(resource, 0o644)+ await fs.symlink('../Resources/mlx.metallib', link)+}++export function configureMacosSidecars(config, target) {+ if (!['aarch64-apple-darwin', 'x86_64-apple-darwin'].includes(target)) {+ throw new Error(`unknown macOS release target: ${target}`)+ }+ config.bundle ??= {}+ config.bundle.macOS ??= {}+ config.bundle.externalBin = [...new Set(config.bundle.externalBin ?? [])]+ .filter((entry) => entry !== 'mlx.metallib')+ const files = config.bundle.macOS.files ??= {}+ delete files['MacOS/mlx.metallib']+ delete files['MacOS/libonnxruntime.dylib']+ // Copy the directory, rather than a file, so Tauri preserves the symlink.+ files['.'] = '../.macos-sidecars'+ if (target === 'x86_64-apple-darwin') {+ files['MacOS/libonnxruntime.dylib'] = 'libonnxruntime.dylib'+ }+ return config+}++if (import.meta.main) {+ // Release workflows load this helper from the workflow revision while+ // building a separately selected source revision. Always target that project.+ const project = path.resolve(process.argv[3] ?? path.join(import.meta.dir, '..'))+ const target = process.argv[2]+ const configPath = path.join(project, 'src-tauri/tauri.macos.conf.json')+ const config = configureMacosSidecars(JSON.parse(await fs.readFile(configPath, 'utf8')), target)+ await stageMlxBundleResources(path.join(project, '.macos-sidecars'),+ target === 'aarch64-apple-darwin' ? path.join(project, 'src-tauri/mlx.metallib') : null)+ await fs.writeFile(configPath, `${JSON.stringify(config, null, 4)}\n`)+}diff --git a/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.test.ts b/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.test.tsnew file mode 100644index 000000000..a131e4a0e--- /dev/null+++ b/apps/screenpipe-app-tauri/scripts/macos_bundle_sidecars.test.ts@@ -0,0 +1,57 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++import { test, expect } from 'bun:test'+import fs from 'node:fs/promises'+import os from 'node:os'+import path from 'node:path'+import { configureMacosSidecars, stageMlxBundleResources } from './macos_bundle_sidecars.js'++test('MLX keeps its runtime lookup through an in-bundle resource link', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'screenpipe-metal-'))+ try {+ const source = path.join(root, 'shader')+ await fs.writeFile(source, 'shader bytes')+ const bundle = path.join(root, 'Contents')+ await stageMlxBundleResources(bundle, source)+ const lookup = path.join(bundle, 'MacOS/mlx.metallib')+ expect(await fs.readlink(lookup)).toBe('../Resources/mlx.metallib')+ expect(await fs.readFile(lookup, 'utf8')).toBe('shader bytes')+ await stageMlxBundleResources(bundle, null)+ expect(await fs.lstat(lookup).catch(() => null)).toBeNull()+ expect(await fs.stat(path.join(bundle, 'Resources/mlx.metallib')).catch(() => null)).toBeNull()+ } finally {+ await fs.rm(root, { recursive: true, force: true })+ }+})++test('release editions share the resource layout without losing localization or Intel ONNX', () => {+ const config = { bundle: { externalBin: ['bun', 'mlx.metallib'], macOS: { files: { Resources: '../.localization/macos-resources' } as Record<string, string> } } }+ configureMacosSidecars(config, 'aarch64-apple-darwin')+ expect(config.bundle.externalBin).toEqual(['bun'])+ expect(config.bundle.macOS.files['.']).toBe('../.macos-sidecars')+ expect(config.bundle.macOS.files.Resources).toBe('../.localization/macos-resources')+ configureMacosSidecars(config, 'x86_64-apple-darwin')+ expect(config.bundle.macOS.files['MacOS/libonnxruntime.dylib']).toBe('libonnxruntime.dylib')+ configureMacosSidecars(config, 'aarch64-apple-darwin')+ expect(config.bundle.macOS.files['MacOS/libonnxruntime.dylib']).toBeUndefined()+ expect(() => configureMacosSidecars(config, 'unknown')).toThrow()+})+++test('workflow helper stages and configures the selected source checkout', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'screenpipe-metal-cli-'))+ try {+ const native = path.join(root, 'src-tauri')+ await fs.mkdir(native)+ await fs.writeFile(path.join(native, 'mlx.metallib'), 'selected shader')+ await fs.writeFile(path.join(native, 'tauri.macos.conf.json'), JSON.stringify({ bundle: { externalBin: ['mlx.metallib'] } }))+ const run = Bun.spawnSync([process.execPath, path.join(import.meta.dir, 'macos_bundle_sidecars.js'), 'aarch64-apple-darwin', root])+ expect(run.exitCode).toBe(0)+ const config = JSON.parse(await fs.readFile(path.join(native, 'tauri.macos.conf.json'), 'utf8'))+ expect(config.bundle.externalBin).toEqual([])+ expect(await fs.readFile(path.join(root, '.macos-sidecars/MacOS/mlx.metallib'), 'utf8')).toBe('selected shader')+ } finally {+ await fs.rm(root, { recursive: true, force: true })+ }+})diff --git a/apps/screenpipe-app-tauri/scripts/native-build-queue.ts b/apps/screenpipe-app-tauri/scripts/native-build-queue.tsindex a9365848c..42aa9754d 100644--- a/apps/screenpipe-app-tauri/scripts/native-build-queue.ts+++ b/apps/screenpipe-app-tauri/scripts/native-build-queue.ts@@ -34,6 +34,7 @@ type BuildMode =| "build"| "e2e"| "signed"+ | "packaged-updater"| "test"| "persistence-test"| "persistence-release"@@ -361,6 +362,7 @@ function modeLabel(mode: BuildMode): string {case "build": return "one-shot debug-dev build";case "e2e": return "debug-dev E2E build";case "signed": return "signed debug-dev app build";+ case "packaged-updater": return "packaged macOS updater regression";case "test": return "queued native app tests";case "persistence-test": return "Windows persistence supervisor tests";case "persistence-release": return "Windows persistence supervisor release build";@@ -390,6 +392,9 @@ async function perform(mode: BuildMode, args: string[]): Promise<number> {], env);case "signed":return run(["bash", "scripts/build_macos.sh", "--queue-held"], env);+ case "packaged-updater":+ env.NEXT_PUBLIC_SCREENPIPE_E2E = "true";+ return run(["bun", "e2e/mock-updates/packaged-update-restart.e2e.ts", ...args], env);case "test": {const exitCode = await run(["bun", "scripts/pre_build.js"], env);if (exitCode !== 0) return exitCode;@@ -642,6 +647,7 @@ async function main(): Promise<number> {"build","e2e","signed",+ "packaged-updater","test","persistence-test","persistence-release",@@ -654,7 +660,7 @@ async function main(): Promise<number> {}console.error(- "usage: bun scripts/native-build-queue.ts <dev|build|e2e|signed|test|persistence-test|persistence-release|persistence-package|persistence-bundle|enterprise-bundle|status>",+ "usage: bun scripts/native-build-queue.ts <dev|build|e2e|signed|packaged-updater|test|persistence-test|persistence-release|persistence-package|persistence-bundle|enterprise-bundle|status>",);return 2;}diff --git a/apps/screenpipe-app-tauri/scripts/pre_build.js b/apps/screenpipe-app-tauri/scripts/pre_build.jsindex 7e4093fc9..d02e9b6fc 100644--- a/apps/screenpipe-app-tauri/scripts/pre_build.js+++ b/apps/screenpipe-app-tauri/scripts/pre_build.js@@ -8,6 +8,7 @@ import fs from 'fs/promises'import os from 'os'import path from 'path'import { setupOpenBlas } from './setup_openblas.js'+import { stageMlxBundleResources } from './macos_bundle_sidecars.js'import { downloadFile, find7z } from './find_tools.js'import { ensureCachedDirectory, ensureCachedFile } from './native_dependency_cache.js'@@ -326,7 +327,11 @@ async function populateZipBinary(url, destination, binaryName) {async function ensureMacosMlxMetallibSidecar() {const releaseTarget = process.env.SCREENPIPE_RELEASE_TARGETconst target = releaseTarget || (process.arch === 'arm64' ? 'aarch64-apple-darwin' : 'x86_64-apple-darwin')- if (target !== 'aarch64-apple-darwin') return+ const bundleResources = path.join(cwd, '../.macos-sidecars')+ if (target !== 'aarch64-apple-darwin') {+ await stageMlxBundleResources(bundleResources, null)+ return+ }const minSize = 1_000_000 // real metallib is ~84MBconst baseMetallib = path.join(cwd, 'mlx.metallib')@@ -347,7 +352,8 @@ async function ensureMacosMlxMetallibSidecar() {})await fs.chmod(sidecarMetallib, 0o755)await fs.copyFile(sidecarMetallib, baseMetallib)- console.log(`mlx.metallib sidecar ready at ${sidecarMetallib}`)+ await stageMlxBundleResources(bundleResources, baseMetallib)+ console.log(`mlx.metallib resource and runtime link ready at ${bundleResources}`)}async function linkSystemBinary(binaryName, destination) {diff --git a/apps/screenpipe-app-tauri/src-tauri/Info.plist b/apps/screenpipe-app-tauri/src-tauri/Info.plistindex 401bd0e53..51e54705d 100644--- a/apps/screenpipe-app-tauri/src-tauri/Info.plist+++ b/apps/screenpipe-app-tauri/src-tauri/Info.plist@@ -2,6 +2,8 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <key>ScreenpipeManualHandoffProtocol</key>+ <integer>1</integer><key>CGRequestScreenCaptureAccess</key><string>This app requires screen capture access to record the screen.</string><key>LSEnvironment</key>diff --git a/apps/screenpipe-app-tauri/src-tauri/build.rs b/apps/screenpipe-app-tauri/src-tauri/build.rsindex 6b0af3353..19a204ef4 100644--- a/apps/screenpipe-app-tauri/src-tauri/build.rs+++ b/apps/screenpipe-app-tauri/src-tauri/build.rs@@ -674,7 +674,7 @@ fn main() {build_native_timeline();// Stage macOS runtime sidecars into src-tauri/. Release builds bundle- // mlx.metallib as a Tauri externalBin on arm64 so Tauri signs it, and+ // mlx.metallib as a signed resource with a prebuilt runtime link, and// copy libonnxruntime.dylib via macOS.files on x86_64 for ort load-dynamic.stage_macos_sidecar_libs();@@ -984,7 +984,7 @@ fn stage_macos_sidecar_libs() {}/// Copy mlx.metallib to a known location so release packaging can bundle it as-/// a Tauri externalBin on aarch64 macOS builds. MLX compiles Metal shaders into+/// a signed resource on aarch64 macOS builds. MLX compiles Metal shaders into/// this file during mlx-sys build. Without it, parakeet-mlx crashes with/// "Failed to load the default metallib".#[cfg(target_os = "macos")]@@ -1007,7 +1007,7 @@ fn stage_mlx_metallib() {if needs_download {// Download mlx.metallib (pre-compiled MLX Metal shaders) for parakeet-mlx.// MLX needs this file next to the binary at runtime. The release- // workflow exposes the target-suffixed externalBin copy to Tauri.+ // prebuild stages the resource and its relative runtime link before signing.eprintln!("mlx-metallib: downloading from GitHub releases...");let url ="https://github.com/screenpipe/screenpipe/releases/download/mlx-metallib-v0.2.0/mlx.metallib";@@ -1028,7 +1028,7 @@ fn stage_mlx_metallib() {eprintln!("mlx-metallib: already present ({} MB)", size / 1_000_000);}- sign_macos_sidecar_if_needed(&metallib);+ // Shader data is sealed by the enclosing bundle, not a detached xattr signature.}/// Stage libonnxruntime.dylib for x86_64 Intel builds. ort `load-dynamic` resolvesdiff --git a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rsindex aeee78562..7e15ea514 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs@@ -79,7 +79,7 @@ fn owned_log_files(files: Vec<LogFile>) -> Vec<LogFile> {fn is_screenpipe_owned_log_name(name: &str) -> bool {crate::log_files::is_panic_log(name)|| name == crate::recording::recovery_log::LOG_NAME- || name == crate::update_diagnostics::LOG_NAME+ || crate::update_diagnostics::is_update_log(name)|| matches!(name,"screenpipe.log"diff --git a/apps/screenpipe-app-tauri/src-tauri/src/e2e/seeds.rs b/apps/screenpipe-app-tauri/src-tauri/src/e2e/seeds.rsindex c9faef757..3dbb22ade 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/e2e/seeds.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/e2e/seeds.rs@@ -50,6 +50,14 @@ pub(crate) async fn seed_database(db: &DatabaseManager) {}}+/// Local E2E fixture only; never used as evidence of real account authentication.+pub(crate) fn seed_cloud_authentication(store: &mut SettingsStore) {+ let token = "e2e-fake-token-onboarding-background-ai-tools".to_string();+ store.user.token = Some(token.clone());+ crate::auth_token::seed_cloud_token(Some(token));+ info!("E2E seed: synthetic cloud authentication enabled");+}+/// Apply deterministic settings mutations requested by `SCREENPIPE_E2E_SEED`.pub(crate) fn apply_settings(app: &AppHandle, store: &mut SettingsStore) {// E2E seed: when SCREENPIPE_E2E_SEED contains "no-recording", flip@@ -60,10 +68,7 @@ pub(crate) fn apply_settings(app: &AppHandle, store: &mut SettingsStore) {// lets Windows hosted runners exercise OCR without booting Whisper.let e2e_flags = flags();if e2e_flags.iter().any(|f| f == "cloud-authenticated") {- let token = "e2e-fake-token-onboarding-background-ai-tools".to_string();- store.user.token = Some(token.clone());- crate::auth_token::seed_cloud_token(Some(token));- info!("E2E seed: synthetic cloud authentication enabled");+ seed_cloud_authentication(store);}if e2e_flags.iter().any(|f| f == "no-recording") {store.recording.disable_audio = true;diff --git a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rsindex d779d4db0..274920559 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs@@ -127,7 +127,7 @@ pub(crate) async fn collect_log_files(dirs: &[PathBuf]) -> Vec<LogFile> {.is_some_and(|name| {is_panic_log(name)|| name == crate::recording::recovery_log::LOG_NAME- || name == crate::update_diagnostics::LOG_NAME+ || crate::update_diagnostics::is_update_log(name)}),std::cmp::Reverse(metadatadiff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex c720c3ad8..e831ac401 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -128,6 +128,8 @@ mod recording;mod remote_support_logs;mod remote_sync_commands;mod search_only;+#[cfg(any(target_os = "macos", test))]+mod manual_handoff;mod secrets;mod server;mod server_core;@@ -584,10 +586,23 @@ async fn main() {}}+ #[cfg(target_os = "macos")]+ if let Err(error) = manual_handoff::initialize().await {+ eprintln!("screenpipe: manual launch failed: {error:#}");+ return;+ }++ #[cfg(target_os = "macos")]+ let use_http_handoff = !manual_handoff::owns_launch();+ #[cfg(not(target_os = "macos"))]+ let use_http_handoff = true;++ // Packaged macOS launches already authenticated their owner above. Do not+ // let an unrelated edition at the shared focus port discard this launch.// Single-instance check: if sidecar server is already listening, hand off and exit.// This covers Linux (where tauri-plugin-single-instance is disabled due to// zbus/tokio conflict) and acts as a fallback on macOS/Windows.- {+ if use_http_handoff {let args: Vec<String> = std::env::args().collect();let deep_link_url = deep_link::url_from_args(&args);let launch_exe = std::env::current_exe()@@ -638,20 +653,7 @@ async fn main() {// Check if telemetry is disabled via store setting (analyticsEnabled)let store_path = screenpipe_core::paths::default_screenpipe_data_dir().join("store.bin");- let store_json = std::fs::read(&store_path).ok().and_then(|data| {- if data.len() >= 8 && &data[..8] == b"SPSTORE1" {- // The encrypted file is authoritative: every reader asks the OS- // vault for its existing key instead of relying on a separate flag.- let key = match secrets::get_key() {- secrets::KeyResult::Found(k) => k,- _ => return None,- };- let plain = screenpipe_vault::crypto::decrypt_small(&data[8..], &key).ok()?;- serde_json::from_slice::<serde_json::Value>(&plain).ok()- } else {- serde_json::from_slice::<serde_json::Value>(&data).ok()- }- });+ let store_json = store::read_startup_store(&store_path).ok();// Helper: look up a bool key in the store JSON (check both top-level and nested "settings")let store_bool = |key: &str| -> Option<bool> {store_json.as_ref().and_then(|data| {@@ -1072,6 +1074,10 @@ async fn main() {// an unrelated developer or CI app silently win before WebDriver starts.#[cfg(all(not(target_os = "linux"), not(feature = "e2e")))]let app = app.plugin(tauri_plugin_single_instance::init(|app, args, _cwd| {+ #[cfg(target_os = "macos")]+ if manual_handoff::pending() {+ return;+ }// Defer off event stack: plugin may invoke this from run loop (nounwind).let app_for_closure = app.clone();let args_clone = args.clone();@@ -1087,6 +1093,13 @@ async fn main() {// consume one plain main-app handoff from the short guard armed// during setup; normal subsequent launches retain Home behavior.let login_duplicate = should_suppress_startup_handoff(&args_clone);+ #[cfg(target_os = "macos")]+ if !login_duplicate+ && deep_link_url.is_none()+ && manual_handoff::reopen(&app_for_closure, "single_instance")+ {+ return;+ }if !crate::enterprise_policy::is_app_ui_hidden() && !login_duplicate {if crate::search_only::is_active() {crate::headless::wake_from_tray(&app_for_closure);@@ -1369,7 +1382,7 @@ async fn main() {// mlx.metallib and libonnxruntime.dylib are staged at build time// for macOS release bundling (see build.rs stage_macos_sidecar_libs).- // arm64 bundles mlx.metallib as a Tauri externalBin so Tauri signs it;+ // arm64 seals mlx.metallib in Resources with its lookup link made before signing;// x86_64 copies libonnxruntime.dylib via macOS.files.//// Previously this block created a symlink at Contents/MacOS/mlx.metallib@@ -2485,6 +2498,8 @@ async fn main() {sync::auto_start_retention(&app_handle_clone).await;});+ #[cfg(target_os = "macos")]+ manual_handoff::install(app.handle())?;Ok(())}).build(tauri::generate_context!())@@ -2621,20 +2636,10 @@ async fn main() {warn!("autostart: could not inspect macOS Reopen event: {error}")}}- // Defer off the event stack so run handler stays panic-free.- // Showing Onboarding is the app-entry gate: it focuses setup- // while incomplete and routes to Home once complete.- if crate::search_only::is_active() {- crate::headless::wake_from_tray(app_handle.app_handle());- }- if crate::enterprise_policy::is_app_ui_hidden() || crate::headless::is_dormant()- {+ if manual_handoff::reopen(app_handle.app_handle(), "native_reopen") {return;}- let app = app_handle.app_handle().clone();- let _ = app_handle.app_handle().run_on_main_thread(move || {- let _ = ShowRewindWindow::Onboarding.show(&app);- });+ manual_reopen(app_handle.app_handle());}_ => {}}@@ -2645,6 +2650,20 @@ async fn main() {});}+#[cfg(target_os = "macos")]+fn manual_reopen(app: &tauri::AppHandle) {+ if crate::search_only::is_active() {+ crate::headless::wake_from_tray(app);+ }+ if crate::enterprise_policy::is_app_ui_hidden() || crate::headless::is_dormant() {+ return;+ }+ let foreground = app.clone();+ let _ = app.run_on_main_thread(move || {+ let _ = ShowRewindWindow::Onboarding.show(&foreground);+ });+}+#[cfg(test)]mod autostart_arg_tests {use super::{diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rsnew file mode 100644index 000000000..7e8d40298--- /dev/null+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff.rs@@ -0,0 +1,199 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++//! A deliberate launch selects a build before either single-instance path runs.+//! The private socket authenticates the connecting process, never a supplied PID.++use serde::{Deserialize, Serialize};+use std::path::PathBuf;++const PROTOCOL: u32 = 1;++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+struct Identity {+ pid: i32,+ started: u64,+ uid: u32,+ identifier: String,+ version: String,+ hash: String,+ executable: PathBuf,+}++#[derive(Debug, PartialEq, Eq)]+enum Selection {+ Focus,+ Replace,+ Reject,+}++fn select(current: &Identity, candidate: &Identity) -> Selection {+ if current.uid != candidate.uid || current.identifier != candidate.identifier {+ return Selection::Reject;+ }+ if current.hash == candidate.hash {+ return Selection::Focus;+ }+ match (+ semver::Version::parse(¤t.version),+ semver::Version::parse(&candidate.version),+ ) {+ (Ok(mut old), Ok(mut new)) => {+ old.build = semver::BuildMetadata::EMPTY;+ new.build = semver::BuildMetadata::EMPTY;+ if new >= old {+ Selection::Replace+ } else {+ Selection::Reject+ }+ }+ _ => Selection::Reject,+ }+}++#[derive(Serialize, Deserialize)]+#[serde(deny_unknown_fields)]+struct Request {+ protocol: u32,+ replace: bool,+}++#[derive(Serialize, Deserialize)]+struct Response {+ protocol: u32,+ identity: Identity,+ outcome: String,+ error: Option<String>,+}++fn report_failure(root: &std::path::Path, stage: &str, error: &str) {+ crate::update_diagnostics::append(+ root,+ "manual_handoff_failed",+ &format!("stage={stage}; cause={error}; outcome=selected_copy_not_started"),+ );+}++#[cfg(target_os = "macos")]+mod macos;+#[cfg(target_os = "macos")]+pub(crate) use macos::{initialize, install, owns_launch, pending, reopen};++#[cfg(test)]+mod tests {+ use super::*;++ fn build(version: &str, hash: &str) -> Identity {+ Identity {+ pid: 10,+ started: 20,+ uid: 501,+ identifier: "screenpi.pe".into(),+ version: version.into(),+ hash: hash.into(),+ executable: "/Applications/screenpipe.app/Contents/MacOS/screenpipe-app".into(),+ }+ }++ #[test]+ fn file_identity_not_path_selects_replacement() {+ let old = build("2.7.95", "old");+ assert_eq!(select(&old, &old), Selection::Focus);+ assert_eq!(select(&old, &build("2.7.96", "new")), Selection::Replace);+ assert_eq!(+ select(&old, &build("2.7.95", "rebuilt")),+ Selection::Replace+ );+ let mut copied = old.clone();+ copied.executable = "/Volumes/download/screenpipe.app/Contents/MacOS/screenpipe-app".into();+ assert_eq!(select(&old, &copied), Selection::Focus);+ copied.hash = "new".into();+ assert_eq!(select(&old, &copied), Selection::Replace);+ }++ #[test]+ fn downgrades_unknown_versions_users_and_editions_cannot_take_over() {+ let old = build("2.7.95", "old");+ for version in ["2.7.94", "unknown", "2.7.95-beta.1"] {+ assert_eq!(select(&old, &build(version, "other")), Selection::Reject);+ }+ for edition in [+ "screenpi.pe.beta",+ "screenpi.pe.enterprise",+ "screenpi.pe.dev",+ ] {+ let mut new = build("2.7.96", "new");+ new.identifier = edition.into();+ assert_eq!(select(&old, &new), Selection::Reject);+ }+ let mut other_user = build("2.7.96", "new");+ other_user.uid += 1;+ assert_eq!(select(&old, &other_user), Selection::Reject);+ }++ #[tokio::test]+ async fn failure_survives_rotation_and_support_redaction() {+ let root = tempfile::tempdir().unwrap();+ report_failure(+ root.path(),+ "drain",+ "database shutdown timed out for [email protected]",+ );+ std::fs::write(+ root.path().join(crate::update_diagnostics::RECOVERY_LOG_NAME),+ "manual_recovery: stage=recovery_validation; cause=Verify app signature: code signature invalid (-67054); [email protected]; outcome=selected_copy_not_started\n",+ ).unwrap();+ for day in 1..=7 {+ std::fs::write(+ root.path()+ .join(format!("screenpipe-app.2026-10-{day:02}.log")),+ "restart\n",+ )+ .unwrap();+ }+ let report = crate::diagnostic_logs::collect_redacted_from_dirs(&[root.path().into()])+ .await+ .unwrap();+ assert!(report.contains("manual_handoff_failed"));+ assert!(report.contains("database shutdown timed out"));+ assert!(report.contains("selected_copy_not_started"));+ assert!(report.contains("manual_recovery"));+ assert!(report.contains("code signature invalid (-67054)"));+ assert!(!report.contains("[email protected]"));+ }++ /// Run only against a disposable guest after a real failed Finder launch.+ /// Exports the same redacted payload used by authorized support collection.+ #[tokio::test]+ #[ignore = "requires a real failed handoff in a disposable macOS guest"]+ async fn collect_vm_failure_for_support() {+ let root = std::env::var_os("HANDOFF_TEST_LOG_DIR").expect("guest log directory");+ let output = std::env::var_os("HANDOFF_TEST_REPORT").expect("redacted report destination");+ let report = crate::diagnostic_logs::collect_redacted_from_dirs(&[root.into()])+ .await+ .unwrap();+ let evidence = if std::env::var_os("HANDOFF_TEST_RECOVERY_LAUNCHER").is_some() {+ vec![+ "manual_recovery",+ "stage=recovery_validation",+ "source=",+ "target=",+ "cause=",+ "selected_copy_not_started",+ ]+ } else {+ vec![+ "manual_handoff_candidate",+ "source=",+ "target=",+ "manual_handoff_failed",+ "cannot authenticate the legacy search API",+ "selected_copy_not_started",+ ]+ };+ for evidence in evidence {+ assert!(report.contains(evidence), "support report lost {evidence}");+ }+ std::fs::write(output, report).unwrap();+ }+}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/kernel_signature.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/kernel_signature.rsnew file mode 100644index 000000000..8bc4ccab1--- /dev/null+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/kernel_signature.rs@@ -0,0 +1,278 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++//! Authenticate a process whose original bundle is no longer on disk. Never+//! treat replacement files as evidence about the executable already mapped by+//! the kernel. The CMS signature is checked by Security.framework, not by us.++use anyhow::{bail, Context, Result};+use core_foundation::{+ base::{CFType, CFTypeRef, TCFType},+ data::CFData,+};+use sha2::Digest;++#[link(name = "Security", kind = "framework")]+extern "C" {+ fn CMSDecoderCreate(decoder: *mut CFTypeRef) -> i32;+ fn CMSDecoderSetDetachedContent(decoder: CFTypeRef, data: CFTypeRef) -> i32;+ fn CMSDecoderUpdateMessage(decoder: CFTypeRef, data: *const u8, len: usize) -> i32;+ fn CMSDecoderFinalizeMessage(decoder: CFTypeRef) -> i32;+ fn CMSDecoderCopySignerStatus(+ decoder: CFTypeRef,+ index: usize,+ policy: CFTypeRef,+ evaluate_trust: u8,+ status: *mut u32,+ trust: *mut CFTypeRef,+ result: *mut i32,+ ) -> i32;+ fn CMSDecoderCopySignerCert(decoder: CFTypeRef, index: usize, cert: *mut CFTypeRef) -> i32;+ fn SecCertificateCopyData(cert: CFTypeRef) -> core_foundation::data::CFDataRef;+ fn SecPolicyCreateWithProperties(policy: CFTypeRef, properties: CFTypeRef) -> CFTypeRef;+ static kSecPolicyAppleCodeSigning: CFTypeRef;+}+extern "C" {+ fn csops(pid: i32, op: u32, data: *mut libc::c_void, len: usize) -> i32;+ fn csops_audittoken(+ pid: i32,+ op: u32,+ data: *mut libc::c_void,+ len: usize,+ audit: *const u32,+ ) -> i32;+}++fn word(data: &[u8], offset: usize) -> Result<usize> {+ Ok(u32::from_be_bytes(+ data.get(offset..offset + 4)+ .context("truncated kernel signature")?+ .try_into()?,+ ) as usize)+}++fn component(data: &[u8], slot: usize, magic: usize) -> Result<&[u8]> {+ if word(data, 0)? != 0xfade0cc0 || word(data, 4)? != data.len() {+ bail!("invalid kernel signature container");+ }+ let count = word(data, 8)?;+ if count > data.len().saturating_sub(12) / 8 {+ bail!("invalid signature index");+ }+ let mut found = None;+ for index in 0..count {+ if word(data, 12 + index * 8)? == slot {+ if found.is_some() {+ bail!("duplicate signature component");+ }+ let offset = word(data, 16 + index * 8)?;+ let len = word(data, offset + 4)?;+ if offset < 12 + count * 8 || len < 8 || word(data, offset)? != magic {+ bail!("invalid signature component");+ }+ found = Some(+ data.get(offset..offset.checked_add(len).context("signature overflow")?)+ .context("truncated signature component")?,+ );+ }+ }+ found.context("missing kernel signature component")+}++fn directory_identity(directory: &[u8], expected_hash: &str) -> Result<String> {+ let algorithm = *directory.get(37).context("truncated code directory")?;+ let digest = match algorithm {+ 1 => sha1::Sha1::digest(directory).to_vec(),+ 2 | 3 => sha2::Sha256::digest(directory).to_vec(),+ _ => bail!("unsupported running code digest {algorithm}"),+ };+ // Do not accept an alternative directory merely because it is present in+ // the blob. Only the primary directory verified by CMS is used here.+ if super::signing::hex(&digest[..20]) != expected_hash {+ bail!("CMS-signed directory does not match the running kernel code hash");+ }+ let offset = word(directory, 20)?;+ let tail = directory+ .get(offset..)+ .context("invalid signed identifier offset")?;+ let end = tail+ .iter()+ .position(|v| *v == 0)+ .context("unterminated signed identifier")?;+ Ok(std::str::from_utf8(&tail[..end])?.to_owned())+}++pub(super) fn verify(+ pid: i32,+ audit: Option<&[u32; 8]>,+ expected_identifier: &str,+ expected_cert: &[u8],+) -> Result<()> {+ let call = |op, buffer: &mut [u8]| unsafe {+ match audit {+ Some(token) => csops_audittoken(+ pid,+ op,+ buffer.as_mut_ptr().cast(),+ buffer.len(),+ token.as_ptr(),+ ),+ None => csops(pid, op, buffer.as_mut_ptr().cast(), buffer.len()),+ }+ };+ let mut status = [0; 4];+ if call(0, &mut status) != 0 || u32::from_ne_bytes(status) & 1 == 0 {+ bail!("running code is no longer valid");+ }+ let mut hash = [0; 20];+ if call(5, &mut hash) != 0 {+ bail!("cannot read authenticated kernel code hash");+ }+ let mut header = [0; 8];+ if call(10, &mut header) != -1+ || std::io::Error::last_os_error().raw_os_error() != Some(libc::ERANGE)+ {+ bail!("cannot read authenticated kernel signature size");+ }+ let len = word(&header, 4)?;+ if !(12..=1024 * 1024).contains(&len) {+ bail!("invalid kernel signature size");+ }+ let mut blob = vec![0; len];+ if call(10, &mut blob) != 0 {+ bail!("cannot read authenticated kernel signature");+ }+ verify_blob(+ &blob,+ &super::signing::hex(&hash),+ expected_identifier,+ expected_cert,+ )+}++fn verify_blob(blob: &[u8], hash: &str, identifier: &str, certificate: &[u8]) -> Result<()> {+ // CS_OPS_BLOB reports the allocated signature region, which can include+ // linker padding after the embedded SuperBlob. Parse only its declared+ // length; component offsets must still remain inside that signed container.+ let blob = signature_container(blob)?;+ let directory = component(blob, 0, 0xfade0c02)?;+ let cms = &component(blob, 0x10000, 0xfade0b01)?[8..];+ if directory_identity(directory, hash)? != identifier {+ bail!("different signed app edition");+ }+ unsafe {+ let mut raw = std::ptr::null();+ super::signing::check(CMSDecoderCreate(&mut raw))?;+ let decoder = CFType::wrap_under_create_rule(raw);+ let content = CFData::from_buffer(directory);+ super::signing::check(CMSDecoderSetDetachedContent(+ decoder.as_CFTypeRef(),+ content.as_CFTypeRef(),+ ))?;+ super::signing::check(CMSDecoderUpdateMessage(+ decoder.as_CFTypeRef(),+ cms.as_ptr(),+ cms.len(),+ ))?;+ super::signing::check(CMSDecoderFinalizeMessage(decoder.as_CFTypeRef()))?;+ let policy = SecPolicyCreateWithProperties(kSecPolicyAppleCodeSigning, std::ptr::null());+ if policy.is_null() {+ bail!("code signing trust policy unavailable");+ }+ let policy = CFType::wrap_under_create_rule(policy);+ let mut status = 0;+ let mut trust_result = 0;+ super::signing::check(CMSDecoderCopySignerStatus(+ decoder.as_CFTypeRef(),+ 0,+ policy.as_CFTypeRef(),+ 1,+ &mut status,+ std::ptr::null_mut(),+ &mut trust_result,+ ))?;+ if status != 1 || trust_result != 0 {+ bail!("running CMS signature or signing trust failed: status={status}, trust={trust_result}");+ }+ let mut cert = std::ptr::null();+ super::signing::check(CMSDecoderCopySignerCert(+ decoder.as_CFTypeRef(),+ 0,+ &mut cert,+ ))?;+ let cert = CFType::wrap_under_create_rule(cert);+ let data = CFData::wrap_under_create_rule(SecCertificateCopyData(cert.as_CFTypeRef()));+ if data.bytes() != certificate {+ bail!("running process has a different signing certificate");+ }+ }+ Ok(())+}++fn signature_container(blob: &[u8]) -> Result<&[u8]> {+ let len = word(blob, 4)?;+ if len < 12 || word(blob, 0)? != 0xfade0cc0 {+ bail!("invalid kernel signature container");+ }+ blob.get(..len)+ .context("truncated kernel signature container")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ #[ignore = "requires a signed process fixture captured inside a disposable macOS guest"]+ fn replaced_process_cms_still_authenticates_and_rejects_tampering() {+ let root =+ std::path::PathBuf::from(std::env::var_os("HANDOFF_TEST_SIGNATURE_DIR").unwrap());+ let blob = std::fs::read(root.join("signature.bin")).unwrap();+ let cert = std::fs::read(root.join("certificate.der")).unwrap();+ let hash = std::fs::read_to_string(root.join("hash.txt")).unwrap();+ verify_blob(&blob, hash.trim(), "screenpi.pe", &cert).unwrap();+ assert!(verify_blob(&blob, hash.trim(), "screenpi.pe.beta", &cert).is_err());+ assert!(verify_blob(&blob, hash.trim(), "screenpi.pe", b"different signer").is_err());+ let mut tampered = blob.clone();+ let directory = component(signature_container(&blob).unwrap(), 0, 0xfade0c02).unwrap();+ let offset = directory.as_ptr() as usize - blob.as_ptr() as usize;+ tampered[offset + 44] ^= 1;+ assert!(verify_blob(&tampered, hash.trim(), "screenpi.pe", &cert).is_err());+ let mut tampered = blob.clone();+ let cms = component(signature_container(&blob).unwrap(), 0x10000, 0xfade0b01).unwrap();+ let offset = cms.as_ptr() as usize - blob.as_ptr() as usize;+ tampered[offset + 8] ^= 1;+ assert!(verify_blob(&tampered, hash.trim(), "screenpi.pe", &cert).is_err());+ }+ #[test]+ fn malformed_kernel_signatures_fail_closed() {+ for bytes in [vec![], vec![0; 8], vec![255; 128]] {+ assert!(verify_blob(&bytes, "hash", "screenpi.pe", b"cert").is_err());+ }+ }+ #[test]+ fn kernel_allocation_padding_is_outside_the_signature_container() {+ let mut blob = Vec::new();+ blob.extend_from_slice(&0xfade0cc0u32.to_be_bytes());+ blob.extend_from_slice(&12u32.to_be_bytes());+ blob.extend_from_slice(&0u32.to_be_bytes());+ blob.resize(4096, 0);+ assert_eq!(signature_container(&blob).unwrap().len(), 12);+ blob[4..8].copy_from_slice(&4097u32.to_be_bytes());+ assert!(signature_container(&blob).is_err());+ }+ #[test]+ fn directory_hash_binds_the_running_identifier() {+ let mut directory = vec![0; 44];+ directory[20..24].copy_from_slice(&44u32.to_be_bytes());+ directory[37] = 2;+ directory.extend_from_slice(b"screenpi.pe\0");+ let hash = super::super::signing::hex(&sha2::Sha256::digest(&directory)[..20]);+ assert_eq!(+ directory_identity(&directory, &hash).unwrap(),+ "screenpi.pe"+ );+ directory[44] = b'x';+ assert!(directory_identity(&directory, &hash).is_err());+ }+}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rsnew file mode 100644index 000000000..0a78663e4--- /dev/null+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/macos.rs@@ -0,0 +1,880 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++use super::{report_failure, select, Identity, Request, Response, Selection, PROTOCOL};+use anyhow::{bail, Context, Result};+use fs2::FileExt;+use sha2::{Digest, Sha256};+use std::{+ fs::{File, OpenOptions},+ os::unix::{+ fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt},+ io::AsRawFd,+ },+ path::{Path, PathBuf},+ sync::{+ atomic::{AtomicBool, Ordering},+ Mutex, OnceLock,+ },+ time::Duration,+};+use tauri::Manager;+use tokio::{+ io::{AsyncBufReadExt, AsyncWriteExt, BufReader},+ net::{UnixListener, UnixStream},+};++#[path = "signing.rs"]+mod signing;+#[path = "kernel_signature.rs"]+mod kernel_signature;++const WAIT: Duration = Duration::from_secs(30);+const EXPECTED_BUILD_ENV: &str = "SCREENPIPE_MANUAL_HANDOFF_BUILD";+static RUNTIME: OnceLock<Runtime> = OnceLock::new();+static LAUNCH_LOCK: Mutex<Option<File>> = Mutex::new(None);+static PENDING: AtomicBool = AtomicBool::new(false);++struct Runtime {+ identity: Identity,+ requirement: String,+ socket: PathBuf,+ lock: PathBuf,+ root: PathBuf,+ executable_stamp: (u64, u64, i64, i64, u64),+}++pub(crate) fn owns_launch() -> bool {+ RUNTIME.get().is_some()+}+pub(crate) fn pending() -> bool {+ PENDING.load(Ordering::SeqCst)+}++fn manual_launch() -> bool {+ !std::env::args().any(|a| a == "--autostart" || a.contains("://"))+ && !std::env::var("XPC_SERVICE_NAME")+ .is_ok_and(|s| !s.starts_with("application.") && s.contains("screenpipe"))+}++fn private_directory(root: &Path, identifier: &str) -> Result<PathBuf> {+ let hash = Sha256::digest(format!("{}:{identifier}", root.display()).as_bytes());+ // Darwin sockaddr_un has only 104 bytes. Keep the owner-only path short.+ let digest = format!("{hash:x}");+ let directory = PathBuf::from(format!(+ "/tmp/screenpipe-handoff-{}-{}",+ unsafe { libc::geteuid() },+ &digest[..24]+ ));+ match std::fs::DirBuilder::new().mode(0o700).create(&directory) {+ Ok(()) => {}+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}+ Err(e) => return Err(e.into()),+ }+ let metadata = std::fs::symlink_metadata(&directory)?;+ if !metadata.is_dir()+ || metadata.uid() != unsafe { libc::geteuid() }+ || metadata.mode() & 0o077 != 0+ {+ bail!("unsafe instance directory");+ }+ Ok(directory)+}++async fn acquire(path: &Path) -> Result<File> {+ let file = OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW)+ .open(path)?;+ let start = std::time::Instant::now();+ loop {+ match file.try_lock_exclusive() {+ Ok(()) => return Ok(file),+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && start.elapsed() < WAIT => {+ tokio::time::sleep(Duration::from_millis(100)).await+ }+ Err(e) => return Err(e).context("another app launch has not finished"),+ }+ }+}++fn peer_token(stream: &UnixStream) -> Result<[u32; 8]> {+ // The kernel audit token includes pidversion, unlike LOCAL_PEERPID. Security+ // binds signature validation to the process that connected, even after PID reuse.+ let mut token = [0u32; 8];+ let mut len = std::mem::size_of_val(&token) as libc::socklen_t;+ let result = unsafe {+ libc::getsockopt(+ stream.as_raw_fd(),+ 0, /* SOL_LOCAL */+ 0x006, /* LOCAL_PEERTOKEN, sys/un.h */+ token.as_mut_ptr().cast(),+ &mut len,+ )+ };+ if result != 0 || len as usize != std::mem::size_of_val(&token) {+ bail!("could not authenticate local peer audit token");+ }+ Ok(token)+}++fn authenticated_peer(stream: &UnixStream, requirement: &str) -> Result<i32> {+ signing::verify_audit_token(&peer_token(stream)?, requirement)+}++async fn read_message<T: serde::de::DeserializeOwned>(stream: &mut UnixStream) -> Result<T> {+ let mut bytes = Vec::new();+ // A length cap prevents even a same-user local client from allocating unbounded memory.+ use tokio::io::AsyncReadExt;+ let mut reader = BufReader::new(stream.take(8193));+ tokio::time::timeout(WAIT, reader.read_until(b'\n', &mut bytes)).await??;+ if bytes.len() > 8192 || bytes.last() != Some(&b'\n') {+ bail!("invalid handoff message");+ }+ Ok(serde_json::from_slice(&bytes)?)+}++async fn write_message<T: serde::Serialize>(stream: &mut UnixStream, message: &T) -> Result<()> {+ let mut bytes = serde_json::to_vec(message)?;+ bytes.push(b'\n');+ tokio::time::timeout(WAIT, stream.write_all(&bytes)).await??;+ Ok(())+}++async fn exchange(runtime: &Runtime, replace: bool) -> Result<Option<Response>> {+ let mut stream = match UnixStream::connect(&runtime.socket).await {+ Ok(stream) => stream,+ Err(e)+ if matches!(+ e.kind(),+ std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused+ ) =>+ {+ return Ok(None)+ }+ Err(e) => return Err(e.into()),+ };+ let pid = authenticated_peer(&stream, &runtime.requirement)?;+ let stamp = signing::process_stamp(pid)?;+ let hash = signing::process_hash(pid)?;+ authenticated_peer(&stream, &runtime.requirement)?;+ write_message(+ &mut stream,+ &Request {+ protocol: PROTOCOL,+ replace,+ },+ )+ .await?;+ let response: Response = read_message(&mut stream).await?;+ if response.protocol != PROTOCOL+ || response.identity.pid != pid+ || response.identity.identifier != runtime.identity.identifier+ || (response.identity.uid, response.identity.started) != stamp+ || response.identity.hash != hash+ {+ bail!("instance identity changed during handshake");+ }+ Ok(Some(response))+}++async fn wait_for_exit(old: &Identity) -> Result<()> {+ wait_until_exit(old, WAIT).await?;+ // Match the existing updater's ScreenCaptureKit release interval.+ tokio::time::sleep(crate::process_exit::MACOS_UPDATER_RELAUNCH_SETTLE).await;+ Ok(())+}++async fn wait_until_exit(old: &Identity, timeout: Duration) -> Result<()> {+ tokio::time::timeout(timeout, async {+ while signing::process_stamp(old.pid).ok() == Some((old.uid, old.started)) {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .context("old process did not exit; replacement was not started")?;+ Ok(())+}++pub(crate) async fn initialize() -> Result<()> {+ // Match the single-instance plugin's existing E2E isolation: those builds+ // use separate data, API, and focus ports and must not inspect another app+ // as a legacy owner merely because it has the same signing identity.+ if cfg!(feature = "e2e") {+ return Ok(());+ }+ // Bare development/test executables do not participate in production ownership.+ let executable = std::env::current_exe()?;+ if !executable.components().any(|c| c.as_os_str() == "Contents") {+ return Ok(());+ }+ let root = screenpipe_core::paths::default_screenpipe_data_dir();+ let result = initialize_inner(root.clone()).await;+ if let Err(error) = &result {+ report_failure(&root, "launch", &format!("{error:#}"));+ show_error(&format!("Screenpipe couldn't open this copy. {error:#}"));+ }+ result+}++async fn initialize_inner(root: PathBuf) -> Result<()> {+ let requirement = signing::own_requirement()?;+ let identity = signing::running(std::process::id() as i32, &requirement)?;+ let verified = signing::on_disk(&identity.executable, &requirement, &identity)?;+ if verified.hash != identity.hash || verified.identifier != identity.identifier {+ bail!("opened bundle changed during launch");+ }+ if let Ok(expected) = std::env::var(EXPECTED_BUILD_ENV) {+ std::env::remove_var(EXPECTED_BUILD_ENV);+ if expected != identity.hash {+ bail!("replacement changed after verification; launch was cancelled");+ }+ }+ let directory = private_directory(&root, &identity.identifier)?;+ let executable_stamp = file_stamp(&identity.executable)?;+ let runtime = Runtime {+ identity,+ requirement,+ socket: directory.join("ipc"),+ lock: directory.join("launch"),+ executable_stamp,+ root,+ };+ let lock = acquire(&runtime.lock).await?;+ let existing = exchange(&runtime, false).await?;+ if let Some(old) = existing {+ record_selection(&runtime, &old.identity);+ let mut replaced = false;+ if manual_launch() {+ match select(&old.identity, &runtime.identity) {+ Selection::Replace => {+ verify_selected_bundle(&runtime)?;+ let reply = exchange(&runtime, true)+ .await?+ .context("old instance disappeared before handoff")?;+ if reply.outcome != "exiting" {+ bail!("{}", reply.error.unwrap_or(reply.outcome));+ }+ wait_for_exit(&old.identity).await?;+ replaced = true;+ }+ Selection::Reject => {+ bail!("the opened copy is older or belongs to a different edition")+ }+ Selection::Focus => {}+ }+ }+ if !replaced {+ // A verified identical build (or background/deep-link launch) must+ // never fall through to engine initialization if focus is unavailable.+ focus_existing(&old.identity).await?;+ std::process::exit(0);+ }+ } else if manual_launch() {+ legacy_takeover(&runtime).await?;+ }+ let _ = RUNTIME.set(runtime);+ *LAUNCH_LOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(lock);+ Ok(())+}++// Revalidate the selected bundle immediately before asking the old owner to exit.+fn verify_selected_bundle(runtime: &Runtime) -> Result<()> {+ let verified = signing::on_disk(+ &runtime.identity.executable,+ &runtime.requirement,+ &runtime.identity,+ )?;+ if verified.hash != runtime.identity.hash || verified.identifier != runtime.identity.identifier+ {+ bail!("opened bundle changed during launch");+ }+ Ok(())+}++async fn focus_existing(old: &Identity) -> Result<()> {+ let port = std::env::var("SCREENPIPE_FOCUS_PORT")+ .ok()+ .and_then(|p| p.parse().ok())+ .unwrap_or(11435);+ verify_listener(old.pid, port).await?;+ let args: Vec<String> = std::env::args().collect();+ let deep_link_url = crate::deep_link::url_from_args(&args);+ let response = reqwest::Client::builder()+ .no_proxy()+ .timeout(Duration::from_secs(3))+ .build()?+ .post(format!("http://127.0.0.1:{port}/focus"))+ .json(&serde_json::json!({+ "args": args, "deep_link_url": deep_link_url,+ "launchd_job_label": std::env::var("XPC_SERVICE_NAME").ok(),+ }))+ .send()+ .await?;+ response+ .error_for_status()+ .context("existing app could not accept this launch")?;+ Ok(())+}++fn record_selection(runtime: &Runtime, old: &Identity) {+ crate::update_diagnostics::append(+ &runtime.root,+ "manual_handoff_candidate",+ &format!(+ "source={}; target={}",+ serde_json::to_string(old).unwrap_or_default(),+ serde_json::to_string(&runtime.identity).unwrap_or_default()+ ),+ );+}++pub(crate) fn install(app: &tauri::AppHandle) -> Result<()> {+ let Some(runtime) = RUNTIME.get() else {+ return Ok(());+ };+ // The startup lock excludes other new builds. A stale socket has no live peer.+ if runtime.socket.exists() {+ std::fs::remove_file(&runtime.socket)?;+ }+ let listener = UnixListener::bind(&runtime.socket)?;+ std::fs::set_permissions(&runtime.socket, std::fs::Permissions::from_mode(0o600))?;+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ while let Ok((mut stream, _)) = listener.accept().await {+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(error) = serve(&app, runtime, &mut stream).await {+ report_failure(&runtime.root, "request", &format!("{error:#}"));+ }+ });+ }+ });+ LAUNCH_LOCK.lock().unwrap_or_else(|e| e.into_inner()).take();+ crate::update_diagnostics::append(+ &runtime.root,+ "manual_handoff_ready",+ &format!(+ "identity={}; requirement={}",+ serde_json::to_string(&runtime.identity).unwrap_or_default(),+ runtime.requirement+ ),+ );+ Ok(())+}++async fn serve(app: &tauri::AppHandle, runtime: &Runtime, stream: &mut UnixStream) -> Result<()> {+ let pid = authenticated_peer(stream, &runtime.requirement)?;+ let peer = signing::running(pid, &runtime.requirement)?;+ authenticated_peer(stream, &runtime.requirement)?;+ if peer.identifier != runtime.identity.identifier {+ bail!("different app edition");+ }+ let request: Request = read_message(stream).await?;+ if request.protocol != PROTOCOL {+ bail!("unsupported handoff protocol");+ }+ let mut response = Response {+ protocol: PROTOCOL,+ identity: runtime.identity.clone(),+ outcome: "running".into(),+ error: None,+ };+ if !request.replace {+ return write_message(stream, &response).await;+ }+ if select(&runtime.identity, &peer) != Selection::Replace {+ bail!("incoming build is not a replacement");+ }+ // Also validate all on-disk resources before the healthy owner gives up its API.+ let candidate = signing::on_disk(&peer.executable, &runtime.requirement, &peer)?;+ if candidate.hash != peer.hash {+ bail!("incoming bundle changed during launch");+ }+ match prepare(app).await {+ Ok(guard) => {+ if !signing::is_same_process(&peer) {+ recover(app);+ bail!("incoming process exited before handoff");+ }+ response.outcome = "exiting".into();+ if let Err(error) = write_message(stream, &response).await {+ recover(app);+ return Err(error);+ }+ crate::update_diagnostics::append(+ &runtime.root,+ "manual_handoff_drained",+ "outcome=exiting; staged_install=suppressed",+ );+ // Keep native initialization excluded until the process is gone.+ std::mem::forget(guard);+ tokio::time::sleep(Duration::from_millis(100)).await;+ crate::process_exit::force_process_exit(0);+ }+ Err(error) => {+ response.outcome = "failed".into();+ response.error = Some(format!("{error:#}"));+ write_message(stream, &response).await?;+ Err(error)+ }+ }+}++async fn prepare(app: &tauri::AppHandle) -> Result<tokio::sync::RwLockWriteGuard<'static, ()>> {+ if PENDING+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)+ .is_err()+ {+ bail!("handoff already in progress");+ }+ let mut drain_started = false;+ let result = async {+ if crate::db_recovery_notifications::recovery_active() {+ bail!("database recovery is still active");+ }+ if crate::search_only::is_entering() {+ bail!("Quit is still stopping capture; reopen this copy once Quit completes");+ }+ if !crate::search_only::is_active() {+ bail!("the existing copy is still active; quit it before switching builds");+ }+ let guard = crate::update_restart::RESTART_SAFETY+ .prepare_restart(WAIT)+ .await+ .context("native startup did not finish")?;+ crate::store::persist_store_before_restart(app).map_err(anyhow::Error::msg)?;+ // A manual launch must not inherit the automatic updater's hidden restart marker.+ crate::search_only::prepare_manual_handoff().map_err(anyhow::Error::msg)?;+ drain_started = true;+ match crate::recording::bounded_teardown(+ crate::recording::PRE_EXIT_TEARDOWN_TIMEOUT,+ async {+ crate::recording::stop_screenpipe(+ app.state::<crate::recording::RecordingState>(),+ app.clone(),+ )+ .await+ },+ )+ .await+ {+ crate::recording::TeardownOutcome::Completed => {}+ other => bail!("search shutdown did not complete: {other:?}"),+ }+ tokio::time::timeout(+ crate::recording::PRE_EXIT_TEARDOWN_TIMEOUT,+ crate::process_exit::run_pre_exit_teardown(app),+ )+ .await+ .context("remaining app shutdown timed out")?;+ Ok(guard)+ }+ .await;+ if result.is_err() {+ if drain_started {+ recover(app);+ } else {+ PENDING.store(false, Ordering::SeqCst);+ }+ }+ result+}++fn recover(app: &tauri::AppHandle) {+ PENDING.store(false, Ordering::SeqCst);+ crate::search_only::recover_after_failed_update(app.clone());+}++pub(crate) fn reopen(app: &tauri::AppHandle, trigger: &'static str) -> bool {+ if pending() {+ return true;+ }+ let Some(runtime) = RUNTIME.get() else {+ return false;+ };+ if file_stamp(&runtime.identity.executable).ok() == Some(runtime.executable_stamp) {+ return false;+ }+ let app = app.clone();+ tauri::async_runtime::spawn(async move {+ let result = async {+ let _lock = acquire(&runtime.lock).await?;+ let candidate = tokio::task::spawn_blocking(move || {+ signing::on_disk(+ &runtime.identity.executable,+ &runtime.requirement,+ &runtime.identity,+ )+ })+ .await??;+ crate::update_diagnostics::append(+ &runtime.root,+ "manual_handoff_reopen_candidate",+ &format!(+ "trigger={trigger}; source={:?}; target={:?}",+ runtime.identity, candidate+ ),+ );+ match select(&runtime.identity, &candidate) {+ Selection::Focus => {+ let foreground = app.clone();+ app.run_on_main_thread(move || crate::manual_reopen(&foreground))?;+ return Ok(());+ }+ Selection::Reject => bail!("the changed bundle is not a valid replacement"),+ Selection::Replace => {}+ }+ let guard = prepare(&app).await?;+ // Launch only after the old PID exits, with no shell interpolation of paths.+ let mut command = crate::process_exit::macos_updater_relaunch_command(+ &candidate.executable,+ std::iter::empty::<&str>(),+ std::process::id(),+ crate::process_exit::MACOS_UPDATER_RELAUNCH_SETTLE,+ );+ use std::os::unix::process::CommandExt;+ command+ .process_group(0)+ .env("SCREENPIPE_DATA_DIR", &runtime.root)+ .env(EXPECTED_BUILD_ENV, &candidate.hash);+ if let Err(error) = command.spawn() {+ recover(&app);+ return Err(+ anyhow::Error::new(error).context("could not launch replacement helper")+ );+ }+ std::mem::forget(guard);+ crate::process_exit::force_process_exit(0);+ #[allow(unreachable_code)]+ Ok::<(), anyhow::Error>(())+ }+ .await;+ if let Err(error) = result {+ report_failure(&runtime.root, trigger, &format!("{error:#}"));+ show_error(&format!(+ "Screenpipe couldn't switch to the replacement. {error:#}"+ ));+ }+ });+ true+}++fn file_stamp(path: &Path) -> Result<(u64, u64, i64, i64, u64)> {+ let m = std::fs::metadata(path)?;+ Ok((m.dev(), m.ino(), m.mtime(), m.mtime_nsec(), m.len()))+}++fn show_error(message: &str) {+ let _ = std::process::Command::new("/usr/bin/osascript")+ .args(["-e", "on run argv\ndisplay alert \"Screenpipe couldn't switch versions\" message (item 1 of argv)\nend run", "--", message]).spawn();+}++async fn legacy_takeover(runtime: &Runtime) -> Result<()> {+ let name = runtime+ .identity+ .executable+ .file_name()+ .context("missing executable name")?;+ for pid in signing::candidates(name)? {+ if let Err(error) = signing::verify_process(pid, &runtime.requirement) {+ if signing::claimed_identifier(pid).as_deref() == Some(&runtime.identity.identifier)+ || signing::process_path(pid).ok().as_ref() == Some(&runtime.identity.executable) {+ bail!("cannot authenticate the existing Screenpipe process {pid}: {error:#}");+ }+ continue;+ }+ let old = signing::running(pid, &runtime.requirement)?;+ if old.identifier != runtime.identity.identifier {+ continue;+ }+ record_selection(runtime, &old);+ match select(&old, &runtime.identity) {+ Selection::Focus => {+ focus_existing(&old).await?;+ std::process::exit(0);+ }+ Selection::Reject => bail!("the opened copy is older than the running build"),+ Selection::Replace => verify_selected_bundle(runtime)?,+ }+ let settings = crate::store::read_startup_store(&runtime.root.join("store.bin"))+ .map_err(anyhow::Error::msg)?;+ let settings = settings.get("settings").unwrap_or(&settings);+ let settings: crate::store::SettingsStore = serde_json::from_value(settings.clone())?;+ let data_dir = crate::config::selected_recording_data_dir(&settings.data_dir)?;+ let mut api = crate::recording::LocalApiContext {+ port: std::env::var("SCREENPIPE_PORT")+ .ok()+ .and_then(|p| p.parse().ok())+ .unwrap_or(settings.recording.port),+ api_key: std::env::var("SCREENPIPE_API_KEY")+ .ok()+ .filter(|k| !k.is_empty())+ .or_else(|| {+ (!settings.recording.api_key.is_empty()).then_some(settings.recording.api_key)+ }),+ };+ if api.api_key.is_none() {+ api.api_key =+ screenpipe_engine::auth_key::find_api_auth_key_for_data_dir(&data_dir).await;+ }+ if api.api_key.is_none() {+ bail!("cannot authenticate the legacy search API without its existing key");+ }+ verify_listener(pid, api.port).await?;+ verify_legacy_stopped(&api).await?;+ // Recheck both immediately before targeting the exact process. Never kill by name/port.+ verify_listener(pid, api.port).await?;+ verify_legacy_stopped(&api).await?;+ if !signing::is_same_process(&old) {+ bail!("legacy process changed before termination");+ }+ if unsafe { libc::kill(old.pid, libc::SIGTERM) } != 0 {+ return Err(std::io::Error::last_os_error()).context("legacy termination failed");+ }+ wait_for_exit(&old).await?;+ crate::update_diagnostics::append(+ &runtime.root,+ "manual_handoff_legacy_exited",+ "outcome=selected_copy_starting; capture=stopped",+ );+ }+ Ok(())+}++async fn verify_listener(pid: i32, port: u16) -> Result<()> {+ let output = tokio::time::timeout(+ Duration::from_secs(3),+ tokio::process::Command::new("/usr/sbin/lsof")+ .args([+ "-nP",+ "-a",+ "-p",+ &pid.to_string(),+ &format!("-iTCP:{port}"),+ "-sTCP:LISTEN",+ "-t",+ ])+ .output(),+ )+ .await??;+ if !output.status.success() || String::from_utf8_lossy(&output.stdout).trim() != pid.to_string()+ {+ bail!("legacy API listener does not belong to the verified app");+ }+ Ok(())+}++async fn verify_legacy_stopped(api: &crate::recording::LocalApiContext) -> Result<()> {+ let client = reqwest::Client::builder()+ .no_proxy()+ .timeout(Duration::from_secs(3))+ .build()?;+ let unauthenticated = client.get(api.url("/pipes")).send().await?;+ if !matches!(unauthenticated.status().as_u16(), 401 | 403) {+ bail!("legacy API does not enforce authentication; cannot verify search-only ownership");+ }+ // This read-only route is blocked by the shipped search-only middleware.+ let response = api.apply_auth(client.get(api.url("/pipes"))).send().await?;+ if response.status() != reqwest::StatusCode::CONFLICT+ || response.json::<serde_json::Value>().await?["error"] != "search_only"+ {+ bail!("legacy app is not in search-only mode");+ }+ for (route, field) in [+ ("/audio/device/status", "is_running"),+ ("/vision/device/status", "active"),+ ] {+ let response = api+ .apply_auth(client.get(api.url(route)))+ .send()+ .await?+ .error_for_status()?+ .json::<serde_json::Value>()+ .await?;+ let devices = response+ .as_array()+ .context("capture status is unavailable")?;+ if devices.iter().any(|d| d[field].as_bool() != Some(false)) {+ bail!("legacy capture has not stopped");+ }+ }+ let health = api+ .apply_auth(client.get(api.url("/health")))+ .send()+ .await?+ .error_for_status()?+ .json::<serde_json::Value>()+ .await?;+ if health["ui_recorder"]["running"].as_bool() != Some(false) {+ bail!("legacy UI capture has not been verified stopped");+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn socket_uses_os_peer_and_rejects_supplied_pid() {+ let (mut left, right) = UnixStream::pair().unwrap();+ let requirement = signing::own_requirement().unwrap();+ assert_eq!(+ authenticated_peer(&right, &requirement).unwrap(),+ std::process::id() as i32+ );+ left.write_all(b"{\"protocol\":1,\"replace\":true,\"pid\":1}\n")+ .await+ .unwrap();+ let mut right = right;+ assert!(read_message::<Request>(&mut right).await.is_err());+ }++ #[tokio::test]+ async fn stale_peer_process_generation_is_rejected() {+ let (_left, right) = UnixStream::pair().unwrap();+ let mut token = peer_token(&right).unwrap();+ token[7] = token[7].wrapping_add(1);+ assert!(signing::verify_audit_token(&token, &signing::own_requirement().unwrap()).is_err());+ }++ #[tokio::test]+ async fn oversized_request_is_rejected() {+ let (mut left, mut right) = UnixStream::pair().unwrap();+ let writer = tokio::spawn(async move { left.write_all(&vec![b'x'; 8193]).await });+ assert!(read_message::<Request>(&mut right).await.is_err());+ writer.await.unwrap().unwrap();+ }++ #[tokio::test]+ async fn concurrent_launches_cannot_hold_the_same_lease() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("launch");+ let first = acquire(&path).await.unwrap();+ let second = OpenOptions::new()+ .read(true)+ .write(true)+ .open(&path)+ .unwrap();+ assert_eq!(+ second.try_lock_exclusive().unwrap_err().kind(),+ std::io::ErrorKind::WouldBlock+ );+ drop(first);+ drop(second);+ // Other tests spawn processes. A fork can briefly inherit the locked+ // descriptor until exec closes it; the production lease retries this.+ let _next = acquire(&path).await.unwrap();+ }++ #[tokio::test]+ async fn live_owner_timeout_never_counts_as_exit() {+ let pid = std::process::id() as i32;+ let (uid, started) = signing::process_stamp(pid).unwrap();+ let mut old = Identity {+ pid,+ uid,+ started,+ identifier: "test".into(),+ version: "1.0.0".into(),+ hash: "unused".into(),+ executable: "test".into(),+ };+ assert!(wait_until_exit(&old, Duration::from_millis(5))+ .await+ .is_err());+ old.started -= 1;+ // PID reuse is not the old process surviving.+ wait_until_exit(&old, Duration::from_millis(5))+ .await+ .unwrap();+ }++ #[test]+ fn same_path_replacement_changes_file_stamp() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("app");+ std::fs::write(&path, "old").unwrap();+ let before = file_stamp(&path).unwrap();+ let replacement = dir.path().join("new");+ std::fs::write(&replacement, "new").unwrap();+ std::fs::rename(&replacement, &path).unwrap();+ assert_ne!(before, file_stamp(&path).unwrap());+ }++ #[tokio::test]+ async fn legacy_takeover_requires_authenticated_search_only_and_stopped_devices() {+ use axum::{routing::get, Json, Router};+ use serde_json::json;+ use std::sync::Arc;+ let active = Arc::new(AtomicBool::new(false));+ let audio_active = active.clone();+ let router =+ Router::new()+ .route(+ "/pipes",+ get(|headers: axum::http::HeaderMap| async move {+ if headers.get("authorization").and_then(|v| v.to_str().ok())+ == Some("Bearer handoff-test")+ {+ (+ axum::http::StatusCode::CONFLICT,+ Json(json!({"error":"search_only"})),+ )+ } else {+ (+ axum::http::StatusCode::UNAUTHORIZED,+ Json(json!({"error":"unauthorized"})),+ )+ }+ }),+ )+ .route(+ "/audio/device/status",+ get(move || {+ let audio_active = audio_active.clone();+ async move {+ Json(json!([{ "is_running": audio_active.load(Ordering::SeqCst) }]))+ }+ }),+ )+ .route(+ "/vision/device/status",+ get(|| async { Json(json!([{ "active":false }])) }),+ )+ .route(+ "/health",+ get(|| async { Json(json!({ "ui_recorder": {"running":false} })) }),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let listener = listener.into_std().unwrap();+ let server = tokio::spawn(async move {+ axum::Server::from_tcp(listener)+ .unwrap()+ .serve(router.into_make_service())+ .await+ .unwrap()+ });+ let mut api = crate::recording::LocalApiContext {+ port,+ api_key: Some("handoff-test".into()),+ };+ verify_legacy_stopped(&api).await.unwrap();+ active.store(true, Ordering::SeqCst);+ assert!(verify_legacy_stopped(&api)+ .await+ .unwrap_err()+ .to_string()+ .contains("capture has not stopped"));+ active.store(false, Ordering::SeqCst);+ api.api_key = Some("wrong-key".into());+ assert!(verify_legacy_stopped(&api).await.is_err());+ server.abort();+ }+}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/signing.rs b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/signing.rsnew file mode 100644index 000000000..236382ce9--- /dev/null+++ b/apps/screenpipe-app-tauri/src-tauri/src/manual_handoff/signing.rs@@ -0,0 +1,415 @@+// screenpipe — AI that knows everything you've seen, said, or heard+// https://screenpipe.com++use super::super::Identity;+use anyhow::{bail, Context, Result};+use core_foundation::{+ array::CFArray,+ base::{CFType, CFTypeRef, TCFType},+ data::CFData,+ dictionary::{CFDictionary, CFDictionaryRef},+ string::{CFString, CFStringRef},+ url::CFURL,+};+use security_framework::os::macos::code_signing::{+ Flags, GuestAttributes, SecCode, SecRequirement, SecStaticCode,+};+use std::{+ mem::size_of,+ path::{Path, PathBuf},+ sync::OnceLock,+};++static SIGNER: OnceLock<(String, Vec<u8>)> = OnceLock::new();++#[link(name = "Security", kind = "framework")]+extern "C" {+ fn SecCodeCopySigningInformation(+ code: CFTypeRef,+ flags: u32,+ info: *mut CFDictionaryRef,+ ) -> i32;+ fn SecCodeCopyDesignatedRequirement(+ code: CFTypeRef,+ flags: u32,+ requirement: *mut CFTypeRef,+ ) -> i32;+ fn SecRequirementCopyString(requirement: CFTypeRef, flags: u32, text: *mut CFStringRef) -> i32;+ static kSecCodeInfoIdentifier: CFStringRef;+ static kSecCodeInfoUnique: CFStringRef;+ static kSecCodeInfoPList: CFStringRef;+ static kSecCodeInfoCertificates: CFStringRef;+ fn SecCertificateCopyData(cert: CFTypeRef) -> core_foundation::data::CFDataRef;+}+extern "C" {+ fn csops(pid: i32, operation: u32, address: *mut libc::c_void, size: usize) -> i32;+}++pub(super) fn check(status: i32) -> Result<()> {+ if status != 0 {+ bail!("code signature status {status}");+ }+ Ok(())+}++fn information(code: CFTypeRef) -> Result<(String, String, String)> {+ unsafe {+ let mut raw = std::ptr::null();+ check(SecCodeCopySigningInformation(code, 1 << 1, &mut raw))?;+ let info = CFDictionary::<CFString, CFType>::wrap_under_create_rule(raw);+ let identifier = info+ .find(&CFString::wrap_under_get_rule(kSecCodeInfoIdentifier))+ .and_then(|v| v.downcast::<CFString>())+ .context("signature has no identifier")?+ .to_string();+ let hash = info+ .find(&CFString::wrap_under_get_rule(kSecCodeInfoUnique))+ .and_then(|v| v.downcast::<CFData>())+ .context("signature has no code hash")?;+ let plist = info+ .find(&CFString::wrap_under_get_rule(kSecCodeInfoPList))+ .and_then(|v| v.downcast::<CFDictionary>())+ .context("signature has no secured bundle metadata")?;+ let plist =+ CFDictionary::<CFString, CFType>::wrap_under_get_rule(plist.as_concrete_TypeRef());+ let version = plist+ .find(&CFString::new("CFBundleShortVersionString"))+ .and_then(|v| v.downcast::<CFString>())+ .context("bundle has no version")?+ .to_string();+ Ok((identifier, hex(hash.bytes()), version))+ }+}++pub(super) fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++pub(super) fn process_stamp(pid: i32) -> Result<(u32, u64)> {+ let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };+ let len = unsafe {+ libc::proc_pidinfo(+ pid,+ libc::PROC_PIDTBSDINFO,+ 0,+ (&mut info as *mut libc::proc_bsdinfo).cast(),+ size_of::<libc::proc_bsdinfo>() as i32,+ )+ };+ if len != size_of::<libc::proc_bsdinfo>() as i32 {+ bail!("process {pid} is unavailable");+ }+ Ok((+ info.pbi_uid,+ info.pbi_start_tvsec * 1_000_000 + info.pbi_start_tvusec,+ ))+}++pub(super) fn process_hash(pid: i32) -> Result<String> {+ let mut hash = [0u8; 20];+ if unsafe {+ csops(+ pid,+ 5, /* CS_OPS_CDHASH */+ hash.as_mut_ptr().cast(),+ hash.len(),+ )+ } != 0+ {+ return Err(std::io::Error::last_os_error()).context("read running code hash");+ }+ Ok(hex(&hash))+}++pub(super) fn is_same_process(identity: &Identity) -> bool {+ process_stamp(identity.pid).ok() == Some((identity.uid, identity.started))+ && process_hash(identity.pid).ok().as_deref() == Some(&identity.hash)+}++fn guest(pid: i32) -> Result<SecCode> {+ let mut attrs = GuestAttributes::new();+ attrs.set_pid(pid);+ Ok(SecCode::copy_guest_with_attribues(+ None,+ &attrs,+ Flags::NONE,+ )?)+}++pub(super) fn claimed_identifier(pid: i32) -> Option<String> {+ // Unverified metadata can only make a failed authentication visible. It+ // never authorizes termination or establishes the running build identity.+ let code = guest(pid).ok()?;+ unsafe {+ let mut raw = std::ptr::null();+ check(SecCodeCopySigningInformation(+ code.as_CFTypeRef(),+ 0,+ &mut raw,+ ))+ .ok()?;+ let info = CFDictionary::<CFString, CFType>::wrap_under_create_rule(raw);+ info.find(&CFString::wrap_under_get_rule(kSecCodeInfoIdentifier))+ .and_then(|v| v.downcast::<CFString>())+ .map(|v| v.to_string())+ }+}++pub(super) fn verify_process(pid: i32, requirement: &str) -> Result<()> {+ let requirement: SecRequirement = requirement.parse()?;+ if guest(pid)?+ .check_validity(Flags::NONE, &requirement)+ .is_ok()+ {+ return Ok(());+ }+ verify_replaced_process(pid, None)+}++fn verify_replaced_process(pid: i32, audit: Option<&[u32; 8]>) -> Result<()> {+ let (identifier, certificate) = SIGNER+ .get()+ .context("verified app signing certificate unavailable")?;+ super::kernel_signature::verify(pid, audit, identifier, certificate)+ .context("authenticate original running signature after bundle replacement")+}++pub(super) fn verify_audit_token(token: &[u32; 8], requirement: &str) -> Result<i32> {+ // audit_token_t fields: auid, euid, egid, ruid, rgid, pid, asid, pidversion.+ let pid = token[5] as i32;+ if token[1] != unsafe { libc::geteuid() } || pid <= 0 {+ bail!("different local user or invalid peer process");+ }+ let bytes: Vec<u8> = token.iter().flat_map(|word| word.to_ne_bytes()).collect();+ let data = CFData::from_buffer(&bytes);+ let mut attrs = GuestAttributes::new();+ attrs.set_audit_token(data.as_concrete_TypeRef());+ let code = SecCode::copy_guest_with_attribues(None, &attrs, Flags::NONE)+ .context("resolve authenticated peer process")?;+ let requirement: SecRequirement = requirement.parse()?;+ if code.check_validity(Flags::NONE, &requirement).is_err() {+ verify_replaced_process(pid, Some(token))?;+ }+ Ok(pid)+}++pub(super) fn own_requirement() -> Result<String> {+ let code = SecCode::for_self(Flags::NONE)?;+ unsafe {+ let mut raw = std::ptr::null();+ check(SecCodeCopyDesignatedRequirement(+ code.as_CFTypeRef(),+ 0,+ &mut raw,+ ))?;+ let requirement = CFType::wrap_under_create_rule(raw);+ let mut text = std::ptr::null();+ check(SecRequirementCopyString(+ requirement.as_CFTypeRef(),+ 0,+ &mut text,+ ))?;+ let requirement = CFString::wrap_under_create_rule(text).to_string();+ // Cache the actual signing certificate before this process's bundle can+ // be replaced. Kernel-only recovery additionally requires this exact+ // certificate and signed identifier, never an untrusted display name.+ let parsed: SecRequirement = requirement.parse()?;+ code.check_validity(Flags::NONE, &parsed)?;+ let mut raw_info = std::ptr::null();+ check(SecCodeCopySigningInformation(+ code.as_CFTypeRef(),+ 1 << 1,+ &mut raw_info,+ ))?;+ let info = CFDictionary::<CFString, CFType>::wrap_under_create_rule(raw_info);+ if let (Some(identifier), Some(certificates)) = (+ info.find(&CFString::wrap_under_get_rule(kSecCodeInfoIdentifier))+ .and_then(|v| v.downcast::<CFString>()),+ info.find(&CFString::wrap_under_get_rule(kSecCodeInfoCertificates))+ .and_then(|v| v.downcast::<CFArray>()),+ ) {+ let certificates =+ CFArray::<CFType>::wrap_under_get_rule(certificates.as_concrete_TypeRef());+ if let Some(cert) = certificates.get(0) {+ let bytes =+ CFData::wrap_under_create_rule(SecCertificateCopyData(cert.as_CFTypeRef()));+ let _ = SIGNER.set((identifier.to_string(), bytes.bytes().to_vec()));+ }+ }+ Ok(requirement)+ }+}++pub(super) fn running(pid: i32, requirement: &str) -> Result<Identity> {+ let (uid, started) = process_stamp(pid)?;+ let code = guest(pid)?;+ let requirement: SecRequirement = requirement.parse()?;+ let metadata = code+ .check_validity(Flags::NONE, &requirement)+ .map_err(anyhow::Error::from)+ .and_then(|()| information(code.as_CFTypeRef()));+ let hash = process_hash(pid)?;+ let (identifier, version) = match metadata {+ Ok((identifier, signed_hash, version)) if hash == signed_hash => (identifier, version),+ _ => {+ verify_replaced_process(pid, None)?;+ let identifier = SIGNER.get().context("missing verified signer")?.0.clone();+ let version = registered_process_version(pid, &identifier)?;+ (identifier, version)+ }+ };+ if process_stamp(pid)? != (uid, started) || process_hash(pid)? != hash {+ bail!("process changed while reading its identity");+ }+ let executable = process_path(pid)?;+ Ok(Identity {+ pid,+ started,+ uid,+ identifier,+ version,+ hash,+ executable,+ })+}++fn registered_process_version(pid: i32, identifier: &str) -> Result<String> {+ // Launch Services retains metadata registered by this PID at launch, even+ // after its bundle is replaced/re-registered. Reading that process record+ // avoids assigning the replacement Info.plist's version to the old process.+ let mut child = std::process::Command::new("/usr/bin/lsappinfo")+ .args([+ "info",+ "-only",+ "CFBundleShortVersionString,CFBundleIdentifier",+ &pid.to_string(),+ ])+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::null())+ .spawn()?;+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);+ while child.try_wait()?.is_none() {+ if std::time::Instant::now() >= deadline {+ let _ = child.kill();+ let _ = child.wait();+ bail!("timed out reading original process version");+ }+ std::thread::sleep(std::time::Duration::from_millis(20));+ }+ let output = child.wait_with_output()?;+ if !output.status.success() {+ bail!("original process version unavailable");+ }+ parse_registered_version(std::str::from_utf8(&output.stdout)?, identifier)+}++fn parse_registered_version(output: &str, identifier: &str) -> Result<String> {+ let mut fields = std::collections::HashMap::new();+ for line in output.lines() {+ if let Some((key, value)) = line.trim().split_once('=') {+ fields.insert(+ serde_json::from_str::<String>(key)?,+ serde_json::from_str::<String>(value)?,+ );+ }+ }+ if fields.get("CFBundleIdentifier").map(String::as_str) != Some(identifier) {+ bail!("original process registration has a different app identity");+ }+ let version = fields+ .remove("CFBundleShortVersionString")+ .context("original process registration has no version")?;+ semver::Version::parse(&version)+ .context("original process registration has an invalid version")?;+ Ok(version)+}++pub(super) fn on_disk(executable: &Path, requirement: &str, owner: &Identity) -> Result<Identity> {+ let macos = executable.parent().context("missing executable parent")?;+ let contents = macos.parent().context("missing bundle Contents")?;+ if macos.file_name() != Some(std::ffi::OsStr::new("MacOS"))+ || contents.file_name() != Some(std::ffi::OsStr::new("Contents"))+ {+ bail!("replacement is not a bundle executable");+ }+ let bundle = contents.parent().context("missing application bundle")?;+ let url = CFURL::from_path(bundle, true).context("invalid executable path")?;+ let code = SecStaticCode::from_path(&url, Flags::NONE)?;+ let requirement: SecRequirement = requirement.parse()?;+ code.check_validity(+ Flags::STRICT_VALIDATE | Flags::CHECK_NESTED_CODE,+ &requirement,+ )?;+ let (identifier, hash, version) = information(code.as_CFTypeRef())?;+ Ok(Identity {+ identifier,+ version,+ hash,+ executable: executable.to_path_buf(),+ ..owner.clone()+ })+}++pub(super) fn process_path(pid: i32) -> Result<PathBuf> {+ let mut buf = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize];+ let len = unsafe { libc::proc_pidpath(pid, buf.as_mut_ptr().cast(), buf.len() as u32) };+ if len <= 0 {+ bail!("process executable is unavailable");+ }+ use std::os::unix::ffi::OsStrExt;+ let end = buf.iter().position(|b| *b == 0).unwrap_or(buf.len());+ Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..end])))+}++pub(super) fn candidates(executable_name: &std::ffi::OsStr) -> Result<Vec<i32>> {+ let mut pids = vec![0i32; 8192];+ let bytes = unsafe {+ libc::proc_listpids(+ 4, /* PROC_UID_ONLY, sys/proc_info.h */+ libc::geteuid(),+ pids.as_mut_ptr().cast(),+ (pids.len() * size_of::<i32>()) as i32,+ )+ };+ if bytes <= 0 || bytes as usize >= pids.len() * size_of::<i32>() {+ bail!("could not enumerate app processes");+ }+ pids.truncate(bytes as usize / size_of::<i32>());+ Ok(pids+ .into_iter()+ .filter(|pid| *pid > 0 && *pid != std::process::id() as i32)+ .filter(|pid| {+ process_path(*pid)+ .ok()+ .and_then(|p| p.file_name().map(|n| n == executable_name))+ .unwrap_or(false)+ })+ .collect())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn original_version_requires_matching_process_registration() {+ let output =+ "\"CFBundleShortVersionString\"=\"2.7.94\"\n\"CFBundleIdentifier\"=\"screenpi.pe\"\n";+ assert_eq!(+ parse_registered_version(output, "screenpi.pe").unwrap(),+ "2.7.94"+ );+ assert!(parse_registered_version(output, "screenpi.pe.beta").is_err());+ assert!(+ parse_registered_version(&output.replace("2.7.94", "unknown"), "screenpi.pe").is_err()+ );+ assert!(parse_registered_version("", "screenpi.pe").is_err());+ }++ #[test]+ fn kernel_process_satisfies_its_designated_requirement() {+ let requirement = own_requirement().unwrap();+ verify_process(std::process::id() as i32, &requirement).unwrap();+ assert!(!process_hash(std::process::id() as i32).unwrap().is_empty());+ }+}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs b/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rsindex 96b5c6c70..eac7dbe1d 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/process_exit.rs@@ -30,7 +30,7 @@ use tracing::{info, warn};const E2E_SCK_RELAUNCH_RACE_SEED: &str = "packaged-updater-sck-race";#[cfg(all(feature = "e2e", target_os = "macos"))]const E2E_SCK_RELAUNCH_DEADLINE_FILE: &str = ".e2e-sck-relaunch-not-before";-const MACOS_UPDATER_RELAUNCH_SETTLE: Duration = Duration::from_secs(3);+pub(crate) const MACOS_UPDATER_RELAUNCH_SETTLE: Duration = Duration::from_secs(3);#[cfg(any(target_os = "macos", test))]const MACOS_UPDATER_RELAUNCH_HELPER: &str = r#"old_pid=$1@@ -46,7 +46,7 @@ exec "$@""#;#[cfg(any(target_os = "macos", test))]-fn macos_updater_relaunch_command<I, S>(+pub(crate) fn macos_updater_relaunch_command<I, S>(binary: &Path,args: I,old_pid: u32,diff --git a/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs b/apps/screenpipe-app-tauri/src-tauri/src/search_only.rsindex 23d8bcc99..8606d4800 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/search_only.rs@@ -135,6 +135,10 @@ pub fn resume_capture() -> Result<(), String> {/// An explicit reopen ends Quit's pause, using the existing capture owner./// Ordinary window opens while already awake do not undo a recording pause.pub fn wake(app: &AppHandle) -> bool {+ #[cfg(target_os = "macos")]+ if crate::manual_handoff::pending() {+ return false;+ }if ENTERING.load(Ordering::SeqCst) || !is_active() {return false;}@@ -185,6 +189,12 @@ pub fn prepare_restart() -> Result<(), String> {})}+/// A replacement selected by the user is a manual open, not a hidden restart.+#[cfg(target_os = "macos")]+pub(crate) fn prepare_manual_handoff() -> Result<(), String> {+ persist(false)+}+pub fn cancel_restart() {if let Err(error) = persist(false) {diagnostic("search_restart_cancel_failed", &error);diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server.rs b/apps/screenpipe-app-tauri/src-tauri/src/server.rsindex 8e750a770..1aef1ca8b 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server.rs@@ -128,6 +128,10 @@ async fn handle_focus(State(state): State<ServerState>,Json(payload): Json<FocusPayload>,) -> Result<Json<ApiResponse>, (StatusCode, String)> {+ #[cfg(target_os = "macos")]+ if crate::manual_handoff::pending() {+ return Err((StatusCode::SERVICE_UNAVAILABLE, "switching to the selected app copy".into()));+ }info!("Received focus request: args_count={}, deep_link_present={}, target={:?}",payload.args.len(),@@ -791,6 +795,13 @@ async fn e2e_updates_start_capture(State(state): State<ServerState>) -> impl Int}));}};+ // The initial boot stays signed out to reproduce the idle-update path.+ // This second phase uses the existing isolated E2E authentication fixture+ // so the production capture path reaches ScreenCaptureKit after relaunch.+ crate::e2e::seeds::seed_cloud_authentication(&mut settings);+ if let Err(error) = crate::store::OnboardingStore::update(&state.app_handle, |onboarding| onboarding.complete()) {+ return Json(serde_json::json!({ "started": false, "error": format!("failed to prepare E2E onboarding: {error}") }));+ }settings.user.id = Some("packaged_updater_e2e".to_string());settings.user.subscription_plan = Some("none".to_string());settings.user.entitlement = Some(serde_json::json!({@@ -800,23 +811,31 @@ async fn e2e_updates_start_capture(State(state): State<ServerState>) -> impl Int"checked_at": chrono::Utc::now().to_rfc3339(),"features": { "app": true, "cloud": false }}));- if let Err(error) = settings.save(&state.app_handle) {+ // Publish the existing fixture sentinel with the account in one store+ // mutation. Otherwise a webview refresh sends the synthetic token to the+ // real account service and clears the fixture on its expected 401.+ let mut user = serde_json::json!(settings.user);+ user["__e2eSkipAccountRefresh"] = serde_json::json!(true);+ if let Err(error) = settings.replace_startup_user(&state.app_handle, user) {return Json(serde_json::json!({"started": false,"error": format!("failed to save E2E recording entitlement: {error}"),}));}- let result = crate::recording::spawn_screenpipe(- state.app_handle.state(),+ if let Err(error) = crate::commands::set_cloud_token(+ settings.user.token.clone(),state.app_handle.clone(),- None,- )- .await;- match result {- Ok(()) => Json(serde_json::json!({ "started": true, "error": null })),- Err(error) => Json(serde_json::json!({ "started": false, "error": error })),+ state.app_handle.state(),+ ).await {+ return Json(serde_json::json!({ "started": false, "error": error }));}++ // set_cloud_token schedules the production deferred account start. Do not+ // also call spawn_screenpipe: that explicit start cancels the deferred+ // request while it can already hold the lifecycle lock, losing both starts.+ // The caller must verify a real frame; this only acknowledges the request.+ Json(serde_json::json!({ "started": true, "error": null }))}async fn set_window_size(diff --git a/apps/screenpipe-app-tauri/src-tauri/src/staged_update.rs b/apps/screenpipe-app-tauri/src-tauri/src/staged_update.rsindex 039aecd86..4b3645676 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/staged_update.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/staged_update.rs@@ -163,6 +163,10 @@ pub fn staged_version() -> Option<String> {/// the exit path; a failure only means the app comes back on the current/// version and the checker re-stages later.pub fn install_staged_if_any<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> bool {+ if crate::manual_handoff::pending() && !crate::updates::update_restart_started() {+ crate::update_diagnostics::record("manual_handoff_skipped_staged_install", "outcome=selected_build_preserved");+ return false;+ }install_staged_with_diagnostics(app,crate::config::app_data_dir(),diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rsindex 0390d8b57..763a58a11 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs@@ -136,6 +136,21 @@ fn read_store_file(path: &Path) -> std::io::Result<Vec<u8>> {retry_windows_store_io(|| std::fs::read(path))}+/// Read existing settings before instance arbitration without opening the DB,+/// creating keys, repairing the store, or writing defaults.+pub(crate) fn read_startup_store(path: &Path) -> Result<Value, String> {+ let data = read_store_file(path).map_err(|e| e.to_string())?;+ let plain = if data.starts_with(b"SPSTORE1") {+ let crate::secrets::KeyResult::Found(key) = crate::secrets::get_key() else {+ return Err("existing settings key is unavailable".into());+ };+ screenpipe_vault::crypto::decrypt_small(&data[8..], &key).map_err(|e| e.to_string())?+ } else {+ data+ };+ serde_json::from_slice(&plain).map_err(|e| e.to_string())+}+#[cfg(windows)]pub(crate) fn reset_windows_store_file_permissions(path: &Path) -> anyhow::Result<()> {use std::os::windows::process::CommandExt;diff --git a/apps/screenpipe-app-tauri/src-tauri/src/update_diagnostics.rs b/apps/screenpipe-app-tauri/src-tauri/src/update_diagnostics.rsindex cb0a0fb74..c3877032f 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/update_diagnostics.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/update_diagnostics.rs@@ -9,6 +9,12 @@ use std::path::Path;use std::sync::Mutex;pub(crate) const LOG_NAME: &str = "update-install.log";+// Written by the separately signed macOS recovery launcher before the app runs.+pub(crate) const RECOVERY_LOG_NAME: &str = "update-recovery.log";++pub(crate) fn is_update_log(name: &str) -> bool {+ matches!(name, LOG_NAME | RECOVERY_LOG_NAME)+}const MAX_BYTES: u64 = 32 * 1024;static WRITER: Mutex<()> = Mutex::new(());diff --git a/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs b/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rsindex 419d388d2..c39db7e73 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/update_restart.rs@@ -64,4 +64,28 @@ mod tests {.await.is_some());}++ #[tokio::test]+ async fn manual_handoff_and_staged_update_cannot_commit_together() {+ let safety = RestartSafety(RwLock::new(()));+ let handoff = safety+ .prepare_restart(Duration::from_secs(1))+ .await+ .unwrap();+ assert!(safety+ .prepare_restart(Duration::from_millis(10))+ .await+ .is_none());+ // A refused handoff releases ownership so the staged update can retry.+ drop(handoff);+ let staged = safety+ .prepare_restart(Duration::from_secs(1))+ .await+ .unwrap();+ assert!(safety+ .prepare_restart(Duration::from_millis(10))+ .await+ .is_none());+ drop(staged);+ }}diff --git a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs b/apps/screenpipe-app-tauri/src-tauri/src/updates.rsindex 3dff8c8da..901d79ae0 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/updates.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/updates.rs@@ -45,7 +45,9 @@ fn configured_updater(app: &tauri::AppHandle) -> Result<tauri_plugin_updater::Uplet mut builder = app.updater_builder();let settings = SettingsStore::get(app).ok().flatten();let is_beta_build = app.config().identifier.contains("beta");- if !is_enterprise_build(app) && !is_beta_build {+ // Packaged updater acceptance supplies a local signed fixture endpoint.+ // Keep that endpoint in E2E builds; shipping consumer builds use their channel.+ if !is_enterprise_build(app) && !is_beta_build && !cfg!(feature = "e2e") {let channel = consumer_update_channel(settings.as_ref());builder = builder.endpoints(vec![consumer_update_endpoint(channel).parse()?])?;}diff --git a/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json b/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.jsonindex 6723a6ae3..470b7829e 100644--- a/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json+++ b/apps/screenpipe-app-tauri/src-tauri/tauri.macos.conf.json@@ -7,7 +7,8 @@"exceptionDomain": "screenpipe.com","provisioningProfile": null,"files": {- "Resources": "../.localization/macos-resources"+ "Resources": "../.localization/macos-resources",+ ".": "../.macos-sidecars"},"dmg": {"background": "assets/dmg-background.png"@@ -16,8 +17,7 @@"externalBin": ["bun","ffmpeg",- "ffprobe",- "mlx.metallib"+ "ffprobe"]}}diff --git a/crates/screenpipe-db/tests/sqlite_architecture_invariants_test.rs b/crates/screenpipe-db/tests/sqlite_architecture_invariants_test.rsindex 773ffa86e..718e9c167 100644--- a/crates/screenpipe-db/tests/sqlite_architecture_invariants_test.rs+++ b/crates/screenpipe-db/tests/sqlite_architecture_invariants_test.rs@@ -143,7 +143,7 @@ fn credential_readers_resolve_the_existing_os_vault_key() {),("apps/screenpipe-app-tauri/src-tauri/src/main.rs",- "secrets::get_key()",+ "store::read_startup_store(",),("apps/screenpipe-app-tauri/src-tauri/src/store.rs",@@ -180,4 +180,19 @@ fn credential_readers_resolve_the_existing_os_vault_key() {"credential reader {relative_path} must resolve the existing OS-vault key via {vault_read}");}++ // Startup now delegates the encrypted settings read to the shared helper.+ // Keep the original invariant on that helper, not just elsewhere in store.rs.+ let store =+ fs::read_to_string(repository.join("apps/screenpipe-app-tauri/src-tauri/src/store.rs"))+ .expect("read settings source");+ let startup_reader = store+ .split("pub(crate) fn read_startup_store(")+ .nth(1)+ .expect("startup settings reader")+ .split("\n}")+ .next()+ .unwrap();+ assert!(startup_reader.contains("secrets::get_key()"));+ assert!(!startup_reader.contains("get_or_create_key"));}diff --git a/crates/screenpipe-engine/src/auth_key.rs b/crates/screenpipe-engine/src/auth_key.rsindex 41bf0dfed..bdaa9ca4a 100644--- a/crates/screenpipe-engine/src/auth_key.rs+++ b/crates/screenpipe-engine/src/auth_key.rs@@ -295,7 +295,11 @@ fn legacy_auth_json_path_for(legacy_dir: &Path, active_dir: &Path) -> Option<Pat}fn read_legacy_auth_json() -> Option<String> {- let content = std::fs::read_to_string(legacy_auth_json_path()?).ok()?;+ read_auth_json(&legacy_auth_json_path()?)+}++fn read_auth_json(path: &Path) -> Option<String> {+ let content = std::fs::read_to_string(path).ok()?;let json: serde_json::Value = serde_json::from_str(&content).ok()?;json["token"].as_str()@@ -313,6 +317,12 @@ fn read_legacy_auth_json() -> Option<String> {/// that doesn't match the running server's in-memory value when called from/// a sibling process.pub async fn find_api_auth_key() -> Option<String> {+ find_api_auth_key_for_data_dir(&screenpipe_core::paths::default_screenpipe_data_dir()).await+}++/// Read the existing key for a selected recording directory before a desktop+/// replacement starts the engine. This never creates or rotates a credential.+pub async fn find_api_auth_key_for_data_dir(data_dir: &Path) -> Option<String> {if let Ok(k) = std::env::var("SCREENPIPE_API_KEY") {if !k.is_empty() {return Some(k);@@ -330,8 +340,7 @@ pub async fn find_api_auth_key() -> Option<String> {}}- let data_dir = screenpipe_core::paths::default_screenpipe_data_dir();- if let Ok(store) = open_secret_store(&data_dir).await {+ if let Ok(store) = open_secret_store(data_dir).await {if let Ok(Some(bytes)) = store.get("api_auth_key").await {if let Ok(s) = String::from_utf8(bytes) {if !s.is_empty() {@@ -341,7 +350,10 @@ pub async fn find_api_auth_key() -> Option<String> {}}- read_legacy_auth_json().or_else(|| read_api_auth_recovery(&data_dir))+ let legacy = dirs::home_dir()+ .and_then(|home| legacy_auth_json_path_for(&home.join(".screenpipe"), data_dir))+ .and_then(|path| read_auth_json(&path));+ legacy.or_else(|| read_api_auth_recovery(data_dir))}#[cfg(test)]