caelum0x ad1bb093ec fix(vend): add a real creation path for KeyScope::EndUser provisioning keys
resolve()/wallets.rs fully enforce KeyScope::EndUser, but every real mint()
call (operator and customer /keys endpoints) hardcoded scope: KeyScope::App,
end_user_id: None — an end-user-scoped key could never actually be issued.

- CreateAppKey now carries scope + end_user_external_ref; issue_app_key
  resolves the ref via TenantRepo::find_end_user (itself the belongs-to-app
  check) and threads scope/end_user_id through to MintParams.
- IssueKeyRequest gains scope ("app"/"end_user", default "app" for backward
  compatibility) + end_user_external_ref on both the operator and customer
  /keys endpoints.
- admin.html and console.html key-issuance forms gained a scope selector and
  end-user external-ref field.
- New apps/vend/crates/vend-store/tests/end_user_scoped_keys.rs proves, against
  a real Postgres, that an EndUser-scoped key now mints and binds the resolved
  end_user_id, that a missing/unknown/cross-app ref is rejected, and that
  App-scoped issuance is unaffected.

bootstrap_product and the Tenant key scope are intentionally untouched — this
closes exactly the EndUser creation-path gap from the audit finding.
2026-11-03 16:01:04 +03:00

714 lines
36 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="robots" content="noindex" />
<title>Vend Admin</title>
<style>
:root {
--bg: #0f1117; --panel: #181b24; --border: #262b38; --fg: #e6e8ee;
--muted: #8b91a1; --accent: #6ea8fe; --danger: #f2668b; --ok: #55c98a;
--row: #1e222d;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
header {
display: flex; align-items: center; gap: 16px; flex-wrap: wrap;
padding: 14px 20px; background: var(--panel); border-bottom: 1px solid var(--border);
position: sticky; top: 0; z-index: 10;
}
header h1 { font-size: 16px; margin: 0; font-weight: 600; letter-spacing: .3px; }
header .spacer { flex: 1; }
input, button, select {
font: inherit; color: var(--fg); background: var(--row);
border: 1px solid var(--border); border-radius: 6px; padding: 7px 10px;
}
input { min-width: 280px; }
input.param { min-width: 220px; }
button { cursor: pointer; }
button.primary { background: var(--accent); color: #0b1020; border-color: var(--accent); font-weight: 600; }
button:hover { filter: brightness(1.08); }
#status { font-size: 12px; color: var(--muted); }
#status.err { color: var(--danger); }
#status.ok { color: var(--ok); }
nav {
display: flex; gap: 4px; padding: 12px 20px 0; flex-wrap: wrap;
}
nav button {
background: transparent; border: 1px solid transparent; border-bottom: none;
border-radius: 6px 6px 0 0; color: var(--muted); padding: 8px 14px;
}
nav button.active { color: var(--fg); background: var(--panel); border-color: var(--border); }
main { padding: 0 20px 40px; }
.card {
background: var(--panel); border: 1px solid var(--border); border-radius: 0 8px 8px 8px;
overflow: auto;
}
table { width: 100%; border-collapse: collapse; }
th, td {
text-align: left; padding: 9px 14px; border-bottom: 1px solid var(--border);
white-space: nowrap; font-variant-numeric: tabular-nums;
}
th { color: var(--muted); font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: .5px; }
tbody tr:hover { background: var(--row); }
td.mono, th.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }
.badge {
display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: 12px;
background: var(--row); border: 1px solid var(--border);
}
.empty, .loading { padding: 28px; color: var(--muted); text-align: center; }
.empty.error { color: var(--danger); }
.gate { max-width: 480px; margin: 80px auto; text-align: center; }
.gate p { color: var(--muted); }
.toolbar { display: flex; align-items: center; gap: 10px; padding: 12px 0; flex-wrap: wrap; }
.count { color: var(--muted); font-size: 12px; }
.hint { color: var(--muted); font-size: 12px; }
code { background: var(--row); padding: 1px 5px; border-radius: 4px; font-size: 12px; }
.actions { margin: 14px 0; background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; }
.actions h3 { margin: 0 0 10px; font-size: 12px; text-transform: uppercase; letter-spacing: .5px; color: var(--muted); }
.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 8px; }
.form-grid label { display: flex; flex-direction: column; gap: 3px; font-size: 12px; color: var(--muted); }
.form-grid input, .form-grid select { min-width: 0; width: 100%; }
button.danger { border-color: var(--danger, #f2668b); color: var(--danger, #f2668b); background: transparent; }
button.small { padding: 3px 8px; font-size: 12px; }
.secret { margin-top: 10px; padding: 10px; border: 1px solid #f2b35a; border-radius: 6px; background: #241f10; }
.secret code { display: block; margin-top: 4px; word-break: break-all; }
</style>
</head>
<body>
<header>
<h1>Vend Admin</h1>
<input id="key" type="password" placeholder="Bearer admin token" autocomplete="off" />
<button id="connect" class="primary">Connect</button>
<button id="logout" style="display:none">Sign out</button>
<div class="spacer"></div>
<span id="status">Not connected</span>
</header>
<div id="gate" class="gate">
<p>Enter the Vend administrator token to load live control-plane data.<br />
Requests use <code>Authorization: Bearer &lt;token&gt;</code> against the same
<code>/v1/control</code> endpoints that serve this page — no server-side bypass.</p>
</div>
<div id="app" style="display:none">
<nav id="tabs"></nav>
<main>
<div class="toolbar" id="toolbar"></div>
<div id="extra"></div>
<div id="view" class="card"><div class="loading">Loading…</div></div>
<div id="actions"></div>
</main>
</div>
<script>
"use strict";
(function () {
const KEY_STORE = "vend_admin_key";
const el = (id) => document.getElementById(id);
const statusEl = el("status");
function setStatus(msg, kind) {
statusEl.textContent = msg;
statusEl.className = kind || "";
}
function getKey() { return sessionStorage.getItem(KEY_STORE) || ""; }
function setKey(k) {
if (k) sessionStorage.setItem(KEY_STORE, k);
else sessionStorage.removeItem(KEY_STORE);
}
// Escape everything data-derived before it touches innerHTML.
function esc(v) {
if (v === null || v === undefined) return "";
return String(v).replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
}
// µ$ (micros of a dollar) → dollar string.
function usd(micros) {
if (micros === null || micros === undefined || micros === "") return "";
const n = Number(micros);
if (Number.isNaN(n)) return esc(micros);
return "$" + (n / 1_000_000).toFixed(6).replace(/0+$/, "").replace(/\.$/, ".0");
}
function num(v) {
if (v === null || v === undefined) return "";
return esc(v);
}
function badge(text) {
if (text === null || text === undefined || text === "") return "—";
return '<span class="badge">' + esc(text) + "</span>";
}
function bool(v) { return badge(v ? "yes" : "no"); }
function list(arr) {
if (!Array.isArray(arr) || arr.length === 0) return "—";
return arr.map((v) => esc(v)).join(", ");
}
function markup(p) {
if (!p || typeof p !== "object") return "—";
return esc(p.markup_bps) + " bps / min " + usd(p.min_fee_micros)
+ " / plat " + esc(p.platform_fee_bps) + " bps / " + esc(p.funding_mode);
}
// Friendly wording for Vend's stable error codes ({success:false,error:{code,message}}
// on the control plane, {error:{code,message}} on the data plane). Unknown
// codes keep the server message, so nothing is hidden.
var VEND_ERROR_CODES = {
insufficient_funds: "Not enough funds in the reserve to cover this request. Top up and try again.",
reserve_insufficient: "The tenant reserve is too low. Top up the reserve and try again.",
spend_cap_exceeded: "A daily spend cap would be exceeded. Raise the cap or wait until it resets.",
idempotency_conflict: "This Idempotency-Key was already used with a different request.",
idempotency_key_required: "An Idempotency-Key header is required for this request.",
idempotency_in_progress: "A request with this Idempotency-Key is still running. Wait for it to finish.",
streaming_idempotency_consumed: "This streaming Idempotency-Key was already used. Send a new key.",
streaming_unsupported: "Streaming is not supported by this Vend deployment.",
funding_mode_unsupported: "That funding mode is not supported by this Vend deployment.",
capture_exceeds_hold: "The capture is larger than the hold it settles.",
unauthorized: "The token was not accepted. Check it and sign in again.",
forbidden: "This token is not allowed to do that.",
not_found: "Not found. It may have been deleted, or the id is wrong.",
invalid_amount: "The amount is not valid. Use a positive amount.",
overflow: "The amount is too large.",
bad_id: "That id is not in the expected format.",
model_not_allowed: "That model is not in this app's allowlist.",
wallet_unprovisioned: "This end user has no wallet (attribution only), so it cannot be funded.",
provider_unavailable: "That sign-in provider is not configured on this server.",
rate_limited: "Too many requests. Wait a moment and try again.",
transport_error: "Vend could not reach Mint or Relay. Try again shortly.",
storage_error: "Vend could not read or write its database. Try again; check the server logs if it persists.",
upstream_error: "Mint or Relay rejected the request.",
config_error: "The server is missing configuration for this action.",
internal_error: "The server hit an error. Check the server logs if it persists."
};
var VEND_STATUS_MESSAGES = {
400: "The request was not understood. Check the values and try again.",
401: "The token was not accepted. Check it and sign in again.",
403: "This token is not allowed to do that.",
404: "Not found.",
409: "This conflicts with a change made meanwhile. Reload and try again.",
429: "Too many requests. Wait a moment and try again.",
500: "The server hit an error. Check the server logs if it persists.",
502: "The server is unreachable right now (bad gateway). Try again shortly.",
503: "Vend is not ready yet or a dependency is down. Try again shortly.",
504: "The server took too long to answer. Check whether the action went through before retrying."
};
function friendlyError(status, body) {
var err = body && body.error;
var code = err && typeof err === "object" ? err.code : (typeof err === "string" ? err : null);
var message = err && typeof err === "object" ? err.message : null;
if (code === "feature_disabled" && message) return message;
if (code === "upstream_error" && message) return VEND_ERROR_CODES.upstream_error + " " + message;
if (code && VEND_ERROR_CODES[code]) return VEND_ERROR_CODES[code];
if (message) return message;
return VEND_STATUS_MESSAGES[status] || ("Request failed (HTTP " + status + ").");
}
async function api(path, method, payload) {
const init = {
method: method || "GET",
headers: { "Authorization": "Bearer " + getKey(), "Accept": "application/json" },
};
if (payload !== undefined) {
init.headers["Content-Type"] = "application/json";
init.body = JSON.stringify(payload);
}
let res;
try { res = await fetch(path, init); }
catch (e) { throw new Error("Could not reach Vend. Check your connection and that the server is running."); }
if (res.status === 401) throw new Error("The admin token was not accepted. Check it and try again.");
if (res.status === 403) throw new Error("This admin token is not allowed to do that.");
if (!res.ok) {
let j = null;
try { j = await res.json(); } catch (_) {}
throw new Error(friendlyError(res.status, j));
}
const body = await res.json();
// Control-plane responses are the { success, data } envelope.
return body && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
}
// Each tab: label, params it needs, the path builder, whether the payload is a
// single object or an array, and columns. Only endpoints the real control plane
// exposes are represented here.
const TABS = [
{
id: "tenants", label: "Tenants",
params: [],
path: () => "/v1/control/tenants",
single: false,
cols: [
{ h: "Tenant ID", f: (r) => esc(r.id), mono: true },
{ h: "Name", f: (r) => esc(r.name) },
{ h: "Mint Account", f: (r) => esc(r.mint_account_id), mono: true },
],
},
{
id: "apps", label: "Apps",
params: [{ key: "tenant_id", label: "Tenant ID", required: true }],
path: (p) => "/v1/control/tenants/" + encodeURIComponent(p.tenant_id) + "/apps",
single: false,
cols: [
{ h: "App ID", f: (r) => esc(r.id), mono: true },
{ h: "Name", f: (r) => esc(r.name) },
{ h: "Enabled", f: (r) => bool(r.enabled) },
{ h: "ZDR", f: (r) => bool(r.zdr) },
{ h: "Models", f: (r) => list(r.model_allowlist) },
{ h: "Markup Policy", f: (r) => markup(r.markup_policy) },
{ h: "Mint Account", f: (r) => esc(r.mint_account_id), mono: true },
],
},
{
id: "keys", label: "API Keys",
params: [{ key: "app_id", label: "App ID", required: true }],
path: (p) => "/v1/control/apps/" + encodeURIComponent(p.app_id) + "/keys",
single: false,
cols: [
{ h: "Key ID", f: (r) => esc(r.id), mono: true },
{ h: "Prefix", f: (r) => esc(r.prefix), mono: true },
{ h: "Scope", f: (r) => badge(r.scope) },
{ h: "Status", f: (r) => badge(r.status) },
{ h: "App ID", f: (r) => esc(r.app_id), mono: true },
{ h: "Daily Cap", f: (r) => usd(r.daily_cap_micros) },
{ h: "Per End-User Cap", f: (r) => usd(r.per_end_user_daily_cap_micros) },
],
},
{
id: "usage", label: "Usage",
params: [
{ key: "app_id", label: "App ID", required: true },
{ key: "utc_day", label: "UTC Day (YYYY-MM-DD)", required: false },
],
path: (p) => "/v1/control/apps/" + encodeURIComponent(p.app_id) + "/usage"
+ (p.utc_day ? "?utc_day=" + encodeURIComponent(p.utc_day) : ""),
single: true,
cols: [
{ h: "App ID", f: (r) => esc(r.app_id), mono: true },
{ h: "UTC Day", f: (r) => esc(r.utc_day) },
{ h: "Requests", f: (r) => num(r.requests) },
{ h: "Pending", f: (r) => num(r.pending_requests) },
{ h: "Captured", f: (r) => num(r.captured_requests) },
{ h: "Released", f: (r) => num(r.released_requests) },
{ h: "Pending Charge", f: (r) => usd(r.pending_charge_micros) },
{ h: "Captured Charge", f: (r) => usd(r.captured_charge_micros) },
],
},
{
id: "users", label: "Users",
params: [{ key: "tenant_id", label: "Tenant ID", required: true }],
path: (p) => "/v1/control/tenants/" + encodeURIComponent(p.tenant_id) + "/users",
single: false,
cols: [
{ h: "User ID", f: (r) => esc(r.id), mono: true },
{ h: "Email", f: (r) => esc(r.email) },
{ h: "Display Name", f: (r) => esc(r.display_name) },
{ h: "Role", f: (r) => badge(r.role) },
{ h: "Status", f: (r) => badge(r.status) },
{ h: "Providers", f: (r) => list(r.external_providers) },
{ h: "Created", f: (r) => esc((r.created_at || "").slice(0, 10)) },
],
},
{
id: "pricing", label: "Model Pricing",
params: [{ key: "app_id", label: "App ID", required: true }],
path: (p) => "/v1/control/apps/" + encodeURIComponent(p.app_id) + "/model-pricing",
rows: (payload) => payload.models,
cols: [
{ h: "Model", f: (r) => esc(r.model), mono: true },
{ h: "Provider in / out (per 1M)", f: (r) => usd(r.provider_input_micros_per_million_tokens) + " / " + usd(r.provider_output_micros_per_million_tokens) },
{ h: "Markup", f: (r) => esc(r.effective_markup_bps) + " bps " + badge(r.override ? "override" : "default") },
{ h: "End-user price in / out (per 1M)", f: (r) => usd(r.input_micros_per_million_tokens) + " / " + usd(r.output_micros_per_million_tokens) },
],
},
{
id: "earnings", label: "Tenant Earnings",
params: [
{ key: "tenant_id", label: "Tenant ID", required: true },
{ key: "from", label: "From (YYYY-MM-DD)", required: false },
{ key: "to", label: "To (YYYY-MM-DD)", required: false },
],
path: (p) => "/v1/control/tenants/" + encodeURIComponent(p.tenant_id) + "/earnings?"
+ (p.from ? "from=" + encodeURIComponent(p.from) + "&" : "") + (p.to ? "to=" + encodeURIComponent(p.to) : ""),
rows: (payload) => payload.days,
cols: [
{ h: "UTC Day", f: (r) => esc(r.utc_day) },
{ h: "Captured", f: (r) => num(r.captured_requests) },
{ h: "End users paid", f: (r) => usd(r.charge_micros) },
{ h: "Provider cost", f: (r) => usd(r.provider_cost_micros) },
{ h: "Platform fee", f: (r) => usd(r.platform_fee_micros) },
{ h: "Tenant net", f: (r) => usd(r.tenant_net_micros) },
],
},
{
id: "payouts", label: "Payouts",
params: [{ key: "pending", label: "Pending only (true/false)", required: false }],
path: (p) => "/v1/control/payouts?limit=200" + (p.pending === "true" ? "&pending=true" : ""),
rows: (payload) => payload.payouts,
cols: [
{ h: "Charge", f: (r) => esc(r.charge_id), mono: true },
{ h: "Tenant", f: (r) => esc(r.tenant_id), mono: true },
{ h: "Charged", f: (r) => usd(r.captured_charge_micros) },
{ h: "Provider", f: (r) => usd(r.provider_cost_micros) + " " + bool(r.provider_transferred) },
{ h: "Tenant net", f: (r) => usd(r.tenant_net_micros) + " " + bool(r.tenant_transferred) },
{ h: "Platform", f: (r) => usd(r.platform_fee_micros) + " " + bool(r.platform_transferred) },
{ h: "State", f: (r) => badge(r.state) + (r.last_error ? '<div class="hint">' + esc(r.last_error) + "</div>" : "") },
],
},
];
// ---- write actions (every one hits a real /v1/control endpoint) ------------
const dollars = (v) => Math.round(Number(v || 0) * 1e6);
const csv = (v) => String(v || "").split(",").map((x) => x.trim()).filter(Boolean);
function secretBox(title, value, note) {
return '<div class="secret"><b>' + esc(title) + '</b><div class="hint">' + esc(note || "Shown once. Store it now.")
+ "</div><code>" + esc(value) + "</code></div>";
}
function field(id, label, attrs) {
return '<label>' + esc(label) + '<input id="' + id + '" ' + (attrs || "") + " /></label>";
}
function goTab(id, params) {
Object.assign(paramState, params || {});
active = TABS.find((t) => t.id === id);
renderTabs(); renderToolbar(); maybeLoad();
}
async function act(fn, okMsg) {
try { const out = await fn(); setStatus(okMsg, "ok"); return out === null || out === undefined ? true : out; }
catch (e) { setStatus(e.message, "err"); return null; }
}
const FORMS = {
tenants: () => '<h3>Bootstrap a tenant</h3><div class="form-grid">'
+ field("b-tenant", "Tenant name") + field("b-app", "First app name")
+ field("b-email", "Owner email", 'type="email"') + field("b-owner", "Owner display name")
+ field("b-acct", "Mint reserve account", 'placeholder="acct_..."')
+ field("b-models", "Allowed models (comma separated, blank = all)")
+ field("b-bps", "Markup bps", 'type="number" value="2000"')
+ field("b-min", "Min fee per request ($)", 'type="number" value="0" step="0.0001"')
+ field("b-plat", "Platform fee bps", 'type="number" value="1000"')
+ field("b-cap", "Key daily cap ($)", 'type="number" value="100" step="0.01"')
+ fundingSelect("b")
+ '</div><div class="toolbar"><button class="primary" id="b-go">Bootstrap</button></div><div id="b-out"></div>',
apps: () => paramState.tenant_id ? '<h3>Create app for ' + esc(paramState.tenant_id) + '</h3><div class="form-grid">'
+ field("a-name", "App name") + field("a-acct", "Mint reserve account", 'placeholder="acct_..."')
+ field("a-models", "Allowed models (comma separated)")
+ field("a-bps", "Markup bps", 'type="number" value="2000"')
+ field("a-min", "Min fee per request ($)", 'type="number" value="0" step="0.0001"')
+ field("a-plat", "Platform fee bps", 'type="number" value="1000"')
+ '<label>ZDR<select id="a-zdr"><option value="false">off</option><option value="true">on</option></select></label>'
+ fundingSelect("a")
+ '</div><div class="toolbar"><button class="primary" id="a-go">Create app</button></div>' : "",
keys: () => paramState.app_id ? '<h3>Issue key for ' + esc(paramState.app_id) + '</h3><div class="form-grid">'
+ '<label>Environment<select id="k-env"><option value="live">live</option><option value="test">test</option></select></label>'
+ '<label>Scope<select id="k-scope"><option value="app">app-wide</option><option value="end_user">single end-user</option></select></label>'
+ field("k-euref", "End-user external ref (scope=end_user)")
+ field("k-cap", "Daily cap ($)", 'type="number" value="100" step="0.01"')
+ field("k-eu", "Per end-user daily cap ($, optional)", 'type="number" step="0.01"')
+ '</div><div class="toolbar"><button class="primary" id="k-go">Issue key</button></div><div id="k-out"></div>'
+ '<h3 style="margin-top:14px">Provision end user</h3><div class="form-grid">'
+ field("e-ref", "External reference") + field("e-acct", "Mint account", 'placeholder="acct_..."')
+ '</div><div class="toolbar"><button id="e-go">Provision</button></div>' : "",
users: () => paramState.tenant_id ? '<h3>Invite user to ' + esc(paramState.tenant_id) + '</h3><div class="form-grid">'
+ field("u-email", "Email", 'type="email"') + field("u-name", "Display name")
+ '<label>Role<select id="u-role"><option value="viewer">viewer</option><option value="admin">admin</option><option value="owner">owner</option></select></label>'
+ '</div><div class="toolbar"><button class="primary" id="u-go">Invite</button></div><div id="u-out"></div>' : "",
usage: () => "",
pricing: () => paramState.app_id ? '<h3>Set a per-model markup for ' + esc(paramState.app_id) + '</h3><div class="form-grid">'
+ field("m-model", "Model id", 'placeholder="tensorzero::model_name::..."')
+ field("m-bps", "Markup bps (10000 = +100%)", 'type="number" min="0" max="1000000" value="2000"')
+ field("m-min", "Min fee per request ($, optional)", 'type="number" min="0" step="0.0001"')
+ '</div><div class="toolbar"><button class="primary" id="m-go">Save markup</button></div>' : "",
};
function fundingSelect(prefix) {
return '<label>Who pays<select id="' + prefix + '-fund"><option value="tenant_reserve">app wallet (tenant_reserve)</option>'
+ '<option value="end_user_reserve">each end user\'s wallet (end_user_reserve)</option></select></label>';
}
const policy = (p) => ({
markup_bps: Number(el(p + "-bps").value || 0),
min_fee_micros: dollars(el(p + "-min").value),
platform_fee_bps: Number(el(p + "-plat").value || 0),
funding_mode: el(p + "-fund") ? el(p + "-fund").value : "tenant_reserve",
});
function bindForms() {
const on = (id, fn) => { const b = el(id); if (b) b.onclick = fn; };
on("b-go", async () => {
const out = await act(() => api("/v1/control/tenants", "POST", {
tenant_name: el("b-tenant").value.trim(), app_name: el("b-app").value.trim(),
owner_email: el("b-email").value.trim(), owner_display_name: el("b-owner").value.trim(),
mint_account_id: el("b-acct").value.trim(), model_allowlist: csv(el("b-models").value), zdr: false,
markup_policy: policy("b"), daily_cap_micros: dollars(el("b-cap").value),
}), "Tenant bootstrapped");
if (out) {
el("b-out").innerHTML = secretBox("Provisioning key", out.provisioning_key)
+ secretBox("Owner setup token", out.owner_setup_token, "Deliver to the owner out of band; they set a password at /console.");
load();
}
});
on("a-go", async () => {
const out = await act(() => api("/v1/control/tenants/" + encodeURIComponent(paramState.tenant_id) + "/apps", "POST", {
name: el("a-name").value.trim(), mint_account_id: el("a-acct").value.trim(),
model_allowlist: csv(el("a-models").value), zdr: el("a-zdr").value === "true", markup_policy: policy("a"),
}), "App created");
if (out) load();
});
on("k-go", async () => {
const scope = el("k-scope") ? el("k-scope").value : "app";
if (scope === "end_user" && !el("k-euref").value.trim()) { setStatus("Enter the end-user's external ref", "err"); return; }
const body = { environment: el("k-env").value, scope: scope, daily_cap_micros: dollars(el("k-cap").value) };
if (scope === "end_user") body.end_user_external_ref = el("k-euref").value.trim();
if (el("k-eu").value) body.per_end_user_daily_cap_micros = dollars(el("k-eu").value);
const out = await act(() => api("/v1/control/apps/" + encodeURIComponent(paramState.app_id) + "/keys", "POST", body), "Key issued");
if (out) { el("k-out").innerHTML = secretBox("New provisioning key", out.secret); load(); }
});
on("e-go", async () => {
await act(() => api("/v1/control/apps/" + encodeURIComponent(paramState.app_id) + "/end-users", "POST", {
external_ref: el("e-ref").value.trim(), mint_account_id: el("e-acct").value.trim(),
}), "End user provisioned");
});
on("m-go", async () => {
const body = { model: el("m-model").value.trim(), markup_bps: Number(el("m-bps").value || 0) };
if (el("m-min").value) body.min_fee_micros = dollars(el("m-min").value);
const out = await act(() => api("/v1/control/apps/" + encodeURIComponent(paramState.app_id) + "/model-pricing", "PUT", body), "Markup saved");
if (out) load();
});
on("u-go", async () => {
const out = await act(() => api("/v1/control/tenants/" + encodeURIComponent(paramState.tenant_id) + "/users", "POST", {
email: el("u-email").value.trim(), display_name: el("u-name").value.trim(), role: el("u-role").value,
}), "User invited");
if (out) { el("u-out").innerHTML = secretBox("Setup token for " + out.user.email, out.setup_token); load(); }
});
}
// Per-row buttons: click-through navigation plus the real write endpoints.
const ROW_ACTIONS = {
tenants: (r) => '<button class="small" data-go="apps" data-tenant="' + esc(r.id) + '">Apps</button> '
+ '<button class="small" data-go="users" data-tenant="' + esc(r.id) + '">Users</button> '
+ '<button class="small" data-go="earnings" data-tenant="' + esc(r.id) + '">Earnings</button>',
apps: (r) => '<button class="small" data-go="keys" data-app="' + esc(r.id) + '">Keys</button> '
+ '<button class="small" data-go="pricing" data-app="' + esc(r.id) + '">Pricing</button> '
+ '<button class="small" data-go="usage" data-app="' + esc(r.id) + '">Usage</button> '
+ '<button class="small' + (r.enabled ? " danger" : "") + '" data-toggle="' + esc(r.id) + '" data-enabled="' + (r.enabled ? "1" : "") + '">'
+ (r.enabled ? "Disable" : "Enable") + "</button>",
pricing: (r) => r.override ? '<button class="small danger" data-reset-model="' + esc(r.model) + '">Reset to default</button>' : "",
keys: (r) => r.status === "revoked" ? "" : '<button class="small danger" data-revoke="' + esc(r.id) + '">Revoke</button>',
users: (r) => '<select class="small" data-role="' + esc(r.id) + '">' + ["viewer", "admin", "owner"].map((x) =>
'<option value="' + x + '"' + (r.role === x ? " selected" : "") + ">" + x + "</option>").join("") + "</select> "
+ (r.status === "disabled"
? '<button class="small" data-user-enable="' + esc(r.id) + '">Enable</button> '
: '<button class="small danger" data-user-disable="' + esc(r.id) + '">Disable</button> ')
+ '<button class="small" data-sessions="' + esc(r.id) + '">Revoke sessions</button>',
};
function bindRowActions() {
const view = el("view");
view.querySelectorAll("button[data-go]").forEach((b) => {
b.onclick = () => goTab(b.dataset.go, b.dataset.tenant ? { tenant_id: b.dataset.tenant } : { app_id: b.dataset.app });
});
view.querySelectorAll("button[data-toggle]").forEach((b) => {
b.onclick = async () => {
const ok = await act(() => api("/v1/control/apps/" + encodeURIComponent(b.dataset.toggle) + "/enabled", "PATCH",
{ enabled: !b.dataset.enabled }), b.dataset.enabled ? "App disabled" : "App enabled");
if (ok !== null) load();
};
});
view.querySelectorAll("button[data-revoke]").forEach((b) => {
b.onclick = async () => {
if (!confirm("Revoke this key? Requests using it fail immediately.")) return;
const ok = await act(() => api("/v1/control/keys/" + encodeURIComponent(b.dataset.revoke), "DELETE"), "Key revoked");
if (ok !== null) load();
};
});
view.querySelectorAll("button[data-reset-model]").forEach((b) => {
b.onclick = async () => {
const ok = await act(() => api("/v1/control/apps/" + encodeURIComponent(paramState.app_id) + "/model-pricing?model="
+ encodeURIComponent(b.dataset.resetModel), "DELETE"), "Markup reset");
if (ok !== null) load();
};
});
const userPatch = async (id, body, msg) => {
const ok = await act(() => api("/v1/control/tenants/" + encodeURIComponent(paramState.tenant_id) + "/users/"
+ encodeURIComponent(id), "PATCH", body), msg);
if (ok !== null) load();
};
view.querySelectorAll("select[data-role]").forEach((s) => { s.onchange = () => userPatch(s.dataset.role, { role: s.value }, "Role updated"); });
view.querySelectorAll("button[data-user-disable]").forEach((b) => { b.onclick = () => userPatch(b.dataset.userDisable, { disabled: true }, "User disabled"); });
view.querySelectorAll("button[data-user-enable]").forEach((b) => { b.onclick = () => userPatch(b.dataset.userEnable, { disabled: false }, "User enabled"); });
view.querySelectorAll("button[data-sessions]").forEach((b) => {
b.onclick = () => act(() => api("/v1/control/tenants/" + encodeURIComponent(paramState.tenant_id) + "/users/"
+ encodeURIComponent(b.dataset.sessions) + "/sessions", "DELETE"), "Sessions revoked");
});
}
function renderActions() {
const html = (FORMS[active.id] || (() => ""))();
el("actions").innerHTML = html ? '<div class="actions">' + html + "</div>" : "";
bindForms();
}
async function renderExtra() {
const box = el("extra");
box.innerHTML = "";
if (active.id === "payouts" || (active.id === "earnings" && paramState.tenant_id)) {
try {
const data = await api(active.path(paramState));
const t = active.id === "payouts" ? data.totals : data.payouts.totals;
const sum = active.id === "earnings" ? data.summary : null;
box.innerHTML = '<div class="actions"><h3>' + (sum ? "Range " + esc(data.from) + " to " + esc(data.to) : "Platform payouts") + "</h3>"
+ (sum ? "End users paid <b>" + usd(sum.charge_micros) + "</b> &middot; tenant net <b>" + usd(sum.tenant_net_micros)
+ "</b> &middot; platform fee <b>" + usd(sum.platform_fee_micros) + "</b><br>" : "")
+ "Paid to tenants <b>" + usd(t.tenant_paid_micros) + "</b> &middot; owed on pending <b>" + usd(t.tenant_pending_micros)
+ "</b> &middot; platform fee collected <b>" + usd(t.platform_paid_micros) + "</b> &middot; "
+ esc(t.complete_count) + " complete / " + esc(t.pending_count) + " pending</div>";
} catch (e) {
box.innerHTML = '<div class="actions"><span class="hint">' + esc(e.message) + "</span></div>";
}
return;
}
if (active.id !== "usage" || !paramState.app_id) return;
try {
const b = await api("/v1/control/apps/" + encodeURIComponent(paramState.app_id) + "/balance");
box.innerHTML = '<div class="actions"><h3>Reserve wallet</h3>Available <b>' + usd(b.available_micros)
+ "</b> &middot; held by in-flight requests <b>" + usd(b.held_micros) + '</b> <span class="hint">(Mint account '
+ esc(b.account_id) + ")</span></div>";
} catch (e) {
box.innerHTML = '<div class="actions"><h3>Reserve wallet</h3><span class="hint">' + esc(e.message) + "</span></div>";
}
}
let active = TABS[0];
const paramState = {}; // key -> value, shared across tabs (tenant_id/app_id reused)
function renderTabs() {
const nav = el("tabs");
nav.innerHTML = "";
TABS.forEach((t) => {
const b = document.createElement("button");
b.textContent = t.label;
b.className = t.id === active.id ? "active" : "";
b.onclick = () => { active = t; renderTabs(); renderToolbar(); maybeLoad(); };
nav.appendChild(b);
});
}
function renderToolbar() {
const bar = el("toolbar");
bar.innerHTML = "";
active.params.forEach((param) => {
const input = document.createElement("input");
input.className = "param";
input.placeholder = param.label + (param.required ? " *" : "");
input.value = paramState[param.key] || "";
input.oninput = () => { paramState[param.key] = input.value.trim(); };
input.onchange = () => { renderActions(); renderExtra(); };
input.addEventListener("keydown", (e) => { if (e.key === "Enter") load(); });
bar.appendChild(input);
});
const refresh = document.createElement("button");
refresh.textContent = active.params.length ? "Load" : "Refresh";
refresh.onclick = load;
bar.appendChild(refresh);
const count = document.createElement("span");
count.id = "count";
count.className = "count";
bar.appendChild(count);
}
function missingParams() {
return active.params.filter((p) => p.required && !(paramState[p.key] || "").trim());
}
function maybeLoad() {
renderActions();
renderExtra();
if (missingParams().length === 0) load();
else {
el("view").innerHTML = '<div class="empty">Enter '
+ active.params.filter((p) => p.required).map((p) => esc(p.label)).join(", ")
+ " to load.</div>";
const c = el("count"); if (c) c.textContent = "";
}
}
function renderRows(payload) {
const view = el("view");
const rows = active.rows ? (payload ? active.rows(payload) : []) : (active.single ? (payload ? [payload] : []) : payload);
if (!Array.isArray(rows) || rows.length === 0) {
view.innerHTML = '<div class="empty">No ' + esc(active.label.toLowerCase()) + " found.</div>";
const c = el("count"); if (c) c.textContent = "0 rows";
return;
}
const rowActions = ROW_ACTIONS[active.id];
const head = active.cols.map((c) =>
'<th' + (c.mono ? ' class="mono"' : "") + ">" + esc(c.h) + "</th>").join("")
+ (rowActions ? "<th>Actions</th>" : "");
const body = rows.map((r) =>
"<tr>" + active.cols.map((c) =>
"<td" + (c.mono ? ' class="mono"' : "") + ">" + c.f(r) + "</td>").join("")
+ (rowActions ? "<td>" + rowActions(r) + "</td>" : "") + "</tr>").join("");
view.innerHTML = "<table><thead><tr>" + head + "</tr></thead><tbody>" + body + "</tbody></table>";
bindRowActions();
const c = el("count"); if (c) c.textContent = rows.length + " row" + (rows.length === 1 ? "" : "s");
}
async function load() {
const missing = missingParams();
if (missing.length) {
setStatus("Missing: " + missing.map((p) => p.label).join(", "), "err");
return;
}
el("view").innerHTML = '<div class="loading">Loading…</div>';
try {
const data = await api(active.path(paramState));
renderRows(data);
setStatus("Connected", "ok");
} catch (e) {
el("view").innerHTML = '<div class="empty error" role="alert">' + esc(e.message) + "</div>";
setStatus(e.message, "err");
if (/Unauthorized/.test(e.message)) showGate();
}
}
function showApp() {
el("gate").style.display = "none";
el("app").style.display = "";
el("logout").style.display = "";
renderTabs();
renderToolbar();
maybeLoad();
}
function showGate() {
el("app").style.display = "none";
el("gate").style.display = "";
el("logout").style.display = "none";
el("key").value = "";
}
el("connect").onclick = () => {
const k = el("key").value.trim();
if (!k) { setStatus("Enter an admin token.", "err"); return; }
setKey(k);
setStatus("Connecting…");
showApp();
};
el("key").addEventListener("keydown", (e) => { if (e.key === "Enter") el("connect").click(); });
el("logout").onclick = () => { setKey(""); setStatus("Not connected"); showGate(); };
if (getKey()) showApp(); else showGate();
})();
</script>
</body>
</html>