bunite-core 0.0.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.
@@ -0,0 +1,41 @@
1
+ import { app } from "./core/App";
2
+ import { BrowserWindow, type WindowOptionsType } from "./core/BrowserWindow";
3
+ import { BrowserView, type BrowserViewOptions } from "./core/BrowserView";
4
+ import * as Utils from "./core/Utils";
5
+ import { buniteEventEmitter } from "./events/eventEmitter";
6
+ import { BuniteEvent } from "./events/event";
7
+ import { completePermissionRequest } from "./proc/native";
8
+ import {
9
+ createRPC,
10
+ defineBuniteRPC,
11
+ type BuniteRPCConfig,
12
+ type BuniteRPCSchema,
13
+ type RPCSchema,
14
+ type RPCWithTransport
15
+ } from "../shared/rpc";
16
+ import type { BuniteConfig } from "../types/config";
17
+ import type { MessageBoxOptions, MessageBoxResponse } from "./core/Utils";
18
+
19
+ export {
20
+ app,
21
+ BrowserWindow,
22
+ BrowserView,
23
+ Utils,
24
+ buniteEventEmitter,
25
+ completePermissionRequest,
26
+ createRPC,
27
+ defineBuniteRPC
28
+ };
29
+
30
+ export type {
31
+ BuniteEvent,
32
+ BuniteConfig,
33
+ BuniteRPCConfig,
34
+ BuniteRPCSchema,
35
+ BrowserViewOptions,
36
+ MessageBoxOptions,
37
+ MessageBoxResponse,
38
+ RPCSchema,
39
+ RPCWithTransport,
40
+ WindowOptionsType
41
+ };
@@ -0,0 +1,73 @@
1
+ import { RPC_FRAME_VERSION, RPC_IV_LENGTH } from "../../shared/rpcWireConstants";
2
+
3
+ type BunitePreloadWindow = Window &
4
+ typeof globalThis & {
5
+ __bunite?: {
6
+ receiveMessageFromBun?: (message: unknown) => void;
7
+ };
8
+ __buniteWebviewId?: number;
9
+ __buniteRpcSocketPort?: number;
10
+ __bunite_encrypt?: (data: Uint8Array) => Promise<Uint8Array>;
11
+ __bunite_decrypt?: (data: Uint8Array) => Promise<Uint8Array>;
12
+ };
13
+
14
+ function base64ToUint8Array(base64: string) {
15
+ return Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
16
+ }
17
+
18
+ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
19
+ const copy = new Uint8Array(bytes.byteLength);
20
+ copy.set(bytes);
21
+ return copy.buffer;
22
+ }
23
+
24
+ async function importAesKey(secretKeyBase64: string) {
25
+ const keyData = base64ToUint8Array(secretKeyBase64);
26
+ return crypto.subtle.importKey("raw", toArrayBuffer(keyData), "AES-GCM", false, ["encrypt", "decrypt"]);
27
+ }
28
+
29
+ export async function installBunitePreloadGlobals(options: {
30
+ webviewId: number;
31
+ rpcSocketPort: number;
32
+ secretKeyBase64: string;
33
+ }) {
34
+ const buniteWindow = window as BunitePreloadWindow;
35
+ const cryptoKey = await importAesKey(options.secretKeyBase64);
36
+
37
+ const encrypt = async (data: Uint8Array) => {
38
+ const iv = crypto.getRandomValues(new Uint8Array(RPC_IV_LENGTH));
39
+ const encrypted = new Uint8Array(
40
+ await crypto.subtle.encrypt({ name: "AES-GCM", iv }, cryptoKey, toArrayBuffer(data))
41
+ );
42
+ const frame = new Uint8Array(1 + iv.length + encrypted.length);
43
+ frame[0] = RPC_FRAME_VERSION;
44
+ frame.set(iv, 1);
45
+ frame.set(encrypted, 1 + iv.length);
46
+ return frame;
47
+ };
48
+
49
+ const decrypt = async (frame: Uint8Array) => {
50
+ if (frame.length < 1 + RPC_IV_LENGTH + 16) {
51
+ throw new Error("Invalid bunite RPC frame.");
52
+ }
53
+ if (frame[0] !== RPC_FRAME_VERSION) {
54
+ throw new Error("Unsupported bunite RPC frame version.");
55
+ }
56
+ const iv = frame.slice(1, 1 + RPC_IV_LENGTH);
57
+ const encrypted = frame.slice(1 + RPC_IV_LENGTH);
58
+
59
+ const decrypted = await crypto.subtle.decrypt(
60
+ { name: "AES-GCM", iv },
61
+ cryptoKey,
62
+ toArrayBuffer(encrypted)
63
+ );
64
+
65
+ return new Uint8Array(decrypted);
66
+ };
67
+
68
+ buniteWindow.__bunite ??= {};
69
+ buniteWindow.__buniteWebviewId = options.webviewId;
70
+ buniteWindow.__buniteRpcSocketPort = options.rpcSocketPort;
71
+ buniteWindow.__bunite_encrypt = encrypt;
72
+ buniteWindow.__bunite_decrypt = decrypt;
73
+ }
@@ -0,0 +1,87 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, resolve, sep } from "node:path";
3
+
4
+ function escapeRootForComparison(path: string) {
5
+ return process.platform === "win32" ? path.toLowerCase() : path;
6
+ }
7
+
8
+ function resolveViewsFile(viewsRoot: string, url: string) {
9
+ const relativePath = url.replace(/^views:\/\//, "").replace(/^[\\/]+/, "");
10
+ const normalizedRoot = resolve(viewsRoot);
11
+ const candidate = resolve(normalizedRoot, relativePath.split("/").join(sep));
12
+ const comparableRoot = escapeRootForComparison(normalizedRoot);
13
+ const comparableCandidate = escapeRootForComparison(candidate);
14
+
15
+ if (
16
+ comparableCandidate !== comparableRoot &&
17
+ !comparableCandidate.startsWith(`${comparableRoot}${sep}`)
18
+ ) {
19
+ throw new Error(`preload path escapes viewsRoot: ${url}`);
20
+ }
21
+
22
+ return candidate;
23
+ }
24
+
25
+ function readCustomPreload(preload: string | null, viewsRoot: string | null) {
26
+ if (!preload) {
27
+ return "";
28
+ }
29
+
30
+ try {
31
+ const resolvedPath = preload.startsWith("views://")
32
+ ? viewsRoot
33
+ ? resolveViewsFile(viewsRoot, preload)
34
+ : null
35
+ : isAbsolute(preload)
36
+ ? preload
37
+ : resolve(preload);
38
+
39
+ if (!resolvedPath) {
40
+ console.warn(`[bunite] Cannot resolve preload without viewsRoot: ${preload}`);
41
+ return "";
42
+ }
43
+ if (!existsSync(resolvedPath)) {
44
+ console.warn(`[bunite] Preload file was not found: ${resolvedPath}`);
45
+ return "";
46
+ }
47
+
48
+ return readFileSync(resolvedPath, "utf8");
49
+ } catch (error) {
50
+ console.warn("[bunite] Failed to resolve preload script.", error);
51
+ return "";
52
+ }
53
+ }
54
+
55
+ // Pre-built preload runtime (built via `bun run build:preload` in package/)
56
+ const runtimePath = resolve(import.meta.dirname, "../../preload/runtime.built.js");
57
+ let cachedRuntime: string | null = null;
58
+
59
+ function getPreloadRuntime(): string {
60
+ if (cachedRuntime === null) {
61
+ if (!existsSync(runtimePath)) {
62
+ throw new Error(
63
+ `Preload runtime not found at ${runtimePath}. Run "bun run build:preload" in the package directory.`
64
+ );
65
+ }
66
+ cachedRuntime = readFileSync(runtimePath, "utf8");
67
+ }
68
+ return cachedRuntime;
69
+ }
70
+
71
+ export function buildViewPreloadScript(options: {
72
+ preload: string | null;
73
+ viewsRoot: string | null;
74
+ webviewId: number;
75
+ rpcSocketPort: number;
76
+ secretKey: Uint8Array;
77
+ }) {
78
+ const secretKeyBase64 = Buffer.from(options.secretKey).toString("base64");
79
+
80
+ // Per-view config — these globals are consumed by the pre-built runtime
81
+ const config = `var __buniteWebviewId=${options.webviewId},__buniteRpcSocketPort=${options.rpcSocketPort},__buniteSecretKeyBase64=${JSON.stringify(secretKeyBase64)};`;
82
+
83
+ const runtime = getPreloadRuntime();
84
+ const customPreload = readCustomPreload(options.preload, options.viewsRoot).trim();
85
+
86
+ return [config, runtime, customPreload].filter(Boolean).join("\n");
87
+ }