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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(knock): let a stranger pay your price to reach you, and be shown in
nirholas3c9206a83199
diff --git a/api/_lib/knock/deliver.js b/api/_lib/knock/deliver.jsnew file mode 100644index 000000000..f7a6c6269--- /dev/null+++ b/api/_lib/knock/deliver.js@@ -0,0 +1,138 @@+// Turning a paid knock into a person walking on screen.+//+// One function, called by both lanes (the x402 endpoint for priced doors and+// /api/knock/send for free ones), so a knock behaves identically however it+// was paid for. The order matters:+//+// 1. refuse early -- closed door, daily cap, block list. Nothing is charged+// by this module, but the paid lane calls checkDoor() BEFORE the 402+// challenge is issued, so a refused knock never takes money.+// 2. write the companion event -- this is what makes the avatar walk on.+// Its importance comes from the price, so the sender's own money decides+// whether the owner is interrupted (api/_lib/knock/policy.js).+// 3. write the knock row, linked to that event, so the inbox and the+// companion feed are two views of one thing.+// 4. notify -- 'knock_received' rides the normal preference matrix, which+// is what puts the line in the bell, the push, and the corner avatar on+// whatever page the owner happens to be on.+//+// Steps 2 and 4 are best-effort: a knock that has been paid for is recorded+// even if the companion feed or the bell is having a bad minute. Losing the+// delivery animation is a degraded experience; losing a paid message is theft.++import { insertEvent } from '../companion/store.js';+import { insertNotification } from '../notify.js';+import {+ KNOCK_SOURCE_KIND,+ blockKeysFor,+ doorRefusal,+ importanceFor,+ spokenLineFor,+ titleFor,+ validateKnock,+} from './policy.js';+import { getDoor, isBlocked, knocksToday, recordKnock, findByRequestId } from './store.js';++/**+ * Everything that can refuse a knock before money moves.+ * @returns {Promise<{door: object}>} the owner's full door row on success.+ * @throws {Error} coded + statused by policy.knockError.+ */+export async function checkDoor(userId, input) {+ const door = await getDoor(userId);+ const refusal = doorRefusal(door, { knocksToday: await knocksToday(userId) });+ if (refusal) throw refusal;++ const clean = validateKnock(input, door);+ const keys = blockKeysFor({ payerWallet: input?.payer_wallet, senderName: clean.senderName });+ if (await isBlocked(userId, keys)) {+ // Deliberately the same shape as a closed door. A blocked sender who can+ // tell they were blocked specifically just knocks again under a new name.+ throw doorRefusal({ ...door, open: false }, {});+ }+ return { door, clean };+}++/**+ * Record and deliver one knock. Assumes checkDoor() already passed and, on the+ * paid lane, that the payment has settled.+ *+ * @param {object} args+ * @param {string} args.userId recipient+ * @param {object} args.clean the output of validateKnock()+ * @param {object} [args.payment] { payerWallet, network, txHash, amountAtomics, asset }+ * @returns {Promise<{knock: object, duplicate: boolean, importance: number}>}+ */+export async function deliverKnock({ userId, clean, payment = {} }) {+ const amountAtomics = String(payment.amountAtomics ?? 0);+ const importance = importanceFor(amountAtomics);+ const spoken = spokenLineFor({+ senderName: clean.senderName,+ amountAtomics,+ subject: clean.subject,+ });+ const title = titleFor({ senderName: clean.senderName, amountAtomics, subject: clean.subject });++ // An idempotency key that has already been used means this exact knock was+ // delivered on an earlier attempt. Return that one rather than staging a+ // second performance for a message the owner already heard.+ if (clean.requestId) {+ const existing = await findByRequestId(userId, clean.requestId);+ if (existing) return { knock: existing, duplicate: true, importance };+ }++ const event = await safeEvent(userId, {+ source_kind: KNOCK_SOURCE_KIND,+ // The knock has no stable upstream id of its own, so the dedupe key is+ // the caller's request id when they supplied one, and a fresh uuid when+ // they did not. Two knocks with no request id are two knocks.+ external_id: clean.requestId || crypto.randomUUID(),+ sender: clean.senderName,+ sender_id: payment.payerWallet ?? null,+ title,+ body: clean.message,+ url: clean.senderUrl,+ importance,+ reason: amountAtomics === '0' ? 'free door' : `paid ${amountAtomics} atomics to knock`,+ spoken_line: spoken,+ triage_engine: 'knock',+ });++ const knock = await recordKnock(userId, {+ ...clean,+ payerWallet: payment.payerWallet ?? null,+ network: payment.network ?? null,+ txHash: payment.txHash ?? null,+ amountAtomics,+ asset: payment.asset ?? null,+ companionEventId: event?.id ?? null,+ });++ // recordKnock returns null only on the request-id conflict, which the check+ // above almost always catches first. Losing that race is still a duplicate.+ if (!knock) {+ const existing = await findByRequestId(userId, clean.requestId);+ return { knock: existing, duplicate: true, importance };+ }++ insertNotification(userId, 'knock_received', {+ title,+ body: clean.message.slice(0, 240),+ spoken_line: spoken,+ knock_id: knock.id,+ sender: clean.senderName,+ amount_atomics: amountAtomics,+ url: '/knock',+ });++ return { knock, duplicate: false, importance };+}++async function safeEvent(userId, event) {+ try {+ return await insertEvent(userId, event);+ } catch (err) {+ console.error('[knock] companion event insert failed:', err.message);+ return null;+ }+}diff --git a/api/_lib/knock/policy.js b/api/_lib/knock/policy.jsnew file mode 100644index 000000000..a26f22201--- /dev/null+++ b/api/_lib/knock/policy.js@@ -0,0 +1,209 @@+// Knock policy: the pure rules behind a priced door.+//+// Everything in this file is a pure function of its arguments. No database, no+// network, no clock beyond an injectable `now`. That is deliberate: the price+// a stranger is quoted, the line the avatar says out loud, and the reasons a+// knock is refused are the parts of this feature a person will argue with, so+// they are the parts that are unit-tested end to end+// (tests/knock-policy.test.js) rather than only exercised through HTTP.++/** USDC has 6 decimals on every chain we settle on. */+export const USDC_DECIMALS = 6;++// A door priced below a tenth of a cent is not a filter, it is a rounding+// error, and the facilitator fee would exceed it. The ceiling is a guardrail+// against a typo turning $5 into $5,000: a door that wants more can raise it+// in steps.+export const MIN_PRICE_ATOMICS = 1000n; // $0.001+export const MAX_PRICE_ATOMICS = 1000000000n; // $1,000+export const DEFAULT_PRICE_ATOMICS = 50000n; // $0.05++export const MIN_MESSAGE_CHARS = 8;+export const MAX_SUBJECT_CHARS = 120;+export const MAX_SENDER_CHARS = 64;++export const KNOCK_STATUSES = ['pending', 'read', 'replied', 'dismissed'];+export const SENDER_KINDS = ['agent', 'human', 'unknown'];++/** A knock is a companion event of this kind. Nothing else writes it. */+export const KNOCK_SOURCE_KIND = 'knock';++/**+ * Render atomic USDC as a human price string.+ * Trailing zeros are trimmed past the cent, so $0.05 reads as "$0.05" and+ * $0.001 as "$0.001" rather than "$0.050000".+ */+export function formatUsdc(atomics) {+ const value = BigInt(atomics ?? 0);+ const negative = value < 0n;+ const abs = negative ? -value : value;+ const whole = abs / 1000000n;+ const frac = (abs % 1000000n).toString().padStart(6, '0').replace(/0+$/, '');+ const cents = frac.length <= 2 ? frac.padEnd(2, '0') : frac;+ return `${negative ? '-' : ''}$${whole.toString()}.${cents}`;+}++/**+ * Parse a price a person typed. Accepts "0.05", "$0.05", "5c" is NOT accepted+ * (ambiguous), and plain atomics when `unit` is 'atomics'.+ * @returns {bigint}+ * @throws {Error} with code 'bad_price' on anything unparseable or out of range.+ */+export function parsePrice(input, { unit = 'usdc' } = {}) {+ const raw = String(input ?? '').trim().replace(/^\$/, '').replace(/,/g, '');+ if (!/^\d+(\.\d{1,6})?$/.test(raw)) throw knockError('bad_price', 'price must be a USDC amount like 0.05');+ let atomics;+ if (unit === 'atomics') {+ if (raw.includes('.')) throw knockError('bad_price', 'atomic prices must be whole numbers');+ atomics = BigInt(raw);+ } else {+ const [whole, frac = ''] = raw.split('.');+ atomics = BigInt(whole) * 1000000n + BigInt(frac.padEnd(6, '0'));+ }+ // Zero is legal and means "free door": it is the one value outside the+ // paid range that the rest of the system understands.+ if (atomics !== 0n && (atomics < MIN_PRICE_ATOMICS || atomics > MAX_PRICE_ATOMICS)) {+ throw knockError(+ 'bad_price',+ `price must be 0 (free) or between ${formatUsdc(MIN_PRICE_ATOMICS)} and ${formatUsdc(MAX_PRICE_ATOMICS)}`,+ );+ }+ return atomics;+}++/** Lowercased, @-stripped username. Returns '' when nothing usable is left. */+export function normalizeHandle(raw) {+ return String(raw ?? '')+ .trim()+ .replace(/^@+/, '')+ .toLowerCase()+ .slice(0, 40)+ .replace(/[^a-z0-9._-]/g, '');+}++/**+ * The keys a block list is matched against for one knock. Both the paying+ * wallet and the name the sender gave are checked, so blocking works whether+ * the sender is a wallet or a named agent.+ */+export function blockKeysFor({ payerWallet = null, senderName = null } = {}) {+ const keys = [];+ if (payerWallet) keys.push(String(payerWallet).trim().toLowerCase());+ if (senderName) keys.push(String(senderName).trim().toLowerCase());+ return [...new Set(keys.filter(Boolean))];+}++/**+ * How loudly a knock lands, on the companion's 0-100 importance scale.+ *+ * A knock is not ranked by keywords like a mail message: the sender already+ * told us how much it is worth to them, in money. The scale is logarithmic so+ * a $50 knock outranks a $0.05 one without a $5,000 knock being able to sit+ * permanently at the top of the feed, and every paid knock starts above the+ * default interrupt threshold (60) because paying to reach someone IS the+ * signal. A free-door knock lands below it: it goes in the feed and the bell,+ * and it does not stop the person's day.+ */+export function importanceFor(amountAtomics) {+ const value = Number(BigInt(amountAtomics ?? 0));+ if (value <= 0) return 45;+ const dollars = value / 10 ** USDC_DECIMALS;+ // log10($0.001) = -3 → 62, log10($1) = 0 → 80, log10($1000) = 3 → 98.+ const scaled = 80 + Math.log10(dollars) * 6;+ return Math.max(62, Math.min(99, Math.round(scaled)));+}++/**+ * The line the avatar says out loud when it walks on.+ *+ * It names the sender and the price first, because those are what the listener+ * needs to decide whether to care, and only then the subject. The message body+ * itself is never spoken: it is shown in the bubble and the inbox, so a long+ * or hostile paragraph cannot be read at someone by their own avatar.+ */+export function spokenLineFor({ senderName, amountAtomics = 0, subject = null } = {}) {+ const who = String(senderName || 'Someone').trim().slice(0, MAX_SENDER_CHARS);+ const topic = String(subject || '').trim();+ const paid = BigInt(amountAtomics ?? 0) > 0n+ ? ` paid ${formatUsdc(amountAtomics)} to reach you`+ : ' is at your door';+ return topic ? `${who}${paid}: ${topic}.` : `${who}${paid}.`;+}++/** The one-line title stored on the knock and shown in the inbox. */+export function titleFor({ senderName, amountAtomics = 0, subject = null } = {}) {+ const who = String(senderName || 'Someone').trim().slice(0, MAX_SENDER_CHARS);+ const topic = String(subject || '').trim();+ if (topic) return `${who}: ${topic}`.slice(0, 200);+ return BigInt(amountAtomics ?? 0) > 0n+ ? `${who} knocked (${formatUsdc(amountAtomics)})`.slice(0, 200)+ : `${who} knocked`.slice(0, 200);+}++/**+ * Validate the caller-supplied half of a knock against the door's own limits.+ * Returns the cleaned payload. Throws a coded error the HTTP layer renders+ * verbatim, because every one of these is something the sender can fix.+ */+export function validateKnock(input, door) {+ const maxChars = Math.max(40, Math.min(2000, Number(door?.max_chars ?? 600)));+ const message = String(input?.message ?? '').trim();+ if (message.length < MIN_MESSAGE_CHARS) {+ throw knockError('message_too_short', `say at least ${MIN_MESSAGE_CHARS} characters`);+ }+ if (message.length > maxChars) {+ throw knockError('message_too_long', `this door accepts up to ${maxChars} characters`);+ }+ const senderName = String(input?.from ?? '').trim().slice(0, MAX_SENDER_CHARS);+ if (!senderName) throw knockError('missing_sender', 'tell them who you are with `from`');++ const subject = String(input?.subject ?? '').trim().slice(0, MAX_SUBJECT_CHARS) || null;+ const senderKind = SENDER_KINDS.includes(input?.sender_kind) ? input.sender_kind : 'unknown';++ let senderUrl = null;+ if (input?.url) {+ const url = String(input.url).trim();+ // Only http(s) links are stored: the inbox renders this as a real anchor+ // and a javascript: or data: URL there would be a handed-over XSS.+ if (!/^https?:\/\/[^\s]+$/i.test(url) || url.length > 400) {+ throw knockError('bad_url', 'url must be a plain http(s) link under 400 characters');+ }+ senderUrl = url;+ }++ const requestId = input?.request_id ? String(input.request_id).trim().slice(0, 80) : null;++ return { message, senderName, subject, senderKind, senderUrl, requestId };+}++/** Reasons a door refuses before any payment is taken. */+export function doorRefusal(door, { now = new Date(), knocksToday = 0 } = {}) {+ if (!door) return knockError('no_door', 'that person has not opened a door');+ if (!door.open) return knockError('door_closed', 'this door is closed right now');+ if (knocksToday >= Number(door.daily_cap ?? 25)) {+ return knockError('door_full', 'this door has taken all the knocks it accepts today');+ }+ void now;+ return null;+}++/** An Error carrying the machine code and the HTTP status the API should use. */+export function knockError(code, message) {+ const err = new Error(message);+ err.code = code;+ err.status = STATUS_BY_CODE[code] ?? 400;+ return err;+}++const STATUS_BY_CODE = {+ no_door: 404,+ door_closed: 403,+ door_full: 429,+ blocked: 403,+ duplicate: 409,+ bad_price: 400,+ bad_url: 400,+ missing_sender: 400,+ message_too_short: 400,+ message_too_long: 400,+};diff --git a/api/_lib/knock/receipt.js b/api/_lib/knock/receipt.jsnew file mode 100644index 000000000..8de5aa2a0--- /dev/null+++ b/api/_lib/knock/receipt.js@@ -0,0 +1,36 @@+// A knock receipt token: the sender's proof that a specific knock is theirs.+//+// Knock is a one-way door. The sender pays, the message lands, and the owner+// may or may not answer. Without a way to look back, "did they reply" would+// mean handing the sender an account, an email address, or a webhook, all of+// which reopen the door the price exists to close. Instead every accepted+// knock returns a receipt URL: an unguessable HMAC over its id, readable by+// whoever holds it and by nobody else, exposing exactly two things: the+// status, and the reply text if one was written.+//+// No new column: the token is derived, so it survives a restart, needs no+// storage, and cannot be leaked from the database on its own.++import { createHmac, timingSafeEqual } from 'node:crypto';+import { env } from '../env.js';++const VERSION = 'knock-receipt-v1';++export function receiptToken(knockId) {+ return createHmac('sha256', env.JWT_SECRET)+ .update(`${VERSION}:${knockId}`)+ .digest('base64url')+ .slice(0, 32);+}++export function receiptValid(knockId, token) {+ const expected = Buffer.from(receiptToken(knockId));+ const given = Buffer.from(String(token || ''));+ // timingSafeEqual throws on a length mismatch, which is itself the answer.+ if (expected.length !== given.length) return false;+ return timingSafeEqual(expected, given);+}++export function receiptUrl(knockId) {+ return `${env.APP_ORIGIN}/api/knock/reply?id=${knockId}&token=${receiptToken(knockId)}`;+}diff --git a/api/_lib/knock/store.js b/api/_lib/knock/store.jsnew file mode 100644index 000000000..7b9ae1e48--- /dev/null+++ b/api/_lib/knock/store.js@@ -0,0 +1,223 @@+// Knock persistence: doors, the knock log, and the block list.+//+// Every write is scoped to a user id the caller already authenticated. The two+// public reads (a door by handle, the directory) deliberately return only what+// a stranger is allowed to see: the price, the greeting, and the owner's+// display identity. A payout address is never in a public payload.++import { sql } from '../db.js';+import { DEFAULT_PRICE_ATOMICS, KNOCK_STATUSES, normalizeHandle } from './policy.js';++const DOOR_COLUMNS = sql`+ user_id, open, price_atomics::text as price_atomics, pay_to_solana, pay_to_base,+ headline, greeting, max_chars, daily_cap, listed, created_at, updated_at+`;++/**+ * The owner's own door. Provisions a closed default row on first read so the+ * settings page always has something real to render and save against.+ */+export async function getDoor(userId) {+ const [row] = await sql`select ${DOOR_COLUMNS} from knock_doors where user_id = ${userId}`;+ if (row) return row;+ const [created] = await sql`+ insert into knock_doors (user_id, price_atomics)+ values (${userId}, ${DEFAULT_PRICE_ATOMICS.toString()})+ on conflict (user_id) do update set updated_at = now()+ returning ${DOOR_COLUMNS}+ `;+ return created;+}++export async function updateDoor(userId, patch) {+ await getDoor(userId);+ const [row] = await sql`+ update knock_doors set+ open = coalesce(${patch.open ?? null}, open),+ price_atomics = coalesce(${patch.price_atomics ?? null}, price_atomics),+ pay_to_solana = ${patch.pay_to_solana === undefined ? sql`pay_to_solana` : patch.pay_to_solana},+ pay_to_base = ${patch.pay_to_base === undefined ? sql`pay_to_base` : patch.pay_to_base},+ headline = ${patch.headline === undefined ? sql`headline` : patch.headline},+ greeting = ${patch.greeting === undefined ? sql`greeting` : patch.greeting},+ max_chars = coalesce(${patch.max_chars ?? null}, max_chars),+ daily_cap = coalesce(${patch.daily_cap ?? null}, daily_cap),+ listed = coalesce(${patch.listed ?? null}, listed),+ updated_at = now()+ where user_id = ${userId}+ returning ${DOOR_COLUMNS}+ `;+ return row;+}++/**+ * A door as a stranger sees it, looked up by @username.+ * Returns null when the handle matches nobody or that account never opened one,+ * so the public endpoint answers the same 404 either way and a probe cannot use+ * it to enumerate which accounts exist.+ */+export async function publicDoorByHandle(handle) {+ const username = normalizeHandle(handle);+ if (!username) return null;+ const [row] = await sql`+ select u.id as user_id, u.username, u.display_name, u.avatar_url, u.verified_type,+ d.open, d.price_atomics::text as price_atomics, d.headline, d.greeting,+ d.max_chars, d.daily_cap, d.listed,+ d.pay_to_solana is not null as has_solana_payout,+ d.pay_to_base is not null as has_base_payout+ from users u+ join knock_doors d on d.user_id = u.id+ where lower(u.username) = ${username} and u.deleted_at is null and d.open+ `;+ return row || null;+}++/** The payout addresses, read only on the settle path. Never in a public body. */+export async function payoutFor(userId) {+ const [row] = await sql`+ select d.pay_to_solana, d.pay_to_base, u.wallet_address+ from knock_doors d join users u on u.id = d.user_id+ where d.user_id = ${userId}+ `;+ return row || null;+}++/** Open, listed doors, cheapest first so the browsable page starts reachable. */+export async function listDirectory({ limit = 60 } = {}) {+ return sql`+ select u.username, u.display_name, u.avatar_url, u.verified_type,+ d.price_atomics::text as price_atomics, d.headline, d.updated_at,+ (select count(*)::int from knock_messages m+ where m.recipient_user_id = d.user_id and m.status = 'replied') as replies+ from knock_doors d+ join users u on u.id = d.user_id+ where d.open and d.listed and u.deleted_at is null and u.username is not null+ order by d.price_atomics asc, d.updated_at desc+ limit ${limit}+ `;+}++export async function knocksToday(userId) {+ const [row] = await sql`+ select count(*)::int as count from knock_messages+ where recipient_user_id = ${userId} and created_at >= date_trunc('day', now() at time zone 'utc')+ `;+ return row?.count ?? 0;+}++export async function isBlocked(userId, keys) {+ if (!keys?.length) return false;+ const [row] = await sql`+ select 1 from knock_blocks+ where user_id = ${userId} and lower(subject) = any(${keys})+ limit 1+ `;+ return Boolean(row);+}++/**+ * Record a knock. Returns null when `request_id` has already been used by this+ * recipient, which is how a retried POST after a settled payment stays one+ * knock instead of two.+ */+export async function recordKnock(userId, knock) {+ const [row] = await sql`+ insert into knock_messages+ (recipient_user_id, sender_name, sender_url, sender_kind, payer_wallet, network,+ tx_hash, amount_atomics, asset, subject, message, companion_event_id, request_id)+ values (${userId}, ${knock.senderName}, ${knock.senderUrl ?? null}, ${knock.senderKind ?? 'unknown'},+ ${knock.payerWallet ?? null}, ${knock.network ?? null}, ${knock.txHash ?? null},+ ${String(knock.amountAtomics ?? 0)}, ${knock.asset ?? null}, ${knock.subject ?? null},+ ${knock.message}, ${knock.companionEventId ?? null}, ${knock.requestId ?? null})+ on conflict (recipient_user_id, request_id) where request_id is not null do nothing+ returning id, sender_name, sender_url, sender_kind, payer_wallet, network, tx_hash,+ amount_atomics::text as amount_atomics, asset, subject, message, status,+ companion_event_id, created_at+ `;+ return row || null;+}++export async function findByRequestId(userId, requestId) {+ if (!requestId) return null;+ const [row] = await sql`+ select id, sender_name, subject, message, status, amount_atomics::text as amount_atomics, created_at+ from knock_messages+ where recipient_user_id = ${userId} and request_id = ${requestId}+ `;+ return row || null;+}++export async function listInbox(userId, { limit = 30, before = null, status = null } = {}) {+ const beforeClause = before ? sql`and created_at < ${before}` : sql``;+ const statusClause = status ? sql`and status = ${status}` : sql``;+ return sql`+ select id, sender_name, sender_url, sender_kind, payer_wallet, network, tx_hash,+ amount_atomics::text as amount_atomics, asset, subject, message, status,+ reply_text, read_at, replied_at, created_at+ from knock_messages+ where recipient_user_id = ${userId}+ ${statusClause}+ ${beforeClause}+ order by created_at desc+ limit ${limit}+ `;+}++export async function inboxTotals(userId) {+ const [row] = await sql`+ select count(*) filter (where status = 'pending')::int as pending,+ count(*)::int as total,+ coalesce(sum(amount_atomics), 0)::text as earned_atomics+ from knock_messages where recipient_user_id = ${userId}+ `;+ return row || { pending: 0, total: 0, earned_atomics: '0' };+}++export async function updateKnock(userId, id, { status = null, reply = null }) {+ const nextStatus = KNOCK_STATUSES.includes(status) ? status : null;+ const [row] = await sql`+ update knock_messages set+ status = coalesce(${nextStatus}, status),+ reply_text = ${reply === null ? sql`reply_text` : reply},+ read_at = ${nextStatus && nextStatus !== 'pending' ? sql`coalesce(read_at, now())` : sql`read_at`},+ replied_at = ${nextStatus === 'replied' ? sql`coalesce(replied_at, now())` : sql`replied_at`}+ where id = ${id} and recipient_user_id = ${userId}+ returning id, sender_name, sender_url, subject, message, status, reply_text,+ amount_atomics::text as amount_atomics, payer_wallet, read_at, replied_at, created_at+ `;+ return row || null;+}++export async function getKnock(userId, id) {+ const [row] = await sql`+ select id, sender_name, sender_url, payer_wallet, subject, message, status,+ amount_atomics::text as amount_atomics, companion_event_id, created_at+ from knock_messages where id = ${id} and recipient_user_id = ${userId}+ `;+ return row || null;+}++export async function listBlocks(userId) {+ return sql`+ select id, subject, note, created_at from knock_blocks+ where user_id = ${userId} order by created_at desc limit 200+ `;+}++export async function addBlock(userId, subject, note = null) {+ const clean = String(subject || '').trim().slice(0, 120);+ if (!clean) return null;+ const [row] = await sql`+ insert into knock_blocks (user_id, subject, note)+ values (${userId}, ${clean}, ${note})+ on conflict (user_id, lower(subject)) do nothing+ returning id, subject, note, created_at+ `;+ return row || null;+}++export async function removeBlock(userId, id) {+ const [row] = await sql`+ delete from knock_blocks where user_id = ${userId} and id = ${id} returning id+ `;+ return Boolean(row);+}diff --git a/api/_lib/migrations/20260828210000_knock_doors.sql b/api/_lib/migrations/20260828210000_knock_doors.sqlnew file mode 100644index 000000000..131f66687--- /dev/null+++ b/api/_lib/migrations/20260828210000_knock_doors.sql@@ -0,0 +1,101 @@+begin;++-- Knock: a priced, machine-payable door to a person.+--+-- Every account can open a public door at /knock/<username>. A visitor (a+-- human on the page, or an agent over x402) pays the price the owner set and+-- gets exactly one message through. The payment settles in USDC straight to+-- the owner's own wallet; the message becomes a companion event, so the+-- owner's 3D companion walks on and delivers it in person.+--+-- Nothing here holds funds. amount_atomics/tx_hash are the settled receipt the+-- x402 layer already produced, recorded so the owner can see what a knock was+-- worth and so the inbox can rank by it.++create table if not exists knock_doors (+ user_id uuid primary key references users(id) on delete cascade,+ -- A door is shut until its owner opens it. Nobody gets knocked at by default.+ open boolean not null default false,+ -- Price of one knock, in USDC atomic units (6 decimals). 0 means the door+ -- is free, which routes through /api/knock/send instead of the x402 lane.+ price_atomics bigint not null default 50000,+ -- Where the money goes. Solana is the home chain and the default lane; the+ -- Base leg is optional and only advertised when set.+ pay_to_solana text,+ pay_to_base text,+ -- What the door says to a visitor before they write.+ headline text,+ greeting text,+ max_chars integer not null default 600,+ -- Knocks accepted per UTC day, after which the door answers 429 and says so.+ daily_cap integer not null default 25,+ -- Listed in the public /knock directory. An open door can still be unlisted,+ -- for someone who wants a reachable link without being browsable.+ listed boolean not null default true,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint knock_doors_price_chk check (price_atomics between 0 and 1000000000),+ constraint knock_doors_max_chars_chk check (max_chars between 40 and 2000),+ constraint knock_doors_cap_chk check (daily_cap between 1 and 1000)+);++create index if not exists knock_doors_listed_idx+ on knock_doors (open, listed, price_atomics)+ where open and listed;++create table if not exists knock_messages (+ id uuid primary key default gen_random_uuid(),+ recipient_user_id uuid not null references users(id) on delete cascade,+ sender_name text not null,+ sender_url text,+ sender_kind text not null default 'unknown',+ -- Settled payment receipt. A free-door knock carries amount_atomics 0 and+ -- no wallet, which is exactly how the inbox tells the two apart.+ payer_wallet text,+ network text,+ tx_hash text,+ amount_atomics bigint not null default 0,+ asset text,+ subject text,+ message text not null,+ status text not null default 'pending',+ -- The companion event this knock became, so opening one from the inbox and+ -- opening it from the companion feed mark the same thing read.+ companion_event_id uuid references companion_events(id) on delete set null,+ reply_text text,+ -- Caller-supplied dedupe key: a retried POST after a settled payment must+ -- not knock twice.+ request_id text,+ read_at timestamptz,+ replied_at timestamptz,+ created_at timestamptz not null default now(),+ constraint knock_messages_status_chk+ check (status in ('pending', 'read', 'replied', 'dismissed')),+ constraint knock_messages_kind_chk+ check (sender_kind in ('agent', 'human', 'unknown')),+ constraint knock_messages_amount_chk check (amount_atomics >= 0)+);++create index if not exists knock_messages_inbox_idx+ on knock_messages (recipient_user_id, created_at desc);+create index if not exists knock_messages_unread_idx+ on knock_messages (recipient_user_id, amount_atomics desc)+ where status = 'pending';+create unique index if not exists knock_messages_request_uniq+ on knock_messages (recipient_user_id, request_id)+ where request_id is not null;++-- Anyone the owner never wants to hear from again. Matched on the lowercased+-- payer wallet or sender name, whichever the knock carried.+create table if not exists knock_blocks (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ subject text not null,+ note text,+ created_at timestamptz not null default now()+);++create unique index if not exists knock_blocks_subject_uniq+ on knock_blocks (user_id, lower(subject));++commit;diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex 36eb0ae11..740af7286 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -52,6 +52,11 @@ export const CATEGORIES = [label: 'Companion deliveries',description: 'Your 3D companion has something from your own inbox, calendar, or phone worth hearing.',},+ {+ key: 'knock',+ label: 'Knocks at your door',+ description: 'Someone paid your price to reach you through /knock. Your companion delivers it in person.',+ },{key: 'account',label: 'Account & security',@@ -116,6 +121,8 @@ const TYPE_CATEGORY = {companion_delivery: 'companion',+ knock_received: 'knock',+forge_complete: 'creations',forge_failed: 'creations',@@ -168,6 +175,7 @@ const DEFAULTS = {// companion triaged as worth hearing (api/_lib/companion/triage.js). Email// and telegram would just relay what the user already gets in that inbox.companion: { in_app: true, push: true, email: false, telegram: false, avatar: true },+ knock: { in_app: true, push: true, email: true, telegram: false, avatar: true },account: { in_app: true, push: true, email: true, telegram: false, avatar: true },};@@ -281,6 +289,7 @@ const PUSH_COPY = {irl_reply: (p) => ['Agent replied 💬', p.message ? `“${p.message}”` : 'An agent replied to your message'],pump_alert: (p) => ['Market alert 📈', p.summary || 'A token alert you configured just fired'],companion_delivery: (p) => [p.sender ? `${p.sender} 👋` : 'Your companion 👋', p.line || p.title || 'Something worth your attention just came in'],+ knock_received: (p) => [p.sender ? `${p.sender} is at your door 🚪` : 'Someone is at your door 🚪', p.title || p.body || 'Someone paid to reach you'],forge_complete: (p) => ['Your 3D model is ready ✨', p.prompt ? `"${String(p.prompt).slice(0, 80)}" finished generating` : 'Your generation finished. Tap to view it'],forge_failed: (p) => ['Generation failed ⚠️', p.prompt ? `"${String(p.prompt).slice(0, 80)}" could not be generated. Tap to retry` : 'A generation could not be completed. Tap to retry'],withdrawal_completed: () => ['Withdrawal complete ✅', 'Your withdrawal has been sent'],diff --git a/api/knock/directory.js b/api/knock/directory.jsnew file mode 100644index 000000000..0d1ba8515--- /dev/null+++ b/api/knock/directory.js@@ -0,0 +1,43 @@+// GET /api/knock/directory+//+// Every open, listed door, cheapest first. This is the browsable half of Knock:+// the page a person lands on to find someone reachable, and the feed an agent+// crawls to discover who it can pay to talk to. Public and cacheable.++import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { formatUsdc } from '../_lib/knock/policy.js';+import { listDirectory } from '../_lib/knock/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.knockPublic(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const limitRaw = Number.parseInt(params.get('limit') || '60', 10);+ const limit = Number.isFinite(limitRaw) ? Math.min(100, Math.max(1, limitRaw)) : 60;++ const rows = await listDirectory({ limit });+ return json(+ res,+ 200,+ {+ doors: rows.map((row) => ({+ handle: row.username,+ display_name: row.display_name || row.username,+ avatar_url: row.avatar_url || null,+ verified: row.verified_type || null,+ price_atomics: String(row.price_atomics),+ price: formatUsdc(row.price_atomics),+ headline: row.headline || null,+ replies: row.replies ?? 0,+ updated_at: row.updated_at,+ })),+ count: rows.length,+ },+ { 'cache-control': 'public, max-age=60' },+ );+});diff --git a/api/knock/door.js b/api/knock/door.jsnew file mode 100644index 000000000..7671d6b0d--- /dev/null+++ b/api/knock/door.js@@ -0,0 +1,71 @@+// GET /api/knock/door?handle=<username>+//+// The public face of one person's door: what it costs to reach them, what they+// want you to know before you write, and which lane to use. Unauthenticated on+// purpose. This is the endpoint an agent reads before deciding whether a human+// is worth the money, and the one the /knock/<handle> page renders from.+//+// A handle that matches nobody and a handle whose owner keeps their door shut+// both answer 404 with the same body, so this cannot be used to enumerate+// accounts.++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { env } from '../_lib/env.js';+import { formatUsdc, normalizeHandle } from '../_lib/knock/policy.js';+import { publicDoorByHandle } from '../_lib/knock/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.knockPublic(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const handle = normalizeHandle(params.get('handle'));+ if (!handle) return error(res, 400, 'bad_handle', 'pass ?handle=<username>');++ const door = await publicDoorByHandle(handle);+ if (!door) return error(res, 404, 'no_door', 'no open door for that handle');++ return json(res, 200, { door: publicShape(door) }, { 'cache-control': 'public, max-age=30' });+});++/**+ * The stranger-visible door. Exported so the page renderer and the SDK's+ * fixtures agree on one shape, and so a payout address can never be added to+ * it by accident: this function names every field that ships.+ */+export function publicShape(row) {+ const priceAtomics = String(row.price_atomics ?? '0');+ const free = priceAtomics === '0';+ return {+ handle: row.username,+ display_name: row.display_name || row.username,+ avatar_url: row.avatar_url || null,+ verified: row.verified_type || null,+ open: Boolean(row.open),+ free,+ price_atomics: priceAtomics,+ price: formatUsdc(priceAtomics),+ currency: 'USDC',+ networks: free ? [] : networksFor(row),+ headline: row.headline || null,+ greeting: row.greeting || null,+ max_chars: Number(row.max_chars ?? 600),+ // The lane a caller should use. Free doors take a plain POST; priced+ // doors answer 402 first and settle before the message is accepted.+ endpoint: free ? `${env.APP_ORIGIN}/api/knock/send` : `${env.APP_ORIGIN}/api/x402/knock?to=${encodeURIComponent(row.username)}`,+ protocol: free ? 'http' : 'x402',+ };+}++// Solana leads because it is the home chain and the settle path we run+// ourselves. Base is advertised only when the owner set an address for it.+function networksFor(row) {+ const nets = [];+ if (row.has_solana_payout) nets.push('solana');+ if (row.has_base_payout) nets.push('base');+ return nets.length ? nets : ['solana'];+}diff --git a/api/knock/inbox/[id].js b/api/knock/inbox/[id].jsnew file mode 100644index 000000000..51132ed29--- /dev/null+++ b/api/knock/inbox/[id].js@@ -0,0 +1,72 @@+// PATCH /api/knock/inbox/<id> → act on one knock.+//+// { status: 'read' | 'dismissed' } mark it+// { status: 'replied', reply: '…' } answer it+// { block: true } and never hear from them again+//+// A reply is stored, not sent: Knock is a one-way door by design, and the+// sender reads the answer back through the same paymentless GET they already+// hold a link to (/api/knock/reply?id=…&token=…) rather than the door owner+// handing out an email address. Blocking uses the paying wallet when there was+// one and the sender's name when the knock was free.++import { z } from 'zod';+import { getRequestUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';+import { requireCsrf } from '../../_lib/csrf.js';+import { limits } from '../../_lib/rate-limit.js';+import { parse } from '../../_lib/validate.js';+import { formatUsdc } from '../../_lib/knock/policy.js';+import { addBlock, getKnock, updateKnock } from '../../_lib/knock/store.js';+import { markEvent } from '../../_lib/companion/store.js';++const patchBody = z.object({+ status: z.enum(['read', 'replied', 'dismissed']).optional(),+ reply: z.string().trim().max(2000).optional(),+ block: z.boolean().optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['PATCH'])) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!(await requireCsrf(req, res, user.id))) return;++ const rl = await limits.knockWrite(user.id);+ if (!rl.success) return rateLimited(res, rl);++ const id = String(req.query?.id || '').trim();+ if (!id) return error(res, 400, 'missing_id', 'knock id required');++ const existing = await getKnock(user.id, id);+ if (!existing) return error(res, 404, 'not_found', 'no such knock');++ const body = parse(patchBody, await readJson(req));+ if (body.status === 'replied' && !body.reply) {+ return error(res, 400, 'missing_reply', 'replying needs a reply');+ }++ if (body.block) {+ // The wallet is the durable identity when the knock was paid for; a free+ // knock only ever gave us a name, so that is what gets blocked.+ await addBlock(user.id, existing.payer_wallet || existing.sender_name, 'blocked from the knock inbox');+ }++ const row = await updateKnock(user.id, id, {+ status: body.status ?? null,+ reply: body.reply ?? null,+ });++ // Reading or dismissing a knock settles its companion delivery too, so the+ // avatar never walks on later to announce something already dealt with.+ if (existing.companion_event_id && body.status) {+ await markEvent(user.id, existing.companion_event_id, {+ delivered: true,+ dismissed: body.status === 'dismissed',+ }).catch(() => null);+ }++ return json(res, 200, { knock: { ...row, amount: formatUsdc(row.amount_atomics) } });+});diff --git a/api/knock/inbox/index.js b/api/knock/inbox/index.jsnew file mode 100644index 000000000..a5fc3e739--- /dev/null+++ b/api/knock/inbox/index.js@@ -0,0 +1,46 @@+// GET /api/knock/inbox → the knocks this account has taken.+//+// Ordered newest first, with the settled amount on every row, because "what was+// this worth" is the first thing an owner wants next to "who was it". The+// companion feed shows the same knocks as deliveries; this is the ledger view.++import { getRequestUser } from '../../_lib/auth.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';+import { limits } from '../../_lib/rate-limit.js';+import { formatUsdc, KNOCK_STATUSES } from '../../_lib/knock/policy.js';+import { listInbox, inboxTotals } from '../../_lib/knock/store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.knockRead(user.id);+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const limitRaw = Number.parseInt(params.get('limit') || '30', 10);+ const limit = Number.isFinite(limitRaw) ? Math.min(50, Math.max(1, limitRaw)) : 30;+ const beforeRaw = params.get('before');+ const before = beforeRaw && !Number.isNaN(Date.parse(beforeRaw)) ? new Date(beforeRaw) : null;+ const statusRaw = params.get('status');+ const status = KNOCK_STATUSES.includes(statusRaw) ? statusRaw : null;++ const [rows, totals] = await Promise.all([+ listInbox(user.id, { limit, before, status }),+ inboxTotals(user.id),+ ]);++ return json(res, 200, {+ knocks: rows.map((row) => ({ ...row, amount: formatUsdc(row.amount_atomics) })),+ has_more: rows.length === limit,+ totals: {+ pending: totals.pending,+ total: totals.total,+ earned_atomics: totals.earned_atomics,+ earned: formatUsdc(totals.earned_atomics),+ },+ });+});diff --git a/api/knock/reply.js b/api/knock/reply.jsnew file mode 100644index 000000000..2d69f9257--- /dev/null+++ b/api/knock/reply.js@@ -0,0 +1,53 @@+// GET /api/knock/reply?id=<knock id>&token=<receipt token>+//+// The other half of the door, for the sender. Whoever holds the receipt URL a+// knock returned can read what became of it: still pending, dismissed, or+// answered, and the answer itself when there is one. No session, no account,+// nothing about the recipient beyond what they chose to write back.+//+// The token is an HMAC over the knock id (api/_lib/knock/receipt.js), so a+// wrong or absent token is a 404 rather than a 403: an id alone should not+// confirm that a knock exists.++import { sql } from '../_lib/db.js';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { receiptValid } from '../_lib/knock/receipt.js';+import { formatUsdc } from '../_lib/knock/policy.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.knockPublic(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const id = String(params.get('id') || '').trim();+ const token = String(params.get('token') || '').trim();+ const notFound = () => error(res, 404, 'not_found', 'no knock for that receipt');++ if (!/^[0-9a-f-]{36}$/i.test(id) || !token || !receiptValid(id, token)) return notFound();++ const [row] = await sql`+ select id, subject, status, reply_text, replied_at, read_at, created_at,+ amount_atomics::text as amount_atomics+ from knock_messages where id = ${id}+ `;+ if (!row) return notFound();++ return json(res, 200, {+ knock: {+ id: row.id,+ subject: row.subject,+ status: row.status,+ // Only ever the reply the owner deliberately wrote. Never their+ // name, wallet, or anything else about the account behind the door.+ reply: row.status === 'replied' ? row.reply_text : null,+ replied_at: row.replied_at,+ seen: Boolean(row.read_at),+ amount: formatUsdc(row.amount_atomics),+ created_at: row.created_at,+ },+ }, { 'cache-control': 'no-store' });+});diff --git a/api/knock/send.js b/api/knock/send.jsnew file mode 100644index 000000000..2ad8b7ad6--- /dev/null+++ b/api/knock/send.js@@ -0,0 +1,71 @@+// POST /api/knock/send+//+// The free lane. A door priced at zero takes a plain JSON post from anyone:+// no wallet, no session, no signature. That is the on-ramp, and the reason it+// exists is that the interesting half of Knock (a stranger reaching a person+// and being announced in person) should be tryable before anyone spends money.+//+// { "to": "nirholas", "from": "Ada", "message": "…", "subject": "…" }+//+// A priced door answers 402 here with the x402 endpoint to use instead, so a+// caller that guessed the wrong lane is told exactly where to go rather than+// being refused. Free means there is no price to make a flood expensive, so+// the IP bucket is deliberately tight (api/_lib/rate-limit.js, knockSendIp).++import { z } from 'zod';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';+import { env } from '../_lib/env.js';+import { formatUsdc, normalizeHandle } from '../_lib/knock/policy.js';+import { publicDoorByHandle } from '../_lib/knock/store.js';+import { checkDoor, deliverKnock } from '../_lib/knock/deliver.js';+import { receiptUrl } from '../_lib/knock/receipt.js';++const body = z.object({+ to: z.string().trim().min(1).max(40),+ from: z.string().trim().min(1).max(64),+ message: z.string().min(1).max(2000),+ subject: z.string().trim().max(120).optional(),+ url: z.string().trim().max(400).optional(),+ sender_kind: z.enum(['agent', 'human', 'unknown']).optional(),+ request_id: z.string().trim().max(80).optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.knockSendIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'this free lane accepts a few knocks per hour from one address');++ const input = parse(body, await readJson(req));+ const handle = normalizeHandle(input.to);+ const door = await publicDoorByHandle(handle);+ if (!door) return error(res, 404, 'no_door', 'no open door for that handle');++ if (String(door.price_atomics) !== '0') {+ return error(res, 402, 'payment_required', `${door.display_name || handle} charges ${formatUsdc(door.price_atomics)} to be reached`, {+ endpoint: `${env.APP_ORIGIN}/api/x402/knock?to=${encodeURIComponent(handle)}`,+ price_atomics: String(door.price_atomics),+ price: formatUsdc(door.price_atomics),+ protocol: 'x402',+ });+ }++ try {+ const { clean } = await checkDoor(door.user_id, input);+ const { knock, duplicate } = await deliverKnock({ userId: door.user_id, clean });+ return json(res, duplicate ? 200 : 201, {+ ok: true,+ duplicate,+ knock_id: knock.id,+ delivered_to: door.display_name || handle,+ receipt_url: receiptUrl(knock.id),+ paid: '$0.00',+ });+ } catch (err) {+ if (err?.code && err?.status) return error(res, err.status, err.code, err.message);+ throw err;+ }+});diff --git a/api/knock/settings.js b/api/knock/settings.jsnew file mode 100644index 000000000..3af9ac870--- /dev/null+++ b/api/knock/settings.js@@ -0,0 +1,117 @@+// GET /api/knock/settings → the owner's door, exactly as they configured it.+// PATCH /api/knock/settings → change any subset of it.+//+// The one endpoint where a payout address is readable, and only by the account+// that owns it. Price is accepted as a human amount ("0.05", "$0.05") and+// stored in USDC atomic units, so nobody has to think in millionths to open a+// door.++import { z } from 'zod';+import { getRequestUser } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';+import { requireCsrf } from '../_lib/csrf.js';+import { limits } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';+import { env } from '../_lib/env.js';+import { formatUsdc, parsePrice } from '../_lib/knock/policy.js';+import { getDoor, updateDoor, inboxTotals, listBlocks, addBlock, removeBlock } from '../_lib/knock/store.js';+import { sql } from '../_lib/db.js';++const patchBody = z.object({+ open: z.boolean().optional(),+ // Accepted as a string so "0.05" survives the trip without float rounding.+ price: z.string().max(24).optional(),+ pay_to_solana: z.string().trim().max(64).nullable().optional(),+ pay_to_base: z.string().trim().max(64).nullable().optional(),+ headline: z.string().trim().max(120).nullable().optional(),+ greeting: z.string().trim().max(600).nullable().optional(),+ max_chars: z.number().int().min(40).max(2000).optional(),+ daily_cap: z.number().int().min(1).max(1000).optional(),+ listed: z.boolean().optional(),+ block: z.string().trim().min(1).max(120).optional(),+ unblock: z.string().uuid().optional(),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PATCH,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PATCH'])) return;++ const user = await getRequestUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') {+ const rl = await limits.knockRead(user.id);+ if (!rl.success) return rateLimited(res, rl);+ return json(res, 200, await ownerView(user));+ }++ if (!(await requireCsrf(req, res, user.id))) return;+ const rl = await limits.knockWrite(user.id);+ if (!rl.success) return rateLimited(res, rl);++ const body = parse(patchBody, await readJson(req));++ if (body.block) await addBlock(user.id, body.block);+ if (body.unblock) await removeBlock(user.id, body.unblock);++ const patch = {};+ if (body.open !== undefined) patch.open = body.open;+ if (body.price !== undefined) {+ try {+ patch.price_atomics = parsePrice(body.price).toString();+ } catch (err) {+ return error(res, 400, err.code || 'bad_price', err.message);+ }+ }+ for (const key of ['pay_to_solana', 'pay_to_base', 'headline', 'greeting']) {+ if (body[key] !== undefined) patch[key] = body[key] || null;+ }+ if (body.max_chars !== undefined) patch.max_chars = body.max_chars;+ if (body.daily_cap !== undefined) patch.daily_cap = body.daily_cap;+ if (body.listed !== undefined) patch.listed = body.listed;++ // Opening a door with a price and nowhere to send the money would take+ // payments into the platform's own wallet. Refuse instead of quietly+ // pocketing a stranger's USDC.+ const merged = { ...(await getDoor(user.id)), ...patch };+ if (merged.open && String(merged.price_atomics) !== '0' && !merged.pay_to_solana && !merged.pay_to_base) {+ return error(+ res,+ 400,+ 'missing_payout',+ 'add the wallet that should receive the USDC before opening a priced door',+ );+ }++ if (Object.keys(patch).length) await updateDoor(user.id, patch);+ return json(res, 200, await ownerView(user));+});++async function ownerView(user) {+ const [door, totals, blocks, handleRow] = await Promise.all([+ getDoor(user.id),+ inboxTotals(user.id),+ listBlocks(user.id),+ sql`select username from users where id = ${user.id}`,+ ]);+ const handle = handleRow?.[0]?.username || null;+ return {+ door: {+ ...door,+ price: formatUsdc(door.price_atomics),+ free: String(door.price_atomics) === '0',+ },+ handle,+ // The link the owner shares. Null until they pick a username, which is+ // what the settings page tells them to do first.+ url: handle ? `${env.APP_ORIGIN}/knock/${handle}` : null,+ endpoint: handle ? `${env.APP_ORIGIN}/api/x402/knock?to=${handle}` : null,+ totals: {+ pending: totals.pending,+ total: totals.total,+ earned_atomics: totals.earned_atomics,+ earned: formatUsdc(totals.earned_atomics),+ },+ blocks,+ };+}diff --git a/api/x402/knock.js b/api/x402/knock.jsnew file mode 100644index 000000000..3cde71ba5--- /dev/null+++ b/api/x402/knock.js@@ -0,0 +1,268 @@+// POST /api/x402/knock?to=<username>+//+// Pay a person's price and get one message through to them, in person.+//+// This is the paid half of Knock. The recipient sets what a moment of their+// attention costs; this endpoint quotes that price as an x402 challenge,+// settles the USDC straight to the recipient's own wallet (never the+// platform's: `payTo` is their address, and a priced door cannot be opened+// without one), and only then accepts the message. The accepted message+// becomes a companion event whose importance is derived from the amount paid,+// which is what makes the recipient's 3D companion walk on screen wherever+// they are and deliver it out loud, with the sender's name and the price.+//+// Solana is the default and the lead network. Base is advertised only when the+// recipient set an address for it.+//+// The order of operations is the whole design:+//+// 1. the body is read and validated against THIS door's limits BEFORE any+// 402 is issued, so nobody ever pays for a message that was going to be+// rejected for being too long, or for knocking at a door that is shut,+// full for the day, or has blocked them;+// 2. the price and payout come from the door row, per request;+// 3. settlement happens in the wrapper;+// 4. the handler records and delivers, and returns a receipt URL the sender+// can poll for a reply without holding an account here.+//+// A request with no body and no payment header is a discovery probe (x402+// catalogs do this). It gets a valid challenge at the door's real price.++import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';+import { buildBazaarSchema, paymentRequirements, send402 } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { cors, error, readBody as readRawBody } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { formatUsdc, normalizeHandle } from '../_lib/knock/policy.js';+import { publicDoorByHandle, payoutFor } from '../_lib/knock/store.js';+import { checkDoor, deliverKnock } from '../_lib/knock/deliver.js';+import { receiptUrl } from '../_lib/knock/receipt.js';++const ROUTE = '/api/x402/knock';++const DESCRIPTION =+ 'Knock on a real person\'s door. Every three.ws account can publish a ' ++ 'priced door at /knock/<username>; paying its price buys you exactly one ' ++ 'message through to that person, delivered out loud and in person by their ' ++ '3D companion, which walks on screen wherever they are on the site and ' ++ 'says who you are and what you paid. The USDC settles directly to the ' ++ 'recipient, not to three.ws. Read GET /api/knock/door?handle=<username> ' ++ 'for a door\'s exact price and limits before you pay, or ' ++ 'GET /api/knock/directory for every open door. The response carries a ' ++ 'receipt URL you can poll for a reply without needing an account.';++const INPUT_EXAMPLE = {+ from: 'Ada (research agent)',+ subject: 'Your x402 settle path',+ message: 'I index x402 endpoints and yours is the only one settling on Solana. Two questions about the facilitator, happy to pay for the time.',+ url: 'https://example.com/ada',+ sender_kind: 'agent',+ request_id: 'ada-2026-08-28-001',+};++const INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['from', 'message'],+ properties: {+ from: { type: 'string', maxLength: 64, description: 'Who is knocking. Shown and spoken to the recipient.' },+ message: { type: 'string', maxLength: 2000, description: 'The message. Length ceiling is per-door; read it from /api/knock/door.' },+ subject: { type: 'string', maxLength: 120, description: 'One line the companion says out loud. The body is shown, never read aloud.' },+ url: { type: 'string', maxLength: 400, description: 'An http(s) link the recipient can follow to check you out.' },+ sender_kind: { type: 'string', enum: ['agent', 'human', 'unknown'], description: 'Self-declared. Shown in the inbox, never trusted for access.' },+ request_id: { type: 'string', maxLength: 80, description: 'Idempotency key. A retry after a settled payment returns the first knock instead of knocking twice.' },+ },+};++const OUTPUT_EXAMPLE = {+ ok: true,+ knock_id: 'c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a',+ delivered_to: 'nirholas',+ announced: true,+ importance: 74,+ paid: '$0.05',+ receipt_url: 'https://three.ws/api/knock/reply?id=c1b0a2d4-7e33-4f01-9a55-2b7c1d0e9f4a&token=…',+ duplicate: false,+};++const OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['ok', 'knock_id', 'delivered_to', 'receipt_url'],+ properties: {+ ok: { type: 'boolean', const: true },+ knock_id: { type: 'string', format: 'uuid' },+ delivered_to: { type: 'string' },+ announced: { type: 'boolean', description: 'True when the amount paid put this above the recipient\'s interrupt threshold.' },+ importance: { type: 'integer', minimum: 0, maximum: 100 },+ paid: { type: 'string' },+ receipt_url: { type: 'string', format: 'uri' },+ duplicate: { type: 'boolean' },+ },+};++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', bodyType: 'json', body: INPUT_EXAMPLE },+ output: { type: 'json', example: OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodySchema: INPUT_SCHEMA,+ outputSchema: OUTPUT_SCHEMA,+ }),+};++export const BAZAAR_SCHEMA = BAZAAR;++// Representative price for a probe with no ?to=. No money can settle against+// it: a paid retry still needs a handle, and the handler below never runs+// without a resolved door.+const PROBE_PRICE_ATOMICS = '50000';++export default async function handler(req, res) {+ // CORS first: this file answers the discovery challenge and its own 4xx+ // bodies before delegating, so a browser client must be able to read them.+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;++ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);+ const handle = normalizeHandle(req.query?.to);++ if (!handle) {+ if (paymentPresent) return error(res, 400, 'to_required', 'query parameter "to" is required');+ return probeChallenge(res, 'query parameter "to" is required. Retry with ?to=<username> for that door\'s exact price.');+ }++ const door = await publicDoorByHandle(handle);+ if (!door) {+ if (paymentPresent) return error(res, 404, 'no_door', `no open door for "${handle}"`);+ return probeChallenge(res, `no open door for "${handle}". GET /api/knock/directory lists every open one.`);+ }++ // A free door has nothing to charge for. Point the caller at the free lane+ // rather than inventing a price.+ if (String(door.price_atomics) === '0') {+ return error(res, 400, 'free_door', `${door.display_name || handle} takes free knocks`, {+ endpoint: `${env.APP_ORIGIN}/api/knock/send`,+ protocol: 'http',+ });+ }++ // Buffer the body once, here, and hand it to both the pre-flight check and+ // the settled handler. Reading the stream twice would hang.+ const body = await readJsonBody(req);+ req.body = body;++ // Pre-flight. When the caller already sent a message we run every refusal+ // (shut door, daily cap, block list, length limits) BEFORE the 402 is+ // issued, so a knock that was never going to land is refused for free and+ // with a specific reason rather than after a payment.+ //+ // A probe with no body skips this and gets the door's real challenge from+ // the wrapper below, priced and addressed to the recipient's own wallet.+ let clean = null;+ if (body && (body.message || body.from)) {+ try {+ ({ clean } = await checkDoor(door.user_id, body));+ } catch (err) {+ if (err?.code && err?.status) return error(res, err.status, err.code, err.message);+ throw err;+ }+ }++ const payout = await payoutFor(door.user_id);+ const inner = paidEndpoint({+ route: ROUTE,+ method: 'POST',+ priceAtomics: String(door.price_atomics),+ networks: networksFor(payout),+ description: `${DESCRIPTION} Currently quoting: ${door.display_name || handle} at ${formatUsdc(door.price_atomics)}.`,+ bazaar: BAZAAR,+ service: withService({+ serviceName: 'three.ws Knock',+ tags: ['knock', 'attention', 'messaging', 'agent-to-human', 'x402'],+ }),+ // The recipient's own wallet. This is the whole point: three.ws never+ // takes custody of what a knock is worth.+ payTo: buildPayTo(payout),+ // Each door is its own good, so each gets its own resource URL. Without+ // this, a payment for one person's door would look like a payment for+ // everyone's.+ resourceUrlBuilder: () => `${env.APP_ORIGIN}${ROUTE}?to=${encodeURIComponent(handle)}`,+ async handler({ requirement, payer }) {+ // A payer who sent payment but no valid message is validated here.+ // The wrapper settles only AFTER this returns, so a throw refuses the+ // knock without moving any money.+ const resolved = clean ?? (await checkDoor(door.user_id, body)).clean;+ const { knock, duplicate, importance } = await deliverKnock({+ userId: door.user_id,+ clean: resolved,+ payment: {+ payerWallet: payer ?? null,+ network: requirement?.network ?? null,+ amountAtomics: requirement?.amount ?? String(door.price_atomics),+ asset: requirement?.asset ?? null,+ },+ });+ return {+ ok: true,+ knock_id: knock.id,+ delivered_to: door.display_name || handle,+ // A paid knock always scores above the default interrupt bar, but+ // the recipient can raise their own, so this reports the score+ // rather than promising an interruption.+ announced: importance >= 60,+ importance,+ paid: formatUsdc(requirement?.amount ?? door.price_atomics),+ receipt_url: receiptUrl(knock.id),+ duplicate,+ };+ },+ });++ return inner(req, res);+}++// Used only when there is no door to quote (no handle, or a handle nobody has+// opened a door for). It advertises the platform receiver at a representative+// price purely so x402 catalogs get a well-formed challenge; nothing can settle+// against it, because a paid retry still has to name a real door.+function probeChallenge(res, errText) {+ const resourceUrl = `${env.APP_ORIGIN}${ROUTE}`;+ return send402(res, {+ resourceUrl,+ accepts: paymentRequirements(resourceUrl, { amount: PROBE_PRICE_ATOMICS }),+ description: DESCRIPTION,+ bazaar: BAZAAR,+ error: errText,+ serviceName: 'three.ws Knock',+ tags: ['knock', 'attention', 'messaging', 'agent-to-human', 'x402'],+ });+}++function buildPayTo(payout) {+ const out = {};+ if (payout?.pay_to_solana) out.solana = payout.pay_to_solana;+ if (payout?.pay_to_base) out.base = payout.pay_to_base;+ return Object.keys(out).length ? out : undefined;+}++// Solana leads: it is the home chain and the rail we settle ourselves. Base is+// offered only when the recipient gave an address for it.+function networksFor(payout) {+ const nets = [];+ if (payout?.pay_to_solana) nets.push('solana');+ if (payout?.pay_to_base) nets.push('base');+ return nets.length ? nets : ['solana'];+}++async function readJsonBody(req) {+ if (req.body && typeof req.body === 'object') return req.body;+ try {+ const raw = (await readRawBody(req, 200_000)).toString('utf8').trim();+ return raw ? JSON.parse(raw) : {};+ } catch {+ return {};+ }+}diff --git a/tests/public-page-cdn-imports.test.js b/tests/public-page-cdn-imports.test.jsindex c68555d6e..4cd7a632e 100644--- a/tests/public-page-cdn-imports.test.js+++ b/tests/public-page-cdn-imports.test.js@@ -32,20 +32,15 @@ function walk(dir, out = []) {// The three hosts /load-module.js knows how to mirror between.const MIRRORABLE = /^https:\/\/(?:esm\.sh|cdn\.jsdelivr\.net|unpkg\.com)\//;-// Comments quote the very pattern they warn against, so strip them before-// scanning; otherwise the explanation of the fix reads as the defect.+// Comments quote the very pattern they warn against, so drop them before+// scanning; otherwise the explanation of the fix reads as the defect. Line+// comments only: pairing `/*` with `*/` across a whole HTML file swallows CSS+// and script alike, which silently hid real code from this scan.function withoutComments(src) {- return src.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/(^|[^:'"`])\/\/[^\n]*/g, '$1');-}--/** Every mirrorable CDN URL a page hands to the loader (directly or via a wrapper). */-function loaderCdnTargets(src) {- const out = [];- const re = /\b(?:loadModule|loadCdnModule)\s*\(\s*['"`]([^'"`]+)['"`]/g;- for (const m of withoutComments(src).matchAll(re)) {- if (MIRRORABLE.test(m[1])) out.push(m[1]);- }- return out;+ return src+ .split('\n')+ .map((line) => line.replace(/(^|[^:'"`])\/\/.*$/, '$1'))+ .join('\n');}/** Every string literal a page passes straight to `import()` from a CDN host. */@@ -92,7 +87,6 @@ describe('public pages load third-party modules through /load-module.js', () =>const src = withoutComments(readFileSync(join(ROOT, rel), 'utf8'));expect(/['"]\/load-module\.js['"]/.test(src), `${rel} must import '/load-module.js'`).toBe(true);expect(/\b(?:loadModule|loadCdnModule)\s*\(/.test(src), `${rel} must call the loader`).toBe(true);- expect(MIRRORABLE.test(''), 'MIRRORABLE guards a full URL, not a bare host').toBe(false);}});