Skip to content

Instantly share code, notes, and snippets.

@dennisreimann
Created October 25, 2019 11:22
Show Gist options
  • Save dennisreimann/cdaf37d1e373fbb8f9beb37fcfdb60de to your computer and use it in GitHub Desktop.
Save dennisreimann/cdaf37d1e373fbb8f9beb37fcfdb60de to your computer and use it in GitHub Desktop.
Minimal OpenAlias implementation in Node.js
#!/usr/bin/env node
const resolveOpenalias = require('./openalias');
const address = process.argv[2]
if (!address) {
console.error('Please provide an address to resolve.\n\nUsage: ./openalias-cli.js my.domain.com')
process.exit(1)
}
(async () => {
try {
const result = await resolveOpenalias(address)
if (result.length) {
console.log(`${address} provides the following OpenAlias records:`, result)
} else {
console.log(`${address} does not provide any valid OpenAlias records`)
}
} catch (err) {
console.error(err)
}
})()
// https://openalias.org/#implement
const dns = require('dns')
const transformAddr = addr => addr.replace(/@/g, '.')
const validateAddr = addr => /\./.test(addr)
const camelize = str => str
.replace(/^[_.\- ]+/, '')
.toLowerCase()
.replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase())
.replace(/\d+(\w|$)/g, m => m.toUpperCase())
const resolveOpenalias = addr =>
new Promise((resolve, reject) => {
// transform and validate
const address = transformAddr(addr)
if (!validateAddr(address)) return reject('Address must be a FQDN.')
// lookup
dns.resolve(address, 'TXT', (err, records) => {
if (err) reject(err)
// parse txt records
const openaliases = records.reduce((result, record) => {
const [, app, data] = (record.length && record[0].match(/^oa1\:([\S]+)\s(.*)/)) || []
if (!app || !data) return result
// convert information
const openalias = data.split(';').reduce((result, entry) => {
const [key, value] = entry.trim().split('=')
if (key && value) result[camelize(key)] = value
return result
}, { app })
// ensure recipient address
return openalias.recipientAddress
? result.concat([openalias])
: result
}, [])
resolve(openaliases)
})
})
module.exports = resolveOpenalias
@dennisreimann
Copy link
Author

Just toying around: This is very minimal and does not support DNSSEC, which is a requirement for serious usage!

See the OpenAlias docs for more information.
Thanks for the inspiration, @bumi!

@bumi
Copy link

bumi commented Oct 25, 2019

ooohh nice! that's super cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment