HTTPSNAP, Safari extension starter
Every file you need to drop into an Xcode Safari Extension App project. The rewriting is declarative, so Safari's networking layer matches the rules directly and the extension never reads your pages or sends anything anywhere.
ViewController.swift
Complete file, including the imports and class. Replace ALL contents of your existing ViewController.swift in Xcode. Remove StartupFix.swift from the project if you added it.
Shared (App)/ViewController.swift — replace the contents of the existing file//
// ViewController.swift
// Shared (App)
//
import WebKit
#if os(iOS)
import UIKit
typealias PlatformViewController = UIViewController
#elseif os(macOS)
import Cocoa
import SafariServices
typealias PlatformViewController = NSViewController
#endif
let extensionBundleIdentifier = "com.httpsnap.HTTPSNAP.Extension"
class ViewController: PlatformViewController, WKNavigationDelegate, WKScriptMessageHandler {
@IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
if self.webView == nil {
let replacement = WKWebView(frame: self.view.bounds)
self.webView = replacement
self.view = replacement
}
guard let webView = self.webView else { return }
webView.navigationDelegate = self
#if os(iOS)
webView.scrollView.isScrollEnabled = false
#endif
webView.configuration.userContentController.add(self, name: "controller")
let mainURL = Bundle.main.url(forResource: "Main", withExtension: "html")
?? Bundle.main.url(forResource: "Main", withExtension: "html", subdirectory: "Resources")
if let mainURL = mainURL {
webView.loadFileURL(mainURL, allowingReadAccessTo: mainURL.deletingLastPathComponent())
} else {
// Show a usable setup screen instead of crashing or leaving a blank window.
webView.loadHTMLString("""
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>HTTPSNAP</title>
<style>
:root{color-scheme:light dark}*{box-sizing:border-box}
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:32px;text-align:center;font:15px/1.5 -apple-system,BlinkMacSystemFont,sans-serif}
main{max-width:360px}h1{font-size:24px}p{opacity:.75}
</style></head><body><main><h1>HTTPSNAP</h1>
<p id="instructions">Turn on HTTPSNAP in Safari Settings → Extensions, then allow access to the websites you want to protect.</p>
<p id="status" aria-live="polite"></p></main>
<script>
function show(platform, enabled, useSettings) {
if (platform === 'ios') document.getElementById('instructions').textContent = 'Turn on HTTPSNAP in Settings → Apps → Safari → Extensions (or Settings → Safari → Extensions on older versions), then allow website access.';
if (typeof enabled === 'boolean') state(enabled, useSettings);
}
function state(enabled, useSettings) {
document.getElementById('status').textContent = enabled ? 'HTTPSNAP is enabled in Safari. Website access permissions still apply.' : 'HTTPSNAP is disabled in Safari. Turn it on in Safari settings.';
}
</script></body></html>
""", baseURL: nil)
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
#if os(iOS)
webView.evaluateJavaScript("show('ios')")
#elseif os(macOS)
webView.evaluateJavaScript("show('mac')")
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extensionBundleIdentifier) { (state, error) in
guard let state = state, error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
if #available(macOS 13, *) {
webView.evaluateJavaScript("show('mac', \(state.isEnabled), true)")
} else {
webView.evaluateJavaScript("show('mac', \(state.isEnabled), false)")
}
}
}
#endif
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
#if os(macOS)
if (message.body as! String != "open-preferences") {
return
}
SFSafariApplication.showPreferencesForExtension(withIdentifier: extensionBundleIdentifier) { error in
guard error == nil else {
// Insert code to inform the user that something went wrong.
return
}
DispatchQueue.main.async {
NSApp.terminate(self)
}
}
#endif
}
}
The errors in your screenshot come from compiling viewDidLoad() by itself, outside its ViewController class, without the imports. Stop the app in Xcode. Open the existing Shared (App)/ViewController.swift, click inside its editor, press Command-A, then paste this entire file using Command-V. Do not replace only the method or add a second ViewController.swift. If you added StartupFix.swift as a separate source file, remove that snippet from the Xcode project so it is not compiled. Then run the app again. This complete file preserves your extension identifier, platform imports and Safari callbacks, while safely handling a missing Main.html or webView connection. Your local Xcode build and launch have not been verified.
A white padlock under an upward chevron on a blue-to-teal gradient: secure, and on the way up. Designed to stay legible at 48 pixels, which is the smallest size Safari asks for.
Icon-2048 and Icon-3072 are the same artwork at the universal 2x and 3x sizes Xcode's AppIcon set asks for. Icon.png is the container app's icon and goes in Shared (App)/Resources. The six numbered files go in an images folder inside the extension's Resources folder, under exactly these names. The toolbar mark, toolbar-icon.svg, is in the file list above - it is deliberately black on transparent, because Safari only renders toolbar icons as a monochrome template image.
Put the files in one folder
Make a new folder anywhere on your Mac and copy seven files into it: manifest.json, rules.json, rules-strict.json, popup.html, popup.js, PrivacyInfo.xcprivacy and an images folder holding toolbar-icon.svg plus the six icon PNGs from the icon set below. manifest.json has to sit at the top level of that folder - Safari looks for it there and nowhere else. ContentView.swift is only needed for the Xcode route, so leave it out for now.
Deal with the icons before you test
Every icon the manifest asks for is on this page already cut to the right pixel size: the six extension sizes (48, 64, 96, 128, 256 and 512) and the toolbar mark. Save them into an images folder inside the extension's Resources folder, keeping the filenames exactly as they are. If you would rather skip that for now, delete the icons block and the default_icon line from manifest.json instead - a manifest pointing at a file that is not there can stop the extension loading.
If the app's own screen shows an empty icon box
The screen inside the container app is Main.html, and it draws Icon.png from the folder next to it. A placeholder there means the image is missing from the app bundle rather than wrong inside the file: in Xcode select Icon.png, open the File inspector, and tick Shared (App) under Target Membership, since a file can sit in the folder without being copied into the app. The name is case-sensitive. If you would rather sidestep it entirely, put the Main.html from the file list in place of the template's - it is self-contained and points at the same image. The icon on the simulator's Home screen is a different thing again: drag Icon.png onto the AppIcon slot in Shared (App)/Resources/Assets.xcassets to fill that one.
If the app crashes on launch: unexpectedly found nil
The highlighted loadFileURL line in the template force-unwraps a Main.html lookup and the bundle's resources URL. A missing file or an unexpected bundle path can therefore stop the container app during startup. Use the complete ViewController.swift from this page to replace ALL contents of your existing Shared (App)/ViewController.swift, including the imports and class. Do not paste a bare viewDidLoad() method at the top of a file: errors about override, self or Bundle mean that method is being compiled without its surrounding class or imports. If you added StartupFix.swift as a separate source file, remove it from the Xcode project. The complete replacement safely checks Main.html at the bundle root and inside Resources, displays an embedded setup screen when the file is absent, and handles a missing webView storyboard connection. Stop and run the app again. This repair changes only the container screen; it does not change the extension's HTTPS rules or verify that the extension is installed, enabled, or allowed website access. Your local Xcode build and launch must still be checked on your Mac.
If it says the class is unknown in Interface Builder
Those two messages belong together: an unknown ViewController class, and a webView outlet that cannot be connected. Both mean the app ran with no ViewController class inside it, so the storyboard found nothing to load and nothing to wire. The usual cause is target membership, and it is easy to miss: a file can sit in the project, look perfectly fine in the editor, and still be left out of the build entirely. Select ViewController.swift in Xcode's navigator, open the File inspector on the right, and make sure HTTPSNAP is ticked for it under Target Membership. While that file is selected, also confirm its top reads import WebKit and then class ViewController, and that the project holds only one ViewController.swift, because a leftover second copy carrying the same class name can be compiled in place of the repaired one, or alongside it. Then press Shift-Command-K to clean the build folder and run again. The long list of sandbox, pasteboard and audio messages printed underneath those two lines is normal noise from a sandboxed app and can be ignored; the two Interface Builder lines are the ones that matter.
If one file reports errors in several targets
The same file listed under several target names, for instance ContentView.swift showing errors under both the app and the extension on iOS and macOS, means that single file has been ticked into all four targets. Select it, open the File inspector, and tick it for the app targets only - the extension targets never need it. Being in an extra target is not what breaks the build on its own, but it repeats every error under each target name, so the report looks four times worse than the problem is. If you never wanted that extra screen, delete the file and its errors go with it.
If it says no such module UIKit
UIKit ships with the iOS SDK, so this is never a missing framework: it means Xcode is compiling that file for a platform that has no UIKit, which is macOS. Work through these in order. First, select AppDelegate.swift and open the File inspector: the one importing UIKit belongs to the iOS app target alone, the macOS app has its own that imports Cocoa instead, and neither belongs to an extension target. Second, check the run destination beside the scheme at the top: if it reads My Mac, choose an iPhone Simulator instead, because an iOS target compiled against macOS gives this error exactly. Third, open the target's General tab and look at Supported Destinations - if the app lists both iOS and macOS, give each platform its own AppDelegate rather than sharing one, and if macOS is not needed yet, set it to iOS only and the whole mix-up disappears. Then press Shift-Command-K to clean the build folder: Xcode caches module resolution per target, so a corrected membership can keep reporting the old error until you clean.
If it also says could not compute dependency graph, or missingTarget
This one sits above the UIKit error and has to be cleared first: the project file holds a pointer to a target that is no longer there, and while that pointer stands, the target it points at cannot resolve any of its frameworks either - which is exactly how a UIKit error ends up reported above a missing-target error. Work through it in this order. Quit Xcode, delete the project's DerivedData folder (~/Library/Developer/Xcode/DerivedData), reopen the project, then Product -> Clean Build Folder. Open Product -> Manage Schemes and delete any scheme that is greyed out or that names a target you no longer have, because a scheme left pointing at a deleted target produces this error on its own. Select the project at the top of the navigator, open the File inspector on the right, and set Project Format to the newest Xcode version offered - an old format with a new Xcode is a known cause. Finally, check the scheme name shown next to the stop button: that name, not the error list, decides which platform is built, so pick the iOS app scheme and an iPhone Simulator destination when you are chasing an iOS error. If the error survives all of that, the project file is inconsistent rather than mis-set, and rebuilding it is faster than repairing it: new Multiplatform Safari Extension App project, named HTTPSNAP, Organization Identifier com.httpsnap, seven files dropped in again.
Turn on Safari's developer features
Safari -> Settings -> Advanced -> tick Show features for web developers. That adds the Developer tab and unlocks the Add Temporary Extension button.
Load the extension
Safari -> Settings -> Developer -> Add Temporary Extension -> select your extension folder -> Open. Safari loads it straight away, with no signing and no Apple Developer account, and it stays loaded until you quit Safari.
Switch it on and give it site access
Safari -> Settings -> Extensions -> tick HTTPSNAP. Set its site access to Allow on every website, or Ask if you would rather approve each site yourself. Without site access the rewrite rules have nothing to match and nothing will change.
Check that it actually works
Open an http:// address and confirm you land on https://. Then click the toolbar popup and switch between Upgrade and Force to see how each behaves on a host that only speaks HTTP.
If you would rather use Xcode
File -> New -> Project -> Choose Template -> Multiplatform tab -> Application section -> Safari Extension App. Name it HTTPSNAP and set Organization Identifier to com.httpsnap - just the reverse of the domain you own, with no product name and no .extension suffix. When it opens, replace the template files in Shared (Extension)/Resources with your seven - meaning its manifest.json, background.js, content.js, popup.html, popup.css, popup.js, _locales folder and images folder all go, SafariWebExtensionHandler.swift stays - and put the container app icon in Shared (App)/Resources as Icon.png, then in Signing & Capabilities for both the app target and the extension target pick your Team (a free Apple ID Personal Team is enough), or set Signing Certificate to Sign to Run Locally with Team set to None to skip signing altogether. Tick Allow unsigned extensions in Safari's Developer tab, run it once, then enable it as in the steps above.
com.httpsnapHTTPSNAP.xcodeproj
Shared (App)/
Resources/
Icon.png (1024x1024 container app icon - this page)
Main.html, Script.js, Style.css (template boilerplate - leave as is)
Assets.xcassets
ViewController.swift (the template's landing screen - leave as is)
Shared (Extension)/
Resources/
manifest.json (this page)
rules.json (this page, enabled by default)
rules-strict.json (this page, off by default)
popup.html (this page)
popup.js (this page)
PrivacyInfo.xcprivacy (this page)
images/
icon-48.png (this page, ready to save)
icon-64.png (this page, ready to save)
icon-96.png (this page, ready to save)
icon-128.png (this page, ready to save)
icon-256.png (this page, ready to save)
icon-512.png (this page, ready to save)
toolbar-icon.svg (this page)
SafariWebExtensionHandler.swift (template boilerplate, unused here)
iOS (App)/, macOS (App)/, iOS (Extension)/, macOS (Extension)/ (target plumbing - leave as is)No code can dismiss Safari's security warning
The certificate and "not secure" warnings are a browser-level boundary. An extension that could click through them would defeat the point of the warning. Only the person using the browser can accept an unsecure page - this is the one part of the original request that is genuinely impossible, in an extension or anywhere else.
There is no fallback to HTTP
Extension rules cannot say "try HTTPS, and if that fails load the insecure version". Upgrade mode asks Safari to use HTTPS and Force mode rewrites the URL outright; hosts that serve only HTTP fail in either case. That fallback logic lives inside Safari itself, not inside extensions.
Safari already does much of this
Safari 15.4 and later upgrade many navigations on their own, and Safari 18.2 and later attempt HTTPS first by default. The real added value here is coverage for old bookmarks, typed http:// addresses and mixed embedded assets on sites that never got around to switching.
HSTS already wins where sites use it
Once a site sends a Strict-Transport-Security header, Safari refuses http:// for that domain no matter what an extension wants. Your extension only matters on domains that have not adopted it.
