├── .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
├── 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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/.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 | 
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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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 os from 'os'
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 | NewWindow: {
33 | label: 'New Window',
34 | click: onNewWindow,
35 | accelerator: accelerators.NewWindow
36 | },
37 | Forward: {
38 | label: 'Forward',
39 | accelerator: accelerators.Forward,
40 | click: onGoForward
41 | },
42 | Back: {
43 | label: 'Back',
44 | accelerator: accelerators.Back,
45 | click: onGoBack
46 | },
47 | FocusURLBar: {
48 | label: 'Focus URL Bar',
49 | click: onFocusURlBar,
50 | accelerator: accelerators.FocusURLBar
51 | },
52 | FindInPage: {
53 | label: 'Find in Page',
54 | click: onFindInPage,
55 | accelerator: accelerators.FindInPage
56 | },
57 | Reload: {
58 | label: 'Reload',
59 | accelerator: accelerators.Reload,
60 | click: onReload
61 | },
62 | HardReload: {
63 | label: 'Hard Reload',
64 | accelerator: accelerators.HardReload,
65 | click: onHardReload
66 | },
67 | LearnMore: {
68 | label: 'Learn More',
69 | accelerator: accelerators.LearnMore,
70 | click: onLearMore
71 | },
72 | SetAsDefault: {
73 | label: 'Set as Default Browser',
74 | accelerator: accelerators.SetAsDefault,
75 | click: onSetAsDefault
76 | },
77 | SetAsDefaultMagnet: {
78 | label: 'Set as Default for Torrents',
79 | accelerator: accelerators.SetAsDefaultMagnet,
80 | click: onSetAsDefaultMagnet
81 | },
82 | OpenExtensionFolder: {
83 | label: 'Open Extensions Folder',
84 | accelerator: accelerators.OpenExtensionFolder,
85 | click: onOpenExtensionFolder
86 | },
87 | OpenDataFolder: {
88 | label: 'Open Data Folder',
89 | accelerator: accelerators.OpenDataFolder,
90 | click: onOpenDataFolder
91 | },
92 | EditConfigFile: {
93 | label: 'Edit Configuration File',
94 | accelerator: accelerators.EditConfigFile,
95 | click: onEditConfigFile
96 | },
97 | OpenConfigFile: {
98 | label: 'Open Configuration File',
99 | accelerator: accelerators.OpenConfigFile,
100 | click: onOpenConfigFile
101 | },
102 | CreateBookmark: {
103 | label: 'Create Bookmark',
104 | accelerator: accelerators.CreateBookmark,
105 | click: onCreateBookmark
106 | }
107 | }
108 | async function onSetAsDefault () {
109 | app.setAsDefaultProtocolClient('http')
110 | app.setAsDefaultProtocolClient('https')
111 | }
112 |
113 | async function onSetAsDefaultMagnet () {
114 | app.setAsDefaultProtocolClient('magnet')
115 | }
116 |
117 | async function onLearMore () {
118 | await shell.openExternal('https://github.com/HybridWare/hybrid-browser')
119 | }
120 |
121 | function onOpenDevTools (event, focusedWindow, focusedWebContents) {
122 | const contents = getContents(focusedWindow)
123 | for (const webContents of contents) {
124 | webContents.openDevTools()
125 | }
126 | }
127 |
128 | function onNewWindow (event, focusedWindow, focusedWebContents) {
129 | createWindow()
130 | }
131 |
132 | function onFocusURlBar (event, focusedWindow) {
133 | focusedWindow.webContents.focus()
134 | focusedWindow.webContents.executeJavaScript(FOCUS_URL_BAR_SCRIPT, true)
135 | }
136 |
137 | function onFindInPage (event, focusedWindow) {
138 | focusedWindow.webContents.focus()
139 | focusedWindow.webContents.executeJavaScript(OPEN_FIND_BAR_SCRIPT, true)
140 | }
141 |
142 | function onReload (event, focusedWindow, focusedWebContents) {
143 | // Reload
144 | for (const webContents of getContents(focusedWindow)) {
145 | webContents.reload()
146 | }
147 | }
148 |
149 | function onHardReload (event, focusedWindow, focusedWebContents) {
150 | // Hard reload
151 | for (const webContents of getContents(focusedWindow)) {
152 | webContents.reloadIgnoringCache()
153 | }
154 | }
155 |
156 | function onGoForward (event, focusedWindow) {
157 | for (const webContents of getContents(focusedWindow)) {
158 | webContents.goForward()
159 | }
160 | }
161 |
162 | function onGoBack (event, focusedWindow) {
163 | for (const webContents of getContents(focusedWindow)) {
164 | webContents.goBack()
165 | }
166 | }
167 |
168 | function getContents (focusedWindow) {
169 | const views = focusedWindow.getBrowserViews()
170 | if (!views.length) return [focusedWindow.webContents]
171 | return views.map(({ webContents }) => webContents)
172 | }
173 |
174 | async function onOpenExtensionFolder () {
175 | try {
176 | const { dir } = extensions
177 | await fs.ensureDir(dir)
178 |
179 | await shell.openPath(dir)
180 | } catch (e) {
181 | console.error(e.stack)
182 | }
183 | }
184 |
185 | async function onOpenDataFolder () {
186 | try {
187 | await shell.openPath(app.getPath('userData'))
188 | } catch (e) {
189 | console.error(e.stack)
190 | }
191 | }
192 |
193 | async function onEditConfigFile () {
194 | await createWindow('hybrid://settings')
195 | }
196 |
197 | async function onOpenConfigFile () {
198 | const file = path.join(os.homedir(), DEFAULT_CONFIG_FILE_NAME)
199 |
200 | const exists = await fs.pathExists(file)
201 |
202 | if (!exists) await fs.writeJson(file, {})
203 |
204 | await shell.openPath(file)
205 | }
206 |
207 | async function onCreateBookmark (event, focusedWindow) {
208 | for (const webContents of getContents(focusedWindow)) {
209 | const defaultPath = app.getPath('desktop')
210 | const outputPath = (await dialog.showOpenDialog({
211 | defaultPath,
212 | properties: ['openDirectory']
213 | })).filePaths[0]
214 |
215 | // If testing from source find and use installed Hybrid location
216 | const filePath = appPath || process.argv[0]
217 |
218 | const title = webContents.getTitle()
219 | const shortcutName = sanitize(title, { replacement: ' ' })
220 | const url = webContents.getURL()
221 | const description = `Hybrid Browser - ${url}`
222 |
223 | const shortcut = {
224 | filePath,
225 | outputPath,
226 | name: shortcutName,
227 | comment: description,
228 | description,
229 | arguments: url
230 | }
231 |
232 | const createShortcut = icon => {
233 | if (icon) shortcut.icon = icon
234 | // TODO: Kyran: Use Hybrid icon if no icon provided.
235 | // TODO: Kyran: OSX doesn't have arguments option. See https://github.com/RangerMauve/hybrid-browser/pull/53#issuecomment-705654060 for solution.
236 | createDesktopShortcut({
237 | windows: shortcut,
238 | linux: shortcut
239 | })
240 | }
241 |
242 | try {
243 | const type = process.platform === 'win32' ? 'ico' : 'png'
244 | const faviconDataURI = await getFaviconDataURL(webContents, type)
245 | const buffer = dataUriToBuffer(faviconDataURI)
246 |
247 | const savePath = path.join(app.getPath('userData'), 'PWAs', shortcutName)
248 | const faviconPath = path.join(savePath, `favicon.${type}`)
249 |
250 | await fs.ensureDir(savePath)
251 | await fs.writeFile(faviconPath, buffer)
252 |
253 | createShortcut(faviconPath)
254 | } catch (e) {
255 | console.error('Error loading favicon')
256 | console.error(e.stack)
257 | createShortcut()
258 | }
259 | }
260 | }
261 | }
262 |
263 | async function getFaviconDataURL (webContents, type) {
264 | return webContents.executeJavaScript(`new Promise(async (resolve, reject) => {
265 | try {
266 | const {href} = document.querySelector("link[rel*='icon']")
267 |
268 | const image = new Image()
269 | await new Promise(resolve => {
270 | image.onload = resolve
271 | image.src = href
272 | })
273 |
274 | const canvas = document.createElement('canvas')
275 | canvas.width = 256
276 | canvas.height = 256
277 |
278 | const context = canvas.getContext('2d')
279 | context.drawImage(image, 0, 0, 256, 256)
280 |
281 | ${
282 | type === 'ico'
283 | ? `
284 | canvas.toBlob(blob => {
285 | const reader = new FileReader()
286 | reader.onload = () => resolve(reader.result)
287 | reader.readAsDataURL(new Blob([].concat([
288 | [0, 0], // ICO header
289 | [1, 0], // Is ICO
290 | [1, 0], // Number of images
291 | [0], // Width (0 seems to work)
292 | [0], // Height (0 seems to work)
293 | [0], // Color palette (none)
294 | [0], // Reserved space
295 | [1, 0], // Color planes
296 | [32, 0], // Bit depth
297 | ].map(part => new Uint8Array(part).buffer), [
298 | [blob.size], // Image byte size
299 | [22], // Image byte offset
300 | ].map(part => new Uint32Array(part).buffer), [
301 | blob, // Image
302 | ]), {type: 'image/vnd.microsoft.icon'}))
303 | })`
304 |
305 | : "resolve(canvas.toDataURL('image/png'))"
306 | }
307 | } catch (e) {
308 | reject(e)
309 | }
310 | })`)
311 | }
312 | //
313 |
--------------------------------------------------------------------------------
/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 url from 'node:url'
7 | import { readFile, writeFile } from 'node:fs/promises'
8 |
9 | const USER_DATA = app.getPath('userData')
10 | const DEFAULT_EXTENSIONS_DIR = path.join(USER_DATA, 'extensions')
11 | const DEFAULT_IPFS_DIR = path.join(USER_DATA, 'ipfs')
12 | const DEFAULT_HYPER_DIR = path.join(USER_DATA, 'hyper')
13 | // const DEFAULT_SSB_DIR = path.join(USER_DATA, 'ssb')
14 | const DEFAULT_BT_DIR = path.join(USER_DATA, 'bt')
15 |
16 | const DEFAULT_PAGE = 'hybrid://welcome'
17 |
18 | const DEFAULT_CONFIG_FILE_NAME = '.hybridrc'
19 | export const MAIN_RC_FILE = path.join(os.homedir(), DEFAULT_CONFIG_FILE_NAME)
20 |
21 | const Config = RC('hybrid', {
22 | llm: {
23 | enabled: true,
24 |
25 | baseURL: 'http://127.0.0.1:11434/v1/',
26 | // Uncomment this to use OpenAI instead
27 | // baseURL: 'https://api.openai.com/v1/'
28 | apiKey: 'ollama',
29 | model: 'qwen2.5-coder:7b-instruct-q4_K_M'
30 | },
31 | accelerators: {
32 | OpenDevTools: 'CommandOrControl+Shift+I',
33 | NewWindow: 'CommandOrControl+N',
34 | Forward: 'CommandOrControl+]',
35 | Back: 'CommandOrControl+[',
36 | FocusURLBar: 'CommandOrControl+L',
37 | FindInPage: 'CommandOrControl+F',
38 | Reload: 'CommandOrControl+R',
39 | HardReload: 'CommandOrControl+Shift+R',
40 | LearnMore: null,
41 | OpenExtensionsFolder: null,
42 | EditConfigFile: 'CommandOrControl+.',
43 | OpenConfigFile: 'CommandOrControl+,',
44 | CreateBookmark: 'CommandOrControl+D'
45 | },
46 |
47 | extensions: {
48 | dir: DEFAULT_EXTENSIONS_DIR,
49 | // TODO: This will be for loading extensions from remote URLs
50 | remote: []
51 | },
52 |
53 | theme: {
54 | 'font-family': 'system-ui',
55 | background: 'var(--hy-color-white)',
56 | text: 'var(--hy-color-black)',
57 | primary: 'var(--hy-color-blue)',
58 | secondary: 'var(--hy-color-red)',
59 | indent: '16px',
60 | 'max-width': '666px'
61 | },
62 |
63 | defaultPage: DEFAULT_PAGE,
64 | autoHideMenuBar: false,
65 |
66 | err: true,
67 |
68 | bt: {
69 | dir: DEFAULT_BT_DIR,
70 | refresh: false,
71 | status: true,
72 | block: true
73 | },
74 |
75 | ipfs: {
76 | repo: DEFAULT_IPFS_DIR,
77 | refresh: false,
78 | status: true,
79 | block: true
80 | },
81 |
82 | hyper: {
83 | storage: DEFAULT_HYPER_DIR,
84 | refresh: false,
85 | status: true,
86 | block: true
87 | },
88 | oui: {
89 | status: true
90 | },
91 |
92 | gemini: {
93 | status: true
94 | },
95 |
96 | gopher: {
97 | status: true
98 | },
99 |
100 | hhttp: {
101 | status: true
102 | },
103 |
104 | tor: {
105 | status: true
106 | },
107 |
108 | iip: {
109 | status: true
110 | },
111 | vid: {
112 | status: true
113 | },
114 | rns: {
115 | status: true
116 | }
117 | })
118 |
119 | export default Config
120 |
121 | export function addPreloads (session) {
122 | const preloadPath = path.join(url.fileURLToPath(new URL('./', import.meta.url)), 'settings-preload.js')
123 | const preloads = session.getPreloads()
124 | preloads.push(preloadPath)
125 | session.setPreloads(preloads)
126 | }
127 |
128 | ipcMain.handle('settings-save', async (event, configMap) => {
129 | await save(configMap)
130 | })
131 |
132 | export async function save (configMap) {
133 | const currentRC = await getRCData()
134 | let hasChanged = false
135 | for (const [key, value] of Object.entries(configMap)) {
136 | const existing = getFrom(key, Config)
137 | if (existing === undefined) continue
138 | if (value === existing) continue
139 | hasChanged = true
140 | setOn(key, Config, value)
141 | setOn(key, currentRC, value)
142 | }
143 | if (hasChanged) {
144 | await writeFile(MAIN_RC_FILE, JSON.stringify(currentRC, null, '\t'))
145 | }
146 | }
147 |
148 | async function getRCData () {
149 | try {
150 | const data = await readFile(MAIN_RC_FILE, 'utf8')
151 | return JSON.parse(data)
152 | } catch {
153 | return {}
154 | }
155 | }
156 |
157 | function setOn (path, object, value) {
158 | if (path.includes('.')) {
159 | const [key, subkey] = path.split('.')
160 | if (typeof object[key] !== 'object') {
161 | object[key] = {}
162 | }
163 | object[key][subkey] = value
164 | } else {
165 | object[path] = value
166 | }
167 | }
168 |
169 | // No support for more than one level
170 | function getFrom (path, object) {
171 | if (path.includes('.')) {
172 | const [key, subkey] = path.split('.')
173 | if (typeof object[key] !== 'object') return undefined
174 | return object[key][subkey]
175 | } else {
176 | return object[path]
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/app/extensions/builtins/hybrid-history.zip
--------------------------------------------------------------------------------
/app/extensions/builtins/ublock.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HybridWare/hybrid-browser/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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 |
2 | let getBackgroundPage = null
3 |
4 | export function setGetBackgroundPage (backgroundPage) {
5 | getBackgroundPage = backgroundPage
6 | }
7 |
8 | export async function search (query = '') {
9 | const webContents = await getBackgroundPage()
10 |
11 | return webContents.executeJavaScript(`
12 | (async () => {
13 | let result = []
14 | for await(let item of search(${JSON.stringify(query)})) {
15 | result.push(item)
16 | }
17 | return result
18 | })()
19 | `)
20 | }
21 |
--------------------------------------------------------------------------------
/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 config from './config.js'
14 | import * as llm from './llm.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 |
133 | async function onready () {
134 | console.log('Building tray and context menu')
135 | const appIcon = new Tray(LOGO_FILE)
136 | const contextMenu = Menu.buildFromTemplate([
137 | { label: 'New Window', click: () => createWindow() },
138 | {
139 | label: 'Quit',
140 | role: 'quit'
141 | }
142 | ])
143 | // Call this again for Linux because we modified the context menu
144 | appIcon.setContextMenu(contextMenu)
145 | appIcon.on('click', () => {
146 | createWindow()
147 | })
148 |
149 | const webSession = session.fromPartition(WEB_PARTITION)
150 |
151 | llm.addPreloads(webSession)
152 | config.addPreloads(webSession)
153 |
154 | const electronSection = /Electron.+ /i
155 | const existingAgent = webSession.getUserAgent()
156 | const newAgent = existingAgent.replace(electronSection, `HybridDesktop/${version}`)
157 |
158 | webSession.setUserAgent(newAgent)
159 | session.defaultSession.setUserAgent(newAgent)
160 |
161 | const actions = createActions({
162 | createWindow
163 | })
164 |
165 | console.log('Setting up protocol handlers')
166 |
167 | await protocols.checkProtocols()
168 |
169 | await protocols.setupProtocols(webSession)
170 |
171 | console.log('Registering context menu')
172 |
173 | await registerMenu(actions)
174 |
175 | function updateBrowserActions (tabId, actions) {
176 | windowManager.reloadBrowserActions(tabId)
177 | }
178 |
179 | console.log('Initializing extensions')
180 |
181 | extensions = createExtensions({ session: webSession, createWindow, updateBrowserActions })
182 |
183 | console.log('Extracting internal extensions')
184 |
185 | // Extract any internal extensions if there are updates
186 | await extensions.extractInternal()
187 |
188 | console.log('Registering extensions from disk')
189 |
190 | // Register all extensions in the extensions folder from disk
191 | await extensions.registerAll()
192 |
193 | // TODO: Better error handling when the extension doesn't exist?
194 | history.setGetBackgroundPage(() => {
195 | return extensions.getBackgroundPageByName('hybrid-history')
196 | })
197 |
198 | console.log('Opening saved windows')
199 |
200 | const opened = await windowManager.openSaved()
201 |
202 | const urls = urlsFromArgs(process.argv.slice(1), process.cwd())
203 | if (urls.length) {
204 | for (const url of urls) {
205 | windowManager.open({ url })
206 | }
207 | } else if (!opened.length) windowManager.open()
208 |
209 | console.log('Waiting for windows to settle')
210 |
211 | await new Promise((resolve) => setTimeout(resolve, REGISTRATION_DELAY))
212 |
213 | protocols.setAsDefaultProtocolClient()
214 |
215 | console.log('Initialization done')
216 | }
217 |
218 | function createWindow (url, options = {}) {
219 | console.log('createWindow', url, options)
220 | return windowManager.open({ url, ...options })
221 | }
222 |
223 | function urlsFromArgs (argv, workingDir) {
224 | const rootURL = new URL(workingDir + sep, 'file://')
225 | return argv
226 | .filter((arg) => arg.includes('/'))
227 | .map((arg) => (arg.includes('://') ? arg : (new URL(arg, rootURL)).href))
228 | }
229 |
--------------------------------------------------------------------------------
/app/llm-preload.js:
--------------------------------------------------------------------------------
1 | const { contextBridge, ipcRenderer } = require('electron')
2 |
3 | contextBridge.exposeInMainWorld('llm', {
4 | chat: (args) => ipcRenderer.invoke('llm-chat', args),
5 | complete: (prompt, args = {}) => ipcRenderer.invoke('llm-complete', { ...args, prompt }),
6 | isSupported: () => ipcRenderer.invoke('llm-supported')
7 | })
8 |
--------------------------------------------------------------------------------
/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 | const { baseURL, apiKey, model } = config.llm
9 | let { enabled } = config.llm
10 |
11 | let isInitialized = false
12 |
13 | ipcMain.handle('llm-supported', async (event) => {
14 | if (!enabled) return false
15 | return isSupported()
16 | })
17 |
18 | ipcMain.handle('llm-chat', async (event, args) => {
19 | if (!enabled) return Promise.reject(new Error('LLM API is disabled'))
20 | return chat(args)
21 | })
22 |
23 | ipcMain.handle('llm-complete', async (event, args) => {
24 | if (!enabled) return Promise.reject(new Error('LLM API is disabled'))
25 | return complete(args)
26 | })
27 |
28 | export async function isSupported () {
29 | if (!enabled) return false
30 | const has = await hasModel()
31 | if (has) return true
32 | return (apiKey === 'ollama')
33 | }
34 |
35 | export function addPreloads (session) {
36 | const preloadPath = path.join(__dirname, 'llm-preload.js')
37 | const preloads = session.getPreloads()
38 | preloads.push(preloadPath)
39 | session.setPreloads(preloads)
40 | }
41 |
42 | export async function init () {
43 | if (!enabled) throw new Error('LLM API is disabled')
44 | if (isInitialized) return
45 | // TODO: prompt for download
46 | if (apiKey === 'ollama') {
47 | const has = await hasModel()
48 | if (!has) {
49 | await confirmPull()
50 | await pullModel()
51 | await notifyPullDone()
52 | }
53 | }
54 | isInitialized = true
55 | }
56 |
57 | async function listModels () {
58 | const { data } = await get('./models', 'Unable to list models')
59 | return data
60 | }
61 |
62 | async function confirmPull () {
63 | const { response, checkboxChecked } = await dialog.showMessageBox({
64 | title: 'Download AI Model?',
65 | 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?',
66 | buttons: ['Yes', 'No'],
67 | defaultId: 0,
68 | cancelId: 1,
69 | checkboxLabel: 'Remember this choice'
70 | })
71 |
72 | if (response === 1) {
73 | if (checkboxChecked) {
74 | enabled = false
75 | }
76 | throw new Error('Cannot use LLM, user denied download')
77 | }
78 | }
79 |
80 | async function notifyPullDone () {
81 | await dialog.showMessageBox({
82 | title: 'AI Model Downloaded',
83 | message: `Hybrid has finished downloading the large lanfguage model. You can clear it by running 'ollama rm ${model}'`
84 | })
85 | }
86 |
87 | async function pullModel () {
88 | await post('/api/pull', {
89 | name: model
90 | }, `Unable to pull model ${model}`, false)
91 | }
92 |
93 | async function hasModel () {
94 | try {
95 | const models = await listModels()
96 |
97 | return !!models.find(({ id }) => id === model)
98 | } catch (e) {
99 | console.error(e.stack)
100 | return false
101 | }
102 | }
103 |
104 | export async function chat ({
105 | messages = [],
106 | temperature,
107 | maxTokens,
108 | stop
109 | }) {
110 | await init()
111 | const { choices } = await post('./chat/completions', {
112 | messages,
113 | model,
114 | temperature,
115 | max_tokens: maxTokens,
116 | stop
117 | }, 'Unable to generate completion')
118 |
119 | return choices[0].message
120 | }
121 |
122 | export async function complete ({
123 | prompt,
124 | temperature,
125 | maxTokens,
126 | stop
127 | }) {
128 | await init()
129 | const { choices } = await post('./completions', {
130 | prompt,
131 | model,
132 | temperature,
133 | max_tokens: maxTokens,
134 | stop
135 | }, 'Unable to generate completion')
136 |
137 | return choices[0].text
138 | }
139 |
140 | async function get (path, errorMessage, parseBody = true) {
141 | const url = new URL(path, baseURL).href
142 |
143 | const response = await fetch(url, {
144 | method: 'GET',
145 | headers: {
146 | Authorization: `Bearer ${apiKey}`
147 | }
148 | })
149 |
150 | if (!response.ok) {
151 | throw new Error(`${errorMessage} ${await response.text()}`)
152 | }
153 |
154 | if (parseBody) {
155 | return await response.json()
156 | } else {
157 | return await response.text()
158 | }
159 | }
160 |
161 | async function post (path, data, errorMessage) {
162 | const url = new URL(path, baseURL).href
163 |
164 | const response = await fetch(url, {
165 | method: 'POST',
166 | headers: {
167 | 'Content-Type': 'application/json; charset=utf8',
168 | Authorization: `Bearer ${apiKey}`
169 | },
170 | body: JSON.stringify(data)
171 | })
172 |
173 | if (!response.ok) {
174 | throw new Error(`${errorMessage} ${await response.text()}`)
175 | }
176 |
177 | return await response.json()
178 | }
179 |
--------------------------------------------------------------------------------
/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 | NewWindow,
9 | Forward,
10 | Back,
11 | FocusURLBar,
12 | FindInPage,
13 | Reload,
14 | HardReload,
15 | LearnMore,
16 | SetAsDefault,
17 | SetAsDefaultMagnet,
18 | OpenExtensionFolder,
19 | OpenDataFolder,
20 | EditConfigFile,
21 | OpenConfigFile,
22 | CreateBookmark
23 | } = actions
24 |
25 | const template = [
26 | // { role: 'appMenu' }
27 | ...(isMac
28 | ? [{
29 | label: app.name,
30 | submenu: [
31 | { role: 'about' },
32 | { type: 'separator' },
33 | { role: 'services' },
34 | { type: 'separator' },
35 | { role: 'hide' },
36 | { role: 'hideothers' },
37 | { role: 'unhide' },
38 | { type: 'separator' },
39 | { role: 'quit' }
40 | ]
41 | }]
42 | : []),
43 | // { role: 'fileMenu' }
44 | {
45 | label: 'File',
46 | submenu: [
47 | isMac ? { role: 'close' } : { role: 'quit' },
48 | OpenDevTools,
49 | NewWindow
50 | ]
51 | },
52 | // { role: 'editMenu' }
53 | {
54 | label: 'Edit',
55 | submenu: [
56 | { role: 'undo' },
57 | { role: 'redo' },
58 | { type: 'separator' },
59 | { role: 'cut' },
60 | { role: 'copy' },
61 | { role: 'paste' },
62 | ...(isMac
63 | ? [
64 | { role: 'pasteAndMatchStyle' },
65 | { role: 'delete' },
66 | { role: 'selectAll' },
67 | { type: 'separator' },
68 | {
69 | label: 'Speech',
70 | submenu: [
71 | { role: 'startspeaking' },
72 | { role: 'stopspeaking' }
73 | ]
74 | }
75 | ]
76 | : [
77 | { role: 'delete' },
78 | { type: 'separator' },
79 | { role: 'selectAll' }
80 | ])
81 | ]
82 | },
83 | // { role: 'viewMenu' }
84 | {
85 | label: 'View',
86 | submenu: [
87 | Forward,
88 | Back,
89 | FocusURLBar,
90 | FindInPage,
91 | { type: 'separator' },
92 | { role: 'resetzoom' },
93 | { role: 'zoomin' },
94 | { role: 'zoomout' },
95 | { type: 'separator' },
96 | { role: 'togglefullscreen' }
97 | ]
98 | },
99 | // { role: 'windowMenu' }
100 | {
101 | label: 'Window',
102 | submenu: [
103 | Reload,
104 | HardReload,
105 | ...(isMac
106 | ? []
107 | : [
108 | CreateBookmark
109 | ]),
110 | { role: 'minimize' },
111 | { role: 'zoom' },
112 | ...(isMac
113 | ? [
114 | { type: 'separator' },
115 | { role: 'front' },
116 | { type: 'separator' },
117 | { role: 'window' }
118 | ]
119 | : [
120 | { role: 'close' }
121 | ])
122 | ]
123 | },
124 | {
125 | role: 'help',
126 | submenu: [
127 | LearnMore,
128 | OpenExtensionFolder,
129 | OpenDataFolder,
130 | EditConfigFile,
131 | OpenConfigFile,
132 | SetAsDefault,
133 | SetAsDefaultMagnet
134 | ]
135 | }
136 | ]
137 |
138 | const menu = Menu.buildFromTemplate(template)
139 | Menu.setApplicationMenu(menu)
140 | }
141 |
--------------------------------------------------------------------------------
/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 |
13 |
19 |
20 |
--------------------------------------------------------------------------------
/app/pages/bt.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HybridWare/hybrid-browser/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/app/pages/iip.ico
--------------------------------------------------------------------------------
/app/pages/ipfs.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HybridWare/hybrid-browser/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/app/pages/oui.ico
--------------------------------------------------------------------------------
/app/pages/settings.html:
--------------------------------------------------------------------------------
1 |
2 | Browser Settings
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
13 |
14 | Settings
15 |
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 | Example
21 |
22 |
23 |
24 |
25 |
26 |
27 | Example
28 | mple
29 | Exa
30 |
31 |
32 |
33 |
34 | ## Media
35 |
36 | ### Image
37 |
38 | 
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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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 | } = Config
57 |
58 | const onCloseHandlers = []
59 |
60 | export async function close () {
61 | await Promise.all(onCloseHandlers.map((handler) => handler()))
62 | }
63 |
64 | export function registerPrivileges () {
65 | globalProtocol.registerSchemesAsPrivileged([
66 | { scheme: 'hybrid', privileges: BROWSER_PRIVILEGES },
67 | { scheme: 'bt', privileges: P2P_PRIVILEGES },
68 | { scheme: 'magnet', privileges: LOW_PRIVILEGES },
69 | { scheme: 'ipfs', privileges: P2P_PRIVILEGES },
70 | { scheme: 'hyper', privileges: P2P_PRIVILEGES },
71 | { scheme: 'oui', privileges: CS_PRIVILEGES },
72 | { scheme: 'ouis', privileges: P2P_PRIVILEGES },
73 | { scheme: 'gemini', privileges: P2P_PRIVILEGES },
74 | { scheme: 'gopher', privileges: CS_PRIVILEGES },
75 | { scheme: 'hhttp', privileges: CS_PRIVILEGES },
76 | { scheme: 'hhttps', privileges: P2P_PRIVILEGES },
77 | { scheme: 'tor', privileges: CS_PRIVILEGES },
78 | { scheme: 'tors', privileges: CS_PRIVILEGES },
79 | { scheme: 'iip', privileges: CS_PRIVILEGES },
80 | { scheme: 'iips', privileges: CS_PRIVILEGES },
81 | { scheme: 'msg', privileges: P2P_PRIVILEGES },
82 | { scheme: 'pubsub', privileges: P2P_PRIVILEGES },
83 | { scheme: 'topic', privileges: P2P_PRIVILEGES },
84 | { scheme: 'vid', privileges: CS_PRIVILEGES },
85 | { scheme: 'rns', privileges: CS_PRIVILEGES },
86 | { scheme: 'magnet', privileges: LOW_PRIVILEGES }
87 | ])
88 | }
89 |
90 | export async function checkProtocols(){
91 | if(bt.refresh){
92 | await fs.emptyDir(bt.dir)
93 | }
94 | if(ipfs.refresh){
95 | await fs.emptyDir(ipfs.repo)
96 | }
97 | if(hyper.refresh){
98 | await fs.emptyDir(hyper.storage)
99 | }
100 | }
101 |
102 | export function setAsDefaultProtocolClient () {
103 | console.log('Setting as default handlers')
104 | app.setAsDefaultProtocolClient('hybrid')
105 | app.setAsDefaultProtocolClient('bt')
106 | app.setAsDefaultProtocolClient('ipfs')
107 | app.setAsDefaultProtocolClient('hyper')
108 | app.setAsDefaultProtocolClient('oui')
109 | app.setAsDefaultProtocolClient('ouis')
110 | app.setAsDefaultProtocolClient('gemini')
111 | app.setAsDefaultProtocolClient('gopher')
112 | app.setAsDefaultProtocolClient('hhttp')
113 | app.setAsDefaultProtocolClient('hhttps')
114 | app.setAsDefaultProtocolClient('tor')
115 | app.setAsDefaultProtocolClient('tors')
116 | app.setAsDefaultProtocolClient('iip')
117 | app.setAsDefaultProtocolClient('iips')
118 | app.setAsDefaultProtocolClient('msg')
119 | app.setAsDefaultProtocolClient('pubsub')
120 | app.setAsDefaultProtocolClient('topic')
121 | app.setAsDefaultProtocolClient('vid')
122 | app.setAsDefaultProtocolClient('rns')
123 | }
124 |
125 | export async function setupProtocols (session) {
126 | const { protocol: sessionProtocol } = session
127 |
128 | const {default: browserProtocolHandler} = await import('./browser-protocol.js')
129 | // const browserProtocolHandler = await createBrowserHandler()
130 | sessionProtocol.handle('hybrid', browserProtocolHandler)
131 | globalProtocol.handle('hybrid', browserProtocolHandler)
132 |
133 | console.log('registered hybrid protocol')
134 |
135 | const torrentz = await (async () => {const {default: Torrentz} = await import('torrentz');return new Torrentz(bt);})()
136 | 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()}}});})()
137 | const sdk = await (async () => {const SDK = await import('hyper-sdk');const sdk = await SDK.create(hyper);return sdk;})()
138 |
139 | // msg
140 | const {default: createMsgHandler} = await import('./msg-protocol.js')
141 | const { handler: msgHandler, close: closeMsg } = await createMsgHandler({...bt, err, torrentz}, session)
142 | onCloseHandlers.push(closeMsg)
143 | sessionProtocol.handle('msg', msgHandler)
144 | globalProtocol.handle('msg', msgHandler)
145 |
146 | console.log('registered msg protocol')
147 | // msg
148 |
149 | // pubsub
150 | const {default: createPubsubHandler} = await import('./pubsub-protocol.js')
151 | const { handler: pubsubHandler, close: closePubsub } = await createPubsubHandler({...ipfs, err, helia}, session)
152 | onCloseHandlers.push(closePubsub)
153 | sessionProtocol.handle('pubsub', pubsubHandler)
154 | globalProtocol.handle('pubsub', pubsubHandler)
155 |
156 | console.log('registered pubsub protocol')
157 | // pubsub
158 |
159 | // topic
160 | const {default: createTopicHandler} = await import('./topic-protocol.js')
161 | const { handler: topicHandler, close: closeTopic } = await createTopicHandler({...hyper, err, sdk}, session)
162 | onCloseHandlers.push(closeTopic)
163 | sessionProtocol.handle('topic', topicHandler)
164 | globalProtocol.handle('topic', topicHandler)
165 |
166 | console.log('registered topic protocol')
167 | // topic
168 |
169 | // bt
170 | const {default: createBTHandler} = await import('./bt-protocol.js')
171 | const { handler: btHandler, close: closeBT } = await createBTHandler({...bt, err, torrentz}, session)
172 | onCloseHandlers.push(closeBT)
173 | sessionProtocol.handle('bt', btHandler)
174 | globalProtocol.handle('bt', btHandler)
175 |
176 | console.log('registered bt protocol')
177 | // bt
178 |
179 | // const {default: createMagnetHandler} = await import('./magnet-protocol.js')
180 | // const magnetHandler = await createMagnetHandler()
181 | // sessionProtocol.handle('magnet', magnetHandler)
182 | // globalProtocol.handle('magnet', magnetHandler)
183 |
184 | // ipfs
185 | const {default: createIPFSHandler} = await import('./ipfs-protocol.js')
186 | const { handler: ipfsHandler, close: closeIPFS } = await createIPFSHandler({...ipfs, err, helia}, session)
187 | onCloseHandlers.push(closeIPFS)
188 | sessionProtocol.handle('ipfs', ipfsHandler)
189 | globalProtocol.handle('ipfs', ipfsHandler)
190 |
191 | console.log('registered ipfs protocol')
192 | // ipfs
193 |
194 | // hyper
195 | const {default: createHyperHandler} = await import('./hyper-protocol.js')
196 | const { handler: hyperHandler, close: closeHyper } = await createHyperHandler({...hyper, err, sdk}, session)
197 | onCloseHandlers.push(closeHyper)
198 | sessionProtocol.handle('hyper', hyperHandler)
199 | globalProtocol.handle('hyper', hyperHandler)
200 |
201 | console.log('registered hyper protocol')
202 | // hyper
203 |
204 | // oui
205 | const {default: createOuiHandler} = await import('./oui-protocol.js')
206 | const ouiHandler = await createOuiHandler(oui, session)
207 | sessionProtocol.handle('oui', ouiHandler)
208 | globalProtocol.handle('oui', ouiHandler)
209 | sessionProtocol.handle('ouis', ouiHandler)
210 | globalProtocol.handle('ouis', ouiHandler)
211 |
212 | console.log('registered ouinet protocol')
213 | // oui
214 |
215 | // gemini
216 | const {default: createGeminiHandler} = await import('./gemini-protocol.js')
217 | const geminiHandler = await createGeminiHandler(gemini, session)
218 | sessionProtocol.handle('gemini', geminiHandler)
219 | globalProtocol.handle('gemini', geminiHandler)
220 |
221 | console.log('registered gemini protocol')
222 | // gemini
223 |
224 | // gopher
225 | const {default: createGopherHandler} = await import('./gopher-protocol.js')
226 | const gopherHandler = await createGopherHandler(gopher, session)
227 | sessionProtocol.handle('gopher', gopherHandler)
228 | globalProtocol.handle('gopher', gopherHandler)
229 |
230 | console.log('registered gopher protocol')
231 | // gopher
232 |
233 | // hhttp
234 | const {default: createHHTTPHandler} = await import('./hhttp-protocol.js')
235 | const hhttpHandler = await createHHTTPHandler(hhttp, session)
236 | sessionProtocol.handle('hhttp', hhttpHandler)
237 | globalProtocol.handle('hhttp', hhttpHandler)
238 | sessionProtocol.handle('hhttps', hhttpHandler)
239 | globalProtocol.handle('hhttps', hhttpHandler)
240 |
241 | console.log('registered hhttp protocol')
242 | // hhttp
243 |
244 | // tor
245 | const {default: createTorHandler} = await import('./tor-protocol.js')
246 | const torHandler = await createTorHandler(tor, session)
247 | sessionProtocol.handle('tor', torHandler)
248 | globalProtocol.handle('tor', torHandler)
249 | sessionProtocol.handle('tors', torHandler)
250 | globalProtocol.handle('tors', torHandler)
251 |
252 | console.log('registered tor protocol')
253 | // tor
254 |
255 | // iip
256 | const {default: createIipHandler} = await import('./iip-protocol.js')
257 | const iipHandler = await createIipHandler(iip, session)
258 | sessionProtocol.handle('iip', iipHandler)
259 | globalProtocol.handle('iip', iipHandler)
260 | sessionProtocol.handle('iips', iipHandler)
261 | globalProtocol.handle('iips', iipHandler)
262 |
263 | console.log('registered i2p protocol')
264 | // iip
265 |
266 | // vid
267 | const {default: createVidHandler} = await import('./vid-protocol.js')
268 | const vidHandler = await createVidHandler(vid, session)
269 | sessionProtocol.handle('vid', vidHandler)
270 | globalProtocol.handle('vid', vidHandler)
271 |
272 | console.log('registered vid protocol')
273 | // vid
274 |
275 | // rns
276 | const {default: createRnsHandler} = await import('./rns-protocol.js')
277 | const rnsHandler = await createRnsHandler(rns, session)
278 | sessionProtocol.handle('rns', rnsHandler)
279 | globalProtocol.handle('rns', rnsHandler)
280 |
281 | console.log('registered rns protocol')
282 | // rns
283 |
284 | // magnet
285 | const {default: createMagnetHandler} = await import('./magnet-protocol.js')
286 | const magnetHandler = createMagnetHandler({bt: btHandler, ipfs: ipfsHandler, hyper: hyperHandler, msg: msgHandler, pubsub: pubsubHandler, topic: topicHandler, vid: vidHandler, rns: rnsHandler})
287 | sessionProtocol.handle('magnet', magnetHandler)
288 | globalProtocol.handle('magnet', magnetHandler)
289 |
290 | console.log('registered magnet protocol')
291 | // magnet
292 | }
293 |
--------------------------------------------------------------------------------
/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/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 = window.getCurrentWindow()
6 | // this.renderLatest()
7 | this.current = this.current ? this.current : window.getCurrentWindow()
8 | await this.renderLatest()
9 | }
10 |
11 | async renderLatest () {
12 | const current = this.current
13 |
14 | const actions = await current.listExtensionActions()
15 | this.innerHTML = ''
16 |
17 | for (const { title, icon, id, badge } of actions) {
18 | const button = document.createElement('button')
19 | button.setAttribute('class', 'browser-actions-button')
20 | button.setAttribute('title', title)
21 | button.addEventListener('click', () => {
22 | current.clickExtensionAction(id)
23 | })
24 | const img = document.createElement('img')
25 | img.setAttribute('class', 'browser-actions-icon')
26 | img.setAttribute('src', icon)
27 |
28 | button.append(img)
29 |
30 | if (badge && badge.text) {
31 | const badgeItem = document.createElement('div')
32 |
33 | const badgeColor = badge.color || 'inherit'
34 | const badgeBackground = badge.background || 'none'
35 | let badgeStyle = ''
36 | if (badge.color) badgeStyle += `color: ${badgeColor};`
37 | if (badge.background) badgeStyle += `background: ${badgeBackground};`
38 |
39 | badgeItem.innerText = badge.text
40 | badgeItem.setAttribute('class', 'browser-actions-badge')
41 | badgeItem.setAttribute('style', badgeStyle)
42 | button.append(badgeItem)
43 | }
44 |
45 | this.appendChild(button)
46 | }
47 | }
48 |
49 | get tabId () {
50 | return this.getAttribute('tab-id')
51 | }
52 | }
53 |
54 | customElements.define('browser-actions', BrowserActions)
55 |
--------------------------------------------------------------------------------
/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 | ]
15 |
16 | class CurrentWindow extends EventEmitter {
17 | constructor () {
18 | super()
19 |
20 | for (const name of EVENTS) {
21 | ipcRenderer.on(`hybrid-window-${name}`, (event, ...args) => this.emit(name, ...args))
22 | }
23 | }
24 |
25 | async goBack () {
26 | return this.invoke('goBack')
27 | }
28 |
29 | async goForward () {
30 | return this.invoke('goForward')
31 | }
32 |
33 | async reload () {
34 | return this.invoke('reload')
35 | }
36 |
37 | async focus () {
38 | return this.invoke('focus')
39 | }
40 |
41 | async loadURL (url) {
42 | return this.invoke('loadURL', url)
43 | }
44 |
45 | async getURL () {
46 | return this.invoke('getURL')
47 | }
48 |
49 | async findInPage (value, opts) {
50 | return this.invoke('findInPage', value, opts)
51 | }
52 |
53 | async stopFindInPage () {
54 | return this.invoke('stopFindInPage')
55 | }
56 |
57 | async setBounds (rect) {
58 | return this.invoke('setBounds', rect)
59 | }
60 |
61 | async searchHistory (query, limit = 8) {
62 | return this.invoke('searchHistory', query, limit)
63 | }
64 |
65 | async listExtensionActions () {
66 | return this.invoke('listExtensionActions')
67 | }
68 |
69 | async clickExtensionAction (id) {
70 | return this.invoke('clickExtensionAction', id)
71 | }
72 |
73 | async invoke (name, ...args) {
74 | return ipcRenderer.invoke(`hybrid-window-${name}`, ...args)
75 | }
76 | }
77 |
78 | return new CurrentWindow()
79 | }
80 |
--------------------------------------------------------------------------------
/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 |
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 |
26 | `
27 | this.backButton = this.$('.omni-box-back')
28 | this.forwardButton = this.$('.omni-box-forward')
29 | this.form = this.$('.omni-box-form')
30 | this.input = this.$('.omni-box-input')
31 | this.targetUrl = this.$('.omni-box-target-input')
32 | this.homeButton = this.$('.omni-box-home')
33 |
34 | this.input.addEventListener('focus', () => {
35 | this.input.select()
36 | })
37 |
38 | this.targetUrl.addEventListener('focus', () => {
39 | this.showInput()
40 | this.input.select()
41 | })
42 |
43 | this.input.addEventListener('blur', () => {
44 | this.input.blur()
45 | })
46 |
47 | this.form.addEventListener('submit', (e) => {
48 | e.preventDefault(true)
49 |
50 | const rawURL = this.getURL()
51 |
52 | let url = rawURL
53 |
54 | if (!isURL(rawURL)) {
55 | if (isBareLocalhost(rawURL)) {
56 | url = makeHttp(rawURL)
57 | } else if (looksLikeDomain(rawURL)) {
58 | url = makeHttps(rawURL)
59 | } else {
60 | url = makeDuckDuckGo(rawURL)
61 | }
62 | }
63 |
64 | this.clearOptions()
65 |
66 | const searchID = Date.now()
67 | this.lastSearch = searchID
68 |
69 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } }))
70 | })
71 | this.input.addEventListener('input', () => {
72 | this.updateOptions()
73 | })
74 | this.input.addEventListener('keydown', ({ keyCode, key }) => {
75 | // Pressed down arrow
76 | if (keyCode === 40) this.selectNext()
77 |
78 | // Pressed up arrow
79 | if (keyCode === 38) this.selectPrevious()
80 |
81 | if (keyCode === 39) {
82 | const { selectionStart, selectionEnd, value } = this.input
83 | const isAtEnd = (selectionStart === value.length) && (selectionEnd === value.length)
84 | if (isAtEnd) this.fillWithSelected()
85 | }
86 |
87 | if (key === 'Escape') {
88 | this.clearOptions()
89 | this.input.blur()
90 | this.dispatchEvent(new CustomEvent('unfocus'))
91 | }
92 | })
93 |
94 | this.backButton.addEventListener('click', () => {
95 | this.dispatchEvent(new CustomEvent('back'))
96 | })
97 | this.forwardButton.addEventListener('click', () => {
98 | this.dispatchEvent(new CustomEvent('forward'))
99 | })
100 | this.homeButton.addEventListener('click', () => {
101 | this.dispatchEvent(new CustomEvent('home'))
102 | })
103 |
104 | // middle mouse click paste&go
105 | this.input.addEventListener('paste', (e) => {
106 | const url = e.clipboardData.getData('text')
107 |
108 | if (isURL(url)) {
109 | e.preventDefault()
110 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } }))
111 | }
112 | })
113 | }
114 |
115 | clearOptions () {
116 | this.options.innerHTML = ''
117 | }
118 |
119 | getURL () {
120 | const item = this.getSelected()
121 |
122 | return item ? item.dataset.url : this.input.value
123 | }
124 |
125 | getSelected () {
126 | return (this.options.querySelector('[data-selected]') || this.options.firstElementChild)
127 | }
128 |
129 | selectNext () {
130 | const item = this.getSelected()
131 |
132 | if (!item) return
133 |
134 | const sibling = item.nextElementSibling
135 |
136 | if (!sibling) return
137 |
138 | item.removeAttribute('data-selected')
139 | sibling.setAttribute('data-selected', 'selected')
140 | }
141 |
142 | selectPrevious () {
143 | const item = this.getSelected()
144 |
145 | if (!item) return
146 |
147 | const sibling = item.previousElementSibling
148 |
149 | if (!sibling) return
150 |
151 | item.removeAttribute('data-selected')
152 | sibling.setAttribute('data-selected', 'selected')
153 | }
154 |
155 | fillWithSelected () {
156 | const item = this.getSelected()
157 |
158 | if (!item) return
159 |
160 | const { url } = item.dataset
161 |
162 | this.input.value = url
163 | }
164 |
165 | async updateOptions () {
166 | const query = this.input.value
167 |
168 | const searchID = Date.now()
169 | this.lastSearch = searchID
170 |
171 | this.clearOptions()
172 |
173 | if (!query) {
174 | return
175 | }
176 |
177 | this.dispatchEvent(new CustomEvent('search', { detail: { query, searchID } }))
178 | }
179 |
180 | async setSearchResults (results, query, searchID) {
181 | if (this.lastSearch !== searchID) {
182 | return console.debug('Urlbar changed since query finished', this.lastSearch, searchID, query)
183 | }
184 |
185 | const finalItems = []
186 |
187 | if (isURL(query)) {
188 | finalItems.push(this.makeNavItem(query, `Go to ${query}`))
189 | } else if (isBareLocalhost(query)) {
190 | finalItems.push(this.makeNavItem(makeHttp(query), `Go to http://${query}`))
191 | } else if (looksLikeDomain(query)) {
192 | finalItems.push(this.makeNavItem(makeHttps(query), `Go to https://${query}`))
193 | } else {
194 | finalItems.push(
195 | this.makeNavItem(
196 | makeDuckDuckGo(query),
197 | `Search for "${query}" on DuckDuckGo`
198 | )
199 | )
200 | }
201 |
202 | finalItems.push(...results
203 | .map(({ title, url }) => this.makeNavItem(url, `${title} - ${url}`))
204 | )
205 |
206 | for (const item of finalItems) {
207 | this.options.appendChild(item)
208 | }
209 |
210 | this.getSelected().setAttribute('data-selected', 'selected')
211 | }
212 |
213 | makeNavItem (url, text) {
214 | const element = document.createElement('button')
215 | element.classList.add('omni-box-nav-item')
216 | element.classList.add('omni-box-button')
217 | element.dataset.url = url
218 | element.innerText = text
219 | element.onclick = () => {
220 | this.clearOptions()
221 |
222 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } }))
223 | }
224 | return element
225 | }
226 |
227 | static get observedAttributes () {
228 | return ['src', 'back', 'forward']
229 | }
230 |
231 | attributeChangedCallback (name, oldValue, newValue) {
232 | if (name === 'src') {
233 | this.input.value = newValue
234 | const noFocus = window.searchParams.get('noFocus') === 'true'
235 | if (noFocus) {
236 | return
237 | }
238 | if (this.firstLoad && (newValue === window.DEFAULT_PAGE)) {
239 | this.firstLoad = false
240 | this.focus()
241 | }
242 | } if (name === 'back') {
243 | this.backButton.classList.toggle('hidden', newValue === 'hidden')
244 | } else if (name === 'forward') {
245 | this.forwardButton.classList.toggle('hidden', newValue === 'hidden')
246 | }
247 | }
248 |
249 | get src () {
250 | return this.input.value
251 | }
252 |
253 | set src (value) {
254 | this.setAttribute('src', value)
255 | }
256 |
257 | showInput (show = true) {
258 | this.targetUrl.classList.toggle('hidden', show)
259 | this.input.classList.toggle('hidden', !show)
260 | }
261 |
262 | showTarget (url) {
263 | this.targetUrl.value = url
264 | const inputSelected = this.input === document.activeElement
265 |
266 | if (url && !inputSelected) {
267 | this.showInput(false)
268 | } else {
269 | this.showInput(true)
270 | }
271 | }
272 |
273 | focus () {
274 | this.input.focus()
275 | this.input.select()
276 | }
277 |
278 | $ (query) {
279 | return this.querySelector(query)
280 | }
281 |
282 | convertURL (rawURL) {
283 | }
284 | }
285 |
286 | function makeHttp (query) {
287 | return `http://${query}`
288 | }
289 |
290 | function makeHttps (query) {
291 | return `https://${query}`
292 | }
293 |
294 | function makeDuckDuckGo (query) {
295 | return `https://duckduckgo.com/?q=${encodeURIComponent(query)}`
296 | }
297 |
298 | function isURL (string) {
299 | try {
300 | // localhost: is a valid url apparently!
301 | if (isBareLocalhost(string)) return false
302 | return !!new URL(string)
303 | } catch {
304 | return false
305 | }
306 | }
307 |
308 | function looksLikeDomain (string) {
309 | return !string.match(/\s/) && string.includes('.')
310 | }
311 |
312 | function isBareLocalhost (string) {
313 | return string.match(/^localhost(:[0-9]+)?\/?$/)
314 | }
315 |
316 | customElements.define('omni-box', OmniBox)
317 |
--------------------------------------------------------------------------------
/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('home', () => {
49 | navigateTo('hybrid://welcome').catch(console.error)
50 | })
51 |
52 | search.addEventListener('navigate', ({ detail }) => {
53 | const { url } = detail
54 |
55 | navigateTo(url).catch(console.error)
56 | })
57 |
58 | search.addEventListener('unfocus', async () => {
59 | await currentWindow.focus()
60 | search.src = await currentWindow.getURL()
61 | })
62 |
63 | search.addEventListener('search', async ({ detail }) => {
64 | const { query, searchID } = detail
65 |
66 | const results = await currentWindow.searchHistory(query, searchID)
67 |
68 | search.setSearchResults(results, query, searchID)
69 | })
70 |
71 | webview.addEventListener('focus', () => {
72 | currentWindow.focus()
73 | })
74 |
75 | webview.addEventListener('resize', ({ detail: rect }) => {
76 | currentWindow.setBounds(rect)
77 | })
78 |
79 | currentWindow.on('navigating', (url) => {
80 | search.src = url
81 | })
82 |
83 | currentWindow.on('history-buttons-change', updateButtons)
84 |
85 | currentWindow.on('page-title-updated', (title) => {
86 | pageTitle.innerText = title + ' - Hybrid Browser'
87 | })
88 | currentWindow.on('enter-html-full-screen', () => {
89 | if (!rawFrame) nav.classList.toggle('hidden', true)
90 | })
91 | currentWindow.on('leave-html-full-screen', () => {
92 | if (!rawFrame) nav.classList.toggle('hidden', false)
93 | })
94 | currentWindow.on('update-target-url', async (url) => {
95 | // if(search.showTarget){
96 | search.showTarget(url)
97 | // }
98 | })
99 | currentWindow.on('browser-actions-changed', () => {
100 | actions.renderLatest()
101 | })
102 |
103 | find.addEventListener('next', ({ detail }) => {
104 | const { value, findNext } = detail
105 |
106 | currentWindow.findInPage(value, { findNext })
107 | })
108 |
109 | find.addEventListener('previous', ({ detail }) => {
110 | const { value, findNext } = detail
111 |
112 | currentWindow.findInPage(value, { forward: false, findNext })
113 | })
114 |
115 | find.addEventListener('hide', () => {
116 | currentWindow.stopFindInPage('clearSelection')
117 | })
118 |
119 | function updateButtons ({ canGoBack, canGoForward }) {
120 | search.setAttribute('back', canGoBack ? 'visible' : 'hidden')
121 | search.setAttribute('forward', canGoForward ? 'visible' : 'hidden')
122 | }
123 |
124 | function $ (query) {
125 | return document.querySelector(query)
126 | }
127 |
128 | async function navigateTo (url) {
129 | const currentURL = await currentWindow.getURL()
130 | if (currentURL === url) {
131 | console.log('Reloading')
132 | currentWindow.reload()
133 | } else {
134 | currentWindow.loadURL(url)
135 | currentWindow.focus()
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/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 {
18 | defaultPage,
19 | autoHideMenuBar: DEFAULT_AUTO_HIDE_MENU_BAR
20 | } = Config
21 |
22 | const IS_DEBUG = process.env.NODE_ENV === 'debug'
23 |
24 | const __dirname = fileURLToPath(new URL('./', import.meta.url))
25 |
26 | const MAIN_PAGE = path.join(__dirname, './ui/index.html')
27 | const LOGO_FILE = path.join(__dirname, './../build/icon-small.png')
28 | const PERSIST_FILE = path.join(app.getPath('userData'), 'lastOpened.json')
29 |
30 | const DEFAULT_SAVE_INTERVAL = 30 * 1000
31 |
32 | // See if we have any stylesheets with rules
33 | // If not manually inject styles to be like Hybrid
34 | const HAS_SHEET = `
35 | [...document.styleSheets].filter((sheet) => {
36 | try {sheet.cssRules; return true} catch {return false}
37 | }).length || !!document.querySelector('[style]')
38 | `
39 |
40 | const WINDOW_METHODS = [
41 | 'goBack',
42 | 'goForward',
43 | 'reload',
44 | 'focus',
45 | 'loadURL',
46 | 'getURL',
47 | 'findInPage',
48 | 'stopFindInPage',
49 | 'setBounds',
50 | 'searchHistory',
51 | 'listExtensionActions',
52 | 'clickExtensionAction'
53 | ]
54 |
55 | const BLINK_FLAGS = [
56 | 'WebBluetooth',
57 | 'WebBluetoothGetDevices',
58 | 'WebBluetoothRemoteCharacteristicNewWriteValue',
59 | 'WebBluetoothWatchAdvertisements',
60 | 'CSSModules'
61 | ].join(',')
62 |
63 | async function DEFAULT_SEARCH () {
64 | return []
65 | }
66 |
67 | async function DEFAULT_LIST_ACTIONS () {
68 | return []
69 | }
70 |
71 | // How long to wait before showing windows
72 | const SHOW_DELAY = 200
73 |
74 | // Used to only show one window at a time
75 | const showQueue = new PQueue({concurrency: 1})
76 |
77 | export class WindowManager extends EventEmitter {
78 | constructor ({
79 | onSearch = DEFAULT_SEARCH,
80 | listActions = DEFAULT_LIST_ACTIONS,
81 | persistTo = PERSIST_FILE,
82 | saverInterval = DEFAULT_SAVE_INTERVAL
83 | } = {}) {
84 | super()
85 | this.windows = new Set()
86 | this.onSearch = onSearch
87 | this.listActions = listActions
88 | this.persistTo = persistTo
89 | this.saverTimer = null
90 | this.saverInterval = saverInterval
91 |
92 | for (const method of WINDOW_METHODS) {
93 | this.relayMethod(method)
94 | }
95 | }
96 |
97 | open (opts = {}) {
98 | const { onSearch, listActions } = this
99 | const window = new Window({
100 | onSearch,
101 | listActions,
102 | ...opts
103 | })
104 |
105 | console.log('created window', window.id)
106 | this.windows.add(window)
107 | window.once('close', () => {
108 | this.windows.delete(window)
109 | this.emit('close', window)
110 | })
111 | window.on('navigating', () => {
112 | this.restartSaver()
113 | })
114 | this.emit('open', window)
115 |
116 | window.load()
117 |
118 | return window
119 | }
120 |
121 | relayMethod (name) {
122 | ipcMain.handle(`hybrid-window-${name}`, ({ sender }, ...args) => {
123 | const { id } = sender
124 | if (IS_DEBUG) console.log('<-', id, name, '(', args, ')')
125 | const window = this.get(id)
126 | if (!window) return console.warn(`Got method ${name} from invalid frame ${id}`)
127 | return window[name](...args)
128 | })
129 | }
130 |
131 | reloadBrowserActions (tabId) {
132 | for (const window of this.all) {
133 | if (tabId) {
134 | if (window.web.id === tabId) {
135 | window.send('browser-actions-changed')
136 | }
137 | } else {
138 | window.send('browser-actions-changed')
139 | }
140 | }
141 | }
142 |
143 | get (id) {
144 | for (const window of this.windows) {
145 | if (window.id === id) return window
146 | }
147 | return null
148 | }
149 |
150 | get all () {
151 | return [...this.windows.values()]
152 | }
153 |
154 | saveOpened () {
155 | console.log('Saving open windows')
156 | let urls = []
157 | for (const window of this.all) {
158 | // We don't need to save popups from extensions
159 | if (window.rawFrame) continue
160 | const url = window.web.getURL()
161 | const position = window.window.getPosition()
162 | const size = window.window.getSize()
163 |
164 | urls.push({ url, position, size })
165 | }
166 |
167 | if (urls.length === 1) urls = []
168 |
169 | fs.outputJsonSync(this.persistTo, urls)
170 | }
171 |
172 | async openSaved () {
173 | const saved = await this.loadSaved()
174 |
175 | return saved.map((info) => {
176 | console.log('About to open', info)
177 | const options = {
178 | noFocus: true
179 | }
180 |
181 | const { url, position, size } = info
182 |
183 | options.url = url
184 |
185 | if (position) {
186 | const [x, y] = position
187 | options.x = x
188 | options.y = y
189 | }
190 |
191 | if (size) {
192 | const [width, height] = size
193 | options.width = width
194 | options.height = height
195 | }
196 |
197 | const window = this.open(options)
198 |
199 | return window
200 | })
201 | }
202 |
203 | async loadSaved () {
204 | try {
205 | const infos = await fs.readJson(this.persistTo)
206 | return infos
207 | } catch (e) {
208 | console.error('Error loading saved windows', e.stack)
209 | return []
210 | }
211 | }
212 |
213 | close () {
214 | this.clearSaver()
215 | }
216 |
217 | restartSaver () {
218 | this.clearSaver()
219 | this.startSaver()
220 | }
221 |
222 | startSaver () {
223 | this.saverTimer = setTimeout(() => {
224 | this.saveOpened()
225 | }, this.saverInterval)
226 | }
227 |
228 | clearSaver () {
229 | clearInterval(this.saverTimer)
230 | }
231 | }
232 |
233 | export class Window extends EventEmitter {
234 | constructor ({
235 | url = defaultPage,
236 | popup = false,
237 | rawFrame = false || popup,
238 | autoResize = false || popup,
239 | noNav = false,
240 | noFocus = false,
241 | onSearch,
242 | listActions,
243 | view,
244 | autoHideMenuBar = DEFAULT_AUTO_HIDE_MENU_BAR || popup,
245 | ...opts
246 | } = {}) {
247 | super()
248 |
249 | this.onSearch = onSearch
250 | this.listActions = listActions
251 | this.rawFrame = rawFrame
252 |
253 | this.window = new BrowserWindow({
254 | autoHideMenuBar,
255 | webPreferences: {
256 | // partition: 'persist:web-content',
257 | defaultEncoding: 'utf-8',
258 | nodeIntegration: true,
259 | webviewTag: false,
260 | contextIsolation: false
261 | },
262 | show: false,
263 | icon: LOGO_FILE,
264 | ...opts
265 | })
266 | this.view = view || new BrowserView({
267 | webPreferences: {
268 | partition: 'persist:web-content',
269 | defaultEncoding: 'utf-8',
270 | nodeIntegration: false,
271 | sandbox: true,
272 | webviewTag: false,
273 | contextIsolation: true,
274 | enableBlinkFeatures: BLINK_FLAGS,
275 | enablePreferredSizeMode: autoResize
276 | }
277 | })
278 |
279 | this.window.setBrowserView(this.view)
280 |
281 | this.web.on('did-start-navigation', (event, url, isInPlace, isMainFrame) => {
282 | this.emitNavigate(url, isMainFrame)
283 | })
284 | this.web.on('did-navigate', (event, url) => {
285 | this.emitNavigate(url, true)
286 | })
287 | this.web.on('did-navigate-in-page', (event, url, isMainFrame) => {
288 | this.emitNavigate(url, isMainFrame)
289 | })
290 |
291 | if (autoResize) {
292 | let reloaded = false
293 | this.web.on('preferred-size-changed', (event, preferredSize) => {
294 | const { width, height } = preferredSize
295 | if (IS_DEBUG) console.log('Preferred size', this.id, preferredSize)
296 | this.window.setSize(width, height, false)
297 | this.view.setBounds({
298 | x: 0,
299 | y: 0,
300 | width,
301 | height
302 | })
303 |
304 | if (!reloaded) {
305 | reloaded = true
306 | this.web.invalidate()
307 | }
308 | })
309 | }
310 |
311 | if (popup) {
312 | this.web.focus()
313 | this.window.once('blur', () => {
314 | if (this.web.isFocused() || this.webContents.isFocused()) return
315 | if (this.web.isDevToolsOpened() || this.webContents.isDevToolsOpened()) return
316 | this.window.close()
317 | })
318 | }
319 |
320 | // Send to UI
321 | this.web.on('page-title-updated', (event, title) => {
322 | this.send('page-title-updated', title)
323 | })
324 | this.window.on('enter-html-full-screen', () => {
325 | this.send('enter-html-full-screen')
326 | })
327 | this.window.on('leave-html-full-screen', () => {
328 | this.send('leave-html-full-screen')
329 | })
330 | this.web.on('update-target-url', (event, url) => {
331 | this.send('update-target-url', url)
332 | })
333 |
334 | this.web.on('dom-ready', async () => {
335 | if (this.web.getURL() === 'hybrid://settings') {
336 | this.web.executeJavaScript(`window.onSettings(${JSON.stringify(Config)})`)
337 | }
338 | const hasStyles = await this.web.executeJavaScript(HAS_SHEET)
339 | console.log({ hasStyles })
340 | if (!hasStyles) {
341 | const style = await getDefaultStylesheet(this.web)
342 | await this.web.insertCSS(style)
343 | }
344 | })
345 |
346 | this.web.once('dom-ready', () => {
347 | showQueue.add(async () => {
348 | await this.window.show()
349 | await delay(SHOW_DELAY)
350 | })
351 | })
352 | this.window.on('close', () => {
353 | this.web.destroy()
354 | this.emit('close')
355 | })
356 |
357 | const toLoad = new URL(MAIN_PAGE, 'file:')
358 |
359 | if (url) toLoad.searchParams.set('url', url)
360 | if (rawFrame) toLoad.searchParams.set('rawFrame', 'true')
361 | if (noNav) toLoad.searchParams.set('noNav', 'true')
362 | if (noFocus) toLoad.searchParams.set('noFocus', 'true')
363 |
364 | this.toLoad = toLoad.href
365 | }
366 |
367 | load () {
368 | return this.window.loadURL(this.toLoad)
369 | }
370 |
371 | emitNavigate (url, isMainFrame) {
372 | if (!isMainFrame) return
373 | if (IS_DEBUG) console.log('Navigating', url)
374 | const canGoBack = this.web.canGoBack()
375 | const canGoForward = this.web.canGoForward()
376 |
377 | this.send('navigating', url)
378 | this.send('history-buttons-change', { canGoBack, canGoForward })
379 | }
380 |
381 | async goBack () {
382 | return this.web.goBack()
383 | }
384 |
385 | async goForward () {
386 | return this.web.goForward()
387 | }
388 |
389 | async reload () {
390 | return this.web.reload()
391 | }
392 |
393 | async focus () {
394 | return this.web.focus()
395 | }
396 |
397 | async loadURL (url) {
398 | return this.web.loadURL(url)
399 | }
400 |
401 | async getURL () {
402 | return this.web.getURL()
403 | }
404 |
405 | async findInPage (value, opts) {
406 | return this.web.findInPage(value, opts)
407 | }
408 |
409 | async stopFindInPage () {
410 | return this.web.stopFindInPage('clearSelection')
411 | }
412 |
413 | async searchHistory (...args) {
414 | return this.onSearch(...args)
415 | }
416 |
417 | async setBounds (rect) {
418 | // Fix non-integer heights causing draw break.
419 | // TODO: This should be fixed wherever rect is sent from, not sure where that is.
420 | Object.keys(rect).forEach(key => {
421 | rect[key] = Math.floor(rect[key])
422 | })
423 |
424 | return this.view.setBounds(rect)
425 | }
426 |
427 | async listExtensionActions () {
428 | const actions = await this.listActions(this)
429 | return actions.map(({
430 | title,
431 | extensionId: id,
432 | icon,
433 | badge,
434 | badgeColor,
435 | badgeBackground
436 | }) => {
437 | return {
438 | title,
439 | id,
440 | icon,
441 | badge: {
442 | text: badge,
443 | color: badgeColor,
444 | background: badgeBackground
445 | }
446 | }
447 | })
448 | }
449 |
450 | async clickExtensionAction (actionId) {
451 | await this.focus()
452 | for (const { extensionId, onClick } of await this.listActions()) {
453 | if (actionId !== extensionId) continue
454 | await onClick(this.web.id)
455 | }
456 | }
457 |
458 | send (name, ...args) {
459 | this.emit(name, ...args)
460 | if (IS_DEBUG) console.log('->', this.id, name, '(', args, ')')
461 | this.window.webContents.send(`hybrid-window-${name}`, ...args)
462 | }
463 |
464 | get web () {
465 | return this.view.webContents
466 | }
467 |
468 | get webContents () {
469 | return this.window.webContents
470 | }
471 |
472 | get id () {
473 | return this.window.webContents.id
474 | }
475 | }
476 |
477 | async function getDefaultStylesheet (webContents) {
478 | const [r1, r2] = await Promise.all([
479 | webContents.session.fetch('hybrid://theme/vars.css'),
480 | webContents.session.fetch('hybrid://theme/style.css')
481 | ])
482 |
483 | const [vars, style] = await Promise.all([
484 | r1.text(),
485 | r2.text()
486 | ])
487 | return vars + style
488 | }
489 |
--------------------------------------------------------------------------------
/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/build/icon-small.png
--------------------------------------------------------------------------------
/build/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HybridWare/hybrid-browser/8ce9960ebaf08f3c055431fd722ec039132c3bb3/build/icon.ico
--------------------------------------------------------------------------------
/build/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/HybridWare/hybrid-browser/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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/8ce9960ebaf08f3c055431fd722ec039132c3bb3/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": "^34.0.0",
183 | "electron-builder": "^23.6.0",
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 | "whatwg-mimetype": "github:jsdom/whatwg-mimetype"
229 | }
230 | }
231 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------