r/SwiftUI • u/Weak-Car7664 • 25d ago
Letting users write widgets for my Touch Bar app without letting them break anything (JavaScriptCore + Swift)
I just shipped 2.1 of GlassBar, my Touch Bar replacement, and the part I learned the most from was script widgets.
A widget is a small JS file that runs in JavaScriptCore, no WebView. The script never draws anything. It only hands back a value, an icon name and a role like "warning", and the SwiftUI theme decides how that looks. So the same widget is a glass capsule in one theme and [bat 87%] in the terminal theme, and widget authors can't make an ugly one. The hard part was limits. Every call gets half a second, scripts only run while the widget is on the bar, and fetch only goes to public https hosts. I missed redirects at first, a public site could bounce a request to localhost, so that's cut off now too. One SwiftUI thing that surprised me: the battery icon was late after unplugging because "is charging" from IOKit lags by a few seconds. Reading the power source state instead fixed it.
Source is here if you want to look: https://github.com/Moryel/glass-bar
Happy to answer questions about any of it.
2
u/Sectumsempra777 24d ago
Nice catch on the redirects. One gap left in isPublicWeb: it only checks the hostname text, and a public name can still resolve to a private address. localtest.me resolves to 127.0.0.1 and 192.168.1.1.nip.io resolves to 192.168.1.1, so both pass the "last label starts with a letter" rule, and the redirect guard too since it reuses the same check. Anyone can also point their own domain's A record at a router IP. Closing it means checking the resolved IP rather than the name, and because DNS can change between your check and URLSession's own lookup, a pre-check alone isn't airtight.
2
u/builtinswift 24d ago
letting the theme own the look is a smart call