Skip to content

Commit

Permalink
Merge pull request #41 from hyphacoop/dns
Browse files Browse the repository at this point in the history
  • Loading branch information
jackyzha0 committed Feb 17, 2023
2 parents 986aae5 + ec41874 commit 0cfd671
Show file tree
Hide file tree
Showing 7 changed files with 109 additions and 16 deletions.
6 changes: 6 additions & 0 deletions v1/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { registerAuth } from '../authorization/cfg.js'
import { authRoutes } from './auth.js'
import { ServerI } from '../index.js'
import { ProtocolManager } from '../protocols/index.js'
import { initDnsServer } from '../dns/index.js'

const paths = envPaths('distributed-press')

Expand Down Expand Up @@ -66,6 +67,10 @@ async function apiBuilder (cfg: APIConfig): Promise<FastifyTypebox> {
server.log.info('Initializing protocols')
await protocols.load()
const store = new Store(cfg, db, protocols)

server.log.info('Initializing DNS server')
const dns = await initDnsServer(cfg.dnsport, store.sites, server.log)

server.log.info('Done')
await registerAuth(cfg, server, store)
await server.register(multipart)
Expand All @@ -80,6 +85,7 @@ async function apiBuilder (cfg: APIConfig): Promise<FastifyTypebox> {
// handle cleanup on shutdown
server.addHook('onClose', async server => {
server.log.info('Begin shutdown, unloading protocols...')
await dns.close()
await protocols.unload()
.then(() => {
server.log.info('Done')
Expand Down
64 changes: 63 additions & 1 deletion v1/dns/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,63 @@
// STUB
import dns2 from 'dns2'
import { FastifyBaseLogger } from 'fastify'
import { SiteConfigStore } from '../config/sites.js'

function protocolToMultiformat(link: string): string {
const [protocol, path] = link.split("://")
return `/${protocol}/${path}`
}

export async function initDnsServer(port: number, store: SiteConfigStore, logger: FastifyBaseLogger): Promise<ReturnType<typeof dns2.createServer>> {
const server = dns2.createServer({
udp: true,
handle: (request, send, rinfo) => {
const response = dns2.Packet.createResponseFromRequest(request)
const [{ name }] = request.questions
logger.info(`[dns] ${rinfo.address}:${rinfo.port} asked for ${name}`)

const trimmedName = name.replace('_dnslink.', '')
store.get(trimmedName)
.then(({ links }) => {
if (links.ipfs !== undefined) {
response.answers.push({
name,
type: dns2.Packet.TYPE.TXT,
class: dns2.Packet.CLASS.IN,
ttl: 60,
data: `dnslink=${protocolToMultiformat(links.ipfs.pubKey)}`
})
}
if (links.hyper !== undefined) {
response.answers.push({
name,
type: dns2.Packet.TYPE.TXT,
class: dns2.Packet.CLASS.IN,
ttl: 60,
data: `dnslink=${protocolToMultiformat(links.hyper.raw)}`
})
}
send(response)
})
.catch((error) => logger.error(`[dns] error handling request: ${error as string}`))
}
})

// add logging handlers
server
.on('requestError', (error) => {
logger.error(`[dns] error handling request: ${error as string}`)
})
.on('listening', () => {
logger.info(`[dns] starting DNS server on port ${port}`)
})
.on('close', () => {
logger.info('[dns] closing DNS server')
})

await server.listen({
udp: port,
tcp: port
})

return server
}
8 changes: 3 additions & 5 deletions v1/fixtures/spawnServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { generateKeyPair } from '../authorization/jwt.js'
import apiBuilder, { FastifyTypebox } from '../api/index.js'
import { nanoid } from 'nanoid'
import { BUILTIN } from '../protocols/ipfs.js'
import getPort from 'get-port'

const paths = envPaths('distributed-press')
export async function spawnTestServer (): Promise<FastifyTypebox> {
Expand All @@ -18,12 +19,9 @@ export async function spawnTestServer (): Promise<FastifyTypebox> {
return await apiBuilder({
useMemoryBackedDB: true,
port: 8080,
dnsport: await getPort(),
host: 'localhost',
storage: storagePath,
ipfsProvider: BUILTIN,
dns: {
server: '127.0.0.1:53',
domains: []
}
ipfsProvider: BUILTIN
})
}
13 changes: 4 additions & 9 deletions v1/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,26 @@ const paths = envPaths('distributed-press')

const argv = yargs(hideBin(process.argv)).options({
port: { type: 'number' },
dnsport: { type: 'number' },
host: { type: 'string' },
data: { type: 'string' },
ipfsProvider: { type: 'string' }
}).parseSync()

export interface ServerI {
port: number
dnsport: number
host: string
storage: string
ipfsProvider: IPFSProvider
dns: {
server: string
domains: string[]
}
}

const cfg: ServerI = {
port: Number(argv.port ?? process.env.PORT ?? '8080'),
dnsport: Number(argv.dnsport ?? process.env.DNSPORT ?? '53'),
host: argv.host ?? process.env.HOST ?? 'localhost',
storage: argv.data ?? paths.data,
ipfsProvider: (argv.ipfsProvider as IPFSProvider) ?? BUILTIN,
dns: {
server: '127.0.0.1:53',
domains: []
}
ipfsProvider: (argv.ipfsProvider as IPFSProvider) ?? BUILTIN
}

const server = await apiBuilder({
Expand Down
30 changes: 30 additions & 0 deletions v1/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions v1/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@sinclair/typebox": "^0.25.9",
"abstract-level": "^1.0.3",
"cors": "^2.8.5",
"dns2": "^2.0.5",
"env-paths": "^3.0.0",
"express": "^4.17.1",
"fast-jwt": "^2.0.2",
Expand All @@ -73,6 +74,7 @@
},
"devDependencies": {
"@ava/typescript": "^3.0.1",
"@types/dns2": "^2.0.2",
"@types/gunzip-maybe": "^1.4.0",
"@types/node": "^18.11.13",
"@types/rimraf": "^3.0.2",
Expand Down
2 changes: 1 addition & 1 deletion v1/protocols/ipfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export class IPFSProtocol implements Protocol<Static<typeof IPFSProtocolFields>>
const pubKey = `ipns://${publishKey}/`
return {
enabled: true,
link: pubKey,
link: `ipns://${id}/`,
// TODO: Pass in gateway parameters in options (DP domain name?)
gateway: `https://gateway.ipfs.io/ipns/${publishKey}/`,
cid,
Expand Down

0 comments on commit 0cfd671

Please sign in to comment.