"use strict";
const $ = (s, el = document) => el.querySelector(s);
const $$ = (s, el = document) => [...el.querySelectorAll(s)];
const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
const usd = (n) => (n == null ? "-" : "$" + Number(n).toFixed(2));
const S = {
cat: null, apps: new Set(), cont: new Set(), comp: new Set(), prov: new Set(),
cities: new Set(), data: null, sort: { key: "total", dir: 1 },
override: {}, preset: null,
};
const COMP = [["hipaa", "HIPAA"], ["soc2", "SOC2"], ["pci", "PCI DSS"], ["gdpr", "GDPR"]];
const API = "/api/v1";
// Calls the Coremarket API with the browser session. The X-Coremarket header marks the request as
// coming from this page (the server rejects cookie-authenticated writes without it).
async function api(path, body, method) {
const r = await fetch(API + path, {
method: method || (body !== undefined ? "POST" : "GET"),
headers: { "Content-Type": "application/json", "X-Coremarket": "1" },
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (r.status === 401 && !path.startsWith("/auth/")) { // session expired
location.href = "/login?next=" + encodeURIComponent(location.pathname);
throw new Error("signed out");
}
if (!r.ok) {
let msg = (await r.text()).slice(0, 400);
try { const d = JSON.parse(msg).detail; msg = typeof d === "string" ? d : d.map((x) => x.msg).join("; "); } catch (_) {}
throw new Error(msg);
}
return r.json();
}
function chip(container, label, on, toggle, title = "") {
const c = document.createElement("span");
c.className = "chip" + (on ? " on" : "");
c.textContent = label;
c.title = title;
c.onclick = () => { toggle(); c.classList.toggle("on"); };
container.appendChild(c);
}
// ------------------------------------------------------------------ init
async function init() {
S.me = await api("/auth/me");
applyRole();
initAccountMenu();
S.cat = await api("/catalog");
$("#coreList").textContent = S.cat.core.join(", ");
renderLiveStatus();
const sel = $("#tierSelect");
sel.innerHTML = `Custom selection ` + Object.entries(S.cat.presets).map(([k, p]) =>
`${esc(p.label.replace(/^Federated /, ""))} · ${p.apps.length} apps${p.federated_price ? ` · $${p.federated_price}/mo` : ""} `).join("");
sel.onchange = () => {
S.preset = sel.value || null;
if (S.preset) S.apps = new Set(S.cat.presets[S.preset].apps);
renderApps(); requote();
};
$("#clearApps").onclick = () => { S.apps.clear(); setPreset(null); renderApps(); requote(); };
S.cat.continents.forEach((c) => chip($("#contFilter"), c, false, () => tog(S.cont, c)));
COMP.forEach(([k, l]) => chip($("#compFilter"), l, false, () => tog(S.comp, k)));
S.cat.providers.forEach((p) => chip($("#provFilter"), p.name.replace(/ \(.*\)/, ""), false, () => tog(S.prov, p.id)));
S.cat.cities.forEach((c) => chip($("#cityFilter"), c.name, S.cities.has(c.id), () => { tog(S.cities, c.id, false); render(); }));
$("#appSearch").oninput = renderApps;
$$("#concurrent,#named,#headroom,#growth,#extraDisk,#allowBurst,#dedicatedOnly,#allowArm,#allowPartial,#needSmtp")
.forEach((el) => (el.onchange = () => requote()));
$("#bestPerProvider").onchange = render;
$("#maxRtt").oninput = render;
$$(".tabs button[data-tab]").forEach((b) => (b.onclick = () => {
$$(".tabs button[data-tab]").forEach((x) => x.classList.toggle("active", x === b));
$$(".tab").forEach((t) => t.classList.toggle("hidden", t.id !== "tab-" + b.dataset.tab));
}));
$("#csvBtn").onclick = exportCsv;
$("#refreshBtn").onclick = refreshLive;
$("#editContaboBtn").onclick = () => openEditor("contabo");
S.apps = new Set(S.cat.presets.base.apps); setPreset("base");
renderApps();
renderNotes();
requote();
}
function setPreset(k) { S.preset = k; $("#tierSelect").value = k || ""; }
function tog(set, v, re = true) { set.has(v) ? set.delete(v) : set.add(v); if (re) requote(); }
function renderLiveStatus() {
const st = S.cat.live_status;
const live = S.cat.providers.filter((p) => p.price_source.startsWith("live")).map((p) => p.name.split(" ")[0]);
$("#liveStatus").textContent = live.length ? `Live prices: ${live.join(", ")}` : `Catalog prices as of ${S.cat.catalog_date}`;
$("#liveStatus").title = st ? Object.entries(st).map(([k, v]) => `${k}: ${v}`).join("\n") : "";
}
async function refreshLive() {
const b = $("#refreshBtn");
b.disabled = true; b.textContent = "Refreshing...";
try {
const r = await api("/prices/refresh", {});
S.cat = await api("/catalog");
renderLiveStatus(); renderNotes(); requote();
alert("Live price refresh:\n" + Object.entries(r.status).map(([k, v]) => `${k}: ${v}`).join("\n"));
} catch (e) { alert("Refresh failed: " + e.message); }
b.disabled = false; b.textContent = "Refresh live prices";
}
function renderApps() {
const q = $("#appSearch").value.toLowerCase();
const box = $("#appList");
box.innerHTML = "";
for (const cat of S.cat.categories) {
const apps = cat.apps.filter((a) => !q || a.name.toLowerCase().includes(q));
if (!apps.length) continue;
const d = document.createElement("details");
d.className = "cat";
const n = apps.filter((a) => S.apps.has(a.id)).length;
d.open = !!q || (cat.name !== "On Demand") ;
d.innerHTML = `${esc(cat.name)} ${n}/${apps.length} `;
for (const a of apps) {
const l = document.createElement("label");
l.className = "app";
l.innerHTML = `${esc(a.name)}${a.note ? `${esc(a.note)} ` : ""} `;
l.querySelector("input").onchange = (e) => { e.target.checked ? S.apps.add(a.id) : S.apps.delete(a.id); setPreset(null); requote(); };
d.appendChild(l);
}
box.appendChild(d);
}
}
// ------------------------------------------------------------------ quote
let qTimer;
function requote() { clearTimeout(qTimer); qTimer = setTimeout(doQuote, 150); }
async function doQuote() {
const body = {
apps: [...S.apps],
concurrent: +$("#concurrent").value || 5,
named: +$("#named").value || 10,
headroom: (+$("#headroom").value || 0) / 100,
disk_growth: (+$("#growth").value || 0) / 100,
extra_disk_gb: +$("#extraDisk").value || 0,
allow_burstable: $("#allowBurst").checked,
dedicated_only: $("#dedicatedOnly").checked,
allow_arm: $("#allowArm").checked,
allow_partial_compliance: $("#allowPartial").checked,
require_smtp: $("#needSmtp").checked,
continents: [...S.cont], compliance: [...S.comp], providers: [...S.prov],
override: S.override,
};
try { S.data = await api("/quote", body); } catch (e) { $("#sizing").textContent = "Error: " + e.message; return; }
renderSizing();
render();
}
function renderSizing() {
const { sizing, need } = S.data;
const preset = S.preset && S.cat.presets[S.preset];
const ovr = (k, v) => ` `;
$("#sizing").innerHTML = `
vCPU${need.vcpu} ${ovr("vcpu", sizing.need.vcpu)}
RAM GB${need.ram_gb} ${ovr("ram_gb", sizing.need.ram_gb)}
Disk GB${need.disk_gb} ${ovr("disk_gb", sizing.need.disk_gb)}
Raw demand ${sizing.raw.cpu} vCPU / ${sizing.raw.ram_gb} GB / ${sizing.raw.disk_gb} GB, plus headroom and growth.
Shape: ${esc(sizing.family)} . Nearest standard size: ${sizing.standard.vcpu} vCPU / ${sizing.standard.ram_gb} GB.
${preset && preset.federated_price ? `
Compare: ${esc(preset.label)} hosted by Federated is $${preset.federated_price}/mo (${preset.storage_gb ? `${preset.storage_gb} GB storage, ` : ""}managed, backups included).
` : ""}
${sizing.needs_smtp ? `
The email server needs outbound TCP 25. Check the SMTP column: "blocked" clouds need an external relay (e.g. SES, Postmark, Mailgun).
` : ""}
Component RAM MB vCPU Disk GB
${sizing.lines.map((l) => `${esc(l.name)} ${l.kind === "core" ? 'core ' : l.kind === "shared" ? 'shared ' : ""}
${Math.round(l.ram_mb)} ${l.cpu.toFixed(2)} ${l.disk_gb.toFixed(1)} `).join("")}
${sizing.notes.length ? `
Sizing notes (${sizing.notes.length}) ${sizing.notes.map((n) => `${esc(n)} `).join("")} ` : ""}
`;
$$(".ovr").forEach((el) => (el.onchange = () => {
const v = +el.value; v ? (S.override[el.dataset.k] = v) : delete S.override[el.dataset.k]; requote();
}));
}
// ------------------------------------------------------------------ render
function latStats(r) {
const ids = [...S.cities];
if (!ids.length) return { avg: null, max: null };
const v = ids.map((id) => r.latency[id]);
return { avg: Math.round(v.reduce((a, b) => a + b, 0) / v.length), max: Math.max(...v) };
}
function filtered() {
if (!S.data) return [];
const max = +$("#maxRtt").value;
return S.data.results.map((r) => ({ ...r, ...latStats(r) })).filter((r) => !max || r.max == null || r.max <= max);
}
function sorted(rows) {
const { key, dir } = S.sort;
return [...rows].sort((a, b) => ((a[key] > b[key]) - (a[key] < b[key])) * dir || a.total - b.total);
}
const badges = (c) => COMP.map(([k, l]) => `${l.split(" ")[0]} `).join("");
const latColor = (ms) => `hsl(${Math.max(0, 130 - ms * 0.6)}, 60%, 45%)`;
const COLS = [
["provider", "Provider"], ["location", "Location"], ["region", "Region code"], ["model", "VM model"],
["vcpu", "vCPU", 1], ["ram_gb", "RAM GB", 1], ["disk_gb", "Disk GB", 1], ["base_price", "VM $/mo", 1],
["extra_storage_cost", "+Storage $/mo", 1], ["ipv4", "IPv4 $/mo", 1], ["recurring", "Monthly $/mo", 1], ["setup_fee", "Setup $ (one-time)", 1],
["total", "Total $ (1st month)", 1],
["storage_price_gb", "Add'l storage $/GB-mo", 1], ["compliance", "Compliance"], ["smtp25", "SMTP 25"],
["avg", "RTT avg ms", 1], ["max", "RTT worst ms", 1],
];
function table(rows) {
const head = COLS.map(([k, l, n]) => `${l}${S.sort.key === k ? (S.sort.dir > 0 ? " ▲" : " ▼") : ""} `).join("");
const body = rows.map((r, i) => `
${esc(r.provider)} ${esc(r.location)}, ${esc(r.country)} ${esc(r.region)}
${esc(r.model)} ${r.cpu_type === "dedicated" ? "ded" : r.cpu_type === "burstable" ? "burst" : ""}${r.arch !== "x86_64" ? " arm" : ""}
${r.vcpu} ${r.ram_gb}
${r.disk_gb || "-"}${r.extra_storage_gb ? ` +${r.extra_storage_gb} ` : ""}
${usd(r.base_price)} ${r.extra_storage_cost ? usd(r.extra_storage_cost) : "-"}
${r.ipv4 ? usd(r.ipv4) : "-"}
${usd(r.recurring)} ${r.setup_fee ? usd(r.setup_fee) : "-"}
${usd(r.total)}${r.price_confidence === "low" ? "*" : ""}
${r.storage_price_gb != null ? "$" + r.storage_price_gb.toFixed(3) : `n/a `}
${badges(r.compliance)} ${esc(r.smtp25)}
${r.avg ?? "-"} ${r.max ?? "-"}
`).join("");
return ``;
}
function wire(container, rows) {
$$("th[data-k]", container).forEach((th) => (th.onclick = () => {
const k = th.dataset.k;
S.sort = { key: k, dir: S.sort.key === k ? -S.sort.dir : 1 };
render();
}));
$$("tr.row", container).forEach((tr) => (tr.onclick = () => showDetail(rows[+tr.dataset.i])));
}
function render() {
const rows = filtered();
$("#count").textContent = `${rows.length} region options`;
// by region
const br = $("#tab-byregion");
br.innerHTML = "";
const onlyBest = $("#bestPerProvider").checked;
for (const cont of S.cat.continents) {
let rs = sorted(rows.filter((r) => r.continent === cont));
if (onlyBest) {
const seen = new Set();
rs = [...rs].sort((a, b) => a.total - b.total).filter((r) => !seen.has(r.provider_id) && seen.add(r.provider_id));
rs = sorted(rs);
}
const sec = document.createElement("div");
sec.innerHTML = `${esc(cont)} ${rs.length ? `from ${usd(Math.min(...rs.map((r) => r.total)))} first month` : "no matching options"} ${rs.length ? table(rs) : ""}`;
br.appendChild(sec);
wire(sec, rs);
}
if (S.cat.continents.includes("Asia")) {
br.insertAdjacentHTML("beforeend", `Asia includes the Middle East (Israel, UAE). * = low price confidence (estimate, verify with provider).
`);
}
// all
const all = sorted(rows);
$("#tab-all").innerHTML = table(all);
wire($("#tab-all"), all);
// matrix
const top = sorted(rows).slice(0, 120);
const cities = S.cat.cities;
$("#tab-matrix").innerHTML = `Estimated round-trip time (ms) from each VM region to each city. Model: great-circle distance x 1.3 route factor at 204 km/ms in fibre + 3 ms, plus per-market penalties and +35 ms across the mainland-China border. Use the detail view to measure real RTT for regions with a probe endpoint. Showing ${top.length} rows in current sort order.
Provider Location $/mo ${cities.map((c) => `${esc(c.name)} `).join("")}
${top.map((r, i) => `${esc(r.provider.split(" (")[0])} ${esc(r.location)} ${usd(r.total)}
${cities.map((c) => { const v = r.latency[c.id]; return `${v} `; }).join("")} `).join("")}
`;
$$("tr.row", $("#tab-matrix")).forEach((tr) => (tr.onclick = () => showDetail(top[+tr.dataset.i])));
}
// ------------------------------------------------------------------ detail
function showDetail(r) {
const p = S.cat.providers.find((x) => x.id === r.provider_id);
const cities = S.cat.cities;
$("#detailBody").innerHTML = `
${esc(r.provider)}: ${esc(r.location)}, ${esc(r.country)} (${esc(r.region)})
${esc(r.model)} | ${r.vcpu} vCPU (${esc(r.cpu_type)}, ${esc(r.arch)}) | ${r.ram_gb} GB RAM | ${r.disk_gb || 0} GB included disk
${r.extra_storage_gb ? `+ ${r.extra_storage_gb} GB ${esc(r.storage_name)}` : ""}
VM ${usd(r.base_price)} + storage ${usd(r.extra_storage_cost)} + IPv4 ${usd(r.ipv4)} = ${usd(r.recurring)}/month
${r.setup_fee ? ` + ${usd(r.setup_fee)} one-time setup = ${usd(r.total)} first month ` : ""}
(${(r.recurring * 12 + r.setup_fee).toFixed(0)} USD first year; price source: ${esc(r.price_source)}, confidence ${esc(r.price_confidence)})
Additional storage: ${r.storage_price_gb != null ? `$${r.storage_price_gb.toFixed(3)}/GB-month (${esc(r.storage_name)})` : esc(r.storage_name)}.
Egress: ${esc(r.egress.note || (r.egress.per_gb != null ? `$${r.egress.per_gb}/GB after ${r.egress.included_gb ?? 0} GB` : "-"))}. SMTP port 25: ${esc(r.smtp25)}.
${badges(r.compliance)} ${esc(p.compliance_note)}
${r.alternatives.length ? `Next-best plans in this region Model vCPU RAM Disk Total $ (1st month)
${r.alternatives.map((a) => `${esc(a.model)} ${esc(a.cpu_type)} ${a.vcpu} ${a.ram_gb} ${a.disk_gb}${a.extra_storage_gb ? "+" + a.extra_storage_gb : ""} ${usd(a.total)} `).join("")}
` : ""}
Latency to all cities (estimated RTT ms)
${r.ping_host ? `Real measurement uses Globalping community probes (TCP ping to ${esc(r.ping_host)}). Free tier is rate-limited.
` : `No public probe endpoint is configured for this region, so only estimates are shown.
`}
City Est. RTT ${r.ping_host ? "Measured " : ""}
${cities.map((c) => `${esc(c.name)}, ${esc(c.country)} ${r.latency[c.id]}
${r.ping_host ? `measure ` : ""} `).join("")}
`;
$$(".meas", $("#detailBody")).forEach((b) => (b.onclick = async () => {
const out = $("#m-" + b.dataset.c);
b.disabled = true; out.textContent = "measuring...";
try {
const m = await api("/latency/measure", { host: r.ping_host, city: b.dataset.c });
out.innerHTML = `${m.min_ms} ms ${m.probe_scope === "country" ? ' (no probe in this city; country-level) ' : ""} ${m.results.map((x) => esc(x.probe) + ": " + x.avg_ms).join("; ")} `;
} catch (e) { out.textContent = "failed: " + e.message.slice(0, 120); }
b.disabled = false;
}));
$("#detail").showModal();
}
// ------------------------------------------------------------------ notes
function renderNotes() {
const ps = S.cat.providers;
$("#tab-notes").innerHTML = `
Methodology
Sizing : each app has an idle footprint plus per-concurrent-user RAM/CPU and per-named-user disk. Shared databases (PostgreSQL, MariaDB, Redis, etc.) are counted once. OS + Docker reserve 1 GB RAM and 30 GB disk (Federated reserves 30 GB). Headroom and growth are then applied, and the minimum is 2 vCPU / 2 GB / 40 GB.
Matching : in every region, the cheapest plan with at least the required vCPU and RAM wins. If its bundled disk is too small, block storage is added at that provider's rate. Providers without block storage must fit the disk in the plan. Public IPv4 charges are included in the total.
Prices : USD per month, on-demand. "Total (1st month)" adds any one-time setup fee (currently Contabo only) to the monthly cost, Linux, before tax/VAT, no commitment discounts (1-3 year reservations typically save 30-60% on AWS/Azure/GCP/OCI). Live API pricing is used where available (${ps.filter((p) => p.live).map((p) => esc(p.name)).join(", ")}). Otherwise the catalog is dated ${esc(S.cat.catalog_date)}. ${esc(S.cat.fx_note)}
Latency : modelled from geography (see Latency matrix tab). Real routes vary by ISP. Use "measure" in the detail view for live probes.
Compliance : provider-level attestations for IaaS compute. "yes" = attested, with a BAA available for HIPAA. "partial" = only some products/regions, or self-declared. You remain responsible for your own controls, and HIPAA requires a signed BAA.
Providers: API documentation and references
Provider API docs Pricing API Pricing page Compliance Price source Add'l storage IPv4 Egress SMTP 25
${ps.map((p) => `
${esc(p.name)} ${p.region_count} regions
API reference ${p.api_docs_note ? `${esc(p.api_docs_note)} ` : ""}
${p.pricing_api ? `pricing API ` : 'none public '}
pricing
${badges(p.compliance)}compliance page
${esc(p.price_source)}confidence: ${p.price_confidence} ${p.manual && isAdmin() ? `Edit prices ` : ""}
${p.setup_fee ? `Setup fee ${usd(p.setup_fee.usd)} : ${esc(p.setup_fee.note)} ` : ""}${p.storage.price_gb != null ? `$${p.storage.price_gb}/GB-mo` : ""} ${esc(p.storage.name)}
${p.ipv4_monthly ? usd(p.ipv4_monthly) : "incl."}
${esc(p.egress.note || (p.egress.per_gb != null ? `$${p.egress.per_gb}/GB (${p.egress.included_gb ?? 0} GB free)` : ""))}
${esc(p.smtp25)}
${esc(p.compliance_note)} `).join("")}
`;
$$(".edit-manual").forEach((b) => (b.onclick = () => openEditor(b.dataset.p)));
}
// ------------------------------------------------------------------ manual price editor
const num = (v) => { const m = String(v ?? "").replace(/,/g, ".").match(/-?\d+(\.\d+)?/); return m ? +m[0] : NaN; };
function parsePastedTable(text) {
// Accepts markdown/pipe, tab or CSV tables with a header row naming the columns.
const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !/^\|?\s*:?-{2,}/.test(l));
const split = (l) => (l.includes("|") ? l.replace(/^\|/, "").replace(/\|$/, "").split("|") : l.includes("\t") ? l.split("\t") : l.split(",")).map((c) => c.trim());
const hi = lines.findIndex((l) => /vcpu|cpu|core/i.test(l) && /ram|memory/i.test(l));
if (hi < 0) throw new Error("No header row with vCPU and RAM columns found.");
const hdr = split(lines[hi]).map((h) => h.toLowerCase());
const col = (re) => hdr.findIndex((h) => re.test(h));
const c = { code: col(/code|id|sku/), name: col(/name|plan|product/), vcpu: col(/vcpu|cpu|core/), ram: col(/ram|memory/),
disk: col(/storage|disk|ssd|nvme/), price: col(/price|€|\$|cost|month/), speed: col(/speed|port|bandwidth|network/) };
if (c.price < 0) throw new Error("No price column found.");
const plans = [];
for (const l of lines.slice(hi + 1)) {
const r = split(l);
const p = { code: c.code >= 0 ? r[c.code] : "", name: c.name >= 0 ? r[c.name] : "", vcpu: num(r[c.vcpu]), ram_gb: num(r[c.ram]),
disk_gb: c.disk >= 0 ? num(r[c.disk]) : 0, price: num(r[c.price]), cpu_type: "shared",
note: [c.disk >= 0 && /ssd|nvme/i.test(r[c.disk]) ? (r[c.disk].match(/ssd|nvme/i) || [""])[0].toUpperCase() : "", c.speed >= 0 ? r[c.speed] : ""].filter(Boolean).join(", ") };
if (!p.name) p.name = p.code || `Plan ${plans.length + 1}`;
if ([p.vcpu, p.ram_gb, p.price].some(isNaN)) continue;
plans.push(p);
}
if (!plans.length) throw new Error("No plan rows could be parsed.");
const cur = /€|eur/i.test(text) ? "EUR" : /\$|usd/i.test(text) ? "USD" : null;
return { plans, currency: cur };
}
async function openEditor(pid) {
const d = await api(`/providers/${pid}/price-sheet`);
const sh = d.sheet;
const body = $("#editorBody");
const planRow = (p = {}) => `
shared dedicated
✕ `;
body.innerHTML = `
Edit ${esc(d.provider)} prices
${d.is_default ? "Showing the built-in price sheet." : `Saved sheet, last updated ${esc(sh.updated_at)}.`}
Prices are per month before VAT. Saved changes apply to all quotes immediately.
Currency EUR USD
USD per 1 EUR
Setup fee (one-time, sheet currency)
Setup fee note
Plans
Code Name vCPU RAM GB Disk GB Price/mo CPU Note
${sh.plans.map(planRow).join("")}
+ Add plan
Paste a table (markdown, tab-separated or CSV, with a header row; replaces the plans above)
Load pasted table
Location surcharge per region (%)
Added to every plan price in that region. 0 = same price as the sheet.
Save prices Cancel
Reset to built-in
`;
const wireDel = () => $$(".del", body).forEach((b) => (b.onclick = () => b.closest("tr").remove()));
wireDel();
$("#edAdd").onclick = () => { $("#edPlans tbody").insertAdjacentHTML("beforeend", planRow()); wireDel(); };
$("#edParse").onclick = () => {
try {
const { plans, currency } = parsePastedTable($("#edPaste").value);
$("#edPlans tbody").innerHTML = plans.map(planRow).join(""); wireDel();
if (currency) $("#edCur").value = currency;
$("#edParseMsg").textContent = `Loaded ${plans.length} plans${currency ? ` (${currency})` : ""}. Review, then Save.`;
} catch (e) { $("#edParseMsg").textContent = e.message; }
};
$("#edCancel").onclick = () => $("#editor").close();
$("#edReset").onclick = async () => {
if (!confirm("Discard saved Contabo prices and go back to the built-in sheet?")) return;
try { await api(`/providers/${pid}/price-sheet`, undefined, "DELETE"); } catch (e) { alert("Not reset: " + e.message); return; }
$("#editor").close(); await afterPriceChange();
};
$("#edSave").onclick = async () => {
const plans = $$("#edPlans tbody tr").map((tr) => {
const o = {};
$$("[data-f]", tr).forEach((el) => { const f = el.dataset.f; o[f] = ["vcpu", "ram_gb", "disk_gb", "price"].includes(f) ? num(el.value) : el.value.trim(); });
return o;
});
const bad = plans.findIndex((p) => !p.name || [p.vcpu, p.ram_gb, p.price].some(isNaN));
if (bad >= 0) { $("#edErr").textContent = `Plan row ${bad + 1}: name, vCPU, RAM and price are required.`; return; }
plans.forEach((p) => { if (isNaN(p.disk_gb)) p.disk_gb = 0; });
const pct = {}; $$(".edPct", body).forEach((el) => (pct[el.dataset.r] = num(el.value) || 0));
const sheet = { currency: $("#edCur").value, fx: num($("#edFx").value), setup_fee: num($("#edSetup").value) || 0,
setup_fee_note: $("#edSetupNote").value.trim(), plans, region_surcharge_pct: pct };
try { await api(`/providers/${pid}/price-sheet`, sheet, "PUT"); }
catch (e) { $("#edErr").textContent = "Not saved: " + e.message; return; }
$("#editor").close(); await afterPriceChange();
};
$("#editor").showModal();
}
async function afterPriceChange() {
S.cat = await api("/catalog");
renderLiveStatus(); renderNotes(); requote();
}
// ------------------------------------------------------------------ accounts
const isAdmin = () => S.me?.role === "admin";
const when = (t) => (t ? new Date(t * 1000).toLocaleString() : "never");
function applyRole() {
$$(".admin-only").forEach((el) => el.classList.toggle("hidden", !isAdmin()));
$("#userBtn").textContent = `${S.me.username} ▾`;
$("#userInfo").textContent = `Signed in as ${S.me.username} (${S.me.role})`;
}
function initAccountMenu() {
const btn = $("#userBtn"), menu = $("#userMenu");
const close = () => { menu.classList.add("hidden"); btn.setAttribute("aria-expanded", "false"); };
btn.onclick = (e) => { e.stopPropagation(); menu.classList.toggle("hidden"); btn.setAttribute("aria-expanded", String(!menu.classList.contains("hidden"))); };
document.addEventListener("click", close);
document.addEventListener("keydown", (e) => e.key === "Escape" && close());
$$("#userMenu [data-act]").forEach((b) => (b.onclick = async () => {
close();
const act = b.dataset.act;
if (act === "keys") openKeys();
else if (act === "users") openUsers();
else if (act === "password") openPassword();
else if (act === "docs") window.open("/docs", "_blank", "noopener");
else if (act === "logout") { try { await api("/auth/logout", {}); } catch (_) {} location.href = "/login"; }
}));
}
function accountDialog(html) {
$("#accountBody").innerHTML = html;
if (!$("#account").open) $("#account").showModal();
return $("#accountBody");
}
async function openKeys(showAll = false, fresh = null) {
let keys, users = [];
try {
keys = await api(showAll ? "/keys?all=true" : "/keys");
if (isAdmin()) users = await api("/users");
} catch (e) { alert(e.message); return; }
const body = accountDialog(`
API keys
Send a key in the X-API-Key header (or Authorization: Bearer). A key acts with its
owner's role${isAdmin() ? "" : " (yours: user)"}. Keys are shown once, when created. Store them somewhere safe.
${fresh ? `New key "${esc(fresh.name)}"${fresh.username ? ` for ${esc(fresh.username)}` : ""}: copy it now, it won't be shown again.
${esc(fresh.key)}
Copy ` : ""}
Create a key
Name
Expires after (days)
${isAdmin() ? `For account ${users.map((u) => `${esc(u.username)} (${u.role}) `).join("")} ` : ""}
Create key
${showAll ? "All keys" : "Your keys"} ${isAdmin() ? ` show every account's keys ` : ""}
${keys.length ? `Name Key ${showAll ? "Account " : ""}Created Expires Last used
${keys.map((k) => `${esc(k.name)} ${esc(k.prefix)} ${showAll ? `${esc(k.username)} ` : ""}
${when(k.created_at)} ${k.expires_at ? when(k.expires_at) + (k.expired ? ' expired ' : "") : "never"}
${when(k.last_used)} Revoke `).join("")}
` : 'No keys yet.
'}`);
$("#copyKey")?.addEventListener("click", async () => {
try { await navigator.clipboard.writeText(fresh.key); $("#copyMsg").textContent = "Copied."; }
catch (_) { $("#copyMsg").textContent = "Select the key and copy it manually."; }
});
$("#kAll")?.addEventListener("change", (e) => openKeys(e.target.checked, fresh));
$("#kCreate").onclick = async () => {
const req = { name: $("#kName").value.trim() || "API key" };
const days = +$("#kDays").value; if (days) req.expires_days = days;
if (isAdmin()) req.user_id = +$("#kUser").value;
try { const k = await api("/keys", req); openKeys(showAll, k); }
catch (e) { $("#kErr").textContent = e.message; }
};
$$(".revoke", body).forEach((b) => (b.onclick = async () => {
if (!confirm(`Revoke API key "${b.dataset.name}"? Anything using it will stop working immediately.`)) return;
try { await api(`/keys/${b.dataset.id}`, undefined, "DELETE"); openKeys(showAll); } catch (e) { alert(e.message); }
}));
}
async function openUsers(note = "") {
let users;
try { users = await api("/users"); } catch (e) { alert(e.message); return; }
const body = accountDialog(`
Users
Admins manage accounts, all API keys and prices. Users can use Coremarket and manage their own API keys.
Disabled accounts can't sign in and their API keys stop working.
Create an account
Username
Password (min 10)
Role user admin
Create account
${esc(note)}
Username Role Status API keys Last sign-in Created
${users.map((u) => {
const me = u.id === S.me.id;
return `
${esc(u.username)}${me ? ' you ' : ""}
${me ? u.role : `user admin `}
${u.disabled ? 'disabled ' : "active"}
${u.api_keys} ${when(u.last_login)} ${when(u.created_at)}
${me ? "" : `${u.disabled ? "Enable" : "Disable"}
Reset password Delete `} `;
}).join("")}
`);
const act = async (fn, okMsg) => { try { await fn(); openUsers(okMsg); } catch (e) { openUsers("Error: " + e.message); } };
$("#uCreate").onclick = () => act(() => api("/users", { username: $("#uName").value.trim(), password: $("#uPass").value, role: $("#uRole").value }),
`Created account "${$("#uName").value.trim()}".`);
$$("tr[data-id]", body).forEach((tr) => {
const id = tr.dataset.id, name = tr.dataset.name;
tr.querySelector(".uRoleSel")?.addEventListener("change", (e) => act(() => api(`/users/${id}`, { role: e.target.value }, "PATCH"), `${name} is now ${e.target.value}.`));
tr.querySelector(".uToggle")?.addEventListener("click", (e) => {
const dis = e.target.textContent === "Disable";
act(() => api(`/users/${id}`, { disabled: dis }, "PATCH"), `${name} ${dis ? "disabled" : "enabled"}.`);
});
tr.querySelector(".uReset")?.addEventListener("click", () => {
const pw = prompt(`New password for ${name} (min 10 characters). They will be signed out everywhere:`);
if (pw) act(() => api(`/users/${id}`, { password: pw }, "PATCH"), `Password for ${name} reset.`);
});
tr.querySelector(".uDelete")?.addEventListener("click", () => {
if (confirm(`Delete account "${name}" and all its API keys? This cannot be undone.`))
act(() => api(`/users/${id}`, undefined, "DELETE"), `Deleted ${name}.`);
});
});
}
function openPassword() {
accountDialog(`
Change password
Your other signed-in sessions will be signed out. API keys keep working.
Current password
New password (min 10)
Repeat new password
Change password
`);
$("#pSave").onclick = async () => {
const msg = $("#pMsg");
if ($("#pNew").value !== $("#pNew2").value) { msg.className = "small err"; msg.textContent = "The new passwords don't match."; return; }
try {
await api("/auth/password", { current_password: $("#pCur").value, new_password: $("#pNew").value });
msg.className = "small ok"; msg.textContent = "Password changed.";
$$("#accountBody input").forEach((i) => (i.value = ""));
} catch (e) { msg.className = "small err"; msg.textContent = e.message; }
};
}
// ------------------------------------------------------------------ csv
function exportCsv() {
const rows = sorted(filtered());
const cities = S.cat.cities;
const hdr = ["provider", "region", "location", "country", "continent", "model", "vcpu", "ram_gb", "disk_gb", "cpu_type", "arch",
"vm_usd_mo", "extra_storage_gb", "extra_storage_usd_mo", "ipv4_usd_mo", "monthly_usd", "setup_fee_usd", "total_first_month_usd", "addl_storage_usd_gb_mo",
"hipaa", "soc2", "pci_dss", "gdpr", "smtp25", "price_source", "price_confidence", ...cities.map((c) => "rtt_ms_" + c.name)];
const q = (v) => `"${String(v ?? "").replace(/"/g, '""')}"`;
const lines = [hdr.map(q).join(",")].concat(rows.map((r) => [r.provider, r.region, r.location, r.country, r.continent, r.model,
r.vcpu, r.ram_gb, r.disk_gb, r.cpu_type, r.arch, r.base_price, r.extra_storage_gb, r.extra_storage_cost, r.ipv4, r.recurring, r.setup_fee, r.total,
r.storage_price_gb, r.compliance.hipaa, r.compliance.soc2, r.compliance.pci, r.compliance.gdpr, r.smtp25, r.price_source,
r.price_confidence, ...cities.map((c) => r.latency[c.id])].map(q).join(",")));
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([lines.join("\n")], { type: "text/csv" }));
a.download = `coremarket-${new Date().toISOString().slice(0, 10)}.csv`;
a.click();
}
init();