├── .gitmodules ├── agregore-demo-2.gif ├── src ├── pages │ ├── theme │ │ ├── FontWithASyntaxHighlighter-Regular.woff2 │ │ ├── example.md │ │ └── style.css │ ├── 404.html │ ├── welcome.html │ ├── icon.svg │ ├── settings.html │ └── settings │ │ └── theme.html ├── protocols │ ├── gemini-protocol.js │ ├── ssb-protocol.js │ ├── hyper-protocol.js │ ├── raw-http-protocol.js │ ├── web3-protocol.js │ ├── bt-protocol.js │ ├── magnet-protocol.js │ ├── fetch-to-handler.js │ ├── ipfs-protocol.js │ ├── browser-protocol.js │ └── index.js ├── settings-preload.js ├── ui │ ├── tracked-box.js │ ├── index.html │ ├── browser-actions.js │ ├── current-window.js │ ├── find-menu.js │ ├── style.css │ ├── script.js │ └── omni-box.js ├── history.js ├── extensions │ ├── builtins.json │ └── index.js ├── main.cjs ├── llm-preload.js ├── menu.js ├── context-menus.js ├── config.js ├── index.js ├── llm.js ├── actions.js └── window.js ├── docs ├── Fetch-Gemini.md ├── Bookmarks.md ├── README.md ├── Extensions.md ├── Protocols.md ├── Keyboard-Shortcuts.md ├── Troubleshooting.md ├── Theming.md ├── Fetch-IPFS.md └── Fetch-Hyper.md ├── update-versions.js ├── rebuild.sh ├── .travis.yml ├── .github └── workflows │ └── build.yml ├── download-extensions.js ├── .gitignore ├── README.md ├── package.json └── LICENSE /.gitmodules: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /agregore-demo-2.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AgregoreWeb/agregore-browser/HEAD/agregore-demo-2.gif -------------------------------------------------------------------------------- /src/pages/theme/FontWithASyntaxHighlighter-Regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AgregoreWeb/agregore-browser/HEAD/src/pages/theme/FontWithASyntaxHighlighter-Regular.woff2 -------------------------------------------------------------------------------- /src/pages/404.html: -------------------------------------------------------------------------------- 1 | 2 | Page Not Found 3 | 4 | 11 | 12 |

Page No Found

