electrobun 0.0.17 → 0.0.19-beta.1

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.
@@ -1,181 +0,0 @@
1
- import type { ServerWebSocket } from "bun";
2
- import { BrowserView } from "./BrowserView";
3
- import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
4
-
5
- function base64ToUint8Array(base64: string) {
6
- {
7
- return new Uint8Array(
8
- atob(base64)
9
- .split("")
10
- .map((char) => char.charCodeAt(0))
11
- );
12
- }
13
- }
14
-
15
- // Encrypt function
16
- function encrypt(secretKey: Uint8Array, text: string) {
17
- const iv = new Uint8Array(randomBytes(12)); // IV for AES-GCM
18
- const cipher = createCipheriv("aes-256-gcm", secretKey, iv);
19
- const encrypted = Buffer.concat([
20
- new Uint8Array(cipher.update(text, "utf8")),
21
- new Uint8Array(cipher.final()),
22
- ]).toString("base64");
23
- const tag = cipher.getAuthTag().toString("base64");
24
- return { encrypted, iv: Buffer.from(iv).toString("base64"), tag };
25
- }
26
-
27
- // Decrypt function
28
- function decrypt(
29
- secretKey: Uint8Array,
30
- encryptedData: Uint8Array,
31
- iv: Uint8Array,
32
- tag: Uint8Array
33
- ) {
34
- const decipher = createDecipheriv("aes-256-gcm", secretKey, iv);
35
- decipher.setAuthTag(tag);
36
- const decrypted = Buffer.concat([
37
- new Uint8Array(decipher.update(encryptedData)),
38
- new Uint8Array(decipher.final()),
39
- ]);
40
- return decrypted.toString("utf8");
41
- }
42
-
43
- export const socketMap: {
44
- [webviewId: string]: {
45
- socket: null | ServerWebSocket<unknown>;
46
- queue: string[];
47
- };
48
- } = {};
49
-
50
- const startRPCServer = () => {
51
- const startPort = 50000;
52
- const endPort = 65535;
53
- const payloadLimit = 1024 * 1024 * 500; // 500MB
54
- let port = startPort;
55
- let server = null;
56
-
57
- while (port <= endPort) {
58
- try {
59
- server = Bun.serve<{ webviewId: number }>({
60
- port,
61
- fetch(req, server) {
62
- const url = new URL(req.url);
63
- // const token = new URL(req.url).searchParams.get("token");
64
- // if (token !== AUTH_TOKEN)
65
- // return new Response("Unauthorized", { status: 401 });
66
- // console.log("fetch!!", url.pathname);
67
- if (url.pathname === "/socket") {
68
- const webviewIdString = url.searchParams.get("webviewId");
69
- if (!webviewIdString) {
70
- return new Response("Missing webviewId", { status: 400 });
71
- }
72
- const webviewId = parseInt(webviewIdString, 10);
73
- const success = server.upgrade(req, { data: { webviewId } });
74
- return success
75
- ? undefined
76
- : new Response("Upgrade failed", { status: 500 });
77
- }
78
-
79
- console.log("unhandled RPC Server request", req.url);
80
- },
81
- websocket: {
82
- idleTimeout: 960,
83
- // 500MB max payload should be plenty
84
- maxPayloadLength: payloadLimit,
85
- // Anything beyond the backpressure limit will be dropped
86
- backpressureLimit: payloadLimit * 2,
87
- open(ws) {
88
- const { webviewId } = ws.data;
89
-
90
- if (!socketMap[webviewId]) {
91
- socketMap[webviewId] = { socket: ws, queue: [] };
92
- } else {
93
- socketMap[webviewId].socket = ws;
94
- }
95
- },
96
- close(ws, code, reason) {
97
- const { webviewId } = ws.data;
98
- console.log("Closed:", webviewId, code, reason);
99
- socketMap[webviewId].socket = null;
100
- },
101
-
102
- message(ws, message) {
103
- const { webviewId } = ws.data;
104
- const browserView = BrowserView.getById(webviewId);
105
-
106
- if (browserView.rpcHandler) {
107
- if (typeof message === "string") {
108
- try {
109
- const encryptedPacket = JSON.parse(message);
110
- const decrypted = decrypt(
111
- browserView.secretKey,
112
- base64ToUint8Array(encryptedPacket.encryptedData),
113
- base64ToUint8Array(encryptedPacket.iv),
114
- base64ToUint8Array(encryptedPacket.tag)
115
- );
116
-
117
- // Note: At this point the secretKey for the webview id would
118
- // have had to match the encrypted packet data, so we can trust
119
- // that this message can be passed to this browserview's rpc
120
- // methods.
121
- browserView.rpcHandler(JSON.parse(decrypted));
122
- } catch (error) {
123
- console.log("Error handling message:", error);
124
- }
125
- } else if (message instanceof ArrayBuffer) {
126
- console.log("TODO: Received ArrayBuffer message:", message);
127
- }
128
- }
129
- },
130
- },
131
- });
132
-
133
- break;
134
- } catch (error: any) {
135
- if (error.code === "EADDRINUSE") {
136
- console.log(`Port ${port} in use, trying next port...`);
137
- port++;
138
- } else {
139
- throw error;
140
- }
141
- }
142
- }
143
-
144
- return { rpcServer: server, rpcPort: port };
145
- };
146
-
147
- export const { rpcServer, rpcPort } = startRPCServer();
148
-
149
- // Will return true if message was sent over websocket
150
- // false if it was not (caller should fallback to postMessage/evaluateJS rpc)
151
- export const sendMessageToWebviewViaSocket = (
152
- webviewId: number,
153
- message: any
154
- ): boolean => {
155
- const rpc = socketMap[webviewId];
156
- const browserView = BrowserView.getById(webviewId);
157
-
158
- if (rpc?.socket?.readyState === WebSocket.OPEN) {
159
- try {
160
- const unencryptedString = JSON.stringify(message);
161
- const encrypted = encrypt(browserView.secretKey, unencryptedString);
162
-
163
- const encryptedPacket = {
164
- encryptedData: encrypted.encrypted,
165
- iv: encrypted.iv,
166
- tag: encrypted.tag,
167
- };
168
-
169
- const encryptedPacketString = JSON.stringify(encryptedPacket);
170
-
171
- rpc.socket.send(encryptedPacketString);
172
- return true;
173
- } catch (error) {
174
- console.error("Error sending message to webview via socket:", error);
175
- }
176
- }
177
-
178
- return false;
179
- };
180
-
181
- console.log("Server started at", rpcServer?.url.origin);
@@ -1,105 +0,0 @@
1
- import { zigRPC, type MenuItemConfig } from "../proc/zig";
2
- import electrobunEventEmitter from "../events/eventEmitter";
3
- import { VIEWS_FOLDER } from "./Paths";
4
- import { join } from "path";
5
-
6
- let nextTrayId = 1;
7
- const TrayMap = {};
8
-
9
- type ConstructorOptions = {
10
- title?: string;
11
- image?: string;
12
- template?: boolean;
13
- width?: number;
14
- height?: number;
15
- };
16
-
17
- export class Tray {
18
- id: number = nextTrayId++;
19
-
20
- constructor({
21
- title = "",
22
- image = "",
23
- template = true,
24
- width = 16,
25
- height = 16,
26
- }: ConstructorOptions = {}) {
27
- console.log("img", image);
28
- console.log("img", this.resolveImagePath(image));
29
- zigRPC.request.createTray({
30
- id: this.id,
31
- title,
32
- image: this.resolveImagePath(image),
33
- template,
34
- width,
35
- height,
36
- });
37
-
38
- TrayMap[this.id] = this;
39
- }
40
-
41
- resolveImagePath(imgPath: string) {
42
- if (imgPath.startsWith("views://")) {
43
- return join(VIEWS_FOLDER, imgPath.replace("views://", ""));
44
- } else {
45
- // can specify any file path here
46
- return imgPath;
47
- }
48
- }
49
-
50
- setTitle(title: string) {
51
- zigRPC.request.setTrayTitle({ id: this.id, title });
52
- }
53
-
54
- setImage(imgPath: string) {
55
- zigRPC.request.setTrayImage({
56
- id: this.id,
57
- image: this.resolveImagePath(imgPath),
58
- });
59
- }
60
-
61
- setMenu(menu: Array<MenuItemConfig>) {
62
- const menuWithDefaults = menuConfigWithDefaults(menu);
63
- zigRPC.request.setTrayMenu({
64
- id: this.id,
65
- menuConfig: JSON.stringify(menuWithDefaults),
66
- });
67
- }
68
-
69
- on(name: "tray-clicked", handler) {
70
- const specificName = `${name}-${this.id}`;
71
- electrobunEventEmitter.on(specificName, handler);
72
- }
73
-
74
- static getById(id: number) {
75
- return TrayMap[id];
76
- }
77
-
78
- static getAll() {
79
- return Object.values(TrayMap);
80
- }
81
- }
82
-
83
- const menuConfigWithDefaults = (
84
- menu: Array<MenuItemConfig>
85
- ): Array<MenuItemConfig> => {
86
- return menu.map((item) => {
87
- if (item.type === "divider" || item.type === "separator") {
88
- return { type: "divider" };
89
- } else {
90
- return {
91
- label: item.label || "",
92
- type: item.type || "normal",
93
- action: item.action || "",
94
- // default enabled to true unless explicitly set to false
95
- enabled: item.enabled === false ? false : true,
96
- checked: Boolean(item.checked),
97
- hidden: Boolean(item.hidden),
98
- tooltip: item.tooltip || undefined,
99
- ...(item.submenu
100
- ? { submenu: menuConfigWithDefaults(item.submenu) }
101
- : {}),
102
- };
103
- }
104
- });
105
- };
@@ -1,387 +0,0 @@
1
- import { join, dirname, resolve } from "path";
2
- import { homedir } from "os";
3
- import { renameSync, unlinkSync, mkdirSync, rmdirSync, statSync } from "fs";
4
- import tar from "tar";
5
- import { ZstdInit } from "@oneidentity/zstd-js/wasm";
6
-
7
- const appSupportDir = join(homedir(), "Library", "Application Support");
8
-
9
- // todo (yoav): share type with cli
10
- let localInfo: {
11
- version: string;
12
- hash: string;
13
- bucketUrl: string;
14
- channel: string;
15
- name: string;
16
- identifier: string;
17
- };
18
-
19
- let updateInfo: {
20
- version: string;
21
- hash: string;
22
- updateAvailable: boolean;
23
- updateReady: boolean;
24
- error: string;
25
- };
26
-
27
- const Updater = {
28
- // workaround for some weird state stuff in this old version of bun
29
- // todo: revisit after updating to the latest bun
30
- updateInfo: () => {
31
- return updateInfo;
32
- },
33
- // todo: allow switching channels, by default will check the current channel
34
- checkForUpdate: async () => {
35
- const localInfo = await Updater.getLocallocalInfo();
36
-
37
- if (localInfo.channel === "dev") {
38
- return {
39
- version: localInfo.version,
40
- hash: localInfo.hash,
41
- updateAvailable: false,
42
- updateReady: false,
43
- error: "",
44
- };
45
- }
46
-
47
- const channelBucketUrl = await Updater.channelBucketUrl();
48
- const cacheBuster = Math.random().toString(36).substring(7);
49
- const updateInfoUrl = join(channelBucketUrl, `update.json?${cacheBuster}`);
50
-
51
- try {
52
- const updateInfoResponse = await fetch(updateInfoUrl);
53
-
54
- if (updateInfoResponse.ok) {
55
- // todo: this seems brittle
56
- updateInfo = await updateInfoResponse.json();
57
-
58
- if (updateInfo.hash !== localInfo.hash) {
59
- updateInfo.updateAvailable = true;
60
- }
61
- } else {
62
- return {
63
- version: "",
64
- hash: "",
65
- updateAvailable: false,
66
- updateReady: false,
67
- error: `Failed to fetch update info from ${updateInfoUrl}`,
68
- };
69
- }
70
- } catch (error) {
71
- return {
72
- version: "",
73
- hash: "",
74
- updateAvailable: false,
75
- updateReady: false,
76
- error: `Failed to fetch update info from ${updateInfoUrl}`,
77
- };
78
- }
79
-
80
- return updateInfo;
81
- },
82
-
83
- downloadUpdate: async () => {
84
- const appDataFolder = await Updater.appDataFolder();
85
- const channelBucketUrl = await Updater.channelBucketUrl();
86
- const appFileName = localInfo.name;
87
-
88
- let currentHash = (await Updater.getLocallocalInfo()).hash;
89
- let latestHash = (await Updater.checkForUpdate()).hash;
90
-
91
- let currentTarPath = join(
92
- appDataFolder,
93
- "self-extraction",
94
- `${currentHash}.tar`
95
- );
96
- const latestTarPath = join(
97
- appDataFolder,
98
- "self-extraction",
99
- `${latestHash}.tar`
100
- );
101
-
102
- const seenHashes = [];
103
-
104
- // todo (yoav): add a check to the while loop that checks for a hash we've seen before
105
- // so that update loops that are cyclical can be broken
106
- if (!(await Bun.file(latestTarPath).exists())) {
107
- while (currentHash !== latestHash) {
108
- seenHashes.push(currentHash);
109
- const currentTar = Bun.file(currentTarPath);
110
-
111
- if (!(await currentTar.exists())) {
112
- // tar file of the current version not found
113
- // so we can't patch it. We need the byte-for-byte tar file
114
- // so break out and download the full version
115
- break;
116
- }
117
-
118
- // check if there's a patch file for it
119
- const patchResponse = await fetch(
120
- join(channelBucketUrl, `${currentHash}.patch`)
121
- );
122
-
123
- if (!patchResponse.ok) {
124
- // patch not found
125
- break;
126
- }
127
-
128
- // The patch file's name is the hash of the "from" version
129
- const patchFilePath = join(
130
- appDataFolder,
131
- "self-extraction",
132
- `${currentHash}.patch`
133
- );
134
- await Bun.write(patchFilePath, await patchResponse.arrayBuffer());
135
- // patch it to a tmp name
136
- const tmpPatchedTarFilePath = join(
137
- appDataFolder,
138
- "self-extraction",
139
- `from-${currentHash}.tar`
140
- );
141
-
142
- // Note: cwd should be Contents/MacOS/ where the binaries are in the amc app bundle
143
- try {
144
- Bun.spawnSync([
145
- "bspatch",
146
- currentTarPath,
147
- tmpPatchedTarFilePath,
148
- patchFilePath,
149
- ]);
150
- } catch (error) {
151
- break;
152
- }
153
-
154
- let versionSubpath = "";
155
- const untarDir = join(appDataFolder, "self-extraction", "tmpuntar");
156
- mkdirSync(untarDir, { recursive: true });
157
-
158
- // extract just the version.json from the patched tar file so we can see what hash it is now
159
- await tar.x({
160
- // gzip: false,
161
- file: tmpPatchedTarFilePath,
162
- cwd: untarDir,
163
- filter: (path, stat) => {
164
- if (path.endsWith("Resources/version.json")) {
165
- versionSubpath = path;
166
- return true;
167
- } else {
168
- return false;
169
- }
170
- },
171
- });
172
-
173
- const currentVersionJson = await Bun.file(
174
- join(untarDir, versionSubpath)
175
- ).json();
176
- const nextHash = currentVersionJson.hash;
177
-
178
- if (seenHashes.includes(nextHash)) {
179
- console.log("Warning: cyclical update detected");
180
- break;
181
- }
182
-
183
- seenHashes.push(nextHash);
184
-
185
- if (!nextHash) {
186
- break;
187
- }
188
- // Sync the patched tar file to the new hash
189
- const updatedTarPath = join(
190
- appDataFolder,
191
- "self-extraction",
192
- `${nextHash}.tar`
193
- );
194
- renameSync(tmpPatchedTarFilePath, updatedTarPath);
195
-
196
- // delete the old tar file
197
- unlinkSync(currentTarPath);
198
- unlinkSync(patchFilePath);
199
- rmdirSync(untarDir, { recursive: true });
200
-
201
- currentHash = nextHash;
202
- currentTarPath = join(
203
- appDataFolder,
204
- "self-extraction",
205
- `${currentHash}.tar`
206
- );
207
- // loop through applying patches until we reach the latest version
208
- // if we get stuck then exit and just download the full latest version
209
- }
210
-
211
- // If we weren't able to apply patches to the current version,
212
- // then just download it and unpack it
213
- if (currentHash !== latestHash) {
214
- const cacheBuster = Math.random().toString(36).substring(7);
215
- const urlToLatestTarball = join(
216
- channelBucketUrl,
217
- `${appFileName}.app.tar.zst`
218
- );
219
- const prevVersionCompressedTarballPath = join(
220
- appDataFolder,
221
- "self-extraction",
222
- "latest.tar.zst"
223
- );
224
- const response = await fetch(urlToLatestTarball + `?${cacheBuster}`);
225
-
226
- if (response.ok && response.body) {
227
- const reader = response.body.getReader();
228
-
229
- const writer = Bun.file(prevVersionCompressedTarballPath).writer();
230
-
231
- while (true) {
232
- const { done, value } = await reader.read();
233
- if (done) break;
234
- await writer.write(value);
235
- }
236
- await writer.flush();
237
- writer.end();
238
- } else {
239
- console.log("latest version not found at: ", urlToLatestTarball);
240
- }
241
-
242
- await ZstdInit().then(async ({ ZstdSimple }) => {
243
- const data = new Uint8Array(
244
- await Bun.file(prevVersionCompressedTarballPath).arrayBuffer()
245
- );
246
- const uncompressedData = ZstdSimple.decompress(data);
247
-
248
- await Bun.write(latestTarPath, uncompressedData);
249
- });
250
-
251
- unlinkSync(prevVersionCompressedTarballPath);
252
- try {
253
- unlinkSync(currentTarPath);
254
- } catch (error) {
255
- // Note: ignore the error. it may have already been deleted by the patching process
256
- // if the patching process only got halfway
257
- }
258
- }
259
- }
260
-
261
- // Note: Bun.file().exists() caches the result, so we nee d an new instance of Bun.file() here
262
- // to check again
263
- if (await Bun.file(latestTarPath).exists()) {
264
- // download patch for this version, apply it.
265
- // check for patch from that tar and apply it, until it matches the latest version
266
- // as a fallback it should just download and unpack the latest version
267
- updateInfo.updateReady = true;
268
- } else {
269
- updateInfo.error = "Failed to download latest version";
270
- }
271
- },
272
-
273
- // todo (yoav): this should emit an event so app can cleanup or block the restart
274
- // todo (yoav): rename this to quitAndApplyUpdate or something
275
- applyUpdate: async () => {
276
- if (updateInfo?.updateReady) {
277
- const appDataFolder = await Updater.appDataFolder();
278
- const extractionFolder = join(appDataFolder, "self-extraction");
279
- let latestHash = (await Updater.checkForUpdate()).hash;
280
- const latestTarPath = join(extractionFolder, `${latestHash}.tar`);
281
-
282
- let appBundleSubpath: string = "";
283
-
284
- if (await Bun.file(latestTarPath).exists()) {
285
- await tar.x({
286
- // gzip: false,
287
- file: latestTarPath,
288
- cwd: extractionFolder,
289
- onentry: (entry) => {
290
- // find the first .app bundle in the tarball
291
- // Some apps may have nested .app bundles
292
- if (!appBundleSubpath && entry.path.endsWith(".app/")) {
293
- appBundleSubpath = entry.path;
294
- }
295
- },
296
- });
297
-
298
- if (!appBundleSubpath) {
299
- console.error("Failed to find app bundle in tarball");
300
- return;
301
- }
302
-
303
- // Note: resolve here removes the extra trailing / that the tar file adds
304
- const newAppBundlePath = resolve(
305
- join(extractionFolder, appBundleSubpath)
306
- );
307
- // Note: dirname(process.execPath) is the path to the running app bundle's
308
- // Contents/MacOS directory
309
- const runningAppBundlePath = resolve(
310
- dirname(process.execPath),
311
- "..",
312
- ".."
313
- );
314
- const backupAppBundlePath = join(extractionFolder, "backup.app");
315
-
316
- try {
317
- // const backupState = statSync(backupAppBundlePath);
318
- if (statSync(backupAppBundlePath, { throwIfNoEntry: false })) {
319
- rmdirSync(backupAppBundlePath, { recursive: true });
320
- } else {
321
- console.log("backupAppBundlePath does not exist");
322
- }
323
- renameSync(runningAppBundlePath, backupAppBundlePath);
324
- renameSync(newAppBundlePath, runningAppBundlePath);
325
- } catch (error) {
326
- console.error("Failed to replace app with new version", error);
327
- return;
328
- }
329
-
330
- await Bun.spawn(["open", runningAppBundlePath]);
331
- process.exit(0);
332
- }
333
- }
334
- },
335
-
336
- channelBucketUrl: async () => {
337
- await Updater.getLocallocalInfo();
338
- // todo: tmp hardcode canary
339
- return join(localInfo.bucketUrl, localInfo.channel);
340
- },
341
-
342
- appDataFolder: async () => {
343
- await Updater.getLocallocalInfo();
344
- const appDataFolder = join(
345
- appSupportDir,
346
- localInfo.identifier,
347
- localInfo.name
348
- );
349
-
350
- return appDataFolder;
351
- },
352
-
353
- // TODO: consider moving this from "Updater.localInfo" to "BuildVars"
354
- localInfo: {
355
- version: async () => {
356
- return (await Updater.getLocallocalInfo()).version;
357
- },
358
- hash: async () => {
359
- return (await Updater.getLocallocalInfo()).hash;
360
- },
361
- channel: async () => {
362
- return (await Updater.getLocallocalInfo()).channel;
363
- },
364
- bucketUrl: async () => {
365
- return (await Updater.getLocallocalInfo()).bucketUrl;
366
- },
367
- },
368
-
369
- getLocallocalInfo: async () => {
370
- if (localInfo) {
371
- return localInfo;
372
- }
373
-
374
- try {
375
- localInfo = await Bun.file("../Resources/version.json").json();
376
- return localInfo;
377
- } catch (error) {
378
- // Handle the error
379
- console.error("Failed to read version.json", error);
380
-
381
- // Then rethrow so the app crashes
382
- throw error;
383
- }
384
- },
385
- };
386
-
387
- export { Updater };