├── .gitignore ├── .gitmodules ├── .travis.yml ├── LICENSE ├── README.md ├── animation.gif ├── app ├── actions.js ├── config.js ├── context-menus.js ├── extensions │ ├── builtins.json │ ├── builtins │ │ ├── hybrid-history.zip │ │ └── ublock.zip │ └── index.js ├── history.js ├── index.js ├── llm-preload.js ├── llm.js ├── menu.js ├── pages │ ├── 404.html │ ├── about.html │ ├── bt.html │ ├── bt.ico │ ├── error.html │ ├── hyper.html │ ├── hyper.ico │ ├── icon.svg │ ├── iip.html │ ├── iip.ico │ ├── ipfs.html │ ├── ipfs.ico │ ├── oui.html │ ├── oui.ico │ ├── settings.html │ ├── theme │ │ ├── example.md │ │ ├── highlight.css │ │ ├── highlight.js │ │ └── style.css │ ├── tor.html │ ├── tor.ico │ └── welcome.html ├── protocols │ ├── browser-protocol.js │ ├── bt-protocol.js │ ├── gemini-protocol.js │ ├── gopher-protocol.js │ ├── hhttp-protocol.js │ ├── hyper-protocol.js │ ├── iip-protocol.js │ ├── index.js │ ├── ipfs-protocol.js │ ├── magnet-protocol.js │ ├── msg-protocol.js │ ├── oui-protocol.js │ ├── pubsub-protocol.js │ ├── rns-protocol.js │ ├── topic-protocol.js │ ├── tor-protocol.js │ ├── vid-protocol.js │ └── web3-protocol.js ├── settings-preload.js ├── ui │ ├── browser-actions.js │ ├── current-window.js │ ├── find-menu.js │ ├── index.html │ ├── omni-box.js │ ├── script.js │ ├── style.css │ └── tracked-box.js ├── version.js └── window.js ├── build ├── generate-logo.js ├── icon-small.png ├── icon.ico ├── icon.png ├── icon.svg └── icons │ └── 512x512.png ├── docs ├── Bookmarks.md ├── Extensions.md ├── Fetch-Gemini.md ├── Fetch-Hyper.md ├── Fetch-IPFS.md ├── Keyboard-Shortcuts.md ├── Protocols.md ├── README.md ├── Theming.md └── Troubleshooting.md ├── download-extensions.js ├── package.json ├── rebuild.sh └── update-versions.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # radata files 10 | radata* 11 | 12 | # radata folder 13 | radata/ 14 | 15 | # Diagnostic reports (https://nodejs.org/api/report.html) 16 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 17 | 18 | # Runtime data 19 | pids 20 | *.pid 21 | *.seed 22 | *.pid.lock 23 | 24 | # Directory for instrumented libs generated by jscoverage/JSCover 25 | lib-cov 26 | 27 | # Coverage directory used by tools like istanbul 28 | coverage 29 | *.lcov 30 | 31 | # nyc test coverage 32 | .nyc_output 33 | 34 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 35 | .grunt 36 | 37 | # Bower dependency directory (https://bower.io/) 38 | bower_components 39 | 40 | # node-waf configuration 41 | .lock-wscript 42 | 43 | # Compiled binary addons (https://nodejs.org/api/addons.html) 44 | build/Release 45 | 46 | # Dependency directories 47 | node_modules/ 48 | jspm_packages/ 49 | 50 | # TypeScript v1 declaration files 51 | typings/ 52 | 53 | # TypeScript cache 54 | *.tsbuildinfo 55 | 56 | # Optional npm cache directory 57 | .npm 58 | 59 | # Optional eslint cache 60 | .eslintcache 61 | 62 | # Microbundle cache 63 | .rpt2_cache/ 64 | .rts2_cache_cjs/ 65 | .rts2_cache_es/ 66 | .rts2_cache_umd/ 67 | 68 | # Optional REPL history 69 | .node_repl_history 70 | 71 | # Output of 'npm pack' 72 | *.tgz 73 | 74 | # Yarn Integrity file 75 | .yarn-integrity 76 | 77 | # dotenv environment variables file 78 | .env 79 | .env.test 80 | 81 | # parcel-bundler cache (https://parceljs.org/) 82 | .cache 83 | 84 | # Next.js build output 85 | .next 86 | 87 | # Nuxt.js build / generate output 88 | .nuxt 89 | dist 90 | 91 | # Gatsby files 92 | .cache/ 93 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 94 | # https://nextjs.org/blog/next-9-1#public-directory-support 95 | # public 96 | 97 | # vuepress build output 98 | .vuepress/dist 99 | 100 | # Serverless directories 101 | .serverless/ 102 | 103 | # FuseBox cache 104 | .fusebox/ 105 | 106 | # DynamoDB Local files 107 | .dynamodb/ 108 | 109 | # TernJS port file 110 | .tern-port 111 | 112 | # Ignore releases folder 113 | release/ 114 | 115 | # Ignore zip files for downloaded extensions 116 | app/extensions/builtins/ 117 | 118 | # Ignore RC file used for testing the config 119 | .hybridrc 120 | 121 | # Ignore nano temporary files 122 | *.swp 123 | 124 | # prettier config 125 | .prettierrc 126 | 127 | # visual code config 128 | .vscode/ 129 | .vs/ 130 | 131 | # We use yarn lockfiles instead of package-lock 132 | package-lock.json 133 | 134 | # This gets generated post install 135 | app/version.js 136 | 137 | # This gets generated when I open in a Container 138 | .devcontainer -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/.gitmodules -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | 3 | language: node_js 4 | node_js: "12.16.2" 5 | 6 | cache: 7 | directories: 8 | # - node_modules 9 | # - app/node_modules 10 | - $HOME/.cache/electron 11 | - $HOME/.cache/electron-builder 12 | # - $HOME/.npm/_prebuilds 13 | 14 | env: 15 | global: 16 | - ELECTRON_CACHE=$HOME/.cache/electron 17 | - ELECTRON_BUILDER_CACHE=$HOME/.cache/electron-builder 18 | 19 | jobs: 20 | include: 21 | - stage: Test 22 | script: 23 | - npm test 24 | - stage: Deploy Linux 25 | if: tag IS present 26 | os: linux 27 | dist: trusty 28 | script: 29 | - npm run build -- --linux -p always 30 | - stage: Deploy Mac and Windows 31 | if: tag IS present 32 | os: osx 33 | osx_image: xcode10.1 34 | script: 35 | - npm run build -- --mac -p always 36 | - npm run build -- --win -p always 37 | before_cache: 38 | - rm -rf $HOME/.cache/electron-builder/wine 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Hybrid Browser 2 | 3 | Browse the p2p networks, create and view p2p websites
4 | [Matrix](https://matrix.to/#/#hybrid-browser:matrix.org)
5 | [Discord](https://discord.gg/8QzHpF8VZt)
6 | 7 |

8 | 9 |

10 | 11 | Hybrid is a p2p browser. it supports the following networks and protocols: 12 | 13 | bittorrent
14 | ipfs
15 | hyper
16 | ouinet
17 | 18 | It means you will be able to interact with p2p networks and view the p2p data on the browser. You will be able to create and upload p2p websites. 19 | 20 | on a regular website, on the html file you would have 21 | 22 | ``` 23 | 24 | 25 | 26 | test 27 | 28 | 29 | 30 |
31 |

test

32 | 33 |
34 | 35 | 36 | ``` 37 | 38 | With hybrid, you can do the same AND MORE like the following 39 | 40 | ``` 41 | 42 | 43 | 44 | test 45 | 46 | 47 | 48 |
49 |

http example, regular http link

50 | 51 | 52 |

bittorrent example, loading from p2p network using p2p link

53 | 54 |
55 | 56 | 57 | ``` 58 | 59 | ![Hybrid Animation](animation.gif) 60 | 61 | This makes it possible to create fully peer to peer websites, no middlemen and no servers. 62 | 63 | --- 64 | user configuration
65 | windows directory: C:\Users\username
66 | linux directory: /home/username
67 | file: .hybridrc
68 | data: JSON object
69 | 70 | ``` 71 | { 72 | "bt": {}, 73 | "ipfs": {}, 74 | "hyper": {}, 75 | "oui": {}, 76 | "gemini": {}, 77 | "gopher": {}, 78 | "hhttp": {} 79 | } 80 | ``` 81 | options for each protocol handler 82 | ``` 83 | // https://github.com/ducksandgoats/torrentz#options for bt options, along with the following 84 | bt: { 85 | status: true, // boolean, enables or disables the handler, optional, default: true 86 | timeout: 0 // number, optional, default: 30000 87 | } 88 | 89 | // https://github.com/ipfs/js-ipfs/blob/master/docs/MODULE.md#ipfscreateoptions for ipfs options, along with the following 90 | ipfs: { 91 | status: true, // boolean, enables or disables the handler, optional, default: true 92 | timeout: 0 // number, optional, default: 30000 93 | } 94 | 95 | // https://github.com/RangerMauve/hyper-sdk#sdkcreate for hyper options, along with the following 96 | hyper: { 97 | status: true, // boolean, enables or disables the handler, optional, default: true 98 | timeout: 0 // number, optional, default: 30000 99 | } 100 | 101 | oui: { 102 | status: true, // boolean, enables or disables the handler, optional, default: true 103 | timeout: 0 // number, optional, default: 30000 104 | }, 105 | 106 | gemini: { 107 | status: true, // boolean, enables or disables the handler, optional, default: true 108 | timeout: 0 // number, optional, default: 30000 109 | }, 110 | 111 | gopher: { 112 | status: true, // boolean, enables or disables the handler, optional, default: true 113 | timeout: 0 // number, optional, default: 30000 114 | }, 115 | 116 | hhttp: { 117 | status: true, // boolean, enables or disables the handler, optional, default: true 118 | timeout: 0 // number, optional, default: 30000 119 | } 120 | ``` 121 | --- 122 | 123 | This project was forked from [Hybrid Browser](https://github.com/HybridWeb/hybrid-browser). 124 | Special thanks and shout out to [RangerMauve](https://github.com/RangerMauve), they are the creator and developer of Hybrid. 125 | -------------------------------------------------------------------------------- /animation.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/animation.gif -------------------------------------------------------------------------------- /app/actions.js: -------------------------------------------------------------------------------- 1 | import { app, shell, dialog } from 'electron' 2 | import fs from 'fs-extra' 3 | import path from 'path' 4 | import createDesktopShortcut from 'create-desktop-shortcuts' 5 | import dataUriToBuffer from 'data-uri-to-buffer' 6 | import sanitize from 'sanitize-filename' 7 | import * as history from './history.js' 8 | 9 | import Config from './config.js' 10 | const { accelerators, extensions, appPath } = Config 11 | 12 | const DEFAULT_CONFIG_FILE_NAME = '.hybridrc' 13 | 14 | const FOCUS_URL_BAR_SCRIPT = ` 15 | document.getElementById('search').showInput() 16 | document.getElementById('search').focus() 17 | ` 18 | 19 | const OPEN_FIND_BAR_SCRIPT = ` 20 | document.getElementById('find').show() 21 | ` 22 | 23 | export function createActions ({ 24 | createWindow 25 | }) { 26 | return { 27 | OpenDevTools: { 28 | label: 'Open Dev Tools', 29 | accelerator: accelerators.OpenDevTools, 30 | click: onOpenDevTools 31 | }, 32 | ViewHistory: { 33 | label: 'View History', 34 | accelerator: accelerators.ViewHistory, 35 | click: onViewHistory 36 | }, 37 | NewWindow: { 38 | label: 'New Window', 39 | click: onNewWindow, 40 | accelerator: accelerators.NewWindow 41 | }, 42 | Forward: { 43 | label: 'Forward', 44 | accelerator: accelerators.Forward, 45 | click: onGoForward 46 | }, 47 | Back: { 48 | label: 'Back', 49 | accelerator: accelerators.Back, 50 | click: onGoBack 51 | }, 52 | FocusURLBar: { 53 | label: 'Focus URL Bar', 54 | click: onFocusURlBar, 55 | accelerator: accelerators.FocusURLBar 56 | }, 57 | FindInPage: { 58 | label: 'Find in Page', 59 | click: onFindInPage, 60 | accelerator: accelerators.FindInPage 61 | }, 62 | Reload: { 63 | label: 'Reload', 64 | accelerator: accelerators.Reload, 65 | click: onReload 66 | }, 67 | HardReload: { 68 | label: 'Hard Reload', 69 | accelerator: accelerators.HardReload, 70 | click: onHardReload 71 | }, 72 | LearnMore: { 73 | label: 'Learn More', 74 | accelerator: accelerators.LearnMore, 75 | click: onLearMore 76 | }, 77 | SetAsDefault: { 78 | label: 'Set as Default Browser', 79 | accelerator: accelerators.SetAsDefault, 80 | click: onSetAsDefault 81 | }, 82 | SetAsDefaultMagnet: { 83 | label: 'Set as Default for Torrents', 84 | accelerator: accelerators.SetAsDefaultMagnet, 85 | click: onSetAsDefaultMagnet 86 | }, 87 | OpenExtensionFolder: { 88 | label: 'Open Extensions Folder', 89 | accelerator: accelerators.OpenExtensionFolder, 90 | click: onOpenExtensionFolder 91 | }, 92 | OpenDataFolder: { 93 | label: 'Open Data Folder', 94 | accelerator: accelerators.OpenDataFolder, 95 | click: onOpenDataFolder 96 | }, 97 | EditConfigFile: { 98 | label: 'Edit Configuration File', 99 | accelerator: accelerators.EditConfigFile, 100 | click: onEditConfigFile 101 | }, 102 | OpenConfigFile: { 103 | label: 'Open Configuration File', 104 | accelerator: accelerators.OpenConfigFile, 105 | click: onOpenConfigFile 106 | }, 107 | CreateBookmark: { 108 | label: 'Create Bookmark', 109 | accelerator: accelerators.CreateBookmark, 110 | click: onCreateBookmark 111 | } 112 | } 113 | async function onSetAsDefault () { 114 | app.setAsDefaultProtocolClient('http') 115 | app.setAsDefaultProtocolClient('https') 116 | } 117 | 118 | async function onSetAsDefaultMagnet () { 119 | app.setAsDefaultProtocolClient('magnet') 120 | } 121 | 122 | async function onLearMore () { 123 | await shell.openExternal('https://github.com/HybridWare/hybrid-browser') 124 | } 125 | 126 | function onOpenDevTools (event, focusedWindow, focusedWebContents) { 127 | const contents = getContents(focusedWindow) 128 | for (const webContents of contents) { 129 | webContents.openDevTools() 130 | } 131 | } 132 | 133 | function onNewWindow (event, focusedWindow, focusedWebContents) { 134 | createWindow() 135 | } 136 | 137 | function onFocusURlBar (event, focusedWindow) { 138 | focusedWindow.webContents.focus() 139 | focusedWindow.webContents.executeJavaScript(FOCUS_URL_BAR_SCRIPT, true) 140 | } 141 | 142 | function onFindInPage (event, focusedWindow) { 143 | focusedWindow.webContents.focus() 144 | focusedWindow.webContents.executeJavaScript(OPEN_FIND_BAR_SCRIPT, true) 145 | } 146 | 147 | function onReload (event, focusedWindow, focusedWebContents) { 148 | // Reload 149 | for (const webContents of getContents(focusedWindow)) { 150 | webContents.reload() 151 | } 152 | } 153 | 154 | function onHardReload (event, focusedWindow, focusedWebContents) { 155 | // Hard reload 156 | for (const webContents of getContents(focusedWindow)) { 157 | webContents.reloadIgnoringCache() 158 | } 159 | } 160 | 161 | function onGoForward (event, focusedWindow) { 162 | for (const webContents of getContents(focusedWindow)) { 163 | webContents.goForward() 164 | } 165 | } 166 | 167 | function onGoBack (event, focusedWindow) { 168 | for (const webContents of getContents(focusedWindow)) { 169 | webContents.goBack() 170 | } 171 | } 172 | 173 | function getContents (focusedWindow) { 174 | const views = focusedWindow.getBrowserViews() 175 | if (!views.length) return [focusedWindow.webContents] 176 | return views.map(({ webContents }) => webContents) 177 | } 178 | 179 | async function onOpenExtensionFolder () { 180 | try { 181 | const { dir } = extensions 182 | await fs.ensureDir(dir) 183 | 184 | await shell.openPath(dir) 185 | } catch (e) { 186 | console.error(e.stack) 187 | } 188 | } 189 | 190 | async function onOpenDataFolder () { 191 | try { 192 | await shell.openPath(app.getPath('userData')) 193 | } catch (e) { 194 | console.error(e.stack) 195 | } 196 | } 197 | 198 | async function onEditConfigFile () { 199 | await createWindow('hybrid://settings') 200 | } 201 | 202 | async function onViewHistory () { 203 | await createWindow(history.getViewPage()) 204 | } 205 | 206 | async function onCreateBookmark (event, focusedWindow) { 207 | for (const webContents of getContents(focusedWindow)) { 208 | const defaultPath = app.getPath('desktop') 209 | const outputPath = (await dialog.showOpenDialog({ 210 | defaultPath, 211 | properties: ['openDirectory'] 212 | })).filePaths[0] 213 | 214 | // If testing from source find and use installed Hybrid location 215 | const filePath = appPath || process.argv[0] 216 | 217 | const title = webContents.getTitle() 218 | const shortcutName = sanitize(title, { replacement: ' ' }) 219 | const url = webContents.getURL() 220 | const description = `Hybrid Browser - ${url}` 221 | 222 | const shortcut = { 223 | filePath, 224 | outputPath, 225 | name: shortcutName, 226 | comment: description, 227 | description, 228 | arguments: url 229 | } 230 | 231 | const createShortcut = icon => { 232 | if (icon) shortcut.icon = icon 233 | // TODO: Kyran: Use Hybrid icon if no icon provided. 234 | // TODO: Kyran: OSX doesn't have arguments option. See https://github.com/RangerMauve/hybrid-browser/pull/53#issuecomment-705654060 for solution. 235 | createDesktopShortcut({ 236 | windows: shortcut, 237 | linux: shortcut 238 | }) 239 | } 240 | 241 | try { 242 | const type = process.platform === 'win32' ? 'ico' : 'png' 243 | const faviconDataURI = await getFaviconDataURL(webContents, type) 244 | const buffer = dataUriToBuffer(faviconDataURI) 245 | 246 | const savePath = path.join(app.getPath('userData'), 'PWAs', shortcutName) 247 | const faviconPath = path.join(savePath, `favicon.${type}`) 248 | 249 | await fs.ensureDir(savePath) 250 | await fs.writeFile(faviconPath, buffer) 251 | 252 | createShortcut(faviconPath) 253 | } catch (e) { 254 | console.error('Error loading favicon') 255 | console.error(e.stack) 256 | createShortcut() 257 | } 258 | } 259 | } 260 | 261 | async function onOpenConfigFile () { 262 | const file = path.join(os.homedir(), DEFAULT_CONFIG_FILE_NAME) 263 | 264 | const exists = await fs.pathExists(file) 265 | 266 | if (!exists) await fs.writeJson(file, {}) 267 | 268 | await shell.openPath(file) 269 | } 270 | } 271 | 272 | async function getFaviconDataURL (webContents, type) { 273 | return webContents.executeJavaScript(`new Promise(async (resolve, reject) => { 274 | try { 275 | const {href} = document.querySelector("link[rel*='icon']") 276 | 277 | const image = new Image() 278 | await new Promise(resolve => { 279 | image.onload = resolve 280 | image.src = href 281 | }) 282 | 283 | const canvas = document.createElement('canvas') 284 | canvas.width = 256 285 | canvas.height = 256 286 | 287 | const context = canvas.getContext('2d') 288 | context.drawImage(image, 0, 0, 256, 256) 289 | 290 | ${ 291 | type === 'ico' 292 | ? ` 293 | canvas.toBlob(blob => { 294 | const reader = new FileReader() 295 | reader.onload = () => resolve(reader.result) 296 | reader.readAsDataURL(new Blob([].concat([ 297 | [0, 0], // ICO header 298 | [1, 0], // Is ICO 299 | [1, 0], // Number of images 300 | [0], // Width (0 seems to work) 301 | [0], // Height (0 seems to work) 302 | [0], // Color palette (none) 303 | [0], // Reserved space 304 | [1, 0], // Color planes 305 | [32, 0], // Bit depth 306 | ].map(part => new Uint8Array(part).buffer), [ 307 | [blob.size], // Image byte size 308 | [22], // Image byte offset 309 | ].map(part => new Uint32Array(part).buffer), [ 310 | blob, // Image 311 | ]), {type: 'image/vnd.microsoft.icon'})) 312 | })` 313 | 314 | : "resolve(canvas.toDataURL('image/png'))" 315 | } 316 | } catch (e) { 317 | reject(e) 318 | } 319 | })`) 320 | } 321 | // 322 | -------------------------------------------------------------------------------- /app/config.js: -------------------------------------------------------------------------------- 1 | import { app, ipcMain } from 'electron' 2 | import RC from 'rc' 3 | 4 | import os from 'node:os' 5 | import path from 'node:path' 6 | import { readFile, writeFile } from 'node:fs/promises' 7 | import url from 'node:url' 8 | import { getDefaultChainList } from 'web3protocol/chains' 9 | 10 | const __dirname = url.fileURLToPath(new URL('./', import.meta.url)) 11 | 12 | const USER_DATA = app.getPath('userData') 13 | const DEFAULT_EXTENSIONS_DIR = path.join(USER_DATA, 'extensions') 14 | const DEFAULT_IPFS_DIR = path.join(USER_DATA, 'ipfs') 15 | const DEFAULT_HYPER_DIR = path.join(USER_DATA, 'hyper') 16 | // const DEFAULT_SSB_DIR = path.join(USER_DATA, 'ssb') 17 | const DEFAULT_BT_DIR = path.join(USER_DATA, 'bt') 18 | 19 | const DEFAULT_PAGE = 'hybrid://welcome' 20 | 21 | const DEFAULT_CONFIG_FILE_NAME = '.hybridrc' 22 | export const MAIN_RC_FILE = path.join(os.homedir(), DEFAULT_CONFIG_FILE_NAME) 23 | 24 | const Config = RC('hybrid', { 25 | llm: { 26 | enabled: true, 27 | 28 | baseURL: 'http://127.0.0.1:11434/v1/', 29 | // Uncomment this to use OpenAI instead 30 | // baseURL: 'https://api.openai.com/v1/' 31 | apiKey: 'ollama', 32 | model: 'qwen2.5-coder:3b' 33 | }, 34 | accelerators: { 35 | OpenDevTools: 'CommandOrControl+Shift+I', 36 | NewWindow: 'CommandOrControl+N', 37 | Forward: 'CommandOrControl+]', 38 | Back: 'CommandOrControl+[', 39 | FocusURLBar: 'CommandOrControl+L', 40 | FindInPage: 'CommandOrControl+F', 41 | Reload: 'CommandOrControl+R', 42 | HardReload: 'CommandOrControl+Shift+R', 43 | LearnMore: null, 44 | OpenExtensionsFolder: null, 45 | EditConfigFile: 'CommandOrControl+.', 46 | OpenConfigFile: 'CommandOrControl+,', 47 | CreateBookmark: 'CommandOrControl+D' 48 | }, 49 | 50 | extensions: { 51 | dir: DEFAULT_EXTENSIONS_DIR, 52 | // TODO: This will be for loading extensions from remote URLs 53 | remote: [] 54 | }, 55 | 56 | theme: { 57 | 'font-family': 'system-ui', 58 | background: 'var(--hy-color-white)', 59 | text: 'var(--hy-color-black)', 60 | primary: 'var(--hy-color-blue)', 61 | secondary: 'var(--hy-color-red)', 62 | indent: '16px', 63 | 'max-width': '666px' 64 | }, 65 | 66 | defaultPage: DEFAULT_PAGE, 67 | autoHideMenuBar: false, 68 | 69 | err: true, 70 | 71 | bt: { 72 | dir: DEFAULT_BT_DIR, 73 | refresh: false, 74 | status: true, 75 | block: true 76 | }, 77 | 78 | ipfs: { 79 | repo: DEFAULT_IPFS_DIR, 80 | refresh: false, 81 | status: true, 82 | block: true 83 | }, 84 | 85 | hyper: { 86 | storage: DEFAULT_HYPER_DIR, 87 | refresh: false, 88 | status: true, 89 | block: true 90 | }, 91 | oui: { 92 | status: true 93 | }, 94 | 95 | gemini: { 96 | status: true 97 | }, 98 | 99 | gopher: { 100 | status: true 101 | }, 102 | 103 | hhttp: { 104 | status: true 105 | }, 106 | 107 | tor: { 108 | status: true 109 | }, 110 | 111 | iip: { 112 | status: true 113 | }, 114 | vid: { 115 | status: true 116 | }, 117 | rns: { 118 | status: true 119 | }, 120 | web3: { 121 | chainList: getDefaultChainList(), 122 | multipleRpcMode: 'fallback' 123 | }, 124 | }) 125 | 126 | export default Config 127 | 128 | export function addPreloads (session) { 129 | const preloadPath = path.join(__dirname, 'settings-preload.js') 130 | const preloads = session.getPreloads() 131 | preloads.push(preloadPath) 132 | session.setPreloads(preloads) 133 | } 134 | 135 | ipcMain.handle('settings-save', async (event, configMap) => { 136 | await save(configMap) 137 | }) 138 | 139 | export async function save (configMap) { 140 | const currentRC = await getRCData() 141 | let hasChanged = false 142 | for (const [key, value] of Object.entries(configMap)) { 143 | const existing = getFrom(key, Config) 144 | if (existing === undefined) continue 145 | if (value === existing) continue 146 | hasChanged = true 147 | setOn(key, Config, value) 148 | setOn(key, currentRC, value) 149 | } 150 | if (hasChanged) { 151 | await writeFile(MAIN_RC_FILE, JSON.stringify(currentRC, null, '\t')) 152 | } 153 | } 154 | 155 | async function getRCData () { 156 | try { 157 | const data = await readFile(MAIN_RC_FILE, 'utf8') 158 | return JSON.parse(data) 159 | } catch { 160 | return {} 161 | } 162 | } 163 | 164 | function setOn (path, object, value) { 165 | if (path.includes('.')) { 166 | const [key, subkey] = path.split('.') 167 | if (typeof object[key] !== 'object') { 168 | object[key] = {} 169 | } 170 | object[key][subkey] = value 171 | } else { 172 | object[path] = value 173 | } 174 | } 175 | 176 | // No support for more than one level 177 | function getFrom (path, object) { 178 | if (path.includes('.')) { 179 | const [key, subkey] = path.split('.') 180 | if (typeof object[key] !== 'object') return undefined 181 | return object[key][subkey] 182 | } else { 183 | return object[path] 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /app/context-menus.js: -------------------------------------------------------------------------------- 1 | import { 2 | Menu, 3 | MenuItem, 4 | clipboard 5 | } from 'electron' 6 | 7 | export function attachContextMenus ({ window, createWindow, extensions }) { 8 | if (window.web) { 9 | window.webContents.on('context-menu', headerContextMenu) 10 | window.web.on('context-menu', pageContextMenu) 11 | } else { 12 | window.webContents.on('context-menu', rawWindowContextMenu) 13 | } 14 | 15 | function rawWindowContextMenu (event, params) { 16 | showContextMenu([ 17 | navigationGroup(window.web || window.webContents, params), 18 | historyBufferGroup(params), 19 | linkGroup(params), 20 | editGroup(params), 21 | developmentGroup(window.web || window.webContents, params) 22 | ]) 23 | } 24 | 25 | function headerContextMenu (event, params) { 26 | if (params.inputFieldType === 'plainText') { 27 | showContextMenu([ 28 | historyBufferGroup(params, false), 29 | editGroup(params, true) 30 | ]) 31 | } 32 | // TODO: Context menus for browser actions 33 | } 34 | 35 | function pageContextMenu (event, params) { 36 | showContextMenu([ 37 | navigationGroup(window.web || window.webContents, params), 38 | historyBufferGroup(params), 39 | linkGroup(params), 40 | saveGroup(params), 41 | editGroup(params), 42 | developmentGroup(window.web || window.webContents, params), 43 | extensionGroup(event, params) 44 | ]) 45 | } 46 | 47 | function showContextMenu (groups) { 48 | const menu = new Menu() 49 | groups 50 | .filter(group => group != null) 51 | .flatMap((group, index, array) => { 52 | if (index + 1 < array.length) { 53 | const separator = new MenuItem({ type: 'separator' }) 54 | group.push(separator) 55 | } 56 | return group 57 | }) 58 | .forEach(item => menu.append(item)) 59 | menu.popup(window.window) 60 | } 61 | 62 | function extensionGroup (event, params) { 63 | const webContents = window.web 64 | return extensions.listContextMenuForEvent(webContents, event, params) 65 | } 66 | 67 | function historyBufferGroup ({ editFlags, isEditable }, showRedo = true) { 68 | return !isEditable 69 | ? null 70 | : [ 71 | new MenuItem({ 72 | label: 'Undo', 73 | enabled: editFlags.canUndo, 74 | accelerator: 'CommandOrControl+Z', 75 | role: 'undo' 76 | }), 77 | new MenuItem({ 78 | label: 'Redo', 79 | enabled: editFlags.canRedo, 80 | visible: showRedo, 81 | accelerator: 'CommandOrControl+Y', 82 | role: 'redo' 83 | }) 84 | ] 85 | } 86 | 87 | function editGroup ({ editFlags, isEditable, selectionText }) { 88 | return !isEditable && !selectionText 89 | ? null 90 | : [ 91 | new MenuItem({ 92 | label: 'Cut', 93 | enabled: editFlags.canCut, 94 | accelerator: 'CommandOrControl+X', 95 | role: 'cut' 96 | }), 97 | new MenuItem({ 98 | label: 'Copy', 99 | enabled: editFlags.canCopy, 100 | accelerator: 'CommandOrControl+C', 101 | role: 'copy' 102 | }), 103 | new MenuItem({ 104 | label: 'Paste', 105 | enabled: editFlags.canPaste, 106 | accelerator: 'CommandOrControl+P', 107 | role: 'paste' 108 | }), 109 | new MenuItem({ 110 | label: 'Delete', 111 | enabled: editFlags.canDelete, 112 | role: 'delete' 113 | }), 114 | new MenuItem({ 115 | type: 'separator' 116 | }), 117 | new MenuItem({ 118 | label: 'Select All', 119 | enabled: editFlags.canSelectAll, 120 | accelerator: 'CommandOrControl+A', 121 | role: 'selectAll' 122 | }) 123 | ] 124 | } 125 | 126 | function navigationGroup (wc, { mediaType, isEditable }) { 127 | return mediaType !== 'none' || isEditable 128 | ? null 129 | : [ 130 | new MenuItem({ 131 | label: 'Back', 132 | enabled: wc.canGoBack(), 133 | click: () => wc.goBack() 134 | }), 135 | new MenuItem({ 136 | label: 'Forward', 137 | enabled: wc.canGoForward(), 138 | click: () => wc.goForward() 139 | }), 140 | new MenuItem({ 141 | label: 'Reload', 142 | click: () => wc.reload() 143 | }), 144 | new MenuItem({ 145 | label: 'Hard Reload', 146 | click: () => wc.reloadIgnoringCache() 147 | }) 148 | ] 149 | } 150 | 151 | function developmentGroup (wc, { x, y }) { 152 | return [ 153 | new MenuItem({ 154 | label: 'Inspect', 155 | click () { 156 | wc.inspectElement(x, y) 157 | if (wc.isDevToolsOpened()) wc.devToolsWebContents.focus() 158 | } 159 | }) 160 | ] 161 | } 162 | 163 | function linkGroup ({ linkURL, linkText, selectionText, frameURL, pageURL }) { 164 | const items = [] 165 | 166 | if (linkURL.length) { 167 | items.push( 168 | new MenuItem({ 169 | label: 'Open link in new window', 170 | click: () => createWindow(linkURL) 171 | }), 172 | new MenuItem({ 173 | label: 'Copy link address', 174 | click: () => clipboard.writeText(linkURL) 175 | }), 176 | new MenuItem({ 177 | label: 'Copy link text', 178 | click: () => clipboard.writeText(linkText) 179 | }) 180 | ) 181 | } 182 | 183 | if (selectionText) { 184 | const url = new URL(frameURL || pageURL) 185 | url.hash = `#$:~:text=${encodeURIComponent(selectionText)}` 186 | items.push( 187 | new MenuItem({ 188 | label: 'Copy link text', 189 | click: () => clipboard.writeText(url.href) 190 | }) 191 | ) 192 | } 193 | 194 | return items.length ? items : null 195 | } 196 | 197 | function saveGroup ({ srcURL }) { 198 | return !srcURL.length 199 | ? null 200 | : [ 201 | new MenuItem({ 202 | label: 'Copy source address', 203 | click: () => clipboard.writeText(srcURL) 204 | }), 205 | new MenuItem({ 206 | label: 'Save As', 207 | click: () => saveAs(srcURL) 208 | }) 209 | ] 210 | } 211 | 212 | async function saveAs (link, browserWindow) { 213 | await window.web.downloadURL(link) 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /app/extensions/builtins.json: -------------------------------------------------------------------------------- 1 | { 2 | "hybrid-history": { 3 | "version": "1.1.1", 4 | "url": "https://github.com/HybridWare/extension-hybrid-history/releases/download/v{version}/v{version}.zip" 5 | }, 6 | "hybrid-renderer": { 7 | "version": "1.1.1", 8 | "url": "https://github.com/HybridWare/extension-hybrid-renderer/releases/download/v{version}/v{version}.zip" 9 | }, 10 | "archiveweb.page": { 11 | "version": "0.10.0", 12 | "url": "https://github.com/webrecorder/archiveweb.page/releases/download/v{version}/ArchiveWeb.page-{version}-extension.zip" 13 | }, 14 | "ublock": { 15 | "version": "1.47.4", 16 | "url": "https://github.com/gorhill/uBlock/releases/download/{version}/uBlock0_{version}.chromium.zip", 17 | "stripPrefix": "uBlock0.chromium/" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /app/extensions/builtins/hybrid-history.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/extensions/builtins/hybrid-history.zip -------------------------------------------------------------------------------- /app/extensions/builtins/ublock.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/extensions/builtins/ublock.zip -------------------------------------------------------------------------------- /app/extensions/index.js: -------------------------------------------------------------------------------- 1 | import path from 'node:path' 2 | import { readdir, readFile } from 'node:fs/promises' 3 | import { fileURLToPath } from 'node:url' 4 | import EventEmitter from 'node:events' 5 | import fs from 'fs-extra' 6 | import semver from 'semver' 7 | import decompress from 'decompress' 8 | 9 | import { ExtendedExtensions } from 'electron-extended-webextensions' 10 | 11 | // TODO: This smells! Inject options in constructor 12 | import Config from '../config.js' 13 | 14 | const { dir: extensionsDir, remote } = Config.extensions 15 | 16 | // Handle `app.asar` Electron functionality so that extensions can be referenced on the FS 17 | // Also note that MacOS uses `app-arm64.asar`, so we should target the first `.asar/` 18 | const __dirname = fileURLToPath(new URL('./', import.meta.url)).replace(`.asar${path.sep}`, `.asar.unpacked${path.sep}`) 19 | const DEFAULT_EXTENSION_LOCATION = path.join(__dirname, 'builtins') 20 | const DEFAULT_EXTENSION_LIST_LOCATION = path.join(__dirname, 'builtins.json') 21 | 22 | export class Extensions extends EventEmitter { 23 | constructor ({ 24 | session, 25 | createWindow, 26 | updateBrowserActions, 27 | builtinsLocation = DEFAULT_EXTENSION_LOCATION, 28 | builtinsListLocation = DEFAULT_EXTENSION_LIST_LOCATION, 29 | storageLocation = extensionsDir 30 | }) { 31 | super() 32 | this.createWindow = createWindow 33 | this.updateBrowserActions = updateBrowserActions 34 | this.session = session 35 | 36 | this.builtinsLocation = builtinsLocation 37 | this.builtinsListLocation = builtinsListLocation 38 | this.storageLocation = storageLocation 39 | 40 | async function onCreateTab ({ url, popup, openerTabId }) { 41 | const options = { url } 42 | if (popup) options.popup = true 43 | if (openerTabId) options.openerTabId = openerTabId 44 | const window = await createWindow(url, options) 45 | return window.web 46 | } 47 | 48 | this.extensions = new ExtendedExtensions(this.session, { 49 | onCreateTab 50 | }) 51 | 52 | this.extensions.browserActions.on('change', (actions) => updateBrowserActions(null, actions)) 53 | this.extensions.browserActions.on('change-tab', (tabId, actions) => updateBrowserActions(tabId, actions)) 54 | } 55 | 56 | async listActions (window) { 57 | const tabId = window ? window.web.id : null 58 | const actions = await this.extensions.browserActions.list(tabId) 59 | return actions.map((action) => { 60 | const onClick = (clickTabId) => this.extensions.browserActions.click(action.extensionId, clickTabId) 61 | return { ...action, onClick } 62 | }) 63 | } 64 | 65 | listContextMenuForEvent (webContents, event, params, additionalOpts = {}) { 66 | return this.extensions.contextMenus.getForEvent(webContents, event, params, additionalOpts) 67 | } 68 | 69 | get all () { 70 | return [...this.extensions.extensions.values()] 71 | } 72 | 73 | async get (id) { 74 | return this.extensions.get(id) 75 | } 76 | 77 | async byName (findName) { 78 | return this.all.find(({ name }) => name === findName) 79 | } 80 | 81 | async getBackgroundPageByName (name) { 82 | const extension = await this.byName(name) 83 | return this.extensions.getBackgroundPage(extension.id) 84 | } 85 | 86 | async loadRemote () { 87 | if (!remote) return 88 | for (const url of remote) { 89 | // TODO: Implement this for different protocols 90 | this.loadFromURL(url) 91 | } 92 | } 93 | 94 | async loadExtension (extensionPath) { 95 | const manifestPath = path.join(extensionPath, 'manifest.json') 96 | const manifestData = await fs.readFile(manifestPath, 'utf8') 97 | const { name } = JSON.parse(manifestData) 98 | const exists = await this.byName(name) 99 | if (exists) { 100 | return console.warn('Trying to load extension with existing name from', extensionPath, 'with existing extension:', exists) 101 | } 102 | return this.extensions.loadExtension(extensionPath) 103 | } 104 | 105 | async getManifestVersionOnDisk (name) { 106 | const manifestLocation = path.join(this.storageLocation, name, 'manifest.json') 107 | 108 | try { 109 | const manifestJSON = await readFile(manifestLocation) 110 | const { version } = JSON.parse(manifestJSON) 111 | 112 | return version 113 | } catch (e) { 114 | console.error(`Unable to load manifest for ${name}. ${e.stack}`) 115 | return '0.0.0' 116 | } 117 | } 118 | 119 | async extractIfNew (name, info) { 120 | const existingVersion = await this.getManifestVersionOnDisk(name) 121 | const isNew = semver.lt(existingVersion, info.version) 122 | if (!isNew) return false 123 | const zipLocation = path.join(this.builtinsLocation, `${name}.zip`) 124 | const extensionLocation = path.join(this.storageLocation, name) 125 | const decompressOptions = {} 126 | if (info.stripPrefix) { 127 | decompressOptions.map = (file) => { 128 | if (file.path.startsWith(info.stripPrefix)) { 129 | file.path = file.path.slice(info.stripPrefix.length) 130 | } 131 | return file 132 | } 133 | } 134 | await decompress(zipLocation, extensionLocation, decompressOptions) 135 | return true 136 | } 137 | 138 | async extractInternal () { 139 | // Read builtins list 140 | const builtinsListJSON = await readFile(this.builtinsListLocation, 'utf8') 141 | console.log({ builtinsListJSON }) 142 | const builtins = await JSON.parse(builtinsListJSON) 143 | 144 | const builtinsEntries = [...Object.entries(builtins)] 145 | // Extract them all in paralell 146 | await Promise.all(builtinsEntries.map(([name, info]) => { 147 | return this.extractIfNew(name, info) 148 | })) 149 | } 150 | 151 | async registerAll (extensionsFolder = this.storageLocation) { 152 | const rawNames = await readdir(extensionsFolder) 153 | const stats = await Promise.all( 154 | rawNames.map( 155 | (name) => fs.stat( 156 | path.join(extensionsFolder, name) 157 | ) 158 | ) 159 | ) 160 | 161 | const extensionFolders = rawNames.filter((name, index) => stats[index].isDirectory()) 162 | 163 | console.log('Loading extensions', extensionFolders) 164 | 165 | for (const folder of extensionFolders) { 166 | try { 167 | const extension = await this.loadExtension(path.join(extensionsFolder, folder)) 168 | // Must have been skipped 169 | if (!extension) continue 170 | console.log('Loaded extension', extension.manifest) 171 | 172 | if (process.env.NODE_ENV === 'debug') { 173 | // TODO: Open devtools? 174 | } 175 | } catch (e) { 176 | console.error('Error loading extension', folder, e) 177 | } 178 | } 179 | } 180 | } 181 | 182 | export function createExtensions (opts) { 183 | return new Extensions(opts) 184 | } 185 | -------------------------------------------------------------------------------- /app/history.js: -------------------------------------------------------------------------------- 1 | let getBackgroundPage = null 2 | let viewPage = null 3 | 4 | export function setGetBackgroundPage (backgroundPage) { 5 | getBackgroundPage = backgroundPage 6 | } 7 | 8 | export function setViewPage (page) { 9 | viewPage = page 10 | } 11 | 12 | export function getViewPage () { 13 | return viewPage 14 | } 15 | 16 | export async function * search (query = '', ...args) { 17 | const searchArgs = JSON.stringify([query, ...args]).slice(1, -1) 18 | const webContents = await getBackgroundPage() 19 | await webContents.executeJavaScript(` 20 | if(window.lastSearch?.return) { 21 | window.lastSearch?.return() 22 | } 23 | window.lastSearch = search(${searchArgs}); 24 | null 25 | `) 26 | 27 | while (true) { 28 | const { done, value } = await webContents 29 | .executeJavaScript('window.lastSearch.next()') 30 | 31 | if (done) break 32 | yield value 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /app/index.js: -------------------------------------------------------------------------------- 1 | import { app, BrowserWindow, session, Menu, Tray } from 'electron' 2 | import path, { sep } from 'node:path' 3 | import { fileURLToPath } from 'node:url' 4 | 5 | import * as protocols from './protocols/index.js' 6 | import { createActions } from './actions.js' 7 | import { registerMenu } from './menu.js' 8 | import { attachContextMenus } from './context-menus.js' 9 | import { WindowManager } from './window.js' 10 | import { createExtensions } from './extensions/index.js' 11 | import * as history from './history.js' 12 | import { version } from './version.js' 13 | import * as llm from './llm.js' 14 | import * as config from './config.js' 15 | 16 | const IS_DEBUG = process.env.NODE_ENV === 'debug' 17 | 18 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 19 | 20 | const WEB_PARTITION = 'persist:web-content' 21 | const LOGO_FILE = path.join(__dirname, './../build/icon-small.png') 22 | 23 | // Wait for two minutes of use before registering handlers 24 | const REGISTRATION_DELAY = 2 * 60 * 1000 25 | 26 | if (IS_DEBUG) { 27 | app.on('web-contents-created', (event, webContents) => { 28 | webContents.openDevTools() 29 | }) 30 | } 31 | 32 | if (!IS_DEBUG) { 33 | // We shouldn't freeze the process when there's an error. Just ignore it. 34 | process.on('uncaughtException', function (error) { 35 | console.error(error) 36 | }) 37 | } 38 | 39 | process.on('SIGINT', () => app.quit()) 40 | 41 | let extensions = null 42 | let windowManager = null 43 | 44 | // Enable text to speech. 45 | // Requires espeak on Linux 46 | app.commandLine.appendSwitch('enable-speech-dispatcher') 47 | 48 | // Smooth scrolling 49 | app.commandLine.appendSwitch('enable-smooth-scrolling') 50 | 51 | // Try to use the GPU for video decode on Pinephone 52 | app.commandLine.appendSwitch('enable-accelerated-video-decode') 53 | app.commandLine.appendSwitch('ignore-gpu-blacklist') 54 | 55 | // Experimental web platform features, such as the FileSystem API 56 | app.commandLine.appendSwitch('enable-experimental-web-platform-features') 57 | 58 | init() 59 | 60 | function init () { 61 | const gotTheLock = app.requestSingleInstanceLock() 62 | 63 | if (!gotTheLock) { 64 | app.quit() 65 | return 66 | } 67 | 68 | windowManager = new WindowManager({ 69 | onSearch: (...args) => history.search(...args), 70 | listActions: (...args) => extensions.listActions(...args) 71 | }) 72 | 73 | app.on('second-instance', (event, argv, workingDirectory) => { 74 | console.log('Got signal from second instance', [...argv]) 75 | const urls = urlsFromArgs(argv.slice(1), workingDirectory) 76 | urls.map((url) => windowManager.open({ url })) 77 | }) 78 | 79 | windowManager.on('open', window => { 80 | attachContextMenus({ window, createWindow, extensions }) 81 | if (!window.rawFrame) { 82 | const asBrowserView = BrowserWindow.fromBrowserView(window.view) 83 | asBrowserView.on('focus', () => { 84 | window.web.focus() 85 | }) 86 | } 87 | 88 | window.web.setWindowOpenHandler(({ url, features, disposition }) => { 89 | console.log('New window', url, disposition) 90 | if ((disposition === 'foreground-tab') || (disposition === 'background-tab')) { 91 | createWindow(url) 92 | 93 | return { action: 'deny' } 94 | } else { 95 | // TODO: Should we override more options here? 96 | return { action: 'allow' } 97 | } 98 | }) 99 | 100 | window.web.on('did-create-window', (window) => { 101 | attachContextMenus({ window, createWindow, extensions }) 102 | }) 103 | }) 104 | } 105 | 106 | // register privileged schemes 107 | protocols.registerPrivileges() 108 | 109 | // This method will be called when Electron has finished 110 | // initialization and is ready to create browser windows. 111 | // Some APIs can only be used after this event occurs. 112 | app.whenReady().then(onready).catch((e) => { 113 | console.error(e) 114 | process.exit(1) 115 | }) 116 | 117 | app.on('activate', () => { 118 | // On macOS it's common to re-create a window in the app when the 119 | // dock icon is clicked and there are no other windows open. 120 | if (BrowserWindow.getAllWindows().length === 0) { 121 | windowManager.open() 122 | } 123 | }) 124 | 125 | app.on('before-quit', () => { 126 | windowManager.saveOpened() 127 | windowManager.close() 128 | protocols.close() 129 | }) 130 | 131 | app.on('window-all-closed', () => {}) 132 | async function onready () { 133 | console.log('Building tray and context menu') 134 | const appIcon = new Tray(LOGO_FILE) 135 | const contextMenu = Menu.buildFromTemplate([ 136 | { label: 'New Window', click: () => createWindow() }, 137 | { 138 | label: 'Quit', 139 | role: 'quit' 140 | } 141 | ]) 142 | // Call this again for Linux because we modified the context menu 143 | appIcon.setContextMenu(contextMenu) 144 | appIcon.on('click', () => { 145 | createWindow() 146 | }) 147 | 148 | const webSession = session.fromPartition(WEB_PARTITION) 149 | 150 | llm.addPreloads(webSession) 151 | config.addPreloads(webSession) 152 | 153 | llm.setCreateWindow(createWindow) 154 | 155 | const electronSection = /Electron.+ /i 156 | const existingAgent = webSession.getUserAgent() 157 | const newAgent = existingAgent.replace(electronSection, `HybridDesktop/${version}`) 158 | 159 | webSession.setUserAgent(newAgent) 160 | session.defaultSession.setUserAgent(newAgent) 161 | 162 | const actions = createActions({ 163 | createWindow 164 | }) 165 | 166 | console.log('Setting up protocol handlers') 167 | 168 | await protocols.checkProtocols() 169 | 170 | await protocols.setupProtocols(webSession) 171 | 172 | console.log('Registering context menu') 173 | 174 | await registerMenu(actions) 175 | 176 | function updateBrowserActions (tabId, actions) { 177 | windowManager.reloadBrowserActions(tabId) 178 | } 179 | 180 | console.log('Initializing extensions') 181 | 182 | extensions = createExtensions({ session: webSession, createWindow, updateBrowserActions }) 183 | 184 | console.log('Extracting internal extensions') 185 | 186 | // Extract any internal extensions if there are updates 187 | await extensions.extractInternal() 188 | 189 | console.log('Registering extensions from disk') 190 | 191 | // Register all extensions in the extensions folder from disk 192 | await extensions.registerAll() 193 | 194 | const historyExtension = await extensions.byName('hybrid-history') 195 | 196 | // TODO: Better error handling when the extension doesn't exist? 197 | history.setGetBackgroundPage(() => { 198 | return extensions.getBackgroundPageByName('hybrid-history') 199 | }) 200 | 201 | history.setViewPage( 202 | new URL( 203 | historyExtension.manifest.options_page, 204 | historyExtension.url 205 | ).href 206 | ) 207 | 208 | console.log('Opening saved windows') 209 | 210 | const opened = await windowManager.openSaved() 211 | 212 | const urls = urlsFromArgs(process.argv.slice(1), process.cwd()) 213 | if (urls.length) { 214 | for (const url of urls) { 215 | windowManager.open({ url }) 216 | } 217 | } else if (!opened.length) windowManager.open() 218 | 219 | console.log('Waiting for windows to settle') 220 | 221 | await new Promise((resolve) => setTimeout(resolve, REGISTRATION_DELAY)) 222 | 223 | protocols.setAsDefaultProtocolClient() 224 | 225 | console.log('Initialization done') 226 | } 227 | 228 | function createWindow (url, options = {}) { 229 | console.log('createWindow', url, options) 230 | return windowManager.open({ url, ...options }) 231 | } 232 | 233 | function urlsFromArgs (argv, workingDir) { 234 | const rootURL = new URL(workingDir + sep, 'file://') 235 | return argv 236 | .filter((arg) => arg.includes('/')) 237 | .map((arg) => (arg.includes('://') ? arg : (new URL(arg, rootURL)).href)) 238 | } 239 | -------------------------------------------------------------------------------- /app/llm-preload.js: -------------------------------------------------------------------------------- 1 | const { contextBridge, ipcRenderer, webFrame } = require('electron') 2 | 3 | const iteratorMaps = new Map() 4 | let iteratorId = 1 5 | 6 | contextBridge.exposeInMainWorld('_hybridLLM', { 7 | chat, 8 | complete, 9 | chatStream, 10 | completeStream, 11 | iteratorNext, 12 | iteratorReturn, 13 | isSupported: () => ipcRenderer.invoke('llm-supported') 14 | }) 15 | 16 | webFrame.executeJavaScript(`(${setUpGlobal.toString()})()`) 17 | 18 | function setUpGlobal () { 19 | globalThis.llm = { 20 | chat, 21 | complete, 22 | isSupported: () => globalThis._agregoreLLM.isSupported() 23 | } 24 | 25 | function chat (args) { 26 | return { 27 | then (onResolve, onReject) { 28 | globalThis._agregoreLLM.chat(args).then(onResolve, onReject) 29 | }, 30 | async * [Symbol.asyncIterator] () { 31 | const id = await globalThis._agregoreLLM.chatStream(args) 32 | try { 33 | while (true) { 34 | const { done, value } = await globalThis._agregoreLLM.iteratorNext(id) 35 | if (done) break 36 | yield value 37 | } 38 | } finally { 39 | globalThis._agregoreLLM.iteratorReturn(id) 40 | } 41 | } 42 | } 43 | } 44 | 45 | function complete (prompt, args = {}) { 46 | return { 47 | then (onResolve, onReject) { 48 | globalThis._agregoreLLM.complete(prompt, args).then(onResolve, onReject) 49 | }, 50 | async * [Symbol.asyncIterator] () { 51 | const id = await globalThis._agregoreLLM.completeStream(prompt, args) 52 | try { 53 | while (true) { 54 | const { done, value } = await globalThis._agregoreLLM.iteratorNext(id) 55 | if (done) break 56 | yield value 57 | } 58 | } finally { 59 | globalThis._agregoreLLM.iteratorReturn(id) 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | async function chat (args) { 67 | return ipcRenderer.invoke('llm-chat', args) 68 | } 69 | 70 | async function complete (prompt, args = {}) { 71 | return ipcRenderer.invoke('llm-complete', { prompt, ...args }) 72 | } 73 | 74 | async function chatStream (args) { 75 | const { id } = await ipcRenderer.invoke('llm-chat-stream', args) 76 | const localId = iteratorId++ 77 | iteratorMaps.set(localId, id) 78 | return localId 79 | } 80 | 81 | async function completeStream (prompt, args = {}) { 82 | const { id } = await ipcRenderer.invoke('llm-complete-stream', { prompt, ...args }) 83 | const localId = iteratorId++ 84 | iteratorMaps.set(localId, id) 85 | return localId 86 | } 87 | 88 | async function iteratorNext (localId) { 89 | const id = iteratorMaps.get(localId) 90 | if (!id) throw new Error('Unknown iterator ID') 91 | return ipcRenderer.invoke('llm-iterate-next', { id }) 92 | } 93 | 94 | async function iteratorReturn (localId) { 95 | const id = iteratorMaps.get(localId) 96 | if (!id) throw new Error('Unknown iterator ID') 97 | iteratorMaps.delete(localId) 98 | return ipcRenderer.invoke('llm-iterate-return', { id }) 99 | } 100 | -------------------------------------------------------------------------------- /app/llm.js: -------------------------------------------------------------------------------- 1 | import config from './config.js' 2 | import { ipcMain, dialog } from 'electron' 3 | import path from 'node:path' 4 | import { fileURLToPath } from 'node:url' 5 | 6 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 7 | 8 | let isInitialized = false 9 | let createWindow = null 10 | // Completion Iterators, id to iterator 11 | const inProgress = new Map() 12 | let streamId = 1 13 | 14 | export function setCreateWindow (create) { 15 | createWindow = create 16 | } 17 | 18 | ipcMain.handle('llm-supported', async (event) => { 19 | if (!config.llm.enabled) return false 20 | return isSupported() 21 | }) 22 | 23 | ipcMain.handle('llm-chat', async (event, args) => { 24 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 25 | return chat(args) 26 | }) 27 | 28 | ipcMain.handle('llm-complete', async (event, args) => { 29 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 30 | return complete(args) 31 | }) 32 | 33 | ipcMain.handle('llm-chat-stream', async (event, args) => { 34 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 35 | const id = streamId++ 36 | const iterator = chatStream(args) 37 | inProgress.set(id, iterator) 38 | return { id } 39 | }) 40 | 41 | ipcMain.handle('llm-complete-stream', async (event, args) => { 42 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 43 | const id = streamId++ 44 | const iterator = completeStream(args) 45 | inProgress.set(id, iterator) 46 | return { id } 47 | }) 48 | 49 | ipcMain.handle('llm-iterate-next', async (event, args) => { 50 | const { id } = args 51 | if (!inProgress.has(id)) throw new Error('Unknown Iterator') 52 | const iterator = inProgress.get(id) 53 | const { done, value } = await iterator.next() 54 | if (done) inProgress.delete(id) 55 | return { done, value } 56 | }) 57 | 58 | ipcMain.handle('llm-iterate-return', async (event, args) => { 59 | const { id } = args 60 | if (!inProgress.has(id)) return 61 | const iterator = inProgress.get(id) 62 | await iterator.return() 63 | }) 64 | 65 | export async function isSupported () { 66 | if (!config.llm.enabled) return false 67 | const has = await hasModel() 68 | if (has) return true 69 | return (config.llm.apiKey === 'ollama') 70 | } 71 | 72 | export function addPreloads (session) { 73 | const preloadPath = path.join(__dirname, 'llm-preload.js') 74 | const preloads = session.getPreloads() 75 | preloads.push(preloadPath) 76 | session.setPreloads(preloads) 77 | } 78 | 79 | export async function init () { 80 | if (!config.llm.enabled) throw new Error('LLM API is disabled') 81 | if (isInitialized) return 82 | // TODO: prompt for download 83 | if (config.llm.apiKey === 'ollama') { 84 | try { 85 | await listModels() 86 | } catch { 87 | await showNeedsOllama() 88 | throw new Error('LLM API needs system service install') 89 | } 90 | 91 | const has = await hasModel() 92 | if (!has) { 93 | await confirmPull() 94 | await pullModel() 95 | await notifyPullDone() 96 | } 97 | } 98 | isInitialized = true 99 | } 100 | 101 | async function listModels () { 102 | const { data } = await get('./models', 'Unable to list models') 103 | return data 104 | } 105 | 106 | async function showNeedsOllama () { 107 | const { response, checkboxChecked } = await dialog.showMessageBox({ 108 | title: 'Set up Ollama', 109 | message: 'Agregore needs a local install of Ollama in order to use AI features. Since it has not been detected, would you like help instaaling it, or would yopu like to go configure the settings to use another endpoint?', 110 | buttons: ['Show Help', 'Configure', 'Cancel'], 111 | defaultId: 0, 112 | cancelId: 2, 113 | checkboxLabel: 'Remember this choice' 114 | }) 115 | 116 | if (response === 2) { 117 | if (checkboxChecked) { 118 | config.llm.enabled = false 119 | } 120 | throw new Error('Cannot use LLM, user denied help') 121 | } 122 | if (response === 0) { 123 | await createWindow('hyper://agregore.mauve.moe/docs/ai#setting-up-ollama') 124 | } 125 | if (response === 1) { 126 | await createWindow('agregore://settings#llm') 127 | } 128 | } 129 | 130 | async function confirmPull () { 131 | const { response, checkboxChecked } = await dialog.showMessageBox({ 132 | title: 'Download AI Model?', 133 | message: 'Hybrid wants to download a large language model to allow websites to use AI features. This can take a few minutes and can take several gigabytes of internet. Do you want to allow this?', 134 | buttons: ['Yes', 'No'], 135 | defaultId: 0, 136 | cancelId: 1, 137 | checkboxLabel: 'Remember this choice' 138 | }) 139 | 140 | if (response === 1) { 141 | if (checkboxChecked) { 142 | config.llm.enabled = false 143 | } 144 | throw new Error('Cannot use LLM, user denied download') 145 | } 146 | } 147 | 148 | async function notifyPullDone () { 149 | await dialog.showMessageBox({ 150 | title: 'AI Model Downloaded', 151 | message: `Hybrid has finished downloading the large lanfguage model. You can clear it by running 'ollama rm ${model}'` 152 | }) 153 | } 154 | 155 | async function pullModel () { 156 | await post('/api/pull', { 157 | name: config.llm.model 158 | }, `Unable to pull model ${config.llm.model}`, false) 159 | } 160 | 161 | async function hasModel () { 162 | try { 163 | const models = await listModels() 164 | 165 | return !!models.find(({ id }) => id === config.llm.model) 166 | } catch (e) { 167 | console.error(e.stack) 168 | return false 169 | } 170 | } 171 | 172 | export async function chat ({ 173 | messages = [], 174 | temperature, 175 | maxTokens, 176 | stop 177 | }) { 178 | await init() 179 | const { choices } = await post('./chat/completions', { 180 | messages, 181 | model: config.llm.model, 182 | temperature, 183 | max_tokens: maxTokens, 184 | stop 185 | }, 'Unable to generate completion') 186 | 187 | return choices[0].message 188 | } 189 | 190 | export async function complete ({ 191 | prompt, 192 | temperature, 193 | maxTokens, 194 | stop 195 | }) { 196 | await init() 197 | const { choices } = await post('./completions', { 198 | prompt, 199 | model: config.llm.model, 200 | temperature, 201 | max_tokens: maxTokens, 202 | stop 203 | }, 'Unable to generate completion') 204 | 205 | return choices[0].text 206 | } 207 | 208 | export async function * chatStream ({ 209 | messages = [], 210 | temperature, 211 | maxTokens, 212 | stop 213 | } = {}) { 214 | await init() 215 | for await (const { choices } of stream('./chat/completions', { 216 | messages, 217 | model: config.llm.model, 218 | temperature, 219 | max_tokens: maxTokens, 220 | stop 221 | }, 'Unable to generate completion')) { 222 | yield choices[0].delta 223 | } 224 | } 225 | 226 | export async function * completeStream ({ 227 | prompt, 228 | temperature, 229 | maxTokens, 230 | stop 231 | }) { 232 | await init() 233 | 234 | for await (const { choices } of stream('./completions', { 235 | prompt, 236 | model: config.llm.model, 237 | temperature, 238 | max_tokens: maxTokens, 239 | stop 240 | }, 'Unable to generate completion')) { 241 | yield choices[0].text 242 | } 243 | } 244 | 245 | async function * stream (path, data = {}, errorMessage = 'Unable to stream') { 246 | const url = new URL(path, config.llm.baseURL).href 247 | if (!data.stream) data.stream = true 248 | 249 | const response = await fetch(url, { 250 | method: 'POST', 251 | headers: { 252 | 'Content-Type': 'application/json; charset=utf8', 253 | Authorization: `Bearer ${config.llm.apiKey}` 254 | }, 255 | body: JSON.stringify(data) 256 | }) 257 | 258 | if (!response.ok) { 259 | throw new Error(`${errorMessage} ${await response.text()}`) 260 | } 261 | 262 | const decoder = new TextDecoder('utf-8') 263 | let remaining = '' 264 | 265 | const reader = response.body.getReader() 266 | 267 | for await (const chunk of iterate(reader)) { 268 | remaining += decoder.decode(chunk) 269 | const lines = remaining.split('data: ') 270 | remaining = lines.splice(-1)[0] 271 | 272 | yield * lines 273 | .filter((line) => !!line) 274 | .map((line) => JSON.parse(line)) 275 | } 276 | } 277 | 278 | async function get (path, errorMessage, parseBody = true) { 279 | const url = new URL(path, config.llm.baseURL).href 280 | 281 | const response = await fetch(url, { 282 | method: 'GET', 283 | headers: { 284 | Authorization: `Bearer ${config.llm.apiKey}` 285 | } 286 | }) 287 | 288 | if (!response.ok) { 289 | throw new Error(`${errorMessage} ${await response.text()}`) 290 | } 291 | 292 | if (parseBody) { 293 | return await response.json() 294 | } else { 295 | return await response.text() 296 | } 297 | } 298 | 299 | async function post (path, data, errorMessage, shouldParse = true) { 300 | const url = new URL(path, config.llm.baseURL).href 301 | 302 | const response = await fetch(url, { 303 | method: 'POST', 304 | headers: { 305 | 'Content-Type': 'application/json; charset=utf8', 306 | Authorization: `Bearer ${config.llm.apiKey}` 307 | }, 308 | body: JSON.stringify(data) 309 | }) 310 | 311 | if (!response.ok) { 312 | throw new Error(`${errorMessage} ${await response.text()}`) 313 | } 314 | 315 | if (shouldParse) { 316 | return await response.json() 317 | } 318 | return await response.text() 319 | } 320 | 321 | async function * iterate (reader) { 322 | while (true) { 323 | const { done, value } = await reader.read() 324 | if (done) return 325 | yield value 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /app/menu.js: -------------------------------------------------------------------------------- 1 | import { Menu, app } from 'electron' 2 | 3 | const isMac = process.platform === 'darwin' 4 | 5 | export function registerMenu (actions) { 6 | const { 7 | OpenDevTools, 8 | ViewHistory, 9 | NewWindow, 10 | Forward, 11 | Back, 12 | FocusURLBar, 13 | FindInPage, 14 | Reload, 15 | HardReload, 16 | LearnMore, 17 | SetAsDefault, 18 | SetAsDefaultMagnet, 19 | OpenExtensionFolder, 20 | OpenDataFolder, 21 | EditConfigFile, 22 | OpenConfigFile, 23 | CreateBookmark 24 | } = actions 25 | 26 | const template = [ 27 | // { role: 'appMenu' } 28 | ...(isMac 29 | ? [{ 30 | label: app.name, 31 | submenu: [ 32 | { role: 'about' }, 33 | { type: 'separator' }, 34 | { role: 'services' }, 35 | { type: 'separator' }, 36 | { role: 'hide' }, 37 | { role: 'hideothers' }, 38 | { role: 'unhide' }, 39 | { type: 'separator' }, 40 | { role: 'quit' } 41 | ] 42 | }] 43 | : []), 44 | // { role: 'fileMenu' } 45 | { 46 | label: 'File', 47 | submenu: [ 48 | isMac ? { role: 'close' } : { role: 'quit' }, 49 | OpenDevTools, 50 | ViewHistory, 51 | NewWindow 52 | ] 53 | }, 54 | // { role: 'editMenu' } 55 | { 56 | label: 'Edit', 57 | submenu: [ 58 | { role: 'undo' }, 59 | { role: 'redo' }, 60 | { type: 'separator' }, 61 | { role: 'cut' }, 62 | { role: 'copy' }, 63 | { role: 'paste' }, 64 | ...(isMac 65 | ? [ 66 | { role: 'pasteAndMatchStyle' }, 67 | { role: 'delete' }, 68 | { role: 'selectAll' }, 69 | { type: 'separator' }, 70 | { 71 | label: 'Speech', 72 | submenu: [ 73 | { role: 'startspeaking' }, 74 | { role: 'stopspeaking' } 75 | ] 76 | } 77 | ] 78 | : [ 79 | { role: 'delete' }, 80 | { type: 'separator' }, 81 | { role: 'selectAll' } 82 | ]) 83 | ] 84 | }, 85 | // { role: 'viewMenu' } 86 | { 87 | label: 'View', 88 | submenu: [ 89 | Forward, 90 | Back, 91 | FocusURLBar, 92 | FindInPage, 93 | { type: 'separator' }, 94 | { role: 'resetzoom' }, 95 | { role: 'zoomin' }, 96 | { role: 'zoomout' }, 97 | { type: 'separator' }, 98 | { role: 'togglefullscreen' } 99 | ] 100 | }, 101 | // { role: 'windowMenu' } 102 | { 103 | label: 'Window', 104 | submenu: [ 105 | Reload, 106 | HardReload, 107 | ...(isMac 108 | ? [] 109 | : [ 110 | CreateBookmark 111 | ]), 112 | { role: 'minimize' }, 113 | { role: 'zoom' }, 114 | ...(isMac 115 | ? [ 116 | { type: 'separator' }, 117 | { role: 'front' }, 118 | { type: 'separator' }, 119 | { role: 'window' } 120 | ] 121 | : [ 122 | { role: 'close' } 123 | ]) 124 | ] 125 | }, 126 | { 127 | role: 'help', 128 | submenu: [ 129 | LearnMore, 130 | OpenExtensionFolder, 131 | OpenDataFolder, 132 | EditConfigFile, 133 | OpenConfigFile, 134 | SetAsDefault, 135 | SetAsDefaultMagnet 136 | ] 137 | } 138 | ] 139 | 140 | const menu = Menu.buildFromTemplate(template) 141 | Menu.setApplicationMenu(menu) 142 | } 143 | -------------------------------------------------------------------------------- /app/pages/404.html: -------------------------------------------------------------------------------- 1 | 2 | Page Not Found 3 | 4 | 9 | 10 |

Page No Found

11 | -------------------------------------------------------------------------------- /app/pages/about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Hybrid Browser - About 8 | 9 | 10 |
11 |

About

12 |
13 |
14 |

Hybrid

15 |

Devs

16 |

ducksandgoats

17 |

resession

18 |
19 | 20 | -------------------------------------------------------------------------------- /app/pages/bt.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/bt.ico -------------------------------------------------------------------------------- /app/pages/error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Error 8 | 9 | 10 |
11 |

Error

12 |

Page Not Found

13 |
14 | 15 | -------------------------------------------------------------------------------- /app/pages/hyper.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/hyper.ico -------------------------------------------------------------------------------- /app/pages/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 10 | 13 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /app/pages/iip.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Iip 10 | 11 | 12 | 13 |
14 |

15 | loading 16 |

17 |
18 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /app/pages/iip.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/iip.ico -------------------------------------------------------------------------------- /app/pages/ipfs.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/ipfs.ico -------------------------------------------------------------------------------- /app/pages/oui.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Oui 9 | 10 | 11 |
12 |

13 | loading 14 |

15 |
16 | 35 | 36 | -------------------------------------------------------------------------------- /app/pages/oui.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/oui.ico -------------------------------------------------------------------------------- /app/pages/settings.html: -------------------------------------------------------------------------------- 1 | 2 | Browser Settings 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 |

Settings

15 |
16 |
17 | 18 | 19 |
20 |
21 | Theme 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 | Keyboard Shortcuts 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 |
46 | llm 47 | 48 | 49 | 50 | 51 |
52 |
53 | 54 |
55 |
56 | 57 | -------------------------------------------------------------------------------- /app/pages/theme/example.md: -------------------------------------------------------------------------------- 1 | # Theme example page 2 | 3 | ## Text 4 | 5 | > Quote 6 | > 7 | > Text 8 | 9 | --- 10 | 11 | `single line code` 12 | 13 | https://hybrid.mauve.moe 14 | 15 | [Custom link text](https://hybrid.mauve.moe) 16 | 17 | 18 | ## Forms 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 31 | 32 | 33 | 34 | ## Media 35 | 36 | ### Image 37 | 38 | ![HYBRID Logo](hybrid://icon.svg) 39 | 40 | ### Video 41 | 42 | 43 | 44 | ### Audio 45 | 46 | 47 | 48 | ### Iframe 49 | 50 | 51 | -------------------------------------------------------------------------------- /app/pages/theme/highlight.css: -------------------------------------------------------------------------------- 1 | /* 2 | Monokai style - ported by Luigi Maselli - http://grigio.org 3 | */ 4 | 5 | .hljs { 6 | display: block; 7 | overflow-x: auto; 8 | padding: 0.5em; 9 | background: #272822; color: #ddd; 10 | } 11 | 12 | .hljs-tag, 13 | .hljs-keyword, 14 | .hljs-selector-tag, 15 | .hljs-literal, 16 | .hljs-strong, 17 | .hljs-name { 18 | color: #f92672; 19 | } 20 | 21 | .hljs-code { 22 | color: #66d9ef; 23 | } 24 | 25 | .hljs-class .hljs-title { 26 | color: white; 27 | } 28 | 29 | .hljs-attribute, 30 | .hljs-symbol, 31 | .hljs-regexp, 32 | .hljs-link { 33 | color: #bf79db; 34 | } 35 | 36 | .hljs-string, 37 | .hljs-bullet, 38 | .hljs-subst, 39 | .hljs-title, 40 | .hljs-section, 41 | .hljs-emphasis, 42 | .hljs-type, 43 | .hljs-built_in, 44 | .hljs-builtin-name, 45 | .hljs-selector-attr, 46 | .hljs-selector-pseudo, 47 | .hljs-addition, 48 | .hljs-variable, 49 | .hljs-template-tag, 50 | .hljs-template-variable { 51 | color: #a6e22e; 52 | } 53 | 54 | .hljs-comment, 55 | .hljs-quote, 56 | .hljs-deletion, 57 | .hljs-meta { 58 | color: #75715e; 59 | } 60 | 61 | .hljs-keyword, 62 | .hljs-selector-tag, 63 | .hljs-literal, 64 | .hljs-doctag, 65 | .hljs-title, 66 | .hljs-section, 67 | .hljs-type, 68 | .hljs-selector-id { 69 | font-weight: bold; 70 | } 71 | -------------------------------------------------------------------------------- /app/pages/theme/style.css: -------------------------------------------------------------------------------- 1 | @charset "utf-8"; 2 | @import url("hybrid://theme/vars.css"); 3 | 4 | * { 5 | box-sizing: border-box; 6 | } 7 | 8 | html { 9 | background: var(--hy-theme-background); 10 | color: var(--hy-theme-text); 11 | font-family: var(--hy-theme-font-family); 12 | font-size: inherit; 13 | } 14 | 15 | body { 16 | padding: 0px; 17 | margin: 0px; 18 | } 19 | 20 | body > p, 21 | body > a, 22 | body > pre, 23 | body > li, 24 | body > ul, 25 | body > table, 26 | body > img, 27 | body > form, 28 | body > iframe, 29 | body > video, 30 | body > audio, 31 | body > h1, 32 | body > h2, 33 | body > h3, 34 | body > h4, 35 | body > h5, 36 | body > h6 { 37 | max-width: var(--hy-theme-max-width); 38 | margin-left: auto; 39 | margin-right: auto; 40 | display: block; 41 | } 42 | 43 | input, button, textarea, select, select *, option { 44 | color: inherit; 45 | font-family: inherit; 46 | font-size: inherit; 47 | background: none; 48 | padding:0.25em; 49 | border-radius: 0.25em; 50 | } 51 | 52 | textarea { 53 | width : 100%; 54 | resize: vertical; 55 | margin: 1em auto; 56 | } 57 | 58 | select option { 59 | background: var(--hy-theme-background); 60 | color: var(--hy-theme-text); 61 | } 62 | 63 | input, button, textarea, select, select *, video { 64 | border: 1px solid var(--hy-theme-primary); 65 | } 66 | 67 | *::selection, option:hover { 68 | background: var(--hy-theme-primary); 69 | color: var(--hy-theme-text); 70 | } 71 | 72 | a { 73 | color: var(--hy-theme-secondary); 74 | text-decoration: underline; 75 | text-decoration-color: var(--hy-theme-primary); 76 | } 77 | 78 | a:hover { 79 | color: var(--hy-theme-background); 80 | background-color: var(--hy-theme-secondary); 81 | text-decoration: none; 82 | } 83 | 84 | a:visited { 85 | color: var(--hy-theme-primary); 86 | } 87 | 88 | img, video, svg, object, audio { 89 | width: 80%; 90 | display: block; 91 | margin: 1em auto; 92 | } 93 | 94 | iframe { 95 | display: block; 96 | margin: 1em auto; 97 | width: 100%; 98 | border: none; 99 | } 100 | 101 | pre { 102 | background: var(--hy-theme-primary); 103 | } 104 | 105 | code { 106 | background: var(--hy-theme-primary); 107 | font-weight: bold; 108 | padding: 0.25em; 109 | } 110 | 111 | blockquote { 112 | border-left: 1px solid var(--hy-theme-primary); 113 | margin: 1em; 114 | padding-left: 1em; 115 | } 116 | 117 | blockquote > *::before { 118 | content: "> "; 119 | color: var(--hy-theme-secondary); 120 | } 121 | 122 | pre > code { 123 | display: block; 124 | padding: 0.5em; 125 | } 126 | 127 | br { 128 | display: none; 129 | } 130 | 131 | li { 132 | list-style-type: " ⟐ "; 133 | } 134 | 135 | hr { 136 | border-color: var(--hy-theme-primary); 137 | } 138 | 139 | *:focus { 140 | outline: 2px solid var(--hy-theme-secondary); 141 | } 142 | 143 | h1 { 144 | text-align: center; 145 | } 146 | 147 | /* Reset style for anchors added to headers */ 148 | h2 a, h3 a, h4 a { 149 | color: var(--hy-theme-text); 150 | text-decoration: none; 151 | } 152 | 153 | h1 a { 154 | color: var(--hy-theme-primary); 155 | text-decoration: none; 156 | } 157 | 158 | h1:hover::after, h2:hover::after, h3:hover::after, h4:hover::after { 159 | text-decoration: none !important; 160 | } 161 | h2::before { 162 | content: "## "; 163 | color: var(--hy-theme-secondary) 164 | } 165 | h3::before { 166 | content: "### "; 167 | color: var(--hy-theme-secondary) 168 | } 169 | h4::before { 170 | content: "#### "; 171 | color: var(--hy-theme-secondary) 172 | } 173 | 174 | *::-webkit-scrollbar { 175 | width: 1em; 176 | } 177 | 178 | *::-webkit-scrollbar-corner { 179 | background: rgba(0,0,0,0); 180 | } 181 | 182 | *::-webkit-scrollbar-thumb { 183 | background-color: var(--hy-theme-primary); 184 | border: 2px solid transparent; 185 | background-clip: content-box; 186 | } 187 | *::-webkit-scrollbar-track { 188 | background-color: rgba(0,0,0,0); 189 | } 190 | 191 | 192 | audio::-webkit-media-controls-mute-button, 193 | audio::-webkit-media-controls-play-button, 194 | audio::-webkit-media-controls-timeline-container, 195 | audio::-webkit-media-controls-current-time-display, 196 | audio::-webkit-media-controls-time-remaining-display, 197 | audio::-webkit-media-controls-timeline, 198 | audio::-webkit-media-controls-volume-slider-container, 199 | audio::-webkit-media-controls-volume-slider, 200 | audio::-webkit-media-controls-seek-back-button, 201 | audio::-webkit-media-controls-seek-forward-button, 202 | audio::-webkit-media-controls-fullscreen-button, 203 | audio::-webkit-media-controls-rewind-button, 204 | audio::-webkit-media-controls-return-to-realtime-button, 205 | audio::-webkit-media-controls-toggle-closed-captions-button 206 | { 207 | border: none; 208 | border-radius: none; 209 | } 210 | 211 | audio::-webkit-media-controls-timeline 212 | { 213 | background: var(--hy-theme-primary); 214 | margin: 0px 1em; 215 | border-radius: none; 216 | } 217 | 218 | audio::-webkit-media-controls-panel { 219 | background: var(--hy-theme-background); 220 | color: var(--hy-theme-text); 221 | font-family: var(--hy-theme-font-family); 222 | font-size: inherit; 223 | border-radius: none; 224 | } 225 | -------------------------------------------------------------------------------- /app/pages/tor.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Tor 10 | 11 | 12 | 13 |
14 |

15 | loading 16 |

17 |
18 | 38 | 39 | -------------------------------------------------------------------------------- /app/pages/tor.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/app/pages/tor.ico -------------------------------------------------------------------------------- /app/pages/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | Hybrid Browser - Welcome 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 66 | 67 | 68 | 69 |

70 | Hybrid 71 |

72 | 73 |

74 | 75 | About 76 | 77 |

78 | 79 |

80 | 81 | OUI 82 | 83 | 84 | BT 85 | 86 | 87 | IPFS 88 | 89 | 90 | HYPER 91 | 92 | 93 | TOR 94 | 95 | 96 | IIP 97 | 98 |

99 |
100 |

101 | 102 | oui:// 103 | 104 | 105 | bt:// 106 | 107 | 108 | ipfs:// 109 | 110 | 111 | hyper:// 112 | 113 | 114 | tor:// 115 | 116 | 117 | iip:// 118 | 119 |

120 | 121 | 124 | 125 | -------------------------------------------------------------------------------- /app/protocols/browser-protocol.js: -------------------------------------------------------------------------------- 1 | import path from 'path' 2 | import { Readable } from 'node:stream' 3 | import { fileURLToPath } from 'node:url' 4 | import mime from 'mime' 5 | import ScopedFS from 'scoped-fs' 6 | 7 | import { version, dependencies as packageDependencies } from '../version.js' 8 | import Config from '../config.js' 9 | const { theme } = Config 10 | 11 | const CHECK_PATHS = [ 12 | (path) => path, 13 | (path) => path + '.html', 14 | (path) => path + '.md' 15 | ] 16 | 17 | const pagesURL = new URL('../pages', import.meta.url) 18 | const pagesPath = fileURLToPath(pagesURL) 19 | 20 | const fs = new ScopedFS(pagesPath) 21 | 22 | async function resolveFile(path) { 23 | for (const toTry of CHECK_PATHS) { 24 | const tryPath = toTry(path) 25 | if (await exists(tryPath)) { 26 | return tryPath 27 | } 28 | } 29 | throw new Error('Not Found') 30 | } 31 | 32 | function exists (path) { 33 | return new Promise((resolve, reject) => { 34 | fs.stat(path, (err, stat) => { 35 | if (err) { 36 | if (err.code === 'ENOENT') resolve(false) 37 | else reject(err) 38 | } else resolve(stat.isFile()) 39 | }) 40 | }) 41 | } 42 | 43 | function intoStream (data) { 44 | return new Readable({ 45 | read () { 46 | this.push(data) 47 | this.push(null) 48 | } 49 | }) 50 | } 51 | 52 | // function useHead(head){ 53 | // const test = {} 54 | // for(const pair of head.entries()){ 55 | // test[pair[0]] = pair[1] 56 | // } 57 | // return test 58 | // } 59 | 60 | export default async function(req){ 61 | try { 62 | const { url, headers: reqHeaders } = req 63 | 64 | const parsed = new URL(url) 65 | const { pathname, hostname, searchParams } = parsed 66 | const toResolve = path.join(hostname, pathname) 67 | if (hostname === 'info') { 68 | const statusCode = 200 69 | 70 | const packagesToRender = [ 71 | 'log-fetch', 72 | 'chunk-fetch', 73 | 'list-fetch', 74 | 'onion-fetch' 75 | ] 76 | 77 | const dependencies = {} 78 | for (const name of packagesToRender) { 79 | dependencies[name] = packageDependencies[name] 80 | } 81 | 82 | const aboutInfo = { 83 | version, 84 | dependencies 85 | } 86 | 87 | const data = intoStream(JSON.stringify(aboutInfo, null, '\t')) 88 | 89 | const headers = { 90 | 'Access-Control-Allow-Origin': '*', 91 | 'Allow-CSP-From': '*', 92 | 'Content-Type': 'application/json' 93 | } 94 | 95 | return new Response(data, {status: statusCode, headers}) 96 | // return 97 | } else if ((hostname === 'theme') && (pathname === '/vars.css')) { 98 | const statusCode = 200 99 | 100 | const themes = Object 101 | .keys(theme) 102 | .map((name) => ` --hy-theme-${name}: ${theme[name]};`) 103 | .join('\n') 104 | 105 | const data = intoStream(` 106 | :root { 107 | --hy-color-blue: #0000FF; 108 | --hy-color-black: #000000; 109 | --hy-color-white: #FFFFFF; 110 | --hy-color-red: #FF0000; 111 | } 112 | 113 | :root { 114 | ${themes} 115 | } 116 | `) 117 | 118 | const headers = { 119 | 'Access-Control-Allow-Origin': '*', 120 | 'Allow-CSP-From': '*', 121 | 'Cache-Control': 'no-cache', 122 | 'Content-Type': 'text/css' 123 | } 124 | 125 | return new Response(data, {status: statusCode, headers}) 126 | // return 127 | } else { 128 | const resolvedPath = await resolveFile(toResolve) 129 | const statusCode = 200 130 | 131 | const contentType = mime.getType(resolvedPath) || 'text/plain' 132 | 133 | const data = fs.createReadStream(resolvedPath) 134 | 135 | const headers = { 136 | 'Access-Control-Allow-Origin': '*', 137 | 'Allow-CSP-From': 'hybrid://welcome', 138 | 'Cache-Control': 'no-cache', 139 | 'Content-Type': contentType 140 | } 141 | 142 | return new Response(data, {status: statusCode, headers}) 143 | } 144 | } catch { 145 | const statusCode = 400 146 | 147 | const data = fs.createReadStream('error.html') 148 | 149 | const headers = { 150 | 'Access-Control-Allow-Origin': '*', 151 | 'Allow-CSP-From': '*', 152 | 'Cache-Control': 'no-cache', 153 | 'Content-Type': 'text/html' 154 | } 155 | 156 | return new Response(data, {status: statusCode, headers}) 157 | } 158 | } -------------------------------------------------------------------------------- /app/protocols/gemini-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeGemini(opts = {}) { 2 | const geminiReq = await import('@derhuerst/gemini/client.js') 3 | const { Readable } = await import('stream') 4 | 5 | const DEFAULT_OPTS = { 6 | timeout: 30000 7 | } 8 | 9 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 10 | const useTimeOut = finalOpts.timeout 11 | 12 | function intoStream (data) { 13 | return new Readable({ 14 | read () { 15 | this.push(data) 16 | this.push(null) 17 | } 18 | }) 19 | } 20 | 21 | async function makeQuery(link, ext) { 22 | return await new Promise((resolve, reject) => { 23 | geminiReq(link, ext, (err, res) => { 24 | if (err) { 25 | reject(err) 26 | } else { 27 | const { statusCode, statusMessage: statusText, meta } = res 28 | 29 | const isOK = (statusCode >= 10) && (statusCode < 300) 30 | 31 | const headers = isOK ? { 'Content-Type': meta } : {} 32 | 33 | const data = isOK ? res : intoStream(meta) 34 | 35 | resolve({ 36 | status: statusCode * 10, 37 | statusText, 38 | headers, 39 | body: data 40 | }) 41 | } 42 | }) 43 | }) 44 | } 45 | 46 | return async function useThefetch(session){ 47 | // const session = new Request(url, opt) 48 | const toRequest = new URL(url, session.referrer) 49 | const reqHeaders = new Headers(session.headers) 50 | const searchParams = toRequest.searchParams 51 | 52 | if (!toRequest.hostname.startsWith('gemini.')) { 53 | toRequest.hostname = 'gemini.' + toRequest.hostname 54 | } 55 | 56 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 57 | 58 | const mainExt = reqHeaders.has('x-ext') || searchParams.has('x-ext') ? JSON.parse(reqHeaders.get('x-ext') || searchParams.get('x-ext')) : {} 59 | 60 | const tempRes = mainTimeout ? 61 | await Promise.race([ 62 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 63 | makeQuery(toRequest.href, mainExt) 64 | ]) : 65 | await makeQuery(toRequest.href, mainExt) 66 | 67 | return new Response(tempRes.body, {...tempRes}) 68 | } 69 | } -------------------------------------------------------------------------------- /app/protocols/gopher-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeGopher(opts = {}) { 2 | const Gopher = await import('gopher-lib') 3 | const DEFAULT_OPTS = {timeout: 30000} 4 | const useTimeOut = opts.timeout || DEFAULT_OPTS.timeout 5 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 6 | delete finalOpts.timeout 7 | const gopher = new Gopher.Client(finalOpts) 8 | 9 | async function makeQuery(link) { 10 | const sendText = await new Promise((resolve, reject) => { 11 | gopher.get(link, (err, reply)=>{ 12 | if(err) { 13 | reject(err); 14 | } else { 15 | resolve(reply.text || '') 16 | } 17 | }); 18 | }) 19 | return {status: 200, headers: {'Content-Type': 'text/plain'}, body: sendText} 20 | } 21 | 22 | return async function useThefetch(session){ 23 | // const session = new Request(url, opt) 24 | const gopherReq = new URL(session.url, session.referrer) 25 | const reqHeaders = new Headers(session.headers) 26 | const searchParams = gopherReq.searchParams 27 | 28 | if(!gopherReq.hostname.startsWith('gopher.')){ 29 | gopherReq.hostname = 'gopher.' + gopherReq.hostname 30 | } 31 | 32 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 33 | 34 | const tempRes = mainTimeout ? 35 | await Promise.race([ 36 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 37 | makeQuery(gopherReq.href) 38 | ]) : 39 | await makeQuery(gopherReq.href) 40 | 41 | return new Response(tempRes.body, {...tempRes}) 42 | } 43 | } -------------------------------------------------------------------------------- /app/protocols/hhttp-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeHTTP(opts){ 2 | const { default: nodeFetch } = await import('node-fetch') 3 | const DEFAULT_OPTS = {timeout: 30000} 4 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 5 | const useTimeOut = finalOpts.timeout 6 | 7 | return async function rawFetch(req) { 8 | const urls = req.url.replace('hhttp', 'http') 9 | delete req.url 10 | const session = new Request(urls, req) 11 | const searchParams = new URL(session.url).searchParams 12 | const reqHeaders = session.headers 13 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 14 | const tempRes = mainTimeout ? 15 | await Promise.race([ 16 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 17 | nodeFetch(session.url, session) 18 | ]) : 19 | await nodeFetch(session.url, session) 20 | return new Response(tempRes.body, {...tempRes}) 21 | } 22 | } -------------------------------------------------------------------------------- /app/protocols/iip-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeGarlic (opts = {}) { 2 | const { default: nodeFetch } = await import('node-fetch') 3 | const {default: detect} = await import('detect-port') 4 | const {SocksProxyAgent} = await import('socks-proxy-agent') 5 | const {HttpProxyAgent} = await import('http-proxy-agent') 6 | const finalOpts = { timeout: 30000, port: 4444, scheme: 'http:', hostname: 'localhost', ...opts } 7 | const mainPort = finalOpts.port 8 | const useTimeOut = finalOpts.timeout 9 | const httpOrSocks = finalOpts.scheme 10 | const mainHost = finalOpts.hostname 11 | const mainAgent = httpOrSocks === 'http:' || httpOrSocks === 'https:' ? new HttpProxyAgent(`${httpOrSocks}//${mainHost}:${mainPort}`) : new SocksProxyAgent(`${httpOrSocks}//${mainHost}:${mainPort}`) 12 | 13 | function useAgent(_parsedURL) { 14 | if (_parsedURL.protocol === 'http:' || _parsedURL.protocol === 'https:') { 15 | return mainAgent 16 | } else { 17 | throw new Error('protocol is not valid') 18 | } 19 | } 20 | 21 | return async function handleIip(req) { 22 | try { 23 | const urls = req.url.replace('iip', 'http') 24 | delete req.url 25 | const session = new Request(urls, req) 26 | const mainURL = new URL(session.url) 27 | const searchParams = mainURL.searchParams 28 | const reqHeaders = session.headers 29 | 30 | if(mainURL.hostname === '_'){ 31 | const detectedPort = await detect(mainPort) 32 | const isItRunning = mainPort !== detectedPort 33 | return new Response(String(isItRunning), {status: 200, headers: {'Content-Type': 'text/plain; charset=utf-8'}}) 34 | } 35 | 36 | session.agent = useAgent 37 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 38 | 39 | const tempRes = mainTimeout ? 40 | await Promise.race([ 41 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 42 | nodeFetch(session.url, session) 43 | ]) : 44 | await nodeFetch(session.url, session) 45 | if(!tempRes.headers.forEach){ 46 | tempRes.headers = new Headers(tempRes.headers) 47 | } 48 | 49 | return new Response(tempRes.body, {...tempRes}) 50 | } catch (error) { 51 | return new Response(intoStream(error.stack), {status: 500, statusText: error.message}) 52 | } 53 | } 54 | 55 | function intoStream (data) { 56 | return new Readable({ 57 | read () { 58 | this.push(data) 59 | this.push(null) 60 | } 61 | }) 62 | } 63 | } -------------------------------------------------------------------------------- /app/protocols/index.js: -------------------------------------------------------------------------------- 1 | import { app, protocol as globalProtocol } from 'electron' 2 | import Config from '../config.js' 3 | import fs from 'fs-extra' 4 | 5 | const P2P_PRIVILEGES = { 6 | standard: true, 7 | secure: true, 8 | allowServiceWorkers: true, 9 | supportFetchAPI: true, 10 | bypassCSP: false, 11 | corsEnabled: true, 12 | stream: true 13 | } 14 | 15 | const BROWSER_PRIVILEGES = { 16 | standard: false, 17 | secure: true, 18 | allowServiceWorkers: false, 19 | supportFetchAPI: true, 20 | bypassCSP: false, 21 | corsEnabled: true 22 | } 23 | 24 | const LOW_PRIVILEGES = { 25 | standard: false, 26 | secure: false, 27 | allowServiceWorkers: false, 28 | supportFetchAPI: false, 29 | bypassCSP: false, 30 | corsEnabled: true 31 | } 32 | 33 | const CS_PRIVILEGES = { 34 | standard: true, 35 | secure: false, 36 | allowServiceWorkers: true, 37 | supportFetchAPI: true, 38 | bypassCSP: false, 39 | corsEnabled: true, 40 | stream: true 41 | } 42 | 43 | const { 44 | ipfs, 45 | hyper, 46 | bt, 47 | oui, 48 | gemini, 49 | gopher, 50 | hhttp, 51 | tor, 52 | iip, 53 | vid, 54 | rns, 55 | err, 56 | web3 57 | } = Config 58 | 59 | const onCloseHandlers = [] 60 | 61 | export async function close () { 62 | await Promise.all(onCloseHandlers.map((handler) => handler())) 63 | } 64 | 65 | export function registerPrivileges () { 66 | globalProtocol.registerSchemesAsPrivileged([ 67 | { scheme: 'hybrid', privileges: BROWSER_PRIVILEGES }, 68 | { scheme: 'bt', privileges: P2P_PRIVILEGES }, 69 | { scheme: 'magnet', privileges: LOW_PRIVILEGES }, 70 | { scheme: 'ipfs', privileges: P2P_PRIVILEGES }, 71 | { scheme: 'hyper', privileges: P2P_PRIVILEGES }, 72 | { scheme: 'oui', privileges: CS_PRIVILEGES }, 73 | { scheme: 'ouis', privileges: P2P_PRIVILEGES }, 74 | { scheme: 'gemini', privileges: P2P_PRIVILEGES }, 75 | { scheme: 'gopher', privileges: CS_PRIVILEGES }, 76 | { scheme: 'hhttp', privileges: CS_PRIVILEGES }, 77 | { scheme: 'hhttps', privileges: P2P_PRIVILEGES }, 78 | { scheme: 'tor', privileges: CS_PRIVILEGES }, 79 | { scheme: 'tors', privileges: CS_PRIVILEGES }, 80 | { scheme: 'iip', privileges: CS_PRIVILEGES }, 81 | { scheme: 'iips', privileges: CS_PRIVILEGES }, 82 | { scheme: 'msg', privileges: P2P_PRIVILEGES }, 83 | { scheme: 'pubsub', privileges: P2P_PRIVILEGES }, 84 | { scheme: 'topic', privileges: P2P_PRIVILEGES }, 85 | { scheme: 'vid', privileges: CS_PRIVILEGES }, 86 | { scheme: 'rns', privileges: CS_PRIVILEGES }, 87 | { scheme: 'magnet', privileges: LOW_PRIVILEGES }, 88 | { scheme: 'web3', privileges: P2P_PRIVILEGES } 89 | ]) 90 | } 91 | 92 | export async function checkProtocols(){ 93 | if(bt.refresh){ 94 | await fs.emptyDir(bt.dir) 95 | } 96 | if(ipfs.refresh){ 97 | await fs.emptyDir(ipfs.repo) 98 | } 99 | if(hyper.refresh){ 100 | await fs.emptyDir(hyper.storage) 101 | } 102 | } 103 | 104 | export function setAsDefaultProtocolClient () { 105 | console.log('Setting as default handlers') 106 | app.setAsDefaultProtocolClient('hybrid') 107 | app.setAsDefaultProtocolClient('bt') 108 | app.setAsDefaultProtocolClient('ipfs') 109 | app.setAsDefaultProtocolClient('hyper') 110 | app.setAsDefaultProtocolClient('oui') 111 | app.setAsDefaultProtocolClient('ouis') 112 | app.setAsDefaultProtocolClient('gemini') 113 | app.setAsDefaultProtocolClient('gopher') 114 | app.setAsDefaultProtocolClient('hhttp') 115 | app.setAsDefaultProtocolClient('hhttps') 116 | app.setAsDefaultProtocolClient('tor') 117 | app.setAsDefaultProtocolClient('tors') 118 | app.setAsDefaultProtocolClient('iip') 119 | app.setAsDefaultProtocolClient('iips') 120 | app.setAsDefaultProtocolClient('msg') 121 | app.setAsDefaultProtocolClient('pubsub') 122 | app.setAsDefaultProtocolClient('topic') 123 | app.setAsDefaultProtocolClient('vid') 124 | app.setAsDefaultProtocolClient('rns') 125 | app.setAsDefaultProtocolClient('web3') 126 | } 127 | 128 | export async function setupProtocols (session) { 129 | const { protocol: sessionProtocol } = session 130 | 131 | const {default: browserProtocolHandler} = await import('./browser-protocol.js') 132 | // const browserProtocolHandler = await createBrowserHandler() 133 | sessionProtocol.handle('hybrid', browserProtocolHandler) 134 | globalProtocol.handle('hybrid', browserProtocolHandler) 135 | 136 | console.log('registered hybrid protocol') 137 | 138 | const torrentz = await (async () => {const {default: Torrentz} = await import('torrentz');return new Torrentz(bt);})() 139 | const helia = await (async () => {const {createHelia} = await import('helia');const {FsDatastore} = await import('datastore-fs');const {FsBlockstore} = await import('blockstore-fs');const { pubsubPeerDiscovery } = await import('@libp2p/pubsub-peer-discovery');const {quic} = await import('@chainsafe/libp2p-quic');const { uPnPNAT } = await import('@libp2p/upnp-nat');const { mdns } = await import('@libp2p/mdns');const {noise} = await import('@chainsafe/libp2p-noise');const { autoNAT } = await import('@libp2p/autonat');const {identify} = await import('@libp2p/identify');const {kadDHT} = await import('@libp2p/kad-dht');const {gossipsub} = await import('@chainsafe/libp2p-gossipsub');return await createHelia({blockstore: new FsBlockstore(ipfs.repo), datastore: new FsDatastore(ipfs.repo), libp2p: {transports: [quic()], addresses: {listen: ['/ip4/0.0.0.0/udp/0/quic-v1']}, connectionEncryption: [noise()], peerDiscovery: [pubsubPeerDiscovery(), mdns()], services: {upnpNAT: uPnPNAT(), autoNAT: autoNAT(), dht: kadDHT(), pubsub: gossipsub(), identify: identify()}}});})() 140 | const sdk = await (async () => {const SDK = await import('hyper-sdk');const sdk = await SDK.create(hyper);return sdk;})() 141 | 142 | // msg 143 | const {default: createMsgHandler} = await import('./msg-protocol.js') 144 | const { handler: msgHandler, close: closeMsg } = await createMsgHandler({...bt, err, torrentz}, session) 145 | onCloseHandlers.push(closeMsg) 146 | sessionProtocol.handle('msg', msgHandler) 147 | globalProtocol.handle('msg', msgHandler) 148 | 149 | console.log('registered msg protocol') 150 | // msg 151 | 152 | // pubsub 153 | const {default: createPubsubHandler} = await import('./pubsub-protocol.js') 154 | const { handler: pubsubHandler, close: closePubsub } = await createPubsubHandler({...ipfs, err, helia}, session) 155 | onCloseHandlers.push(closePubsub) 156 | sessionProtocol.handle('pubsub', pubsubHandler) 157 | globalProtocol.handle('pubsub', pubsubHandler) 158 | 159 | console.log('registered pubsub protocol') 160 | // pubsub 161 | 162 | // topic 163 | const {default: createTopicHandler} = await import('./topic-protocol.js') 164 | const { handler: topicHandler, close: closeTopic } = await createTopicHandler({...hyper, err, sdk}, session) 165 | onCloseHandlers.push(closeTopic) 166 | sessionProtocol.handle('topic', topicHandler) 167 | globalProtocol.handle('topic', topicHandler) 168 | 169 | console.log('registered topic protocol') 170 | // topic 171 | 172 | // bt 173 | const {default: createBTHandler} = await import('./bt-protocol.js') 174 | const { handler: btHandler, close: closeBT } = await createBTHandler({...bt, err, torrentz}, session) 175 | onCloseHandlers.push(closeBT) 176 | sessionProtocol.handle('bt', btHandler) 177 | globalProtocol.handle('bt', btHandler) 178 | 179 | console.log('registered bt protocol') 180 | // bt 181 | 182 | // const {default: createMagnetHandler} = await import('./magnet-protocol.js') 183 | // const magnetHandler = await createMagnetHandler() 184 | // sessionProtocol.handle('magnet', magnetHandler) 185 | // globalProtocol.handle('magnet', magnetHandler) 186 | 187 | // ipfs 188 | const {default: createIPFSHandler} = await import('./ipfs-protocol.js') 189 | const { handler: ipfsHandler, close: closeIPFS } = await createIPFSHandler({...ipfs, err, helia}, session) 190 | onCloseHandlers.push(closeIPFS) 191 | sessionProtocol.handle('ipfs', ipfsHandler) 192 | globalProtocol.handle('ipfs', ipfsHandler) 193 | 194 | console.log('registered ipfs protocol') 195 | // ipfs 196 | 197 | // hyper 198 | const {default: createHyperHandler} = await import('./hyper-protocol.js') 199 | const { handler: hyperHandler, close: closeHyper } = await createHyperHandler({...hyper, err, sdk}, session) 200 | onCloseHandlers.push(closeHyper) 201 | sessionProtocol.handle('hyper', hyperHandler) 202 | globalProtocol.handle('hyper', hyperHandler) 203 | 204 | console.log('registered hyper protocol') 205 | // hyper 206 | 207 | // oui 208 | const {default: createOuiHandler} = await import('./oui-protocol.js') 209 | const ouiHandler = await createOuiHandler(oui, session) 210 | sessionProtocol.handle('oui', ouiHandler) 211 | globalProtocol.handle('oui', ouiHandler) 212 | sessionProtocol.handle('ouis', ouiHandler) 213 | globalProtocol.handle('ouis', ouiHandler) 214 | 215 | console.log('registered ouinet protocol') 216 | // oui 217 | 218 | // gemini 219 | const {default: createGeminiHandler} = await import('./gemini-protocol.js') 220 | const geminiHandler = await createGeminiHandler(gemini, session) 221 | sessionProtocol.handle('gemini', geminiHandler) 222 | globalProtocol.handle('gemini', geminiHandler) 223 | 224 | console.log('registered gemini protocol') 225 | // gemini 226 | 227 | // gopher 228 | const {default: createGopherHandler} = await import('./gopher-protocol.js') 229 | const gopherHandler = await createGopherHandler(gopher, session) 230 | sessionProtocol.handle('gopher', gopherHandler) 231 | globalProtocol.handle('gopher', gopherHandler) 232 | 233 | console.log('registered gopher protocol') 234 | // gopher 235 | 236 | // hhttp 237 | const {default: createHHTTPHandler} = await import('./hhttp-protocol.js') 238 | const hhttpHandler = await createHHTTPHandler(hhttp, session) 239 | sessionProtocol.handle('hhttp', hhttpHandler) 240 | globalProtocol.handle('hhttp', hhttpHandler) 241 | sessionProtocol.handle('hhttps', hhttpHandler) 242 | globalProtocol.handle('hhttps', hhttpHandler) 243 | 244 | console.log('registered hhttp protocol') 245 | // hhttp 246 | 247 | // tor 248 | const {default: createTorHandler} = await import('./tor-protocol.js') 249 | const torHandler = await createTorHandler(tor, session) 250 | sessionProtocol.handle('tor', torHandler) 251 | globalProtocol.handle('tor', torHandler) 252 | sessionProtocol.handle('tors', torHandler) 253 | globalProtocol.handle('tors', torHandler) 254 | 255 | console.log('registered tor protocol') 256 | // tor 257 | 258 | // iip 259 | const {default: createIipHandler} = await import('./iip-protocol.js') 260 | const iipHandler = await createIipHandler(iip, session) 261 | sessionProtocol.handle('iip', iipHandler) 262 | globalProtocol.handle('iip', iipHandler) 263 | sessionProtocol.handle('iips', iipHandler) 264 | globalProtocol.handle('iips', iipHandler) 265 | 266 | console.log('registered i2p protocol') 267 | // iip 268 | 269 | // vid 270 | const {default: createVidHandler} = await import('./vid-protocol.js') 271 | const vidHandler = await createVidHandler(vid, session) 272 | sessionProtocol.handle('vid', vidHandler) 273 | globalProtocol.handle('vid', vidHandler) 274 | 275 | console.log('registered vid protocol') 276 | // vid 277 | 278 | // rns 279 | const {default: createRnsHandler} = await import('./rns-protocol.js') 280 | const rnsHandler = await createRnsHandler(rns, session) 281 | sessionProtocol.handle('rns', rnsHandler) 282 | globalProtocol.handle('rns', rnsHandler) 283 | 284 | console.log('registered rns protocol') 285 | // rns 286 | 287 | // magnet 288 | const {default: createMagnetHandler} = await import('./magnet-protocol.js') 289 | const magnetHandler = createMagnetHandler({bt: btHandler, ipfs: ipfsHandler, hyper: hyperHandler, msg: msgHandler, pubsub: pubsubHandler, topic: topicHandler, vid: vidHandler, rns: rnsHandler}) 290 | sessionProtocol.handle('magnet', magnetHandler) 291 | globalProtocol.handle('magnet', magnetHandler) 292 | 293 | console.log('registered magnet protocol') 294 | // magnet 295 | 296 | // web3 297 | const {default: createWeb3Handler} = await import('./web3-protocol.js') 298 | const web3Handler = await createWeb3Handler(web3, session) 299 | sessionProtocol.handle('web3', web3Handler) 300 | globalProtocol.handle('web3', web3Handler) 301 | 302 | console.log('registered web3 protocol') 303 | // web3 304 | } 305 | -------------------------------------------------------------------------------- /app/protocols/magnet-protocol.js: -------------------------------------------------------------------------------- 1 | import { Readable } from 'stream' 2 | import magnet from 'magnet-uri' 3 | 4 | function intoStream (data) { 5 | return new Readable({ 6 | read () { 7 | this.push(data) 8 | this.push(null) 9 | } 10 | }) 11 | } 12 | 13 | function parseQuery(data){ 14 | if(data){ 15 | let str = '?' 16 | const arr = data.split(',') 17 | for(const i of arr){ 18 | const kv = i.split(':') 19 | str = str + kv[0] + '=' + kv[1] + '&' 20 | } 21 | return str 22 | } else { 23 | return '' 24 | } 25 | } 26 | 27 | function parseHeader(data, session){ 28 | if(data){ 29 | const arr = data.split(',') 30 | for(const i of arr){ 31 | const kv = i.split(':') 32 | session.headers.set(kv[0], kv[1]) 33 | } 34 | } 35 | } 36 | 37 | export default function(proto){ 38 | const obj = proto 39 | return async function(session){ 40 | try { 41 | const parsed = magnet(session.url) 42 | if(parsed.xt && session.method === 'GET'){ 43 | const arr = parsed.xt.split(':') 44 | if(arr[0] === 'urn'){ 45 | if(arr[1] === 'btih' || arr[1] === 'btpk'){ 46 | return new Response(null, {headers: {'Location': `bt://${arr[2]}/`}, status: 308}) 47 | } else { 48 | throw new Error('must have btih or btpk') 49 | } 50 | } else { 51 | throw new Error('must have urn') 52 | } 53 | } else { 54 | delete session.url 55 | parsed.xn = parsed.xn || '/' 56 | parseHeader(parsed.xo, session) 57 | if(obj[parsed.xp]){ 58 | return await obj[parsed.xp](new Request(`${parsed.xp}://${parsed.xh || parsed.xk}${parsed.xn}${parseQuery(parsed.xq)}`, session)) 59 | } else { 60 | throw new Error('unknown scheme') 61 | } 62 | } 63 | } catch (error) { 64 | return new Response(intoStream(error.stack), {status: 500, statusText: error.message}) 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /app/protocols/msg-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeMsgFetch (opts = {}) { 2 | const errLog = opts.err 3 | const path = await import('path') 4 | const fs = await import('fs/promises') 5 | const {Readable} = await import('stream') 6 | const fse = await import('fs-extra') 7 | const { EventIterator } = await import('event-iterator') 8 | const { concat, arr2text } = await import('uint8-util') 9 | const DEFAULT_OPTS = {timeout: 30000} 10 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 11 | const block = finalOpts.block 12 | const dir = finalOpts.dir 13 | const mainHeaders = { 14 | 'Access-Control-Allow-Origin': '*', 15 | 'Allow-CSP-From': '*', 16 | 'Access-Control-Allow-Headers': '*', 17 | 'Access-Control-Allow-Methods': '*', 18 | 'Access-Control-Request-Headers': '*' 19 | } 20 | 21 | // async function checkPath(data){ 22 | // try { 23 | // await fs.access(data) 24 | // return true 25 | // } catch { 26 | // return false 27 | // } 28 | // } 29 | 30 | if(!await fse.pathExists(dir)){ 31 | await fse.ensureDir(dir) 32 | } 33 | 34 | const app = await (async () => {if(finalOpts.torrentz){return finalOpts.torrentz}else{const Torrentz = await import('torrentz');return new Torrentz(finalOpts);}})() 35 | if(!await fse.pathExists(path.join(dir, 'block.txt'))){ 36 | await fs.writeFile(path.join(dir, 'block.txt'), JSON.stringify([])) 37 | } 38 | const blockList = block ? JSON.parse((await fs.readFile(path.join(dir, 'block.txt'))).toString('utf-8')) : null 39 | 40 | const current = new Map() 41 | 42 | async function makeMsg(session){ 43 | try { 44 | const mainURL = new URL(session.url) 45 | const body = session.body 46 | const method = session.method 47 | const useHeaders = session.headers 48 | const useSearch = mainURL.searchParams 49 | 50 | if(mainURL.pathname !== '/'){ 51 | throw new Error('path must be /') 52 | } 53 | if(!mainURL.hostname){ 54 | throw new Error('must have hostname') 55 | } 56 | if(block && blockList.includes(mainURL.hostname)){ 57 | throw new Error('id is blocked') 58 | } 59 | if(method === 'HEAD'){ 60 | const {torrent} = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : await iter(mainURL, useHeaders) 61 | if(useHeaders.has('x-iden') && JSON.parse(useHeaders.get('x-iden'))){ 62 | const arr = torrent.allUsers() 63 | const rand = arr[Math.floor(Math.random() * arr.length)] 64 | if(rand){ 65 | return new Response(null, {status: 200, headers: {...mainHeaders, 'X-Iden': rand}}) 66 | } else { 67 | return new Response(null, {status: 400, headers: mainHeaders}) 68 | } 69 | } else { 70 | return new Response(null, {status: 200, headers: {...mainHeaders, 'X-Hash': torrent.infoHash}}) 71 | } 72 | } else if(method === 'GET'){ 73 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : await iter(mainURL, useHeaders) 74 | if(useHeaders.has('x-iden') && JSON.parse(useHeaders.get('x-iden'))){ 75 | return new Response(JSON.stringify(obj.torrent.allUsers()), {status: 200, headers: {...mainHeaders, 'X-Hash': obj.torrent.infoHash}}) 76 | } else { 77 | return new Response(obj.events, {status: 200, headers: {...mainHeaders, 'X-Hash': obj.torrent.infoHash}}) 78 | } 79 | } else if(method === 'POST'){ 80 | const id = useHeaders.has('x-iden') || useSearch.has('x-iden') ? useHeaders.get('x-iden') || useSearch.get('x-iden') : null 81 | const {torrent} = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : await iter(mainURL, useHeaders) 82 | torrent.say(await toBody(body, useHeaders.has('x-ben') ? useHeaders.get('x-ben') : null), id) 83 | return new Response(null, {status: 200, headers: {...mainHeaders, 'X-Hash': torrent.infoHash}}) 84 | } else if(method === 'DELETE'){ 85 | if(current.has(mainURL.hostname)){ 86 | const obj = current.get(mainURL.hostname) 87 | // const hash = obj.torrent.infoHash 88 | obj.stop() 89 | current.delete(mainURL.hostname) 90 | const test = useHeaders.has('x-shred') && JSON.parse(useHeaders.get('x-shred')) ? await app.shredTorrent(mainURL.hostname, mainURL.pathname, {buf: useHeaders.has('x-buf') ? JSON.parse(useHeaders.get('x-buf')) : false}) : mainURL.hostname 91 | return new Response(test, {status: 200, headers: {...mainHeaders, 'X-Hash': hash}}) 92 | } else { 93 | // const test = await app.shredTorrent({msg: mainURL.hostname}, mainURL.pathname, {}) 94 | return new Response(null, {status: 200, headers: mainHeaders}) 95 | } 96 | } else { 97 | return new Response('invalid method', {status: 400, headers: mainHeaders}) 98 | } 99 | } catch (error) { 100 | if(errLog){ 101 | console.error(error) 102 | } 103 | return new Response(intoStream(error.stack), {status: 500, headers: mainHeaders}) 104 | } 105 | } 106 | 107 | async function iter(mainURL, useHeaders){ 108 | const {torrent} = await app.loadTorrent(mainURL.hostname, mainURL.pathname, {torrent: true, buf: useHeaders.has('x-buf') ? JSON.parse(useHeaders.get('x-buf')) : false}) 109 | const obj = {} 110 | obj.torrent = torrent 111 | obj.events = new EventIterator(({ push, fail, stop }) => { 112 | obj.push = push 113 | obj.fail = fail 114 | obj.stop = stop 115 | function handle () { 116 | // torrent.off('msg', push) 117 | // torrent.off('over', handle) 118 | // current.delete(mainURL.hostname) 119 | stop() 120 | } 121 | function onmsg(obj){ 122 | try { 123 | obj.data = JSON.parse(new TextDecoder().decode(obj.data)) 124 | } catch (error) { 125 | console.error(error) 126 | } 127 | push(JSON.stringify(obj)) 128 | } 129 | torrent.on('msg', onmsg) 130 | torrent.on('over', handle) 131 | // obj.func = () => { 132 | // torrent.off('msg', push) 133 | // torrent.off('over', handle) 134 | // } 135 | return () => { 136 | torrent.off('msg', onmsg) 137 | torrent.off('over', handle) 138 | current.delete(mainURL.hostname) 139 | // stop() 140 | } 141 | }) 142 | current.set(mainURL.hostname, obj) 143 | return obj 144 | } 145 | 146 | async function toBody(body, ben){ 147 | const arr = [] 148 | for await (const data of body){ 149 | arr.push(data) 150 | } 151 | if(ben){ 152 | if(ben === 'str'){ 153 | return arr2text(concat(arr)) 154 | } else if(ben === 'json'){ 155 | return JSON.parse(arr2text(concat(arr))) 156 | } else if(ben === 'buf'){ 157 | return concat(arr) 158 | } else { 159 | throw new Error('x-ben header must must be str, json, or bin') 160 | } 161 | } else { 162 | return concat(arr) 163 | } 164 | } 165 | 166 | async function close(){ 167 | current.forEach((e) => { 168 | // e.func() 169 | e.stop() 170 | }) 171 | current.clear() 172 | return 173 | } 174 | 175 | function intoStream (data) { 176 | return new Readable({ 177 | read () { 178 | this.push(data) 179 | this.push(null) 180 | } 181 | }) 182 | } 183 | 184 | return {handler: makeMsg, close} 185 | } -------------------------------------------------------------------------------- /app/protocols/oui-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeIndex (opts = {}) { 2 | const { default: nodeFetch } = await import('node-fetch') 3 | const {default: detect} = await import('detect-port') 4 | const {HttpProxyAgent} = await import('http-proxy-agent') 5 | const finalOpts = { timeout: 30000, port: 8077, ...opts } 6 | const mainPort = finalOpts.port 7 | const useTimeOut = finalOpts.timeout 8 | const mainAgent = new HttpProxyAgent(`http://127.0.0.1:${mainPort}`) 9 | 10 | function useAgent(_parsedURL) { 11 | if (_parsedURL.protocol === 'http:' || _parsedURL.protocol === 'https:') { 12 | return mainAgent 13 | } else { 14 | throw new Error('protocol is not valid') 15 | } 16 | } 17 | 18 | return async function handleOui(req) { 19 | const urls = req.url.replace('oui', 'http') 20 | delete req.url 21 | const session = new Request(urls, req) 22 | const mainURL = new URL(session.url) 23 | const searchParams = mainURL.searchParams 24 | const reqHeaders = session.headers 25 | 26 | if(mainURL.hostname === '_'){ 27 | const detectedPort = await detect(mainPort) 28 | const isItRunning = mainPort !== detectedPort 29 | return {status: 200, headers: {'Content-Type': 'text/plain; charset=utf-8'}, body: String(isItRunning)} 30 | } 31 | 32 | session.agent = useAgent 33 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 34 | 35 | const tempRes = mainTimeout ? 36 | await Promise.race([ 37 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 38 | nodeFetch(session.url, session) 39 | ]) : 40 | await nodeFetch(session.url, session) 41 | if(!tempRes.headers.forEach){ 42 | tempRes.headers = new Headers(tempRes.headers) 43 | } 44 | 45 | return new Response(tempRes.body, {...tempRes}) 46 | } 47 | } -------------------------------------------------------------------------------- /app/protocols/pubsub-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makePubsubFetch (opts = {}) { 2 | const errLog = opts.err 3 | const {default: Room} = await import('ipfs-pubsub-room') 4 | const { Readable } = await import('streamx') 5 | const path = await import('path') 6 | const fs = await import('fs/promises') 7 | const fse = await import('fs-extra') 8 | const { EventIterator } = await import('event-iterator') 9 | const DEFAULT_OPTS = {timeout: 30000} 10 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 11 | const block = finalOpts.block 12 | const repo = finalOpts.repo 13 | const mainHeaders = { 14 | 'Access-Control-Allow-Origin': '*', 15 | 'Allow-CSP-From': '*', 16 | 'Access-Control-Allow-Headers': '*', 17 | 'Access-Control-Allow-Methods': '*', 18 | 'Access-Control-Request-Headers': '*' 19 | } 20 | 21 | // async function checkPath(data){ 22 | // try { 23 | // await fs.access(data) 24 | // return true 25 | // } catch { 26 | // return false 27 | // } 28 | // } 29 | 30 | if(!await fse.pathExists(repo)){ 31 | await fse.ensureDir(repo) 32 | } 33 | 34 | const app = await (async () => { if (finalOpts.helia) { return finalOpts.helia; } else {const {createHelia} = await import('helia');const {FsDatastore} = await import('datastore-fs');const {FsBlockstore} = await import('blockstore-fs');const {identify} = await import('@libp2p/identify');const {kadDHT} = await import('@libp2p/kad-dht');const {gossipsub} = await import('@chainsafe/libp2p-gossipsub');return await createHelia({blockstore: new FsBlockstore(repo), datastore: new FsDatastore(repo), libp2p: {services: {dht: kadDHT(), pubsub: gossipsub(), identify: identify()}}});} })() 35 | // const fileSystem = await (async () => {const {unixfs} = await import('@helia/unixfs');return unixfs(app);})() 36 | if(!await fse.pathExists(path.join(repo, 'block.txt'))){ 37 | await fs.writeFile(path.join(repo, 'block.txt'), JSON.stringify([])) 38 | } 39 | const blockList = block ? JSON.parse((await fs.readFile(path.join(repo, 'block.txt'))).toString('utf-8')) : null 40 | 41 | const current = new Map() 42 | 43 | async function makePubsub(session){ 44 | try { 45 | const mainURL = new URL(session.url) 46 | const body = session.body 47 | const method = session.method 48 | const headers = session.headers 49 | const search = mainURL.searchParams 50 | 51 | if(mainURL.pathname !== '/'){ 52 | throw new Error('path must be /') 53 | } 54 | if(!mainURL.hostname){ 55 | throw new Error('must have hostname') 56 | } 57 | if(block && blockList.includes(mainURL.hostname)){ 58 | throw new Error('id is blocked') 59 | } 60 | 61 | if(method === 'HEAD'){ 62 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(mainURL.hostname) 63 | if(headers.has('x-iden') && JSON.parse(headers.get('x-iden'))){ 64 | const {room} = obj 65 | const arr = room.getPeers() 66 | const rand = arr[Math.floor(Math.random() * arr.length)] 67 | if(rand){ 68 | return new Response(null, {status: 200, headers: {...mainHeaders, 'X-Iden': rand}}) 69 | } else { 70 | return new Response(null, {status: 400, headers: mainHeaders}) 71 | } 72 | } else { 73 | return new Response(null, {status: 200, headers: mainHeaders}) 74 | } 75 | } else if(method === 'GET'){ 76 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(mainURL.hostname) 77 | if(headers.has('x-iden') && JSON.parse(headers.get('x-iden'))){ 78 | return new Response(JSON.stringify(obj.room.getPeers()), {status: 200, headers: mainHeaders}) 79 | } else { 80 | return new Response(obj.events, {status: 200, headers: mainHeaders}) 81 | } 82 | } else if(method === 'POST'){ 83 | const id = headers.has('x-iden') || search.has('x-iden') ? headers.get('x-iden') || search.get('x-iden') : null 84 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(mainURL.hostname) 85 | if(id){ 86 | try { 87 | obj.room.sendTo(id, await toStr(body)) 88 | } catch (error) { 89 | if(error.message !== 'PublishError.NoPeersSubscribedToTopic'){ 90 | console.error(error) 91 | } 92 | } 93 | } else { 94 | try { 95 | await obj.room.broadcast(await toStr(body)) 96 | } catch (error) { 97 | if(error.message !== 'PublishError.NoPeersSubscribedToTopic'){ 98 | console.error(error) 99 | } 100 | } 101 | } 102 | return new Response(null, {status: 200, headers: mainHeaders}) 103 | } else if(method === 'DELETE'){ 104 | if(current.has(mainURL.hostname)){ 105 | const test = current.get(mainURL.hostname) 106 | test.stop() 107 | current.delete(mainURL.hostname) 108 | return new Response(mainURL.hostname, {status: 200, headers: mainHeaders}) 109 | } else { 110 | return new Response(mainURL.hostname, {status: 400, headers: mainHeaders}) 111 | } 112 | } else { 113 | return new Response('invalid method', {status: 400, headers: mainHeaders}) 114 | } 115 | } catch (error) { 116 | if(error.message === 'PublishError.NoPeersSubscribedToTopic'){ 117 | return new Response(null, {status: 200, headers: mainHeaders}) 118 | } else { 119 | if(errLog){ 120 | console.error(error) 121 | } 122 | return new Response(intoStream(error.stack), {status: 500, headers: mainHeaders}) 123 | } 124 | } 125 | } 126 | 127 | function iter(hostname){ 128 | const obj = {room: new Room(app.libp2p, hostname)} 129 | obj.events = new EventIterator(({ push, fail, stop }) => { 130 | obj.push = push 131 | obj.fail = fail 132 | obj.stop = stop 133 | function handleFunc(message){ 134 | message.data = new TextDecoder().decode(message.data) 135 | push(JSON.stringify(message)) 136 | } 137 | obj.room.on('message', handleFunc) 138 | // app.libp2p.services.pubsub.subscribe(hostname) 139 | return () => { 140 | // app.libp2p.services.pubsub.unsubscribe(hostname) 141 | obj.room.off('message', handleFunc) 142 | obj.room.leave().then(() => {}).catch(console.error) 143 | current.delete(hostname) 144 | // stop() 145 | } 146 | }) 147 | current.set(hostname, obj) 148 | return obj 149 | } 150 | 151 | async function toStr(data){ 152 | const chunks = [] 153 | for await (let chunk of data) { 154 | chunks.push(chunk) 155 | } 156 | return Buffer.concat(chunks).toString() 157 | } 158 | 159 | async function close(){ 160 | // app.libp2p.services.pubsub.removeEventListener('message', handle) 161 | for(const [k, v] of current){ 162 | await v.room.leave() 163 | } 164 | current.clear() 165 | return 166 | } 167 | 168 | function intoStream (data) { 169 | return new Readable({ 170 | read () { 171 | this.push(data) 172 | this.push(null) 173 | } 174 | }) 175 | } 176 | 177 | return {handler: makePubsub, close} 178 | } -------------------------------------------------------------------------------- /app/protocols/rns-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeReticulum (opts = {}) { 2 | const finalOpts = { timeout: 30000, port: 11010, ...opts } 3 | const mainPort = finalOpts.port 4 | const useTimeOut = finalOpts.timeout 5 | const mainAgent = `http://localhost:${mainPort}` 6 | 7 | return async function handleReti(req) { 8 | try { 9 | if(!['GET', 'POST'].includes(req.method)){ 10 | throw new Error('method must be GET or POST') 11 | } 12 | const mainURL = new URL(req.url) 13 | delete req.url 14 | const searchParams = mainURL.searchParams 15 | req.headers.set('X-id', mainURL.hostname) 16 | const reqHeaders = req.headers 17 | // req.headers.set('X-id', mainURL.hostname) 18 | const useUrl = mainAgent + mainURL.pathname 19 | 20 | 21 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? (() => {const getHead = reqHeaders.get('X-timer');const getSearch = searchParams.get('x-timer');reqHeaders.delete('x-timer');searchParams.delete('x-timer');getHead !== '0' || getSearch !== '0' ? Number(getHead || getSearch) * 1000 : 0})() : useTimeOut 22 | 23 | const session = new Request(useUrl, req) 24 | 25 | const tempRes = mainTimeout ? 26 | await Promise.race([ 27 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 28 | fetch(session.url, session) 29 | ]) : 30 | await fetch(session.url, session) 31 | if(!tempRes.headers.forEach){ 32 | tempRes.headers = new Headers(tempRes.headers) 33 | } 34 | 35 | return new Response(tempRes.body, tempRes) 36 | } catch (error) { 37 | return new Response(intoStream(error.stack), {status: 500, statusText: error.message}) 38 | } 39 | } 40 | 41 | function intoStream (data) { 42 | return new Readable({ 43 | read () { 44 | this.push(data) 45 | this.push(null) 46 | } 47 | }) 48 | } 49 | } -------------------------------------------------------------------------------- /app/protocols/topic-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeTopicFetch (opts = {}) { 2 | const errLog = opts.err 3 | const { Readable, pipelinePromise } = await import('streamx') 4 | const fs = await import('fs/promises') 5 | const fse = await import('fs-extra') 6 | const { EventIterator } = await import('event-iterator') 7 | const path = await import('path') 8 | const DEFAULT_OPTS = {timeout: 30000} 9 | const finalOpts = { ...DEFAULT_OPTS, ...opts } 10 | const block = finalOpts.block 11 | const storage = finalOpts.storage 12 | const mainHeaders = { 13 | 'Access-Control-Allow-Origin': '*', 14 | 'Allow-CSP-From': '*', 15 | 'Access-Control-Allow-Headers': '*', 16 | 'Access-Control-Allow-Methods': '*', 17 | 'Access-Control-Request-Headers': '*' 18 | } 19 | 20 | // async function checkPath(data){ 21 | // try { 22 | // await fs.access(data) 23 | // return true 24 | // } catch { 25 | // return false 26 | // } 27 | // } 28 | 29 | if(!await fse.pathExists(storage)){ 30 | await fse.ensureDir(storage) 31 | } 32 | 33 | const app = await (async () => {if(finalOpts.sdk){return finalOpts.sdk}else{const SDK = await import('hyper-sdk');const sdk = await SDK.create(finalOpts);return sdk;}})() 34 | if(!await fse.pathExists(path.join(storage, 'block.txt'))){ 35 | await fs.writeFile(path.join(storage, 'block.txt'), JSON.stringify([])) 36 | } 37 | const blockList = block ? JSON.parse((await fs.readFile(path.join(storage, 'block.txt'))).toString('utf-8')) : null 38 | 39 | const current = new Map() 40 | const connection = new Map() 41 | const line = new Map() 42 | 43 | function handle(socket, relay){ 44 | const pub = socket.publicKey.toString('hex') 45 | const peerKey = relay.publicKey 46 | socket.peerKey = peerKey 47 | if(!socket.ids){ 48 | socket.ids = new Set() 49 | } 50 | for(const topic of relay.topics){ 51 | const bufToStr = topic.toString() 52 | if(current.has(bufToStr)){ 53 | if(!connection.has(pub)){ 54 | connection.set(pub, socket) 55 | } 56 | const test = current.get(bufToStr) 57 | if(!test.ids.has(pub)){ 58 | test.ids.add(pub) 59 | } 60 | if(!socket.ids.has(bufToStr)){ 61 | socket.ids.add(bufToStr) 62 | } 63 | if(!test.peers.has(peerKey)){ 64 | test.peers.add(peerKey) 65 | } 66 | } 67 | } 68 | if(connection.has(pub)){ 69 | if(!socket.funcs){ 70 | function handleData(data){ 71 | test.push(JSON.stringify({peer: peerKey, data: new TextDecoder().decode(data)})) 72 | } 73 | function handleErr(err){ 74 | test.fail(err) 75 | } 76 | function handler(){ 77 | socket.off('data', handleData) 78 | socket.off('error', handleErr) 79 | socket.off('close', handler) 80 | } 81 | socket.on('data', handleData) 82 | socket.on('error', handleErr) 83 | socket.on('close', handler) 84 | socket.funcs = true 85 | } 86 | } 87 | if(!line.has(peerKey, socket)){ 88 | line.set(peerKey, socket) 89 | } 90 | } 91 | 92 | app.swarm.on('connection', handle) 93 | 94 | async function makeTopic(session){ 95 | try { 96 | const mainURL = new URL(session.url) 97 | const body = session.body 98 | const method = session.method 99 | const headers = session.headers 100 | const search = mainURL.searchParams 101 | 102 | if(mainURL.pathname !== '/'){ 103 | throw new Error('path must be /') 104 | } 105 | 106 | if(!mainURL.hostname){ 107 | throw new Error('must have hostname') 108 | } 109 | 110 | if(block && blockList.includes(mainURL.hostname)){ 111 | throw new Error('id is blocked') 112 | } 113 | 114 | if(method === 'HEAD'){ 115 | const buf = Buffer.alloc(32).fill(mainURL.hostname) 116 | const str = buf.toString() 117 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(str, buf) 118 | if(headers.has('x-iden') && JSON.parse(headers.get('x-iden'))){ 119 | const {peers} = obj 120 | const arr = [] 121 | for(const i of peers){ 122 | arr.push(i) 123 | } 124 | const rand = arr[Math.floor(Math.random() * arr.length)] 125 | if(rand){ 126 | return new Response(null, {status: 200, headers: {...mainHeaders, 'X-Iden': rand}}) 127 | } else { 128 | return new Response(null, {status: 400, headers: mainHeaders}) 129 | } 130 | } else { 131 | return new Response(null, {status: 200, headers: mainHeaders}) 132 | } 133 | } else if(method === 'GET'){ 134 | const buf = Buffer.alloc(32).fill(mainURL.hostname) 135 | const str = buf.toString() 136 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(str, buf) 137 | if(headers.has('x-iden') && JSON.parse(headers.get('x-iden'))){ 138 | const arr = [] 139 | for(const i of obj.peers){ 140 | arr.push(i) 141 | } 142 | return new Response(JSON.stringify(arr), {status: 200, headers: mainHeaders}) 143 | } else { 144 | return new Response(obj.events, {status: 200, headers: mainHeaders}) 145 | } 146 | } else if(method === 'POST'){ 147 | const id = headers.has('x-iden') || search.has('x-iden') ? headers.get('x-iden') || search.get('x-iden') : null 148 | const buf = Buffer.alloc(32).fill(mainURL.hostname) 149 | const str = buf.toString() 150 | const obj = current.has(mainURL.hostname) ? current.get(mainURL.hostname) : iter(str, buf) 151 | if(id){ 152 | if(line.has(id)){ 153 | line.get(id).write(await toBuff(body)) 154 | } 155 | } else { 156 | for(const prop of obj.ids){ 157 | if(connection.has(prop)){ 158 | connection.get(prop).write(await toBuff(body)) 159 | } 160 | } 161 | } 162 | return new Response(null, {status: 200, headers: mainHeaders}) 163 | } else if(method === 'DELETE'){ 164 | if(current.has(mainURL.hostname)){ 165 | const obj = current.get(mainURL.hostname) 166 | obj.stop() 167 | current.delete(mainURL.hostname) 168 | return new Response(mainURL.hostname, {status: 200, headers: mainHeaders}) 169 | } else { 170 | return new Response(mainURL.hostname, {status: 400, headers: mainHeaders}) 171 | } 172 | } else { 173 | return new Response('invalid method', {status: 400, headers: mainHeaders}) 174 | } 175 | } catch (error) { 176 | if(errLog){ 177 | console.error(error) 178 | } 179 | return new Response(intoStream(error.stack), {status: 500, headers: mainHeaders}) 180 | } 181 | } 182 | 183 | function iter(hostname, bufOFStr){ 184 | const obj = {} 185 | obj.ids = new Set() 186 | obj.peers = new Set() 187 | obj.events = new EventIterator(({ push, fail, stop }) => { 188 | obj.push = push 189 | obj.fail = fail 190 | obj.stop = stop 191 | // obj.status = false 192 | // const disc = app.swarm.join(mainURL.hostname, {}) 193 | app.swarm.join(bufOFStr, {}) 194 | return () => { 195 | // disc.destroy().then(console.log).catch(console.error) 196 | app.swarm.leave(bufOFStr).then(console.log).catch(console.error) 197 | // if(current.has(hostname)){ 198 | for(const prop of obj.ids){ 199 | if(connection.has(prop)){ 200 | const soc = connection.get(prop) 201 | if(soc.ids.has(hostname)){ 202 | soc.ids.delete(hostname) 203 | if(!soc.ids.size){ 204 | if(line.has(soc.peerKey)){ 205 | line.delete(soc.peerKey) 206 | } 207 | soc.destroy() 208 | connection.delete(prop) 209 | } 210 | } 211 | } 212 | } 213 | // } 214 | current.delete(hostname) 215 | // stop() 216 | } 217 | }) 218 | current.set(hostname, obj) 219 | return obj 220 | } 221 | 222 | async function close(){ 223 | app.swarm.off('connection', handle) 224 | for(const cur of current.values()){ 225 | cur.stop() 226 | } 227 | for(const soc of connection.values()){ 228 | soc.destroy() 229 | } 230 | current.clear() 231 | connection.clear() 232 | return 233 | } 234 | 235 | async function toBuff(data){ 236 | const chunks = [] 237 | for await (let chunk of data) { 238 | chunks.push(chunk) 239 | } 240 | return Buffer.concat(chunks) 241 | } 242 | 243 | function intoStream (data) { 244 | return new Readable({ 245 | read () { 246 | this.push(data) 247 | this.push(null) 248 | } 249 | }) 250 | } 251 | 252 | return {handler: makeTopic, close} 253 | } -------------------------------------------------------------------------------- /app/protocols/tor-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeOnion (opt = {}) { 2 | const { default: nodeFetch } = await import('node-fetch') 3 | const {default: detect} = await import('detect-port') 4 | const {SocksProxyAgent} = await import('socks-proxy-agent') 5 | const finalOpts = { timeout: 30000, port: 9050, scheme: 'socks5:', hostname: 'localhost', ...opt } 6 | const mainPort = finalOpts.port 7 | const useTimeOut = finalOpts.timeout 8 | const socksh = finalOpts.scheme 9 | const mainHost = finalOpts.hostname 10 | const mainAgent = new SocksProxyAgent(`${socksh}//${mainHost}:${mainPort}`) 11 | 12 | function useAgent(_parsedURL) { 13 | if (_parsedURL.protocol === 'http:' || _parsedURL.protocol === 'https:') { 14 | return mainAgent 15 | } else { 16 | throw new Error('protocol is not valid') 17 | } 18 | } 19 | 20 | return async function handleTor(req) { 21 | try { 22 | const urls = req.url.replace('tor', 'http') 23 | delete req.url 24 | const session = new Request(urls, req) 25 | const mainURL = new URL(session.url) 26 | const searchParams = mainURL.searchParams 27 | const reqHeaders = session.headers 28 | 29 | if(mainURL.hostname === '_'){ 30 | const detectedPort = await detect(mainPort) 31 | const isItRunning = mainPort !== detectedPort 32 | return new Response(String(isItRunning), {status: 200, headers: {'Content-Type': 'text/plain; charset=utf-8'}}) 33 | } 34 | 35 | session.agent = useAgent 36 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? reqHeaders.get('x-timer') !== '0' || searchParams.get('x-timer') !== '0' ? Number(reqHeaders.get('x-timer') || searchParams.get('x-timer')) * 1000 : 0 : useTimeOut 37 | 38 | const tempRes = mainTimeout ? 39 | await Promise.race([ 40 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 41 | nodeFetch(session.url, session) 42 | ]) : 43 | await nodeFetch(session.url, session) 44 | if(!tempRes.headers.forEach){ 45 | tempRes.headers = new Headers(tempRes.headers) 46 | } 47 | 48 | return new Response(tempRes.body, {...tempRes}) 49 | } catch (error) { 50 | return new Response(intoStream(error.stack), {status: 500, statusText: error.message}) 51 | } 52 | } 53 | 54 | function intoStream (data) { 55 | return new Readable({ 56 | read () { 57 | this.push(data) 58 | this.push(null) 59 | } 60 | }) 61 | } 62 | } -------------------------------------------------------------------------------- /app/protocols/vid-protocol.js: -------------------------------------------------------------------------------- 1 | export default async function makeVeilid (opts = {}) { 2 | const {hex2arr, arr2hex, arr2text} = await import('uint8-util') 3 | const path = await import('path') 4 | const {Readable} = await import('streamx') 5 | const finalOpts = { timeout: 30000, port: 9990, ...opts } 6 | const mainPort = finalOpts.port 7 | const useTimeOut = finalOpts.timeout 8 | const mainAgent = `http://localhost:${mainPort}` 9 | 10 | return async function handleVeil(req) { 11 | try { 12 | if(!['HEAD', 'GET', 'POST'].includes(req.method)){ 13 | throw new Error('method must be HEAD, GET, or POST') 14 | } 15 | const mainURL = new URL(req.url) 16 | delete req.url 17 | const searchParams = mainURL.searchParams 18 | // req.headers.set('X-id', mainURL.hostname) 19 | const reqHeaders = req.headers 20 | if(/^[0-9a-fA-F]+$/.test(mainURL.hostname)){ 21 | req.headers.set('X-id', arr2text(hex2arr(mainURL.hostname))) 22 | } else if(req.headers.has('x-id') || searchParams.has('x-id')){ 23 | req.headers.set('X-id', req.headers.get('x-id') || searchParams.get('x-id')) 24 | } else { 25 | throw new Error('must have x-id header key') 26 | } 27 | const useUrl = path.join(mainAgent, mainURL.pathname).replace(/\\/g, '/') 28 | 29 | 30 | const mainTimeout = reqHeaders.has('x-timer') || searchParams.has('x-timer') ? (() => {const getHead = reqHeaders.get('X-timer');const getSearch = searchParams.get('x-timer');reqHeaders.delete('x-timer');searchParams.delete('x-timer');getHead !== '0' || getSearch !== '0' ? Number(getHead || getSearch) * 1000 : 0})() : useTimeOut 31 | 32 | const session = new Request(useUrl, req) 33 | 34 | const tempRes = mainTimeout ? 35 | await Promise.race([ 36 | new Promise((resolve, reject) => setTimeout(() => { const err = new Error('timed out'); err.name = 'timeout'; reject(err) }, mainTimeout)), 37 | fetch(session.url, session) 38 | ]) : 39 | await fetch(session.url, session) 40 | if(!tempRes.headers.forEach){ 41 | tempRes.headers = new Headers(tempRes.headers) 42 | } 43 | 44 | return new Response(tempRes.body, tempRes) 45 | } catch (error) { 46 | return new Response(intoStream(error.stack), {status: 500, statusText: error.message}) 47 | } 48 | } 49 | 50 | function intoStream (data) { 51 | return new Readable({ 52 | read () { 53 | this.push(data) 54 | this.push(null) 55 | } 56 | }) 57 | } 58 | } -------------------------------------------------------------------------------- /app/protocols/web3-protocol.js: -------------------------------------------------------------------------------- 1 | import { Client } from 'web3protocol' 2 | 3 | export default async function makeWeb3 (options) { 4 | const { chainList, ...opts } = options 5 | const web3Client = new Client(chainList, opts) 6 | 7 | return async function useThefetch(session){ 8 | if (session.method !== 'GET') { 9 | return new Response('Method Not Allowed', { 10 | status: 405 11 | }) 12 | } 13 | const { httpCode, httpHeaders, output } = await web3Client.fetchUrl(session.url) 14 | 15 | return new Response(output, { status: httpCode, headers: httpHeaders }) 16 | } 17 | } -------------------------------------------------------------------------------- /app/settings-preload.js: -------------------------------------------------------------------------------- 1 | const { contextBridge, ipcRenderer, webFrame } = require('electron') 2 | 3 | webFrame.top.executeJavaScript('window.location.href').then((url) => { 4 | if (url === 'hybrid://settings') { 5 | contextBridge.exposeInMainWorld('settings', { 6 | save: (args) => ipcRenderer.invoke('settings-save', args) 7 | }) 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /app/ui/browser-actions.js: -------------------------------------------------------------------------------- 1 | /* global HTMLElement, customElements */ 2 | 3 | class BrowserActions extends HTMLElement { 4 | async connectedCallback () { 5 | this.current = this.current ? this.current : window.getCurrentWindow() 6 | await this.renderLatest() 7 | 8 | // this.current = window.getCurrentWindow() 9 | // this.renderLatest() 10 | } 11 | 12 | async renderLatest () { 13 | const current = this.current 14 | 15 | const actions = await current.listExtensionActions() 16 | this.innerHTML = '' 17 | 18 | for (const { title, icon, id, badge } of actions) { 19 | const button = document.createElement('button') 20 | button.setAttribute('class', 'browser-actions-button') 21 | button.setAttribute('title', title) 22 | button.addEventListener('click', () => { 23 | current.clickExtensionAction(id) 24 | }) 25 | const img = document.createElement('img') 26 | img.setAttribute('class', 'browser-actions-icon') 27 | img.setAttribute('src', icon) 28 | 29 | button.append(img) 30 | 31 | if (badge && badge.text) { 32 | const badgeItem = document.createElement('div') 33 | 34 | const badgeColor = badge.color || 'inherit' 35 | const badgeBackground = badge.background || 'none' 36 | let badgeStyle = '' 37 | if (badge.color) badgeStyle += `color: ${badgeColor};` 38 | if (badge.background) badgeStyle += `background: ${badgeBackground};` 39 | 40 | badgeItem.innerText = badge.text 41 | badgeItem.setAttribute('class', 'browser-actions-badge') 42 | badgeItem.setAttribute('style', badgeStyle) 43 | button.append(badgeItem) 44 | } 45 | 46 | this.appendChild(button) 47 | } 48 | } 49 | 50 | get tabId () { 51 | return this.getAttribute('tab-id') 52 | } 53 | } 54 | 55 | customElements.define('browser-actions', BrowserActions) 56 | -------------------------------------------------------------------------------- /app/ui/current-window.js: -------------------------------------------------------------------------------- 1 | window.getCurrentWindow = function getCurrentWindow () { 2 | const { ipcRenderer } = require('electron') 3 | const EventEmitter = require('events') 4 | 5 | const EVENTS = [ 6 | 'navigating', 7 | 'history-buttons-change', 8 | 'page-title-updated', 9 | 'enter-html-full-screen', 10 | 'leave-html-full-screen', 11 | 'update-target-url', 12 | 'browser-actions-changed', 13 | 'close', 14 | 'enter-full-screen', 15 | 'leave-full-screen' 16 | ] 17 | 18 | class CurrentWindow extends EventEmitter { 19 | constructor () { 20 | super() 21 | 22 | for (const name of EVENTS) { 23 | ipcRenderer.on(`hybrid-window-${name}`, (event, ...args) => this.emit(name, ...args)) 24 | } 25 | } 26 | 27 | async goBack () { 28 | return this.invoke('goBack') 29 | } 30 | 31 | async goForward () { 32 | return this.invoke('goForward') 33 | } 34 | 35 | async reload () { 36 | return this.invoke('reload') 37 | } 38 | 39 | async focus () { 40 | return this.invoke('focus') 41 | } 42 | 43 | async loadURL (url) { 44 | return this.invoke('loadURL', url) 45 | } 46 | 47 | async getURL () { 48 | return this.invoke('getURL') 49 | } 50 | 51 | async findInPage (value, opts) { 52 | return this.invoke('findInPage', value, opts) 53 | } 54 | 55 | async stopFindInPage () { 56 | return this.invoke('stopFindInPage') 57 | } 58 | 59 | async setBounds (rect) { 60 | return this.invoke('setBounds', rect) 61 | } 62 | 63 | async * searchHistory (query, limit = 8) { 64 | // Open iterator, get back an id 65 | // Invoke next until done 66 | await this.invoke('searchHistoryStart', query, limit) 67 | while (true) { 68 | const { done, value } = await this.invoke('searchHistoryNext') 69 | if (done) break 70 | yield value 71 | } 72 | } 73 | 74 | async listExtensionActions () { 75 | return this.invoke('listExtensionActions') 76 | } 77 | 78 | async clickExtensionAction (id) { 79 | return this.invoke('clickExtensionAction', id) 80 | } 81 | 82 | async invoke (name, ...args) { 83 | return ipcRenderer.invoke(`hybrid-window-${name}`, ...args) 84 | } 85 | } 86 | 87 | return new CurrentWindow() 88 | } 89 | -------------------------------------------------------------------------------- /app/ui/find-menu.js: -------------------------------------------------------------------------------- 1 | /* global CustomEvent, customElements, HTMLElement */ 2 | 3 | class FindMenu extends HTMLElement { 4 | constructor () { 5 | super() 6 | 7 | this.addEventListener('keydown', ({ key }) => { 8 | if (key === 'Escape') this.hide() 9 | }) 10 | } 11 | 12 | connectedCallback () { 13 | this.innerHTML = ` 14 | 15 | 16 | 17 | 18 | ` 19 | 20 | this.input = this.$('.find-menu-input') 21 | this.previousButton = this.$('.find-menu-previous') 22 | this.nextButton = this.$('.find-menu-next') 23 | this.hideButton = this.$('.find-menu-hide') 24 | 25 | this.input.addEventListener('input', (e) => { 26 | const { value } = this 27 | 28 | if (!value) return 29 | 30 | this.dispatchEvent(new CustomEvent('next', { detail: { value } })) 31 | }) 32 | 33 | this.input.addEventListener('keydown', ({ keyCode, shiftKey }) => { 34 | if (keyCode === 13) { 35 | const { value } = this 36 | 37 | if (!value) return this.hide() 38 | 39 | const direction = shiftKey ? 'previous' : 'next' 40 | this.dispatchEvent(new CustomEvent(direction, { detail: { value, findNext: true } })) 41 | } 42 | }) 43 | 44 | this.previousButton.addEventListener('click', () => { 45 | const { value } = this 46 | 47 | if (!value) return 48 | 49 | this.dispatchEvent(new CustomEvent('previous', { detail: { value, findNext: false } })) 50 | }) 51 | this.nextButton.addEventListener('click', () => { 52 | const { value } = this 53 | 54 | if (!value) return 55 | 56 | this.dispatchEvent(new CustomEvent('next', { detail: { value, findNext: true } })) 57 | }) 58 | this.hideButton.addEventListener('click', () => this.hide()) 59 | } 60 | 61 | get value () { 62 | return this.input.value 63 | } 64 | 65 | show () { 66 | this.classList.toggle('hidden', false) 67 | setTimeout(() => { 68 | this.focus() 69 | }, 10) 70 | } 71 | 72 | hide () { 73 | this.classList.toggle('hidden', true) 74 | this.dispatchEvent(new CustomEvent('hide')) 75 | } 76 | 77 | toggle () { 78 | const isActive = this.classList.toggle('hidden') 79 | if (isActive) this.focus() 80 | else this.dispatchEvent(new CustomEvent('hide')) 81 | } 82 | 83 | focus () { 84 | this.input.focus() 85 | this.input.select() 86 | } 87 | 88 | $ (query) { 89 | return this.querySelector(query) 90 | } 91 | } 92 | 93 | customElements.define('find-menu', FindMenu) 94 | -------------------------------------------------------------------------------- /app/ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | Hybrid Browser 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 |
22 | 23 | 24 | 25 |
26 | 27 |
28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /app/ui/omni-box.js: -------------------------------------------------------------------------------- 1 | /* global HTMLElement, CustomEvent, customElements */ 2 | 3 | class OmniBox extends HTMLElement { 4 | constructor () { 5 | super() 6 | this.firstLoad = true 7 | this.lastSearch = 0 8 | } 9 | 10 | get options () { 11 | return document.querySelector('#' + this.getAttribute('nav-options-id')) 12 | } 13 | 14 | connectedCallback () { 15 | this.innerHTML = ` 16 |
17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 |
26 |
27 | ` 28 | this.backButton = this.$('.omni-box-back') 29 | this.forwardButton = this.$('.omni-box-forward') 30 | this.upButton = this.$('.omni-box-up') 31 | this.form = this.$('.omni-box-form') 32 | this.input = this.$('.omni-box-input') 33 | this.targetUrl = this.$('.omni-box-target-input') 34 | this.homeButton = this.$('.omni-box-home') 35 | 36 | this.input.addEventListener('focus', () => { 37 | this.input.select() 38 | }) 39 | 40 | this.targetUrl.addEventListener('focus', () => { 41 | this.showInput() 42 | this.input.select() 43 | }) 44 | 45 | this.input.addEventListener('blur', () => { 46 | this.input.blur() 47 | }) 48 | 49 | this.form.addEventListener('submit', (e) => { 50 | e.preventDefault(true) 51 | 52 | const rawURL = this.getURL() 53 | 54 | let url = rawURL 55 | 56 | if (!isURL(rawURL)) { 57 | if (isBareLocalhost(rawURL)) { 58 | url = makeHttp(rawURL) 59 | } else if (looksLikeDomain(rawURL)) { 60 | url = makeHttps(rawURL) 61 | } else { 62 | url = makeDuckDuckGo(rawURL) 63 | } 64 | } 65 | 66 | this.clearOptions() 67 | 68 | const searchID = Date.now() 69 | this.lastSearch = searchID 70 | 71 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 72 | }) 73 | this.input.addEventListener('input', () => { 74 | this.updateOptions() 75 | }) 76 | this.input.addEventListener('keydown', ({ keyCode, key }) => { 77 | // Pressed down arrow 78 | if (keyCode === 40) this.selectNext() 79 | 80 | // Pressed up arrow 81 | if (keyCode === 38) this.selectPrevious() 82 | 83 | if (keyCode === 39) { 84 | const { selectionStart, selectionEnd, value } = this.input 85 | const isAtEnd = (selectionStart === value.length) && (selectionEnd === value.length) 86 | if (isAtEnd) this.fillWithSelected() 87 | } 88 | 89 | if (key === 'Escape') { 90 | this.clearOptions() 91 | this.input.blur() 92 | this.dispatchEvent(new CustomEvent('unfocus')) 93 | } 94 | }) 95 | 96 | this.backButton.addEventListener('click', () => { 97 | this.dispatchEvent(new CustomEvent('back')) 98 | }) 99 | this.forwardButton.addEventListener('click', () => { 100 | this.dispatchEvent(new CustomEvent('forward')) 101 | }) 102 | this.upButton.addEventListener('click', () => { 103 | this.dispatchEvent(new CustomEvent('up')) 104 | }) 105 | this.homeButton.addEventListener('click', () => { 106 | this.dispatchEvent(new CustomEvent('home')) 107 | }) 108 | 109 | // middle mouse click paste&go 110 | this.input.addEventListener('paste', (e) => { 111 | const url = e.clipboardData.getData('text') 112 | 113 | if (isURL(url)) { 114 | e.preventDefault() 115 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 116 | } 117 | }) 118 | } 119 | 120 | clearOptions () { 121 | this.options.innerHTML = '' 122 | } 123 | 124 | getURL () { 125 | const item = this.getSelected() 126 | 127 | return item ? item.dataset.url : this.input.value 128 | } 129 | 130 | getSelected () { 131 | return (this.options.querySelector('[data-selected]') || this.options.firstElementChild) 132 | } 133 | 134 | selectNext () { 135 | const item = this.getSelected() 136 | 137 | if (!item) return 138 | 139 | const sibling = item.nextElementSibling 140 | 141 | if (!sibling) return 142 | 143 | item.removeAttribute('data-selected') 144 | sibling.setAttribute('data-selected', 'selected') 145 | } 146 | 147 | selectPrevious () { 148 | const item = this.getSelected() 149 | 150 | if (!item) return 151 | 152 | const sibling = item.previousElementSibling 153 | 154 | if (!sibling) return 155 | 156 | item.removeAttribute('data-selected') 157 | sibling.setAttribute('data-selected', 'selected') 158 | } 159 | 160 | fillWithSelected () { 161 | const item = this.getSelected() 162 | 163 | if (!item) return 164 | 165 | const { url } = item.dataset 166 | 167 | this.input.value = url 168 | } 169 | 170 | async updateOptions () { 171 | const query = this.input.value 172 | 173 | const searchID = Date.now() 174 | this.lastSearch = searchID 175 | 176 | this.clearOptions() 177 | 178 | if (!query) { 179 | return 180 | } 181 | 182 | this.dispatchEvent(new CustomEvent('search', { detail: { query, searchID } })) 183 | } 184 | 185 | async setSearchResults (results, query, searchID) { 186 | if (this.lastSearch !== searchID) { 187 | return console.debug('Urlbar changed since query finished', this.lastSearch, searchID, query) 188 | } 189 | const finalItems = [] 190 | 191 | if (isURL(query)) { 192 | finalItems.push(this.makeNavItem(query, `Go to ${query}`)) 193 | } else if (isBareLocalhost(query)) { 194 | finalItems.push(this.makeNavItem(makeHttp(query), `Go to http://${query}`)) 195 | } else if (looksLikeDomain(query)) { 196 | finalItems.push(this.makeNavItem(makeHttps(query), `Go to https://${query}`)) 197 | } else { 198 | finalItems.push( 199 | this.makeNavItem( 200 | makeDuckDuckGo(query), 201 | `Search for "${query}" on DuckDuckGo` 202 | ) 203 | ) 204 | } 205 | 206 | finalItems.push(...results 207 | .map(({ title, url }) => this.makeNavItem(url, `${title} - ${url}`)) 208 | ) 209 | 210 | this.options.replaceChildren(...finalItems) 211 | 212 | this.getSelected().setAttribute('data-selected', 'selected') 213 | } 214 | 215 | addSearchResult ({ title, url }) { 216 | const item = this.makeNavItem(url, `${title} - ${url}`) 217 | this.options.appendChild(item) 218 | } 219 | 220 | makeNavItem (url, text) { 221 | const element = document.createElement('button') 222 | element.classList.add('omni-box-nav-item') 223 | element.classList.add('omni-box-button') 224 | element.dataset.url = url 225 | element.innerText = text 226 | element.onclick = () => { 227 | this.clearOptions() 228 | 229 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 230 | } 231 | return element 232 | } 233 | 234 | static get observedAttributes () { 235 | return ['src', 'back', 'forward'] 236 | } 237 | 238 | attributeChangedCallback (name, oldValue, newValue) { 239 | if (name === 'src') { 240 | this.input.value = newValue 241 | 242 | const { pathname } = new URL(newValue) 243 | const hasUpperFolders = pathname !== '/' 244 | this.upButton.classList.toggle('hidden', !hasUpperFolders) 245 | 246 | const noFocus = (new URL(window.location.href).searchParams).get('noFocus') === 'true' 247 | if (noFocus) { 248 | return 249 | } 250 | if (this.firstLoad && (newValue === window.DEFAULT_PAGE)) { 251 | this.firstLoad = false 252 | this.focus() 253 | } 254 | } if (name === 'back') { 255 | this.backButton.classList.toggle('hidden', newValue === 'hidden') 256 | } else if (name === 'forward') { 257 | this.forwardButton.classList.toggle('hidden', newValue === 'hidden') 258 | } 259 | } 260 | 261 | get src () { 262 | return this.input.value 263 | } 264 | 265 | set src (value) { 266 | this.setAttribute('src', value) 267 | } 268 | 269 | showInput (show = true) { 270 | this.targetUrl.classList.toggle('hidden', show) 271 | this.input.classList.toggle('hidden', !show) 272 | } 273 | 274 | showTarget (url) { 275 | this.targetUrl.value = url 276 | const inputSelected = this.input === document.activeElement 277 | 278 | if (url && !inputSelected) { 279 | this.showInput(false) 280 | } else { 281 | this.showInput(true) 282 | } 283 | } 284 | 285 | focus () { 286 | this.input.focus() 287 | this.input.select() 288 | } 289 | 290 | $ (query) { 291 | return this.querySelector(query) 292 | } 293 | 294 | convertURL (rawURL) { 295 | } 296 | } 297 | 298 | function makeHttp (query) { 299 | return `http://${query}` 300 | } 301 | 302 | function makeHttps (query) { 303 | return `https://${query}` 304 | } 305 | 306 | function makeDuckDuckGo (query) { 307 | return `https://duckduckgo.com/?ia=web&q=${encodeURIComponent(query)}` 308 | } 309 | 310 | function isURL (string) { 311 | try { 312 | // localhost: is a valid url apparently! 313 | if (isBareLocalhost(string)) return false 314 | return !!new URL(string) 315 | } catch { 316 | return false 317 | } 318 | } 319 | 320 | function looksLikeDomain (string) { 321 | return !string.match(/\s/) && string.includes('.') 322 | } 323 | 324 | function isBareLocalhost (string) { 325 | return string.match(/^localhost(:[0-9]+)?\/?$/) 326 | } 327 | 328 | customElements.define('omni-box', OmniBox) 329 | -------------------------------------------------------------------------------- /app/ui/script.js: -------------------------------------------------------------------------------- 1 | const DEFAULT_PAGE = 'hybrid://welcome' 2 | 3 | const webview = $('#view') 4 | // Kyran: Using variable name "top" causes issues for some reason? I would assume it's because of another one of the UI scripts but it doesn't seem like that's the case. 5 | const nav = $('#top') 6 | const search = $('#search') 7 | const find = $('#find') 8 | const actions = $('#actions') 9 | 10 | const checkWindow = document.getElementsByTagName('browser-actions')[0] 11 | if(!checkWindow.current){ 12 | checkWindow.current = window.getCurrentWindow() 13 | } 14 | const currentWindow = checkWindow.current 15 | 16 | // const currentWindow = window.getCurrentWindow() 17 | 18 | const pageTitle = $('title') 19 | 20 | const searchParams = new URL(window.location.href).searchParams 21 | 22 | // remove window.searchParams if issues arise 23 | // window.searchParams = searchParams 24 | // remove window.searchParams if issues arise 25 | 26 | const toNavigate = searchParams.has('url') ? searchParams.get('url') : DEFAULT_PAGE 27 | 28 | const rawFrame = searchParams.get('rawFrame') === 'true' 29 | const noNav = searchParams.get('noNav') === 'true' 30 | 31 | if (rawFrame) nav.classList.toggle('hidden', true) 32 | 33 | window.addEventListener('load', () => { 34 | if (noNav) return 35 | console.log('toNavigate', toNavigate) 36 | currentWindow.loadURL(toNavigate).catch(console.error) 37 | webview.emitResize() 38 | }) 39 | 40 | search.addEventListener('back', () => { 41 | currentWindow.goBack() 42 | }) 43 | 44 | search.addEventListener('forward', () => { 45 | currentWindow.goForward() 46 | }) 47 | 48 | search.addEventListener('up', () => { 49 | const next = search.src.endsWith('/') ? '../' : './' 50 | currentWindow.loadURL(new URL(next, search.src).href).catch(console.error) 51 | }) 52 | 53 | search.addEventListener('navigate', ({ detail }) => { 54 | const { url } = detail 55 | 56 | navigateTo(url).catch(console.error) 57 | }) 58 | 59 | search.addEventListener('unfocus', async () => { 60 | await currentWindow.focus() 61 | search.src = await currentWindow.getURL() 62 | }) 63 | 64 | search.addEventListener('search', async ({ detail }) => { 65 | const { query, searchID } = detail 66 | 67 | search.setSearchResults([], query, searchID) 68 | for await (const result of currentWindow.searchHistory(query)) { 69 | search.addSearchResult(result) 70 | } 71 | }) 72 | 73 | search.addEventListener('home', () => { 74 | navigateTo('hybrid://welcome').catch(console.error) 75 | }) 76 | 77 | webview.addEventListener('focus', () => { 78 | currentWindow.focus() 79 | }) 80 | 81 | webview.addEventListener('resize', ({ detail: rect }) => { 82 | currentWindow.setBounds(rect) 83 | }) 84 | 85 | currentWindow.on('navigating', (url) => { 86 | search.src = url 87 | }) 88 | 89 | currentWindow.on('history-buttons-change', updateButtons) 90 | 91 | currentWindow.on('page-title-updated', (title) => { 92 | pageTitle.innerText = title + ' - Hybrid Browser' 93 | }) 94 | currentWindow.on('enter-html-full-screen', () => { 95 | if (!rawFrame) nav.classList.toggle('hidden', true) 96 | webview.emitResize() 97 | }) 98 | currentWindow.on('leave-html-full-screen', () => { 99 | if (!rawFrame) nav.classList.toggle('hidden', false) 100 | webview.emitResize() 101 | }) 102 | currentWindow.on('update-target-url', async (url) => { 103 | // if(search.showTarget){ 104 | search.showTarget(url) 105 | // } 106 | }) 107 | currentWindow.on('browser-actions-changed', () => { 108 | actions.renderLatest() 109 | }) 110 | currentWindow.on('enter-full-screen', () => { 111 | if (!rawFrame) nav.classList.toggle('hidden', true) 112 | webview.emitResize() 113 | }) 114 | currentWindow.on('leave-full-screen', () => { 115 | if (!rawFrame) nav.classList.toggle('hidden', false) 116 | webview.emitResize() 117 | }) 118 | 119 | find.addEventListener('next', ({ detail }) => { 120 | const { value, findNext } = detail 121 | 122 | currentWindow.findInPage(value, { findNext }) 123 | }) 124 | 125 | find.addEventListener('previous', ({ detail }) => { 126 | const { value, findNext } = detail 127 | 128 | currentWindow.findInPage(value, { forward: false, findNext }) 129 | }) 130 | 131 | find.addEventListener('hide', () => { 132 | currentWindow.stopFindInPage('clearSelection') 133 | }) 134 | 135 | function updateButtons ({ canGoBack, canGoForward }) { 136 | search.setAttribute('back', canGoBack ? 'visible' : 'hidden') 137 | search.setAttribute('forward', canGoForward ? 'visible' : 'hidden') 138 | } 139 | 140 | function $ (query) { 141 | return document.querySelector(query) 142 | } 143 | 144 | async function navigateTo (url) { 145 | const currentURL = await currentWindow.getURL() 146 | if (currentURL === url) { 147 | console.log('Reloading') 148 | currentWindow.reload() 149 | } else { 150 | currentWindow.loadURL(url) 151 | currentWindow.focus() 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /app/ui/style.css: -------------------------------------------------------------------------------- 1 | @import url("hybrid://theme/vars.css"); 2 | 3 | :root { 4 | --top-height: 2.5em; 5 | --border-width: 1px; 6 | } 7 | 8 | html, body { 9 | width: 100%; 10 | height: 100%; 11 | padding: 0; 12 | margin: 0; 13 | display: flex; 14 | flex: 1; 15 | flex-direction: column; 16 | background: var(--hy-color-white); 17 | font-family: var(--hy-theme-font-family); 18 | } 19 | 20 | #view { 21 | flex:1 22 | } 23 | 24 | #toptop { 25 | display: flex; 26 | flex-direction: row; 27 | } 28 | 29 | #search { 30 | flex: 1; 31 | } 32 | 33 | .hidden { 34 | display: none !important; 35 | } 36 | 37 | omni-box { 38 | display: block 39 | } 40 | 41 | .omni-box-header { 42 | display: flex; 43 | flex-direction: row; 44 | border-bottom: var(--border-width) solid var(--hy-theme-primary); 45 | background: var(--hy-theme-background); 46 | color: var(--hy-theme-text); 47 | height: calc(100% - var(--border-width)); 48 | } 49 | 50 | .omni-box-form, .find-menu-form { 51 | display: flex; 52 | flex-direction: row; 53 | flex:1; 54 | border: none; 55 | } 56 | 57 | .omni-box-input, .find-menu-input, .omni-box-target-input { 58 | flex: 1; 59 | border:none; 60 | background: none; 61 | padding: 0.5em; 62 | color: inherit; 63 | font-size: inherit; 64 | font-family: inherit; 65 | } 66 | 67 | .nav-options { 68 | display: flex; 69 | flex-direction: column; 70 | margin: 0px; 71 | padding: 0px; 72 | border: var(--border-width) solid var(--hy-theme-primary); 73 | background: var(--hy-theme-background); 74 | color: var(--hy-theme-text); 75 | } 76 | 77 | .nav-options [data-selected] { 78 | border: 1px solid var(--hy-theme-secondary); 79 | } 80 | 81 | .nav-options:empty { 82 | display: none; 83 | } 84 | 85 | .omni-box-button, .find-menu-button, .browser-actions-button { 86 | color: inherit; 87 | font-size: inherit; 88 | padding: 0.5em; 89 | border: none; 90 | background: none; 91 | font-family: inherit; 92 | } 93 | 94 | .omni-box-nav-item { 95 | border: 1px solid var(--hy-theme-primary); 96 | display: flex; 97 | flex-direction: row; 98 | overflow: hidden; 99 | white-space: nowrap; 100 | text-overflow: ellipsis; 101 | } 102 | 103 | find-menu { 104 | border: var(--border-width) solid var(--hy-theme-primary); 105 | border-top: none; 106 | display: flex; 107 | flex-direction: row; 108 | background: var(--hy-theme-background); 109 | color: var(--hy-theme-text); 110 | } 111 | 112 | browser-actions { 113 | height: calc(var(--top-height) - calc(var(--border-width) * 3)); 114 | border-bottom: var(--border-width) solid var(--hy-theme-primary); 115 | border-left: var(--border-width) solid var(--hy-theme-primary); 116 | display: flex; 117 | flex-direction: row; 118 | background: var(--hy-theme-background); 119 | color: var(--hy-theme-text); 120 | justify-content: center; 121 | align-items: center; 122 | padding: var(--border-width); 123 | } 124 | .browser-actions-button { 125 | padding: 0 calc(var(--border-width) * 2); 126 | height: calc(100% - calc(var(--border-width) * 2)); 127 | width: auto; 128 | position: relative; 129 | } .browser-actions-button>img { 130 | height: 100%; 131 | width: auto; 132 | } 133 | .browser-actions-badge { 134 | border-radius: 0.25em; 135 | position: absolute; 136 | bottom: 0px; 137 | min-width: 1em; 138 | min-height: 1em; 139 | left: 50%; 140 | transform: translateX(-50%); 141 | background: var(--hy-theme-background); 142 | color: var(--hy-theme-text); 143 | } 144 | 145 | browser-actions:empty { 146 | display: none; 147 | } 148 | 149 | *:focus { 150 | outline: var(--border-width) solid var(--hy-theme-secondary); 151 | } 152 | 153 | *::-webkit-scrollbar { 154 | width: 1em; 155 | background: var(--hy-theme-background); 156 | } 157 | 158 | *::-webkit-scrollbar-corner { 159 | background: rgba(0,0,0,0); 160 | } 161 | 162 | *::-webkit-scrollbar-thumb { 163 | background-color: var(--hy-theme-primary); 164 | border: 2px solid transparent; 165 | background-clip: content-box; 166 | } 167 | *::-webkit-scrollbar-track { 168 | background-color: rgba(0,0,0,0); 169 | } 170 | -------------------------------------------------------------------------------- /app/ui/tracked-box.js: -------------------------------------------------------------------------------- 1 | /* global HTMLElement, ResizeObserver, CustomEvent, customElements */ 2 | 3 | class TrackedBox extends HTMLElement { 4 | constructor () { 5 | super() 6 | 7 | this.observer = new ResizeObserver(() => this.emitResize()) 8 | } 9 | 10 | connectedCallback () { 11 | this.observer.observe(this) 12 | 13 | this.emitResize() 14 | } 15 | 16 | disconnectedCallback () { 17 | this.observer.unobserve(this) 18 | } 19 | 20 | emitResize () { 21 | const { x, y, width, height } = this.getBoundingClientRect() 22 | 23 | this.dispatchEvent(new CustomEvent('resize', { detail: { x, y, width, height } })) 24 | } 25 | } 26 | 27 | customElements.define('tracked-box', TrackedBox) 28 | -------------------------------------------------------------------------------- /app/version.js: -------------------------------------------------------------------------------- 1 | 2 | export const name = 'hybrid-browser' 3 | export const version = '3.0.5' 4 | export const dependencies = { 5 | "@chainsafe/libp2p-gossipsub": "^14.1.0", 6 | "@derhuerst/gemini": "^2.0.0", 7 | "@helia/unixfs": "^4.0.2", 8 | "@libp2p/bootstrap": "^11.0.32", 9 | "@libp2p/identify": "^3.0.15", 10 | "@libp2p/kad-dht": "^14.2.0", 11 | "@libp2p/tcp": "^10.1.8", 12 | "abort-controller": "^3.0.0", 13 | "blockstore-fs": "^2.0.2", 14 | "create-desktop-shortcuts": "^1.11.0", 15 | "data-uri-to-buffer": "^6.0.2", 16 | "datastore-fs": "^10.0.2", 17 | "decompress": "^4.2.1", 18 | "delay": "^6.0.0", 19 | "detect-port": "^2.1.0", 20 | "electron-extended-webextensions": "github:HybridWare/electron-extended-WebExtensions", 21 | "event-iterator": "^2.0.0", 22 | "fs-extra": "^11.3.0", 23 | "gopher-lib": "^0.2.0", 24 | "helia": "^5.2.0", 25 | "http-proxy-agent": "^7.0.2", 26 | "hyper-sdk": "^5.1.0", 27 | "ipfs-pubsub-room": "github:ducksandgoats/ipfs-pubsub-room", 28 | "mime": "^4.0.6", 29 | "multiformats": "^9.9.0", 30 | "node-fetch": "^3.3.2", 31 | "p-queue": "^8.1.0", 32 | "range-parser": "^1.2.1", 33 | "rc": "^1.2.8", 34 | "sanitize-filename": "^1.6.3", 35 | "scoped-fs": "^1.4.1", 36 | "semver": "^7.7.0", 37 | "socks-proxy-agent": "^8.0.5", 38 | "streamx": "^2.22.0", 39 | "torrentz": "^20.0.4", 40 | "uint8-util": "^2.2.5", 41 | "whatwg-mimetype": "github:jsdom/whatwg-mimetype" 42 | } 43 | -------------------------------------------------------------------------------- /app/window.js: -------------------------------------------------------------------------------- 1 | import { 2 | BrowserWindow, 3 | BrowserView, 4 | ipcMain, 5 | app 6 | } from 'electron' 7 | import path from 'node:path' 8 | import EventEmitter from 'node:events' 9 | import { fileURLToPath } from 'node:url' 10 | 11 | import fs from 'fs-extra' 12 | import PQueue from 'p-queue' 13 | import delay from 'delay' 14 | 15 | import Config from './config.js' 16 | 17 | const IS_DEBUG = process.env.NODE_ENV === 'debug' 18 | 19 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 20 | 21 | const MAIN_PAGE = path.join(__dirname, './ui/index.html') 22 | const LOGO_FILE = path.join(__dirname, './../build/icon-small.png') 23 | const PERSIST_FILE = path.join(app.getPath('userData'), 'lastOpened.json') 24 | 25 | const DEFAULT_SAVE_INTERVAL = 30 * 1000 26 | 27 | // See if we have any stylesheets with rules 28 | // If not manually inject styles to be like Hybrid 29 | const HAS_SHEET = ` 30 | [...document.styleSheets].filter((sheet) => { 31 | try {sheet.cssRules; return true} catch {return false} 32 | }).length || !!document.querySelector('[style]') 33 | ` 34 | 35 | const WINDOW_METHODS = [ 36 | 'goBack', 37 | 'goForward', 38 | 'reload', 39 | 'focus', 40 | 'loadURL', 41 | 'getURL', 42 | 'findInPage', 43 | 'stopFindInPage', 44 | 'setBounds', 45 | 'searchHistoryStart', 46 | 'searchHistoryNext', 47 | 'listExtensionActions', 48 | 'clickExtensionAction' 49 | ] 50 | 51 | const BLINK_FLAGS = [ 52 | 'WebBluetooth', 53 | 'WebBluetoothGetDevices', 54 | 'WebBluetoothRemoteCharacteristicNewWriteValue', 55 | 'WebBluetoothWatchAdvertisements', 56 | 'CSSModules' 57 | ].join(',') 58 | 59 | async function DEFAULT_SEARCH () { 60 | return [] 61 | } 62 | 63 | async function DEFAULT_LIST_ACTIONS () { 64 | return [] 65 | } 66 | 67 | // How long to wait before showing windows 68 | const SHOW_DELAY = 200 69 | 70 | // Used to only show one window at a time 71 | const showQueue = new PQueue({ concurrency: 1 }) 72 | 73 | export class WindowManager extends EventEmitter { 74 | constructor ({ 75 | onSearch = DEFAULT_SEARCH, 76 | listActions = DEFAULT_LIST_ACTIONS, 77 | persistTo = PERSIST_FILE, 78 | saverInterval = DEFAULT_SAVE_INTERVAL 79 | } = {}) { 80 | super() 81 | this.windows = new Set() 82 | this.onSearch = onSearch 83 | this.listActions = listActions 84 | this.persistTo = persistTo 85 | this.saverTimer = null 86 | this.saverInterval = saverInterval 87 | 88 | for (const method of WINDOW_METHODS) { 89 | this.relayMethod(method) 90 | } 91 | } 92 | 93 | open (opts = {}) { 94 | const { onSearch, listActions } = this 95 | const window = new Window({ 96 | onSearch, 97 | listActions, 98 | ...opts 99 | }) 100 | 101 | if (IS_DEBUG) console.log('created window', window.id) 102 | this.windows.add(window) 103 | window.once('close', () => { 104 | this.windows.delete(window) 105 | this.emit('close', window) 106 | }) 107 | window.on('navigating', () => { 108 | this.restartSaver() 109 | }) 110 | this.emit('open', window) 111 | 112 | window.load() 113 | 114 | return window 115 | } 116 | 117 | relayMethod (name) { 118 | ipcMain.handle(`hybrid-window-${name}`, ({ sender }, ...args) => { 119 | const { id } = sender 120 | if (IS_DEBUG) console.log('<-', id, name, '(', args, ')') 121 | const window = this.get(id) 122 | if (!window) return console.warn(`Got method ${name} from invalid frame ${id}`) 123 | return window[name](...args) 124 | }) 125 | } 126 | 127 | reloadBrowserActions (tabId) { 128 | for (const window of this.all) { 129 | if (tabId) { 130 | if (window.web.id === tabId) { 131 | window.send('browser-actions-changed') 132 | } 133 | } else { 134 | window.send('browser-actions-changed') 135 | } 136 | } 137 | } 138 | 139 | get (id) { 140 | for (const window of this.windows) { 141 | if (window.id === id) return window 142 | } 143 | return null 144 | } 145 | 146 | get all () { 147 | return [...this.windows.values()] 148 | } 149 | 150 | saveOpened () { 151 | console.log('Saving open windows') 152 | let urls = [] 153 | for (const window of this.all) { 154 | // We don't need to save popups from extensions 155 | if (window.rawFrame) continue 156 | const url = window.web.getURL() 157 | const position = window.window.getPosition() 158 | const size = window.window.getSize() 159 | 160 | urls.push({ url, position, size }) 161 | } 162 | 163 | if (urls.length === 1) urls = [] 164 | 165 | fs.outputJsonSync(this.persistTo, urls) 166 | } 167 | 168 | async openSaved () { 169 | const saved = await this.loadSaved() 170 | 171 | return saved.map((info) => { 172 | console.log('About to open', info) 173 | const options = { 174 | noFocus: true 175 | } 176 | 177 | const { url, position, size } = info 178 | 179 | options.url = url 180 | 181 | if (position) { 182 | const [x, y] = position 183 | options.x = x 184 | options.y = y 185 | } 186 | 187 | if (size) { 188 | const [width, height] = size 189 | options.width = width 190 | options.height = height 191 | } 192 | 193 | const window = this.open(options) 194 | 195 | return window 196 | }) 197 | } 198 | 199 | async loadSaved () { 200 | try { 201 | const infos = await fs.readJson(this.persistTo) 202 | return infos 203 | } catch (e) { 204 | console.error('Error loading saved windows', e.stack) 205 | return [] 206 | } 207 | } 208 | 209 | close () { 210 | this.clearSaver() 211 | } 212 | 213 | restartSaver () { 214 | this.clearSaver() 215 | this.startSaver() 216 | } 217 | 218 | startSaver () { 219 | this.saverTimer = setTimeout(() => { 220 | this.saveOpened() 221 | }, this.saverInterval) 222 | } 223 | 224 | clearSaver () { 225 | clearInterval(this.saverTimer) 226 | } 227 | } 228 | 229 | export class Window extends EventEmitter { 230 | #searchIterator = null 231 | constructor ({ 232 | url = Config.defaultPage, 233 | popup = false, 234 | rawFrame = false || popup, 235 | autoResize = false || popup, 236 | noNav = false, 237 | noFocus = false, 238 | onSearch, 239 | listActions, 240 | view, 241 | autoHideMenuBar = Config.autoHideMenuBar || popup, 242 | ...opts 243 | } = {}) { 244 | super() 245 | 246 | this.onSearch = onSearch 247 | this.listActions = listActions 248 | this.rawFrame = rawFrame 249 | 250 | this.window = new BrowserWindow({ 251 | autoHideMenuBar, 252 | webPreferences: { 253 | // partition: 'persist:web-content', 254 | defaultEncoding: 'utf-8', 255 | nodeIntegration: true, 256 | webviewTag: false, 257 | contextIsolation: false 258 | }, 259 | show: false, 260 | icon: LOGO_FILE, 261 | ...opts 262 | }) 263 | this.view = view || new BrowserView({ 264 | webPreferences: { 265 | partition: 'persist:web-content', 266 | defaultEncoding: 'utf-8', 267 | nodeIntegration: false, 268 | nodeIntegrationInSubFrames: true, 269 | sandbox: true, 270 | webviewTag: false, 271 | contextIsolation: true, 272 | enableBlinkFeatures: BLINK_FLAGS, 273 | enablePreferredSizeMode: autoResize 274 | } 275 | }) 276 | 277 | this.window.setBrowserView(this.view) 278 | 279 | this.web.on('did-start-navigation', (event, url, isInPlace, isMainFrame) => { 280 | this.emitNavigate(url, isMainFrame) 281 | }) 282 | this.web.on('did-navigate', (event, url) => { 283 | this.emitNavigate(url, true) 284 | }) 285 | this.web.on('did-navigate-in-page', (event, url, isMainFrame) => { 286 | this.emitNavigate(url, isMainFrame) 287 | }) 288 | 289 | if (autoResize) { 290 | let reloaded = false 291 | this.web.on('preferred-size-changed', (event, preferredSize) => { 292 | const { width, height } = preferredSize 293 | if (IS_DEBUG) console.log('Preferred size', this.id, preferredSize) 294 | this.window.setSize(width, height, false) 295 | this.view.setBounds({ 296 | x: 0, 297 | y: 0, 298 | width, 299 | height 300 | }) 301 | 302 | if (!reloaded) { 303 | reloaded = true 304 | this.web.invalidate() 305 | } 306 | }) 307 | } 308 | 309 | if (popup) { 310 | this.web.focus() 311 | this.window.once('blur', () => { 312 | if (this.web.isFocused() || this.webContents.isFocused()) return 313 | if (this.web.isDevToolsOpened() || this.webContents.isDevToolsOpened()) return 314 | this.window.close() 315 | }) 316 | } 317 | 318 | // Send to UI 319 | this.web.on('page-title-updated', (event, title) => { 320 | this.send('page-title-updated', title) 321 | }) 322 | this.window.on('enter-html-full-screen', () => { 323 | this.send('enter-html-full-screen') 324 | }) 325 | this.window.on('leave-html-full-screen', () => { 326 | this.send('leave-html-full-screen') 327 | }) 328 | this.web.on('update-target-url', (event, url) => { 329 | this.send('update-target-url', url) 330 | }) 331 | this.window.on('enter-full-screen', () => { 332 | this.send('enter-full-screen') 333 | }) 334 | this.window.on('leave-full-screen', () => { 335 | this.send('leave-full-screen') 336 | }) 337 | 338 | this.web.on('dom-ready', async () => { 339 | if (this.web.getURL() === 'hybrid://settings') { 340 | this.web.executeJavaScript(`window.onSettings(${JSON.stringify(Config)})`) 341 | } 342 | const hasStyles = await this.web.executeJavaScript(HAS_SHEET, true).catch(() => false) // If we error out checking styles, try it anyway 343 | if (!hasStyles) { 344 | const style = await getDefaultStylesheet(this.web) 345 | await this.web.insertCSS(style, { 346 | cssOrigin: 'user' 347 | }) 348 | } 349 | }) 350 | 351 | this.web.once('dom-ready', () => { 352 | showQueue.add(async () => { 353 | await this.window.show() 354 | await delay(SHOW_DELAY) 355 | }) 356 | }) 357 | this.window.on('close', () => { 358 | this.web.destroy() 359 | this.emit('close') 360 | }) 361 | 362 | const toLoad = new URL(MAIN_PAGE, 'file:') 363 | 364 | if (url) toLoad.searchParams.set('url', url) 365 | if (rawFrame) toLoad.searchParams.set('rawFrame', 'true') 366 | if (noNav) toLoad.searchParams.set('noNav', 'true') 367 | if (noFocus) toLoad.searchParams.set('noFocus', 'true') 368 | 369 | this.toLoad = toLoad.href 370 | } 371 | 372 | load () { 373 | return this.window.loadURL(this.toLoad) 374 | } 375 | 376 | emitNavigate (url, isMainFrame) { 377 | if (!isMainFrame) return 378 | if (IS_DEBUG) console.log('Navigating', url) 379 | const canGoBack = this.web.canGoBack() 380 | const canGoForward = this.web.canGoForward() 381 | 382 | this.send('navigating', url) 383 | this.send('history-buttons-change', { canGoBack, canGoForward }) 384 | } 385 | 386 | async goBack () { 387 | return this.web.goBack() 388 | } 389 | 390 | async goForward () { 391 | return this.web.goForward() 392 | } 393 | 394 | async reload () { 395 | return this.web.reload() 396 | } 397 | 398 | async focus () { 399 | return this.web.focus() 400 | } 401 | 402 | async loadURL (url) { 403 | return this.web.loadURL(url) 404 | } 405 | 406 | async getURL () { 407 | return this.web.getURL() 408 | } 409 | 410 | async findInPage (value, opts) { 411 | return this.web.findInPage(value, opts) 412 | } 413 | 414 | async stopFindInPage () { 415 | return this.web.stopFindInPage('clearSelection') 416 | } 417 | 418 | async searchHistoryStart (...args) { 419 | this.#searchIterator = this.onSearch(...args) 420 | } 421 | 422 | async searchHistoryNext () { 423 | if (!this.#searchIterator) return { done: true, value: null } 424 | try { 425 | const { done, value } = await this.#searchIterator.next() 426 | if (done) this.#searchIterator = null 427 | return { done, value } 428 | } catch (e) { 429 | console.error('Error getting next history item') 430 | throw e 431 | } 432 | } 433 | 434 | async setBounds (rect) { 435 | // Fix non-integer heights causing draw break. 436 | // TODO: This should be fixed wherever rect is sent from, not sure where that is. 437 | Object.keys(rect).forEach(key => { 438 | rect[key] = Math.floor(rect[key]) 439 | }) 440 | 441 | return this.view.setBounds(rect) 442 | } 443 | 444 | async listExtensionActions () { 445 | const actions = await this.listActions(this) 446 | return actions.map(({ 447 | title, 448 | extensionId: id, 449 | icon, 450 | badge, 451 | badgeColor, 452 | badgeBackground 453 | }) => { 454 | return { 455 | title, 456 | id, 457 | icon, 458 | badge: { 459 | text: badge, 460 | color: badgeColor, 461 | background: badgeBackground 462 | } 463 | } 464 | }) 465 | } 466 | 467 | async clickExtensionAction (actionId) { 468 | await this.focus() 469 | for (const { extensionId, onClick } of await this.listActions()) { 470 | if (actionId !== extensionId) continue 471 | await onClick(this.web.id) 472 | } 473 | } 474 | 475 | send (name, ...args) { 476 | this.emit(name, ...args) 477 | if (IS_DEBUG) console.log('->', this.id, name, '(', args, ')') 478 | this.window.webContents.send(`hybrid-window-${name}`, ...args) 479 | } 480 | 481 | get web () { 482 | return this.view.webContents 483 | } 484 | 485 | get webContents () { 486 | return this.window.webContents 487 | } 488 | 489 | get id () { 490 | return this.window.webContents.id 491 | } 492 | } 493 | 494 | async function getDefaultStylesheet (webContents) { 495 | const [r1, r2] = await Promise.all([ 496 | webContents.session.fetch('hybrid://theme/vars.css'), 497 | webContents.session.fetch('hybrid://theme/style.css') 498 | ]) 499 | 500 | const [vars, style] = await Promise.all([ 501 | r1.text(), 502 | r2.text() 503 | ]) 504 | return vars + style 505 | } 506 | -------------------------------------------------------------------------------- /build/generate-logo.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const WHITE = '#FCFCFC' 4 | const BLACK = '#111' 5 | const PURPLE = 'rgb(165, 24, 201)' 6 | 7 | const GOLD = 1.61803398874989 8 | const DIAMETER = 666 9 | const TRUE_RADIUS = DIAMETER / 2 10 | const RADIUS = DIAMETER / (GOLD * 2.5) 11 | const THICKNESS = DIAMETER / (GOLD * 13) 12 | const INNER = THICKNESS * GOLD 13 | const POINT_WIDTH = 360 / 32 14 | 15 | console.log(` 16 | 25 | 55 | 56 | 57 | 58 | 59 | 60 | ${makeRays(8, TRUE_RADIUS - INNER - THICKNESS, INNER)} 61 | 62 | ${makePoints(8, TRUE_RADIUS, POINT_WIDTH, THICKNESS * 2)} 63 | 64 | 65 | `) 66 | 67 | function makeRays (n, outer, inner, offset = 0) { 68 | return makeCorners(n, offset).map((theta) => makeRay(theta, outer, inner)).join('\n') 69 | } 70 | 71 | function makeRay (theta, outer, inner) { 72 | return `\t` 73 | } 74 | 75 | function makePoints (n, scale, width, size = THICKNESS, offset = 0) { 76 | return makeCorners(n, offset).map((theta) => { 77 | return makePoint(theta, scale, width, size) 78 | }).join('\n') 79 | } 80 | 81 | function makePoint (theta, scale, width, size = THICKNESS) { 82 | const pointX = (xAt(theta) * scale).toFixed(6) 83 | const leftX = (xAt(theta - width) * (scale - size)).toFixed(6) 84 | const rightX = (xAt(theta + width) * (scale - size)).toFixed(6) 85 | 86 | const pointY = (yAt(theta) * scale).toFixed(6) 87 | const leftY = (yAt(theta - width) * (scale - size)).toFixed(6) 88 | const rightY = (yAt(theta + width) * (scale - size)).toFixed(6) 89 | 90 | const path = `M ${leftX} ${leftY} L ${pointX} ${pointY} L ${rightX} ${rightY} Z` 91 | 92 | return `\t` 93 | } 94 | 95 | function makeCorners (n, offset = 0) { 96 | const increment = 360 / n 97 | const corners = [] 98 | for (let i = 0; i < n; i++) { 99 | corners.push(i * increment + offset) 100 | } 101 | 102 | return corners 103 | } 104 | 105 | function linePoint (theta, scale = 0, index = '') { 106 | return `x${index}="${(xAt(theta) * scale).toFixed(6)}" y${index}="${(yAt(theta) * scale).toFixed(6)}"` 107 | } 108 | 109 | /* 110 | function makeDots (n, scale, offset = 0) { 111 | return makeCorners(n, offset).map((theta) => { 112 | return `\t` 113 | }).join('\n') 114 | } 115 | 116 | function centerPoint (theta, scale = 0) { 117 | return `cx="${xAt(theta) * scale}" cy="${yAt(theta) * scale}"` 118 | } 119 | */ 120 | 121 | function xAt (theta) { 122 | return Math.cos(toRad(theta)) 123 | } 124 | 125 | function yAt (theta) { 126 | return Math.sin(toRad(theta)) 127 | } 128 | 129 | function toRad (theta) { 130 | return Math.PI / 180 * theta 131 | } 132 | -------------------------------------------------------------------------------- /build/icon-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/build/icon-small.png -------------------------------------------------------------------------------- /build/icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/build/icon.ico -------------------------------------------------------------------------------- /build/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/build/icon.png -------------------------------------------------------------------------------- /build/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 4 | 7 | 8 | 10 | 13 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /build/icons/512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HybridWare/hybrid-browser/65f82c650cfa3638522bf6ce2f71bcea195ccd17/build/icons/512x512.png -------------------------------------------------------------------------------- /docs/Bookmarks.md: -------------------------------------------------------------------------------- 1 | # Bookmarks 2 | 3 | Bookmarks are stored as files. If you wish to specify the path to hybrid set the `appPath` property in your `.hybridrc` config file. You may need to do this if you've moved an hybrid AppImage to `/usr/bin` for example. 4 | 5 | This can be done by pressing `ALT` to bring up the menu and then clicking `Help > Edit Configuration File`, then adding in the following contents: 6 | 7 | ```json 8 | { 9 | "appPath": "/usr/bin/or/wherever/hybrid-browser" 10 | } 11 | ``` -------------------------------------------------------------------------------- /docs/Extensions.md: -------------------------------------------------------------------------------- 1 | # Installing extensions 2 | 3 | Hybrid doesn't yet support loading extensions from app stores or zip files, but you can place the extracted extensions inside a folder for it to load. 4 | 5 | Click on `Help > Open Extension Folder` in the application menu on any window to open up your extensions folder. 6 | 7 | You can drop folders in here to have them load when Hybrid starts up. 8 | 9 | For a list of APIs that are supported, please look at the [Electron Extensions](https://github.com/sentialx/electron-extensions/issues/14) module. 10 | 11 | Hybrid comes with two built-in extensions. A basic ad blocker, and the history tracking extension. 12 | 13 | You can change the location of your extensions folder by editing your `.hybridrc` config file. 14 | 15 | This can be done by clicking `Help > Edit Configuration File`, then adding in the following contents: 16 | 17 | ```json 18 | { 19 | "extensions": { 20 | "dir": "/your/extensions/folder/here" 21 | } 22 | } 23 | ``` 24 | -------------------------------------------------------------------------------- /docs/Fetch-Gemini.md: -------------------------------------------------------------------------------- 1 | # Fetch API for `gemini://` 2 | 3 | ### `fetch('gemini://hostname/path')` 4 | 5 | You can currently only fetch pages from Gemini. 6 | The status codes from requests are multiplied by `10`. 7 | When the interface returns a `text/gemini` page, it will be rendered to HTML with hybrid-provided styling. 8 | `100` and `110` status codes mean that you should be supplying data in the query string of the URL. 9 | There's currently no support for certificate management stuff. 10 | -------------------------------------------------------------------------------- /docs/Fetch-Hyper.md: -------------------------------------------------------------------------------- 1 | # Fetch API for `hyper://` 2 | 3 | This API is implemented in [dat-fetch](https://github.com/RangerMauve/dat-fetch) 4 | 5 | ### Common Headers 6 | 7 | Each response will contain a header for the canonical URL represented as a `Link` header with `rel=canonical`. 8 | 9 | Each response will also contain the `Allow` header of all the methods currently allowed. If the archive is writable, this will contain `PUT`. 10 | 11 | There is also an `ETag` header which will be a JSON string containing the drive's current `version`. This will change only when the drive has gotten an update of some sort and is monotonically incrementing. 12 | 13 | ### `fetch('hyper://NAME/example.txt', {method: 'GET'})` 14 | 15 | This will attempt to load `example.txt` from the archive labeled by `NAME`. 16 | 17 | It will also load `index.html` files automatically for a folder. 18 | You can find the details about how resolution works in the [resolve-dat-path](https://github.com/RangerMauve/resolve-dat-path/blob/master/index.js#L3) module. 19 | 20 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 21 | 22 | The response headers will contain `X-Blocks` for the number of blocks of data this file represents on disk, and `X-Blocks-Downloaded` which is the number of blocks from this file that have been downloaded locally. 23 | 24 | ### `fetch('hyper://NAME/.well-known/dat', {method: 'GET'})` 25 | 26 | This is used by the dat-dns module for resolving dns domains to `dat://` URLs. 27 | 28 | This will return some text which will have a `dat://` URL of your archive, followed by a newline and a TTL for the DNS record. 29 | 30 | ### `fetch('hyper://NAME/example/', {method: 'GET'})` 31 | 32 | When doing a `GET` on a directory, you will get a directory listing. 33 | 34 | By default it will render out an HTML page with links to files within that directory. 35 | 36 | You can set the `Accept` header to `application/json` in order to have it return a JSON array with file names. 37 | 38 | e.g. 39 | 40 | ```json 41 | ["example.txt", "posts/", "example2.md"] 42 | ``` 43 | 44 | Files in the directory will be listed under their name, sub-directories will have a `/` appended to them. 45 | 46 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 47 | 48 | ### `fetch('hyper://NAME/example.txt', {method: 'GET', headers: {'X-Resolve': 'none'}})` 49 | 50 | Setting the `X-Resolve` header to `none` will prevent resolving `index.html` files and will attempt to load the path as is. 51 | This can be useful for list files in a directory that would normally render as a page. 52 | 53 | You should omit the header for the default behavior, different values may be supported in the future. 54 | 55 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 56 | 57 | The response headers will contain `X-Blocks` for the number of blocks of data this file represents on disk, and `X-Blocks-Downloaded` which is the number of blocks from this file that have been downloaded locally. 58 | 59 | ### `fetch('hyper://NAME/example.txt', {method: 'PUT', body: 'Hello World'})` 60 | 61 | You can add files to archives using a `PUT` method along with a `body`. 62 | 63 | The `body` can be either a `String`, an `ArrayBuffer`, a `Blob`, a WHATWG `ReadableStream`, a Node.js `Stream`, 64 | or electron's [UploadData](https://www.electronjs.org/docs/api/structures/upload-data) object (make sure to specify the `session` argument in the `makeFetch` function for electron support). 65 | 66 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 67 | 68 | Your `NAME` will likely be a `name` in most cases to ensure you have a writeable archive. 69 | 70 | ### `fetch('hyper://NAME/example.txt', {method: 'DELETE'})` 71 | 72 | You can delete a file in an archive by using the `DELETE` method. 73 | 74 | You cannot delete directories if they are not empty. 75 | 76 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 77 | 78 | ### `fetch('hyper://NAME/example.txt', {method: 'DOWNLOAD'})` 79 | 80 | You can download a file or an entire folder using the `DOWNLOAD` method. 81 | 82 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 83 | 84 | You can use `/` for the path to download the entire contents 85 | 86 | ### `fetch('hyper://NAME/example.txt', {method: 'CLEAR'})` 87 | 88 | You can clear the data stored for a file using the `CLEAR` method. 89 | 90 | This is like the opposite of the `DOWNLOAD` method. 91 | 92 | This does not delete data, it only deletes the cached data from disk. 93 | 94 | `NAME` can either be the 64 character hex key for an archive, a domain to parse with [dat-dns](https://www.npmjs.com/package/dat-dns), or a name for an archive which allows you to write to it. 95 | 96 | You can use `/` for the path to clear all data for the archive. 97 | 98 | ### `fetch('hyper://NAME/`, {method: 'TAG', body: 'Tag name here'})` 99 | 100 | You can add a tag a version of the archive with a human readable name (like SPAGHETTI). 101 | 102 | You can place the name of the tag into the `body` of the request. 103 | 104 | Afterwards you can load the archive at that given version with `hyper://NAME+TAG_NAME`. E.g. `hyper://123kjh213kjh123+v4.20/example.txt` 105 | 106 | ### `fetch('hyper://NAME/', {method: 'TAGS'})` 107 | 108 | You can get a list of all tags using the `TAGS` method. 109 | 110 | The response will be a JSON object which maps tag names to archive versions. 111 | 112 | Use `await response.json()` to get the data out. 113 | 114 | ### `fetch('hyper://NAME+TAG_NAME/', {method: 'TAG-DELETE'})` 115 | 116 | You can delete a given tag with the `TAG-DELETE` method. 117 | 118 | Specify the tag you want in the URL, and it'll be removed from the tags list. 119 | -------------------------------------------------------------------------------- /docs/Fetch-IPFS.md: -------------------------------------------------------------------------------- 1 | # Fetch API for `ipfs://` and `ipns://` 2 | 3 | This API is implemented in [js-ipfs-fetch](https://github.com/RangerMauve/js-ipfs-fetch). 4 | 5 | ## Example 6 | 7 | ```javascript 8 | // Upload some data to IPFS 9 | const response1 = await fetch(`ipfs:///index.html`, { 10 | method: 'POST', 11 | body: ` 12 | 13 | 14 | Hello World! 15 | 16 | Hello World! 17 | 18 | Hello World! 19 | 20 | 21 | 22 | ` 23 | }) 24 | 25 | const url = await response1.text() 26 | 27 | // Should look like this: 28 | // ipfs://k2jmtxw856nqrm9pc7up4acmbtco1muuenxjy1lkv9x6rsxd1zclki9m/index.html 29 | console.log('IPFS URL:', url) 30 | 31 | // You can load the data back up 32 | const response2 = await fetch(url) 33 | 34 | console.log('Uploaded content', await response2.text()) 35 | 36 | // Get the root of the new IPFS site you created 37 | // This with automagically serve the `index.html` file when you navigate to it 38 | const root = new URL('/', url).href 39 | 40 | // Publish to IPNS 41 | // `ExampleName` can be any name, it'll be used to generate a keypair 42 | // Instead of exposing private keys directly, you can use the key names wherever you need 43 | const response3 = await fetch(`ipns://ExampleName`, { 44 | method: 'PUBLISH', 45 | body: root 46 | }) 47 | 48 | // Should look something like this: 49 | // ipns://k2jmtxu20rj3axf43s36u7r9ds7fsgy5djbdxmuhnfyan2dgom9cil72/ 50 | // Every time you PUBLISH a new version, the URL will stay the same for the given key 51 | const ipnsURL = await response3.text() 52 | 53 | console.log('Published URL', ipnsURL) 54 | ``` 55 | 56 | ### `await fetch('ipfs://CID/example.txt')` 57 | 58 | If you specify a URL for a file (no trailing slashes), it will be loaded from IPFS and the content will be sent as the response body. 59 | 60 | The response headers will contain a `Content-Length` header set to the size of the file. 61 | 62 | ### `await fetch('ipfs://CID/example/')` 63 | 64 | If you specify a URL for a folder (has a trailing slash), the folder will be enumerated from IPFS and an HTML page listing its various files will be rendered. 65 | 66 | Hyperlinks to files/folders will be automatically generated as relative URLs. 67 | 68 | Links will have a trailing slash for folders. 69 | 70 | If the folder contains an `index.html` it will be served as a file instead of performing a directory listing. 71 | 72 | ### `await fetch('ipfs://CID/example/', {headers: {'X-Resolve': none}})` 73 | 74 | If you specify the `X-Resolve: none` header in your request, the resolution of `index.html` will be ignored and a directory listing will always be performed. 75 | 76 | ### `await fetch('ipfs://CID/example/', {headers: {Accept: 'application/json'}})` 77 | 78 | If you specify a URL for a folder, and set the `Accept` header to only contain `application/json`, the directory will be enumerated and the list of files/folders will be returned as a JSON array. 79 | 80 | You can get the file/folder list out of the response using `await response.json()`. 81 | 82 | Names will have a trailing slash for folders. 83 | 84 | ### `await fetch('ipfs://CID/example.txt', {method: 'HEAD'})` 85 | 86 | If you set the method to `HEAD`, it will be like doing a `GET` request but without actually loading data. 87 | 88 | This is useful for getting the `Content-Length` or checking if a file exists. 89 | 90 | ### `await fetch('ipfs://CID/example.txt', { headers: { Range: 'bytes=0-4' })` 91 | 92 | You can specify the `Range` header when making a request to load a subset of a file. 93 | 94 | ### `await fetch('ipfs:///example.txt', {methhod: 'post', body: 'Hello World!'})` 95 | 96 | You can upload files to IPFS by using `POST` messages. 97 | 98 | The response body will contain the `ipfs://` URL for your data. 99 | 100 | Please open a GitHub issue if you have ideas for how to support multiple files in a fetch-compliant way. 101 | 102 | ### `await fetch('ipns://CID/example.txt')` 103 | 104 | You can specify an IPNS URL to have it resolve to whatever resource you wanted using the Inter-Planetary Naming System 105 | 106 | ### `await fetch('ipns://self', {method: 'publish', body: 'ipfs://CID/example.txt'})` 107 | 108 | You can publish to IPNS using the `PUBLISH` method. 109 | 110 | The `body` should contain the `ipfs://` URL you want to point to. 111 | 112 | The response will be an `ipns://` URL for your data. 113 | 114 | It's best to point at directories when possible so that they can be treated as origins within browser contexts. 115 | 116 | Specify the key name in the `origin` portion of the ipns URL. 117 | If the key doesn't exist, it will ge generated. 118 | 119 | Please open a GitHub issue if you have ideas for how to do key import and export. 120 | -------------------------------------------------------------------------------- /docs/Keyboard-Shortcuts.md: -------------------------------------------------------------------------------- 1 | # Configuring keyboard shortcuts 2 | 3 | Hybrid uses the [rc](https://www.npmjs.com/package/rc#standards) module for loading configuration. 4 | 5 | There's a bunch of functionality in there, but the short of it is that you can use the following as a starting point for your configuration. 6 | 7 | Save this as a file called `.hybridrc` in your "home" or "user" folder. 8 | 9 | You can open this file by navigating to `Help > Edit Configuration File`. 10 | 11 | ```json 12 | { 13 | "accelerators": { 14 | "OpenDevTools": "CommandOrControl+Shift+I", 15 | "NewWindow": "CommandOrControl+N", 16 | "Forward": "CommandOrControl+]", 17 | "Back": "CommandOrControl+[", 18 | "FocusURLBar": "CommandOrControl+L", 19 | "FindInPage": "CommandOrControl+F", 20 | "Reload": "CommandOrControl+R", 21 | "HardReload": "CommandOrControl+Shift+R" 22 | } 23 | } 24 | ``` 25 | 26 | The accelerators section maps names of actions to [keyboard shortcuts](https://www.electronjs.org/docs/api/accelerator). 27 | 28 | You can set these to whatever you want and it will override the defaults listed above. 29 | 30 | Check out `app/actions.js` for a full list of action names since some of them don't have keyboard shortcuts by default. 31 | -------------------------------------------------------------------------------- /docs/Protocols.md: -------------------------------------------------------------------------------- 1 | # Supported protocols 2 | 3 | - [x] `hyper://` [Hypercore](https://hypercore-protocol.org/) 4 | - Able to read from archives 5 | - Able to resolve `dat-dns` domains 6 | - Able to write, create and modify archives 7 | - [x] `dat://` 8 | - Able to read from archives 9 | - Able to resolve `dat-dns` domains 10 | - No `DatArchive` support. 11 | - [x] `gemini://` [Gemini](https://gemini.circumlunar.space/) 12 | - Able to read from gemini servers 13 | - Render Gemini pages as HTML 14 | - No certificate management code yet 15 | - [x] ipfs 16 | - Able to read from `ipfs://` and `ipns://` URLs 17 | - Able to `POST` data into `IPFS` 18 | - Able to `PUBLISH` an infohash to IPNS 19 | - [x] BitTorrent 20 | - Able to read from `bittorrent://` URLs 21 | - Able to redirect `magnet:` URIs to `bittorrent://` URLs 22 | - [ ] [EarthStar](https://github.com/earthstar-project/earthstar) 23 | - [ ] [Pigeon Protocol](https://tildegit.org/PigeonProtocolConsortium/protocol_spec) 24 | 25 | PRs for more protocols are welcome. 26 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Hybrid Documentation 2 | 3 | - [Installing and using extensions](Extensions.md) 4 | - [Configuring keyboard shortcuts](Keyboard-Shortcuts.md) 5 | - [Configuring and using the browser theme](Theming.md) 6 | - [Details about the protocols Hybrid supports and will support](Protocols.md) 7 | - [Using the fetch API with the `hyper://` protocol](Fetch-Hyper.md) 8 | - [Using the fetch API with the `gemini://` protocol](Fetch-Gemini.md) 9 | - [Using the fetch API with the `ipfs://` protocol](Fetch-IPFS.md) 10 | -------------------------------------------------------------------------------- /docs/Theming.md: -------------------------------------------------------------------------------- 1 | # Theming 2 | 3 | Hybrid provides CSS variables for themeing the browser at the URL `hybrid://theme/vars.css`. 4 | 5 | The contents of this look something like: 6 | 7 | ```css 8 | :root { 9 | --ag-color-purple: #6e2de5; 10 | --ag-color-black: #111; 11 | --ag-color-white: #F2F2F2; 12 | --ag-color-green: #2de56e; 13 | } 14 | 15 | :root { 16 | --ag-theme-font-family: system-ui; 17 | --ag-theme-background: var(--ag-color-black); 18 | --ag-theme-text: var(--ag-color-white); 19 | --ag-theme-primary: var(--ag-color-purple); 20 | --ag-theme-secondary: var(--ag-color-green); 21 | } 22 | ``` 23 | 24 | These can be imported anywhere you'd like to use browser styling. 25 | 26 | Specifically, you should try to use the `--ag-theme-*` variables for the page when possible. 27 | 28 | You can also make use of the `hybrid://theme/style.css` which adds some default styling to stuff like headers, the background/text colors, and links. 29 | 30 | This is useful for styling markdown pages or other pages with basic HTML. You probably shouldn't include this if you're doing something fancy with styling as the styles may change over time. 31 | 32 | The style includes a class called `hybrid-header-anchor` which can be used on anchors within headers for linking to headings. Checkout the markdown extension 33 | 34 | ## Customization 35 | 36 | The `--ag-theme-*` variables can me modified in the `.hybridrc` file by clicking `Help > Edit Configuration File` and adding the following content: 37 | 38 | ``` 39 | { 40 | "theme": { 41 | "font-family": "system-ui", 42 | "background": "var(--ag-color-black)", 43 | "text": "var(--ag-color-white)", 44 | "primary": "var(--ag-color-purple)", 45 | "secondary": "var(--ag-color-green)" 46 | } 47 | } 48 | ``` 49 | 50 | You can replace the various values with any valid CSS values like Hex codes: `#FFAABB`, or `rgb()`. 51 | 52 | More styles will be added here as needed. If you feel we should standardize on some sort of style, feel free to open an issue talking about what it is and why it should be added. 53 | 54 | ## Highlight.js 55 | 56 | For convenience, Hybrid bundles [highlight.js](https://highlightjs.org/) and a default theme for it. 57 | 58 | You can load it up using `hybrid://theme/highlight.js` and `hybrid://theme/highlight.css`. 59 | -------------------------------------------------------------------------------- /docs/Troubleshooting.md: -------------------------------------------------------------------------------- 1 | # Troubleshooting 2 | 3 | ## Electron sandbox issue on Linux 4 | 5 | On some Linux distros you can get the following error when running `start`: 6 | 7 | ``` 8 | [2720:0425/142001.775056:FATAL:setuid_sandbox_host.cc(157)] The SUID sandbox helper binary was found, but is not configured correctly. Rather than run without sandboxing I'm aborting now. You need to make sure that /path/to/hybrid/node_modules/electron/dist/chrome-sandbox is owned by root and has mode 4755. 9 | ``` 10 | 11 | The simplest solution is to change the permissions on the `chrome-sandbox` binary, as stated in the error: 12 | 13 | ``` 14 | sudo chown root:root node_modules/electron/dist/chrome-sandbox 15 | sudo chmod 4755 node_modules/electron/dist/chrome-sandbox 16 | ``` 17 | 18 | Note that it is important to run these commands *in that order*, otherwise it won't work. You might also run into further permission issues when trying to update the project dependencies. 19 | 20 | If your distro supports it, the following might work as a more permanent solution: 21 | 22 | ``` 23 | sudo sysctl kernel.unprivileged_userns_clone=1 24 | ``` 25 | 26 | If the solutions above don't work for some reason, you can always run Electron with the `--no-sandbox` flag, although this is definitely [not recommended](https://www.electronjs.org/docs/api/sandbox-option) when loading untrusted web content. 27 | -------------------------------------------------------------------------------- /download-extensions.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { fileURLToPath } from 'node:url' 4 | import path from 'node:path' 5 | import { readFile, mkdir, access } from 'node:fs/promises' 6 | import { createWriteStream } from 'node:fs' 7 | import { Readable } from 'stream' 8 | import { pipeline } from 'stream/promises' 9 | 10 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 11 | 12 | const EXTENSION_FOLDER = path.join(__dirname, 'app/extensions') 13 | const EXTENSIONS_LIST_FILE = path.join(EXTENSION_FOLDER, 'builtins.json') 14 | const EXTENSIONS_BUILTINS_FOLDER = path.join(EXTENSION_FOLDER, 'builtins/') 15 | 16 | console.log('Loading extension list') 17 | 18 | const extensionsJSON = await readFile(EXTENSIONS_LIST_FILE, 'utf8') 19 | 20 | try { 21 | await access(EXTENSIONS_BUILTINS_FOLDER) 22 | } catch { 23 | console.log(`Creating destination folder:\n${EXTENSIONS_BUILTINS_FOLDER}`) 24 | await mkdir(EXTENSIONS_BUILTINS_FOLDER) 25 | } 26 | 27 | const extensions = JSON.parse(extensionsJSON) 28 | 29 | console.log('Downloading extensions') 30 | 31 | for (const [name, options] of Object.entries(extensions)) { 32 | downloadExtension(name, options) 33 | } 34 | 35 | async function downloadExtension (name, { version, url, subfolder }) { 36 | const finalURL = url.replaceAll('{version}', version) 37 | const destination = path.join(EXTENSIONS_BUILTINS_FOLDER, `${name}.zip`) 38 | 39 | console.log(`Downloading: ${name}`) 40 | console.log(`URL: ${finalURL}`) 41 | console.log(`Destination: ${destination}`) 42 | 43 | const response = await fetch(finalURL) 44 | 45 | if (!response.ok) { 46 | throw new Error(`Could not download ${name} at ${version} from ${finalURL}\n${await response.text()}`) 47 | } 48 | 49 | // Based on this Stack Overflow question: https://stackoverflow.com/questions/37614649/how-can-i-download-and-save-a-file-using-the-fetch-api-node-js 50 | const fileSourceStream = Readable.fromWeb(response.body) 51 | const fileDestinationStream = createWriteStream(destination) 52 | 53 | await pipeline(fileSourceStream, fileDestinationStream) 54 | console.log(`Finished downloading ${name}`) 55 | } 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hybrid-browser", 3 | "version": "3.0.5", 4 | "description": "A peer to peer browser", 5 | "main": "app/index.js", 6 | "type": "module", 7 | "scripts": { 8 | "test": "npm run lint", 9 | "start": "electron .", 10 | "debug": "env NODE_ENV=debug electron --trace-uncaught .", 11 | "builder": "electron-builder build --publish never", 12 | "builder-all": "electron-builder build -mwl", 13 | "lint": "standard --fix", 14 | "preversion": "npm run test", 15 | "postinstall": "npm run postversion && npm run download-extensions && electron-builder install-app-deps", 16 | "download-extensions": "node ./download-extensions.js", 17 | "postversion": "node ./update-versions.js" 18 | }, 19 | "standard": { 20 | "ignore": [ 21 | "bundle.js", 22 | "bundle-markdown.js", 23 | "bundle-json.js", 24 | "bundle-gemini.js", 25 | "bundle-ssb.js", 26 | "extension-hybrid-*/", 27 | "version.js" 28 | ] 29 | }, 30 | "build": { 31 | "npmRebuild": true, 32 | "asar": true, 33 | "asarUnpack": [ 34 | "app/**", 35 | "node_modules/**", 36 | "build/icon.png", 37 | "build/icon-small.png", 38 | "package.json" 39 | ], 40 | "productName": "Hybrid Browser", 41 | "appId": "browser.hybridware.app", 42 | "files": [ 43 | "build/*", 44 | "app/**/*", 45 | "app/*", 46 | "node_modules/**/*", 47 | "package.json" 48 | ], 49 | "fileAssociations": [ 50 | { 51 | "ext": "html", 52 | "name": "web page", 53 | "role": "Viewer" 54 | }, 55 | { 56 | "ext": "md", 57 | "name": "markdown", 58 | "role": "Viewer" 59 | }, 60 | { 61 | "ext": "gemini", 62 | "role": "Viewer" 63 | } 64 | ], 65 | "directories": { 66 | "output": "release" 67 | }, 68 | "protocols": [ 69 | { 70 | "name": "Holepunch", 71 | "schemes": [ 72 | "hyper" 73 | ], 74 | "role": "Viewer" 75 | }, 76 | { 77 | "name": "webpages", 78 | "schemes": [ 79 | "http", 80 | "https" 81 | ], 82 | "role": "Viewer" 83 | }, 84 | { 85 | "name": "gemini", 86 | "schemes": [ 87 | "gemini" 88 | ], 89 | "role": "Viewer" 90 | }, 91 | { 92 | "name": "gopher", 93 | "schemes": [ 94 | "gopher" 95 | ], 96 | "role": "Viewer" 97 | }, 98 | { 99 | "name": "InterPlanetary File System", 100 | "schemes": [ 101 | "ipfs" 102 | ], 103 | "role": "Viewer" 104 | }, 105 | { 106 | "name": "BitTorrent", 107 | "schemes": [ 108 | "magnet", 109 | "bt" 110 | ], 111 | "role": "Viewer" 112 | } 113 | ], 114 | "dmg": { 115 | "contents": [ 116 | { 117 | "x": 130, 118 | "y": 220 119 | }, 120 | { 121 | "x": 410, 122 | "y": 220, 123 | "type": "link", 124 | "path": "/Applications" 125 | } 126 | ] 127 | }, 128 | "mac": { 129 | "artifactName": "${name}-${version}-${os}-${arch}.${ext}", 130 | "darkModeSupport": true, 131 | "gatekeeperAssess": false, 132 | "target": [ 133 | { 134 | "target": "dmg", 135 | "arch": [ 136 | "x64" 137 | ] 138 | } 139 | ] 140 | }, 141 | "win": { 142 | "target": [ 143 | "nsis", 144 | "portable" 145 | ] 146 | }, 147 | "linux": { 148 | "artifactName": "${name}-${version}-${os}-${arch}.${ext}", 149 | "executableArgs": [ 150 | "--enable-accelerated-video" 151 | ], 152 | "target": [ 153 | "deb", 154 | "AppImage", 155 | "apk", 156 | "pacman" 157 | ], 158 | "category": "Network;FileTransfer:P2P" 159 | } 160 | }, 161 | "repository": { 162 | "type": "git", 163 | "url": "git+https://github.com/HybridWare/hybrid-browser.git" 164 | }, 165 | "keywords": [ 166 | "dat", 167 | "hypercore", 168 | "hyper", 169 | "hyperdrive", 170 | "ipfs", 171 | "browser", 172 | "dweb" 173 | ], 174 | "author": "HybridWare ", 175 | "license": "AGPL-3.0", 176 | "bugs": { 177 | "url": "https://github.com/HybridWare/hybrid-browser/issues" 178 | }, 179 | "homepage": "https://github.com/HybridWare/hybrid-browser#readme", 180 | "devDependencies": { 181 | "@netless/extension-flat": "^1.0.1", 182 | "electron": "^37.2.6", 183 | "electron-builder": "^26.0.12", 184 | "standard": "^17.1.2" 185 | }, 186 | "dependencies": { 187 | "@chainsafe/libp2p-gossipsub": "^14.1.0", 188 | "@chainsafe/libp2p-noise": "^16.1.0", 189 | "@chainsafe/libp2p-quic": "^1.1.1", 190 | "@derhuerst/gemini": "^2.0.0", 191 | "@helia/unixfs": "^4.0.2", 192 | "@libp2p/autonat": "^2.0.28", 193 | "@libp2p/identify": "^3.0.15", 194 | "@libp2p/kad-dht": "^14.2.0", 195 | "@libp2p/mdns": "^11.0.32", 196 | "@libp2p/pubsub-peer-discovery": "^11.0.1", 197 | "@libp2p/upnp-nat": "^3.1.11", 198 | "abort-controller": "^3.0.0", 199 | "blockstore-fs": "^2.0.2", 200 | "create-desktop-shortcuts": "^1.11.0", 201 | "data-uri-to-buffer": "^6.0.2", 202 | "datastore-fs": "^10.0.2", 203 | "decompress": "^4.2.1", 204 | "delay": "^6.0.0", 205 | "detect-port": "^2.1.0", 206 | "electron-extended-webextensions": "github:HybridWare/electron-extended-WebExtensions", 207 | "event-iterator": "^2.0.0", 208 | "fs-extra": "^11.3.0", 209 | "gopher-lib": "^0.2.0", 210 | "helia": "^5.2.0", 211 | "http-proxy-agent": "^7.0.2", 212 | "hyper-sdk": "^5.1.0", 213 | "ipfs-pubsub-room": "github:ducksandgoats/ipfs-pubsub-room", 214 | "magnet-uri": "^7.0.7", 215 | "mime": "^4.0.6", 216 | "multiformats": "^9.9.0", 217 | "node-fetch": "^3.3.2", 218 | "p-queue": "^8.1.0", 219 | "range-parser": "^1.2.1", 220 | "rc": "^1.2.8", 221 | "sanitize-filename": "^1.6.3", 222 | "scoped-fs": "^1.4.1", 223 | "semver": "^7.7.0", 224 | "socks-proxy-agent": "^8.0.5", 225 | "streamx": "^2.22.0", 226 | "torrentz": "^20.0.4", 227 | "uint8-util": "^2.2.5", 228 | "web3protocol": "^0.6.2", 229 | "whatwg-mimetype": "github:jsdom/whatwg-mimetype" 230 | } 231 | } 232 | -------------------------------------------------------------------------------- /rebuild.sh: -------------------------------------------------------------------------------- 1 | # Electron's version. 2 | export npm_config_target=11.4.10 3 | # The architecture of Electron, see https://electronjs.org/docs/tutorial/support#supported-platforms 4 | # for supported architectures. 5 | export npm_config_arch=x64 6 | export npm_config_target_arch=x64 7 | # Download headers for Electron. 8 | export npm_config_disturl=https://electronjs.org/headers 9 | # Tell node-pre-gyp that we are building for Electron. 10 | export npm_config_runtime=electron 11 | # Tell node-pre-gyp to build module from source code. 12 | export npm_config_build_from_source=true 13 | # Install all dependencies, and store cache to ~/.electron-gyp. 14 | HOME=~/.electron-gyp npm rebuild better-sqlite3 15 | -------------------------------------------------------------------------------- /update-versions.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import * as fs from 'node:fs/promises' 3 | 4 | const packageData = await fs.readFile('./package.json', 'utf8') 5 | 6 | const json = JSON.parse(packageData) 7 | 8 | const { name, version, dependencies } = json 9 | 10 | console.log('Updating version.js with latest package', { name, version, dependencies }) 11 | 12 | const fileContents = ` 13 | export const name = '${name}' 14 | export const version = '${version}' 15 | export const dependencies = ${JSON.stringify(dependencies, null, ' ')} 16 | ` 17 | 18 | await fs.writeFile('./app/version.js', fileContents) 19 | 20 | console.log('Done!') 21 | --------------------------------------------------------------------------------