Skip to content

Instantly share code, notes, and snippets.

@stefansundin
Last active October 29, 2021 23:57
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save stefansundin/7244405 to your computer and use it in GitHub Desktop.
A node.js server to redirect custom TLDs in Chrome without the need for the http:// prefix. You can extend this to do all kinds of things.

What this is

A simple node.js server to redirect whatever.dev to http://whatever.dev. It also redirects you to other websites based on your query (see tips below).

Tips

You can quickly go to different websites with certain queries:

It also redirects you to various other services based on your keywords. For example, paste an EC2 instance id to be redirected to a search for it in the EC2 console. By default your AWS searches go to us-east-1, but you can end your query with /us-east-2 or /ohio to perform the action in another region.

Try it

Launch it super fast with:

node -e "`curl -fsL https://gist.githubusercontent.com/stefansundin/7244405/raw/devtld.js`"

Then go to localhost:8888 to make Chrome automatically add it as a search engine. Then go to your settings and set devtld.js as the default search engine.

Alternatively, add a search engine manually and set the search url to: http://localhost:8888/?q=%s

Side effect: Chrome will no longer predict your search terms from Google. But since I personally hate the autocomplete it normally does, I don't mind this.

Install permanently

Save the file to /opt/devtld.js

sudo curl -L -o /opt/devtld.js https://gist.githubusercontent.com/stefansundin/7244405/raw/devtld.js

Ubuntu

Add this command to your startup applications: sh -c "node /opt/devtld.js"

Mac OS X

curl -L -o ~/Library/LaunchAgents/com.stefansundin.devtld.plist https://gist.githubusercontent.com/stefansundin/7244405/raw/com.stefansundin.devtld.plist
chmod 644 ~/Library/LaunchAgents/com.stefansundin.devtld.plist
mkdir -p /usr/local/var/log/
touch /usr/local/var/log/devtld.js.log
launchctl bootstrap user/$UID ~/Library/LaunchAgents/com.stefansundin.devtld.plist
launchctl kickstart user/$UID/com.stefansundin.devtld
launchctl enable user/$UID/com.stefansundin.devtld

If you have problems, make sure permissions are correct, and check tail -f /var/log/system.log for errors, as launchctl doesn't give them you easily.

If your /usr/local directory has weird permissions, you may have problems. Run chown -R ... /usr/local to fix (insert your user and group).

To reload (e.g. after changing the map):

launchctl unload ~/Library/LaunchAgents/com.stefansundin.devtld.plist
launchctl load ~/Library/LaunchAgents/com.stefansundin.devtld.plist

Misc

Note: Chrome will never support this out of the box: https://bugs.chromium.org/p/chromium/issues/detail?id=30636