13 | Go back to welcome -------------------------------------------------------------------------------- /src/protocols/gemini-protocol.js: -------------------------------------------------------------------------------- 1 | import makeFetch from 'gemini-fetch' 2 | import fetchToHandler from './fetch-to-handler.js' 3 | 4 | export default async function createHandler () { 5 | return fetchToHandler(async () => { 6 | const fetch = makeFetch() 7 | 8 | return fetch 9 | }) 10 | } 11 | -------------------------------------------------------------------------------- /src/protocols/ssb-protocol.js: -------------------------------------------------------------------------------- 1 | import fetchToHandler from './fetch-to-handler.js' 2 | 3 | export default async function createHandler (options, session) { 4 | return fetchToHandler(async () => { 5 | const { default: makeSsbFetch } = await import('ssb-fetch') 6 | 7 | const fetch = makeSsbFetch(options) 8 | 9 | return fetch 10 | }, session) 11 | } 12 | -------------------------------------------------------------------------------- /src/settings-preload.js: -------------------------------------------------------------------------------- 1 | const { contextBridge, ipcRenderer, webFrame } = require('electron') 2 | 3 | webFrame.top.executeJavaScript('window.location.href').then((url) => { 4 | if (url.startsWith('agregore://settings')) { 5 | contextBridge.exposeInMainWorld('settings', { 6 | save: (args) => ipcRenderer.invoke('settings-save', args) 7 | }) 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /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 agregore-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/Bookmarks.md: -------------------------------------------------------------------------------- 1 | # Bookmarks 2 | 3 | Bookmarks are stored as files. If you wish to specify the path to agregore set the `appPath` property in your `.agregorerc` config file. You may need to do this if you've moved an agregore 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/agregore-browser" 10 | } 11 | ``` -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Agregore 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 Agregore 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 | -------------------------------------------------------------------------------- /src/protocols/hyper-protocol.js: -------------------------------------------------------------------------------- 1 | import fetchToHandler from './fetch-to-handler.js' 2 | 3 | export default async function createHandler (options, session) { 4 | return fetchToHandler(async () => { 5 | const { default: hyperFetch } = await import('hypercore-fetch') 6 | const SDK = await import('hyper-sdk') 7 | 8 | const sdk = await SDK.create(options) 9 | const fetch = await hyperFetch({ 10 | sdk, 11 | writable: true 12 | }) 13 | 14 | console.log({ sdk, fetch }) 15 | 16 | fetch.close = () => sdk.close() 17 | 18 | return fetch 19 | }, session) 20 | } 21 | -------------------------------------------------------------------------------- /src/protocols/raw-http-protocol.js: -------------------------------------------------------------------------------- 1 | import fetchToHandler from './fetch-to-handler.js' 2 | 3 | export default async function createHandler () { 4 | return fetchToHandler(async () => { 5 | return async function rawFetch ({ url, headers, ...options } = {}) { 6 | const finalURL = url.replace('https+raw:', 'https:') 7 | const response = await fetch(finalURL, { 8 | headers, 9 | redirect: 'follow', 10 | credentials: 'omit', 11 | cache: 'no-store', 12 | referrerPolicy: 'no-referrer' 13 | }) 14 | 15 | return response 16 | } 17 | }) 18 | } 19 | -------------------------------------------------------------------------------- /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('./src/version.js', fileContents) 19 | 20 | console.log('Done!') 21 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/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 | -------------------------------------------------------------------------------- /src/protocols/web3-protocol.js: -------------------------------------------------------------------------------- 1 | /* globals Response */ 2 | import { Client } from 'web3protocol' 3 | import fetchToHandler from './fetch-to-handler.js' 4 | 5 | export default async function createHandler (options) { 6 | return fetchToHandler(async () => { 7 | const { chainList, ...opts } = options 8 | const web3Client = new Client(chainList, opts) 9 | async function fetch ({ url, method }) { 10 | if (method !== 'GET') { 11 | return new Response('Method Not Allowed', { 12 | status: 405 13 | }) 14 | } 15 | const { httpCode, httpHeaders, output } = await web3Client.fetchUrl(url) 16 | 17 | return new Response(output, { status: httpCode, headers: httpHeaders }) 18 | } 19 | 20 | return fetch 21 | }) 22 | } 23 | -------------------------------------------------------------------------------- /src/protocols/bt-protocol.js: -------------------------------------------------------------------------------- 1 | /* global globalThis */ 2 | import fetchToHandler from './fetch-to-handler.js' 3 | 4 | export default async function createHandler (options, session) { 5 | return fetchToHandler(async () => { 6 | // This enables webtorrent-hybrid functionality 7 | // https://github.com/webtorrent/webtorrent-hybrid/blob/v4.1.3/lib/global.js 8 | const { default: createTorrent } = await import('create-torrent') 9 | const { default: wrtc } = await import('@roamhq/wrtc') 10 | globalThis.WEBTORRENT_ANNOUNCE = createTorrent.announceList 11 | .map(arr => arr[0]) 12 | .filter(url => url.indexOf('wss://') === 0 || url.indexOf('ws://') === 0) 13 | globalThis.WRTC = wrtc 14 | 15 | const { default: makeFetch } = await import('bt-fetch') 16 | 17 | const fetch = makeFetch(options) 18 | 19 | return fetch 20 | }, session) 21 | } 22 | -------------------------------------------------------------------------------- /src/history.js: -------------------------------------------------------------------------------- 1 | let getBackgroundPage = null 2 | let viewPage = null 3 | 4 | export function setGetBackgroundPage (backgroundPage) { 5 | getBackgroundPage = backgroundPage 6 | } 7 | 8 | export function setViewPage (page) { 9 | viewPage = page 10 | } 11 | 12 | export function getViewPage () { 13 | return viewPage 14 | } 15 | 16 | export async function * search (query = '', ...args) { 17 | const searchArgs = JSON.stringify([query, ...args]).slice(1, -1) 18 | const webContents = await getBackgroundPage() 19 | await webContents.executeJavaScript(` 20 | if(window.lastSearch?.return) { 21 | window.lastSearch?.return() 22 | } 23 | window.lastSearch = search(${searchArgs}); 24 | null 25 | `) 26 | 27 | while (true) { 28 | const { done, value } = await webContents 29 | .executeJavaScript('window.lastSearch.next()') 30 | 31 | if (done) break 32 | yield value 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /docs/Extensions.md: -------------------------------------------------------------------------------- 1 | # Installing extensions 2 | 3 | Agregore 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 Agregore 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 | Agregore 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 `.agregorerc` 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/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 | -------------------------------------------------------------------------------- /src/ui/index.html: -------------------------------------------------------------------------------- 1 | 2 | Agregore Browser 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 |
22 | 23 | 24 | 25 |
26 | 27 |
28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /docs/Keyboard-Shortcuts.md: -------------------------------------------------------------------------------- 1 | # Configuring keyboard shortcuts 2 | 3 | Agregore 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 `.agregorerc` 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 | -------------------------------------------------------------------------------- /src/extensions/builtins.json: -------------------------------------------------------------------------------- 1 | { 2 | "agregore-history": { 3 | "version": "2.0.1", 4 | "url": "https://github.com/AgregoreWeb/extension-agregore-history/releases/download/v{version}/agregore-history-v{version}.zip" 5 | }, 6 | "agregore-renderer": { 7 | "version": "2.3.1", 8 | "url": "https://github.com/AgregoreWeb/extension-agregore-renderer/releases/download/v{version}/agregore-renderer-v{version}.zip" 9 | }, 10 | "agregore-qr-share": { 11 | "version": "1.0.1", 12 | "url": "https://github.com/AgregoreWeb/extension-agregore-qr-share/releases/download/v{version}/agregore-qr-share-v{version}.zip" 13 | }, 14 | "consent-autodeny": { 15 | "version": "1.0.0", 16 | "url": "https://github.com/AgregoreWeb/extension-consent-autodeny/releases/download/v{version}/extension-consent-autodeny-v{version}.zip" 17 | }, 18 | "archiveweb.page": { 19 | "version": "0.10.0", 20 | "url": "https://github.com/webrecorder/archiveweb.page/releases/download/v{version}/ArchiveWeb.page-{version}-extension.zip" 21 | }, 22 | "ublock": { 23 | "version": "1.47.4", 24 | "url": "https://github.com/gorhill/uBlock/releases/download/{version}/uBlock0_{version}.chromium.zip", 25 | "stripPrefix": "uBlock0.chromium/" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /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/agregore/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 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build/release 2 | 3 | on: 4 | push: 5 | ## Run on tags starting with `v*` 6 | tags: 7 | - 'v*' 8 | 9 | # Allows you to run this workflow manually from the Actions tab 10 | workflow_dispatch: 11 | 12 | jobs: 13 | release: 14 | continue-on-error: true 15 | runs-on: ${{ matrix.os }} 16 | 17 | strategy: 18 | matrix: 19 | os: [macos-latest, ubuntu-latest, windows-latest] 20 | 21 | steps: 22 | - name: Install libarchive-tools for pacman build # Related https://github.com/electron-userland/electron-builder/issues/4181 23 | if: startsWith(matrix.os, 'ubuntu') 24 | run: sudo apt-get install libarchive-tools 25 | 26 | - name: Check out Git repository 27 | uses: actions/checkout@v3 28 | with: 29 | submodules: true 30 | 31 | - name: Install Node.js, NPM and Yarn 32 | uses: actions/setup-node@v3 33 | with: 34 | node-version: 'lts/*' 35 | 36 | - name: Build binaries with electron-builder 37 | uses: coparse-inc/action-electron-builder@29a7606c7d726b5b0f4dc2f334026f58bea0e1bb # v1.6.0 but safer than a tag that can be changed 38 | with: 39 | max_attempts: 2 40 | # GH token for attaching atrifacts to release draft on tag build 41 | github_token: ${{ secrets.github_token }} 42 | # If the commit is tagged with a version (e.g. "v1.0.0"), 43 | # release the app after building 44 | release: ${{ startsWith(github.ref, 'refs/tags/v') }} 45 | -------------------------------------------------------------------------------- /src/protocols/magnet-protocol.js: -------------------------------------------------------------------------------- 1 | /* global Response */ 2 | const INFO_HASH_MATCH = /^urn:btih:([a-f0-9]{40})$/ig 3 | const PUBLIC_KEY_MATCH = /^urn:btpk:([a-f0-9]{64})$/ig 4 | 5 | export default async function createHandler () { 6 | return function magnetHandler (req) { 7 | try { 8 | const parsed = new URL(req.url) 9 | 10 | const xt = parsed.searchParams.get('xt') 11 | const xs = parsed.searchParams.get('xs') 12 | 13 | if (xs) { 14 | const match = PUBLIC_KEY_MATCH.exec(xs) 15 | if (match) { 16 | const publicKey = match[1] 17 | const final = `bittorrent://${publicKey}` 18 | return sendFinal(final) 19 | } 20 | } 21 | if (xt) { 22 | const match = INFO_HASH_MATCH.exec(xt) 23 | if (!match) { 24 | return sendError('Magnet has no bittorrent infohash') 25 | } 26 | const infohash = match[1] 27 | const final = `bittorrent://${infohash}/` 28 | return sendFinal(final) 29 | } 30 | 31 | return sendError('Magnet link has no `xt` or `xs` parameter') 32 | } catch (e) { 33 | return sendError(e.stack) 34 | } 35 | 36 | function sendFinal (Location) { 37 | return new Response('', { 38 | status: 308, 39 | headers: { 40 | Location 41 | } 42 | }) 43 | } 44 | 45 | function sendError (message) { 46 | return new Response(message, { 47 | statusCode: 400, 48 | headers: { 49 | 'content-type': 'text/html' 50 | } 51 | }) 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main.cjs: -------------------------------------------------------------------------------- 1 | const { protocol } = require('electron') 2 | const path = require('path') 3 | const { pathToFileURL } = require('url') 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 | protocol.registerSchemesAsPrivileged([ 34 | { scheme: 'https+raw', privileges: P2P_PRIVILEGES }, 35 | { scheme: 'hyper', privileges: P2P_PRIVILEGES }, 36 | { scheme: 'gemini', privileges: P2P_PRIVILEGES }, 37 | { scheme: 'ipfs', privileges: P2P_PRIVILEGES }, 38 | { scheme: 'ipns', privileges: P2P_PRIVILEGES }, 39 | { scheme: 'ipld', privileges: P2P_PRIVILEGES }, 40 | { scheme: 'pubsub', privileges: P2P_PRIVILEGES }, 41 | { scheme: 'bittorrent', privileges: P2P_PRIVILEGES }, 42 | { scheme: 'bt', privileges: P2P_PRIVILEGES }, 43 | { scheme: 'ssb', privileges: P2P_PRIVILEGES }, 44 | { scheme: 'agregore', privileges: BROWSER_PRIVILEGES }, 45 | { scheme: 'magnet', privileges: LOW_PRIVILEGES } 46 | ]) 47 | 48 | const indexFile = path.join(__dirname, 'index.js') 49 | .replace(`.asar${path.sep}`, `.asar.unpacked${path.sep}`) 50 | 51 | import(pathToFileURL(indexFile)).catch((e) => { 52 | console.error(e.stack) 53 | process.exit(1) 54 | }) 55 | -------------------------------------------------------------------------------- /src/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 | } 8 | 9 | async renderLatest () { 10 | const current = this.current 11 | 12 | const actions = await current.listExtensionActions() 13 | this.innerHTML = '' 14 | 15 | for (const { title, icon, id, badge } of actions) { 16 | const button = document.createElement('button') 17 | button.setAttribute('class', 'browser-actions-button') 18 | button.setAttribute('title', title) 19 | button.addEventListener('click', () => { 20 | current.clickExtensionAction(id) 21 | }) 22 | const img = document.createElement('img') 23 | img.setAttribute('class', 'browser-actions-icon') 24 | img.setAttribute('src', icon) 25 | 26 | button.append(img) 27 | 28 | if (badge && badge.text) { 29 | const badgeItem = document.createElement('div') 30 | 31 | const badgeColor = badge.color || 'inherit' 32 | const badgeBackground = badge.background || 'none' 33 | let badgeStyle = '' 34 | if (badge.color) badgeStyle += `color: ${badgeColor};` 35 | if (badge.background) badgeStyle += `background: ${badgeBackground};` 36 | 37 | badgeItem.innerText = badge.text 38 | badgeItem.setAttribute('class', 'browser-actions-badge') 39 | badgeItem.setAttribute('style', badgeStyle) 40 | button.append(badgeItem) 41 | } 42 | 43 | this.appendChild(button) 44 | } 45 | } 46 | 47 | get tabId () { 48 | return this.getAttribute('tab-id') 49 | } 50 | } 51 | 52 | customElements.define('browser-actions', BrowserActions) 53 | -------------------------------------------------------------------------------- /src/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://agregore.mauve.moe 14 | 15 | [Custom link text](https://agregore.mauve.moe) 16 | 17 | ```javascript 18 | HELLO.world("HI") 19 | ``` 20 | 21 |
22 | Show and hide details 23 | Example content hidden in some details. 24 |
25 | 26 | ## Forms 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 40 | 44 | 49 | 50 | 51 | 52 | ## Media 53 | 54 | ### Image 55 | 56 | ![AGREGORE Logo](agregore://icon.svg) 57 | 58 | ### Video 59 | 60 | 61 | 62 | ### Audio 63 | 64 | 65 | 66 | ### Iframe 67 | 68 | 69 | 70 | ### Tables (try sorting) 71 | 72 | | ID | Name | Age | Score | Date | 73 | |----|------|-----|-------|------| 74 | | 3 | Charlie | 25 | 85 | 2024-01-15 | 75 | | 1 | Alice | 30 | 92 | 2024-01-10 | 76 | | 2 | Bob | 28 | 78 | 2024-01-20 | 77 | | 4 | Diana | 22 | 95 | 2024-01-05 | 78 | 79 | | Product | Price | Category | Stock | Rating | 80 | |---------|-------|----------|-------|--------| 81 | | Laptop | $999.99 | Electronics | 15 | 4.5 | 82 | | Book | $19.99 | Books | 42 | 4.2 | 83 | | Shirt | $45.50 | Clothing | 8 | 3.8 | 84 | | Phone | $699.00 | Electronics | 23 | 4.7 | 85 | -------------------------------------------------------------------------------- /src/protocols/fetch-to-handler.js: -------------------------------------------------------------------------------- 1 | /* global Response, Headers */ 2 | export const CORS_HEADERS = [ 3 | 'Access-Control-Allow-Origin', 4 | 'Allow-CSP-From', 5 | 'Access-Control-Allow-Headers', 6 | 'Access-Control-Allow-Methods', 7 | 'Access-Control-Request-Headers' 8 | ] 9 | 10 | export default function fetchToHandler (getFetch, session) { 11 | let hasFetch = null 12 | let loadingFetch = null 13 | 14 | async function load () { 15 | if (hasFetch) return hasFetch 16 | if (loadingFetch) return loadingFetch 17 | 18 | loadingFetch = Promise.resolve().then(getFetch).then((fetch) => { 19 | hasFetch = fetch 20 | loadingFetch = null 21 | return fetch 22 | }).catch((e) => { 23 | loadingFetch = null 24 | throw e 25 | }) 26 | 27 | return loadingFetch 28 | } 29 | 30 | const close = async () => { 31 | if (loadingFetch) { 32 | await loadingFetch 33 | await close() 34 | } else if (hasFetch) { 35 | if (hasFetch.close) await hasFetch.close() 36 | else if (hasFetch.destroy) await hasFetch.destroy() 37 | } 38 | } 39 | 40 | return { handler: protocolHandler, close } 41 | 42 | async function protocolHandler (request) { 43 | try { 44 | // Lazy load fetch implementation 45 | const fetch = await load() 46 | 47 | const response = await fetch(request) 48 | try { 49 | for (const header of CORS_HEADERS) { 50 | response.headers.set(header, '*') 51 | } 52 | } catch { 53 | const newHeaders = new Headers([...response.headers]) 54 | 55 | return new Response(response.body, { 56 | headers: newHeaders, 57 | statusText: response.statusText, 58 | status: response.status 59 | }) 60 | } 61 | 62 | return response 63 | } catch (e) { 64 | console.log(e) 65 | return new Response(e.stack, { 66 | status: 500 67 | }) 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/pages/welcome.html: -------------------------------------------------------------------------------- 1 | 2 | Agregore Browser - Welcome 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 51 | 52 | 53 | 54 |

55 | Agregore 56 |

57 | 58 |

59 | Explore 60 | Build 61 | FileViewer 62 |

63 |

64 | Main Website 65 | Matrix Community 66 |

67 | 68 | 69 | 70 | 71 | 72 | 85 | -------------------------------------------------------------------------------- /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, 'src/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 | -------------------------------------------------------------------------------- /src/protocols/ipfs-protocol.js: -------------------------------------------------------------------------------- 1 | import fetchToHandler from './fetch-to-handler.js' 2 | import path from 'node:path' 3 | import * as fs from 'node:fs/promises' 4 | 5 | export default async function createHandler (ipfsOptions, session) { 6 | return fetchToHandler(async () => { 7 | const { default: makeFetch } = await import('js-ipfs-fetch') 8 | const ipfsHttpModule = await import('ipfs-http-client') 9 | 10 | const Ctl = await import('ipfsd-ctl') 11 | 12 | const GoIPFS = await import('kubo') 13 | 14 | const ipfsBin = GoIPFS 15 | .path() 16 | .replace(`.asar${path.sep}`, `.asar.unpacked${path.sep}`) 17 | 18 | const ipfsdOpts = { 19 | ipfsOptions, 20 | type: 'go', 21 | disposable: false, 22 | test: false, 23 | remote: false, 24 | ipfsHttpModule, 25 | ipfsBin 26 | } 27 | 28 | let ipfsd = await Ctl.createController(ipfsdOpts) 29 | 30 | await ipfsd.init({ ipfsOptions }) 31 | const version = await ipfsd.version() 32 | console.log(`IPFS Version: ${version}\nIPFS bin path: ${ipfsBin}`) 33 | 34 | try { 35 | await ipfsd.start() 36 | await ipfsd.api.id() 37 | } catch (e) { 38 | console.log('IPFS Unable to boot daemon', e.message) 39 | const { repo } = ipfsOptions 40 | const lockFile = path.join(repo, 'repo.lock') 41 | const apiFile = path.join(repo, 'api') 42 | try { 43 | await Promise.all([ 44 | fs.rm(lockFile), 45 | fs.rm(apiFile) 46 | ]) 47 | ipfsd = await Ctl.createController(ipfsdOpts) 48 | await ipfsd.start() 49 | await ipfsd.api.id() 50 | } catch (cause) { 51 | const message = `Unable to start daemon due to extra lockfile. Please clear your ipfs folder at ${repo} and try again.` 52 | throw new Error(message, { cause }) 53 | } 54 | } 55 | 56 | console.log('IPFS ID:', await ipfsd.api.id()) 57 | 58 | const fetch = await makeFetch({ 59 | ipfs: ipfsd.api 60 | }) 61 | 62 | fetch.close = async () => { 63 | return ipfsd.stop() 64 | } 65 | 66 | return fetch 67 | }, session) 68 | } 69 | -------------------------------------------------------------------------------- /src/ui/current-window.js: -------------------------------------------------------------------------------- 1 | window.getCurrentWindow = function getCurrentWindow () { 2 | const { ipcRenderer } = require('electron') 3 | const EventEmitter = require('events') 4 | 5 | const EVENTS = [ 6 | 'navigating', 7 | 'history-buttons-change', 8 | 'page-title-updated', 9 | 'enter-html-full-screen', 10 | 'leave-html-full-screen', 11 | 'update-target-url', 12 | 'browser-actions-changed', 13 | 'close', 14 | 'enter-full-screen', 15 | 'leave-full-screen' 16 | ] 17 | 18 | class CurrentWindow extends EventEmitter { 19 | constructor () { 20 | super() 21 | 22 | for (const name of EVENTS) { 23 | ipcRenderer.on(`agregore-window-${name}`, (event, ...args) => this.emit(name, ...args)) 24 | } 25 | } 26 | 27 | async goBack () { 28 | return this.invoke('goBack') 29 | } 30 | 31 | async goForward () { 32 | return this.invoke('goForward') 33 | } 34 | 35 | async reload () { 36 | return this.invoke('reload') 37 | } 38 | 39 | async focus () { 40 | return this.invoke('focus') 41 | } 42 | 43 | async loadURL (url) { 44 | return this.invoke('loadURL', url) 45 | } 46 | 47 | async getURL () { 48 | return this.invoke('getURL') 49 | } 50 | 51 | async findInPage (value, opts) { 52 | return this.invoke('findInPage', value, opts) 53 | } 54 | 55 | async stopFindInPage () { 56 | return this.invoke('stopFindInPage') 57 | } 58 | 59 | async setBounds (rect) { 60 | return this.invoke('setBounds', rect) 61 | } 62 | 63 | async * searchHistory (query, limit = 8) { 64 | // Open iterator, get back an id 65 | // Invoke next until done 66 | await this.invoke('searchHistoryStart', query, limit) 67 | while (true) { 68 | const { done, value } = await this.invoke('searchHistoryNext') 69 | if (done) break 70 | yield value 71 | } 72 | } 73 | 74 | async listExtensionActions () { 75 | return this.invoke('listExtensionActions') 76 | } 77 | 78 | async clickExtensionAction (id) { 79 | return this.invoke('clickExtensionAction', id) 80 | } 81 | 82 | async invoke (name, ...args) { 83 | return ipcRenderer.invoke(`agregore-window-${name}`, ...args) 84 | } 85 | } 86 | 87 | return new CurrentWindow() 88 | } 89 | -------------------------------------------------------------------------------- /src/pages/icon.svg: -------------------------------------------------------------------------------- 1 | 2 | 11 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /docs/Theming.md: -------------------------------------------------------------------------------- 1 | # Theming 2 | 3 | Agregore provides CSS variables for themeing the browser at the URL `agregore://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 `agregore://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 `agregore-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 `.agregorerc` 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 | ## Syntax Highlighting Font 55 | 56 | Agregore now uses a custom font for syntax highlighting in code blocks. The font file is located at `agregore://theme/FontWithASyntaxHighlighter-Regular.woff2`. 57 | 58 | To use this font for `code` elements, you can include the following CSS in your stylesheet: 59 | 60 | ```css 61 | @font-face { 62 | font-family: 'FontWithASyntaxHighlighter'; 63 | src: url('agregore://theme/FontWithASyntaxHighlighter-Regular.woff2') format('woff2'); 64 | } 65 | 66 | code { 67 | font-family: 'FontWithASyntaxHighlighter', monospace; 68 | } 69 | ``` 70 | 71 | This font provides built-in syntax highlighting for code blocks, making it easier to read and understand code snippets. 72 | -------------------------------------------------------------------------------- /src/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 | -------------------------------------------------------------------------------- /.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 | .agregorerc 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 -------------------------------------------------------------------------------- /src/llm-preload.js: -------------------------------------------------------------------------------- 1 | const { contextBridge, ipcRenderer, webFrame } = require('electron') 2 | 3 | const iteratorMaps = new Map() 4 | let iteratorId = 1 5 | 6 | contextBridge.exposeInMainWorld('_agregoreLLM', { 7 | chat, 8 | complete, 9 | chatStream, 10 | completeStream, 11 | iteratorNext, 12 | iteratorReturn, 13 | isSupported: () => ipcRenderer.invoke('llm-supported') 14 | }) 15 | 16 | webFrame.executeJavaScript(`(${setUpGlobal.toString()})()`) 17 | 18 | function setUpGlobal () { 19 | globalThis.llm = { 20 | chat, 21 | complete, 22 | isSupported: () => globalThis._agregoreLLM.isSupported() 23 | } 24 | 25 | function chat (args) { 26 | return { 27 | then (onResolve, onReject) { 28 | globalThis._agregoreLLM.chat(args).then(onResolve, onReject) 29 | }, 30 | async * [Symbol.asyncIterator] () { 31 | const id = await globalThis._agregoreLLM.chatStream(args) 32 | try { 33 | while (true) { 34 | const { done, value } = await globalThis._agregoreLLM.iteratorNext(id) 35 | if (done) break 36 | yield value 37 | } 38 | } finally { 39 | globalThis._agregoreLLM.iteratorReturn(id) 40 | } 41 | } 42 | } 43 | } 44 | 45 | function complete (prompt, args = {}) { 46 | return { 47 | then (onResolve, onReject) { 48 | globalThis._agregoreLLM.complete(prompt, args).then(onResolve, onReject) 49 | }, 50 | async * [Symbol.asyncIterator] () { 51 | const id = await globalThis._agregoreLLM.completeStream(prompt, args) 52 | try { 53 | while (true) { 54 | const { done, value } = await globalThis._agregoreLLM.iteratorNext(id) 55 | if (done) break 56 | yield value 57 | } 58 | } finally { 59 | globalThis._agregoreLLM.iteratorReturn(id) 60 | } 61 | } 62 | } 63 | } 64 | } 65 | 66 | async function chat (args) { 67 | return ipcRenderer.invoke('llm-chat', args) 68 | } 69 | 70 | async function complete (prompt, args = {}) { 71 | return ipcRenderer.invoke('llm-complete', { prompt, ...args }) 72 | } 73 | 74 | async function chatStream (args) { 75 | const { id } = await ipcRenderer.invoke('llm-chat-stream', args) 76 | const localId = iteratorId++ 77 | iteratorMaps.set(localId, id) 78 | return localId 79 | } 80 | 81 | async function completeStream (prompt, args = {}) { 82 | const { id } = await ipcRenderer.invoke('llm-complete-stream', { prompt, ...args }) 83 | const localId = iteratorId++ 84 | iteratorMaps.set(localId, id) 85 | return localId 86 | } 87 | 88 | async function iteratorNext (localId) { 89 | const id = iteratorMaps.get(localId) 90 | if (!id) throw new Error('Unknown iterator ID') 91 | return ipcRenderer.invoke('llm-iterate-next', { id }) 92 | } 93 | 94 | async function iteratorReturn (localId) { 95 | const id = iteratorMaps.get(localId) 96 | if (!id) throw new Error('Unknown iterator ID') 97 | iteratorMaps.delete(localId) 98 | return ipcRenderer.invoke('llm-iterate-return', { id }) 99 | } 100 | -------------------------------------------------------------------------------- /src/menu.js: -------------------------------------------------------------------------------- 1 | import { Menu, app } from 'electron' 2 | 3 | const isMac = process.platform === 'darwin' 4 | 5 | export function registerMenu (actions) { 6 | const { 7 | OpenDevTools, 8 | ViewHistory, 9 | NewWindow, 10 | Forward, 11 | Back, 12 | Up, 13 | BackAlt, 14 | ForwardAlt, 15 | UpAlt, 16 | FocusURLBar, 17 | FindInPage, 18 | Reload, 19 | HardReload, 20 | LearnMore, 21 | SetAsDefault, 22 | SetAsDefaultMagnet, 23 | OpenExtensionFolder, 24 | OpenDataFolder, 25 | EditConfigFile, 26 | CreateBookmark 27 | } = actions 28 | 29 | const template = [ 30 | // { role: 'appMenu' } 31 | ...(isMac 32 | ? [{ 33 | label: app.name, 34 | submenu: [ 35 | { role: 'about' }, 36 | { type: 'separator' }, 37 | { role: 'services' }, 38 | { type: 'separator' }, 39 | { role: 'hide' }, 40 | { role: 'hideothers' }, 41 | { role: 'unhide' }, 42 | { type: 'separator' }, 43 | { role: 'quit' } 44 | ] 45 | }] 46 | : []), 47 | // { role: 'fileMenu' } 48 | { 49 | label: 'File', 50 | submenu: [ 51 | isMac ? { role: 'close' } : { role: 'quit' }, 52 | OpenDevTools, 53 | ViewHistory, 54 | NewWindow 55 | ] 56 | }, 57 | // { role: 'editMenu' } 58 | { 59 | label: 'Edit', 60 | submenu: [ 61 | { role: 'undo' }, 62 | { role: 'redo' }, 63 | { type: 'separator' }, 64 | { role: 'cut' }, 65 | { role: 'copy' }, 66 | { role: 'paste' }, 67 | ...(isMac 68 | ? [ 69 | { role: 'pasteAndMatchStyle' }, 70 | { role: 'delete' }, 71 | { role: 'selectAll' }, 72 | { type: 'separator' }, 73 | { 74 | label: 'Speech', 75 | submenu: [ 76 | { role: 'startspeaking' }, 77 | { role: 'stopspeaking' } 78 | ] 79 | } 80 | ] 81 | : [ 82 | { role: 'delete' }, 83 | { type: 'separator' }, 84 | { role: 'selectAll' } 85 | ]) 86 | ] 87 | }, 88 | // { role: 'viewMenu' } 89 | { 90 | label: 'View', 91 | submenu: [ 92 | Forward, 93 | Back, 94 | Up, 95 | ForwardAlt, 96 | BackAlt, 97 | UpAlt, 98 | FocusURLBar, 99 | FindInPage, 100 | { type: 'separator' }, 101 | { role: 'resetzoom' }, 102 | { role: 'zoomin' }, 103 | { role: 'zoomout' }, 104 | { type: 'separator' }, 105 | { role: 'togglefullscreen' } 106 | ] 107 | }, 108 | // { role: 'windowMenu' } 109 | { 110 | label: 'Window', 111 | submenu: [ 112 | Reload, 113 | HardReload, 114 | ...(isMac 115 | ? [] 116 | : [ 117 | CreateBookmark 118 | ]), 119 | { role: 'minimize' }, 120 | { role: 'zoom' }, 121 | ...(isMac 122 | ? [ 123 | { type: 'separator' }, 124 | { role: 'front' }, 125 | { type: 'separator' }, 126 | { role: 'window' } 127 | ] 128 | : [ 129 | { role: 'close' } 130 | ]) 131 | ] 132 | }, 133 | { 134 | role: 'help', 135 | submenu: [ 136 | LearnMore, 137 | OpenExtensionFolder, 138 | OpenDataFolder, 139 | EditConfigFile, 140 | SetAsDefault, 141 | SetAsDefaultMagnet 142 | ] 143 | } 144 | ] 145 | 146 | const menu = Menu.buildFromTemplate(template) 147 | Menu.setApplicationMenu(menu) 148 | } 149 | -------------------------------------------------------------------------------- /src/ui/style.css: -------------------------------------------------------------------------------- 1 | @import url("agregore://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 | font-family: var(--ag-theme-font-family); 17 | } 18 | 19 | #view { 20 | flex:1 21 | } 22 | 23 | #toptop { 24 | display: flex; 25 | flex-direction: row; 26 | } 27 | 28 | #search { 29 | flex: 1; 30 | } 31 | 32 | .hidden { 33 | display: none !important; 34 | } 35 | 36 | omni-box { 37 | display: block 38 | } 39 | 40 | .omni-box-header { 41 | display: flex; 42 | flex-direction: row; 43 | border-bottom: var(--border-width) solid var(--ag-theme-primary); 44 | background: var(--ag-theme-background); 45 | color: var(--ag-theme-text); 46 | height: calc(100% - var(--border-width)); 47 | } 48 | 49 | .omni-box-form, .find-menu-form { 50 | display: flex; 51 | flex-direction: row; 52 | flex:1; 53 | border: none; 54 | } 55 | 56 | .omni-box-input, .find-menu-input, .omni-box-target-input { 57 | flex: 1; 58 | border:none; 59 | background: none; 60 | padding: 0.5em; 61 | color: inherit; 62 | font-size: inherit; 63 | font-family: inherit; 64 | } 65 | 66 | .nav-options { 67 | display: flex; 68 | flex-direction: column; 69 | margin: 0px; 70 | padding: 0px; 71 | border: var(--border-width) solid var(--ag-theme-primary); 72 | background: var(--ag-theme-background); 73 | color: var(--ag-theme-text); 74 | } 75 | 76 | .nav-options [data-selected] { 77 | border: 1px solid var(--ag-theme-secondary); 78 | } 79 | 80 | .nav-options:empty { 81 | display: none; 82 | } 83 | 84 | .omni-box-button, .find-menu-button, .browser-actions-button { 85 | color: inherit; 86 | font-size: inherit; 87 | padding: 0.5em; 88 | border: none; 89 | background: none; 90 | font-family: inherit; 91 | } 92 | 93 | .omni-box-nav-item { 94 | border: 1px solid var(--ag-theme-primary); 95 | display: flex; 96 | flex-direction: row; 97 | overflow: hidden; 98 | white-space: nowrap; 99 | text-overflow: ellipsis; 100 | } 101 | 102 | find-menu { 103 | border: var(--border-width) solid var(--ag-theme-primary); 104 | border-top: none; 105 | display: flex; 106 | flex-direction: row; 107 | background: var(--ag-theme-background); 108 | color: var(--ag-theme-text); 109 | } 110 | 111 | browser-actions { 112 | height: calc(var(--top-height) - calc(var(--border-width) * 3)); 113 | border-bottom: var(--border-width) solid var(--ag-theme-primary); 114 | border-left: var(--border-width) solid var(--ag-theme-primary); 115 | display: flex; 116 | flex-direction: row; 117 | background: var(--ag-theme-background); 118 | color: var(--ag-theme-text); 119 | justify-content: center; 120 | align-items: center; 121 | padding: var(--border-width); 122 | } 123 | .browser-actions-button { 124 | padding: 0 calc(var(--border-width) * 2); 125 | height: calc(100% - calc(var(--border-width) * 2)); 126 | width: auto; 127 | position: relative; 128 | } .browser-actions-button>img { 129 | height: 100%; 130 | width: auto; 131 | } 132 | .browser-actions-badge { 133 | border-radius: 0.25em; 134 | position: absolute; 135 | bottom: 0px; 136 | min-width: 1em; 137 | min-height: 1em; 138 | left: 50%; 139 | transform: translateX(-50%); 140 | background: var(--ag-theme-background); 141 | color: var(--ag-theme-text); 142 | } 143 | 144 | browser-actions:empty { 145 | display: none; 146 | } 147 | 148 | *:focus { 149 | outline: var(--border-width) solid var(--ag-theme-secondary); 150 | } 151 | 152 | *::-webkit-scrollbar { 153 | width: 1em; 154 | background: var(--ag-theme-background); 155 | } 156 | 157 | *::-webkit-scrollbar-corner { 158 | background: rgba(0,0,0,0); 159 | } 160 | 161 | *::-webkit-scrollbar-thumb { 162 | background-color: var(--ag-theme-primary); 163 | border: 2px solid transparent; 164 | background-clip: content-box; 165 | } 166 | *::-webkit-scrollbar-track { 167 | background-color: rgba(0,0,0,0); 168 | } 169 | -------------------------------------------------------------------------------- /src/pages/settings.html: -------------------------------------------------------------------------------- 1 | 2 | Browser Settings 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 |

Settings

15 |
16 |
17 | 18 | 19 | 20 |
21 |
22 | Theme 23 |

24 | Visual Theme Editor 25 |

26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 |
34 |
35 | llm 36 | 37 | 38 | 39 | 40 |
41 |
42 | Keyboard Shortcuts 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
56 |
57 | 58 |
59 |
60 | 61 | 100 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/ui/script.js: -------------------------------------------------------------------------------- 1 | const DEFAULT_PAGE = 'agregore://welcome' 2 | const DEFAULT_SEARCH_PROVIDER = 'https://duckduckgo.com/?ia=web&q=%s' 3 | 4 | const webview = $('#view') 5 | // 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. 6 | const nav = $('#top') 7 | const search = $('#search') 8 | const find = $('#find') 9 | const actions = $('#actions') 10 | 11 | const currentWindow = window.getCurrentWindow() 12 | 13 | const pageTitle = $('title') 14 | 15 | const searchParams = new URL(window.location.href).searchParams 16 | 17 | const toNavigate = searchParams.has('url') ? searchParams.get('url') : DEFAULT_PAGE 18 | 19 | const rawFrame = searchParams.get('rawFrame') === 'true' 20 | const noNav = searchParams.get('noNav') === 'true' 21 | 22 | const searchProvider = searchParams.has('searchProvider') ? searchParams.get('searchProvider') : DEFAULT_SEARCH_PROVIDER 23 | window.searchProvider = searchProvider // Used by omni-box.js 24 | 25 | if (rawFrame) nav.classList.toggle('hidden', true) 26 | 27 | let searchAborter = null 28 | 29 | window.addEventListener('load', () => { 30 | if (noNav) return 31 | console.log('toNavigate', toNavigate) 32 | currentWindow.loadURL(toNavigate) 33 | webview.emitResize() 34 | }) 35 | 36 | search.addEventListener('back', () => { 37 | currentWindow.goBack() 38 | }) 39 | 40 | search.addEventListener('forward', () => { 41 | currentWindow.goForward() 42 | }) 43 | 44 | search.addEventListener('up', () => { 45 | const next = search.src.endsWith('/') ? '../' : './' 46 | currentWindow.loadURL(new URL(next, search.src).href) 47 | }) 48 | 49 | search.addEventListener('navigate', ({ detail }) => { 50 | const { url } = detail 51 | 52 | navigateTo(url) 53 | }) 54 | 55 | search.addEventListener('unfocus', async () => { 56 | await currentWindow.focus() 57 | search.src = await currentWindow.getURL() 58 | }) 59 | 60 | search.addEventListener('search', async ({ detail }) => { 61 | if (searchAborter) searchAborter.abort() 62 | searchAborter = new AbortController() 63 | const { signal } = searchAborter 64 | 65 | const { query, searchID } = detail 66 | 67 | search.setSearchResults([], query, searchID) 68 | for await (const result of currentWindow.searchHistory(query)) { 69 | if (signal.aborted) break 70 | search.addSearchResult(result) 71 | } 72 | }) 73 | 74 | webview.addEventListener('focus', () => { 75 | currentWindow.focus() 76 | }) 77 | 78 | webview.addEventListener('resize', ({ detail: rect }) => { 79 | currentWindow.setBounds(rect) 80 | }) 81 | 82 | currentWindow.on('navigating', (url) => { 83 | search.src = url 84 | find.hide() 85 | if (searchAborter) searchAborter.abort() 86 | }) 87 | 88 | currentWindow.on('history-buttons-change', updateButtons) 89 | 90 | currentWindow.on('page-title-updated', (title) => { 91 | pageTitle.innerText = title + ' - Agregore Browser' 92 | }) 93 | currentWindow.on('enter-html-full-screen', () => { 94 | if (!rawFrame) nav.classList.toggle('hidden', true) 95 | webview.emitResize() 96 | }) 97 | currentWindow.on('leave-html-full-screen', () => { 98 | if (!rawFrame) nav.classList.toggle('hidden', false) 99 | webview.emitResize() 100 | }) 101 | currentWindow.on('update-target-url', async (url) => { 102 | search.showTarget(url) 103 | }) 104 | currentWindow.on('browser-actions-changed', () => { 105 | actions.renderLatest() 106 | }) 107 | currentWindow.on('enter-full-screen', () => { 108 | if (!rawFrame) nav.classList.toggle('hidden', true) 109 | webview.emitResize() 110 | }) 111 | currentWindow.on('leave-full-screen', () => { 112 | if (!rawFrame) nav.classList.toggle('hidden', false) 113 | webview.emitResize() 114 | }) 115 | 116 | find.addEventListener('next', ({ detail }) => { 117 | const { value, findNext } = detail 118 | 119 | currentWindow.findInPage(value, { findNext }) 120 | }) 121 | 122 | find.addEventListener('previous', ({ detail }) => { 123 | const { value, findNext } = detail 124 | 125 | currentWindow.findInPage(value, { forward: false, findNext }) 126 | }) 127 | 128 | find.addEventListener('hide', () => { 129 | currentWindow.stopFindInPage('clearSelection') 130 | }) 131 | 132 | function updateButtons ({ canGoBack, canGoForward }) { 133 | search.setAttribute('back', canGoBack ? 'visible' : 'hidden') 134 | search.setAttribute('forward', canGoForward ? 'visible' : 'hidden') 135 | } 136 | 137 | function $ (query) { 138 | return document.querySelector(query) 139 | } 140 | 141 | async function navigateTo (url) { 142 | const currentURL = await currentWindow.getURL() 143 | if (currentURL === url) { 144 | console.log('Reloading') 145 | currentWindow.reload() 146 | } else { 147 | currentWindow.loadURL(url) 148 | currentWindow.focus() 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Agregore Browser 2 | A minimal web browser for the distributed web 3 | 4 |

5 | 6 |

7 | 8 | [Website](https://agregore.mauve.moe/) 9 | 10 | [Download the installer](https://github.com/AgregoreWeb/agregore-browser/releases) 11 | 12 | [Matrix Chat](https://matrix.to/#/#agregore:mauve.moe) 13 | 14 | [Discord Chat](https://discord.gg/QMthd4Y) 15 | 16 | Wanna help out? Try your hand at one of the [open issues](https://github.com/AgregoreWeb/agregore-browser/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22good%20first%20issue%22)! 17 | 18 | ## Videos 19 | 20 | [Overview from SpeakeasyJS](https://www.youtube.com/watch?v=ciRWmEhL8e8) 21 | 22 | [Watch the intro video from Dat Conference](https://www.youtube.com/watch?v=TnYKvOQB0ts&list=PL7sG5SCUNyeYx8wnfMOUpsh7rM_g0w_cu&index=14) 23 | 24 | [Intro to IPFS interface from IPFS meetup](https://youtu.be/kI9Issf3MNc?t=1606) 25 | 26 | [5 minute overview from Dweb meetup](https://archive.org/embed/dweb-meetup-dec-2020-dweb-lightning-talks?start=4212) 27 | 28 | [Decentralized Web - Bloom Fireside](https://www.youtube.com/watch?v=gHrul4jEHvs) 29 | 30 | ## Goals 31 | 32 | - Enable people to make and use local first apps using the web 33 | - Be minimal (fewer built-in features, leave more to the OS) 34 | - Be open to anything p2p / decentralized / local-first 35 | - Rely on web extensions for extra functionality 36 | - Work with mesh networks / Bluetooth Low Energy networks 37 | 38 | ![Agregore demo](agregore-demo-2.gif) 39 | 40 | ## Features 41 | 42 | ### Keyboard Shortcuts 43 | (Ctrl means Command or Control) 44 | |Shortcut|Does|Is configurable| 45 | |:-:|:-:|:-:| 46 | |Alt|Show Menu Bar|-| 47 | |Ctrl+N|New Window|+| 48 | |F11|Fullscreen|-| 49 | |Ctrl+M|Minimize|-| 50 | |Ctrl+W|Close|-| 51 | |Ctrl+Shift+I|Open Devtools|+| 52 | |Ctrl+]|Navigate Forward|+| 53 | |Ctrl+\[|Navigate Backward|+| 54 | |Ctrl+L|Focus URL Bar|+| 55 | |Ctrl+F|Find in page|-| 56 | |Ctrl+R|Reload|+| 57 | |Ctrl+Shift+R|Hard Reload|+| 58 | ||Learn More|+| 59 | ||Open Extensions Folder|+| 60 | |Ctrl+.|Edit Config File|+| 61 | 62 | ### Other features 63 | 64 | - Web Extension support 65 | - Built-in Markdown/Gemini/JSON rendering extension 66 | - Built-in QR code scanner and generator extension 67 | - Generate a QR code for the current page 68 | - Scan a QR code from the browser action window. 69 | - Right click a link or image to generate a QR code for it 70 | - Built-in ad blocker (ublock origin) 71 | - Use local and cloud LLMs via `window.llm.chat({messages})` and `window.llm.complete("prompt")` 72 | - Built-in support for creating web archives via [ArchiveWeb.page](https://github.com/webrecorder/archiveweb.page/) 73 | - Open links in new windows (right click on element) 74 | - Autocomplete URLs from history (type in the URL bar, up/down to navigate, right to autocomplete) 75 | - Manage history (File > View History) 76 | - Persist open windows when quitting 77 | - Save files from pages (any protocol, right click it) 78 | - Set as default browser (click Set As Default in the menu bar (`ALT`)) 79 | - Set as default Torrent handler (click Set as Default Torrent in the menu bar (`ALT`)) 80 | - Auto-convert SSB sigils, BitTorrent magnet links, `/ipfs/Qm` paths, and `/ipns/` paths to proper URLs. 81 | - Configure whether the menu bar should be visible by default (edit .agregorerc `autoHideMenuBar` property) 82 | 83 | ## Docs 84 | 85 | Check out the [documentation](./docs). 86 | 87 | ## Contributing 88 | 89 | Feel free to open a Github issue if you wish to tackle one of the items on the roadmap, or message @RangerMauve directly on whatever platform you can find them on. 90 | 91 | This project uses the [StandardJS](https://standardjs.com/) code style. Please format your code with `standard --fix` or run `npm run lint`. 92 | 93 | To build from source do the following: 94 | 95 | - Set up node.js (at least Node 18) and git 96 | - Set up [Node-gyp](https://github.com/nodejs/node-gyp) and its dependencies for your OS 97 | - fork the repo 98 | - Pull your fork to your computer 99 | - Load submodules with `git submodule update --init --recursive` 100 | - Run `npm install` to install dependencies 101 | - Run `npm start` to start the browser and test your changes 102 | - After coding, when ready to submit, run `npm run lint` to check code style 103 | - Push to your clone 104 | - Submit a pull request 105 | 106 | Other notes: 107 | - To debug extensions, run `npm run debug` to have devtools opened for their background pages 108 | - If you're interested in a CLI for these protocols, check out [curld](https://github.com/Lohn/curld) `cURL for Distributed Web`. That project supports the same protocols as Agregore, but in a terminal way. 109 | - To download the latest versions of ArchiveWeb.page or Ublock Origin, run `npm run download-extensions` 110 | -------------------------------------------------------------------------------- /src/pages/settings/theme.html: -------------------------------------------------------------------------------- 1 | 2 | Theme Editor 3 | 4 | 5 | Theme Editor 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 35 | 36 |

Theme Editor

37 |
38 | 39 | 40 | 41 | 42 | 43 |
44 | 45 | 46 | 47 | 48 |
49 | 50 | 51 | 52 |

53 | This page lets you customize your browser's color scheme. 54 | Fiddle with the values and when you're happy with the look hit Save to apply the style to all pages. 55 |

56 |

57 | You can also copy this style as JSON, 58 | and send it to a friend. 59 | They can then paste the result anywhere on the page to have the style applied. 60 | If you want to share your style with others, consider sharing it on the website. 61 |

62 |

63 | 64 |

65 |
66 | 67 |
68 |
69 | 70 | 153 | -------------------------------------------------------------------------------- /src/protocols/browser-protocol.js: -------------------------------------------------------------------------------- 1 | /* global Response, ReadableStream */ 2 | import path from 'node:path' 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 | 10 | const CHECK_PATHS = [ 11 | (path) => path, 12 | (path) => path + 'index.html', 13 | (path) => path + 'index.md', 14 | (path) => path + '/index.html', 15 | (path) => path + '/index.md', 16 | (path) => path + '.html', 17 | (path) => path + '.md' 18 | ] 19 | 20 | const pagesURL = new URL('../pages', import.meta.url) 21 | const pagesPath = fileURLToPath(pagesURL) 22 | 23 | const fs = new ScopedFS(pagesPath) 24 | 25 | export default async function createHandler () { 26 | return { handler: protocolHandler, close } 27 | 28 | function close () {} 29 | 30 | async function protocolHandler (req) { 31 | const { url } = req 32 | 33 | const parsed = new URL(url) 34 | const { pathname, hostname } = parsed 35 | const toResolve = path.join(hostname, pathname) 36 | 37 | if (hostname === 'about') { 38 | const status = 200 39 | 40 | const packagesToRender = [ 41 | 'hypercore-fetch', 42 | 'hyper-sdk', 43 | 'js-ipfs-fetch', 44 | 'ipfs-core', 45 | 'bt-fetch', 46 | 'gun-fetch', 47 | 'gemini-fetch' 48 | ] 49 | 50 | const dependencies = {} 51 | for (const name of packagesToRender) { 52 | dependencies[name] = packageDependencies[name] 53 | } 54 | 55 | const aboutInfo = { 56 | version, 57 | dependencies 58 | } 59 | 60 | const body = JSON.stringify(aboutInfo, null, '\t') 61 | 62 | const headers = { 63 | 'Access-Control-Allow-Origin': '*', 64 | 'Allow-CSP-From': 'agregore://welcome', 65 | 'Content-Type': 'application/json' 66 | } 67 | 68 | return new Response(body, { 69 | status, 70 | headers 71 | }) 72 | } else if ((hostname === 'theme') && (pathname === '/vars.css')) { 73 | const status = 200 74 | 75 | const themes = Object 76 | .keys(Config.theme) 77 | .map((name) => ` --ag-theme-${name}: ${Config.theme[name]};`) 78 | .join('\n') 79 | 80 | const body = ` 81 | :root { 82 | --ag-color-purple: #6e2de5; 83 | --ag-color-black: #111111; 84 | --ag-color-white: #F2F2F2; 85 | --ag-color-green: #2de56e; 86 | } 87 | 88 | :root { 89 | ${themes} 90 | 91 | --browser-theme-font-family: var(--ag-theme-font-family); 92 | --browser-theme-background: var(--ag-theme-background); 93 | --browser-theme-page-background: var(--ag-theme-page); 94 | --browser-theme-text-color: var(--ag-theme-text); 95 | --browser-theme-primary-highlight: var(--ag-theme-primary); 96 | --browser-theme-secondary-highlight: var(--ag-theme-secondary); 97 | --browser-theme-border-radius: var(--ag-theme-border-radius); 98 | --browser-theme-border-color: var(--ag-theme-border-color); 99 | } 100 | ` 101 | 102 | const headers = { 103 | 'Access-Control-Allow-Origin': '*', 104 | 'Allow-CSP-From': '*', 105 | 'Cache-Control': 'no-cache', 106 | 'Content-Type': 'text/css' 107 | } 108 | 109 | return new Response(body, { 110 | status, 111 | headers 112 | }) 113 | } else if ((hostname === 'theme') && (pathname === '/base.css')) { 114 | const status = 200 115 | const headers = { 116 | 'Access-Control-Allow-Origin': '*', 117 | 'Allow-CSP-From': '*', 118 | 'Cache-Control': 'no-cache', 119 | 'Content-Type': 'text/css' 120 | } 121 | 122 | const data = fs.createReadStream('theme/style.css') 123 | const body = new NodeReadableToWebReadable(data) 124 | 125 | return new Response(body, { 126 | status, 127 | headers 128 | }) 129 | } 130 | 131 | try { 132 | const resolvedPath = await resolveFile(toResolve) 133 | const status = 200 134 | 135 | const contentType = mime.getType(resolvedPath) || 'text/plain' 136 | 137 | const data = fs.createReadStream(resolvedPath) 138 | const body = new NodeReadableToWebReadable(data) 139 | 140 | const headers = { 141 | 'Access-Control-Allow-Origin': '*', 142 | 'Cache-Control': 'no-cache', 143 | 'Content-Type': contentType 144 | } 145 | 146 | return new Response(body, { 147 | status, 148 | headers 149 | }) 150 | } catch (e) { 151 | const status = 404 152 | 153 | const data = fs.createReadStream('404.html') 154 | const body = new NodeReadableToWebReadable(data) 155 | 156 | const headers = { 157 | 'Access-Control-Allow-Origin': '*', 158 | 'Allow-CSP-From': '*', 159 | 'Cache-Control': 'no-cache', 160 | 'Content-Type': 'text/html' 161 | } 162 | 163 | return new Response(body, { 164 | status, 165 | headers 166 | }) 167 | } 168 | } 169 | } 170 | 171 | async function resolveFile (path) { 172 | for (const toTry of CHECK_PATHS) { 173 | const tryPath = toTry(path) 174 | if (await exists(tryPath)) return tryPath 175 | } 176 | throw new Error('Not Found') 177 | } 178 | 179 | function exists (path) { 180 | return new Promise((resolve, reject) => { 181 | fs.stat(path, (err, stat) => { 182 | if (err) { 183 | if (err.code === 'ENOENT') resolve(false) 184 | else reject(err) 185 | } else resolve(stat.isFile()) 186 | }) 187 | }) 188 | } 189 | 190 | class NodeReadableToWebReadable extends ReadableStream { 191 | constructor (nodeReadable) { 192 | super({ 193 | start (controller) { 194 | nodeReadable.on('data', (chunk) => { 195 | controller.enqueue(chunk) 196 | }) 197 | nodeReadable.on('end', () => { 198 | controller.close() 199 | }) 200 | nodeReadable.on('error', (err) => controller.error(err)) 201 | } 202 | }) 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /src/protocols/index.js: -------------------------------------------------------------------------------- 1 | import { app, protocol as globalProtocol } from 'electron' 2 | import Config from '../config.js' 3 | 4 | import createHyperHandler from './hyper-protocol.js' 5 | import createSsbHandler from './ssb-protocol.js' 6 | import createIPFSHandler from './ipfs-protocol.js' 7 | import createBrowserHandler from './browser-protocol.js' 8 | import createGeminiHandler from './gemini-protocol.js' 9 | import createBTHandler from './bt-protocol.js' 10 | import createMagnetHandler from './magnet-protocol.js' 11 | import createRawHTTPSHandler from './raw-http-protocol.js' 12 | import createWeb3Handler from './web3-protocol.js' 13 | 14 | const P2P_PRIVILEGES = { 15 | standard: true, 16 | secure: true, 17 | allowServiceWorkers: true, 18 | supportFetchAPI: true, 19 | bypassCSP: false, 20 | corsEnabled: true, 21 | stream: true 22 | } 23 | 24 | const BROWSER_PRIVILEGES = { 25 | standard: true, 26 | secure: true, 27 | allowServiceWorkers: true, 28 | supportFetchAPI: true, 29 | bypassCSP: false, 30 | corsEnabled: true, 31 | stream: true 32 | } 33 | 34 | const LOW_PRIVILEGES = { 35 | standard: false, 36 | secure: false, 37 | allowServiceWorkers: false, 38 | supportFetchAPI: false, 39 | bypassCSP: false, 40 | corsEnabled: true 41 | } 42 | 43 | const { 44 | ipfsOptions, 45 | ssbOptions, 46 | hyperOptions, 47 | web3Options, 48 | btOptions 49 | } = Config 50 | 51 | const onCloseHandlers = [] 52 | 53 | export async function close () { 54 | await Promise.all(onCloseHandlers.map((handler) => handler())) 55 | } 56 | 57 | export function registerPrivileges () { 58 | globalProtocol.registerSchemesAsPrivileged([ 59 | { scheme: 'https+raw', privileges: P2P_PRIVILEGES }, 60 | { scheme: 'hyper', privileges: P2P_PRIVILEGES }, 61 | { scheme: 'gemini', privileges: P2P_PRIVILEGES }, 62 | { scheme: 'ipfs', privileges: P2P_PRIVILEGES }, 63 | { scheme: 'ipns', privileges: P2P_PRIVILEGES }, 64 | { scheme: 'ipld', privileges: P2P_PRIVILEGES }, 65 | { scheme: 'pubsub', privileges: P2P_PRIVILEGES }, 66 | { scheme: 'bittorrent', privileges: P2P_PRIVILEGES }, 67 | { scheme: 'bt', privileges: P2P_PRIVILEGES }, 68 | { scheme: 'ssb', privileges: P2P_PRIVILEGES }, 69 | { scheme: 'web3', privileges: P2P_PRIVILEGES }, 70 | { scheme: 'agregore', privileges: BROWSER_PRIVILEGES }, 71 | { scheme: 'browser', privileges: BROWSER_PRIVILEGES }, 72 | { scheme: 'magnet', privileges: LOW_PRIVILEGES } 73 | ]) 74 | } 75 | 76 | export function setAsDefaultProtocolClient () { 77 | console.log('Setting as default handlers') 78 | 79 | app.setAsDefaultProtocolClient('agregore') 80 | app.setAsDefaultProtocolClient('hyper') 81 | app.setAsDefaultProtocolClient('ssb') 82 | app.setAsDefaultProtocolClient('gemini') 83 | app.setAsDefaultProtocolClient('ipfs') 84 | app.setAsDefaultProtocolClient('ipns') 85 | app.setAsDefaultProtocolClient('ipld') 86 | app.setAsDefaultProtocolClient('pubsub') 87 | app.setAsDefaultProtocolClient('bittorrent') 88 | app.setAsDefaultProtocolClient('bt') 89 | app.setAsDefaultProtocolClient('web3') 90 | } 91 | 92 | export async function setupProtocols (session) { 93 | const { protocol: sessionProtocol } = session 94 | 95 | const { handler: browserProtocolHandler } = await createBrowserHandler() 96 | sessionProtocol.handle('agregore', browserProtocolHandler) 97 | globalProtocol.handle('agregore', browserProtocolHandler) 98 | sessionProtocol.handle('browser', browserProtocolHandler) 99 | globalProtocol.handle('browser', browserProtocolHandler) 100 | 101 | console.log('Registering hyper handlers') 102 | 103 | const { 104 | handler: hyperProtocolHandler, 105 | close: closeHyper 106 | } = await createHyperHandler(hyperOptions, session) 107 | onCloseHandlers.push(closeHyper) 108 | sessionProtocol.handle('hyper', hyperProtocolHandler) 109 | globalProtocol.handle('hyper', hyperProtocolHandler) 110 | 111 | console.log('Registering ssb handlers') 112 | 113 | const { handler: ssbProtocolHandler } = await createSsbHandler(ssbOptions, session) 114 | sessionProtocol.handle('ssb', ssbProtocolHandler) 115 | globalProtocol.handle('ssb', ssbProtocolHandler) 116 | 117 | console.log('Registering gemini handlers') 118 | 119 | const { handler: geminiProtocolHandler } = await createGeminiHandler() 120 | sessionProtocol.handle('gemini', geminiProtocolHandler) 121 | globalProtocol.handle('gemini', geminiProtocolHandler) 122 | 123 | console.log('Registering IPFS handlers') 124 | 125 | const { 126 | handler: ipfsProtocolHandler, 127 | close: closeIPFS 128 | } = await createIPFSHandler(ipfsOptions, session) 129 | onCloseHandlers.push(closeIPFS) 130 | sessionProtocol.handle('ipfs', ipfsProtocolHandler) 131 | globalProtocol.handle('ipfs', ipfsProtocolHandler) 132 | sessionProtocol.handle('ipns', ipfsProtocolHandler) 133 | globalProtocol.handle('ipns', ipfsProtocolHandler) 134 | sessionProtocol.handle('ipld', ipfsProtocolHandler) 135 | globalProtocol.handle('ipld', ipfsProtocolHandler) 136 | sessionProtocol.handle('pubsub', ipfsProtocolHandler) 137 | globalProtocol.handle('pubsub', ipfsProtocolHandler) 138 | 139 | console.log('Registering bittorrent handlers') 140 | 141 | const { 142 | handler: btHandler, 143 | close: closeBT 144 | } = await createBTHandler(btOptions, session) 145 | onCloseHandlers.push(closeBT) 146 | sessionProtocol.handle('bittorrent', btHandler) 147 | globalProtocol.handle('bittorrent', btHandler) 148 | sessionProtocol.handle('bt', btHandler) 149 | globalProtocol.handle('bt', btHandler) 150 | 151 | const magnetHandler = await createMagnetHandler() 152 | sessionProtocol.handle('magnet', magnetHandler) 153 | globalProtocol.handle('magnet', magnetHandler) 154 | 155 | console.log('Registering raw HTTPS handler') 156 | 157 | const { handler: rawHTTPSHandler } = await createRawHTTPSHandler() 158 | sessionProtocol.handle('https+raw', rawHTTPSHandler) 159 | 160 | console.log('Regisyering web3 handlers') 161 | const { handler: web3Handler } = await createWeb3Handler(web3Options) 162 | sessionProtocol.handle('web3', web3Handler) 163 | globalProtocol.handle('web3', web3Handler) 164 | } 165 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "agregore-browser", 3 | "version": "2.20.0", 4 | "description": "A minimal web browser for the distributed web", 5 | "main": "src/main.cjs", 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", 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-agregore-*/", 27 | "version.js" 28 | ] 29 | }, 30 | "build": { 31 | "npmRebuild": false, 32 | "asar": true, 33 | "asarUnpack": [ 34 | "src/**", 35 | "node_modules/**", 36 | "build/icon.png", 37 | "build/icon-small.png", 38 | "package.json" 39 | ], 40 | "productName": "Agregore Browser", 41 | "appId": "agregore.mauve.moe", 42 | "files": [ 43 | "build/*", 44 | "src/**/*", 45 | "src/*", 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": "hypercore-protocol", 71 | "schemes": [ 72 | "hyper", 73 | "dat" 74 | ], 75 | "role": "Viewer" 76 | }, 77 | { 78 | "name": "webpages", 79 | "schemes": [ 80 | "http", 81 | "https" 82 | ], 83 | "role": "Viewer" 84 | }, 85 | { 86 | "name": "gemini", 87 | "schemes": [ 88 | "gemini" 89 | ], 90 | "role": "Viewer" 91 | }, 92 | { 93 | "name": "ipfs", 94 | "schemes": [ 95 | "ipfs", 96 | "ipns", 97 | "ipld" 98 | ], 99 | "role": "Viewer" 100 | }, 101 | { 102 | "name": "bittorrent", 103 | "schemes": [ 104 | "magnet", 105 | "bittorrent", 106 | "bt" 107 | ], 108 | "role": "Viewer" 109 | }, 110 | { 111 | "name": "SecureScuttlebutt", 112 | "schemes": [ 113 | "ssb" 114 | ], 115 | "role": "Viewer" 116 | } 117 | ], 118 | "dmg": { 119 | "contents": [ 120 | { 121 | "x": 130, 122 | "y": 220 123 | }, 124 | { 125 | "x": 410, 126 | "y": 220, 127 | "type": "link", 128 | "path": "/Applications" 129 | } 130 | ] 131 | }, 132 | "mac": { 133 | "artifactName": "${name}-${version}-${os}-${arch}.${ext}", 134 | "darkModeSupport": true, 135 | "gatekeeperAssess": false, 136 | "extendInfo": { 137 | "NSMicrophoneUsageDescription": "The current page is asking to use your microphone", 138 | "NSCameraUsageDescription": "The current page is asking to use your camera", 139 | "com.apple.security.device.audio-input": true, 140 | "com.apple.security.device.camera": true 141 | }, 142 | "target": [ 143 | { 144 | "target": "dmg", 145 | "arch": [ 146 | "x64" 147 | ] 148 | } 149 | ] 150 | }, 151 | "win": { 152 | "target": [ 153 | "nsis", 154 | "portable" 155 | ] 156 | }, 157 | "linux": { 158 | "artifactName": "${name}-${version}-${os}-${arch}.${ext}", 159 | "executableArgs": [ 160 | "--enable-accelerated-video" 161 | ], 162 | "target": [ 163 | "deb", 164 | "AppImage", 165 | "apk", 166 | "pacman" 167 | ], 168 | "category": "Network;FileTransfer:P2P" 169 | } 170 | }, 171 | "repository": { 172 | "type": "git", 173 | "url": "git+https://github.com/AgregoreWeb/agregore-browser.git" 174 | }, 175 | "keywords": [ 176 | "dat", 177 | "hypercore", 178 | "hyper", 179 | "hyperdrive", 180 | "ipfs", 181 | "browser", 182 | "dweb" 183 | ], 184 | "author": "rangermauve (https://mauve.moe/)", 185 | "license": "AGPL-3.0", 186 | "bugs": { 187 | "url": "https://github.com/AgregoreWeb/agregore-browser/issues" 188 | }, 189 | "homepage": "https://github.com/AgregoreWeb/agregore-browser#readme", 190 | "devDependencies": { 191 | "@netless/extension-flat": "^1.0.1", 192 | "electron": "^37.2.2", 193 | "electron-builder": "^26.0.12", 194 | "standard": "^17.1.2" 195 | }, 196 | "dependencies": { 197 | "@roamhq/wrtc": "^0.8.0", 198 | "abort-controller": "^3.0.0", 199 | "bt-fetch": "^3.1.1", 200 | "create-desktop-shortcuts": "^1.7.0", 201 | "data-uri-to-buffer": "^3.0.1", 202 | "decompress": "^4.2.1", 203 | "delay": "^6.0.0", 204 | "electron-extended-webextensions": "^0.0.11", 205 | "fs-extra": "^9.0.1", 206 | "gemini-fetch": "^2.1.1", 207 | "gemini-to-html": "^1.0.0", 208 | "hyper-sdk": "^6.1.0", 209 | "hypercore-fetch": "^10.0.0", 210 | "ipfs-http-client": "^60.0.0", 211 | "ipfsd-ctl": "^13.0.0", 212 | "js-ipfs-fetch": "^5.1.0", 213 | "kubo": "^0.36.0", 214 | "make-fetch": "^3.1.3", 215 | "mime": "^2.4.6", 216 | "multiformats": "^9.9.0", 217 | "p-queue": "^7.3.4", 218 | "rc": "^1.2.8", 219 | "sanitize-filename": "^1.6.3", 220 | "scoped-fs": "^1.4.1", 221 | "semver": "^7.5.2", 222 | "ssb-fetch": "^1.5.2", 223 | "web3protocol": "^0.6.2" 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/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 | -------------------------------------------------------------------------------- /src/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 | -------------------------------------------------------------------------------- /src/config.js: -------------------------------------------------------------------------------- 1 | import { app, ipcMain, nativeTheme } from 'electron' 2 | import RC from 'rc' 3 | 4 | import os from 'node:os' 5 | import path from 'node:path' 6 | import { readFile, writeFile } from 'node:fs/promises' 7 | import { fileURLToPath } from 'node:url' 8 | import { getDefaultChainList } from 'web3protocol/chains' 9 | const { join } = path 10 | 11 | // Called whenever there's a change 12 | let onChange = () => null 13 | 14 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 15 | 16 | const isWindows = process.platform === 'win32' 17 | const isMac = process.platform === 'darwin' 18 | 19 | const USER_DATA = app.getPath('userData') 20 | const DEFAULT_EXTENSIONS_DIR = path.join(USER_DATA, 'extensions') 21 | const DEFAULT_IPFS_DIR = path.join(USER_DATA, 'ipfs') 22 | const DEFAULT_HYPER_DIR = path.join(USER_DATA, 'hyper') 23 | // const DEFAULT_SSB_DIR = path.join(USER_DATA, 'ssb') 24 | const DEFAULT_BT_DIR = path.join(USER_DATA, 'bt') 25 | 26 | const DEFAULT_PAGE = 'agregore://welcome' 27 | const DEFAULT_SEARCH_PROVIDER = 'https://duckduckgo.com/?ia=web&q=%s' 28 | 29 | const DEFAULT_CONFIG_FILE_NAME = '.agregorerc' 30 | export const MAIN_RC_FILE = join(os.homedir(), DEFAULT_CONFIG_FILE_NAME) 31 | 32 | let DEFAULT_BACKGROUND = 'var(--ag-color-black)' 33 | let DEFAULT_TEXT = 'var(--ag-color-white)' 34 | let DEFAULT_PAGE_THEME = 'var(--ag-color-black)' 35 | const DEFAULT_BORDER_RADIUS = '0.25em' 36 | const DEFAULT_BORDER_COLOR = 'var(--ag-theme-secondary)' 37 | 38 | const { shouldUseDarkColors } = nativeTheme 39 | 40 | if (shouldUseDarkColors === false) { 41 | DEFAULT_BACKGROUND = 'var(--ag-color-white)' 42 | DEFAULT_TEXT = 'var(--ag-color-black)' 43 | DEFAULT_PAGE_THEME = 'var(--ag-color-white)' 44 | 45 | if (isMac) { 46 | DEFAULT_BACKGROUND = '#F5F5F7' 47 | DEFAULT_TEXT = '#1D1D1F' 48 | } 49 | if (isWindows) { 50 | DEFAULT_BACKGROUND = '#F3F3F3' 51 | DEFAULT_TEXT = '#1a1a1a' 52 | } 53 | } else { 54 | if (isMac) { 55 | DEFAULT_BACKGROUND = '#2C2C2E' 56 | } 57 | if (isWindows) { 58 | DEFAULT_BACKGROUND = '#202020' 59 | } 60 | } 61 | 62 | if (isMac || isWindows) { 63 | DEFAULT_PAGE_THEME = 'none' 64 | } 65 | 66 | const Config = RC('agregore', { 67 | llm: { 68 | enabled: true, 69 | 70 | baseURL: 'http://127.0.0.1:11434/v1/', 71 | // Uncomment this to use OpenAI instead 72 | // baseURL: 'https://api.openai.com/v1/' 73 | apiKey: 'ollama', 74 | model: 'qwen2.5-coder:3b' 75 | }, 76 | accelerators: { 77 | OpenDevTools: 'CommandOrControl+Shift+I', 78 | NewWindow: 'CommandOrControl+N', 79 | Forward: 'CommandOrControl+]', 80 | Back: 'CommandOrControl+[', 81 | FocusURLBar: 'CommandOrControl+L', 82 | FindInPage: 'CommandOrControl+F', 83 | Reload: 'CommandOrControl+R', 84 | HardReload: 'CommandOrControl+Shift+R', 85 | LearnMore: null, 86 | OpenExtensionsFolder: null, 87 | EditConfigFile: 'CommandOrControl+.', 88 | CreateBookmark: 'CommandOrControl+D' 89 | }, 90 | 91 | extensions: { 92 | dir: DEFAULT_EXTENSIONS_DIR, 93 | // TODO: This will be for loading extensions from remote URLs 94 | remote: [] 95 | }, 96 | 97 | theme: { 98 | 'font-family': 'system-ui', 99 | background: DEFAULT_BACKGROUND, 100 | text: DEFAULT_TEXT, 101 | page: DEFAULT_PAGE_THEME, 102 | primary: 'var(--ag-color-purple)', 103 | secondary: 'var(--ag-color-green)', 104 | indent: '16px', 105 | 'max-width': '666px', 106 | 'border-radius': DEFAULT_BORDER_RADIUS, 107 | 'border-color': DEFAULT_BORDER_COLOR 108 | }, 109 | 110 | defaultPage: DEFAULT_PAGE, 111 | autoHideMenuBar: false, 112 | searchProvider: DEFAULT_SEARCH_PROVIDER, 113 | 114 | // All options here: https://github.com/ipfs/js-ipfs/blob/master/docs/CONFIG.md 115 | ipfsOptions: { 116 | repo: DEFAULT_IPFS_DIR, 117 | silent: true, 118 | preload: { 119 | enabled: false 120 | }, 121 | config: { 122 | Ipns: { 123 | UsePubsub: true 124 | }, 125 | Pubsub: { 126 | Enabled: true 127 | }, 128 | Addresses: { 129 | API: '/ip4/127.0.0.1/tcp/2473', 130 | Gateway: '/ip4/127.0.0.1/tcp/2474', 131 | Swarm: [ 132 | '/ip4/0.0.0.0/tcp/2475', 133 | '/ip6/::/tcp/2475', 134 | '/ip4/0.0.0.0/udp/2475/quic', 135 | '/ip6/::/udp/2475/quic' 136 | ] 137 | }, 138 | // We don't need a gateway running. 🤷 139 | Gateway: null 140 | } 141 | }, 142 | 143 | // All options here: https://github.com/datproject/sdk/#const-hypercore-hyperdrive-resolvename-keypair-derivesecret-registerextension-close--await-sdkopts 144 | hyperOptions: { 145 | storage: DEFAULT_HYPER_DIR 146 | }, 147 | 148 | // All options here: https://github.com/ssbc/ssb-config#configuration 149 | ssbOptions: {}, 150 | 151 | // All options here: https://www.npmjs.com/package/web3protocol 152 | web3Options: { 153 | chainList: getDefaultChainList(), 154 | multipleRpcMode: 'fallback' 155 | }, 156 | 157 | // All options here: https://github.com/webtorrent/webtorrent/blob/master/docs/api.md 158 | btOptions: { 159 | folder: DEFAULT_BT_DIR 160 | } 161 | }) 162 | 163 | export default Config 164 | 165 | export function addPreloads (session) { 166 | const preloadPath = path.join(__dirname, 'settings-preload.js') 167 | const preloads = session.getPreloads() 168 | preloads.push(preloadPath) 169 | session.setPreloads(preloads) 170 | } 171 | 172 | ipcMain.handle('settings-save', async (event, configMap) => { 173 | await save(configMap) 174 | }) 175 | 176 | export async function save (configMap) { 177 | const currentRC = await getRCData() 178 | let hasChanged = false 179 | for (const [key, value] of Object.entries(configMap)) { 180 | const existing = getFrom(key, Config) 181 | if (existing === undefined) continue 182 | if (value === existing) continue 183 | hasChanged = true 184 | setOn(key, Config, value) 185 | setOn(key, currentRC, value) 186 | } 187 | if (hasChanged) { 188 | await writeFile(MAIN_RC_FILE, JSON.stringify(currentRC, null, '\t')) 189 | onChange(configMap) 190 | } 191 | } 192 | 193 | async function getRCData () { 194 | try { 195 | const data = await readFile(MAIN_RC_FILE, 'utf8') 196 | return JSON.parse(data) 197 | } catch { 198 | return {} 199 | } 200 | } 201 | 202 | function setOn (path, object, value) { 203 | if (path.includes('.')) { 204 | const [key, subkey] = path.split('.') 205 | if (typeof object[key] !== 'object') { 206 | object[key] = {} 207 | } 208 | object[key][subkey] = value 209 | } else { 210 | object[path] = value 211 | } 212 | } 213 | 214 | // No support for more than one level 215 | function getFrom (path, object) { 216 | if (path.includes('.')) { 217 | const [key, subkey] = path.split('.') 218 | if (typeof object[key] !== 'object') return undefined 219 | return object[key][subkey] 220 | } else { 221 | return object[path] 222 | } 223 | } 224 | 225 | export function setOnChange (newOnChange) { 226 | onChange = newOnChange 227 | } 228 | -------------------------------------------------------------------------------- /src/pages/theme/style.css: -------------------------------------------------------------------------------- 1 | @charset "utf-8"; 2 | @import url("agregore://theme/vars.css"); 3 | 4 | 5 | @font-face { 6 | font-family: 'FontWithASyntaxHighlighter'; 7 | src: url('agregore://theme/FontWithASyntaxHighlighter-Regular.woff2') format('woff2'); 8 | } 9 | 10 | * { 11 | box-sizing: border-box; 12 | } 13 | 14 | html { 15 | background: var(--browser-theme-page-background); 16 | color: var(--browser-theme-text-color); 17 | font-family: var(--browser-theme-font-family); 18 | font-size: inherit; 19 | } 20 | 21 | body { 22 | padding: 1em; 23 | } 24 | 25 | body>p, 26 | body>a, 27 | body>pre, 28 | body>ol, 29 | body>ul, 30 | body>table, 31 | body>img, 32 | body>form, 33 | body>iframe, 34 | body>video, 35 | body>audio, 36 | body>blockquote, 37 | body>details, 38 | body>h1, 39 | body>h2, 40 | body>h3, 41 | body>h4, 42 | body>h5, 43 | body>h6 { 44 | max-width: var(--ag-theme-max-width); 45 | margin-left: auto; 46 | margin-right: auto; 47 | display: block; 48 | } 49 | 50 | input, 51 | button, 52 | textarea, 53 | select, 54 | select *, 55 | option { 56 | color: inherit; 57 | font-family: inherit; 58 | font-size: inherit; 59 | background: var(--browser-theme-background); 60 | padding: var(--browser-theme-border-radius); 61 | margin: 0.5em; 62 | border-radius: var(--browser-theme-border-radius); 63 | } 64 | input[type=color] { 65 | padding: 0px; 66 | } 67 | 68 | input { 69 | font-family: 'FontWithASyntaxHighlighter', monospace; 70 | } 71 | 72 | textarea { 73 | width: 100%; 74 | resize: vertical; 75 | margin: 1em auto; 76 | font-family: 'FontWithASyntaxHighlighter', monospace; 77 | } 78 | 79 | select option { 80 | background: var(--browser-theme-background); 81 | color: var(--browser-theme-text-color); 82 | } 83 | 84 | input, 85 | button, 86 | textarea, 87 | select, 88 | select *, 89 | video, 90 | dialog { 91 | border: 1px solid var(--browser-theme-primary-highlight); 92 | } 93 | 94 | fieldset { 95 | border: 1px solid var(--browser-theme-secondary-highlight); 96 | display: grid; 97 | grid-template-columns: 1fr 1fr; 98 | gap: 1em; 99 | margin-top: 1em; 100 | margin-bottom: 1em; 101 | } 102 | 103 | dialog { 104 | background: var(--browser-theme-background); 105 | color: var(--browser-theme-text-color); 106 | width: 80vw; 107 | height: 80vh; 108 | } 109 | 110 | details summary { 111 | cursor: pointer; 112 | } 113 | 114 | details summary>* { 115 | display: inline; 116 | } 117 | 118 | details summary::marker, 119 | details summary::-webkit-details-marker { 120 | color: var(--browser-theme-primary-highlight) 121 | } 122 | 123 | table { 124 | border-collapse: collapse; 125 | margin: 1em auto; 126 | } 127 | 128 | body>table, 129 | body>pre { 130 | overflow-x: auto; 131 | } 132 | 133 | body>pre:only-child { 134 | color: inherit; 135 | font-size: inherit; 136 | background: none; 137 | padding: 0.5em; 138 | font-family: 'FontWithASyntaxHighlighter', monospace; 139 | } 140 | 141 | th, 142 | td { 143 | border: 1px solid var(--browser-theme-primary-highlight); 144 | /* Set a common border for all cells */ 145 | padding: 0.5em; 146 | /* Add some padding inside each cell */ 147 | text-align: left; 148 | /* Align text to the left within each cell */ 149 | } 150 | 151 | *::selection, 152 | option:hover { 153 | background: var(--browser-theme-primary-highlight); 154 | color: var(--browser-theme-text-highlight); 155 | } 156 | 157 | a { 158 | color: var(--browser-theme-secondary-highlight); 159 | text-decoration: underline; 160 | text-decoration-color: var(--browser-theme-primary-highlight); 161 | } 162 | 163 | a:hover { 164 | color: var(--browser-theme-background); 165 | background-color: var(--browser-theme-secondary-highlight); 166 | text-decoration: none; 167 | } 168 | 169 | a:visited { 170 | color: var(--browser-theme-primary-highlight); 171 | } 172 | 173 | img, 174 | video, 175 | svg, 176 | object, 177 | audio { 178 | width: 80%; 179 | display: block; 180 | margin: 1em auto; 181 | } 182 | 183 | iframe { 184 | display: block; 185 | margin: 1em auto; 186 | width: 100%; 187 | border: none; 188 | } 189 | 190 | pre { 191 | background: var(--browser-theme-primary-highlight); 192 | } 193 | 194 | code { 195 | background: var(--browser-theme-primary-highlight); 196 | font-weight: bold; 197 | padding: 0.25em; 198 | font-family: 'FontWithASyntaxHighlighter', monospace; 199 | } 200 | 201 | blockquote { 202 | border-left: 1px solid var(--browser-theme-primary-highlight); 203 | margin: 1em; 204 | padding-left: 1em; 205 | } 206 | 207 | blockquote>*::before { 208 | content: "> "; 209 | color: var(--browser-theme-secondary-highlight); 210 | } 211 | 212 | pre>code { 213 | display: block; 214 | padding: 0.5em; 215 | background: var(--browser-theme-background); 216 | color: var(--browser-theme-text-color); 217 | } 218 | 219 | br { 220 | display: none; 221 | } 222 | 223 | ul>li { 224 | list-style-type: " ⟐ "; 225 | } 226 | 227 | hr { 228 | border-color: var(--browser-theme-primary-highlight); 229 | } 230 | 231 | *:focus { 232 | outline: 2px solid var(--browser-theme-secondary-highlight); 233 | } 234 | 235 | h1 { 236 | text-align: center; 237 | } 238 | 239 | /* Reset style for anchors added to headers */ 240 | h2 a, 241 | h3 a, 242 | h4 a { 243 | color: var(--browser-theme-text-color); 244 | text-decoration: none; 245 | } 246 | 247 | h1 a { 248 | color: var(--browser-theme-primary-highlight); 249 | text-decoration: none; 250 | } 251 | 252 | h1:hover::after, 253 | h2:hover::after, 254 | h3:hover::after, 255 | h4:hover::after { 256 | text-decoration: none !important; 257 | } 258 | 259 | h2::before { 260 | content: "## "; 261 | color: var(--browser-theme-secondary-highlight) 262 | } 263 | 264 | h3::before { 265 | content: "### "; 266 | color: var(--browser-theme-secondary-highlight) 267 | } 268 | 269 | h4::before { 270 | content: "#### "; 271 | color: var(--browser-theme-secondary-highlight) 272 | } 273 | 274 | *::-webkit-scrollbar { 275 | width: 1em; 276 | } 277 | 278 | *::-webkit-scrollbar-corner { 279 | background: rgba(0, 0, 0, 0); 280 | } 281 | 282 | *::-webkit-scrollbar-thumb { 283 | background-color: var(--browser-theme-primary-highlight); 284 | border: 2px solid transparent; 285 | background-clip: content-box; 286 | } 287 | 288 | *::-webkit-scrollbar-track { 289 | background-color: rgba(0, 0, 0, 0); 290 | } 291 | 292 | 293 | audio::-webkit-media-controls-mute-button, 294 | audio::-webkit-media-controls-play-button, 295 | audio::-webkit-media-controls-timeline-container, 296 | audio::-webkit-media-controls-current-time-display, 297 | audio::-webkit-media-controls-time-remaining-display, 298 | audio::-webkit-media-controls-timeline, 299 | audio::-webkit-media-controls-volume-slider-container, 300 | audio::-webkit-media-controls-volume-slider, 301 | audio::-webkit-media-controls-seek-back-button, 302 | audio::-webkit-media-controls-seek-forward-button, 303 | audio::-webkit-media-controls-fullscreen-button, 304 | audio::-webkit-media-controls-rewind-button, 305 | audio::-webkit-media-controls-return-to-realtime-button, 306 | audio::-webkit-media-controls-toggle-closed-captions-button { 307 | border: none; 308 | border-radius: none; 309 | } 310 | 311 | audio::-webkit-media-controls-timeline { 312 | background: var(--browser-theme-primary-highlight); 313 | margin: 0px 1em; 314 | border-radius: none; 315 | } 316 | 317 | audio::-webkit-media-controls-panel { 318 | background: var(--browser-theme-background); 319 | color: var(--browser-theme-text-color); 320 | font-family: var(--browser-theme-font-family); 321 | font-size: inherit; 322 | border-radius: none; 323 | } 324 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { app, BrowserWindow, session, Menu, Tray } from 'electron' 2 | import path, { sep } from 'node:path' 3 | import { fileURLToPath } from 'node:url' 4 | 5 | import * as protocols from './protocols/index.js' 6 | import { createActions } from './actions.js' 7 | import { registerMenu } from './menu.js' 8 | import { attachContextMenus } from './context-menus.js' 9 | import { WindowManager } from './window.js' 10 | import { createExtensions } from './extensions/index.js' 11 | import * as history from './history.js' 12 | import { version } from './version.js' 13 | import * as llm from './llm.js' 14 | import * as config from './config.js' 15 | 16 | const IS_DEBUG = process.env.NODE_ENV === 'debug' 17 | 18 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 19 | 20 | const WEB_PARTITION = 'persist:web-content' 21 | const LOGO_FILE = path.join(__dirname, './../build/icon-small.png') 22 | 23 | // Wait for two minutes of use before registering handlers 24 | const REGISTRATION_DELAY = 2 * 60 * 1000 25 | 26 | if (IS_DEBUG) { 27 | app.on('web-contents-created', (event, webContents) => { 28 | webContents.openDevTools() 29 | }) 30 | } 31 | 32 | if (!IS_DEBUG) { 33 | // We shouldn't freeze the process when there's an error. Just ignore it. 34 | process.on('uncaughtException', function (error) { 35 | console.error(error) 36 | }) 37 | } 38 | 39 | process.on('SIGINT', () => app.quit()) 40 | 41 | let extensions = null 42 | let windowManager = null 43 | 44 | // Enable text to speech. 45 | // Requires espeak on Linux 46 | app.commandLine.appendSwitch('enable-speech-dispatcher') 47 | 48 | // Smooth scrolling 49 | app.commandLine.appendSwitch('enable-smooth-scrolling') 50 | 51 | // Try to use the GPU for video decode on Pinephone 52 | app.commandLine.appendSwitch('enable-accelerated-video-decode') 53 | app.commandLine.appendSwitch('ignore-gpu-blacklist') 54 | 55 | // Experimental web platform features, such as the FileSystem API 56 | app.commandLine.appendSwitch('enable-experimental-web-platform-features') 57 | 58 | init() 59 | 60 | function init () { 61 | const gotTheLock = app.requestSingleInstanceLock() 62 | 63 | if (!gotTheLock) { 64 | app.quit() 65 | return 66 | } 67 | 68 | windowManager = new WindowManager({ 69 | onSearch: (...args) => history.search(...args), 70 | listActions: (...args) => extensions.listActions(...args) 71 | }) 72 | 73 | app.on('second-instance', (event, argv, workingDirectory) => { 74 | console.log('Got signal from second instance', [...argv]) 75 | const urls = urlsFromArgs(argv.slice(1), workingDirectory) 76 | urls.map((url) => windowManager.open({ url })) 77 | }) 78 | 79 | windowManager.on('open', window => { 80 | attachContextMenus({ window, createWindow, extensions }) 81 | if (!window.rawFrame) { 82 | const asBrowserView = BrowserWindow.fromBrowserView(window.view) 83 | asBrowserView.on('focus', () => { 84 | window.web.focus() 85 | }) 86 | } 87 | 88 | window.web.setWindowOpenHandler(({ url, features, disposition }) => { 89 | console.log('New window', url, disposition) 90 | if ((disposition === 'foreground-tab') || (disposition === 'background-tab')) { 91 | createWindow(url) 92 | 93 | return { action: 'deny' } 94 | } else { 95 | // TODO: Should we override more options here? 96 | return { action: 'allow' } 97 | } 98 | }) 99 | 100 | window.web.on('did-create-window', (window) => { 101 | attachContextMenus({ window, createWindow, extensions }) 102 | }) 103 | }) 104 | } 105 | 106 | // This method will be called when Electron has finished 107 | // initialization and is ready to create browser windows. 108 | // Some APIs can only be used after this event occurs. 109 | app.whenReady().then(onready).catch((e) => { 110 | console.error(e) 111 | process.exit(1) 112 | }) 113 | 114 | app.on('activate', () => { 115 | // On macOS it's common to re-create a window in the app when the 116 | // dock icon is clicked and there are no other windows open. 117 | if (BrowserWindow.getAllWindows().length === 0) { 118 | windowManager.open() 119 | } 120 | }) 121 | 122 | app.on('before-quit', async (e) => { 123 | e.preventDefault() 124 | // Fallback to quit if quitting takes too long 125 | setTimeout(() => app.exit(0), 20000) 126 | try { 127 | await windowManager.saveOpened() 128 | await windowManager.close() 129 | await protocols.close() 130 | } finally { 131 | app.exit(0) 132 | } 133 | }) 134 | 135 | app.on('window-all-closed', () => {}) 136 | 137 | async function onready () { 138 | console.log('Building tray and context menu') 139 | const appIcon = new Tray(LOGO_FILE) 140 | const contextMenu = Menu.buildFromTemplate([ 141 | { label: 'New Window', click: () => createWindow() }, 142 | { 143 | label: 'Quit', 144 | role: 'quit' 145 | } 146 | ]) 147 | // Call this again for Linux because we modified the context menu 148 | appIcon.setContextMenu(contextMenu) 149 | appIcon.on('click', () => { 150 | createWindow() 151 | }) 152 | 153 | const webSession = session.fromPartition(WEB_PARTITION) 154 | 155 | llm.addPreloads(webSession) 156 | config.addPreloads(webSession) 157 | 158 | llm.setCreateWindow(createWindow) 159 | 160 | const electronSection = /Electron.+ /i 161 | const existingAgent = webSession.getUserAgent() 162 | const newAgent = existingAgent.replace(electronSection, `AgregoreDesktop/${version} `) 163 | 164 | webSession.setUserAgent(newAgent) 165 | session.defaultSession.setUserAgent(newAgent) 166 | 167 | const actions = createActions({ 168 | createWindow 169 | }) 170 | 171 | console.log('Setting up protocol handlers') 172 | 173 | await protocols.setupProtocols(webSession) 174 | 175 | console.log('Registering context menu') 176 | 177 | await registerMenu(actions) 178 | 179 | function updateBrowserActions (tabId, actions) { 180 | windowManager.reloadBrowserActions(tabId) 181 | } 182 | 183 | console.log('Initializing extensions') 184 | 185 | extensions = createExtensions({ session: webSession, createWindow, updateBrowserActions }) 186 | 187 | console.log('Extracting internal extensions') 188 | 189 | // Extract any internal extensions if there are updates 190 | await extensions.extractInternal() 191 | 192 | console.log('Registering extensions from disk') 193 | 194 | // Register all extensions in the extensions folder from disk 195 | await extensions.registerAll() 196 | 197 | const historyExtension = await extensions.byName('agregore-history') 198 | 199 | // TODO: Better error handling when the extension doesn't exist? 200 | history.setGetBackgroundPage(() => { 201 | return extensions.getBackgroundPageByName('agregore-history') 202 | }) 203 | 204 | history.setViewPage( 205 | new URL( 206 | historyExtension.manifest.options_page, 207 | historyExtension.url 208 | ).href 209 | ) 210 | 211 | config.setOnChange((configMap) => { 212 | const themeVars = {} 213 | let hadThemeVars = false 214 | for (const key of Object.keys(configMap)) { 215 | if (key.startsWith('theme.')) { 216 | hadThemeVars = true 217 | themeVars[key.slice('theme.'.length)] = configMap[key] 218 | } 219 | } 220 | if (hadThemeVars) windowManager.updateThemeVars(themeVars) 221 | }) 222 | 223 | console.log('Opening saved windows') 224 | 225 | const opened = await windowManager.openSaved() 226 | 227 | const urls = urlsFromArgs(process.argv.slice(1), process.cwd()) 228 | if (urls.length) { 229 | for (const url of urls) { 230 | windowManager.open({ url }) 231 | } 232 | } else if (!opened.length) windowManager.open() 233 | 234 | console.log('Waiting for windows to settle') 235 | 236 | await new Promise((resolve) => setTimeout(resolve, REGISTRATION_DELAY)) 237 | 238 | protocols.setAsDefaultProtocolClient() 239 | 240 | console.log('Initialization done') 241 | } 242 | 243 | function createWindow (url, options = {}) { 244 | console.log('createWindow', url, options) 245 | return windowManager.open({ url, ...options }) 246 | } 247 | 248 | function urlsFromArgs (argv, workingDir) { 249 | const rootURL = new URL(workingDir + sep, 'file://') 250 | return argv 251 | .filter((arg) => arg.includes('/')) 252 | .map((arg) => (arg.includes('://') ? arg : (new URL(arg, rootURL)).href)) 253 | } 254 | -------------------------------------------------------------------------------- /src/llm.js: -------------------------------------------------------------------------------- 1 | import config from './config.js' 2 | import { ipcMain, dialog } from 'electron' 3 | import path from 'node:path' 4 | import { fileURLToPath } from 'node:url' 5 | 6 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 7 | 8 | let isInitialized = false 9 | let createWindow = null 10 | // Completion Iterators, id to iterator 11 | const inProgress = new Map() 12 | let streamId = 1 13 | 14 | export function setCreateWindow (create) { 15 | createWindow = create 16 | } 17 | 18 | ipcMain.handle('llm-supported', async (event) => { 19 | if (!config.llm.enabled) return false 20 | return isSupported() 21 | }) 22 | 23 | ipcMain.handle('llm-chat', async (event, args) => { 24 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 25 | return chat(args) 26 | }) 27 | 28 | ipcMain.handle('llm-complete', async (event, args) => { 29 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 30 | return complete(args) 31 | }) 32 | 33 | ipcMain.handle('llm-chat-stream', async (event, args) => { 34 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 35 | const id = streamId++ 36 | const iterator = chatStream(args) 37 | inProgress.set(id, iterator) 38 | return { id } 39 | }) 40 | 41 | ipcMain.handle('llm-complete-stream', async (event, args) => { 42 | if (!config.llm.enabled) return Promise.reject(new Error('LLM API is disabled')) 43 | const id = streamId++ 44 | const iterator = completeStream(args) 45 | inProgress.set(id, iterator) 46 | return { id } 47 | }) 48 | 49 | ipcMain.handle('llm-iterate-next', async (event, args) => { 50 | const { id } = args 51 | if (!inProgress.has(id)) throw new Error('Unknown Iterator') 52 | const iterator = inProgress.get(id) 53 | const { done, value } = await iterator.next() 54 | if (done) inProgress.delete(id) 55 | return { done, value } 56 | }) 57 | 58 | ipcMain.handle('llm-iterate-return', async (event, args) => { 59 | const { id } = args 60 | if (!inProgress.has(id)) return 61 | const iterator = inProgress.get(id) 62 | await iterator.return() 63 | }) 64 | 65 | export async function isSupported () { 66 | if (!config.llm.enabled) return false 67 | const has = await hasModel() 68 | if (has) return true 69 | return (config.llm.apiKey === 'ollama') 70 | } 71 | 72 | export function addPreloads (session) { 73 | const preloadPath = path.join(__dirname, 'llm-preload.js') 74 | const preloads = session.getPreloads() 75 | preloads.push(preloadPath) 76 | session.setPreloads(preloads) 77 | } 78 | 79 | export async function init () { 80 | if (!config.llm.enabled) throw new Error('LLM API is disabled') 81 | if (isInitialized) return 82 | // TODO: prompt for download 83 | if (config.llm.apiKey === 'ollama') { 84 | try { 85 | await listModels() 86 | } catch { 87 | await showNeedsOllama() 88 | throw new Error('LLM API needs system service install') 89 | } 90 | 91 | const has = await hasModel() 92 | if (!has) { 93 | await confirmPull() 94 | await pullModel() 95 | await notifyPullDone() 96 | } 97 | } 98 | isInitialized = true 99 | } 100 | 101 | async function listModels () { 102 | const { data } = await get('./models', 'Unable to list models') 103 | return data 104 | } 105 | 106 | async function showNeedsOllama () { 107 | const { response, checkboxChecked } = await dialog.showMessageBox({ 108 | title: 'Set up Ollama', 109 | message: 'Agregore needs a local install of Ollama in order to use AI features. Since it has not been detected, would you like help installing it, or would you like to go configure the settings to use another endpoint?', 110 | buttons: ['Show Help', 'Configure', 'Cancel'], 111 | defaultId: 0, 112 | cancelId: 2, 113 | checkboxLabel: 'Remember this choice' 114 | }) 115 | 116 | if (response === 2) { 117 | if (checkboxChecked) { 118 | config.llm.enabled = false 119 | } 120 | throw new Error('Cannot use LLM, user denied help') 121 | } 122 | if (response === 0) { 123 | await createWindow('hyper://agregore.mauve.moe/docs/ai#setting-up-ollama') 124 | } 125 | if (response === 1) { 126 | await createWindow('agregore://settings#llm') 127 | } 128 | } 129 | 130 | async function confirmPull () { 131 | const { response, checkboxChecked } = await dialog.showMessageBox({ 132 | title: 'Download AI Model?', 133 | message: 'Agregore wants to download a large language model to allow websites to use AI features. This can take a few minutes and can take several gigabytes of internet. Do you want to allow this?', 134 | buttons: ['Yes', 'No'], 135 | defaultId: 0, 136 | cancelId: 1, 137 | checkboxLabel: 'Remember this choice' 138 | }) 139 | 140 | if (response === 1) { 141 | if (checkboxChecked) { 142 | config.llm.enabled = false 143 | } 144 | throw new Error('Cannot use LLM, user denied download') 145 | } 146 | } 147 | 148 | async function notifyPullDone () { 149 | await dialog.showMessageBox({ 150 | title: 'AI Model Downloaded', 151 | message: `Agregore has finished downloading the large lanfguage model. You can clear it by running 'ollama rm ${config.llm.model}'` 152 | }) 153 | } 154 | 155 | async function pullModel () { 156 | await post('/api/pull', { 157 | name: config.llm.model 158 | }, `Unable to pull model ${config.llm.model}`, false) 159 | } 160 | 161 | async function hasModel () { 162 | try { 163 | const models = await listModels() 164 | 165 | return !!models.find(({ id }) => id === config.llm.model) 166 | } catch (e) { 167 | console.error(e.stack) 168 | return false 169 | } 170 | } 171 | 172 | export async function chat ({ 173 | messages = [], 174 | temperature, 175 | maxTokens, 176 | stop 177 | }) { 178 | await init() 179 | const { choices } = await post('./chat/completions', { 180 | messages, 181 | model: config.llm.model, 182 | temperature, 183 | max_tokens: maxTokens, 184 | stop 185 | }, 'Unable to generate completion') 186 | 187 | return choices[0].message 188 | } 189 | 190 | export async function complete ({ 191 | prompt, 192 | temperature, 193 | maxTokens, 194 | stop 195 | }) { 196 | await init() 197 | const { choices } = await post('./completions', { 198 | prompt, 199 | model: config.llm.model, 200 | temperature, 201 | max_tokens: maxTokens, 202 | stop 203 | }, 'Unable to generate completion') 204 | 205 | return choices[0].text 206 | } 207 | 208 | export async function * chatStream ({ 209 | messages = [], 210 | temperature, 211 | maxTokens, 212 | stop 213 | } = {}) { 214 | await init() 215 | for await (const { choices } of stream('./chat/completions', { 216 | messages, 217 | model: config.llm.model, 218 | temperature, 219 | max_tokens: maxTokens, 220 | stop 221 | }, 'Unable to generate completion')) { 222 | yield choices[0].delta 223 | } 224 | } 225 | 226 | export async function * completeStream ({ 227 | prompt, 228 | temperature, 229 | maxTokens, 230 | stop 231 | }) { 232 | await init() 233 | 234 | for await (const { choices } of stream('./completions', { 235 | prompt, 236 | model: config.llm.model, 237 | temperature, 238 | max_tokens: maxTokens, 239 | stop 240 | }, 'Unable to generate completion')) { 241 | yield choices[0].text 242 | } 243 | } 244 | 245 | async function * stream (path, data = {}, errorMessage = 'Unable to stream') { 246 | const url = new URL(path, config.llm.baseURL).href 247 | if (!data.stream) data.stream = true 248 | 249 | const response = await fetch(url, { 250 | method: 'POST', 251 | headers: { 252 | 'Content-Type': 'application/json; charset=utf8', 253 | Authorization: `Bearer ${config.llm.apiKey}` 254 | }, 255 | body: JSON.stringify(data) 256 | }) 257 | 258 | if (!response.ok) { 259 | throw new Error(`${errorMessage} ${await response.text()}`) 260 | } 261 | 262 | const decoder = new TextDecoder('utf-8') 263 | let remaining = '' 264 | 265 | const reader = response.body.getReader() 266 | 267 | for await (const chunk of iterate(reader)) { 268 | remaining += decoder.decode(chunk) 269 | const lines = remaining.split('data: ') 270 | remaining = lines.splice(-1)[0] 271 | 272 | yield * lines 273 | .filter((line) => !!line) 274 | .map((line) => JSON.parse(line)) 275 | } 276 | } 277 | 278 | async function get (path, errorMessage, parseBody = true) { 279 | const url = new URL(path, config.llm.baseURL).href 280 | 281 | const response = await fetch(url, { 282 | method: 'GET', 283 | headers: { 284 | Authorization: `Bearer ${config.llm.apiKey}` 285 | } 286 | }) 287 | 288 | if (!response.ok) { 289 | throw new Error(`${errorMessage} ${await response.text()}`) 290 | } 291 | 292 | if (parseBody) { 293 | return await response.json() 294 | } else { 295 | return await response.text() 296 | } 297 | } 298 | 299 | async function post (path, data, errorMessage, shouldParse = true) { 300 | const url = new URL(path, config.llm.baseURL).href 301 | 302 | const response = await fetch(url, { 303 | method: 'POST', 304 | headers: { 305 | 'Content-Type': 'application/json; charset=utf8', 306 | Authorization: `Bearer ${config.llm.apiKey}` 307 | }, 308 | body: JSON.stringify(data) 309 | }) 310 | 311 | if (!response.ok) { 312 | throw new Error(`${errorMessage} ${await response.text()}`) 313 | } 314 | 315 | if (shouldParse) { 316 | return await response.json() 317 | } 318 | return await response.text() 319 | } 320 | 321 | async function * iterate (reader) { 322 | while (true) { 323 | const { done, value } = await reader.read() 324 | if (done) return 325 | yield value 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /src/actions.js: -------------------------------------------------------------------------------- 1 | import { app, shell, dialog } from 'electron' 2 | import fs from 'fs-extra' 3 | import path from 'path' 4 | import createDesktopShortcut from 'create-desktop-shortcuts' 5 | import dataUriToBuffer from 'data-uri-to-buffer' 6 | import sanitize from 'sanitize-filename' 7 | import * as history from './history.js' 8 | 9 | import Config from './config.js' 10 | const { accelerators, extensions, appPath } = Config 11 | 12 | const FOCUS_URL_BAR_SCRIPT = ` 13 | document.getElementById('search').showInput() 14 | document.getElementById('search').focus() 15 | ` 16 | 17 | const OPEN_FIND_BAR_SCRIPT = ` 18 | document.getElementById('find').show() 19 | ` 20 | 21 | export function createActions ({ 22 | createWindow 23 | }) { 24 | return { 25 | OpenDevTools: { 26 | label: 'Open Dev Tools', 27 | accelerator: accelerators.OpenDevTools, 28 | click: onOpenDevTools 29 | }, 30 | ViewHistory: { 31 | label: 'View History', 32 | accelerator: accelerators.ViewHistory, 33 | click: onViewHistory 34 | }, 35 | NewWindow: { 36 | label: 'New Window', 37 | click: onNewWindow, 38 | accelerator: accelerators.NewWindow 39 | }, 40 | Forward: { 41 | label: 'Forward', 42 | accelerator: accelerators.Forward, 43 | click: onGoForward 44 | }, 45 | Back: { 46 | label: 'Back', 47 | accelerator: accelerators.Back, 48 | click: onGoBack 49 | }, 50 | Up: { 51 | label: 'Up', 52 | accelerator: accelerators.Up, 53 | click: onGoUp 54 | }, 55 | ForwardAlt: { 56 | label: 'Forward', 57 | accelerator: 'Alt+Right', 58 | click: onGoForward, 59 | visible: false 60 | }, 61 | BackAlt: { 62 | label: 'Back', 63 | accelerator: 'Alt+Left', 64 | click: onGoBack, 65 | visible: false 66 | }, 67 | UpAlt: { 68 | label: 'Up', 69 | accelerator: 'Alt+Up', 70 | click: onGoUp, 71 | visible: false 72 | }, 73 | FocusURLBar: { 74 | label: 'Focus URL Bar', 75 | click: onFocusURlBar, 76 | accelerator: accelerators.FocusURLBar 77 | }, 78 | FindInPage: { 79 | label: 'Find in Page', 80 | click: onFindInPage, 81 | accelerator: accelerators.FindInPage 82 | }, 83 | Reload: { 84 | label: 'Reload', 85 | accelerator: accelerators.Reload, 86 | click: onReload 87 | }, 88 | HardReload: { 89 | label: 'Hard Reload', 90 | accelerator: accelerators.HardReload, 91 | click: onHardReload 92 | }, 93 | LearnMore: { 94 | label: 'Learn More', 95 | accelerator: accelerators.LearnMore, 96 | click: onLearMore 97 | }, 98 | SetAsDefault: { 99 | label: 'Set as Default Browser', 100 | accelerator: accelerators.SetAsDefault, 101 | click: onSetAsDefault 102 | }, 103 | SetAsDefaultMagnet: { 104 | label: 'Set as Default for Torrents', 105 | accelerator: accelerators.SetAsDefaultMagnet, 106 | click: onSetAsDefaultMagnet 107 | }, 108 | OpenExtensionFolder: { 109 | label: 'Open Extensions Folder', 110 | accelerator: accelerators.OpenExtensionFolder, 111 | click: onOpenExtensionFolder 112 | }, 113 | OpenDataFolder: { 114 | label: 'Open Data Folder', 115 | accelerator: accelerators.OpenDataFolder, 116 | click: onOpenDataFolder 117 | }, 118 | EditConfigFile: { 119 | label: 'Edit Configuration File', 120 | accelerator: accelerators.EditConfigFile, 121 | click: onEditConfigFile 122 | }, 123 | CreateBookmark: { 124 | label: 'Create Bookmark', 125 | accelerator: accelerators.CreateBookmark, 126 | click: onCreateBookmark 127 | } 128 | } 129 | async function onSetAsDefault () { 130 | app.setAsDefaultProtocolClient('http') 131 | app.setAsDefaultProtocolClient('https') 132 | } 133 | 134 | async function onSetAsDefaultMagnet () { 135 | app.setAsDefaultProtocolClient('magnet') 136 | } 137 | 138 | async function onLearMore () { 139 | await shell.openExternal('https://github.com/RangerMauve/agregore-browser') 140 | } 141 | 142 | function onOpenDevTools (event, focusedWindow, focusedWebContents) { 143 | const contents = getContents(focusedWindow) 144 | for (const webContents of contents) { 145 | webContents.openDevTools() 146 | } 147 | } 148 | 149 | function onNewWindow (event, focusedWindow, focusedWebContents) { 150 | createWindow() 151 | } 152 | 153 | function onFocusURlBar (event, focusedWindow) { 154 | focusedWindow.webContents.focus() 155 | focusedWindow.webContents.executeJavaScript(FOCUS_URL_BAR_SCRIPT, true) 156 | } 157 | 158 | function onFindInPage (event, focusedWindow) { 159 | focusedWindow.webContents.focus() 160 | focusedWindow.webContents.executeJavaScript(OPEN_FIND_BAR_SCRIPT, true) 161 | } 162 | 163 | function onReload (event, focusedWindow, focusedWebContents) { 164 | // Reload 165 | for (const webContents of getContents(focusedWindow)) { 166 | webContents.reload() 167 | } 168 | } 169 | 170 | function onHardReload (event, focusedWindow, focusedWebContents) { 171 | // Hard reload 172 | for (const webContents of getContents(focusedWindow)) { 173 | webContents.reloadIgnoringCache() 174 | } 175 | } 176 | 177 | function onGoForward (event, focusedWindow) { 178 | for (const webContents of getContents(focusedWindow)) { 179 | webContents.goForward() 180 | } 181 | } 182 | 183 | function onGoBack (event, focusedWindow) { 184 | for (const webContents of getContents(focusedWindow)) { 185 | webContents.goBack() 186 | } 187 | } 188 | 189 | function onGoUp (event, focusedWindow) { 190 | for (const webContents of getContents(focusedWindow)) { 191 | const currentURL = webContents.getURL() 192 | const next = currentURL.endsWith('/') ? '../' : './' 193 | const toLoad = new URL(next, currentURL).href 194 | webContents.loadURL(toLoad) 195 | } 196 | } 197 | 198 | function getContents (focusedWindow) { 199 | const views = focusedWindow.getBrowserViews() 200 | if (!views.length) return [focusedWindow.webContents] 201 | return views.map(({ webContents }) => webContents) 202 | } 203 | 204 | async function onOpenExtensionFolder () { 205 | try { 206 | const { dir } = extensions 207 | await fs.ensureDir(dir) 208 | 209 | await shell.openPath(dir) 210 | } catch (e) { 211 | console.error(e.stack) 212 | } 213 | } 214 | 215 | async function onOpenDataFolder () { 216 | try { 217 | await shell.openPath(app.getPath('userData')) 218 | } catch (e) { 219 | console.error(e.stack) 220 | } 221 | } 222 | 223 | async function onEditConfigFile () { 224 | await createWindow('agregore://settings') 225 | } 226 | 227 | async function onViewHistory () { 228 | await createWindow(history.getViewPage()) 229 | } 230 | 231 | async function onCreateBookmark (event, focusedWindow) { 232 | for (const webContents of getContents(focusedWindow)) { 233 | const defaultPath = app.getPath('desktop') 234 | const outputPath = (await dialog.showOpenDialog({ 235 | defaultPath, 236 | properties: ['openDirectory'] 237 | })).filePaths[0] 238 | 239 | // If testing from source find and use installed Agregore location 240 | const filePath = appPath || process.argv[0] 241 | 242 | const title = webContents.getTitle() 243 | const shortcutName = sanitize(title, { replacement: ' ' }) 244 | const url = webContents.getURL() 245 | const description = `Agregore Browser - ${url}` 246 | 247 | const shortcut = { 248 | filePath, 249 | outputPath, 250 | name: shortcutName, 251 | comment: description, 252 | description, 253 | arguments: url 254 | } 255 | 256 | const createShortcut = icon => { 257 | if (icon) shortcut.icon = icon 258 | // TODO: Kyran: Use Agregore icon if no icon provided. 259 | // TODO: Kyran: OSX doesn't have arguments option. See https://github.com/RangerMauve/agregore-browser/pull/53#issuecomment-705654060 for solution. 260 | createDesktopShortcut({ 261 | windows: shortcut, 262 | linux: shortcut 263 | }) 264 | } 265 | 266 | try { 267 | const type = process.platform === 'win32' ? 'ico' : 'png' 268 | const faviconDataURI = await getFaviconDataURL(webContents, type) 269 | const buffer = dataUriToBuffer(faviconDataURI) 270 | 271 | const savePath = path.join(app.getPath('userData'), 'PWAs', shortcutName) 272 | const faviconPath = path.join(savePath, `favicon.${type}`) 273 | 274 | await fs.ensureDir(savePath) 275 | await fs.writeFile(faviconPath, buffer) 276 | 277 | createShortcut(faviconPath) 278 | } catch (e) { 279 | console.error('Error loading favicon') 280 | console.error(e.stack) 281 | createShortcut() 282 | } 283 | } 284 | } 285 | } 286 | 287 | async function getFaviconDataURL (webContents, type) { 288 | return webContents.executeJavaScript(`new Promise(async (resolve, reject) => { 289 | try { 290 | const {href} = document.querySelector("link[rel*='icon']") 291 | 292 | const image = new Image() 293 | await new Promise(resolve => { 294 | image.onload = resolve 295 | image.src = href 296 | }) 297 | 298 | const canvas = document.createElement('canvas') 299 | canvas.width = 256 300 | canvas.height = 256 301 | 302 | const context = canvas.getContext('2d') 303 | context.drawImage(image, 0, 0, 256, 256) 304 | 305 | ${ 306 | type === 'ico' 307 | ? ` 308 | canvas.toBlob(blob => { 309 | const reader = new FileReader() 310 | reader.onload = () => resolve(reader.result) 311 | reader.readAsDataURL(new Blob([].concat([ 312 | [0, 0], // ICO header 313 | [1, 0], // Is ICO 314 | [1, 0], // Number of images 315 | [0], // Width (0 seems to work) 316 | [0], // Height (0 seems to work) 317 | [0], // Color palette (none) 318 | [0], // Reserved space 319 | [1, 0], // Color planes 320 | [32, 0], // Bit depth 321 | ].map(part => new Uint8Array(part).buffer), [ 322 | [blob.size], // Image byte size 323 | [22], // Image byte offset 324 | ].map(part => new Uint32Array(part).buffer), [ 325 | blob, // Image 326 | ]), {type: 'image/vnd.microsoft.icon'})) 327 | })` 328 | 329 | : "resolve(canvas.toDataURL('image/png'))" 330 | } 331 | } catch (e) { 332 | reject(e) 333 | } 334 | })`) 335 | } 336 | // 337 | -------------------------------------------------------------------------------- /src/ui/omni-box.js: -------------------------------------------------------------------------------- 1 | /* global HTMLElement, CustomEvent, customElements */ 2 | 3 | const { looksLikeLegacySSB, convertLegacySSB: makeSSB } = require('ssb-fetch') 4 | const { CID } = require('multiformats/cid') 5 | 6 | const IPNS_PREFIX = '/ipns/' 7 | const IPFS_PREFIX = '/ipfs/' 8 | 9 | const WEB_SEARCH_QUERY_PARAM = /%s/gi 10 | 11 | class OmniBox extends HTMLElement { 12 | constructor () { 13 | super() 14 | this.firstLoad = true 15 | this.lastSearch = 0 16 | } 17 | 18 | get options () { 19 | return document.querySelector('#' + this.getAttribute('nav-options-id')) 20 | } 21 | 22 | connectedCallback () { 23 | this.innerHTML = ` 24 |
25 | 26 | 27 | 28 |
29 | 30 | 31 | 32 |
33 |
34 | ` 35 | this.backButton = this.$('.omni-box-back') 36 | this.forwardButton = this.$('.omni-box-forward') 37 | this.upButton = this.$('.omni-box-up') 38 | this.form = this.$('.omni-box-form') 39 | this.input = this.$('.omni-box-input') 40 | this.targetUrl = this.$('.omni-box-target-input') 41 | 42 | this.input.addEventListener('focus', () => { 43 | this.input.select() 44 | }) 45 | 46 | this.targetUrl.addEventListener('focus', () => { 47 | this.showInput() 48 | this.input.select() 49 | }) 50 | 51 | this.input.addEventListener('blur', () => { 52 | this.input.blur() 53 | }) 54 | 55 | this.form.addEventListener('submit', (e) => { 56 | e.preventDefault(true) 57 | 58 | const rawURL = this.getURL() 59 | 60 | let url = rawURL 61 | 62 | if (!isURL(rawURL)) { 63 | if (looksLikeLegacySSB(rawURL)) { 64 | url = makeSSB(rawURL) 65 | } else if (looksLikeIPFS(rawURL)) { 66 | url = makeIPFS(rawURL) 67 | } else if (looksLikeIPNS(rawURL)) { 68 | url = makeIPNS(rawURL) 69 | } else if (isBareLocalhost(rawURL)) { 70 | url = makeHttp(rawURL) 71 | } else if (looksLikeDomain(rawURL)) { 72 | url = makeHttps(rawURL) 73 | } else { 74 | url = makeWebSearch(rawURL) 75 | } 76 | } 77 | 78 | this.clearOptions() 79 | 80 | const searchID = Date.now() 81 | this.lastSearch = searchID 82 | 83 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 84 | }) 85 | this.input.addEventListener('input', () => { 86 | this.updateOptions() 87 | }) 88 | this.input.addEventListener('keydown', ({ keyCode, key }) => { 89 | // Pressed down arrow 90 | if (keyCode === 40) this.selectNext() 91 | 92 | // Pressed up arrow 93 | if (keyCode === 38) this.selectPrevious() 94 | 95 | if (keyCode === 39) { 96 | const { selectionStart, selectionEnd, value } = this.input 97 | const isAtEnd = (selectionStart === value.length) && (selectionEnd === value.length) 98 | if (isAtEnd) this.fillWithSelected() 99 | } 100 | 101 | if (key === 'Escape') { 102 | this.clearOptions() 103 | this.input.blur() 104 | this.dispatchEvent(new CustomEvent('unfocus')) 105 | } 106 | }) 107 | 108 | this.backButton.addEventListener('click', () => { 109 | this.dispatchEvent(new CustomEvent('back')) 110 | }) 111 | this.forwardButton.addEventListener('click', () => { 112 | this.dispatchEvent(new CustomEvent('forward')) 113 | }) 114 | this.upButton.addEventListener('click', () => { 115 | this.dispatchEvent(new CustomEvent('up')) 116 | }) 117 | 118 | // middle mouse click paste&go 119 | this.input.addEventListener('paste', (e) => { 120 | const url = e.clipboardData.getData('text') 121 | 122 | if (isURL(url)) { 123 | e.preventDefault() 124 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 125 | } 126 | }) 127 | } 128 | 129 | clearOptions () { 130 | this.options.innerHTML = '' 131 | } 132 | 133 | getURL () { 134 | const item = this.getSelected() 135 | 136 | return item ? item.dataset.url : this.input.value 137 | } 138 | 139 | getSelected () { 140 | return (this.options.querySelector('[data-selected]') || this.options.firstElementChild) 141 | } 142 | 143 | selectNext () { 144 | const item = this.getSelected() 145 | 146 | if (!item) return 147 | 148 | const sibling = item.nextElementSibling 149 | 150 | if (!sibling) return 151 | 152 | item.removeAttribute('data-selected') 153 | sibling.setAttribute('data-selected', 'selected') 154 | } 155 | 156 | selectPrevious () { 157 | const item = this.getSelected() 158 | 159 | if (!item) return 160 | 161 | const sibling = item.previousElementSibling 162 | 163 | if (!sibling) return 164 | 165 | item.removeAttribute('data-selected') 166 | sibling.setAttribute('data-selected', 'selected') 167 | } 168 | 169 | fillWithSelected () { 170 | const item = this.getSelected() 171 | 172 | if (!item) return 173 | 174 | const { url } = item.dataset 175 | 176 | this.input.value = url 177 | } 178 | 179 | async updateOptions () { 180 | const query = this.input.value 181 | 182 | const searchID = Date.now() 183 | this.lastSearch = searchID 184 | 185 | this.clearOptions() 186 | 187 | if (!query) { 188 | return 189 | } 190 | 191 | this.dispatchEvent(new CustomEvent('search', { detail: { query, searchID } })) 192 | } 193 | 194 | async setSearchResults (results, query, searchID) { 195 | if (this.lastSearch !== searchID) { 196 | return console.debug('Urlbar changed since query finished', this.lastSearch, searchID, query) 197 | } 198 | const finalItems = [] 199 | 200 | if (isURL(query)) { 201 | finalItems.push(this.makeNavItem(query, `Go to ${query}`)) 202 | } else if (looksLikeLegacySSB(query)) { 203 | const url = makeSSB(query) 204 | finalItems.push(this.makeNavItem(url, `Go to ${url}`)) 205 | } else if (looksLikeIPNS(query)) { 206 | const url = makeIPNS(query) 207 | finalItems.push(this.makeNavItem(url, `Go to ${url}`)) 208 | } else if (looksLikeIPFS(query)) { 209 | const url = makeIPFS(query) 210 | finalItems.push(this.makeNavItem(url, `Go to ${url}`)) 211 | } else if (isBareLocalhost(query)) { 212 | finalItems.push(this.makeNavItem(makeHttp(query), `Go to http://${query}`)) 213 | } else if (looksLikeDomain(query)) { 214 | finalItems.push(this.makeNavItem(makeHttps(query), `Go to https://${query}`)) 215 | } else { 216 | finalItems.push( 217 | this.makeNavItem( 218 | makeWebSearch(query), 219 | `Search for "${query}" on Web` 220 | ) 221 | ) 222 | } 223 | 224 | finalItems.push(...results 225 | .map(({ title, url }) => this.makeNavItem(url, `${title} - ${url}`)) 226 | ) 227 | 228 | this.options.replaceChildren(...finalItems) 229 | 230 | this.getSelected().setAttribute('data-selected', 'selected') 231 | } 232 | 233 | addSearchResult ({ title, url }) { 234 | const item = this.makeNavItem(url, `${title} - ${url}`) 235 | this.options.appendChild(item) 236 | } 237 | 238 | makeNavItem (url, text) { 239 | const element = document.createElement('button') 240 | element.classList.add('omni-box-nav-item') 241 | element.classList.add('omni-box-button') 242 | element.dataset.url = url 243 | element.innerText = text 244 | element.onclick = () => { 245 | this.clearOptions() 246 | 247 | this.dispatchEvent(new CustomEvent('navigate', { detail: { url } })) 248 | } 249 | return element 250 | } 251 | 252 | static get observedAttributes () { 253 | return ['src', 'back', 'forward'] 254 | } 255 | 256 | attributeChangedCallback (name, oldValue, newValue) { 257 | if (name === 'src') { 258 | this.input.value = newValue 259 | 260 | const { pathname } = new URL(newValue) 261 | const hasUpperFolders = pathname !== '/' 262 | this.upButton.classList.toggle('hidden', !hasUpperFolders) 263 | 264 | const noFocus = (new URL(window.location.href).searchParams).get('noFocus') === 'true' 265 | if (noFocus) { 266 | return 267 | } 268 | if (this.firstLoad && (newValue === window.DEFAULT_PAGE)) { 269 | this.firstLoad = false 270 | this.focus() 271 | } 272 | } if (name === 'back') { 273 | this.backButton.classList.toggle('hidden', newValue === 'hidden') 274 | } else if (name === 'forward') { 275 | this.forwardButton.classList.toggle('hidden', newValue === 'hidden') 276 | } 277 | } 278 | 279 | get src () { 280 | return this.input.value 281 | } 282 | 283 | set src (value) { 284 | this.setAttribute('src', value) 285 | } 286 | 287 | showInput (show = true) { 288 | this.targetUrl.classList.toggle('hidden', show) 289 | this.input.classList.toggle('hidden', !show) 290 | } 291 | 292 | showTarget (url) { 293 | this.targetUrl.value = url 294 | const inputSelected = this.input === document.activeElement 295 | 296 | if (url && !inputSelected) { 297 | this.showInput(false) 298 | } else { 299 | this.showInput(true) 300 | } 301 | } 302 | 303 | focus () { 304 | this.input.focus() 305 | this.input.select() 306 | } 307 | 308 | $ (query) { 309 | return this.querySelector(query) 310 | } 311 | 312 | convertURL (rawURL) { 313 | } 314 | } 315 | 316 | function makeHttp (query) { 317 | return `http://${query}` 318 | } 319 | 320 | function makeHttps (query) { 321 | return `https://${query}` 322 | } 323 | 324 | function makeWebSearch (query) { 325 | const searchProvider = window.searchProvider // Initialized in script.js 326 | return searchProvider.replaceAll(WEB_SEARCH_QUERY_PARAM, encodeURIComponent(query)) 327 | } 328 | 329 | function isURL (string) { 330 | try { 331 | // localhost: is a valid url apparently! 332 | if (isBareLocalhost(string)) return false 333 | return !!new URL(string) 334 | } catch { 335 | return false 336 | } 337 | } 338 | 339 | function looksLikeDomain (string) { 340 | return !string.match(/\s/) && string.includes('.') 341 | } 342 | 343 | function isBareLocalhost (string) { 344 | return string.match(/^localhost(:[0-9]+)?\/?$/) 345 | } 346 | 347 | function looksLikeIPFS (string) { 348 | return string.startsWith(IPFS_PREFIX) 349 | } 350 | 351 | function makeIPFS (path) { 352 | const sections = path.slice(IPFS_PREFIX.length).split('/') 353 | const cid = sections[0] 354 | if (cid.startsWith('Qm')) { 355 | const parsed = CID.parse(cid) 356 | sections[0] = parsed.toV1().toString() 357 | } 358 | const final = sections.join('/') 359 | return `ipfs://${final}` 360 | } 361 | 362 | function looksLikeIPNS (string) { 363 | return string.startsWith(IPNS_PREFIX) 364 | } 365 | 366 | function makeIPNS (path) { 367 | return `ipns://${path.slice(IPNS_PREFIX.length)}` 368 | } 369 | 370 | customElements.define('omni-box', OmniBox) 371 | -------------------------------------------------------------------------------- /src/window.js: -------------------------------------------------------------------------------- 1 | import { 2 | BrowserWindow, 3 | BrowserView, 4 | ipcMain, 5 | app 6 | } from 'electron' 7 | import path from 'node:path' 8 | import EventEmitter from 'node:events' 9 | import { fileURLToPath } from 'node:url' 10 | 11 | import fs from 'fs-extra' 12 | import PQueue from 'p-queue' 13 | import delay from 'delay' 14 | 15 | import Config from './config.js' 16 | 17 | const IS_DEBUG = process.env.NODE_ENV === 'debug' 18 | 19 | const __dirname = fileURLToPath(new URL('./', import.meta.url)) 20 | 21 | const MAIN_PAGE = path.join(__dirname, './ui/index.html') 22 | const LOGO_FILE = path.join(__dirname, './../build/icon-small.png') 23 | const PERSIST_FILE = path.join(app.getPath('userData'), 'lastOpened.json') 24 | 25 | const DEFAULT_SAVE_INTERVAL = 30 * 1000 26 | 27 | // See if we have any stylesheets with rules 28 | // If not manually inject styles to be like Agregore 29 | const HAS_SHEET = ` 30 | [...document.styleSheets].filter((sheet) => { 31 | try {sheet.cssRules; return true} catch {return false} 32 | }).length || !!(document.querySelectorAll('[style]').length > 1) 33 | ` 34 | 35 | const WINDOW_METHODS = [ 36 | 'goBack', 37 | 'goForward', 38 | 'reload', 39 | 'focus', 40 | 'loadURL', 41 | 'getURL', 42 | 'findInPage', 43 | 'stopFindInPage', 44 | 'setBounds', 45 | 'searchHistoryStart', 46 | 'searchHistoryNext', 47 | 'listExtensionActions', 48 | 'clickExtensionAction' 49 | ] 50 | 51 | const BLINK_FLAGS = [ 52 | 'WebBluetooth', 53 | 'WebBluetoothGetDevices', 54 | 'WebBluetoothRemoteCharacteristicNewWriteValue', 55 | 'WebBluetoothWatchAdvertisements', 56 | 'CSSModules' 57 | ].join(',') 58 | 59 | async function DEFAULT_SEARCH () { 60 | return [] 61 | } 62 | 63 | async function DEFAULT_LIST_ACTIONS () { 64 | return [] 65 | } 66 | 67 | // How long to wait before showing windows 68 | const SHOW_DELAY = 200 69 | 70 | // Used to only show one window at a time 71 | const showQueue = new PQueue({ concurrency: 1 }) 72 | 73 | export class WindowManager extends EventEmitter { 74 | constructor ({ 75 | onSearch = DEFAULT_SEARCH, 76 | listActions = DEFAULT_LIST_ACTIONS, 77 | persistTo = PERSIST_FILE, 78 | saverInterval = DEFAULT_SAVE_INTERVAL 79 | } = {}) { 80 | super() 81 | this.windows = new Set() 82 | this.onSearch = onSearch 83 | this.listActions = listActions 84 | this.persistTo = persistTo 85 | this.saverTimer = null 86 | this.saverInterval = saverInterval 87 | 88 | for (const method of WINDOW_METHODS) { 89 | this.relayMethod(method) 90 | } 91 | } 92 | 93 | open (opts = {}) { 94 | const { onSearch, listActions } = this 95 | const window = new Window({ 96 | onSearch, 97 | listActions, 98 | ...opts 99 | }) 100 | 101 | if (IS_DEBUG) console.log('created window', window.id) 102 | this.windows.add(window) 103 | window.once('close', () => { 104 | this.windows.delete(window) 105 | this.emit('close', window) 106 | }) 107 | window.on('navigating', () => { 108 | this.restartSaver() 109 | }) 110 | this.emit('open', window) 111 | 112 | window.load() 113 | 114 | return window 115 | } 116 | 117 | relayMethod (name) { 118 | ipcMain.handle(`agregore-window-${name}`, ({ sender }, ...args) => { 119 | const { id } = sender 120 | if (IS_DEBUG) console.log('<-', id, name, '(', args, ')') 121 | const window = this.get(id) 122 | if (!window) return console.warn(`Got method ${name} from invalid frame ${id}`) 123 | return window[name](...args) 124 | }) 125 | } 126 | 127 | reloadBrowserActions (tabId) { 128 | for (const window of this.all) { 129 | if (tabId) { 130 | if (window.web.id === tabId) { 131 | window.send('browser-actions-changed') 132 | } 133 | } else { 134 | window.send('browser-actions-changed') 135 | } 136 | } 137 | } 138 | 139 | get (id) { 140 | for (const window of this.windows) { 141 | if (window.id === id) return window 142 | } 143 | return null 144 | } 145 | 146 | get all () { 147 | return [...this.windows.values()] 148 | } 149 | 150 | async updateThemeVars (themeVars) { 151 | const setVars = Object.entries(themeVars) 152 | .map(([key, value]) => `document 153 | .documentElement 154 | .style.setProperty('--ag-theme-${key}', '${value}')`) 155 | .join('\n') 156 | 157 | console.log({ setVars }) 158 | await Promise.all(this.all.map((window) => Promise.all([ 159 | window.web.executeJavaScript(setVars), 160 | window.window.webContents.executeJavaScript(setVars) 161 | ])) 162 | ) 163 | } 164 | 165 | async saveOpened () { 166 | console.log('Saving open windows') 167 | let urls = [] 168 | await Promise.all(this.all.map(async (window) => { 169 | // We don't need to save popups from extensions 170 | if (window.rawFrame) return 171 | const url = window.web.getURL() 172 | if (!url) return 173 | const position = window.window.getPosition() 174 | const size = window.window.getSize() 175 | const scrollOffset = await window.web.executeJavaScript('window.pageYOffset') 176 | urls.push({ url, position, size, scrollOffset }) 177 | })) 178 | 179 | if (urls.length === 1) urls = [] 180 | fs.outputJsonSync(this.persistTo, urls) 181 | } 182 | 183 | async openSaved () { 184 | const saved = await this.loadSaved() 185 | 186 | return saved.map((info) => { 187 | console.log('About to open', info) 188 | const options = { 189 | noFocus: true 190 | } 191 | 192 | const { url, position, size, scrollOffset } = info 193 | 194 | options.url = url 195 | 196 | if (position) { 197 | const [x, y] = position 198 | options.x = x 199 | options.y = y 200 | } 201 | 202 | if (size) { 203 | const [width, height] = size 204 | options.width = width 205 | options.height = height 206 | } 207 | 208 | const window = this.open(options) 209 | 210 | if (scrollOffset) { 211 | window.web.once('dom-ready', () => { 212 | // Wait a bit the JS to settle down 213 | const scrollCode = `setTimeout(()=>window.scrollTo(0, ${scrollOffset}), 100)` 214 | window.web.executeJavaScript(scrollCode) 215 | }) 216 | } 217 | 218 | return window 219 | }) 220 | } 221 | 222 | async loadSaved () { 223 | try { 224 | const infos = await fs.readJson(this.persistTo) 225 | return infos 226 | } catch (e) { 227 | console.error('Error loading saved windows', e.stack) 228 | return [] 229 | } 230 | } 231 | 232 | close () { 233 | this.clearSaver() 234 | for (const window of this.all) { 235 | window.window.close() 236 | } 237 | } 238 | 239 | restartSaver () { 240 | this.clearSaver() 241 | this.startSaver() 242 | } 243 | 244 | startSaver () { 245 | this.saverTimer = setTimeout(() => { 246 | this.saveOpened() 247 | }, this.saverInterval) 248 | } 249 | 250 | clearSaver () { 251 | clearInterval(this.saverTimer) 252 | } 253 | } 254 | 255 | export class Window extends EventEmitter { 256 | #searchIterator = null 257 | constructor ({ 258 | url = Config.defaultPage, 259 | popup = false, 260 | rawFrame = false || popup, 261 | autoResize = false || popup, 262 | noNav = false, 263 | noFocus = false, 264 | onSearch, 265 | listActions, 266 | view, 267 | autoHideMenuBar = Config.autoHideMenuBar || popup, 268 | searchProvider = Config.searchProvider, 269 | ...opts 270 | } = {}) { 271 | super() 272 | 273 | this.onSearch = onSearch 274 | this.listActions = listActions 275 | this.rawFrame = rawFrame 276 | 277 | this.window = new BrowserWindow({ 278 | autoHideMenuBar, 279 | webPreferences: { 280 | // partition: 'persist:web-content', 281 | defaultEncoding: 'utf-8', 282 | nodeIntegration: true, 283 | webviewTag: false, 284 | contextIsolation: false 285 | }, 286 | vibrancy: 'dark', 287 | backgroundMaterial: 'mica', 288 | // transparent: true, 289 | show: false, 290 | icon: LOGO_FILE, 291 | ...opts 292 | }) 293 | this.view = view || new BrowserView({ 294 | webPreferences: { 295 | partition: 'persist:web-content', 296 | defaultEncoding: 'utf-8', 297 | nodeIntegration: false, 298 | nodeIntegrationInSubFrames: true, 299 | sandbox: true, 300 | webviewTag: false, 301 | contextIsolation: true, 302 | enableBlinkFeatures: BLINK_FLAGS, 303 | enablePreferredSizeMode: autoResize 304 | } 305 | }) 306 | 307 | this.window.setVibrancy('fullscreen-ui') 308 | this.window.setBackgroundColor('#00000000') 309 | this.window.setBackgroundMaterial('mica') 310 | 311 | this.window.setBrowserView(this.view) 312 | 313 | this.web.on('did-start-navigation', (event, url, isInPlace, isMainFrame) => { 314 | this.emitNavigate(url, isMainFrame) 315 | }) 316 | this.web.on('did-navigate', (event, url) => { 317 | this.emitNavigate(url, true) 318 | }) 319 | this.web.on('did-navigate-in-page', (event, url, isMainFrame) => { 320 | this.emitNavigate(url, isMainFrame) 321 | }) 322 | 323 | if (autoResize) { 324 | let reloaded = false 325 | this.web.on('preferred-size-changed', (event, preferredSize) => { 326 | const { width, height } = preferredSize 327 | if (IS_DEBUG) console.log('Preferred size', this.id, preferredSize) 328 | this.window.setSize(width, height, false) 329 | this.view.setBounds({ 330 | x: 0, 331 | y: 0, 332 | width, 333 | height 334 | }) 335 | 336 | if (!reloaded) { 337 | reloaded = true 338 | this.web.invalidate() 339 | } 340 | }) 341 | } 342 | 343 | if (popup) { 344 | this.web.focus() 345 | this.window.once('blur', () => { 346 | if (this.web.isFocused() || this.webContents.isFocused()) return 347 | if (this.web.isDevToolsOpened() || this.webContents.isDevToolsOpened()) return 348 | this.window.close() 349 | }) 350 | } 351 | 352 | // Send to UI 353 | this.web.on('page-title-updated', (event, title) => { 354 | this.send('page-title-updated', title) 355 | }) 356 | this.window.on('enter-html-full-screen', () => { 357 | this.send('enter-html-full-screen') 358 | }) 359 | this.window.on('leave-html-full-screen', () => { 360 | this.send('leave-html-full-screen') 361 | }) 362 | this.web.on('update-target-url', (event, url) => { 363 | this.send('update-target-url', url) 364 | }) 365 | this.window.on('enter-full-screen', () => { 366 | this.send('enter-full-screen') 367 | }) 368 | this.window.on('leave-full-screen', () => { 369 | this.send('leave-full-screen') 370 | }) 371 | 372 | this.web.on('dom-ready', async () => { 373 | if (this.web.getURL().startsWith('agregore://settings')) { 374 | this.web.executeJavaScript(`window.onSettings(${JSON.stringify(Config)})`) 375 | } 376 | const hasStyles = await this.web.executeJavaScript(HAS_SHEET, true) 377 | .catch(() => false) // If we error out checking styles, try it anyway 378 | if (!hasStyles) { 379 | const style = await getDefaultStylesheet(this.web) 380 | await this.web.insertCSS(style, { 381 | cssOrigin: 'user' 382 | }) 383 | } 384 | }) 385 | 386 | this.web.once('dom-ready', () => { 387 | showQueue.add(async () => { 388 | await this.window.show() 389 | await delay(SHOW_DELAY) 390 | }) 391 | }) 392 | this.window.on('close', () => { 393 | this.web.destroy() 394 | this.emit('close') 395 | }) 396 | 397 | const toLoad = new URL(MAIN_PAGE, 'file:') 398 | 399 | if (url) toLoad.searchParams.set('url', url) 400 | if (rawFrame) toLoad.searchParams.set('rawFrame', 'true') 401 | if (noNav) toLoad.searchParams.set('noNav', 'true') 402 | if (noFocus) toLoad.searchParams.set('noFocus', 'true') 403 | if (searchProvider) toLoad.searchParams.set('searchProvider', searchProvider) 404 | 405 | this.toLoad = toLoad.href 406 | } 407 | 408 | load () { 409 | return this.window.loadURL(this.toLoad) 410 | } 411 | 412 | emitNavigate (url, isMainFrame) { 413 | if (!isMainFrame) return 414 | if (IS_DEBUG) console.log('Navigating', url) 415 | const canGoBack = this.web.canGoBack() 416 | const canGoForward = this.web.canGoForward() 417 | 418 | this.send('navigating', url) 419 | this.send('history-buttons-change', { canGoBack, canGoForward }) 420 | } 421 | 422 | async goBack () { 423 | return this.web.goBack() 424 | } 425 | 426 | async goForward () { 427 | return this.web.goForward() 428 | } 429 | 430 | async reload () { 431 | return this.web.reload() 432 | } 433 | 434 | async focus () { 435 | return this.web.focus() 436 | } 437 | 438 | async loadURL (url) { 439 | return this.web.loadURL(url) 440 | } 441 | 442 | async getURL () { 443 | return this.web.getURL() 444 | } 445 | 446 | async findInPage (value, opts) { 447 | return this.web.findInPage(value, opts) 448 | } 449 | 450 | async stopFindInPage () { 451 | return this.web.stopFindInPage('clearSelection') 452 | } 453 | 454 | async searchHistoryStart (...args) { 455 | this.#searchIterator = this.onSearch(...args) 456 | } 457 | 458 | async searchHistoryNext () { 459 | if (!this.#searchIterator) return { done: true, value: null } 460 | try { 461 | const { done, value } = await this.#searchIterator.next() 462 | if (done) this.#searchIterator = null 463 | return { done, value } 464 | } catch (e) { 465 | console.error('Error getting next history item') 466 | throw e 467 | } 468 | } 469 | 470 | async setBounds (rect) { 471 | // Fix non-integer heights causing draw break. 472 | // TODO: This should be fixed wherever rect is sent from, not sure where that is. 473 | Object.keys(rect).forEach(key => { 474 | rect[key] = Math.floor(rect[key]) 475 | }) 476 | 477 | return this.view.setBounds(rect) 478 | } 479 | 480 | async listExtensionActions () { 481 | const actions = await this.listActions(this) 482 | return actions.map(({ 483 | title, 484 | extensionId: id, 485 | icon, 486 | badge, 487 | badgeColor, 488 | badgeBackground 489 | }) => { 490 | return { 491 | title, 492 | id, 493 | icon, 494 | badge: { 495 | text: badge, 496 | color: badgeColor, 497 | background: badgeBackground 498 | } 499 | } 500 | }) 501 | } 502 | 503 | async clickExtensionAction (actionId) { 504 | await this.focus() 505 | for (const { extensionId, onClick } of await this.listActions()) { 506 | if (actionId !== extensionId) continue 507 | await onClick(this.web.id) 508 | } 509 | } 510 | 511 | send (name, ...args) { 512 | this.emit(name, ...args) 513 | if (IS_DEBUG) console.log('->', this.id, name, '(', args, ')') 514 | this.window.webContents.send(`agregore-window-${name}`, ...args) 515 | } 516 | 517 | get web () { 518 | return this.view.webContents 519 | } 520 | 521 | get webContents () { 522 | return this.window.webContents 523 | } 524 | 525 | get id () { 526 | return this.window.webContents.id 527 | } 528 | } 529 | 530 | async function getDefaultStylesheet (webContents) { 531 | const [r1, r2] = await Promise.all([ 532 | webContents.session.fetch('agregore://theme/vars.css'), 533 | webContents.session.fetch('agregore://theme/style.css') 534 | ]) 535 | 536 | const [vars, style] = await Promise.all([ 537 | r1.text(), 538 | r2.text() 539 | ]) 540 | return vars + style 541 | } 542 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------