Skip to content

Commit

Permalink
DApps server (#9)
Browse files Browse the repository at this point in the history
* DApps server

* Update link to install script after repo rename
  • Loading branch information
noisekit authored Apr 19, 2023
1 parent 4c3db98 commit 1e69763
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 19 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Anyone with a computer and an internet connection can join the swarm. It’s fin

Open terminal and run the following command:
```sh
curl https://raw.githubusercontent.com/Synthetixio/snx-node/main/install-macos.sh | bash
curl https://synthetixio.github.io/synthetix-node/install-macos.sh | bash
```

### Manual Installation
Expand Down
2 changes: 2 additions & 0 deletions assets/entitlements.mac.plist
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,7 @@
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
6 changes: 3 additions & 3 deletions src/main/dapps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export async function isPinned(qm: string): Promise<boolean> {
}
}

export async function getDappUrl(ens: string): Promise<string | undefined> {
export async function getDappHost(ens: string): Promise<string | undefined> {
try {
const { codec, hash } = await resolveEns(ens);
logger.log(ens, 'resolved', codec, hash);
Expand All @@ -87,8 +87,8 @@ export async function getDappUrl(ens: string): Promise<string | undefined> {
await ipfs(`pin add --progress ${qm}`);
}
const bafy = await convertCid(qm);
const url = `http://${bafy}.ipfs.localhost:8080`;
logger.log(ens, 'local URL:', url);
const url = `${bafy}.ipfs.localhost`;
logger.log(ens, 'local IPFS host:', url);
return url;
} catch (e) {
logger.error(e);
Expand Down
45 changes: 30 additions & 15 deletions src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,10 @@ import {
followerKill,
followerPid,
} from './follower';
import { getDappUrl } from './dapps';
import { getDappHost } from './dapps';
import * as settings from './settings';
import http from 'http';
import { proxy } from './proxy';

logger.transports.file.level = 'info';

Expand All @@ -53,6 +55,10 @@ const dapps: { [key: string]: string | undefined } = {
'kwenta.eth': undefined,
'staking.synthetix.eth': undefined,
};
const localDapps: { [key: string]: string | undefined } = {
'kwenta.eth': 'kwenta',
'staking.synthetix.eth': 'staking',
};

if (process.env.NODE_ENV === 'production') {
const sourceMapSupport = require('source-map-support');
Expand Down Expand Up @@ -204,15 +210,11 @@ function generateMenuItems() {
separator: {
type: 'separator',
},
dapps: Object.entries(dapps).map(([name, url]) => {
dapps: Object.entries(localDapps).map(([name, shortcut]) => {
return {
enabled: Boolean(url),
enabled: Boolean(dapps[name]),
label: name,
click: () => {
if (url) {
shell.openExternal(url);
}
},
click: () => shell.openExternal(`http://${shortcut}.localhost:8888`),
};
}),
quit: {
Expand Down Expand Up @@ -310,15 +312,12 @@ followerDaemon();
const followerCheck = setInterval(followerDaemon, 10_000);
app.on('will-quit', () => clearInterval(followerCheck));

ipcMain.handle('dapp', async (_event, ens: string) => {
if (!(ens in dapps)) {
dapps[ens] = undefined;
}
return dapps[ens];
});
ipcMain.handle('dapp', async (_event, ens: string) =>
dapps[ens] ? `http://${localDapps[ens]}.localhost:8888` : null
);
async function updateAllDapps() {
Object.keys(dapps).forEach((ens) =>
getDappUrl(ens).then((url) => {
getDappHost(ens).then((url) => {
if (url) {
dapps[ens] = url;
updateContextMenu();
Expand All @@ -329,3 +328,19 @@ async function updateAllDapps() {
const dappsUpdater = setInterval(updateAllDapps, 600_000); // 10 minutes
app.on('will-quit', () => clearInterval(dappsUpdater));
waitForIpfs().then(updateAllDapps).catch(logger.error);

http
.createServer((req, res) => {
const shortcut = `${req.headers.host}`.replace('.localhost:8888', '');
const host = Object.keys(localDapps).find(
(key) => localDapps[key] === shortcut
);
if (host && host in dapps && dapps[host]) {
req.headers.host = dapps[host];
proxy({ host: '127.0.0.1', port: 8080 }, req, res);
return;
}
res.writeHead(404);
res.end('Not found');
})
.listen(8888, '0.0.0.0');
32 changes: 32 additions & 0 deletions src/main/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import http, { IncomingMessage, ServerResponse } from 'http';
import logger from 'electron-log';

export function proxy(
upstream: {
host: string;
port: number;
},
req: IncomingMessage,
res: ServerResponse
) {
const options = {
hostname: upstream.host,
port: upstream.port,
path: req.url,
method: req.method,
headers: req.headers,
};

const proxyReq = http.request(options, (proxyRes: IncomingMessage) => {
res.writeHead(proxyRes.statusCode!, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});

req.pipe(proxyReq, { end: true });

proxyReq.once('error', (err) => {
logger.error(`Error in proxy request: ${err.message}`);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Error occurred while processing the request.');
});
}

0 comments on commit 1e69763

Please sign in to comment.