forked from unimatrix/web
22 lines
9.7 KiB
JavaScript
22 lines
9.7 KiB
JavaScript
import {createCipheriv,createDecipheriv,randomBytes,scrypt as rawScrypt,timingSafeEqual} from 'node:crypto';
|
|
import {readFile,writeFile,mkdir,stat} from 'node:fs/promises';import {promisify} from 'node:util';import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
|
|
const scrypt=promisify(rawScrypt),keyPath='/home/dunerealms/.config/hosting-master.key',providers=['godaddy','hetzner-cloud','hetzner-robot'];
|
|
const reply=(v,status=200)=>Response.json(v,{status,headers:{'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});
|
|
export async function hostingKey(){await mkdir('/home/dunerealms/.config',{recursive:true,mode:0o700});try{await writeFile(keyPath,randomBytes(32),{flag:'wx',mode:0o600});}catch(e){if(e.code!=='EEXIST')throw e;}const info=await stat(keyPath),key=await readFile(keyPath);if(key.length!==32||(info.mode&0o077))throw Error('Hosting encryption unavailable');return key;}
|
|
export function sealHosting(value,key){const iv=randomBytes(12),c=createCipheriv('aes-256-gcm',key,iv),data=Buffer.concat([c.update(JSON.stringify(value),'utf8'),c.final()]);return JSON.stringify({iv:iv.toString('base64'),tag:c.getAuthTag().toString('base64'),data:data.toString('base64')});}
|
|
export function openHosting(value,key){const v=JSON.parse(value),c=createDecipheriv('aes-256-gcm',key,Buffer.from(v.iv,'base64'));c.setAuthTag(Buffer.from(v.tag,'base64'));return JSON.parse(Buffer.concat([c.update(Buffer.from(v.data,'base64')),c.final()]).toString('utf8'));}
|
|
export async function initializeHosting(db){await db.prepare('CREATE TABLE IF NOT EXISTS site_hosting_connections(user_id CHAR(36) NOT NULL,provider VARCHAR(24) NOT NULL,credentials TEXT NOT NULL,verified_at BIGINT NOT NULL,PRIMARY KEY(user_id,provider))').run();}
|
|
export function validateHostingCredentials(provider,v){const clean=x=>typeof x==='string'&&x.length>=8&&x.length<=256&&!/[\x00-\x20\x7f]/.test(x);if(!providers.includes(provider)||!v||typeof v!=='object')throw Error('Choose a supported provider.');if(provider==='godaddy'){if(!clean(v.key)||!clean(v.secret))throw Error('Enter your production GoDaddy API key and secret.');return{key:v.key,secret:v.secret};}if(provider==='hetzner-cloud'){if(!clean(v.token))throw Error('Enter your Hetzner Cloud API token.');return{token:v.token};}if(!clean(v.username)||typeof v.password!=='string'||v.password.length<8||v.password.length>256||/[\r\n\0]/.test(v.password))throw Error('Enter your Robot webservice username and password.');return{username:v.username,password:v.password};}
|
|
export async function hostingRequest(provider,credentials,path,{fetcher=fetch}={}){const base=provider==='godaddy'?'https://api.godaddy.com':provider==='hetzner-cloud'?'https://api.hetzner.cloud/v1':'https://robot-ws.your-server.de';if(!path.startsWith('/')||path.startsWith('//'))throw Error('Invalid provider path');const auth=provider==='godaddy'?'sso-key '+credentials.key+':'+credentials.secret:provider==='hetzner-cloud'?'Bearer '+credentials.token:'Basic '+Buffer.from(credentials.username+':'+credentials.password).toString('base64');const r=await fetcher(base+path,{headers:{Authorization:auth,Accept:'application/json'},redirect:'error',signal:AbortSignal.timeout(12000)});if(!r.ok)throw Object.assign(Error([401,403].includes(r.status)?'Provider rejected access. Check your credentials and API eligibility.':r.status===429?'Provider rate limit reached. Try again shortly.':'The provider is temporarily unavailable.'),{status:503});const text=await r.text();if(text.length>4*1024*1024)throw Error('Provider response exceeds limit');return JSON.parse(text);}
|
|
export async function providerInventory(provider,c,options={}){if(provider==='godaddy'){const out=[];let marker='';for(let page=0;page<20;page++){const rows=await hostingRequest(provider,c,'/v1/domains?limit=100'+(marker?'&marker='+encodeURIComponent(marker):''),options);if(!Array.isArray(rows))throw Error('Unexpected domain response');for(const r of rows)if(typeof r.domain==='string'&&/^[a-z0-9.-]+$/i.test(r.domain))out.push({domain:r.domain,status:String(r.status||''),expires:r.expires||null,manageUrl:'https://dcc.godaddy.com/control/portfolio/'+encodeURIComponent(r.domain)+'/settings?tab=dns'});if(rows.length<100)return out;const next=rows.at(-1)?.domain;if(!next||next===marker)throw Error('Incomplete provider pagination');marker=next;}throw Error('Domain inventory exceeds supported page limit');}
|
|
if(provider==='hetzner-cloud'){const out=[];for(let page=1;page<=50;page++){const v=await hostingRequest(provider,c,'/servers?per_page=50&page='+page,options);if(!Array.isArray(v.servers))throw Error('Unexpected Cloud response');for(const r of v.servers)out.push({id:String(r.id),name:r.name,status:r.status,ipv4:r.public_net?.ipv4?.ip||null,location:r.datacenter?.location?.name||null,type:r.server_type?.description||r.server_type?.name||null,manageUrl:'https://console.hetzner.com/'});if(!v.meta?.pagination?.next_page)return out;}throw Error('Server inventory exceeds supported page limit');}
|
|
const rows=await hostingRequest(provider,c,'/server',options);if(!Array.isArray(rows))throw Error('Unexpected Robot response');return rows.map(v=>v.server).filter(Boolean).map(r=>({id:String(r.server_number),name:r.server_name||r.product,status:r.cancelled?'Cancellation scheduled':r.status||'Registered',ipv4:r.server_ip,location:r.dc,type:r.product,manageUrl:'https://robot.hetzner.com/server'}));}
|
|
export function createHosting(db,{origin='https://cp.dunerealms.com',getIdentity=identity,access=accessFor,key=hostingKey,inventory=providerInventory,providerRequest=hostingRequest}={}){const attempts=new Map();let ready;const init=()=>ready??=initializeHosting(db);return async request=>{const url=new URL(request.url);if(!url.pathname.startsWith('/api/hosting/'))return reply({message:'Not found'},404);const user=await getIdentity(request,db);if(!user)return reply({message:'Sign in first.'},401);if(!(await access(db,user)).nodes.includes('web.menu.security'))return reply({message:'Account services access required.'},403);const methods={'/api/hosting/providers':'GET','/api/hosting/connect':'POST','/api/hosting/disconnect':'POST','/api/hosting/domains':'GET','/api/hosting/servers':'GET','/api/hosting/dns':'GET'};if(!methods[url.pathname])return reply({message:'Not found'},404);if(request.method!==methods[url.pathname])return reply({message:'Method not allowed'},405);if(request.method==='POST'&&request.headers.get('Origin')!==origin)return reply({message:'Request origin rejected'},403);
|
|
try{await init();const get=async p=>{const row=await db.prepare('SELECT credentials,verified_at FROM site_hosting_connections WHERE user_id=? AND provider=?').bind(user.id,p).first();return row?openHosting(row.credentials,await key()):null;};
|
|
if(url.pathname==='/api/hosting/providers'){const{results}=await db.prepare('SELECT provider,verified_at FROM site_hosting_connections WHERE user_id=?').bind(user.id).all();return reply({connections:results.map(r=>({provider:r.provider,verifiedAt:r.verified_at})),available:providers});}
|
|
if(request.method==='POST'){let b;try{b=await request.json();}catch{return reply({message:'Send valid settings.'},400);}if(!providers.includes(b.provider))return reply({message:'Choose a supported provider.'},400);const now=Date.now();for(const[k,v]of attempts)if(v.until<now)attempts.delete(k);let a=attempts.get(user.id);if(!a){if(attempts.size>5000)return reply({message:'Try again shortly.'},429);a={count:0,until:now+900000};attempts.set(user.id,a);}if(++a.count>5)return reply({message:'Too many attempts. Try again in15minutes.'},429);if(typeof b.currentPassword!=='string'||b.currentPassword.length>256)return reply({message:'Confirm your website password.'},400);const account=await db.prepare('SELECT password_hash,password_salt FROM site_accounts WHERE id=?').bind(user.id).first();if(!/^[a-f0-9]{128}$/i.test(account?.password_hash||''))return reply({message:'Password verification unavailable.'},403);const hash=await scrypt(b.currentPassword,account.password_salt,64);if(!timingSafeEqual(hash,Buffer.from(account.password_hash,'hex')))return reply({message:'Incorrect website password.'},403);
|
|
if(url.pathname.endsWith('/disconnect')){await db.prepare('DELETE FROM site_hosting_connections WHERE user_id=? AND provider=?').bind(user.id,b.provider).run();return reply({ok:true});}
|
|
let c;try{c=validateHostingCredentials(b.provider,b.credentials);}catch(e){return reply({message:e.message},400);}const assets=await inventory(b.provider,c);await db.prepare('INSERT INTO site_hosting_connections(user_id,provider,credentials,verified_at) VALUES(?,?,?,?) ON CONFLICT(user_id,provider) DO UPDATE SET credentials=excluded.credentials,verified_at=excluded.verified_at').bind(user.id,b.provider,sealHosting(c,await key()),now).run();return reply({ok:true,assetCount:assets.length});}
|
|
if(url.pathname.endsWith('/domains')||url.pathname.endsWith('/dns')){const c=await get('godaddy');if(!c)return reply({connected:false,domains:[]});const domains=await inventory('godaddy',c);if(url.pathname.endsWith('/domains'))return reply({connected:true,domains});const domain=url.searchParams.get('domain');if(!domains.some(d=>d.domain===domain))return reply({message:'Domain is not in your connected account.'},403);const records=await providerRequest('godaddy',c,'/v1/domains/'+encodeURIComponent(domain)+'/records');if(!Array.isArray(records))throw Error();return reply({domain,records:records.map(r=>({type:r.type,name:r.name,data:r.data,ttl:r.ttl,priority:r.priority}))});}
|
|
const servers=[],connections=[];for(const p of ['hetzner-cloud','hetzner-robot']){const c=await get(p);if(!c)continue;connections.push(p);servers.push(...(await inventory(p,c)).map(r=>({...r,provider:p})));}return reply({connections,servers});
|
|
}catch(e){return reply({message:e.status===503?e.message:'Hosting information is temporarily unavailable.'},503);}};}
|

Staff