diff --git a/app/presentation/static/app.js b/app/presentation/static/app.js index ac6c145..f8bb5be 100644 --- a/app/presentation/static/app.js +++ b/app/presentation/static/app.js @@ -32,11 +32,13 @@ document.addEventListener("DOMContentLoaded", () => { // Hero CTA smooth focus into interactive generator const btnHeroStart = document.getElementById("btnHeroStart"); const cardIssue = document.getElementById("cardIssue"); - btnHeroStart.addEventListener("click", () => { - document.getElementById("console-section").scrollIntoView({ behavior: "smooth" }); + // Scrolls to the Issue card and issues the license right away, so the token appears next to the button. + btnHeroStart.addEventListener("click", async () => { + cardIssue.scrollIntoView({ behavior: "smooth", block: "center" }); cardIssue.classList.add("pulse-focus"); - issueEmail.focus(); setTimeout(() => cardIssue.classList.remove("pulse-focus"), 1400); + await runIssue(); + issueResult.scrollIntoView({ behavior: "smooth", block: "nearest" }); }); function renderBox(el, payload, state = "ok") { @@ -222,7 +224,7 @@ document.addEventListener("DOMContentLoaded", () => { // 1. Issue License const btnIssue = document.getElementById("btnIssue"); const issueResult = document.getElementById("issueResult"); - btnIssue.addEventListener("click", () => + const runIssue = () => withButtonLock(btnIssue, "Issuing...", async () => { const domainVal = issueDomain.value.trim(); const payload = { @@ -260,8 +262,8 @@ document.addEventListener("DOMContentLoaded", () => { } catch (err) { renderBox(issueResult, { error: err.message }, "err"); } - }) - ); + }); + btnIssue.addEventListener("click", runIssue); // 2A. Verify Online const btnVerifyOnline = document.getElementById("btnVerifyOnline"); @@ -536,6 +538,53 @@ document.addEventListener("DOMContentLoaded", () => { }) ); + // 3D. Auto-refund demo: debit -> simulated tool failure -> refund with the same idempotency key + const btnQuotaRefundDemo = document.getElementById("btnQuotaRefundDemo"); + btnQuotaRefundDemo.addEventListener("click", () => + withButtonLock(btnQuotaRefundDemo, "Simulating...", async () => { + const key = quotaKey.value.trim(); + const credits = parseInt(quotaCredits.value || "5", 10); + const idem = "ui_refund_" + crypto.randomUUID(); + const post = async (path, body) => { + const res = await fetch(path, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + return { res, data: await res.json() }; + }; + try { + const d = await post("/api/v1/quota/deduct", { + license_key: key, credits, idempotency_key: idem, event_type: "console_refund_demo", + }); + if (!d.res.ok) { + renderBox(quotaResult, d.data, classifyResponse(d.res, d.data)); + return; + } + const afterDebit = d.data.data.remaining_balance ?? d.data.data.credit_balance; + const r = await post("/api/v1/quota/refund", { + license_key: key, idempotency_key: idem, reason: "simulated tool failure (isError: true)", + }); + if (!r.res.ok) { + renderBox(quotaResult, r.data, classifyResponse(r.res, r.data)); + return; + } + const afterRefund = r.data.data.remaining_balance; + renderBox(quotaResult, { + "1_debit": { credits, idempotency_key: idem, balance: afterDebit }, + "2_tool_call": { isError: true, content: "Simulated failure: the tool raised an exception" }, + "3_auto_refund": { refunded: r.data.data.refunded, balance: afterRefund }, + balance_before: afterDebit + credits, + balance_after: afterRefund, + restored: afterRefund === afterDebit + credits, + }, "ok"); + await refreshTelemetry(key); + } catch (err) { + renderBox(quotaResult, { error: err.message }, "err"); + } + }) + ); + // 4. Simulate Signed Webhook const btnSimulate = document.getElementById("btnSimulate"); const simResult = document.getElementById("simResult"); @@ -788,7 +837,7 @@ kf = KeyFlint() # reads KEYFLINT_LICENSE, KEYFLINT_PUBLIC_K "ts-mcp": `import { createKeyFlint } from "keyflint-verify/mcp"; -const kf = createKeyFlint({ gatewayUrl: "https://licenses.tu-dominio.com" }); +const kf = createKeyFlint({ gatewayUrl: "https://licenses.your-domain.com" }); // Atomic per-call debit in @modelcontextprotocol/sdk server.tool("audit_code", schema, kf.metered(2, async (args) => { @@ -862,8 +911,8 @@ fmt.Println(payload.Tier, payload.Features)` const btnCopyGenerated = document.getElementById("btnCopyGenerated"); function buildSnippet(lang, credits, pub, gateway) { - const key = /^[0-9a-fA-F]{64}$/.test(pub) ? pub.toLowerCase() : "PEGA_AQUI_TU_CLAVE_PUBLICA_HEX"; - const gw = gateway || "https://licencias.tu-dominio.com"; + const key = /^[0-9a-fA-F]{64}$/.test(pub) ? pub.toLowerCase() : "PASTE_YOUR_PUBLIC_KEY_HEX"; + const gw = gateway || "https://licenses.your-domain.com"; const n = Number.isInteger(credits) && credits > 0 ? credits : 0; if (lang === "ts") { const wrap = n ? `kf.metered(${n}, async ({ query }: { query: string }) => {` : "kf.requireLicense(async ({ query }: { query: string }) => {"; @@ -875,10 +924,10 @@ fmt.Println(payload.Tier, payload.Features)` 'import { createKeyFlint } from "keyflint-verify/mcp";', "", `const kf = createKeyFlint({ publicKeys: ${JSON.stringify(key)}${n ? `, gatewayUrl: ${JSON.stringify(gw)}` : ""} });`, - 'const server = new McpServer({ name: "mi-herramienta", version: "1.0.0" });', + 'const server = new McpServer({ name: "my-tool", version: "1.0.0" });', "", n ? `// ${n} credit(s) per call; refunded if the tool fails` : "// License only (offline)", - 'server.registerTool("buscar", { inputSchema: { query: z.string() } }, ' + wrap, + 'server.registerTool("search", { inputSchema: { query: z.string() } }, ' + wrap, ' return { content: [{ type: "text" as const, text: `Result for ${query}` }] };', "}));", "", @@ -916,12 +965,12 @@ fmt.Println(payload.Tier, payload.Features)` "from keyflint_verify.mcp import KeyFlint", "", `kf = KeyFlint(public_keys=${JSON.stringify(key)}${n ? `, gateway_url=${JSON.stringify(gw)}` : ""})`, - 'mcp = FastMCP("mi-herramienta")', + 'mcp = FastMCP("my-tool")', "", n ? `# ${n} credit(s) per call; refunded if the tool fails` : "# License only (offline)", "@mcp.tool()", n ? `@kf.metered(credits=${n})` : "@kf.require_license", - "def buscar(query: str) -> str:", + "def search(query: str) -> str:", ' return f"Result for {query}"', "", 'if __name__ == "__main__":', @@ -929,8 +978,16 @@ fmt.Println(payload.Tier, payload.Features)` ].join("\n"); } + const genPubKeyHint = document.getElementById("genPubKeyHint"); function renderGenerated() { if (!genOutput) return; + const pub = genPubKey.value.trim(); + const badKey = pub !== "" && !/^[0-9a-fA-F]{64}$/.test(pub); + genPubKey.setAttribute("aria-invalid", badKey ? "true" : "false"); + if (genPubKeyHint) { + genPubKeyHint.hidden = !badKey; + genPubKeyHint.textContent = `Must be exactly 64 hex characters (0-9, a-f); got ${pub.length}. Using a placeholder until it is valid.`; + } genOutput.textContent = buildSnippet( genLang.value, parseInt(genCredits.value, 10), diff --git a/app/presentation/static/index.html b/app/presentation/static/index.html index 8b10fcb..36a758d 100644 --- a/app/presentation/static/index.html +++ b/app/presentation/static/index.html @@ -229,6 +229,8 @@ .code-box.state-warn::before { content: "AVISO"; color: var(--warn); } .code-box.state-err { border-left-color: var(--err); background: color-mix(in srgb, var(--err-bg) 45%, var(--code-bg)); } .code-box.state-err::before { content: "ERROR"; color: var(--err); } + .field-hint { display: block; margin-top: 8px; font-size: 12px; color: var(--err); } + input[aria-invalid="true"] { border-color: var(--err); } .code-box.is-idle { border-left-color: var(--line-strong); color: var(--muted); } .code-box.is-idle::before { content: "ESPERANDO"; color: var(--muted); } @keyframes reveal { from { opacity: 0; transform: translateY(-2px); } to { opacity: 1; transform: none; } } @@ -617,7 +619,8 @@

3-step generator

- + +
@@ -716,7 +719,7 @@

Verify, activate and revoke

Credit quota

-

Atomic debit; every operation carries its own idempotency key.

+

Atomic debit; every operation carries its own idempotency key. "Simulate failed call" shows the automatic refund.

3
@@ -732,6 +735,7 @@

Credit quota

+
diff --git a/docs/app.js b/docs/app.js index ac6c145..f8bb5be 100644 --- a/docs/app.js +++ b/docs/app.js @@ -32,11 +32,13 @@ document.addEventListener("DOMContentLoaded", () => { // Hero CTA smooth focus into interactive generator const btnHeroStart = document.getElementById("btnHeroStart"); const cardIssue = document.getElementById("cardIssue"); - btnHeroStart.addEventListener("click", () => { - document.getElementById("console-section").scrollIntoView({ behavior: "smooth" }); + // Scrolls to the Issue card and issues the license right away, so the token appears next to the button. + btnHeroStart.addEventListener("click", async () => { + cardIssue.scrollIntoView({ behavior: "smooth", block: "center" }); cardIssue.classList.add("pulse-focus"); - issueEmail.focus(); setTimeout(() => cardIssue.classList.remove("pulse-focus"), 1400); + await runIssue(); + issueResult.scrollIntoView({ behavior: "smooth", block: "nearest" }); }); function renderBox(el, payload, state = "ok") { @@ -222,7 +224,7 @@ document.addEventListener("DOMContentLoaded", () => { // 1. Issue License const btnIssue = document.getElementById("btnIssue"); const issueResult = document.getElementById("issueResult"); - btnIssue.addEventListener("click", () => + const runIssue = () => withButtonLock(btnIssue, "Issuing...", async () => { const domainVal = issueDomain.value.trim(); const payload = { @@ -260,8 +262,8 @@ document.addEventListener("DOMContentLoaded", () => { } catch (err) { renderBox(issueResult, { error: err.message }, "err"); } - }) - ); + }); + btnIssue.addEventListener("click", runIssue); // 2A. Verify Online const btnVerifyOnline = document.getElementById("btnVerifyOnline"); @@ -536,6 +538,53 @@ document.addEventListener("DOMContentLoaded", () => { }) ); + // 3D. Auto-refund demo: debit -> simulated tool failure -> refund with the same idempotency key + const btnQuotaRefundDemo = document.getElementById("btnQuotaRefundDemo"); + btnQuotaRefundDemo.addEventListener("click", () => + withButtonLock(btnQuotaRefundDemo, "Simulating...", async () => { + const key = quotaKey.value.trim(); + const credits = parseInt(quotaCredits.value || "5", 10); + const idem = "ui_refund_" + crypto.randomUUID(); + const post = async (path, body) => { + const res = await fetch(path, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + return { res, data: await res.json() }; + }; + try { + const d = await post("/api/v1/quota/deduct", { + license_key: key, credits, idempotency_key: idem, event_type: "console_refund_demo", + }); + if (!d.res.ok) { + renderBox(quotaResult, d.data, classifyResponse(d.res, d.data)); + return; + } + const afterDebit = d.data.data.remaining_balance ?? d.data.data.credit_balance; + const r = await post("/api/v1/quota/refund", { + license_key: key, idempotency_key: idem, reason: "simulated tool failure (isError: true)", + }); + if (!r.res.ok) { + renderBox(quotaResult, r.data, classifyResponse(r.res, r.data)); + return; + } + const afterRefund = r.data.data.remaining_balance; + renderBox(quotaResult, { + "1_debit": { credits, idempotency_key: idem, balance: afterDebit }, + "2_tool_call": { isError: true, content: "Simulated failure: the tool raised an exception" }, + "3_auto_refund": { refunded: r.data.data.refunded, balance: afterRefund }, + balance_before: afterDebit + credits, + balance_after: afterRefund, + restored: afterRefund === afterDebit + credits, + }, "ok"); + await refreshTelemetry(key); + } catch (err) { + renderBox(quotaResult, { error: err.message }, "err"); + } + }) + ); + // 4. Simulate Signed Webhook const btnSimulate = document.getElementById("btnSimulate"); const simResult = document.getElementById("simResult"); @@ -788,7 +837,7 @@ kf = KeyFlint() # reads KEYFLINT_LICENSE, KEYFLINT_PUBLIC_K "ts-mcp": `import { createKeyFlint } from "keyflint-verify/mcp"; -const kf = createKeyFlint({ gatewayUrl: "https://licenses.tu-dominio.com" }); +const kf = createKeyFlint({ gatewayUrl: "https://licenses.your-domain.com" }); // Atomic per-call debit in @modelcontextprotocol/sdk server.tool("audit_code", schema, kf.metered(2, async (args) => { @@ -862,8 +911,8 @@ fmt.Println(payload.Tier, payload.Features)` const btnCopyGenerated = document.getElementById("btnCopyGenerated"); function buildSnippet(lang, credits, pub, gateway) { - const key = /^[0-9a-fA-F]{64}$/.test(pub) ? pub.toLowerCase() : "PEGA_AQUI_TU_CLAVE_PUBLICA_HEX"; - const gw = gateway || "https://licencias.tu-dominio.com"; + const key = /^[0-9a-fA-F]{64}$/.test(pub) ? pub.toLowerCase() : "PASTE_YOUR_PUBLIC_KEY_HEX"; + const gw = gateway || "https://licenses.your-domain.com"; const n = Number.isInteger(credits) && credits > 0 ? credits : 0; if (lang === "ts") { const wrap = n ? `kf.metered(${n}, async ({ query }: { query: string }) => {` : "kf.requireLicense(async ({ query }: { query: string }) => {"; @@ -875,10 +924,10 @@ fmt.Println(payload.Tier, payload.Features)` 'import { createKeyFlint } from "keyflint-verify/mcp";', "", `const kf = createKeyFlint({ publicKeys: ${JSON.stringify(key)}${n ? `, gatewayUrl: ${JSON.stringify(gw)}` : ""} });`, - 'const server = new McpServer({ name: "mi-herramienta", version: "1.0.0" });', + 'const server = new McpServer({ name: "my-tool", version: "1.0.0" });', "", n ? `// ${n} credit(s) per call; refunded if the tool fails` : "// License only (offline)", - 'server.registerTool("buscar", { inputSchema: { query: z.string() } }, ' + wrap, + 'server.registerTool("search", { inputSchema: { query: z.string() } }, ' + wrap, ' return { content: [{ type: "text" as const, text: `Result for ${query}` }] };', "}));", "", @@ -916,12 +965,12 @@ fmt.Println(payload.Tier, payload.Features)` "from keyflint_verify.mcp import KeyFlint", "", `kf = KeyFlint(public_keys=${JSON.stringify(key)}${n ? `, gateway_url=${JSON.stringify(gw)}` : ""})`, - 'mcp = FastMCP("mi-herramienta")', + 'mcp = FastMCP("my-tool")', "", n ? `# ${n} credit(s) per call; refunded if the tool fails` : "# License only (offline)", "@mcp.tool()", n ? `@kf.metered(credits=${n})` : "@kf.require_license", - "def buscar(query: str) -> str:", + "def search(query: str) -> str:", ' return f"Result for {query}"', "", 'if __name__ == "__main__":', @@ -929,8 +978,16 @@ fmt.Println(payload.Tier, payload.Features)` ].join("\n"); } + const genPubKeyHint = document.getElementById("genPubKeyHint"); function renderGenerated() { if (!genOutput) return; + const pub = genPubKey.value.trim(); + const badKey = pub !== "" && !/^[0-9a-fA-F]{64}$/.test(pub); + genPubKey.setAttribute("aria-invalid", badKey ? "true" : "false"); + if (genPubKeyHint) { + genPubKeyHint.hidden = !badKey; + genPubKeyHint.textContent = `Must be exactly 64 hex characters (0-9, a-f); got ${pub.length}. Using a placeholder until it is valid.`; + } genOutput.textContent = buildSnippet( genLang.value, parseInt(genCredits.value, 10), diff --git a/docs/demo-api.js b/docs/demo-api.js index bf5440a..77e4d36 100644 --- a/docs/demo-api.js +++ b/docs/demo-api.js @@ -10,7 +10,7 @@ community: { seats: 1, credits: 25, recurring: false }, indie: { seats: 3, credits: 10000, recurring: false }, agency: { seats: 25, credits: 50000, recurring: false }, - pro: { seats: 3, credits: 500, recurring: true }, + pro: { seats: 3, credits: 1000, recurring: true }, studio: { seats: 25, credits: 5000, recurring: true }, lifetime: { seats: 3, credits: 10000, recurring: false }, }; @@ -77,7 +77,7 @@ const license_key = `LIC-${t.toUpperCase()}-${b64url(body)}.${b64url(sig)}`; const rec = { license_key, payload, algo, status: "active", balance: spec.credits, - activations: new Map(), idem: new Set(), created_at: nowIso(), + activations: new Map(), idem: new Map(), refunded: new Set(), created_at: nowIso(), }; licenses.set(license_key, rec); log(rec, "license_issued", { tier: t, signing_algorithm: algo }); @@ -187,10 +187,23 @@ if (rec.balance < credits) { return fail(402, "ERR_QUOTA_EXHAUSTED", `Insufficient balance: ${rec.balance} credits left.`); } - rec.idem.add(b.idempotency_key); + rec.idem.set(b.idempotency_key, credits); rec.balance -= credits; log(rec, "quota_deducted", { credits, idempotency_key: b.idempotency_key }); - return ok({ deducted: credits, credit_balance: rec.balance, idempotency_key: b.idempotency_key }); + return ok({ deducted: credits, remaining_balance: rec.balance, credit_balance: rec.balance, idempotency_key: b.idempotency_key }); + }, + "POST /api/v1/quota/refund": async (b) => { + const rec = find(b.license_key); + if (!rec) return notFound(); + const credits = rec.idem.get(b.idempotency_key); + if (credits === undefined) return fail(404, "ERR_DEDUCT_NOT_FOUND", "No debit found for that idempotency key."); + if (rec.refunded.has(b.idempotency_key)) { + return ok({ refunded: 0, is_cached: true, remaining_balance: rec.balance, idempotency_key: b.idempotency_key }); + } + rec.refunded.add(b.idempotency_key); + rec.balance += credits; + log(rec, "quota_refunded", { credits, idempotency_key: b.idempotency_key, reason: b.reason || null }); + return ok({ refunded: credits, remaining_balance: rec.balance, idempotency_key: b.idempotency_key }); }, "POST /api/v1/quota/replenish": async (b) => { const rec = find(b.license_key); diff --git a/docs/index.html b/docs/index.html index 94d86c2..c30573b 100644 --- a/docs/index.html +++ b/docs/index.html @@ -244,6 +244,8 @@ .code-box.state-warn::before { content: "AVISO"; color: var(--warn); } .code-box.state-err { border-left-color: var(--err); background: color-mix(in srgb, var(--err-bg) 45%, var(--code-bg)); } .code-box.state-err::before { content: "ERROR"; color: var(--err); } + .field-hint { display: block; margin-top: 8px; font-size: 12px; color: var(--err); } + input[aria-invalid="true"] { border-color: var(--err); } .code-box.is-idle { border-left-color: var(--line-strong); color: var(--muted); } .code-box.is-idle::before { content: "ESPERANDO"; color: var(--muted); } @keyframes reveal { from { opacity: 0; transform: translateY(-2px); } to { opacity: 1; transform: none; } } @@ -628,7 +630,8 @@

3-step generator

- + +
@@ -727,7 +730,7 @@

Verify, activate and revoke

Credit quota

-

Atomic debit; every operation carries its own idempotency key.

+

Atomic debit; every operation carries its own idempotency key. "Simulate failed call" shows the automatic refund.

3
@@ -743,6 +746,7 @@

Credit quota

+