The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
packaging(macos): Safari app-wrapper script, compatibility review, smoke checklist, MDM declaration
Claude68173bb9b5d1
diff --git a/browser-extension/README.md b/browser-extension/README.mdindex 2fa73ec5..33831a51 100644--- a/browser-extension/README.md+++ b/browser-extension/README.md@@ -187,6 +187,22 @@ staging one. Prefer a throwaway account where practical.- **(d) live smoke** (opt-in, headed) — drive the real sites in a persistent authed profile; adrift alarm that flags when recorded fixtures go stale. *(not yet implemented)*+## Safari (experimental, not shipped)++Safari support is in progress (#392). Its packaging lives in+[`packaging/macos/safari/`](../packaging/macos/safari/README.md): the Xcode app+wrapper script, the signing plan, the MDM example, and a+[compatibility review](../packaging/macos/safari/compatibility.md) with its gap+list.++**The self-verifying loop above does not cover Safari.** Playwright cannot load+extensions into WebKit, and `safaridriver` cannot install them. The replay e2e+(layer b) therefore runs on Chromium only, and it stays the correctness gate for+the site adapters. The unit tests (layer a) are browser-agnostic. A Safari build+is verified by hand with the+[Safari smoke checklist](../packaging/macos/safari/smoke-checklist.md) until an+XCTest-based check exists.+## StatusThis is a **V0 MVP**: both **Claude.ai** and **ChatGPT** capture are proven end-to-end against thediff --git a/packaging/macos/README.md b/packaging/macos/README.mdindex 51baba1f..499d5e4d 100644--- a/packaging/macos/README.md+++ b/packaging/macos/README.md@@ -562,6 +562,14 @@ sudo /opt/beacon/bin/beacon endpoint wazuh validatesudo launchctl print system/com.beacon.endpoint.collector```+### Safari Browser Extension (Experimental)++The Safari build of the browser collector is not shipped yet. Its app wrapper,+signing plan, and Declarative Device Management example live in+[`safari/`](safari/README.md). Safari extensions can only be force-enabled by a+declaration on supervised Macs running macOS 15 or later, not by a+configuration profile.+## FleetUpload the signed/notarized `.pkg` as Fleet software and scope it to a pilotdiff --git a/packaging/macos/safari/README.md b/packaging/macos/safari/README.mdnew file mode 100644index 00000000..b3127257--- /dev/null+++ b/packaging/macos/safari/README.md@@ -0,0 +1,183 @@+# Safari packaging for the browser collector++Experimental, and not shipped. These files cover the Safari-specific pieces of+[#392](https://github.com/Asymptote-Labs/agent-beacon/issues/392): the Xcode app+wrapper, distribution and signing, MDM, and manual verification. None of it has+been run in Safari yet. [`compatibility.md`](compatibility.md) lists what is+documented and what still needs a Mac to confirm.++| File | Purpose |+|---|---|+| `create-safari-project.sh` | Generates the Xcode app wrapper from a built extension with `xcrun safari-web-extension-packager`. |+| `compatibility.md` | Safari support for each API and manifest key the extension uses, with sources and a gap list. |+| `smoke-checklist.md` | The manual checks a Safari build must pass. There is no automated Safari test. |+| `mdm/safari-extension-settings.declaration.json` | Example Declarative Device Management configuration that force-enables the extension and pre-grants its sites. |+| `check-mdm-declaration.py` | Validates that declaration against Apple's schema and the extension manifest. |+| `test-safari-packaging.sh` | Tests the wrapper's argument handling and guards (with a fake `xcrun`) and the declaration. Runs on Linux, and from `packaging/macos/test-endpoint-scripts.sh`. |++## How Safari differs++A Safari web extension cannot be loaded unpacked for real use. It ships inside a+macOS app. Safari discovers the extension from the app's `PlugIns/*.appex`, and+the app has to be signed. Safari's "Allow unsigned extensions" setting and its+"Add Temporary Extension…" button are development tools only: both reset when+Safari quits, and temporary extensions also expire after 24 hours.++The extension code itself needs little change. Safari exposes the `chrome.*`+namespace, and every API the collector calls is documented as supported in+Safari 18 or later. The open risks are the site-access grants and whether the+service worker's POST reaches `127.0.0.1:4318`. See the gap list in+`compatibility.md`.++## Generate the Xcode project++On a Mac with full Xcode (the Command Line Tools alone do not include the+packager):++```bash+cd browser-extension && npm ci && npm run build && cd ..+sh packaging/macos/safari/create-safari-project.sh+```++This writes `dist/safari/Beacon Browser Collector/`, which holds a macOS app+target (`ai.asymptote.beacon.browser-collector`) and the extension target+(`ai.asymptote.beacon.browser-collector.Extension`). The extension files are+**copied** into the project, so it is a snapshot of that build. Regenerate it+(`--force`) after rebuilding the extension. For a local edit-and-build loop, use+`--reference-resources`; the project then points at `browser-extension/dist`,+and Product > Build picks up each rebuild.++`--dry-run` validates the inputs and prints the exact packager command on any+OS. Run `--help` for all options: `--platform ios|all`, `--app-name`,+`--bundle-id`, and the rest.++The project is generated, not committed. The packager's output changes between+Xcode releases. Regenerating it from a fresh build keeps the wrapper and the+extension in step, and avoids a hand-edited Xcode project in the repository. If+the wrapper later needs native code (it does not today), commit the project+then.++### Dependency on the Firefox work (#393)++This directory wraps whatever build it is pointed at. It does not add a+`browser.*` shim or per-target manifests: #393 owns both.++- Safari does not need the shim. It supports `chrome.*`.+- Safari may need a manifest variant. If S5 in the checklist shows the service+ worker's POST failing CORS even after `127.0.0.1` access is granted, the Safari+ target needs `background.scripts` plus `preferred_environment`. That comes from+ #393's per-target manifest build. Point the script at that target's output+ with `--extension-dir` (or `SAFARI_EXTENSION_DIR`).++## Distribution and signing plan++Nothing here is wired into CI or a release workflow yet. This is the proposed+path.++**Recommendation: Developer ID, notarized, delivered as a signed package. Not the+App Store, at least at first.**++- Beacon already signs and notarizes a macOS package with Developer ID+ (`build-signed-notarized-pkg.sh`, and the `package` job in `release.yml`).+ Fleets deploy it through Jamf or Fleet. A Safari app delivered the same way+ fits that model: the same identities, the same notary profile, and the same+ MDM upload.+- The App Store adds review latency to every extension release. It also forces+ a privacy-label discussion about `retention: 'full'`. And it doesn't help+ managed fleets, which install through MDM anyway.+- The trade-off: Safari has no `update_url`, so a Developer ID build updates only+ when a newer package is installed. That's how the endpoint package already+ updates. Revisit the App Store if unmanaged individual users become a target.++Proposed release steps, for a macOS runner in the existing `release` environment,+which already holds `DEVELOPER_ID_APP_CERT_P12`, `DEVELOPER_ID_INSTALLER_CERT_P12`,+their passwords, and the `NOTARY_API_KEY_*` secrets:++1. Build the extension and strip sourcemaps, as the Chrome zip job does.+2. `sh packaging/macos/safari/create-safari-project.sh --force`+3. Archive the app with the Developer ID Application identity, the team from the+ `APPLE_TEAM_ID` variable, and the hardened runtime. macOS requires app+ extensions to be sandboxed, so keep the App Sandbox entitlement in the+ generated `.entitlements` files. The scheme name below assumes the default+ app name; `xcodebuild -list` shows the real one:++ ```bash+ xcodebuild -project "dist/safari/Beacon Browser Collector/Beacon Browser Collector.xcodeproj" \+ -scheme "Beacon Browser Collector" -configuration Release \+ -archivePath "dist/safari/BeaconBrowserCollector.xcarchive" \+ DEVELOPMENT_TEAM="$APPLE_TEAM_ID" CODE_SIGN_STYLE=Manual \+ CODE_SIGN_IDENTITY="$DEVELOPER_ID_APP_IDENTITY" \+ OTHER_CODE_SIGN_FLAGS=--timestamp ENABLE_HARDENED_RUNTIME=YES archive+ xcodebuild -exportArchive -archivePath "dist/safari/BeaconBrowserCollector.xcarchive" \+ -exportOptionsPlist ExportOptions.plist -exportPath dist/safari/export # method: developer-id+ ```++4. Notarize and staple the app (`xcrun notarytool submit --wait`, then+ `xcrun stapler staple`), using the same notary credentials as+ `build-signed-notarized-pkg.sh`.+5. Wrap the app in a package that installs to `/Applications`. Sign it with the+ Developer ID Installer identity (`productbuild --component ... /Applications+ --sign "$DEVELOPER_ID_INSTALLER_IDENTITY"`), then notarize and staple the+ package.+6. Verify with checks R1 to R4 in [`smoke-checklist.md`](smoke-checklist.md),+ then publish the package and its `.sha256` on the `ext-v*` release.++This makes the reasoning in `release-extension.yml`'s header out of date. That+job skips `environment: release` because it has no signing secrets, but a+Safari job would need them. Add the Safari job to that workflow in the+`release` environment. The Chrome job can stay outside it.++Open question, carried over from the issue: should the Safari app eventually+ride inside the endpoint `.pkg`? That would give one artifact and one MDM upload.+But it ties the extension's `ext-v*` cadence to the CLI's `v*` releases, so start+with a separate package.++## MDM++Safari extension management is **Declarative Device Management only**. It needs+Safari 18, macOS 15 or later, and a **supervised** Mac. The issue assumed a+configuration profile (`.mobileconfig`) payload. None exists for this: an Apple+Device Management engineer confirmed on the forums that Safari extensions are+managed "via declarative device management (not a profile)", and a+`.mobileconfig` carrying these keys does nothing+([forum thread 760255](https://developer.apple.com/forums/thread/760255)).++[`mdm/safari-extension-settings.declaration.json`](mdm/safari-extension-settings.declaration.json)+is a `com.apple.configuration.safari.extensions.settings` declaration+([Apple schema](https://github.com/apple/device-management/blob/release/declarative/declarations/configurations/safari.extensions.settings.yaml)).+It:++- turns the collector on and prevents users from turning it off (`State: AlwaysOn`);+- leaves Private Browsing to the user (`PrivateBrowsing: Allowed`). Set it to+ `AlwaysOn` to capture private windows too, or to `AlwaysOff` to exclude them;+- pre-grants the sites in the manifest's `host_permissions`, including+ `127.0.0.1` and `localhost` for the collector, so users are never asked for+ site access (`AllowedDomains`). Whether Safari accepts IP literals such as+ `127.0.0.1` in `AllowedDomains` is not documented; check M2 confirms it.++Before deploying it:++1. Replace `TEAMID1234` in the `ManagedExtensions` key with the signing team ID.+ The key is the extension's composed identifier,+ `<extension bundle id> (<team id>)`. Read it from a signed build with+ `codesign -dv "/Applications/Beacon Browser Collector.app/Contents/PlugIns/"*.appex`.+2. Change `ServerToken` whenever you change the declaration, so devices apply the+ update.+3. Validate the edited file:++ ```bash+ python3 packaging/macos/safari/check-mdm-declaration.py \+ packaging/macos/safari/mdm/safari-extension-settings.declaration.json \+ --manifest browser-extension/src/manifest.json \+ --extension-bundle-id ai.asymptote.beacon.browser-collector.Extension+ ```++How to deliver the declaration depends on the MDM. It must support Declarative+Device Management and the Safari extensions configuration, so check your+vendor's documentation. Deploy the signed app package first (for example, as a+Jamf policy alongside the endpoint `.pkg`, as described in+[`../README.md`](../README.md#jamf-pro)), then the declaration.++Unsupervised Macs and macOS 14 or earlier cannot be managed this way. There,+users enable the extension and grant site access themselves; the prompts they+see are recorded by check S4.diff --git a/packaging/macos/safari/check-mdm-declaration.py b/packaging/macos/safari/check-mdm-declaration.pynew file mode 100755index 00000000..92d08208--- /dev/null+++ b/packaging/macos/safari/check-mdm-declaration.py@@ -0,0 +1,151 @@+#!/usr/bin/env python3+"""Validate the Safari extension-settings declaration shipped for MDM.++Checks the declaration against Apple's published schema for+com.apple.configuration.safari.extensions.settings+(https://github.com/apple/device-management/blob/release/declarative/declarations/configurations/safari.extensions.settings.yaml)+and against Beacon's own contract: the declaration names the collector's+extension and grants every host the extension's manifest asks for.++Usage:+ check-mdm-declaration.py DECLARATION.json --manifest MANIFEST.json \+ --extension-bundle-id ID++Standard library only, so it runs on a stock macOS or Linux Python 3.+"""++import argparse+import json+import re+import sys+from urllib.parse import urlsplit++DECLARATION_TYPE = "com.apple.configuration.safari.extensions.settings"+STATE_VALUES = {"Allowed", "AlwaysOn", "AlwaysOff"}+EXTENSION_KEYS = {"State", "PrivateBrowsing", "AllowedDomains", "DeniedDomains"}+# DDM declarations carry these top-level keys; ServerToken is required.+DECLARATION_KEYS = {"Type", "Identifier", "ServerToken", "Payload"}+# "Identifier (TeamIdentifier)"; Apple team IDs are 10 upper-case alphanumerics.+COMPOSED_ID = re.compile(r"^(?P<bundle>[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+) \((?P<team>[A-Z0-9]{10})\)$")+# Domain entries are bare hosts, optionally with a leading "*" wildcard, or "*".+DOMAIN = re.compile(r"^(\*|\*?[A-Za-z0-9.-]+)$")+++def manifest_hosts(manifest):+ hosts = set()+ for pattern in manifest.get("host_permissions", []):+ host = urlsplit(pattern.replace("*://", "https://", 1)).hostname+ if host:+ hosts.add(host)+ return hosts+++def check(declaration, manifest, extension_bundle_id):+ errors = []++ if not isinstance(declaration, dict):+ return ["declaration must be a JSON object"]+ missing = DECLARATION_KEYS - declaration.keys()+ if missing:+ errors.append(f"missing top-level keys: {sorted(missing)}")+ extra = declaration.keys() - DECLARATION_KEYS+ if extra:+ errors.append(f"unknown top-level keys: {sorted(extra)}")+ if declaration.get("Type") != DECLARATION_TYPE:+ errors.append(f"Type must be {DECLARATION_TYPE!r}, got {declaration.get('Type')!r}")+ for key in ("Identifier", "ServerToken"):+ value = declaration.get(key)+ if not isinstance(value, str) or not value.strip():+ errors.append(f"{key} must be a non-empty string")++ payload = declaration.get("Payload")+ if not isinstance(payload, dict):+ return errors + ["Payload must be an object"]+ if payload.keys() - {"ManagedExtensions"}:+ errors.append(f"unknown Payload keys: {sorted(payload.keys() - {'ManagedExtensions'})}")+ managed = payload.get("ManagedExtensions")+ if not isinstance(managed, dict) or not managed:+ return errors + ["Payload.ManagedExtensions must be a non-empty object"]++ beacon_entry = None+ for composed, settings in managed.items():+ where = f"ManagedExtensions[{composed!r}]"+ match = COMPOSED_ID.match(composed)+ if composed != "*" and not match:+ errors.append(f"{where}: key must be '*' or 'bundle.id (TEAMID)' with a 10-character team ID")+ if not isinstance(settings, dict):+ errors.append(f"{where}: settings must be an object")+ continue+ unknown = settings.keys() - EXTENSION_KEYS+ if unknown:+ errors.append(f"{where}: unknown keys {sorted(unknown)}")+ for key in ("State", "PrivateBrowsing"):+ if key in settings and settings[key] not in STATE_VALUES:+ errors.append(f"{where}.{key}: must be one of {sorted(STATE_VALUES)}, got {settings[key]!r}")+ for key in ("AllowedDomains", "DeniedDomains"):+ if key not in settings:+ continue+ domains = settings[key]+ if not isinstance(domains, list) or not all(isinstance(d, str) for d in domains):+ errors.append(f"{where}.{key}: must be an array of strings")+ continue+ for d in domains:+ if not DOMAIN.match(d):+ errors.append(f"{where}.{key}: {d!r} is not a bare domain (no scheme, port, or path)")+ if composed == "*" and "AllowedDomains" in settings:+ errors.append(f"{where}: AllowedDomains is ignored for the '*' identifier")+ if match and match.group("bundle") == extension_bundle_id:+ beacon_entry = settings++ if beacon_entry is None:+ errors.append(f"no ManagedExtensions entry for the collector extension {extension_bundle_id!r}")+ else:+ def domain_set(key):+ value = beacon_entry.get(key, [])+ # Shape errors were reported above; don't crash on them here.+ return {d for d in value if isinstance(d, str)} if isinstance(value, list) else set()++ allowed = domain_set("AllowedDomains")+ denied = domain_set("DeniedDomains")+ wanted = manifest_hosts(manifest)+ if not wanted:+ errors.append("manifest declares no host_permissions to compare against")+ missing_hosts = wanted - allowed+ if missing_hosts:+ errors.append(f"collector entry does not allow manifest hosts: {sorted(missing_hosts)}")+ blocked = wanted & denied+ if blocked:+ errors.append(f"collector entry denies manifest hosts: {sorted(blocked)}")+ if beacon_entry.get("State") == "AlwaysOff":+ errors.append("collector entry turns the extension off (State AlwaysOff)")++ return errors+++def main(argv):+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("declaration")+ parser.add_argument("--manifest", required=True)+ parser.add_argument("--extension-bundle-id", required=True)+ args = parser.parse_args(argv)++ try:+ with open(args.declaration, encoding="utf-8") as f:+ declaration = json.load(f)+ with open(args.manifest, encoding="utf-8") as f:+ manifest = json.load(f)+ except (OSError, json.JSONDecodeError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 1++ errors = check(declaration, manifest, args.extension_bundle_id)+ for e in errors:+ print(f"error: {args.declaration}: {e}", file=sys.stderr)+ if errors:+ return 1+ print(f"ok: {args.declaration}")+ return 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/packaging/macos/safari/compatibility.md b/packaging/macos/safari/compatibility.mdnew file mode 100644index 00000000..6bb130d9--- /dev/null+++ b/packaging/macos/safari/compatibility.md@@ -0,0 +1,143 @@+# Safari compatibility of the browser collector++Researched 2026-09-23 against Apple's developer documentation, Apple Developer+Forums answers from Apple engineers, and MDN's browser-compat-data (the table+Apple's own docs point to). **Nothing here has been run in Safari yet.** Every+"supported" below means *documented as supported*. Each item names the manual+check in [`smoke-checklist.md`](smoke-checklist.md) that confirms it.++## What the extension uses, and what Safari documents++| Extension feature (from `browser-extension/src/manifest.json` and `src/`) | Safari support | Source | Verify with |+|---|---|---|---|+| Manifest V3 | Safari 15.4+ supports MV2 and MV3 | [Assessing browser compatibility][assess] | S1 |+| `background.service_worker` | Safari 15.4+ | [BCD background][bcd-bg] | S2 |+| `background.scripts` + `preferred_environment` (a fallback, if one is needed) | `scripts` Safari 14+; `preferred_environment` Safari 18+ | [BCD background][bcd-bg] | only if S5 fails |+| `content_scripts[].world: "MAIN"` (the interceptor depends on it) | **Safari 18+** | [BCD content_scripts][bcd-cs] | S3 |+| `scripting.executeScript` with `world: "MAIN"` (fallback if the manifest key misbehaves) | Safari 15.4+ | [BCD scripting][bcd-scripting] | only if S3 fails |+| `scripting.registerContentScripts` with `world` | Safari 16.4+; an Apple engineer confirmed MAIN is supported there | [BCD scripting][bcd-scripting], [forum 728849][forum-main] | only if S3 fails |+| `content_scripts[].run_at: "document_start"` | Safari 14+, **but** scripts are not injected until the user grants site access; later loads honour `run_at` | [BCD content_scripts][bcd-cs] | S3, S4 |+| `host_permissions` | Safari 15.4+, but **not granted at install**: the user grants each site (once, for a day, or always) from the toolbar, or in Safari Settings > Websites | [Managing permissions][perms] | S4 |+| `web_accessible_resources` object form (`resources`, `matches`) | Safari 15.4+. `use_dynamic_url` is always effectively on | [BCD WAR][bcd-war] | S3 |+| `options_page` | Safari 14+ | [BCD options_page][bcd-options] | S8 |+| `action.default_popup` | Safari 15.4+ | [BCD action][bcd-action] | S8 |+| `storage.local` (durable delivery queue, settings) | Supported; 5 MB limit unless `unlimitedStorage` | [Assessing browser compatibility][assess] | S7 |+| `alarms.create` / `alarms.onAlarm` (delivery retry) | Safari 14+ | [BCD alarms][bcd-alarms] | S7 |+| `runtime.sendMessage` / `onMessage` / `onInstalled` / `getPlatformInfo` / `id` | Safari 14+ | [BCD runtime][bcd-runtime] | S2, S5 |+| `chrome.*` namespace (the source calls `chrome.*` directly) | **Supported.** Safari exposes both `chrome.*` and `browser.*`, with callbacks and Promises | [Assessing browser compatibility][assess] | S1 |+| Service-worker `fetch` POST to `http://127.0.0.1:4318/v1/logs` | See "Reaching the collector" below | — | S5 |++Minimum Safari for the current manifest: **18**, because of the MAIN-world+content script. Safari 18 runs on macOS 13 Ventura and later.++## Reaching the collector++The issue expected two macOS network gates to apply. Both look unlikely to apply,+and a third gate, not in the issue, is the real risk.++1. **Local Network privacy prompt: not expected.** [TN3179][tn3179] defines a+ local network as an IP network on a broadcast-capable interface (Wi-Fi,+ Ethernet); loopback is not one. It also says, in so many words, "Traffic+ originating from WKWebView, SFSafariViewController, and Safari doesn't+ require local network access." The extension's `fetch` runs inside Safari,+ not in the wrapper app's process.+2. **App Transport Security exception (`NSAllowsLocalNetworking`): probably not+ needed.** ATS governs the app's own `URLSession` traffic. The extension's+ JavaScript runs in Safari's web and networking processes. Apple's Safari+ extension docs say nothing about ATS for extension `fetch`. If S5 shows an ATS+ error in the service worker console, add `NSAppTransportSecurity` >+ `NSAllowsLocalNetworking = YES` to the **extension target's** `Info.plist`+ and retest. Do not add it to the app's.+3. **CORS in the service worker: the real risk.** Safari bypasses CORS for+ background fetches only to hosts the extension *has been granted*+ ([forum 654839][forum-cors], Apple engineer). Host permissions start in "ask"+ mode in Safari ([Managing permissions][perms]). And there is a reported+ Safari bug where the bypass works for background *pages* but not background+ *service workers* ([repro repo][sw-cors-bug]; the same forum thread suggests+ `background.scripts` as the workaround). The collector's OTLP/HTTP receiver+ has no CORS configuration. The POST sends `content-type: application/json`,+ which forces a preflight. So an ungranted or unbypassed request fails with+ "Fetch API cannot load http://127.0.0.1:4318/v1/logs due to access control+ checks", and nothing is captured. Mitigations, in order of preference:+ - Grant `127.0.0.1` site access, either by the user or through MDM+ `AllowedDomains` (see [`mdm/`](mdm/)). This is the first thing to try in S5.+ - If the service worker still fails once access is granted, ship a Safari+ manifest variant with `background.scripts` (plus+ `preferred_environment: ["document", "service_worker"]`). That needs the+ per-target manifest build owned by #393.+ - Last resort: add a `cors.allowed_origins` entry for+ `safari-web-extension://*` to the collector's OTLP HTTP receiver.+ Safari changes the extension's origin UUID on every launch+ ([forum 654839][forum-cors]), so an exact origin cannot be pinned. A wildcard+ would let any Safari extension post to the collector, so treat this as a+ security change, not a packaging tweak.++## Gap list++Blocking. Must be confirmed on a Mac before Safari counts as supported:++- **G1: collector reachability (S5).** The CORS and host-grant behaviour above.+ If this fails, nothing is captured.+- **G2: MAIN-world interceptor (S3).** Documented for Safari 18, but not yet+ observed teeing `window.fetch` on claude.ai and chatgpt.com in Safari.+- **G3: site-access grants.** Content scripts do not run on claude.ai or+ chatgpt.com until the user grants access. Unmanaged users need an onboarding+ step. Managed fleets can pre-grant with MDM `AllowedDomains`, but only on+ supervised macOS 15+ (see [`README.md`](README.md#mdm)).++Non-blocking differences:++- **G4: service-worker lifetime.** Safari's MV3 background is non-persistent,+ like Chrome's. The in-memory assembler has the same mid-stream-suspension+ limitation the README already lists. Safari's idle timeout is not documented.+- **G5: no `update_url`.** Apple says to deliver Safari extension updates+ through the App Store ([Assessing browser compatibility][assess]). A+ Developer ID build updates only when a newer app is installed, by a package or+ by MDM.+- **G6: sites' streaming in WebKit.** claude.ai and chatgpt.com may serve WebKit a+ different transport, such as XHR or a different SSE framing. The adapters are+ fixture-tested on Chromium captures only. Record a Safari fixture if S4 or S6+ shows different traffic.+- **G7: no automated in-browser test.** Playwright cannot load extensions into+ WebKit, and `safaridriver` cannot install them. The replay e2e stays+ Chromium-only. Safari is covered by the unit tests, which are+ browser-agnostic, plus the manual checklist.+- **G8: browser identity.** Safari events carry the same `claude_web` and+ `chatgpt_web` harness names. The browser-identity attribute is #394's work.++Not needed for Safari:++- **A `browser.*` shim.** Safari supports `chrome.*` natively. The shim #393 adds+ is harmless here but not required.+- **The Local Network usage string (`NSLocalNetworkUsageDescription`).** See+ "Reaching the collector" above.++## Sources++- [Assessing your Safari web extension's browser compatibility][assess]+- [Managing Safari web extension permissions][perms]+- [Packaging a web extension for Safari][packaging]+- [Running your Safari web extension][running]+- [TN3179: Understanding local network privacy][tn3179]+- [Safari 18 release notes][safari18]: Device Management of extension state, private browsing, and website access+- MDN browser-compat-data: [manifest `background`][bcd-bg], [manifest `content_scripts`][bcd-cs], [manifest `web_accessible_resources`][bcd-war], [manifest `options_page`][bcd-options], [manifest `action`][bcd-action], [`scripting`][bcd-scripting], [`alarms`][bcd-alarms], [`runtime`][bcd-runtime]+- Apple Developer Forums: [world MAIN support (728849)][forum-main], [background CORS (654839)][forum-cors]+- [Safari service-worker background CORS repro][sw-cors-bug]++[assess]: https://developer.apple.com/documentation/safariservices/assessing-your-safari-web-extension-s-browser-compatibility+[perms]: https://developer.apple.com/documentation/safariservices/managing-safari-web-extension-permissions+[packaging]: https://developer.apple.com/documentation/safariservices/packaging-a-web-extension-for-safari+[running]: https://developer.apple.com/documentation/safariservices/running-your-safari-web-extension+[tn3179]: https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy+[safari18]: https://developer.apple.com/documentation/safari-release-notes/safari-18-release-notes+[bcd-bg]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/manifest/background.json+[bcd-cs]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/manifest/content_scripts.json+[bcd-war]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/manifest/web_accessible_resources.json+[bcd-options]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/manifest/options_page.json+[bcd-action]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/manifest/action.json+[bcd-scripting]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/api/scripting.json+[bcd-alarms]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/api/alarms.json+[bcd-runtime]: https://github.com/mdn/browser-compat-data/blob/main/webextensions/api/runtime.json+[forum-main]: https://developer.apple.com/forums/thread/728849+[forum-cors]: https://developer.apple.com/forums/thread/654839+[sw-cors-bug]: https://github.com/JamiesWhiteShirt/safari-service-worker-background-bugdiff --git a/packaging/macos/safari/create-safari-project.sh b/packaging/macos/safari/create-safari-project.shnew file mode 100755index 00000000..ee260892--- /dev/null+++ b/packaging/macos/safari/create-safari-project.sh@@ -0,0 +1,247 @@+#!/bin/sh+# Generate the Xcode app wrapper for the Safari build of the Beacon browser+# collector (browser-extension/) with Apple's Safari web extension packager.+#+# Safari has no "load unpacked": a Safari web extension ships inside a macOS app+# bundle, and that app is built with Xcode. This script wraps+# `xcrun safari-web-extension-packager` (formerly `safari-web-extension-converter`;+# both names are tried) so the bundle identifiers and flags are the same on every+# machine, and so the generated project is disposable: regenerate it from a fresh+# extension build instead of committing and hand-editing it.+#+# It does not sign, notarize, or build the app. See packaging/macos/safari/README.md.+set -eu++ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd)"++EXTENSION_DIR="${SAFARI_EXTENSION_DIR:-$ROOT_DIR/browser-extension/dist}"+PROJECT_DIR="${SAFARI_PROJECT_DIR:-$ROOT_DIR/dist/safari}"+APP_NAME="${SAFARI_APP_NAME:-Beacon Browser Collector}"+BUNDLE_IDENTIFIER="${SAFARI_BUNDLE_IDENTIFIER:-ai.asymptote.beacon.browser-collector}"+PLATFORM="macos"+COPY_RESOURCES=1+FORCE=0+DRY_RUN=0++# The bundles and static files a loadable build must contain. Kept in step with+# the "Verify the build produced a loadable MV3 extension" step in ci.yml.+REQUIRED_FILES="manifest.json sw.js content.js interceptor.js popup.html popup.js options.html options.js"++usage() {+ cat <<'USAGE'+Usage:+ sh packaging/macos/safari/create-safari-project.sh [options]++Build the extension first (cd browser-extension && npm ci && npm run build),+then run this on a Mac with Xcode installed.++Options:+ --extension-dir DIR Built extension to wrap (default: browser-extension/dist).+ --project-dir DIR Directory the Xcode project is written under+ (default: dist/safari). The packager creates+ DIR/<app name>/.+ --app-name NAME App and Xcode project name+ (default: "Beacon Browser Collector").+ --bundle-id ID App bundle identifier+ (default: ai.asymptote.beacon.browser-collector).+ The packager derives the extension's identifier from it.+ --platform PLATFORM macos (default), ios, or all.+ --reference-resources Reference the extension files in place instead of+ copying them into the project. Handy for a local edit,+ rebuild, Product > Build loop; not for release builds.+ --force Overwrite an existing project directory.+ --dry-run Validate the inputs and print the packager command+ without running it. Works on any OS.+ -h, --help Show this help.++Environment defaults: SAFARI_EXTENSION_DIR, SAFARI_PROJECT_DIR, SAFARI_APP_NAME,+SAFARI_BUNDLE_IDENTIFIER.+USAGE+}++die() {+ echo "error: $*" >&2+ exit 1+}++# Print one argument quoted for a POSIX shell, so --dry-run output can be pasted.+quote() {+ printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"+}++require_value() {+ [ "$2" -ge 2 ] || die "$1 requires a value"+}++while [ "$#" -gt 0 ]; do+ case "$1" in+ --extension-dir)+ require_value "$1" "$#"+ EXTENSION_DIR="$2"+ shift 2+ ;;+ --project-dir)+ require_value "$1" "$#"+ PROJECT_DIR="$2"+ shift 2+ ;;+ --app-name)+ require_value "$1" "$#"+ APP_NAME="$2"+ shift 2+ ;;+ --bundle-id)+ require_value "$1" "$#"+ BUNDLE_IDENTIFIER="$2"+ shift 2+ ;;+ --platform)+ require_value "$1" "$#"+ PLATFORM="$2"+ shift 2+ ;;+ --reference-resources)+ COPY_RESOURCES=0+ shift+ ;;+ --force)+ FORCE=1+ shift+ ;;+ --dry-run)+ DRY_RUN=1+ shift+ ;;+ -h|--help)+ usage+ exit 0+ ;;+ *)+ die "unknown argument: $1"+ ;;+ esac+done++# --- Validate inputs (on every OS, so --dry-run exercises the same checks) ---++case "$PLATFORM" in+ macos|ios|all) ;;+ *) die "--platform must be macos, ios, or all (got '$PLATFORM')" ;;+esac++[ -n "$APP_NAME" ] || die "--app-name must not be empty"+case "$APP_NAME" in+ */*) die "--app-name must not contain '/' (got '$APP_NAME')" ;;+esac++# Apple bundle identifiers: reverse-DNS, ASCII letters, digits, hyphens, periods.+if ! printf '%s\n' "$BUNDLE_IDENTIFIER" | grep -Eq '^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$'; then+ die "--bundle-id must be a reverse-DNS identifier of letters, digits, hyphens, and periods (got '$BUNDLE_IDENTIFIER')"+fi++[ -d "$EXTENSION_DIR" ] || die "extension directory not found: $EXTENSION_DIR (run 'npm ci && npm run build' in browser-extension first)"+EXTENSION_DIR="$(CDPATH= cd -- "$EXTENSION_DIR" && pwd)"++for f in $REQUIRED_FILES; do+ [ -s "$EXTENSION_DIR/$f" ] || die "missing or empty $f in $EXTENSION_DIR; is this a complete extension build?"+done+if ! grep -Eq '"manifest_version"[[:space:]]*:[[:space:]]*3([^0-9]|$)' "$EXTENSION_DIR/manifest.json"; then+ die "$EXTENSION_DIR/manifest.json is not a Manifest V3 manifest"+fi+if [ -n "$(find "$EXTENSION_DIR" -name '*.map' -print 2>/dev/null | head -n 1)" ]; then+ echo "warning: $EXTENSION_DIR contains sourcemaps (*.map); delete them before a release build, as release-extension.yml does for the Chrome zip" >&2+fi++# Make the project path absolute without creating it: validation and --dry-run+# have no side effects.+if [ -d "$PROJECT_DIR" ]; then+ PROJECT_DIR="$(CDPATH= cd -- "$PROJECT_DIR" && pwd)"+else+ case "$PROJECT_DIR" in+ /*) ;;+ *) PROJECT_DIR="$(pwd)/$PROJECT_DIR" ;;+ esac+fi+case "$PROJECT_DIR/" in+ "$EXTENSION_DIR"/*) die "--project-dir must not be inside the extension directory ($EXTENSION_DIR); the packager would wrap its own output" ;;+esac++OUTPUT_DIR="$PROJECT_DIR/$APP_NAME"+if [ -e "$OUTPUT_DIR" ] && [ "$FORCE" -ne 1 ]; then+ die "$OUTPUT_DIR already exists; pass --force to overwrite it"+fi++# --- Build the packager argument list ---++set -- "$EXTENSION_DIR" \+ --project-location "$PROJECT_DIR" \+ --app-name "$APP_NAME" \+ --bundle-identifier "$BUNDLE_IDENTIFIER" \+ --swift \+ --no-open \+ --no-prompt+case "$PLATFORM" in+ macos) set -- "$@" --macos-only ;;+ ios) set -- "$@" --ios-only ;;+ all) ;;+esac+if [ "$COPY_RESOURCES" -eq 1 ]; then+ set -- "$@" --copy-resources+fi+if [ "$FORCE" -eq 1 ]; then+ set -- "$@" --force+fi++print_command() {+ tool="$1"+ shift+ printf 'xcrun %s' "$tool"+ for arg in "$@"; do+ printf ' %s' "$(quote "$arg")"+ done+ printf '\n'+}++if [ "$DRY_RUN" -eq 1 ]; then+ print_command safari-web-extension-packager "$@"+ exit 0+fi++# --- Run on macOS only ---++if [ "$(uname -s)" != "Darwin" ]; then+ die "the Safari web extension packager ships with Xcode and only runs on macOS; use --dry-run to check arguments elsewhere"+fi+command -v xcrun >/dev/null 2>&1 || die "xcrun not found; install Xcode (the Command Line Tools alone do not include the Safari packager)"++TOOL=""+for candidate in safari-web-extension-packager safari-web-extension-converter; do+ if xcrun --find "$candidate" >/dev/null 2>&1; then+ TOOL="$candidate"+ break+ fi+done+[ -n "$TOOL" ] || die "neither safari-web-extension-packager nor safari-web-extension-converter is available through xcrun; install full Xcode and select it with 'sudo xcode-select -s /Applications/Xcode.app'"++mkdir -p "$PROJECT_DIR" || die "cannot create project directory: $PROJECT_DIR"+print_command "$TOOL" "$@"+xcrun "$TOOL" "$@"++# Prefer DIR/<app name>/ so a stale project from another --app-name is not reported.+SEARCH_DIR="$PROJECT_DIR"+[ -d "$OUTPUT_DIR" ] && SEARCH_DIR="$OUTPUT_DIR"+PROJECT_FILE="$(find "$SEARCH_DIR" -maxdepth 3 -name '*.xcodeproj' -type d -print 2>/dev/null | head -n 1)"+[ -n "$PROJECT_FILE" ] || die "$TOOL exited 0 but no .xcodeproj was found under $SEARCH_DIR"++echo "Xcode project: $PROJECT_FILE"+if [ -f "$PROJECT_FILE/project.pbxproj" ]; then+ echo "Bundle identifiers in the project:"+ sed -n 's/.*PRODUCT_BUNDLE_IDENTIFIER = "\{0,1\}\([^";]*\)"\{0,1\};.*/ \1/p' "$PROJECT_FILE/project.pbxproj" | sort -u+fi+cat <<EOF+Next steps (see packaging/macos/safari/README.md):+ - Open the project in Xcode, set the signing team, and build the app scheme.+ - Run the manual checklist in packaging/macos/safari/smoke-checklist.md.+ - For MDM, the extension's composed identifier is "<extension bundle id> (<team id>)";+ read it from the built .appex with: codesign -dv "<App>.app/Contents/PlugIns/<Extension>.appex"+EOFdiff --git a/packaging/macos/safari/mdm/safari-extension-settings.declaration.json b/packaging/macos/safari/mdm/safari-extension-settings.declaration.jsonnew file mode 100644index 00000000..15c1ccb0--- /dev/null+++ b/packaging/macos/safari/mdm/safari-extension-settings.declaration.json@@ -0,0 +1,20 @@+{+ "Type": "com.apple.configuration.safari.extensions.settings",+ "Identifier": "ai.asymptote.beacon.browser-collector.safari-extension-settings",+ "ServerToken": "beacon-browser-collector-safari-1",+ "Payload": {+ "ManagedExtensions": {+ "ai.asymptote.beacon.browser-collector.Extension (TEAMID1234)": {+ "State": "AlwaysOn",+ "PrivateBrowsing": "Allowed",+ "AllowedDomains": [+ "claude.ai",+ "chatgpt.com",+ "chat.openai.com",+ "127.0.0.1",+ "localhost"+ ]+ }+ }+ }+}diff --git a/packaging/macos/safari/smoke-checklist.md b/packaging/macos/safari/smoke-checklist.mdnew file mode 100644index 00000000..8f72db65--- /dev/null+++ b/packaging/macos/safari/smoke-checklist.md@@ -0,0 +1,90 @@+# Safari manual smoke checklist++Safari has no automated in-browser test. Playwright cannot load extensions into+WebKit, and `safaridriver` cannot install them. The Playwright replay e2e in+`browser-extension/e2e/` therefore runs on Chromium only, and it remains the+correctness gate for the site adapters. Run this checklist by hand on a Mac for+every Safari build you intend to hand to users, and record the results in the+pull request or release notes.++The IDs (S1 to S10) are referenced from [`compatibility.md`](compatibility.md).++## Setup++- A Mac with Safari 18 or later (Safari > About Safari). Safari 18 is the first+ version documented to support `world: "MAIN"` in manifest content scripts.+- The Beacon endpoint agent installed and running, so the collector is listening+ on `127.0.0.1:4318`:++ ```bash+ beacon endpoint status # add --system for the package install+ lsof -nP -iTCP:4318 -sTCP:LISTEN+ ```++- A fresh extension build:++ ```bash+ cd browser-extension && npm ci && npm run build && cd ..+ ```++- Safari > Settings > Advanced: turn on "Show features for web developers".++Choose one of two ways to load the build:++- **Quick (no Xcode, unsigned):** Safari > Settings > Developer > turn on+ "Allow unsigned extensions", then "Add Temporary Extension…" and select+ `browser-extension/dist`. Safari removes temporary extensions after 24 hours or+ when you quit Safari, and "Allow unsigned extensions" also resets on quit.+- **App wrapper (what users get):**++ ```bash+ sh packaging/macos/safari/create-safari-project.sh+ open "dist/safari/Beacon Browser Collector/Beacon Browser Collector.xcodeproj"+ ```++ In Xcode, set the signing team on both targets, select the macOS app scheme,+ and choose Product > Run. Then enable the extension in Safari > Settings >+ Extensions.++Keep the runtime log open in a terminal throughout:++```bash+tail -f ~/.beacon/endpoint/logs/runtime.jsonl # user install+sudo tail -f /var/log/beacon-agent/runtime.jsonl # system/package install+```++## Checks++| ID | Check | Pass when |+|---|---|---|+| S1 | **Loads.** The extension appears in Safari > Settings > Extensions with name "Agent Beacon — Browser Collector" and the manifest's version, and can be enabled. If you used the app wrapper, note any packager warnings about unsupported manifest keys. | Enabled, no load error. Any packager warnings are copied into the results. |+| S2 | **Service worker starts.** Develop > Web Extension Background Content (or the extension's service worker entry in the Develop menu) opens an inspector for `sw.js`. | The console shows no uncaught errors at startup. |+| S3 | **MAIN-world interceptor runs.** Grant the extension access to claude.ai (toolbar button > Always Allow on This Website), reload claude.ai, open the page's Web Inspector, and check that `window.fetch` has been wrapped. For example, `window.fetch.toString()` does not print `[native code]`. | The interceptor is installed before the page's first chat request. |+| S4 | **Site-access flow.** On a site you have not granted yet, the toolbar badge asks for access and capture does not happen. After you grant access, capture works. | The behaviour matches Safari's documented ask-first model. Write down the exact prompts shown; users will see the same ones. |+| S5 | **Reaches the collector.** Grant access to `127.0.0.1` too, if Safari lists it: Safari > Settings > Websites > the extension, or "Always Allow on Every Website" for a test profile only. Send a claude.ai message and watch the service worker inspector's Network and Console tabs. | The `POST http://127.0.0.1:4318/v1/logs` returns 200. There is no "access control checks" (CORS) error, no ATS error, and no Local Network prompt from macOS. If it fails, record the exact console error and see "Reaching the collector" in `compatibility.md`. |+| S6 | **claude.ai end to end.** Send one message on claude.ai. | `runtime.jsonl` gains a `prompt.submitted` and an `agent.response.completed` event with harness `claude_web`, the right model, and the prompt and response text (with retention `full`). |+| S7 | **chatgpt.com end to end.** Send one message on chatgpt.com. | The same pair of events, with harness `chatgpt_web`. |+| S8 | **Retention control.** In the popup, set retention to `metadata` and send a message, then `redacted` with an email address in the prompt, then back to `full`. The options page (Safari > Settings > Extensions > the extension > Settings) shows the OTLP endpoint and the per-site toggles. | Under `metadata` the new events carry no prompt or response text. Under `redacted` the email is scrubbed. Under `full` the text returns. Settings persist across a Safari restart. |+| S9 | **Collector down, then up.** Stop the collector, send a message, then start it again. Package install: `sudo launchctl bootout system/com.beacon.endpoint.collector`, then `sudo launchctl bootstrap system /Library/LaunchDaemons/com.beacon.endpoint.collector.plist`. User install: the same with `gui/$(id -u)/com.beacon.endpoint.collector.user` and `~/Library/LaunchAgents/com.beacon.endpoint.collector.user.plist`. | The popup's queue depth rises while the collector is down. Within about a minute of restarting it (alarms-driven retry), the queued events land in `runtime.jsonl` and the queue drains. Keep the outage to a minute or two: `delivery.ts` drops an item after 6 failed attempts. |+| S10 | **Scope.** Browse an unrelated site with the extension enabled. | No events, and the extension requests no access to that site. |++## MDM (only for managed-fleet validation)++Run this on a **supervised** Mac with macOS 15 or later, enrolled in an MDM that+supports Declarative Device Management. Use a signed build, not a temporary+extension.++| ID | Check | Pass when |+|---|---|---|+| M1 | Install the signed app. Read the extension's composed identifier with `codesign -dv "/Applications/Beacon Browser Collector.app/Contents/PlugIns/"*.appex`: the `Identifier=` value plus ` (<TeamIdentifier>)`. | The identifier matches the key in `mdm/safari-extension-settings.declaration.json` once `TEAMID1234` is replaced. |+| M2 | Deploy the declaration. Open Safari. | The extension is on and cannot be turned off (`State: AlwaysOn`), and claude.ai, chatgpt.com and `127.0.0.1` need no user grant (`AllowedDomains`). |+| M3 | Repeat S5 to S7 without granting anything by hand. | Capture works end to end. Also note whether the app had to be launched once before Safari listed the extension. |++## Signed build (only for release candidates)++| ID | Check | Pass when |+|---|---|---|+| R1 | `codesign --verify --deep --strict --verbose=2 "Beacon Browser Collector.app"` | Valid, with a Developer ID Application authority. |+| R2 | `xcrun stapler validate "Beacon Browser Collector.app"` (and the `.pkg`, if one is built) | "The validate action worked!" |+| R3 | `spctl --assess --type execute -vv "Beacon Browser Collector.app"` | `accepted`, `source=Notarized Developer ID`. |+| R4 | On a clean Mac or VM without "Allow unsigned extensions" turned on, install the release artifact and repeat S1, S5 and S6. | The extension works without any developer setting. |diff --git a/packaging/macos/safari/test-safari-packaging.sh b/packaging/macos/safari/test-safari-packaging.shnew file mode 100755index 00000000..6e64960c--- /dev/null+++ b/packaging/macos/safari/test-safari-packaging.sh@@ -0,0 +1,334 @@+#!/bin/sh+# Checks for the Safari packaging helpers. Runs on Linux and macOS: the packager+# itself is replaced by a fake xcrun and uname is faked both ways, so what is+# tested here is the wrapper's argument handling and guards, not Apple's tool.+# The real conversion is a manual step on a Mac (see smoke-checklist.md).+set -eu++ROOT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")/../../.." && pwd)"+SAFARI_DIR="$ROOT_DIR/packaging/macos/safari"+SCRIPT="$SAFARI_DIR/create-safari-project.sh"+CHECKER="$SAFARI_DIR/check-mdm-declaration.py"+DECLARATION="$SAFARI_DIR/mdm/safari-extension-settings.declaration.json"+MANIFEST="$ROOT_DIR/browser-extension/src/manifest.json"+TMP_DIR="$(mktemp -d)"+trap 'rm -rf "$TMP_DIR"' EXIT INT TERM++unset SAFARI_EXTENSION_DIR SAFARI_PROJECT_DIR SAFARI_APP_NAME SAFARI_BUNDLE_IDENTIFIER++command -v python3 >/dev/null 2>&1 || { echo "python3 is required to validate the MDM declaration" >&2; exit 1; }++fail() {+ echo "FAIL: $*" >&2+ exit 1+}++# expect_fail NAME PATTERN -- CMD...: CMD must exit non-zero and print PATTERN on stderr.+expect_fail() {+ name="$1"+ pattern="$2"+ shift 3+ if "$@" >"$TMP_DIR/out" 2>"$TMP_DIR/err"; then+ fail "$name: expected a non-zero exit"+ fi+ grep -q -- "$pattern" "$TMP_DIR/err" || fail "$name: stderr did not contain '$pattern': $(cat "$TMP_DIR/err")"+}++# A complete fake build: every file the wrapper requires, and the real manifest.+make_extension() {+ dir="$1"+ mkdir -p "$dir"+ cp "$MANIFEST" "$dir/manifest.json"+ for f in sw.js content.js interceptor.js popup.html popup.js options.html options.js; do+ printf '// %s\n' "$f" >"$dir/$f"+ done+}++EXT="$TMP_DIR/ext"+make_extension "$EXT"+PROJECTS="$TMP_DIR/projects"++# Fake bin directories. The Linux one has an xcrun that must never run.+LINUX_BIN="$TMP_DIR/linux-bin"+DARWIN_BIN="$TMP_DIR/darwin-bin"+XCRUN_LOG="$TMP_DIR/xcrun.log"+mkdir -p "$LINUX_BIN" "$DARWIN_BIN"+printf '#!/bin/sh\necho Linux\n' >"$LINUX_BIN/uname"+printf '#!/bin/sh\necho Darwin\n' >"$DARWIN_BIN/uname"+cat >"$LINUX_BIN/xcrun" <<'STUB'+#!/bin/sh+echo "xcrun must not run off macOS" >>"$XCRUN_LOG"+exit 99+STUB+# FAKE_XCRUN_TOOLS: space-separated tools that `xcrun --find` reports.+# FAKE_XCRUN_CREATE=1: create DIR/<app>/<app>.xcodeproj like the real packager.+# FAKE_XCRUN_STATUS: exit status of the tool run.+cat >"$DARWIN_BIN/xcrun" <<'STUB'+#!/bin/sh+if [ "$1" = "--find" ]; then+ for t in ${FAKE_XCRUN_TOOLS:-}; do+ [ "$t" = "$2" ] && { echo "/fake/$t"; exit 0; }+ done+ exit 1+fi+: >"$XCRUN_LOG"+for a in "$@"; do printf '%s\n' "$a" >>"$XCRUN_LOG"; done+location=""+app=""+while [ "$#" -gt 0 ]; do+ case "$1" in+ --project-location) location="$2"; shift 2 ;;+ --app-name) app="$2"; shift 2 ;;+ *) shift ;;+ esac+done+if [ "${FAKE_XCRUN_CREATE:-0}" = "1" ]; then+ mkdir -p "$location/$app/$app.xcodeproj"+ cat >"$location/$app/$app.xcodeproj/project.pbxproj" <<EOF+ PRODUCT_BUNDLE_IDENTIFIER = ai.asymptote.beacon.browser-collector;+ PRODUCT_BUNDLE_IDENTIFIER = ai.asymptote.beacon.browser-collector.Extension;+EOF+fi+exit "${FAKE_XCRUN_STATUS:-0}"+STUB+chmod +x "$LINUX_BIN/uname" "$LINUX_BIN/xcrun" "$DARWIN_BIN/uname" "$DARWIN_BIN/xcrun"+export XCRUN_LOG++run_linux() {+ PATH="$LINUX_BIN:$PATH" sh "$SCRIPT" "$@"+}+run_darwin() {+ PATH="$DARWIN_BIN:$PATH" sh "$SCRIPT" "$@"+}++# --- syntax and help ---++sh -n "$SCRIPT"+sh -n "$0"+run_linux --help >"$TMP_DIR/out" || fail "--help should exit 0"+grep -q '^Usage:' "$TMP_DIR/out" || fail "--help should print usage"++# --- argument handling ---++expect_fail "unknown argument" "unknown argument: --bogus" -- run_linux --bogus+expect_fail "flag without value" "--app-name requires a value" -- run_linux --app-name+expect_fail "empty app name" "must not be empty" -- run_linux --dry-run --extension-dir "$EXT" --app-name ""+expect_fail "app name with slash" "must not contain '/'" -- run_linux --dry-run --extension-dir "$EXT" --app-name "a/b"+expect_fail "bundle id with space" "reverse-DNS identifier" -- run_linux --dry-run --extension-dir "$EXT" --bundle-id "ai.asymptote bad"+expect_fail "bundle id without dot" "reverse-DNS identifier" -- run_linux --dry-run --extension-dir "$EXT" --bundle-id "beacon"+expect_fail "bundle id with underscore" "reverse-DNS identifier" -- run_linux --dry-run --extension-dir "$EXT" --bundle-id "ai.asymptote.bad_id"+expect_fail "unknown platform" "--platform must be macos, ios, or all" -- run_linux --dry-run --extension-dir "$EXT" --platform windows++# --- extension build validation ---++expect_fail "missing extension dir" "extension directory not found" -- run_linux --dry-run --extension-dir "$TMP_DIR/nope"++INCOMPLETE="$TMP_DIR/incomplete"+make_extension "$INCOMPLETE"+rm "$INCOMPLETE/interceptor.js"+expect_fail "incomplete build" "missing or empty interceptor.js" -- run_linux --dry-run --extension-dir "$INCOMPLETE"++EMPTY_FILE="$TMP_DIR/empty-file"+make_extension "$EMPTY_FILE"+: >"$EMPTY_FILE/sw.js"+expect_fail "empty bundle" "missing or empty sw.js" -- run_linux --dry-run --extension-dir "$EMPTY_FILE"++MV2="$TMP_DIR/mv2"+make_extension "$MV2"+printf '{ "manifest_version": 2, "name": "x", "version": "1" }\n' >"$MV2/manifest.json"+expect_fail "MV2 manifest" "is not a Manifest V3 manifest" -- run_linux --dry-run --extension-dir "$MV2"++MV30="$TMP_DIR/mv30"+make_extension "$MV30"+printf '{ "manifest_version": 30 }\n' >"$MV30/manifest.json"+expect_fail "manifest_version 30 is not 3" "is not a Manifest V3 manifest" -- run_linux --dry-run --extension-dir "$MV30"++WITH_MAPS="$TMP_DIR/with-maps"+make_extension "$WITH_MAPS"+printf '{}\n' >"$WITH_MAPS/sw.js.map"+run_linux --dry-run --extension-dir "$WITH_MAPS" --project-dir "$PROJECTS" >/dev/null 2>"$TMP_DIR/err" ||+ fail "a build with sourcemaps should still convert"+grep -q 'contains sourcemaps' "$TMP_DIR/err" || fail "sourcemaps should produce a warning"++# --- dry run: the packager command, on any OS, with no side effects ---++run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" >"$TMP_DIR/out" 2>"$TMP_DIR/err" ||+ fail "default dry run should succeed off macOS: $(cat "$TMP_DIR/err")"+[ ! -e "$PROJECTS" ] || fail "--dry-run must not create the project directory"+[ ! -s "$XCRUN_LOG" ] || fail "--dry-run must not run xcrun"+[ ! -s "$TMP_DIR/err" ] || fail "default dry run should print no warnings: $(cat "$TMP_DIR/err")"++# Evaluate the printed command with xcrun replaced by an argument dumper, so+# the check covers the quoting as well as the flags.+dump_args() {+ (+ xcrun() {+ for a in "$@"; do printf '%s\n' "$a"; done+ }+ eval "$(cat "$1")"+ )+}+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+cat >"$TMP_DIR/want" <<EOF+safari-web-extension-packager+$EXT+--project-location+$PROJECTS+--app-name+Beacon Browser Collector+--bundle-identifier+ai.asymptote.beacon.browser-collector+--swift+--no-open+--no-prompt+--macos-only+--copy-resources+EOF+diff -u "$TMP_DIR/want" "$TMP_DIR/args" >&2 || fail "default packager arguments changed"++has_arg() { grep -qx -- "$1" "$TMP_DIR/args"; }++run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" --platform all >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+if has_arg --macos-only || has_arg --ios-only; then fail "--platform all should pass neither platform flag"; fi++run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" --platform ios >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+has_arg --ios-only || fail "--platform ios should pass --ios-only"+if has_arg --macos-only; then fail "--platform ios should not pass --macos-only"; fi++run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" --reference-resources --force >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+if has_arg --copy-resources; then fail "--reference-resources should drop --copy-resources"; fi+has_arg --force || fail "--force should be passed to the packager"++# Names with spaces and quotes survive the round trip; env defaults apply.+(+ export SAFARI_APP_NAME="Beacon's Collector" SAFARI_BUNDLE_IDENTIFIER="com.example.beacon-test"+ run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS"+) >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+has_arg "Beacon's Collector" || fail "SAFARI_APP_NAME with a quote should round-trip"+has_arg "com.example.beacon-test" || fail "SAFARI_BUNDLE_IDENTIFIER should set the bundle identifier"++# Relative paths are made absolute.+(cd "$TMP_DIR" && PATH="$LINUX_BIN:$PATH" sh "$SCRIPT" --dry-run --extension-dir ext --project-dir rel-projects) >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+has_arg "$TMP_DIR/rel-projects" || fail "a relative --project-dir should be made absolute"+has_arg "$EXT" || fail "a relative --extension-dir should be made absolute"++# --- output directory guards ---++mkdir -p "$PROJECTS/Beacon Browser Collector"+expect_fail "existing output dir" "already exists; pass --force" -- run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS"+run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" --force >/dev/null ||+ fail "--force should allow an existing output directory"+rm -rf "$PROJECTS"++expect_fail "project inside extension" "must not be inside the extension directory" -- run_linux --dry-run --extension-dir "$EXT" --project-dir "$EXT/safari"+expect_fail "project is extension dir" "must not be inside the extension directory" -- run_linux --dry-run --extension-dir "$EXT" --project-dir "$EXT"++# --- off-macOS guard ---++expect_fail "Linux run" "only runs on macOS" -- run_linux --extension-dir "$EXT" --project-dir "$PROJECTS"+[ ! -s "$XCRUN_LOG" ] || fail "xcrun must not run off macOS"+[ ! -e "$PROJECTS" ] || fail "a refused run must not create the project directory"++# --- macOS path with a fake xcrun ---++# Assignments before a shell function are not reliably exported in POSIX sh,+# so the fake's knobs are exported explicitly.+export FAKE_XCRUN_TOOLS="safari-web-extension-packager safari-web-extension-converter" FAKE_XCRUN_CREATE=1 FAKE_XCRUN_STATUS=0+run_darwin --extension-dir "$EXT" --project-dir "$PROJECTS" >"$TMP_DIR/out" 2>"$TMP_DIR/err" ||+ fail "macOS run should succeed: $(cat "$TMP_DIR/err")"+[ "$(head -n 1 "$XCRUN_LOG")" = "safari-web-extension-packager" ] || fail "should prefer safari-web-extension-packager"+tail -n +2 "$XCRUN_LOG" >"$TMP_DIR/ran"+tail -n +2 "$TMP_DIR/want" >"$TMP_DIR/want-args"+diff -u "$TMP_DIR/want-args" "$TMP_DIR/ran" >&2 || fail "macOS run should pass the same arguments as --dry-run prints"+grep -q "Xcode project: $PROJECTS/Beacon Browser Collector/Beacon Browser Collector.xcodeproj" "$TMP_DIR/out" ||+ fail "should report the generated project: $(cat "$TMP_DIR/out")"+grep -q '^ ai.asymptote.beacon.browser-collector.Extension$' "$TMP_DIR/out" ||+ fail "should list the extension bundle identifier"+rm -rf "$PROJECTS"++export FAKE_XCRUN_TOOLS="safari-web-extension-converter"+run_darwin --extension-dir "$EXT" --project-dir "$PROJECTS" >/dev/null 2>&1 ||+ fail "should fall back to safari-web-extension-converter"+[ "$(head -n 1 "$XCRUN_LOG")" = "safari-web-extension-converter" ] || fail "fallback should run safari-web-extension-converter"+rm -rf "$PROJECTS"+: >"$XCRUN_LOG"++export FAKE_XCRUN_TOOLS=""+expect_fail "no packager" "neither safari-web-extension-packager nor safari-web-extension-converter" -- \+ run_darwin --extension-dir "$EXT" --project-dir "$PROJECTS"+[ ! -s "$XCRUN_LOG" ] || fail "no conversion should run without a packager"++export FAKE_XCRUN_TOOLS="safari-web-extension-packager" FAKE_XCRUN_CREATE=0+expect_fail "no project produced" "no .xcodeproj was found" -- \+ run_darwin --extension-dir "$EXT" --project-dir "$PROJECTS"+rm -rf "$PROJECTS"++export FAKE_XCRUN_CREATE=1 FAKE_XCRUN_STATUS=3+if run_darwin --extension-dir "$EXT" --project-dir "$PROJECTS" >/dev/null 2>&1; then+ fail "a failing packager should fail the wrapper"+fi+rm -rf "$PROJECTS"+unset FAKE_XCRUN_TOOLS FAKE_XCRUN_CREATE FAKE_XCRUN_STATUS++# --- MDM declaration ---++# The declaration must name the extension the wrapper produces: the packager+# derives the extension identifier as <app bundle id>.Extension.+run_linux --dry-run --extension-dir "$EXT" --project-dir "$PROJECTS" >"$TMP_DIR/out"+dump_args "$TMP_DIR/out" >"$TMP_DIR/args"+APP_BUNDLE_ID="$(grep -A1 -x -- '--bundle-identifier' "$TMP_DIR/args" | tail -n 1)"+EXTENSION_BUNDLE_ID="$APP_BUNDLE_ID.Extension"++python3 "$CHECKER" "$DECLARATION" --manifest "$MANIFEST" --extension-bundle-id "$EXTENSION_BUNDLE_ID" >/dev/null ||+ fail "the shipped MDM declaration should validate"++# Prove the checker rejects the mistakes it exists to catch.+mutate() {+ python3 - "$DECLARATION" "$1" "$2" <<'PY'+import json, sys+src, out, change = sys.argv[1], sys.argv[2], sys.argv[3]+d = json.load(open(src))+managed = d["Payload"]["ManagedExtensions"]+key = next(iter(managed))+entry = managed[key]+if change == "state-with-space":+ entry["State"] = "Always On"+elif change == "wrong-type":+ d["Type"] = "com.apple.Safari.Extensions"+elif change == "no-team-id":+ managed[key.split(" ")[0]] = managed.pop(key)+elif change == "missing-host":+ entry["AllowedDomains"].remove("chatgpt.com")+elif change == "url-not-domain":+ entry["AllowedDomains"].append("https://claude.ai/")+elif change == "denied-host":+ entry["DeniedDomains"] = ["127.0.0.1"]+elif change == "always-off":+ entry["State"] = "AlwaysOff"+elif change == "no-server-token":+ del d["ServerToken"]+elif change == "unknown-key":+ entry["Enabled"] = True+json.dump(d, open(out, "w"))+PY+}+for change in state-with-space wrong-type no-team-id missing-host url-not-domain denied-host always-off no-server-token unknown-key; do+ mutate "$TMP_DIR/bad-$change.json" "$change"+ if python3 "$CHECKER" "$TMP_DIR/bad-$change.json" --manifest "$MANIFEST" --extension-bundle-id "$EXTENSION_BUNDLE_ID" >/dev/null 2>&1; then+ fail "MDM checker should reject a declaration with change '$change'"+ fi+done+printf '{ not json' >"$TMP_DIR/bad-json.json"+if python3 "$CHECKER" "$TMP_DIR/bad-json.json" --manifest "$MANIFEST" --extension-bundle-id "$EXTENSION_BUNDLE_ID" >/dev/null 2>&1; then+ fail "MDM checker should reject invalid JSON"+fi+if python3 "$CHECKER" "$DECLARATION" --manifest "$MANIFEST" --extension-bundle-id "com.example.other.Extension" >/dev/null 2>&1; then+ fail "MDM checker should reject a declaration that does not name the collector extension"+fi++echo "Safari packaging checks passed"diff --git a/packaging/macos/test-endpoint-scripts.sh b/packaging/macos/test-endpoint-scripts.shindex c6cb54cd..3e7e0d66 100644--- a/packaging/macos/test-endpoint-scripts.sh+++ b/packaging/macos/test-endpoint-scripts.sh@@ -1079,3 +1079,7 @@ if [ ! -f "$GCS_FORWARDER_MARKER" ]; thenecho "combined GCS Vector repair should run forwarder before failing repair" >&2exit 1fi++# Safari app-wrapper helper and MDM declaration (packaging/macos/safari). Runs on+# Linux too: the packager and uname are faked.+sh "$ROOT_DIR/packaging/macos/safari/test-safari-packaging.sh"