|
|
|
@@ -0,0 +1,621 @@
|
|
|
|
|
"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(["nyc", "chi", "lax", "dfw"]), 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 = `<option value="">Custom selection</option>` + Object.entries(S.cat.presets).map(([k, p]) =>
|
|
|
|
|
`<option value="${esc(k)}" title="${esc(p.label)}">${esc(p.label.replace(/^Federated /, ""))} · ${p.apps.length} apps${p.federated_price ? ` · $${p.federated_price}/mo` : ""}</option>`).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.good.apps); setPreset("good");
|
|
|
|
|
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 = `<summary>${esc(cat.name)} <span class="muted small">${n}/${apps.length}</span></summary>`;
|
|
|
|
|
for (const a of apps) {
|
|
|
|
|
const l = document.createElement("label");
|
|
|
|
|
l.className = "app";
|
|
|
|
|
l.innerHTML = `<input type="checkbox" ${S.apps.has(a.id) ? "checked" : ""}><span>${esc(a.name)}${a.note ? `<small>${esc(a.note)}</small>` : ""}</span>`;
|
|
|
|
|
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) => `<input class="ovr" data-k="${k}" type="number" min="1" placeholder="${v}" value="${S.override[k] ?? ""}" title="Override">`;
|
|
|
|
|
$("#sizing").innerHTML = `
|
|
|
|
|
<div>
|
|
|
|
|
<div class="spec">
|
|
|
|
|
<div>vCPU<b>${need.vcpu}</b>${ovr("vcpu", sizing.need.vcpu)}</div>
|
|
|
|
|
<div>RAM GB<b>${need.ram_gb}</b>${ovr("ram_gb", sizing.need.ram_gb)}</div>
|
|
|
|
|
<div>Disk GB<b>${need.disk_gb}</b>${ovr("disk_gb", sizing.need.disk_gb)}</div>
|
|
|
|
|
</div>
|
|
|
|
|
<p class="small">Raw demand ${sizing.raw.cpu} vCPU / ${sizing.raw.ram_gb} GB / ${sizing.raw.disk_gb} GB, plus headroom and growth.<br>
|
|
|
|
|
Shape: <b>${esc(sizing.family)}</b>. Nearest standard size: ${sizing.standard.vcpu} vCPU / ${sizing.standard.ram_gb} GB.</p>
|
|
|
|
|
${preset && preset.federated_price ? `<p class="cmp">Compare: <b>${esc(preset.label)}</b> hosted by Federated is <b>$${preset.federated_price}/mo</b> (${preset.storage_gb ? `${preset.storage_gb} GB storage, ` : ""}managed, backups included).</p>` : ""}
|
|
|
|
|
${sizing.needs_smtp ? `<div class="warn small">The email server needs outbound TCP 25. Check the SMTP column: "blocked" clouds need an external relay (e.g. SES, Postmark, Mailgun).</div>` : ""}
|
|
|
|
|
</div>
|
|
|
|
|
<div class="breakdown">
|
|
|
|
|
<table><thead><tr><th>Component</th><th class="num">RAM MB</th><th class="num">vCPU</th><th class="num">Disk GB</th></tr></thead><tbody>
|
|
|
|
|
${sizing.lines.map((l) => `<tr><td>${esc(l.name)} ${l.kind === "core" ? '<span class="muted small">core</span>' : l.kind === "shared" ? '<span class="muted small">shared</span>' : ""}</td>
|
|
|
|
|
<td class="num">${Math.round(l.ram_mb)}</td><td class="num">${l.cpu.toFixed(2)}</td><td class="num">${l.disk_gb.toFixed(1)}</td></tr>`).join("")}
|
|
|
|
|
</tbody></table>
|
|
|
|
|
${sizing.notes.length ? `<details class="small"><summary>Sizing notes (${sizing.notes.length})</summary><ul>${sizing.notes.map((n) => `<li>${esc(n)}</li>`).join("")}</ul></details>` : ""}
|
|
|
|
|
</div>`;
|
|
|
|
|
$$(".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]) => `<span class="badge ${c[k]}" title="${l}: ${c[k]}">${l.split(" ")[0]}</span>`).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]) => `<th class="${n ? "num" : ""}" data-k="${k}">${l}${S.sort.key === k ? (S.sort.dir > 0 ? " ▲" : " ▼") : ""}</th>`).join("");
|
|
|
|
|
const body = rows.map((r, i) => `<tr class="row" data-i="${i}">
|
|
|
|
|
<td>${esc(r.provider)}</td><td>${esc(r.location)}, ${esc(r.country)}</td><td class="muted">${esc(r.region)}</td>
|
|
|
|
|
<td title="${esc(r.cpu_type)} ${esc(r.arch)} ${esc(r.plan_note)}">${esc(r.model)} <span class="muted small">${r.cpu_type === "dedicated" ? "ded" : r.cpu_type === "burstable" ? "burst" : ""}${r.arch !== "x86_64" ? " arm" : ""}</span></td>
|
|
|
|
|
<td class="num">${r.vcpu}</td><td class="num">${r.ram_gb}</td>
|
|
|
|
|
<td class="num">${r.disk_gb || "-"}${r.extra_storage_gb ? `<span class="muted"> +${r.extra_storage_gb}</span>` : ""}</td>
|
|
|
|
|
<td class="num">${usd(r.base_price)}</td><td class="num">${r.extra_storage_cost ? usd(r.extra_storage_cost) : "-"}</td>
|
|
|
|
|
<td class="num">${r.ipv4 ? usd(r.ipv4) : "-"}</td>
|
|
|
|
|
<td class="num">${usd(r.recurring)}</td><td class="num">${r.setup_fee ? usd(r.setup_fee) : "-"}</td>
|
|
|
|
|
<td class="num total ${"conf-" + r.price_confidence}" title="Price confidence: ${r.price_confidence}; source: ${esc(r.price_source)}">${usd(r.total)}${r.price_confidence === "low" ? "*" : ""}</td>
|
|
|
|
|
<td class="num">${r.storage_price_gb != null ? "$" + r.storage_price_gb.toFixed(3) : `<span class="muted" title="${esc(r.storage_name)}">n/a</span>`}</td>
|
|
|
|
|
<td>${badges(r.compliance)}</td><td>${esc(r.smtp25)}</td>
|
|
|
|
|
<td class="lat">${r.avg ?? "-"}</td><td class="lat" style="color:${r.max != null ? latColor(r.max) : ""}">${r.max ?? "-"}</td>
|
|
|
|
|
</tr>`).join("");
|
|
|
|
|
return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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 = `<h3>${esc(cont)} <span class="muted small">${rs.length ? `from ${usd(Math.min(...rs.map((r) => r.total)))} first month` : "no matching options"}</span></h3>${rs.length ? table(rs) : ""}`;
|
|
|
|
|
br.appendChild(sec);
|
|
|
|
|
wire(sec, rs);
|
|
|
|
|
}
|
|
|
|
|
if (S.cat.continents.includes("Asia")) {
|
|
|
|
|
br.insertAdjacentHTML("beforeend", `<p class="muted small">Asia includes the Middle East (Israel, UAE). * = low price confidence (estimate, verify with provider).</p>`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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 = `<p class="muted small">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.</p>
|
|
|
|
|
<table class="matrix"><thead><tr><th>Provider</th><th>Location</th><th class="num">$/mo</th>${cities.map((c) => `<th class="city">${esc(c.name)}</th>`).join("")}</tr></thead><tbody>
|
|
|
|
|
${top.map((r, i) => `<tr class="row" data-i="${i}"><td>${esc(r.provider.split(" (")[0])}</td><td>${esc(r.location)}</td><td class="num">${usd(r.total)}</td>
|
|
|
|
|
${cities.map((c) => { const v = r.latency[c.id]; return `<td class="lat" style="background:${latColor(v)};color:#fff">${v}</td>`; }).join("")}</tr>`).join("")}
|
|
|
|
|
</tbody></table>`;
|
|
|
|
|
$$("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 = `
|
|
|
|
|
<h2>${esc(r.provider)}: ${esc(r.location)}, ${esc(r.country)} <span class="muted">(${esc(r.region)})</span></h2>
|
|
|
|
|
<p><b>${esc(r.model)}</b> | ${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)}` : ""}<br>
|
|
|
|
|
VM ${usd(r.base_price)} + storage ${usd(r.extra_storage_cost)} + IPv4 ${usd(r.ipv4)} = <b>${usd(r.recurring)}/month</b>
|
|
|
|
|
${r.setup_fee ? ` + ${usd(r.setup_fee)} one-time setup = <b>${usd(r.total)} first month</b>` : ""}
|
|
|
|
|
<span class="muted">(${(r.recurring * 12 + r.setup_fee).toFixed(0)} USD first year; price source: ${esc(r.price_source)}, confidence ${esc(r.price_confidence)})</span></p>
|
|
|
|
|
<p>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)}.</p>
|
|
|
|
|
<p>${badges(r.compliance)} <span class="small">${esc(p.compliance_note)}</span></p>
|
|
|
|
|
${r.alternatives.length ? `<h3>Next-best plans in this region</h3><table><tr><th>Model</th><th class="num">vCPU</th><th class="num">RAM</th><th class="num">Disk</th><th class="num">Total $ (1st month)</th></tr>
|
|
|
|
|
${r.alternatives.map((a) => `<tr><td>${esc(a.model)} <span class="muted small">${esc(a.cpu_type)}</span></td><td class="num">${a.vcpu}</td><td class="num">${a.ram_gb}</td><td class="num">${a.disk_gb}${a.extra_storage_gb ? "+" + a.extra_storage_gb : ""}</td><td class="num">${usd(a.total)}</td></tr>`).join("")}</table>` : ""}
|
|
|
|
|
<h3>Latency to all cities (estimated RTT ms)</h3>
|
|
|
|
|
${r.ping_host ? `<p class="small muted">Real measurement uses Globalping community probes (TCP ping to ${esc(r.ping_host)}). Free tier is rate-limited.</p>` : `<p class="small muted">No public probe endpoint is configured for this region, so only estimates are shown.</p>`}
|
|
|
|
|
<table><tr><th>City</th><th class="num">Est. RTT</th>${r.ping_host ? "<th>Measured</th>" : ""}</tr>
|
|
|
|
|
${cities.map((c) => `<tr><td>${esc(c.name)}, ${esc(c.country)}</td><td class="lat" style="color:${latColor(r.latency[c.id])}">${r.latency[c.id]}</td>
|
|
|
|
|
${r.ping_host ? `<td><button class="ghost small meas" data-c="${c.id}">measure</button> <span id="m-${c.id}"></span></td>` : ""}</tr>`).join("")}
|
|
|
|
|
</table>`;
|
|
|
|
|
$$(".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 = `<b>${m.min_ms} ms</b>${m.probe_scope === "country" ? ' <span class="small">(no probe in this city; country-level)</span>' : ""} <span class="muted small">${m.results.map((x) => esc(x.probe) + ": " + x.avg_ms).join("; ")}</span>`;
|
|
|
|
|
} 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 = `<div class="notes">
|
|
|
|
|
<h3>Methodology</h3>
|
|
|
|
|
<ul>
|
|
|
|
|
<li><b>Sizing</b>: 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.</li>
|
|
|
|
|
<li><b>Matching</b>: 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.</li>
|
|
|
|
|
<li><b>Prices</b>: 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)}</li>
|
|
|
|
|
<li><b>Latency</b>: modelled from geography (see Latency matrix tab). Real routes vary by ISP. Use "measure" in the detail view for live probes.</li>
|
|
|
|
|
<li><b>Compliance</b>: 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.</li>
|
|
|
|
|
</ul>
|
|
|
|
|
<h3>Providers: API documentation and references</h3>
|
|
|
|
|
<table><thead><tr><th>Provider</th><th>API docs</th><th>Pricing API</th><th>Pricing page</th><th>Compliance</th><th>Price source</th><th>Add'l storage</th><th>IPv4</th><th>Egress</th><th>SMTP 25</th></tr></thead><tbody>
|
|
|
|
|
${ps.map((p) => `<tr>
|
|
|
|
|
<td><b>${esc(p.name)}</b><br><span class="muted small">${p.region_count} regions</span></td>
|
|
|
|
|
<td><a href="${esc(p.api_docs)}" target="_blank" rel="noopener">API reference</a>${p.api_docs_note ? `<br><span class="small muted">${esc(p.api_docs_note)}</span>` : ""}</td>
|
|
|
|
|
<td>${p.pricing_api ? `<a href="${esc(p.pricing_api)}" target="_blank" rel="noopener">pricing API</a>` : '<span class="muted">none public</span>'}</td>
|
|
|
|
|
<td><a href="${esc(p.pricing_url)}" target="_blank" rel="noopener">pricing</a></td>
|
|
|
|
|
<td>${badges(p.compliance)}<br><a class="small" href="${esc(p.compliance_url)}" target="_blank" rel="noopener">compliance page</a></td>
|
|
|
|
|
<td class="small">${esc(p.price_source)}<br><span class="conf-${p.price_confidence}">confidence: ${p.price_confidence}</span>${p.manual && isAdmin() ? `<br><button class="ghost small edit-manual" data-p="${esc(p.id)}">Edit prices</button>` : ""}</td>
|
|
|
|
|
<td class="small">${p.setup_fee ? `<b>Setup fee ${usd(p.setup_fee.usd)}</b>: ${esc(p.setup_fee.note)}<br>` : ""}${p.storage.price_gb != null ? `$${p.storage.price_gb}/GB-mo` : ""} ${esc(p.storage.name)}</td>
|
|
|
|
|
<td class="num">${p.ipv4_monthly ? usd(p.ipv4_monthly) : "incl."}</td>
|
|
|
|
|
<td class="small">${esc(p.egress.note || (p.egress.per_gb != null ? `$${p.egress.per_gb}/GB (${p.egress.included_gb ?? 0} GB free)` : ""))}</td>
|
|
|
|
|
<td>${esc(p.smtp25)}</td></tr>
|
|
|
|
|
<tr><td></td><td colspan="9" class="small muted" style="white-space:normal">${esc(p.compliance_note)}</td></tr>`).join("")}
|
|
|
|
|
</tbody></table></div>`;
|
|
|
|
|
$$(".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 = {}) => `<tr>
|
|
|
|
|
<td><input data-f="code" value="${esc(p.code ?? "")}"></td><td><input class="w-name" data-f="name" value="${esc(p.name ?? "")}"></td>
|
|
|
|
|
<td><input data-f="vcpu" type="number" min="1" value="${p.vcpu ?? ""}"></td><td><input data-f="ram_gb" type="number" min="0" step="any" value="${p.ram_gb ?? ""}"></td>
|
|
|
|
|
<td><input data-f="disk_gb" type="number" min="0" step="any" value="${p.disk_gb ?? ""}"></td><td><input data-f="price" type="number" min="0" step="0.01" value="${p.price ?? ""}"></td>
|
|
|
|
|
<td><select data-f="cpu_type"><option ${p.cpu_type !== "dedicated" ? "selected" : ""}>shared</option><option ${p.cpu_type === "dedicated" ? "selected" : ""}>dedicated</option></select></td>
|
|
|
|
|
<td><input class="w-note" data-f="note" value="${esc(p.note ?? "")}"></td><td><button class="ghost del" title="Remove">✕</button></td></tr>`;
|
|
|
|
|
body.innerHTML = `
|
|
|
|
|
<h2>Edit ${esc(d.provider)} prices</h2>
|
|
|
|
|
<p class="small muted">${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.</p>
|
|
|
|
|
<div class="row-inline">
|
|
|
|
|
<label>Currency <select id="edCur"><option ${sh.currency === "EUR" ? "selected" : ""}>EUR</option><option ${sh.currency === "USD" ? "selected" : ""}>USD</option></select></label>
|
|
|
|
|
<label>USD per 1 EUR <input id="edFx" type="number" step="0.0001" min="0" value="${sh.fx}"></label>
|
|
|
|
|
<label>Setup fee (one-time, sheet currency) <input id="edSetup" type="number" step="0.01" min="0" value="${sh.setup_fee}"></label>
|
|
|
|
|
<label style="flex:1">Setup fee note <input id="edSetupNote" value="${esc(sh.setup_fee_note || "")}"></label>
|
|
|
|
|
</div>
|
|
|
|
|
<h3>Plans</h3>
|
|
|
|
|
<table id="edPlans"><thead><tr><th>Code</th><th>Name</th><th>vCPU</th><th>RAM GB</th><th>Disk GB</th><th>Price/mo</th><th>CPU</th><th>Note</th><th></th></tr></thead>
|
|
|
|
|
<tbody>${sh.plans.map(planRow).join("")}</tbody></table>
|
|
|
|
|
<button class="ghost" id="edAdd">+ Add plan</button>
|
|
|
|
|
<details style="margin-top:.6rem"><summary><b>Paste a table</b> <span class="small muted">(markdown, tab-separated or CSV, with a header row; replaces the plans above)</span></summary>
|
|
|
|
|
<textarea id="edPaste" placeholder="| Code | Name | vCPU | RAM | Storage | Speed | Price/mo |"></textarea>
|
|
|
|
|
<button class="ghost" id="edParse">Load pasted table</button> <span id="edParseMsg" class="small"></span>
|
|
|
|
|
</details>
|
|
|
|
|
<h3>Location surcharge per region (%)</h3>
|
|
|
|
|
<p class="small muted">Added to every plan price in that region. 0 = same price as the sheet.</p>
|
|
|
|
|
<table><thead><tr><th>Region</th><th>Code</th><th>Surcharge %</th></tr></thead><tbody>
|
|
|
|
|
${d.regions.map((r) => `<tr><td>${esc(r.label)}, ${esc(r.country)}</td><td class="muted">${esc(r.code)}</td>
|
|
|
|
|
<td><input class="edPct" data-r="${esc(r.code)}" type="number" step="any" value="${sh.region_surcharge_pct?.[r.code] ?? 0}" style="width:6em"></td></tr>`).join("")}
|
|
|
|
|
</tbody></table>
|
|
|
|
|
<p id="edErr" class="err small"></p>
|
|
|
|
|
<div class="actions"><button id="edSave">Save prices</button><button class="ghost" id="edCancel">Cancel</button>
|
|
|
|
|
<span class="spacer"></span><button class="ghost" id="edReset" title="Discard saved edits and use the built-in sheet">Reset to built-in</button></div>`;
|
|
|
|
|
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(`
|
|
|
|
|
<h2>API keys</h2>
|
|
|
|
|
<p class="small muted">Send a key in the <code>X-API-Key</code> header (or <code>Authorization: Bearer</code>). A key acts with its
|
|
|
|
|
owner's role${isAdmin() ? "" : " (yours: user)"}. Keys are shown once, when created. Store them somewhere safe.</p>
|
|
|
|
|
${fresh ? `<div class="warn"><b>New key "${esc(fresh.name)}"${fresh.username ? ` for ${esc(fresh.username)}` : ""}: copy it now, it won't be shown again.</b>
|
|
|
|
|
<div class="newkey" id="newKey">${esc(fresh.key)}</div><button class="ghost small" id="copyKey">Copy</button> <span id="copyMsg" class="small"></span></div>` : ""}
|
|
|
|
|
<h3>Create a key</h3>
|
|
|
|
|
<div class="row-inline">
|
|
|
|
|
<label>Name <input id="kName" placeholder="e.g. CI pipeline" maxlength="100"></label>
|
|
|
|
|
<label>Expires after (days) <input id="kDays" type="number" min="1" max="3650" placeholder="never" style="width:8em"></label>
|
|
|
|
|
${isAdmin() ? `<label>For account <select id="kUser">${users.map((u) => `<option value="${u.id}" ${u.id === S.me.id ? "selected" : ""}>${esc(u.username)} (${u.role})</option>`).join("")}</select></label>` : ""}
|
|
|
|
|
<button id="kCreate">Create key</button>
|
|
|
|
|
</div>
|
|
|
|
|
<p id="kErr" class="err small"></p>
|
|
|
|
|
<h3>${showAll ? "All keys" : "Your keys"} ${isAdmin() ? `<label class="chk small" style="display:inline-flex;margin-left:1rem"><input type="checkbox" id="kAll" ${showAll ? "checked" : ""}> show every account's keys</label>` : ""}</h3>
|
|
|
|
|
${keys.length ? `<table><thead><tr><th>Name</th><th>Key</th>${showAll ? "<th>Account</th>" : ""}<th>Created</th><th>Expires</th><th>Last used</th><th></th></tr></thead><tbody>
|
|
|
|
|
${keys.map((k) => `<tr><td>${esc(k.name)}</td><td><code>${esc(k.prefix)}</code></td>${showAll ? `<td>${esc(k.username)}</td>` : ""}
|
|
|
|
|
<td>${when(k.created_at)}</td><td>${k.expires_at ? when(k.expires_at) + (k.expired ? ' <span class="tag">expired</span>' : "") : "never"}</td>
|
|
|
|
|
<td>${when(k.last_used)}</td><td><button class="ghost revoke" data-id="${k.id}" data-name="${esc(k.name)}">Revoke</button></td></tr>`).join("")}
|
|
|
|
|
</tbody></table>` : '<p class="muted">No keys yet.</p>'}`);
|
|
|
|
|
$("#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(`
|
|
|
|
|
<h2>Users</h2>
|
|
|
|
|
<p class="small muted">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.</p>
|
|
|
|
|
<h3>Create an account</h3>
|
|
|
|
|
<div class="row-inline">
|
|
|
|
|
<label>Username <input id="uName" autocomplete="off" maxlength="64"></label>
|
|
|
|
|
<label>Password (min 10) <input id="uPass" type="password" autocomplete="new-password"></label>
|
|
|
|
|
<label>Role <select id="uRole"><option value="user">user</option><option value="admin">admin</option></select></label>
|
|
|
|
|
<button id="uCreate">Create account</button>
|
|
|
|
|
</div>
|
|
|
|
|
<p id="uMsg" class="small ${note.startsWith("Error") ? "err" : "ok"}">${esc(note)}</p>
|
|
|
|
|
<table><thead><tr><th>Username</th><th>Role</th><th>Status</th><th class="num">API keys</th><th>Last sign-in</th><th>Created</th><th></th></tr></thead><tbody>
|
|
|
|
|
${users.map((u) => {
|
|
|
|
|
const me = u.id === S.me.id;
|
|
|
|
|
return `<tr data-id="${u.id}" data-name="${esc(u.username)}">
|
|
|
|
|
<td>${esc(u.username)}${me ? ' <span class="tag">you</span>' : ""}</td>
|
|
|
|
|
<td>${me ? u.role : `<select class="uRoleSel"><option ${u.role === "user" ? "selected" : ""}>user</option><option ${u.role === "admin" ? "selected" : ""}>admin</option></select>`}</td>
|
|
|
|
|
<td>${u.disabled ? '<span class="tag">disabled</span>' : "active"}</td>
|
|
|
|
|
<td class="num">${u.api_keys}</td><td>${when(u.last_login)}</td><td>${when(u.created_at)}</td>
|
|
|
|
|
<td>${me ? "" : `<button class="ghost uToggle">${u.disabled ? "Enable" : "Disable"}</button>
|
|
|
|
|
<button class="ghost uReset">Reset password</button> <button class="ghost uDelete">Delete</button>`}</td></tr>`;
|
|
|
|
|
}).join("")}
|
|
|
|
|
</tbody></table>`);
|
|
|
|
|
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(`
|
|
|
|
|
<h2>Change password</h2>
|
|
|
|
|
<p class="small muted">Your other signed-in sessions will be signed out. API keys keep working.</p>
|
|
|
|
|
<div class="row-inline" style="flex-direction:column;align-items:stretch;max-width:320px">
|
|
|
|
|
<label>Current password <input id="pCur" type="password" autocomplete="current-password"></label>
|
|
|
|
|
<label>New password (min 10) <input id="pNew" type="password" autocomplete="new-password"></label>
|
|
|
|
|
<label>Repeat new password <input id="pNew2" type="password" autocomplete="new-password"></label>
|
|
|
|
|
<button id="pSave">Change password</button>
|
|
|
|
|
</div>
|
|
|
|
|
<p id="pMsg" class="small"></p>`);
|
|
|
|
|
$("#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();
|