If you ever find yourself on a computer without this, just append / to the end of the hostname, it's faster than adding http:// in the beginning.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.stefansundin.devtld</string>
<key>Program</key>
<string>/usr/local/bin/node</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/node</string>
<string>/opt/devtld.js</string>
</array>
<key>LimitLoadToSessionType</key>
<array>
<string>Background</string>
<string>Aqua</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<false/>
<key>WorkingDirectory</key>
<string>/usr/local/var</string>
<key>StandardErrorPath</key>
<string>/usr/local/var/log/devtld.js.log</string>
<key>StandardOutPath</key>
<string>/usr/local/var/log/devtld.js.log</string>
</dict>
</plist>
// https://gist.github.com/stefansundin/7244405
// Reload:
// launchctl unload ~/Library/LaunchAgents/com.stefansundin.devtld.plist
// launchctl load ~/Library/LaunchAgents/com.stefansundin.devtld.plist
var tlds = (process.env.TLDS || 'dev,local').split(',');
process.env.SEARCH_URL = process.env.SEARCH_URL || 'https://duckduckgo.com/?q=%s';
process.env.PORT = process.env.PORT || 8888;
process.env.TARGETPROCESS_DOMAIN = process.env.TARGETPROCESS_DOMAIN || 'test';
process.env.AWS_REGION = process.env.AWS_REGION || 'us-east-1';
var http = require('http');
var url = require('url');
var os = require('os');
// get server ip
function ip() {
var ifaces = os.networkInterfaces();
var ips = [];
for (var name in ifaces) {
ifaces[name].forEach((iface) => {
if (iface.family == 'IPv4' && iface.address != '127.0.0.1') {
ips.push(iface.address);
}
});
}
return ips[0];
}
function redirect(res, url) {
console.log(`=> redirected to: ${url}`);
res.writeHead(302, { "Location": url });
res.end();
}
function str_insert_vars(str) {
var args = [].slice.call(arguments, 1);
var i = 0;
return str.replace(/%s/g, () => {
return encodeURIComponent(args[i++]).replace(/%20/g, "+");
});
}
function onRequest(req, res) {
var host = req.headers.host;
var proto = req.headers['x-forwarded-proto'] || 'http';
// force ssl
if (proto != 'https' && /\.herokuapp\.com$/.test(host)) {
redirect(res, `https://${host}${req.url}`)
return;
}
var url_parts = url.parse(req.url, true);
console.log(url_parts.href);
if (url_parts.href == '/') {
res.writeHead(200, {
"Content-Type": "text/html",
"Content-Security-Policy": "default-src 'none'; script-src 'unsafe-inline'"
});
res.write('<!DOCTYPE html><html><head><title>devtld</title><link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="devtld" /></head>\
<body>A search engine should have been added for you. Right click on your address bar and click \'Edit Search Engines...\' (<input type="text" value="chrome://settings/searchEngines" onclick="this.select()" size="35">), then set devtld as the default.\
<p><form action="/" method="get"><input type="text" name="q" placeholder="Test search" size="35"> <input type="submit"></form></p>\
<p><a href="https://gist.github.com/stefansundin/7244405">Gist</a></p>\
</body></html>');
res.end();
return;
}
if (url_parts.href == '/opensearch.xml') {
res.writeHead(200, {
"Content-Type": "application/opensearchdescription+xml",
"Content-Security-Policy": "default-src 'none'"
});
res.write(`<OpenSearchDescription xmlns=\"http://a9.com/-/spec/opensearch/1.1/\" xmlns:moz=\"http://www.mozilla.org/2006/browser/search/\">\n\
<ShortName>devtld</ShortName>\n\
<Description>Search devtld</Description>\n\
<InputEncoding>UTF-8</InputEncoding>\n\
<Image width=\"16\" height=\"16\" type=\"image/x-icon\">https://duckduckgo.com/favicon.ico</Image>\n\
<Url type=\"text/html\" method=\"get\" template=\"${proto}://${host}/?q={searchTerms}\"/>\n\
</OpenSearchDescription>`);
res.end();
return;
}
var q = url_parts.query.q;
if (!q) {
redirect(res, process.env.SEARCH_URL);
return;
}
var aws_region = url_parts.query.aws_region || process.env.AWS_REGION;
var aws_account_id = url_parts.query.aws_account_id;
var slash = q.lastIndexOf('/');
if (slash != -1) {
var suffix = q.substr(slash+1);
// short regions must match exactly
var short_regions = {
'e1': 'us-east-1',
'e2': 'us-east-2',
'w1': 'us-west-1',
'w2': 'us-west-2',
'ue1': 'us-east-1',
'ue2': 'us-east-2',
'uw1': 'us-west-1',
'uw2': 'us-west-2',
'use1': 'us-east-1',
'use2': 'us-east-2',
'usw1': 'us-west-1',
'usw2': 'us-west-2',
'cac1': 'ca-central-1',
'euw1': 'eu-west-1',
'euw2': 'eu-west-2',
'euc1': 'eu-central-1',
'apne1': 'ap-northeast-1',
'apne2': 'ap-northeast-2',
'apse1': 'ap-southeast-1',
'apse2': 'ap-southeast-2',
'aps1': 'ap-south-1',
'sae1': 'sa-east-1',
};
// region names just need to match the beginning
var regions = {
'virginia': 'us-east-1',
'california': 'us-west-1',
'oregon': 'us-west-2',
'ohio': 'us-east-2', // ohio is below oregon so "o" takes you to oregon
'canada': 'ca-central-1',
'ireland': 'eu-west-1',
'frankfurt': 'eu-central-1',
'london': 'eu-west-2',
'tokyo': 'ap-northeast-1',
'seoul': 'ap-northeast-2',
'singapore': 'ap-southeast-1',
'sydney': 'ap-southeast-2',
'mumbai': 'ap-south-1',
'saopaulo': 'sa-east-1',
'global': 'global',
};
if (r = /^((?:us|ca|eu|ap|sa)-(?:south|north)?(?:east|west|central)-\d)$/.exec(suffix)) {
q = q.substr(0, slash)
aws_region = r[1];
}
else if (suffix in short_regions) {
q = q.substr(0, slash)
aws_region = short_regions[suffix];
}
else {
for (var key in regions) {
if (key.indexOf(suffix) == 0) {
q = q.substr(0, slash)
aws_region = regions[key];
break;
}
}
}
}
var argv = q.split(' ');
var args = argv.slice(1).join(' ');
if (slash == -1) {
if (argv[0] == 'ec2' && args) {
var short_regions = [
[/\bue1\b/, 'us-east-1'],
[/\bue2\b/, 'us-east-2'],
[/\buw1\b/, 'us-west-1'],
[/\buw2\b/, 'us-west-2'],
];
var r;
if (r=short_regions.find((r) => { return r[0].test(args) })) {
aws_region = r[1];
}
}
}
var aws_host = 'console.aws.amazon.com';
if (aws_region != 'us-east-1' && aws_region != 'global') {
aws_host = `${aws_region}.${aws_host}`;
}
var dest;
console.log(args);
if (argv[0] == 'mdn') {
dest = 'https://developer.mozilla.org/';
if (args) {
dest += `en-US/search?q=${args}`
}
}
else if (argv[0] == 'tp') { // TargetProcess
dest = `https://${process.env.TARGETPROCESS_DOMAIN}.tpondemand.com/`;
if (args) {
dest += `entity/${args}`;
}
}
else if (argv[0] == 'pow') {
var app = args.replace(/^http:\/\/|\.dev\/?.+$/g, '');
if (req.headers['x-forwarded-for']) {
dest = `http://${app}.${req.headers['x-forwarded-for']}.xip.io/`;
}
else {
dest = `http://${app}.${ip()}.xip.io/`;
}
}
else if (argv[0] == 'gem' && argv[1]) {
var arg = argv[1].toLowerCase().split(/'|"|,| /).find((v) => { return v.length > 0 });
dest = `https://rubygems.org/gems/${arg}`;
}
else if (argv.length == 1 && argv[0].startsWith('ppa:') && argv[0].indexOf('/') != -1) {
var arg = argv[0].substr(4).split('/');
dest = `https://launchpad.net/~${arg[0]}/+archive/ubuntu/${arg[1]}`;
}
else if (argv[0] == 'cookbook' && argv[1]) {
var arg = argv[1].toLowerCase().split(/'|"|,| /).find((v) => { return v.length > 0 });
dest = `https://supermarket.chef.io/cookbooks/${arg}`;
}
else if (argv[0] == 'brew' && argv[1]) {
var arg = argv[1].toLowerCase().split(/'|"|,| /).find((v) => { return v.length > 0 });
dest = `http://brewformulas.org/${arg}`;
}
else if (argv.length == 2 && argv[0] == 'npm') {
dest = `https://www.npmjs.com/package/${args.toLowerCase()}`;
}
else if (argv.length == 2 && argv[0] == 'gopkg') {
dest = `https://golang.org/pkg/${args.toLowerCase()}`;
}
else if (argv.length == 2 && argv[0] == 'pip') {
dest = `https://pypi.python.org/pypi/${args.toLowerCase()}`;
}
else if (argv[0] == 'gh') {
dest = `https://github.com/${args}`;
}
else if (argv[0] == 'commit') {
dest = `https://github.com/${argv[1]}/commit/${argv[2]}`;
}
else if (argv[0] == 'tree') {
dest = `https://github.com/${argv[1]}/tree/${argv[2]}`;
}
// AWS
else if (argv.length == 1 && argv[0] == 'aws') {
dest = `https://${aws_host}/console/home?region=${aws_region}`;
}
else if (argv.length > 1 && argv[0] == 'awsdocs') {
dest = `https://docs.aws.amazon.com/search/doc-search.html?searchPath=documentation-guide&searchQuery=${args}`;
}
else if (argv.length == 1 && argv[0] == 'appspec.yml') {
dest = `https://docs.aws.amazon.com/codedeploy/latest/userguide/app-spec-ref-structure.html`;
}
else if (argv[0] == 'ec2') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Instances:`;
if (r = /^(?:ip-)?(\d{1,3})-(\d{1,3})-(\d{1,3})-(\d{1,3})$/.exec(args)) args = `${r[1]}.${r[2]}.${r[3]}.${r[4]}`;
if (args) dest += `search=${args};`;
dest += `sort=desc:launchTime`; // show most recently launched instances first
}
else if (argv.length == 1 && ['sir','sfr'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/ec2sp/v1/spot/dashboard?region=${aws_region}`;
}
else if (argv.length == 1 && argv[0] == 'ecs') {
dest = `https://${aws_host}/ecs/home?region=${aws_region}#/clusters`;
}
else if (argv.length == 1 && argv[0] == 'ecr') {
dest = `https://${aws_host}/ecs/home?region=${aws_region}#/repositories`;
}
else if (argv.length <= 2 && argv[0] == 'eb') {
dest = `https://${aws_host}/elasticbeanstalk/home?region=${aws_region}#/applications`;
if (args) dest += `?applicationNameFilter=${args}`;
}
else if (argv.length <= 2 && argv[0] == 'ami') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Images:visibility=private-images;`;
if (args) dest += `search=${args};`;
dest += `sort=desc:creationDate`;
}
else if (argv.length <= 2 && ['vol','ebs'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Volumes:`;
if (args) dest += `search=${args};`;
dest += `sort=desc:size`;
}
else if (argv.length <= 2 && ['snap','snapshot','snapshots'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Snapshots:visibility=private;`;
if (args) dest += `search=${args};`;
dest += `sort=desc:startTime`;
}
else if (argv.length == 1 && argv[0] == 'lambda') {
dest = `https://${aws_host}/lambda/home?region=${aws_region}#/functions?display=list`;
}
else if (argv.length == 1 && argv[0] == 'glacier') {
dest = `https://${aws_host}/glacier/home?region=${aws_region}#/vaults`;
}
else if (argv.length == 1 && argv[0] == 'config') {
dest = `https://${aws_host}/config/home?region=${aws_region}#/resource-listing`;
}
else if (argv.length == 1 && argv[0] == 'cognito') {
dest = `https://${aws_host}/cognito/home?region=${aws_region}`;
}
else if (argv.length == 1 && /^(r|route)?53$/.test(argv[0])) {
dest = `https://${aws_host}/route53/home?region=${aws_region}#hosted-zones:`;
}
else if (argv.length == 1 && argv[0] == 'cloudfront') {
dest = `https://${aws_host}/cloudfront/home?region=${aws_region}#`;
}
else if (argv.length == 1 && argv[0] == 'efs') {
dest = `https://${aws_host}/efs/home?region=${aws_region}#/filesystems`;
}
else if (argv.length == 1 && argv[0] == 'vpc') {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vpcs:`;
}
else if (argv.length == 1 && /^(rtb|routetables?)$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#routetables:`;
}
else if (argv.length == 1 && /^igws?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#igws:`;
}
else if (argv.length == 1 && /^eigws?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#EgressOnlyInternetGateways:sort=egressOnlyInternetGatewayId`;
}
else if (argv.length == 1 && /^subnets?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#subnets:`;
}
else if (argv.length == 1 && /^eips?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#Addresses:`;
}
else if (argv.length <= 2 && /^(?:eni|nic)s?$/i.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#NIC:`;
if (args) dest += `search=${args};`;
dest += `sort=networkInterfaceId`;
}
else if (argv.length <= 2 && argv[0] == 'pcx') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#PeeringConnections:`;
if (args) dest += `search=${args};`;
dest += `sort=vpcPeeringConnectionId`;
}
else if (argv.length == 1 && argv[0] == 'vpce') {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#Endpoints:sort=desc:creationTimestamp`;
}
else if (argv.length == 1 && argv[0] == 'nat') {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#NatGateways:sort=natGatewayAddresses.privateIp`;
}
else if (argv.length == 1 && /^n?acls?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#acls:`;
}
else if (argv.length == 1 && /^cgws?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#cgws:`;
}
else if (argv.length == 1 && /^vgws?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vgws:`;
}
else if (argv.length == 1 && /^vpns?$/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vpns:`;
}
else if (argv.length <= 2 && argv[0] == 'cw') {
dest = `https://${aws_host}/cloudwatch/home?region=${aws_region}`;
if (args) dest += `#metricsV2:search=${args}`;
}
else if (argv.length == 1 && argv[0] == 'cwe') {
dest = `https://${aws_host}/cloudwatch/home?region=${aws_region}#rules:`;
}
else if (argv.length <= 2 && argv[0] == 'cwl') {
dest = `https://${aws_host}/cloudwatch/home?region=${aws_region}#logs:`;
if (args) dest += `prefix=${args}`;
}
else if (argv.length <= 2 && ['ls','lightsail'].indexOf(argv[0]) != -1) {
dest = `https://lightsail.aws.amazon.com/ls/webapp/`;
if (args) dest += `instances/${args}/connect`;
else dest += `home/resources`;
}
else if (argv.length <= 2 && ['cd','codedeploy'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/codedeploy/home?region=${aws_region}#/applications`;
if (args) dest += `/${args}`;
}
else if (argv.length <= 2 && ['cb','codebuild'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/codebuild/home?region=${aws_region}#`;
if (args.indexOf(':') != -1) dest += `/builds/${args}/view/new`;
else if (args) dest += `/projects/${args}/view`;
else dest += `/projects`;
}
else if (argv.length == 1 && argv[0] == 'cf') {
dest = `https://${aws_host}/cloudformation/home?region=${aws_region}#/stacks?filter=active`;
}
else if (argv.length == 1 && ['ta','trustedadvisor'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/trustedadvisor/home?region=${aws_region}#/dashboard`;
}
else if (argv.length == 1 && ['ct','cloudtrail'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/cloudtrail/home?region=${aws_region}#/events`;
}
else if (argv.length <= 2 && argv[0] == 'es') {
dest = `https://${aws_host}/es/home?region=${aws_region}`;
if (args) dest += `#${args}:dashboard`;
}
else if (argv.length <= 2 && argv[0] == 'iam') {
dest = `https://console.aws.amazon.com/iam/home?region=${aws_region}#/users`;
if (args) dest += `/${args}`;
}
else if (argv.length == 1 && argv[0] == 'kms') {
dest = `https://console.aws.amazon.com/iam/home?region=${aws_region}#/encryptionKeys/${aws_region}`;
}
else if (argv.length <= 2 && argv[0] == 'sns') {
dest = `https://${aws_host}/sns/v2/home?region=${aws_region}#/topics`;
if (args && aws_account_id) dest += `/arn:aws:sns:${aws_region}:${aws_account_id}:${args}`;
}
else if (argv.length == 1 && argv[0] == 'sqs') {
dest = `https://${aws_host}/sqs/home?region=${aws_region}#`;
}
else if (argv.length == 1 && argv[0] == 'ses') {
dest = `https://${aws_host}/ses/home?region=${aws_region}#home:`;
}
else if (argv.length == 1 && argv[0] == 'waf') {
dest = `https://${aws_host}/waf/home?region=${aws_region}#/webacls`;
}
else if (argv.length == 1 && argv[0] == 'inspector') {
dest = `https://${aws_host}/inspector/home?region=${aws_region}#/dashboard`;
}
else if (argv.length == 1 && argv[0] == 'acm') {
dest = `https://${aws_host}/acm/home?region=${aws_region}#/`;
}
else if (argv.length == 1 && ['emr','elasticmapreduce'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/elasticmapreduce/home?region=${aws_region}#cluster-list:`;
}
else if (argv.length == 1 && ['athena'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/athena/home?region=${aws_region}#query`;
}
else if (argv.length == 1 && ['dp','datapipeline'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/datapipeline/home?region=${aws_region}#`;
}
else if (argv.length == 1 && ['et','elastictranscoder'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/elastictranscoder/home?region=${aws_region}#pipelines:`;
}
else if (argv.length == 1 && ['ag','apigateway'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/apigateway/home?region=${aws_region}#/apis`;
}
else if (argv.length <= 2 && argv[0] == 'rds') {
dest = `https://${aws_host}/rds/home?region=${aws_region}`;
if (args) dest += `#dbinstance:id=${args}`;
else dest += `#dbinstances:`;
}
else if (argv.length == 1 && argv[0] == 'dms') {
dest = `https://${aws_host}/dms/home?region=${aws_region}#`;
}
else if (argv.length <= 2 && ['dd','ddb','dynamo','dynamodb'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/dynamodb/home?region=${aws_region}#tables:`;
if (args) dest += `selected=${args}`;
}
else if (argv.length <= 2 && ['ec','elasticache'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/elasticache/home?region=${aws_region}`;
if (args) dest += `#redis-nodes:id=${args};clusters`;
}
else if (argv.length <= 2 && ['rs','redshift'].indexOf(argv[0]) != -1) {
dest = `https://${aws_host}/redshift/home?region=${aws_region}`;
if (args) dest += `#cluster-details:cluster=${args}`;
else dest += `#cluster-list:`;
}
else if (argv.length == 1 && argv[0] == 'phd') {
dest = `https://phd.aws.amazon.com/phd/home#/dashboard/open-issues`;
}
else if (argv.length <= 2 && argv[0] == 'sg') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#SecurityGroups:`;
if (args) dest += `search=${args};`
dest += `sort=groupName`;
}
else if (argv.length <= 2 && argv[0] == 'elb') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#LoadBalancers:`;
if (args) dest += `search=${args}`
}
else if (argv.length <= 2 && argv[0] == 'alb') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#TargetGroups:`;
if (args) dest += `search=${args}`
}
else if (argv.length <= 2 && argv[0] == 'lc') {
dest = `https://${aws_host}/ec2/autoscaling/home?region=${aws_region}#LaunchConfigurations:`;
if (args) dest += `filter=${args}`
}
else if (argv.length <= 2 && /^asg?$/.test(argv[0])) {
dest = `https://${aws_host}/ec2/autoscaling/home?region=${aws_region}#AutoScalingGroups:`;
if (args) dest += `filter=${args};`
dest += `view=details`;
}
else if (argv.length == 1 && argv[0] == 'ssm') {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Commands:sort=CommandId`;
}
else if (/^i-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Instances:search=${argv[0]};sort=desc:launchTime`;
}
else if (/^e-[0-9a-z]{10,}/.test(argv[0])) {
dest = `https://${aws_host}/elasticbeanstalk/home?region=${aws_region}#/environment/dashboard?environmentId=${argv[0]}`;
}
else if (/^(?:sir|sfr)-[0-9a-z\-]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2sp/v1/spot/dashboard?region=${aws_region}`;
}
else if (/^ami-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Images:visibility=private-images;search=${argv[0]};sort=Name`;
}
else if (/^vol-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Volumes:search=${argv[0]};sort=state`;
}
else if (/^snap-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Snapshots:visibility=private;search=${argv[0]};sort=startTime`;
}
else if (/^sg-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#SecurityGroups:groupId=${argv[0]};sort=groupName`;
}
else if (/^eip(?:alloc|assoc)-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#Addresses:search=${argv[0]};sort=publicIp`;
}
else if (/^eni-[0-9a-f]{8,}/.test(argv[0]) || /^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$/.test(argv[0])) {
dest = `https://${aws_host}/ec2/v2/home?region=${aws_region}#NIC:search=${argv[0]};sort=desc:launchTime`;
}
else if (/^fs-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/efs/home?region=${aws_region}#/filesystems/${argv[0]}`;
}
else if (/^vpc-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vpcs:filter=${argv[0]}`;
}
else if (/^subnet-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#subnets:filter=${argv[0]}`;
}
else if (/^rtb-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#routetables:filter=${argv[0]}`;
}
else if (/^igw-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#igws:filter=${argv[0]}`;
}
else if (/^eigw-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#EgressOnlyInternetGateways:egressOnlyInternetGatewayId=${argv[0]};sort=egressOnlyInternetGatewayId`;
}
else if (/^dopt-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#dhcpOptions:filter=${argv[0]}`;
}
else if (/^vpce-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#Endpoints:vpcEndpointId=${argv[0]};sort=desc:createTime`;
}
else if (/^pcx-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#PeeringConnections:search=${argv[0]}`;
}
else if (/^nat-[0-9a-f]{17,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#NatGateways:search=${argv[0]}`;
}
else if (/^acl-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#acls:filter=${argv[0]}`;
}
else if (/^cgw-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#cgws:filter=${argv[0]}`;
}
else if (/^vgw-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vgws:filter=${argv[0]}`;
}
else if (/^vpn-[0-9a-f]{8,}/.test(argv[0])) {
dest = `https://${aws_host}/vpc/home?region=${aws_region}#vpns:filter=${argv[0]}`;
}
else if (/^j-[0-9A-Z]{13}/.test(argv[0])) {
dest = `https://${aws_host}/elasticmapreduce/home?region=${aws_region}#cluster-details:${argv[0]}`;
}
else if (/^df-[0-9A-Z]{20}/.test(argv[0])) {
dest = `https://${aws_host}/datapipeline/home?region=${aws_region}#ArchitectPlace:pipelineId=${argv[0]}`;
}
else if (/^d-[0-9A-Z]{9,}/.test(argv[0])) {
dest = `https://${aws_host}/codedeploy/home?region=${aws_region}#/deployments/${argv[0]}`;
}
else if (/^d-[0-9a-z]{10,}/.test(argv[0])) {
dest = `https://${aws_host}/workspaces/home?region=${aws_region}#directories:directories`;
}
else if (/^ws-[0-9a-z]{9,}/.test(argv[0])) {
dest = `https://${aws_host}/workspaces/home?region=${aws_region}#listworkspaces:listworkspaces`;
}
else if (/^ml-[0-9a-zA-Z]{9,}/.test(argv[0])) {
dest = `https://${aws_host}/machinelearning/home?region=${aws_region}#/`;
}
else if (/^ev-[0-9a-zA-Z]{11,}/.test(argv[0])) {
dest = `https://${aws_host}/machinelearning/home?region=${aws_region}#/predictor-insight/?tabId=evaluations&evaluationId=${argv[0]}&viewId=summary`;
}
else if (/^db[0-9a-f\-]{34,}/.test(argv[0])) {
dest = `https://${aws_host}/machinelearning/home?region=${aws_region}#/insights/${argv[0]}/summary`;
}
else if (/^E[0-9A-Z]{12}/.test(argv[0])) {
dest = `https://${aws_host}/cloudfront/home?region=${aws_region}#distribution-settings:${argv[0]}`;
}
else if (/^Z[0-9A-Z]{10,}$/.test(argv[0])) {
dest = `https://${aws_host}/route53/home?region=${aws_region}#resource-record-sets:${argv[0]}`;
}
else if (argv[0] == 's3' || argv[0].startsWith('s3://') || argv[0].startsWith('arn:aws:s3:::')) {
var matches = /https?:\/\/([^.]+)\.s3\.amazonaws\.com\/([^?]+)/.exec(argv[1])
|| /https?:\/\/s3\.amazonaws\.com\/([^/]+)\/([^?]+)/.exec(argv[1])
|| /s3:\/\/([^/]+)(?:\/([^?]+))?/.exec(argv[1] || argv[0])
|| /arn:aws:s3:::([^/]+)(?:\/([^?*]+))?/.exec(argv[0]);
if (matches != null) {
var bucket = matches[1];
var prefix = matches[2];
}
else if (argv[1] && argv[1].indexOf('/') > 0) {
var bucket = argv[1].split('/')[0];
var prefix = argv[1].split('/')[1];
}
else {
var bucket = argv[1];
var prefix = argv[2];
}
if (prefix && !prefix.endsWith('/')) {
prefix += '/';
}
dest = `https://${aws_host}/s3/`;
if (bucket) {
dest += `buckets/${bucket}/${prefix || ''}`;
}
else {
dest += `home`;
}
dest += `?region=${aws_region}`;
}
else if (argv.length == 1 && (r=/^(?:(cache|db)\.)?[tmcgridhsxpef]{1,2}[e]?\d\.\d*(nano|micro|small|medium|large|xlarge)$/.exec(argv[0]))) {
if (r[1] == 'cache') {
dest = `https://aws.amazon.com/elasticache/pricing/#Available_Cache_Node_Types`;
}
else {
dest = `http://www.ec2instances.info/${r[1] == 'db'?'rds/':''}?selected=${argv[0]}`;
}
}
else if (argv.length == 1 && argv[0] == 'ec2/pricing') {
dest = `https://aws.amazon.com/ec2/pricing/#On-Demand_Instance_Prices`;
}
else if (argv.length == 1 && (r=/^ip-([\d\-]+)(?:\.(?:ec2|[a-z\-\d]+\.compute)\.internal)?$/.exec(argv[0]))) {
// https://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-dns.html#vpc-dns-hostnames
// .ec2.internal is used for us-east-1, .region.compute.internal for all other regions
// ip-10-50-12-70.ec2.internal
// ip-10-61-2-25.us-west-2.compute.internal
res.writeHead(200, {
"Content-Type": "text/plain",
"Content-Security-Policy": "default-src 'none'"
});
res.write(r[1].replace(/-/g,'.'));
res.end();
return;
}
// End AWS
// Terraform - https://github.com/terraform-providers/terraform-provider-aws/blob/master/CHANGELOG.md
else if ((r=/^aws_(api_gateway_(?:account|api_key|authorizer|base_path_mapping|client_certificate|deployment|domain_name|gateway_response|integration(?:_response)?|method(?:_response|_settings)|model|resource|rest_api|request_validator|stage|usage(?:_plan(?:_key)?)?))$/.exec(argv[0]))
|| (r=/^aws_(appautoscaling_(?:policy|target)|cloudformation_stack|cloudfront_(?:distribution|origin_access_identity)|cloudtrail)$/.exec(argv[0]))
|| (r=/^aws_(cloudwatch_(?:dashboard|event_(?:rule|target)|(?:log_(?:destination(?:policy)?|group|metric_filter|stream|subscription_filter)|metric_alarm)))$/.exec(argv[0]))
|| (r=/^aws_(codebuild_project|codedeploy_(?:app|deployment_(?:config|group))|codepipeline|cognito_identity_pool)$/.exec(argv[0]))
|| (r=/^aws_(config_(?:config_rule|configuration_recorder(?:_status)?|delivery_channel)|dms_(?:certificate|endpoint|replication_(?:instance|subnet_group|task))|devicefarm_project|directory_service_directory|dynamodb_table)$/.exec(argv[0]))
|| (r=/^aws_(alb|alb_listener(?:_rule)?|alb_target_group(?:_attachment)?|ami|ami_(?:copy|from_instance|launch_permission)|app_cookie_stickiness_policy|autoscaling_(?:attachment|group|lifecycle_hook|notification|policy|schedule)|snapshot_create_volume_permissic)$/.exec(argv[0]))
|| (r=/^aws_(ebs_(?:snapshot|volume)|eip(?:_association)?|elb(?:_attachment)?|instance|key_pair|launch_configuration|lb_cookie_stickiness_policy|lb_ssl_negotiation_policy|load_balancer(?:_backend_server|_listener)?_policy)$/.exec(argv[0]))
|| (r=/^aws_(placement_group|proxy_protocol_policy|spot_(?:datafeed_subscription|(?:fleet|instance)_request)|volume_attachment)$/.exec(argv[0]))
|| (r=/^aws_(ecr_repository(?:_policy)?|ecs_(?:cluster|service|task_definition)|efs_(?:file_system|mount_target)|elasticache_(?:cluster|(?:parameter|replication|security|subnet)_group))$/.exec(argv[0]))
|| (r=/^aws_(elastic_beanstalk_(?:application(?:_version)?|configuration_template|environment)|emr_(?:cluster|instance_group|security_configuration)|elasticsearch_domain(?:_policy)?|elastictranscoder_(?:pipeline|preset)|glacier_vault)$/.exec(argv[0]))
|| (r=/^aws_(iam_(?:access_key|account_(?:alias|password_policy)|group(?:_membership)?|instance_profile|openid_connect_provider|role|saml_provider|server_certificate|user(?:_login_profile|_ssh_key)?|(?:(?:group|role|user)_)?policy(?:_attachment)?))$/.exec(argv[0]))
|| (r=/^aws_(iot_(?:certificate|policy)|inspector_(?:assessment_(?:target|template)|resource_group)|kinesis_(?:stream|firehose_delivery_stream)|kms_alias|kms_key|lambda_(?:alias|event_source_mapping|function|permission)|lightsail_(?:domain|instance|key_pair|static_ip(?:_attachment)?))$/.exec(argv[0]))
|| (r=/^aws_(opsworks_(?:application|permission|stack|user_profile|(?:rds_db_)?instance|(?:custom|ganglia|haproxy|memcached|mysql|static_web|(?:java|nodejs|php|rails)_app)_layer))$/.exec(argv[0]))
|| (r=/^aws_(db_(?:event_subscription|instance|(?:option|parameter|security|subnet)_group)|rds_cluster(?:_instance|_parameter_group)?)$/.exec(argv[0]))
|| (r=/^aws_(redshift_(?:cluster|(?:parameter|security|subnet)_group)|waf_(?:web_acl|rate_based_rule|rule|ipset|size_constraint_set|(?:byte|xss|sql_injection)_match_set)|wafregional_(?:byte_match_set|ipset))$/.exec(argv[0]))
|| (r=/^aws_(route53_(?:delegation_set|health_check|record|zone(?:_association)?)|s3_bucket(?:_notification|_object|_policy)?)$/.exec(argv[0]))
|| (r=/^aws_(ses_(?:(?:active_)?receipt_(?:rule(?:_set)?|filter)|domain_identity|configuration_set|event_destination)|sfn_activity|sfn_state_machine|simpledb_domain)$/.exec(argv[0]))
|| (r=/^aws_(sns_topic(?:_policy|_subscription)?|ssm_(?:association|activation|document|maintenance_window(?:_target|_task)?)|sqs_queue(?:_policy)?)$/.exec(argv[0]))
|| (r=/^aws_((?:customer|(?:egress_only_)?internet|nat|vpn)_gateway|vpn_gateway_attachment|default_(?:network_acl|route_table|security_group|subnet|vpc(?:_dhcp_options)?)|flow_log|(?:main_|vpc_endpoint_)?route_table_association|route(?:_table)?|network_acl(?:_rule)?|network_interface(?:(?:_sg)?_attachment)?|security_group(?:_rule)?|subnet|vpc|vpc_(?:dhcp_options(?:_association)?|endpoint|peering_connection(?:_accepter)?)?|vpn_connection(?:_route)?|vpn_gateway(?:_attachment|_route_propagation)?)$/.exec(argv[0]))) {
dest = `https://www.terraform.io/docs/providers/aws/r/${r[1]}.html`;
}
else if (r=/^aws_(codecommit_(?:repository|trigger))$/.exec(argv[0])) {
dest = `https://www.terraform.io/docs/providers/aws/r/${r[1].replace('codecommit','code_commit')}.html`;
}
else if (r=/^aws_(acm_certificate|autoscaling_groups|availability_zones?|caller_identity|canonical_user_id|cloudformation_stack|db_instance|ebs_(?:snapshot|volume)|ecs_(?:container_definition|task_definition)|elb_(?:hosted_zone_id|service_account)|iam_(?:account_alias|policy_document)|instance|ip_ranges|kms_(?:ciphertext|secret)|partition|prefix_list|redshift_service_account|region|route53_zone|route_table|s3_bucket_object|security_group|sns_topic|subnet_ids|vpc_(?:endpoint_service|peering_connection)|vpn_gateway)$/.exec(argv[0])) {
// some duplicates have been removed (resources have precedence)
dest = `https://www.terraform.io/docs/providers/aws/d/${r[1]}.html`;
}
else if (argv[0] == 'tf') {
var q = str_insert_vars(process.env.SEARCH_URL, `${argv.slice(1).join(' ')} site:https://www.terraform.io/docs/`);
redirect(res, q);
return;
}
// End Terraform
else if (argv[0].startsWith('r/')) {
dest = `https://www.reddit.com/${argv[0]}`;
}
else if (argv[0] == 'rt') {
dest = `http://www.rottentomatoes.com/search/?search=${args}`;
}
else if (argv[0] == 's') {
// shorthand to search for stuff that begins with the helpers above
var q = str_insert_vars(process.env.SEARCH_URL, argv.slice(1).join(' '));
redirect(res, q);
return;
}
if (dest) {
redirect(res, dest);
return;
}
// console.log(url_parts.query);
var uri = `http://${q}`;
var host = url.parse(uri, true).hostname;
var dot = host.lastIndexOf('.');
if (dot != -1) {
var tld = host.substr(dot+1).toLowerCase();
if (tlds.indexOf(tld) != -1) {
redirect(res, uri);
return;
}
}
// perform a search
console.log(url_parts);
var q = str_insert_vars(process.env.SEARCH_URL, q);
redirect(res, q);
}
http.createServer(onRequest).listen(process.env.PORT);
console.log(`Server started: http://localhost:${process.env.PORT}/`);
if (ip()) {
console.log(` http://${ip()}:${process.env.PORT}/`);
}

Ok, so you came all the way down here

I have to admit I found a way to keep your autocomplete snazzyness, but this is dangerous since we're editing directly in a Chrome SQLite file.

You have to completely shut down Chrome before you run this command, otherwise you will get the error message: Error: database is locked.

This will overwrite your current Google search engine, and replace the url it goes to when you press enter.

Don't blame me if this sets your house on fire or kills your cat

For some reason I could not get this hack working on Mac OS X.

I have only gotten this working properly in Ubuntu!

Ubuntu

Make sure you have sqlite3 installed:

sudo apt-get install sqlite3

First backup your Web Data file.

cp $HOME/.config/google-chrome/Default/Web\ Data{,-backup}

Then run this to make the change:

sqlite3 "$HOME/.config/google-chrome/Default/Web Data" 'UPDATE keywords SET url="http://localhost:8888/?q=%s" WHERE keyword="google.com";'

To restore, run:

sqlite3 "$HOME/.config/google-chrome/Default/Web Data" 'UPDATE keywords SET url="{google:baseURL}search?q={searchTerms}&{google:RLZ}{google:originalQueryForSuggestion}{google:assistedQueryStats}{google:searchFieldtrialParameter}{google:searchClient}{google:sourceId}{google:instantExtendedEnabledParameter}{google:omniboxStartMarginParameter}ie={inputEncoding}" WHERE keyword="google.com";'
{
"name": "devtld",
"version": "0.3.0",
"description": "A node.js server to redirect custom TLDs in Chrome without the need for the http:// prefix.",
"main": "devtld.js",
"scripts": {
"start": "node devtld.js"
},
"dependencies": {},
"engines": {
"node": "7.x"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/stefansundin/7244405"
},
"keywords": [
"node",
"devtld"
],
"license": "GPL-3.0"
}
web: node devtld.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment