Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(knock): ship the door page and its client

nirholas3a89337dfd91
diff --git a/pages/knock-door.html b/pages/knock-door.html
new file mode 100644
index 000000000..480cc0dfb
--- /dev/null
+++ b/pages/knock-door.html
@@ -0,0 +1,208 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <style>/* three.ws hidden-guard - make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>
+ <script>/* three.ws theme boot */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Knock · three.ws</title>
+ <meta name="description" content="Pay someone's price and get one message through to them. Their 3D companion walks on screen and delivers it in person, with your name and what you paid." />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Knock · three.ws">
+ <meta property="og:description" content="Pay someone's price and get one message through. Their 3D companion delivers it in person.">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
+ <meta name="robots" content="noindex, follow">
+ <meta property="og:locale" content="en_US">
+ <style>
+ :root{--bg:#0d0d0d;--bg-2:#141414;--card:#181818;--line:rgba(255,255,255,0.07);--line-2:rgba(255,255,255,0.12);--text:#e7e9ee;--muted:rgba(231,233,238,0.55);--dim:rgba(231,233,238,0.35);--blue:#3b82f6;--green:#22c55e;--amber:#f59e0b;--red:#ef4444;--radius:14px;--skeleton-base:rgba(255,255,255,0.04);--skeleton-sheen:rgba(255,255,255,0.08);}
+ [data-theme="light"]{--bg:#f5f5f5;--bg-2:#ffffff;--card:#ffffff;--line:rgba(0,0,0,0.07);--line-2:rgba(0,0,0,0.12);--text:#111;--muted:rgba(0,0,0,0.55);--dim:rgba(0,0,0,0.35);--skeleton-base:rgba(0,0,0,0.04);--skeleton-sheen:rgba(0,0,0,0.08);}
+ *{box-sizing:border-box;margin:0;padding:0;}
+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}
+ a{color:inherit;text-decoration:none;}
+ .shell{max-width:760px;margin:0 auto;padding:0 20px 120px;}
+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:13px;font-weight:600;padding:9px 15px;border-radius:9px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s,transform .1s;font-family:inherit;}
+ .btn:hover{border-color:var(--blue);}
+ .btn:active{transform:translateY(1px);}
+ .btn:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}
+ .btn[disabled]{opacity:.5;cursor:not-allowed;}
+ .btn.is-ok{border-color:var(--green);color:var(--green);}
+ .btn-primary{background:var(--blue);border-color:var(--blue);color:#fff;}
+ .btn-primary:hover{background:#2f74e6;}
+ .btn-sm{font-size:12px;padding:6px 11px;}
+ .btn-lg{font-size:14px;padding:12px 20px;width:100%;}
+ .card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:22px;}
+ .skeleton{background:linear-gradient(90deg,var(--skeleton-base) 25%,var(--skeleton-sheen) 37%,var(--skeleton-base) 63%);background-size:400% 100%;animation:sheen 1.3s ease infinite;border-radius:8px;}
+ @keyframes sheen{0%{background-position:100% 50%}100%{background-position:0 50%}}
+ .sk-row{height:14px;margin-bottom:10px;}
+ .who{display:flex;align-items:center;gap:14px;margin-bottom:18px;}
+ .face{width:56px;height:56px;border-radius:50%;overflow:hidden;background:var(--bg-2);border:1px solid var(--line-2);flex-shrink:0;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:22px;color:var(--muted);}
+ .face::after{content:attr(data-initial);}
+ .face:has(img:not([hidden]))::after{content:none;}
+ .face img{width:100%;height:100%;object-fit:cover;}
+ .who-text h1{font-size:21px;font-weight:700;letter-spacing:-0.02em;line-height:1.25;}
+ .who-text a{color:var(--muted);font-size:13px;}
+ .who-text a:hover{color:var(--blue);}
+ .verified{color:var(--blue);font-size:13px;margin-left:5px;}
+ .price{margin-left:auto;text-align:right;flex-shrink:0;}
+ .price-badge{display:inline-block;font-size:19px;font-weight:700;letter-spacing:-0.02em;padding:5px 12px;border-radius:999px;background:rgba(59,130,246,.14);color:var(--blue);border:1px solid rgba(59,130,246,.3);}
+ .price-badge.is-free{background:rgba(34,197,94,.14);color:var(--green);border-color:rgba(34,197,94,.3);}
+ .headline{font-size:15px;font-weight:600;margin-bottom:6px;}
+ .greeting{color:var(--muted);font-size:14px;line-height:1.6;white-space:pre-wrap;}
+ .price-note{color:var(--dim);font-size:12.5px;margin-top:14px;padding-top:14px;border-top:1px solid var(--line);line-height:1.55;}
+ form{margin-top:18px;display:grid;gap:14px;}
+ label{display:grid;gap:6px;font-size:12.5px;font-weight:600;color:var(--muted);}
+ input,textarea{width:100%;background:var(--bg-2);border:1px solid var(--line-2);border-radius:9px;padding:10px 12px;color:var(--text);font-family:inherit;font-size:14px;transition:border-color .15s;}
+ input:focus,textarea:focus{outline:none;border-color:var(--blue);}
+ textarea{min-height:130px;resize:vertical;line-height:1.55;}
+ .row{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
+ .counter{font-size:11.5px;color:var(--dim);text-align:right;font-variant-numeric:tabular-nums;}
+ .counter.is-full{color:var(--amber);}
+ .error{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);color:#fca5a5;border-radius:9px;padding:10px 13px;font-size:13px;}
+ .sent{border:1px solid rgba(34,197,94,.35);background:rgba(34,197,94,.07);border-radius:var(--radius);padding:20px;margin-top:18px;}
+ .sent h2{font-size:16px;font-weight:700;margin-bottom:6px;}
+ .sent p{color:var(--muted);font-size:13.5px;line-height:1.6;}
+ .receipt{display:block;background:var(--bg-2);border:1px solid var(--line-2);border-radius:9px;padding:9px 11px;font-size:11.5px;word-break:break-all;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);margin:12px 0;}
+ .reply-box{background:var(--bg-2);border:1px solid var(--line-2);border-left:3px solid var(--blue);border-radius:9px;padding:11px 13px;font-size:13.5px;line-height:1.6;margin-top:12px;white-space:pre-wrap;}
+ .sent-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:4px;}
+ details.agents{margin-top:26px;border:1px solid var(--line);border-radius:var(--radius);background:var(--card);overflow:hidden;}
+ details.agents summary{cursor:pointer;padding:15px 20px;font-size:13.5px;font-weight:600;list-style:none;display:flex;align-items:center;justify-content:space-between;gap:10px;}
+ details.agents summary::-webkit-details-marker{display:none;}
+ details.agents summary::after{content:'+';color:var(--muted);font-size:17px;font-weight:400;}
+ details.agents[open] summary::after{content:'\2212';}
+ details.agents summary:hover{background:var(--bg-2);}
+ details.agents summary:focus-visible{outline:2px solid var(--blue);outline-offset:-2px;}
+ .agents-body{padding:0 20px 20px;display:grid;gap:16px;}
+ .agents-body h3{font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--dim);margin-bottom:7px;}
+ pre{background:var(--bg-2);border:1px solid var(--line);border-radius:10px;padding:12px 14px;font-size:11.5px;line-height:1.65;overflow-x:auto;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);white-space:pre;}
+ code.inline{background:var(--bg-2);border:1px solid var(--line);border-radius:7px;padding:7px 10px;font-size:11.5px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all;display:block;color:var(--muted);}
+ .snip-head{display:flex;align-items:center;justify-content:space-between;gap:10px;}
+ .empty{text-align:center;padding:60px 20px;}
+ .empty h2{font-size:18px;font-weight:700;margin-bottom:8px;}
+ .empty p{color:var(--muted);font-size:14px;line-height:1.6;max-width:420px;margin:0 auto 18px;}
+ .foot-note{color:var(--dim);font-size:12px;text-align:center;margin-top:26px;line-height:1.6;}
+ .foot-note a{color:var(--muted);text-decoration:underline;text-underline-offset:2px;}
+ .foot-note a:hover{color:var(--blue);}
+ @media(max-width:560px){.row{grid-template-columns:1fr;}.who{flex-wrap:wrap;}.price{margin-left:0;width:100%;text-align:left;}}
+ @media(prefers-reduced-motion:reduce){.skeleton{animation:none;}}
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="shell">
+ <div id="loading" class="card" style="margin-top:40px;" aria-live="polite" aria-busy="true">
+ <div class="skeleton sk-row" style="width:45%;height:22px;"></div>
+ <div class="skeleton sk-row" style="width:70%;"></div>
+ <div class="skeleton sk-row" style="width:60%;"></div>
+ <span class="sr-only" style="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);">Loading this door</span>
+ </div>
+
+ <div id="not-found" class="empty" hidden>
+ <h2>No answer</h2>
+ <p data-msg></p>
+ <a class="btn" href="/knock">See who is open</a>
+ </div>
+
+ <section id="door-card" class="card" style="margin-top:40px;" hidden>
+ <div class="who">
+ <div class="face" data-initial="?"><img id="avatar" alt="" hidden /></div>
+ <div class="who-text">
+ <h1><span id="display-name"></span><span class="verified" id="verified" hidden title="Verified">&#10003;</span></h1>
+ <a id="handle" href="#"></a>
+ </div>
+ <div class="price"><span class="price-badge" id="price-badge"></span></div>
+ </div>
+
+ <p class="headline" id="headline" hidden></p>
+ <p class="greeting" id="greeting" hidden></p>
+ <p class="price-note" id="price-note"></p>
+
+ <form id="form" novalidate>
+ <div class="row">
+ <label>Who are you
+ <input id="from" type="text" maxlength="64" required autocomplete="name" placeholder="Ada, or Ada's research agent" />
+ </label>
+ <label>Link (optional)
+ <input id="url" type="url" maxlength="400" placeholder="https://" />
+ </label>
+ </div>
+ <label>One line they will hear out loud (optional)
+ <input id="subject" type="text" maxlength="120" placeholder="Why you are knocking, in a few words" />
+ </label>
+ <label>Your message
+ <textarea id="message" required placeholder="This is shown to them in full. Only the line above is spoken."></textarea>
+ <span class="counter" id="counter">0 / 600</span>
+ </label>
+ <div class="error" id="form-error" hidden></div>
+ <button type="submit" class="btn btn-primary btn-lg" id="submit">Knock</button>
+ </form>
+
+ <div class="sent" id="sent" hidden>
+ <h2>Through the door</h2>
+ <p id="sent-line"></p>
+ <code class="receipt" id="receipt-url" hidden></code>
+ <div class="reply-box" id="reply-box" hidden></div>
+ <div class="sent-actions">
+ <button type="button" class="btn btn-sm" id="copy-receipt" hidden>Copy receipt link</button>
+ <button type="button" class="btn btn-sm" id="check-reply" hidden>Check for a reply</button>
+ <button type="button" class="btn btn-sm" id="knock-again">Knock again</button>
+ </div>
+ </div>
+ </section>
+
+ <details class="agents" id="agent-panel">
+ <summary>Reach this person from an agent</summary>
+ <div class="agents-body">
+ <div>
+ <div class="snip-head">
+ <h3>Endpoint</h3>
+ <button type="button" class="btn btn-sm" id="copy-endpoint">Copy</button>
+ </div>
+ <code class="inline" id="agent-endpoint"></code>
+ </div>
+ <div>
+ <div class="snip-head">
+ <h3>curl</h3>
+ <button type="button" class="btn btn-sm" data-copy-target="curl-snippet">Copy</button>
+ </div>
+ <pre id="curl-snippet"></pre>
+ </div>
+ <div>
+ <div class="snip-head">
+ <h3>SDK</h3>
+ <button type="button" class="btn btn-sm" data-copy-target="sdk-snippet">Copy</button>
+ </div>
+ <pre id="sdk-snippet"></pre>
+ </div>
+ <div>
+ <div class="snip-head">
+ <h3>MCP (Claude, Cursor, any MCP client)</h3>
+ <button type="button" class="btn btn-sm" data-copy-target="mcp-snippet">Copy</button>
+ </div>
+ <pre id="mcp-snippet"></pre>
+ </div>
+ </div>
+ </details>
+
+ <p class="foot-note">
+ Knock is a priced door to a person. The money settles straight to them, never to three.ws.
+ <a href="/docs/knock">How it works</a> &middot; <a href="/knock">Open your own door</a>
+ </p>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/x402.js"></script>
+ <script type="module" src="/src/knock/door.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/src/knock/api.js b/src/knock/api.js
new file mode 100644
index 000000000..d9da43419
--- /dev/null
+++ b/src/knock/api.js
@@ -0,0 +1,67 @@
+// Client for /api/knock/*.
+//
+// Two audiences, one file. The owner-side calls go through apiFetch (session
+// cookie, CSRF on writes, redirect on an expired session, src/api.js). The
+// public calls (a door, the directory, sending a free knock, reading a receipt)
+// use plain fetch on purpose: the door page has to work for a visitor with no
+// account, and pulling the auth layer in would make an anonymous read look like
+// a signed-out error.
+
+import { apiFetch } from '../api.js';
+
+async function unwrap(res) {
+ const text = await res.text();
+ let data = null;
+ if (text) {
+ try {
+ data = JSON.parse(text);
+ } catch {
+ data = null;
+ }
+ }
+ if (!res.ok) {
+ const err = new Error(data?.error_description || data?.message || `request failed (${res.status})`);
+ err.status = res.status;
+ err.code = data?.error || data?.code || null;
+ err.data = data;
+ throw err;
+ }
+ return data;
+}
+
+async function authed(path, { method = 'GET', body = null } = {}) {
+ return unwrap(
+ await apiFetch(path, {
+ method,
+ ...(body ? { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } : {}),
+ }),
+ );
+}
+
+async function open(path, { method = 'GET', body = null } = {}) {
+ return unwrap(
+ await fetch(path, {
+ method,
+ ...(body ? { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) } : {}),
+ }),
+ );
+}
+
+export const knockApi = {
+ // Public
+ door: (handle) => open(`/api/knock/door?handle=${encodeURIComponent(handle)}`),
+ directory: (limit = 60) => open(`/api/knock/directory?limit=${limit}`),
+ send: (body) => open('/api/knock/send', { method: 'POST', body }),
+ receipt: (url) => open(url.replace(/^https?:\/\/[^/]+/, '')),
+
+ // Owner
+ settings: () => authed('/api/knock/settings'),
+ saveSettings: (patch) => authed('/api/knock/settings', { method: 'PATCH', body: patch }),
+ inbox: ({ limit = 30, before = null, status = null } = {}) => {
+ const params = new URLSearchParams({ limit: String(limit) });
+ if (before) params.set('before', before);
+ if (status) params.set('status', status);
+ return authed(`/api/knock/inbox?${params.toString()}`);
+ },
+ actOn: (id, patch) => authed(`/api/knock/inbox/${encodeURIComponent(id)}`, { method: 'PATCH', body: patch }),
+};
diff --git a/src/knock/door.js b/src/knock/door.js
new file mode 100644
index 000000000..ec400ee8c
--- /dev/null
+++ b/src/knock/door.js
@@ -0,0 +1,305 @@
+// The public door page: /knock/<handle>.
+//
+// One job, done for two very different visitors. A person reads who they are
+// about to interrupt and what it costs, writes a message, and pays with the
+// wallet they already have in this browser. An agent lands here to learn the
+// endpoint, the price and the schema, then never opens the page again.
+//
+// Both get the same truth from GET /api/knock/door, so the page can never
+// advertise a price the API would not charge.
+//
+// Payment is the browser x402 checkout (window.X402.pay, /x402.js), the same
+// modal the club cover and the billboard use. It settles the USDC directly to
+// the door owner and returns the endpoint's own JSON, which is the accepted
+// knock plus its receipt URL.
+
+import { knockApi } from './api.js';
+
+const els = {};
+let door = null;
+let lastReceiptUrl = null;
+
+document.addEventListener('DOMContentLoaded', () => {
+ for (const id of [
+ 'loading', 'not-found', 'door-card', 'avatar', 'display-name', 'handle', 'verified',
+ 'headline', 'greeting', 'price-badge', 'price-note', 'form', 'from', 'subject',
+ 'message', 'url', 'counter', 'submit', 'form-error', 'sent', 'sent-line', 'receipt-url',
+ 'copy-receipt', 'check-reply', 'reply-box', 'knock-again', 'agent-panel', 'agent-endpoint',
+ 'curl-snippet', 'sdk-snippet', 'mcp-snippet', 'copy-endpoint',
+ ]) {
+ els[id] = document.getElementById(id);
+ }
+
+ bind();
+ load();
+});
+
+function handleFromPath() {
+ const fromPath = decodeURIComponent(window.location.pathname.replace(/^\/knock\/?/, '')).trim();
+ if (fromPath) return fromPath;
+ return new URLSearchParams(window.location.search).get('to') || '';
+}
+
+async function load() {
+ const handle = handleFromPath();
+ if (!handle) return showNotFound('No handle in this link. Try /knock and pick a door.');
+
+ try {
+ const data = await knockApi.door(handle);
+ door = data.door;
+ render();
+ } catch (err) {
+ showNotFound(
+ err.status === 404
+ ? `Nobody is answering at @${handle}. They may not have opened a door yet.`
+ : err.message,
+ );
+ }
+}
+
+function showNotFound(message) {
+ els.loading.hidden = true;
+ els['not-found'].hidden = false;
+ els['not-found'].querySelector('[data-msg]').textContent = message;
+}
+
+function render() {
+ els.loading.hidden = true;
+ els['door-card'].hidden = false;
+
+ document.title = `Knock on ${door.display_name} · three.ws`;
+ els['display-name'].textContent = door.display_name;
+ els.handle.textContent = `@${door.handle}`;
+ els.handle.href = `/u/${door.handle}`;
+ els.verified.hidden = !door.verified;
+
+ if (door.avatar_url) {
+ els.avatar.src = door.avatar_url;
+ els.avatar.alt = `${door.display_name}'s avatar`;
+ els.avatar.hidden = false;
+ } else {
+ // No avatar is still a designed state: the initial keeps the layout
+ // stable instead of leaving a hole where a face should be.
+ els.avatar.hidden = true;
+ els.avatar.parentElement.dataset.initial = (door.display_name || '?').slice(0, 1).toUpperCase();
+ }
+
+ els.headline.textContent = door.headline || '';
+ els.headline.hidden = !door.headline;
+ els.greeting.textContent = door.greeting || '';
+ els.greeting.hidden = !door.greeting;
+
+ els['price-badge'].textContent = door.free ? 'Free' : door.price;
+ els['price-badge'].classList.toggle('is-free', door.free);
+ els['price-note'].textContent = door.free
+ ? 'This door is open to anyone. One message, no payment.'
+ : `${door.price} USDC on ${door.networks.join(' or ')}, settled straight to ${door.display_name}. One message.`;
+
+ els.message.maxLength = door.max_chars;
+ updateCounter();
+ els.submit.textContent = door.free ? 'Knock' : `Pay ${door.price} and knock`;
+
+ renderAgentPanel();
+}
+
+function renderAgentPanel() {
+ const endpoint = door.endpoint;
+ els['agent-endpoint'].textContent = endpoint;
+ els['copy-endpoint'].dataset.copy = endpoint;
+
+ const example = {
+ from: 'Your agent',
+ subject: 'One line they will hear out loud',
+ message: 'What you actually want to say.',
+ };
+
+ els['curl-snippet'].textContent = door.free
+ ? `curl -X POST ${endpoint} \\\n -H 'content-type: application/json' \\\n -d '${JSON.stringify({ to: door.handle, ...example })}'`
+ : `# 402 first, then pay and retry. Any x402 client does both steps.\ncurl -i -X POST '${endpoint}' \\\n -H 'content-type: application/json' \\\n -d '${JSON.stringify(example)}'`;
+
+ els['sdk-snippet'].textContent = [
+ "import { knock } from '@three-ws/knock';",
+ '',
+ 'const receipt = await knock({',
+ ` to: '${door.handle}',`,
+ " from: 'Your agent',",
+ " message: 'What you actually want to say.',",
+ ' wallet, // a Solana signer you already have',
+ ' confirm: true, // shows the price and asks before it pays',
+ '});',
+ '',
+ 'console.log(receipt.receipt_url); // poll this for a reply',
+ ].join('\n');
+
+ els['mcp-snippet'].textContent = [
+ '{',
+ ' "mcpServers": {',
+ ' "knock": {',
+ ' "command": "npx",',
+ ' "args": ["-y", "@three-ws/knock-mcp"]',
+ ' }',
+ ' }',
+ '}',
+ ].join('\n');
+}
+
+function updateCounter() {
+ const max = door?.max_chars ?? 600;
+ const used = els.message.value.length;
+ els.counter.textContent = `${used} / ${max}`;
+ els.counter.classList.toggle('is-full', used >= max);
+}
+
+function bind() {
+ els.message?.addEventListener('input', updateCounter);
+ els.form?.addEventListener('submit', onSubmit);
+ els['knock-again']?.addEventListener('click', () => {
+ els.sent.hidden = true;
+ els.form.hidden = false;
+ els.message.value = '';
+ els.subject.value = '';
+ updateCounter();
+ els.from.focus();
+ });
+ els['check-reply']?.addEventListener('click', checkReply);
+ for (const btn of document.querySelectorAll('[data-copy-target], [data-copy]')) {
+ btn.addEventListener('click', () => copy(btn));
+ }
+ // Cmd/Ctrl+Enter sends, because everyone tries it in a message box.
+ els.message?.addEventListener('keydown', (e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') els.form.requestSubmit();
+ });
+}
+
+async function copy(btn) {
+ const text = btn.dataset.copy || document.getElementById(btn.dataset.copyTarget)?.textContent || '';
+ if (!text) return;
+ try {
+ await navigator.clipboard.writeText(text);
+ const original = btn.textContent;
+ btn.textContent = 'Copied';
+ btn.classList.add('is-ok');
+ setTimeout(() => {
+ btn.textContent = original;
+ btn.classList.remove('is-ok');
+ }, 1400);
+ } catch {
+ // Clipboard blocked (insecure context, denied permission). Select the
+ // text instead so the visitor can copy it by hand rather than get
+ // nothing at all.
+ const target = document.getElementById(btn.dataset.copyTarget);
+ if (target) window.getSelection()?.selectAllChildren(target);
+ }
+}
+
+function payload() {
+ const body = {
+ from: els.from.value.trim(),
+ message: els.message.value.trim(),
+ sender_kind: 'human',
+ };
+ if (els.subject.value.trim()) body.subject = els.subject.value.trim();
+ if (els.url.value.trim()) body.url = els.url.value.trim();
+ return body;
+}
+
+async function onSubmit(e) {
+ e.preventDefault();
+ setError('');
+ const body = payload();
+ if (body.message.length < 8) return setError('Say at least 8 characters.');
+ if (!body.from) return setError('Tell them who you are.');
+
+ els.submit.disabled = true;
+ const label = els.submit.textContent;
+ els.submit.textContent = door.free ? 'Knocking…' : 'Opening wallet…';
+
+ try {
+ const result = door.free
+ ? await knockApi.send({ to: door.handle, ...body })
+ : await payAndKnock(body);
+ showSent(result);
+ } catch (err) {
+ setError(friendlyError(err));
+ } finally {
+ els.submit.disabled = false;
+ els.submit.textContent = label;
+ }
+}
+
+async function payAndKnock(body) {
+ if (!window.X402?.pay) {
+ throw new Error('The payment widget is still loading. Give it a second and try again.');
+ }
+ const out = await window.X402.pay({
+ endpoint: door.endpoint,
+ method: 'POST',
+ body,
+ merchant: `three.ws Knock`,
+ action: `Knock on ${door.display_name} (${door.price})`,
+ autoConnect: true,
+ autoClose: true,
+ });
+ const result = out?.result;
+ if (!result?.ok) throw new Error(result?.error_description || result?.error || 'the payment did not settle');
+ return result;
+}
+
+function friendlyError(err) {
+ const map = {
+ door_closed: 'This door just closed.',
+ door_full: 'This door has taken all the knocks it accepts today. Try tomorrow.',
+ message_too_long: `Trim it to ${door?.max_chars ?? 600} characters.`,
+ message_too_short: 'Say at least 8 characters.',
+ bad_url: 'That link needs to be a plain http(s) URL.',
+ payment_required: 'This door charges now. Reload the page to see the price.',
+ };
+ if (err.status === 429) return 'Too many knocks from here for now. Try again a bit later.';
+ return map[err.code] || err.message || 'That did not go through.';
+}
+
+function setError(message) {
+ els['form-error'].textContent = message;
+ els['form-error'].hidden = !message;
+}
+
+function showSent(result) {
+ els.form.hidden = true;
+ els.sent.hidden = false;
+ lastReceiptUrl = result.receipt_url || null;
+ els['sent-line'].textContent = result.duplicate
+ ? `Already delivered. ${door.display_name} has this one.`
+ : `Delivered. ${door.display_name}'s companion will walk on and say who you are.`;
+ els['receipt-url'].textContent = lastReceiptUrl || '';
+ els['receipt-url'].hidden = !lastReceiptUrl;
+ els['copy-receipt'].dataset.copy = lastReceiptUrl || '';
+ els['copy-receipt'].hidden = !lastReceiptUrl;
+ els['check-reply'].hidden = !lastReceiptUrl;
+ els['reply-box'].hidden = true;
+ els.sent.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+}
+
+async function checkReply() {
+ if (!lastReceiptUrl) return;
+ els['check-reply'].disabled = true;
+ const label = els['check-reply'].textContent;
+ els['check-reply'].textContent = 'Checking…';
+ try {
+ const { knock } = await knockApi.receipt(lastReceiptUrl);
+ els['reply-box'].hidden = false;
+ els['reply-box'].textContent =
+ knock.status === 'replied'
+ ? knock.reply
+ : knock.status === 'dismissed'
+ ? 'They read it and moved on. No reply.'
+ : knock.seen
+ ? 'Read. No reply written yet.'
+ : 'Not opened yet.';
+ } catch {
+ els['reply-box'].hidden = false;
+ els['reply-box'].textContent = 'Could not reach the receipt just now. Try again shortly.';
+ } finally {
+ els['check-reply'].disabled = false;
+ els['check-reply'].textContent = label;
+ }
+}
diff --git a/src/knock/page.js b/src/knock/page.js
new file mode 100644
index 000000000..5cabbd36e
--- /dev/null
+++ b/src/knock/page.js
@@ -0,0 +1,415 @@
+// The /knock hub: your own door, the knocks it has taken, and everyone else's.
+//
+// Signed out, this page is a directory: who is reachable and for how much. The
+// directory is public on purpose, because a door nobody can find is not a door.
+//
+// Signed in, the same page grows the owner half: the price, the wallet the
+// money lands in, the share link, the inbox, and the block list. Everything
+// saves through PATCH /api/knock/settings, which refuses to open a priced door
+// with no payout address, so the UI never has to guess whether a save was safe.
+
+import { knockApi } from './api.js';
+
+const els = {};
+let state = { door: null, handle: null, url: null, totals: null, blocks: [], knocks: [], loadingMore: false };
+
+document.addEventListener('DOMContentLoaded', () => {
+ for (const id of [
+ 'directory', 'directory-empty', 'directory-loading', 'owner', 'owner-loading', 'signed-out',
+ 'door-open', 'door-price', 'door-solana', 'door-base', 'door-headline', 'door-greeting',
+ 'door-max', 'door-cap', 'door-listed', 'save', 'save-note', 'settings-error',
+ 'share-url', 'copy-share', 'share-block', 'endpoint-url', 'copy-endpoint',
+ 'stat-pending', 'stat-total', 'stat-earned', 'inbox', 'inbox-empty', 'inbox-loading',
+ 'load-more', 'blocks', 'blocks-empty', 'no-handle',
+ ]) {
+ els[id] = document.getElementById(id);
+ }
+ bind();
+ loadDirectory();
+ loadOwner();
+});
+
+// ── Directory (public) ──────────────────────────────────────────────────────
+
+async function loadDirectory() {
+ try {
+ const { doors } = await knockApi.directory(60);
+ els['directory-loading'].hidden = true;
+ if (!doors.length) {
+ els['directory-empty'].hidden = false;
+ return;
+ }
+ els.directory.hidden = false;
+ els.directory.replaceChildren(...doors.map(doorCard));
+ } catch {
+ els['directory-loading'].hidden = true;
+ els['directory-empty'].hidden = false;
+ els['directory-empty'].querySelector('[data-msg]').textContent =
+ 'The directory could not be reached. Reload to try again.';
+ }
+}
+
+function doorCard(door) {
+ const a = document.createElement('a');
+ a.className = 'door-card';
+ a.href = `/knock/${encodeURIComponent(door.handle)}`;
+ const face = document.createElement('div');
+ face.className = 'face';
+ face.dataset.initial = (door.display_name || door.handle).slice(0, 1).toUpperCase();
+ if (door.avatar_url) {
+ const img = document.createElement('img');
+ img.src = door.avatar_url;
+ img.alt = '';
+ img.loading = 'lazy';
+ face.appendChild(img);
+ }
+ const body = document.createElement('div');
+ body.className = 'door-card-body';
+ const name = document.createElement('div');
+ name.className = 'door-card-name';
+ name.textContent = door.display_name;
+ const handle = document.createElement('div');
+ handle.className = 'door-card-handle';
+ handle.textContent = `@${door.handle}`;
+ body.append(name, handle);
+ if (door.headline) {
+ const head = document.createElement('div');
+ head.className = 'door-card-headline';
+ head.textContent = door.headline;
+ body.appendChild(head);
+ }
+ const price = document.createElement('span');
+ price.className = `door-card-price${door.price_atomics === '0' ? ' is-free' : ''}`;
+ price.textContent = door.price_atomics === '0' ? 'Free' : door.price;
+ a.append(face, body, price);
+ return a;
+}
+
+// ── Owner half ──────────────────────────────────────────────────────────────
+
+async function loadOwner() {
+ try {
+ const data = await knockApi.settings();
+ applyOwner(data);
+ els['owner-loading'].hidden = true;
+ els.owner.hidden = false;
+ await loadInbox();
+ } catch (err) {
+ els['owner-loading'].hidden = true;
+ if (err.status === 401) {
+ els['signed-out'].hidden = false;
+ return;
+ }
+ els.owner.hidden = false;
+ showSettingsError(err.message);
+ }
+}
+
+function applyOwner(data) {
+ state = { ...state, ...data };
+ const door = data.door;
+ els['door-open'].checked = Boolean(door.open);
+ els['door-price'].value = door.free ? '0' : String(Number(door.price_atomics) / 1e6);
+ els['door-solana'].value = door.pay_to_solana || '';
+ els['door-base'].value = door.pay_to_base || '';
+ els['door-headline'].value = door.headline || '';
+ els['door-greeting'].value = door.greeting || '';
+ els['door-max'].value = String(door.max_chars);
+ els['door-cap'].value = String(door.daily_cap);
+ els['door-listed'].checked = Boolean(door.listed);
+
+ els['no-handle'].hidden = Boolean(data.handle);
+ els['share-block'].hidden = !data.handle;
+ if (data.url) {
+ els['share-url'].textContent = data.url;
+ els['copy-share'].dataset.copy = data.url;
+ }
+ if (data.endpoint) {
+ els['endpoint-url'].textContent = data.endpoint;
+ els['copy-endpoint'].dataset.copy = data.endpoint;
+ }
+
+ els['stat-pending'].textContent = String(data.totals.pending);
+ els['stat-total'].textContent = String(data.totals.total);
+ els['stat-earned'].textContent = data.totals.earned;
+
+ renderBlocks(data.blocks || []);
+}
+
+function renderBlocks(blocks) {
+ state.blocks = blocks;
+ if (!blocks.length) {
+ els.blocks.hidden = true;
+ els['blocks-empty'].hidden = false;
+ return;
+ }
+ els['blocks-empty'].hidden = true;
+ els.blocks.hidden = false;
+ els.blocks.replaceChildren(
+ ...blocks.map((b) => {
+ const li = document.createElement('li');
+ const label = document.createElement('span');
+ label.textContent = b.subject;
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'btn btn-sm';
+ btn.textContent = 'Unblock';
+ btn.addEventListener('click', async () => {
+ btn.disabled = true;
+ try {
+ const data = await knockApi.saveSettings({ unblock: b.id });
+ applyOwner(data);
+ } catch (err) {
+ showSettingsError(err.message);
+ btn.disabled = false;
+ }
+ });
+ li.append(label, btn);
+ return li;
+ }),
+ );
+}
+
+async function saveSettings() {
+ showSettingsError('');
+ const patch = {
+ open: els['door-open'].checked,
+ price: els['door-price'].value.trim() || '0',
+ pay_to_solana: els['door-solana'].value.trim() || null,
+ pay_to_base: els['door-base'].value.trim() || null,
+ headline: els['door-headline'].value.trim() || null,
+ greeting: els['door-greeting'].value.trim() || null,
+ max_chars: Number(els['door-max'].value) || 600,
+ daily_cap: Number(els['door-cap'].value) || 25,
+ listed: els['door-listed'].checked,
+ };
+ els.save.disabled = true;
+ els.save.textContent = 'Saving…';
+ try {
+ applyOwner(await knockApi.saveSettings(patch));
+ els['save-note'].textContent = patch.open ? 'Saved. Your door is open.' : 'Saved. Your door is shut.';
+ els['save-note'].hidden = false;
+ setTimeout(() => { els['save-note'].hidden = true; }, 2600);
+ } catch (err) {
+ showSettingsError(err.message);
+ } finally {
+ els.save.disabled = false;
+ els.save.textContent = 'Save door';
+ }
+}
+
+function showSettingsError(message) {
+ els['settings-error'].textContent = message;
+ els['settings-error'].hidden = !message;
+}
+
+// ── Inbox ───────────────────────────────────────────────────────────────────
+
+async function loadInbox({ append = false } = {}) {
+ if (state.loadingMore) return;
+ state.loadingMore = true;
+ const before = append && state.knocks.length ? state.knocks[state.knocks.length - 1].created_at : null;
+ try {
+ const data = await knockApi.inbox({ limit: 20, before });
+ state.knocks = append ? [...state.knocks, ...data.knocks] : data.knocks;
+ els['inbox-loading'].hidden = true;
+ els['load-more'].hidden = !data.has_more;
+ renderInbox();
+ if (data.totals) {
+ els['stat-pending'].textContent = String(data.totals.pending);
+ els['stat-total'].textContent = String(data.totals.total);
+ els['stat-earned'].textContent = data.totals.earned;
+ }
+ } catch (err) {
+ els['inbox-loading'].hidden = true;
+ els['inbox-empty'].hidden = false;
+ els['inbox-empty'].querySelector('[data-msg]').textContent =
+ err.status === 401 ? 'Sign in to read your knocks.' : 'Could not load your knocks. Reload to try again.';
+ } finally {
+ state.loadingMore = false;
+ }
+}
+
+function renderInbox() {
+ if (!state.knocks.length) {
+ els.inbox.hidden = true;
+ els['inbox-empty'].hidden = false;
+ return;
+ }
+ els['inbox-empty'].hidden = true;
+ els.inbox.hidden = false;
+ els.inbox.replaceChildren(...state.knocks.map(knockRow));
+}
+
+function knockRow(knock) {
+ const li = document.createElement('li');
+ li.className = `knock${knock.status === 'pending' ? ' is-new' : ''}`;
+ li.dataset.id = knock.id;
+
+ const head = document.createElement('div');
+ head.className = 'knock-head';
+ const who = document.createElement('strong');
+ who.textContent = knock.sender_name;
+ const amount = document.createElement('span');
+ amount.className = `knock-amount${knock.amount_atomics === '0' ? ' is-free' : ''}`;
+ amount.textContent = knock.amount_atomics === '0' ? 'free' : knock.amount;
+ const when = document.createElement('time');
+ when.dateTime = knock.created_at;
+ when.textContent = relative(knock.created_at);
+ head.append(who, amount, when);
+
+ const body = document.createElement('div');
+ body.className = 'knock-body';
+ if (knock.subject) {
+ const subject = document.createElement('div');
+ subject.className = 'knock-subject';
+ subject.textContent = knock.subject;
+ body.appendChild(subject);
+ }
+ const text = document.createElement('p');
+ text.textContent = knock.message;
+ body.appendChild(text);
+ if (knock.sender_url) {
+ const link = document.createElement('a');
+ link.className = 'knock-link';
+ link.href = knock.sender_url;
+ link.textContent = knock.sender_url;
+ link.rel = 'nofollow noopener noreferrer';
+ link.target = '_blank';
+ body.appendChild(link);
+ }
+ if (knock.reply_text) {
+ const reply = document.createElement('div');
+ reply.className = 'knock-reply';
+ reply.textContent = knock.reply_text;
+ body.appendChild(reply);
+ }
+
+ const actions = document.createElement('div');
+ actions.className = 'knock-actions';
+ if (knock.status !== 'replied') {
+ const replyBtn = button('Reply', () => openReply(li, knock));
+ actions.appendChild(replyBtn);
+ }
+ if (knock.status === 'pending') {
+ actions.appendChild(button('Mark read', () => act(knock.id, { status: 'read' })));
+ }
+ if (knock.status !== 'dismissed') {
+ actions.appendChild(button('Dismiss', () => act(knock.id, { status: 'dismissed' })));
+ }
+ actions.appendChild(button('Block sender', () => act(knock.id, { status: 'dismissed', block: true }), 'danger'));
+
+ li.append(head, body, actions);
+ return li;
+}
+
+function button(label, onClick, tone = null) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = `btn btn-sm${tone === 'danger' ? ' btn-danger' : ''}`;
+ b.textContent = label;
+ b.addEventListener('click', onClick);
+ return b;
+}
+
+function openReply(li, knock) {
+ if (li.querySelector('.reply-form')) return;
+ const form = document.createElement('form');
+ form.className = 'reply-form';
+ const area = document.createElement('textarea');
+ area.maxLength = 2000;
+ area.placeholder = `Answer ${knock.sender_name}. They read it through their receipt link.`;
+ area.required = true;
+ const row = document.createElement('div');
+ row.className = 'reply-row';
+ const send = document.createElement('button');
+ send.type = 'submit';
+ send.className = 'btn btn-sm btn-primary';
+ send.textContent = 'Send reply';
+ const cancel = button('Cancel', () => form.remove());
+ row.append(send, cancel);
+ form.append(area, row);
+ form.addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const reply = area.value.trim();
+ if (!reply) return;
+ send.disabled = true;
+ send.textContent = 'Sending…';
+ await act(knock.id, { status: 'replied', reply });
+ });
+ li.appendChild(form);
+ area.focus();
+}
+
+async function act(id, patch) {
+ try {
+ const { knock } = await knockApi.actOn(id, patch);
+ state.knocks = state.knocks.map((k) => (k.id === id ? { ...k, ...knock } : k));
+ renderInbox();
+ if (patch.block) applyOwner(await knockApi.settings());
+ else refreshTotals();
+ } catch (err) {
+ showSettingsError(err.message);
+ }
+}
+
+async function refreshTotals() {
+ try {
+ const data = await knockApi.inbox({ limit: 1 });
+ els['stat-pending'].textContent = String(data.totals.pending);
+ els['stat-total'].textContent = String(data.totals.total);
+ els['stat-earned'].textContent = data.totals.earned;
+ } catch {
+ // The list on screen is already correct; a stale counter is not worth
+ // an error banner.
+ }
+}
+
+function relative(iso) {
+ const then = Date.parse(iso);
+ if (Number.isNaN(then)) return '';
+ const secs = Math.max(0, Math.round((Date.now() - then) / 1000));
+ if (secs < 60) return 'just now';
+ if (secs < 3600) return `${Math.floor(secs / 60)}m ago`;
+ if (secs < 86400) return `${Math.floor(secs / 3600)}h ago`;
+ return `${Math.floor(secs / 86400)}d ago`;
+}
+
+// ── Wiring ──────────────────────────────────────────────────────────────────
+
+function bind() {
+ els.save?.addEventListener('click', saveSettings);
+ els['load-more']?.addEventListener('click', () => loadInbox({ append: true }));
+ for (const btn of document.querySelectorAll('[data-copy]')) {
+ btn.addEventListener('click', () => copy(btn));
+ }
+ // Opening a priced door with no wallet is the one save that always fails,
+ // so say it before the round trip rather than after.
+ els['door-open']?.addEventListener('change', hintPayout);
+ els['door-price']?.addEventListener('input', hintPayout);
+ els['door-solana']?.addEventListener('input', hintPayout);
+}
+
+function hintPayout() {
+ const priced = (els['door-price'].value.trim() || '0') !== '0';
+ const needsWallet = els['door-open'].checked && priced && !els['door-solana'].value.trim() && !els['door-base'].value.trim();
+ showSettingsError(needsWallet ? 'A priced door needs the wallet that should receive the USDC.' : '');
+}
+
+async function copy(btn) {
+ const text = btn.dataset.copy;
+ if (!text) return;
+ try {
+ await navigator.clipboard.writeText(text);
+ const original = btn.textContent;
+ btn.textContent = 'Copied';
+ btn.classList.add('is-ok');
+ setTimeout(() => {
+ btn.textContent = original;
+ btn.classList.remove('is-ok');
+ }, 1400);
+ } catch {
+ btn.textContent = 'Copy failed';
+ setTimeout(() => { btn.textContent = 'Copy'; }, 1400);
+ }
+}