@hanzo/browser-extension 1.9.53 → 1.9.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hanzo/browser-extension",
3
- "version": "1.9.53",
3
+ "version": "1.9.54",
4
4
  "description": "Hanzo AI Browser Extension",
5
5
  "main": "dist/background.js",
6
6
  "dependencies": {
@@ -0,0 +1,153 @@
1
+ //
2
+ // SafariWebExtensionHandler.swift
3
+ // Shared (Extension)
4
+ //
5
+ // Relays the extension to zapd, which is the same fabric Chrome and Firefox
6
+ // join. They reach it by spawning `zapd` over stdio as a native messaging
7
+ // host; Safari cannot spawn a binary, so it carries the last hop itself and
8
+ // writes to the router's socket directly.
9
+ //
10
+ // The message is the router envelope the shared transport already sends —
11
+ // { t, flags, from, to, payload } with a base64 payload — so the browser side
12
+ // is byte-identical across all three engines and only the hop changes.
13
+ //
14
+
15
+ import SafariServices
16
+ import Foundation
17
+ import os.log
18
+
19
+ /// One connection to the router, kept open across messages.
20
+ ///
21
+ /// A native port is a channel, not a request: the router pushes ROUTE commands
22
+ /// on it long after the extension last spoke, and a socket opened per message
23
+ /// would miss every one of them.
24
+ final class ZapSocket {
25
+ static let shared = ZapSocket()
26
+
27
+ private let path = NSHomeDirectory() + "/.zap/run/zapd.sock"
28
+ private var fd: Int32 = -1
29
+ private let lock = NSLock()
30
+
31
+ /// Connect if we are not already. Returns false when the router is absent —
32
+ /// which is a normal state (zapd not running), not an error to throw at the
33
+ /// browser.
34
+ @discardableResult
35
+ private func connect() -> Bool {
36
+ if fd >= 0 { return true }
37
+ let s = socket(AF_UNIX, SOCK_STREAM, 0)
38
+ if s < 0 { return false }
39
+
40
+ var addr = sockaddr_un()
41
+ addr.sun_family = sa_family_t(AF_UNIX)
42
+ let bytes = Array(path.utf8)
43
+ // sun_path is a fixed C array; a path that does not fit is not a path
44
+ // this socket can name, and truncating it would name a different one.
45
+ guard bytes.count < MemoryLayout.size(ofValue: addr.sun_path) else { close(s); return false }
46
+ withUnsafeMutablePointer(to: &addr.sun_path) { p in
47
+ p.withMemoryRebound(to: CChar.self, capacity: bytes.count + 1) { dst in
48
+ for (i, b) in bytes.enumerated() { dst[i] = CChar(bitPattern: b) }
49
+ dst[bytes.count] = 0
50
+ }
51
+ }
52
+ let size = socklen_t(MemoryLayout<sockaddr_un>.size)
53
+ let ok = withUnsafePointer(to: &addr) { p in
54
+ p.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
55
+ Darwin.connect(s, sa, size) == 0
56
+ }
57
+ }
58
+ if !ok { close(s); return false }
59
+ fd = s
60
+ return true
61
+ }
62
+
63
+ private func drop() {
64
+ if fd >= 0 { close(fd) }
65
+ fd = -1
66
+ }
67
+
68
+ /// Send one envelope and read one back.
69
+ ///
70
+ /// Length-prefixed both ways, matching the native messaging framing the
71
+ /// other two engines get from the host: u32 little-endian, then the JSON.
72
+ func exchange(_ message: Any) -> Any? {
73
+ lock.lock()
74
+ defer { lock.unlock() }
75
+ guard connect() else { return nil }
76
+ guard let body = try? JSONSerialization.data(withJSONObject: message) else { return nil }
77
+
78
+ var length = UInt32(body.count).littleEndian
79
+ var frame = Data(bytes: &length, count: 4)
80
+ frame.append(body)
81
+
82
+ guard write(frame) else { drop(); return nil }
83
+ guard let header = read(exactly: 4) else { drop(); return nil }
84
+ let expected = header.withUnsafeBytes { $0.load(as: UInt32.self).littleEndian }
85
+ // A reply that claims more than the router will ever send is a desynced
86
+ // stream, not a big message. Start over rather than block on it.
87
+ guard expected > 0, expected <= 16 * 1024 * 1024, let payload = read(exactly: Int(expected)) else {
88
+ drop(); return nil
89
+ }
90
+ return try? JSONSerialization.jsonObject(with: payload)
91
+ }
92
+
93
+ private func write(_ data: Data) -> Bool {
94
+ var sent = 0
95
+ return data.withUnsafeBytes { raw -> Bool in
96
+ guard let base = raw.baseAddress else { return false }
97
+ while sent < data.count {
98
+ let n = Darwin.write(fd, base.advanced(by: sent), data.count - sent)
99
+ if n <= 0 { return false }
100
+ sent += n
101
+ }
102
+ return true
103
+ }
104
+ }
105
+
106
+ private func read(exactly count: Int) -> Data? {
107
+ var out = Data()
108
+ var buf = [UInt8](repeating: 0, count: count)
109
+ while out.count < count {
110
+ let n = buf.withUnsafeMutableBytes { p -> Int in
111
+ guard let base = p.baseAddress else { return -1 }
112
+ return Darwin.read(fd, base, count - out.count)
113
+ }
114
+ if n <= 0 { return nil }
115
+ out.append(contentsOf: buf[0..<n])
116
+ }
117
+ return out
118
+ }
119
+ }
120
+
121
+ class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
122
+
123
+ func beginRequest(with context: NSExtensionContext) {
124
+ let request = context.inputItems.first as? NSExtensionItem
125
+
126
+ let message: Any?
127
+ if #available(iOS 15.0, macOS 11.0, *) {
128
+ message = request?.userInfo?[SFExtensionMessageKey]
129
+ } else {
130
+ message = request?.userInfo?["message"]
131
+ }
132
+
133
+ // iOS has no router to reach: zapd is a desktop daemon and an iOS app
134
+ // has no filesystem path to another process's socket. The extension
135
+ // treats a null reply as "not connected", which is what this is.
136
+ var reply: Any? = nil
137
+ #if os(macOS)
138
+ if let message { reply = ZapSocket.shared.exchange(message) }
139
+ #endif
140
+
141
+ if reply == nil {
142
+ os_log(.default, "zapd unreachable at ~/.zap/run/zapd.sock")
143
+ }
144
+
145
+ let response = NSExtensionItem()
146
+ if #available(iOS 15.0, macOS 11.0, *) {
147
+ response.userInfo = [SFExtensionMessageKey: reply ?? [:]]
148
+ } else {
149
+ response.userInfo = ["message": reply ?? [:]]
150
+ }
151
+ context.completeRequest(returningItems: [response], completionHandler: nil)
152
+ }
153
+ }