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: auth-hints extension, mobile.css injection, paid demo, receipts migration

nirholasb2a78e60005c
diff --git a/api/_lib/migrations/2026-05-24-x402-receipts.sql b/api/_lib/migrations/2026-05-24-x402-receipts.sql
new file mode 100644
index 000000000..275092627
--- /dev/null
+++ b/api/_lib/migrations/2026-05-24-x402-receipts.sql
@@ -0,0 +1,37 @@
+-- Migration: durable log of x402 offer-receipt artifacts (USE-17).
+-- Apply: npm run db:migrate -- --apply --file 2026-05-24-x402-receipts.sql
+-- Idempotent.
+--
+-- Every successful paid /api/x402/* call writes one row here: the signed
+-- receipt we returned in the SettlementResponse, the resource it covered, the
+-- payer wallet, and the chain network. Buyers can later query their own
+-- receipts via /api/x402/my-receipts (gated by a buyer-signed message so only
+-- the wallet that received the receipt can list it).
+--
+-- Stored as JSONB so verifiers don't have to reconstruct the wire shape —
+-- they can pull the exact signed artifact and run verifyReceiptSignatureEIP712
+-- against it.
+
+begin;
+
+create table if not exists x402_receipts (
+ id uuid primary key default gen_random_uuid(),
+ payer text not null,
+ network text not null,
+ resource_url text not null,
+ format text not null,
+ receipt jsonb not null,
+ transaction text,
+ issued_at timestamptz not null default now()
+);
+
+-- Primary query path: buyer asks "show me my receipts since timestamp X".
+-- payer is lower-cased on insert so address-format comparisons stay stable
+-- across EVM checksummed / non-checksummed shapes.
+create index if not exists x402_receipts_payer_issued
+ on x402_receipts (payer, issued_at desc);
+
+create index if not exists x402_receipts_resource_issued
+ on x402_receipts (resource_url, issued_at desc);
+
+commit;
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index a6f1a31aa..5ba9ac6dd 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -16,6 +16,7 @@ import { cors, error } from './http.js';
import { env } from './env.js';
import { PAYMENT_EVENT_TOPIC as BSC_PAYMENT_EVENT_TOPIC } from './x402-bsc-direct.js';
import {
+ BUILDER_CODE,
NETWORK_BASE_MAINNET,
NETWORK_BSC_MAINNET,
NETWORK_SOLANA_MAINNET,
@@ -27,6 +28,18 @@ import {
settlePayment,
verifyPayment,
} from './x402-spec.js';
+import { declareBuilderCodeExtension } from './x402-builder-code.js';
+import {
+ PAYMENT_IDENTIFIER,
+ checkCache,
+ enforceRequired,
+ extractIdFromHeader,
+ hashRequestPayload,
+ paymentIdentifierExtension,
+ storeResponse,
+ writeCachedResponse,
+ writeConflict,
+} from './x402/payment-identifier-server.js';
const NETWORK_ALIASES = {
base: NETWORK_BASE_MAINNET,
@@ -124,6 +137,19 @@ function buildRequirements({ priceAtomics, networks, resourceUrl }) {
// payment verifies. It should return a JSON-serializable result; throwing an
// Error with .status + .code maps to a clean error response. Throwing an
// X402Error with status=402 re-emits the 402 challenge (e.g. wrong network).
+//
+// `spec.accessControl` (optional) — async (req, routeConfig) => result hook
+// matching the v2 SDK onProtectedRequest contract. Built via
+// installAccessControl() from api/_lib/x402/access-control.js. Returns:
+// • { grantAccess: true, reason, callerId, headers? } → bypass payment,
+// invoke the handler with `bypass = { reason, callerId, subscription?,
+// oauth? }` instead of `requirement`/`payer`, and skip settlement.
+// • { abort: true, status, reason, headers? } → reject the request with the
+// given status (default 403) and message.
+// • null / undefined → continue to the normal 402 flow.
+//
+// `spec.requiredScope` (optional) — OAuth scope the route declares for
+// bypass-via-Bearer. Passed to the hook in routeConfig.requiredScope.
export function paidEndpoint(spec) {
const {
route,
@@ -134,14 +160,36 @@ export function paidEndpoint(spec) {
mimeType = 'application/json',
bazaar,
handler,
+ // ERC-8021 builder-code attribution. Optional per-route service codes
+ // — e.g. a multi-service route declares ["pose-studio", "openai-proxy"]
+ // so the on-chain CBOR suffix records every internal service that
+ // participated. The app code (`a`) is pulled from env so every route
+ // attributes to the same X402_BUILDER_CODE_APP. When env is unset, no
+ // builder-code extension is declared and echo verification is skipped.
+ services,
+ accessControl,
+ requiredScope = null,
+ // USE-15: payment-identifier idempotency. Defaults to optional so any
+ // caller can opt in. Set `{ required: true }` for routes where a
+ // duplicate call is materially expensive or observable (oracle
+ // submissions, fact-check writes, on-chain mints). `ttlSeconds`
+ // overrides the env default (X402_IDEMPOTENCY_TTL_SECONDS).
+ paymentIdentifier = {},
} = spec;
if (!route) throw new Error('paidEndpoint: route is required');
if (!description) throw new Error('paidEndpoint: description is required');
if (!bazaar) throw new Error('paidEndpoint: bazaar discovery extension is required');
if (typeof handler !== 'function') throw new Error('paidEndpoint: handler must be a function');
+ if (accessControl != null && typeof accessControl !== 'function') {
+ throw new Error('paidEndpoint: accessControl must be a function when provided');
+ }
+ const routeConfig = { path: route, method: method.toUpperCase(), requiredScope };
const allowMethods = `${method.toUpperCase()},OPTIONS`;
+ const pidRequired = Boolean(paymentIdentifier.required);
+ const pidTtlSeconds = paymentIdentifier.ttlSeconds;
+ const pidExtension = paymentIdentifierExtension(pidRequired);
return async function paidHandler(req, res) {
if (cors(req, res, { methods: allowMethods, origins: '*' })) return;
@@ -163,14 +211,137 @@ export function paidEndpoint(spec) {
);
}
- const challenge = { resourceUrl, accepts: requirements, description, mimeType, bazaar };
+ // Build the builder-code extension once per challenge so the same block
+ // is advertised in the 402 body AND passed to verifyPayment for echo
+ // validation. If a route declares services, override the auto-declared
+ // block from build402Body.
+ const appCode = env.X402_BUILDER_CODE_APP;
+ const builderCode =
+ appCode && Array.isArray(services) && services.length
+ ? declareBuilderCodeExtension({ a: appCode, s: services })
+ : appCode
+ ? declareBuilderCodeExtension({ a: appCode })
+ : null;
+
+ const extraExtensions = {
+ [PAYMENT_IDENTIFIER]: pidExtension,
+ ...(builderCode ? { [BUILDER_CODE]: builderCode } : {}),
+ };
+ const challenge = {
+ resourceUrl,
+ accepts: requirements,
+ description,
+ mimeType,
+ bazaar,
+ extensions: extraExtensions,
+ };
+
+ // Access-control hook (USE-23). Runs before the 402 so internal /
+ // subscription / OAuth callers can bypass payment entirely. Headers
+ // from `acResult.headers` are applied in both grant + abort paths.
+ if (accessControl) {
+ let acResult;
+ try {
+ acResult = await accessControl(req, routeConfig);
+ } catch (err) {
+ return error(
+ res,
+ err.status || 500,
+ err.code || 'access_control_failed',
+ err.message || 'access control failed',
+ );
+ }
+ if (acResult?.abort) {
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ return error(
+ res,
+ acResult.status || 403,
+ acResult.code || 'access_denied',
+ acResult.reason || 'access denied',
+ );
+ }
+ if (acResult?.grantAccess) {
+ let bypassResult;
+ try {
+ bypassResult = await handler({
+ req,
+ res,
+ bypass: {
+ reason: acResult.reason,
+ callerId: acResult.callerId,
+ subscription: acResult.subscription || null,
+ oauth: acResult.oauth || null,
+ },
+ requirement: null,
+ payer: null,
+ });
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return send402(res, { ...challenge, error: err.message });
+ }
+ return error(
+ res,
+ err.status || 500,
+ err.code || 'internal_error',
+ err.message,
+ );
+ }
+ if (res.writableEnded) return;
+ if (acResult.headers) {
+ for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);
+ }
+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', `${mimeType}; charset=utf-8`);
+ res.end(
+ typeof bypassResult === 'string' ? bypassResult : JSON.stringify(bypassResult),
+ );
+ return;
+ }
+ }
const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
if (!paymentHeader) return send402(res, challenge);
+ // USE-15: required-mode rejects the call before we burn an RPC round-trip.
+ try {
+ enforceRequired({ paymentHeader, required: pidRequired });
+ } catch (err) {
+ if (err instanceof X402Error && err.status >= 400 && err.status < 500) {
+ return error(res, err.status, err.code, err.message);
+ }
+ throw err;
+ }
+
+ // USE-15: deduplicate before /verify. Hashing the request URL is enough
+ // for our GET-only paid endpoints — none of them read request bodies.
+ // When/if a POST endpoint joins the family, the handler can buffer
+ // `req.body` and pass it in here.
+ const paymentId = extractIdFromHeader(paymentHeader);
+ const payloadHash = hashRequestPayload({
+ method: req.method,
+ url: req.url,
+ body: null,
+ });
+ if (paymentId) {
+ const lookup = await checkCache({ route, paymentId, payloadHash });
+ if (lookup.kind === 'hit') {
+ return writeCachedResponse(res, lookup.entry);
+ }
+ if (lookup.kind === 'conflict') {
+ return writeConflict(res, {
+ route,
+ attemptedHash: lookup.attemptedHash,
+ existingHash: lookup.existingHash,
+ });
+ }
+ }
+
let verified;
try {
- verified = await verifyPayment({ paymentHeader, requirements });
+ verified = await verifyPayment({ paymentHeader, requirements, builderCode });
} catch (err) {
if (err.status === 402) return send402(res, { ...challenge, error: err.message });
return error(res, err.status || 502, err.code || 'verify_failed', err.message);
@@ -206,9 +377,26 @@ export function paidEndpoint(spec) {
return error(res, err.status || 502, err.code || 'settle_failed', err.message);
}
- res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ const paymentResponseHeader = encodePaymentResponseHeader(settled);
+ const contentType = `${mimeType}; charset=utf-8`;
+ const body = typeof result === 'string' ? result : JSON.stringify(result);
+
+ res.setHeader('x-payment-response', paymentResponseHeader);
res.setHeader('cache-control', 'no-store');
- res.setHeader('content-type', `${mimeType}; charset=utf-8`);
- res.end(typeof result === 'string' ? result : JSON.stringify(result));
+ res.setHeader('content-type', contentType);
+ res.end(body);
+
+ if (paymentId) {
+ await storeResponse({
+ route,
+ paymentId,
+ payloadHash,
+ status: 200,
+ body,
+ contentType,
+ paymentResponseHeader,
+ ttlSeconds: pidTtlSeconds,
+ });
+ }
};
}
diff --git a/api/_lib/x402/auth-hints.js b/api/_lib/x402/auth-hints.js
new file mode 100644
index 000000000..9aadf783b
--- /dev/null
+++ b/api/_lib/x402/auth-hints.js
@@ -0,0 +1,366 @@
+// x402 `auth-hints` extension — declare authentication paths a client can use
+// instead of (or in addition to) paying via x402.
+//
+// Spec: /tmp/x402-docs/specs/extensions/extension-auth-hints.md
+//
+// The extension surfaces in a 402 response under `extensions["auth-hints"]`
+// and maps specific `accepts[]` entries to required authentication methods.
+// Per spec, when a client picks an entry referenced by `acceptIndexes`, the
+// listed authentication is REQUIRED for that entry.
+//
+// We use the extension to advertise FREE-tier accept entries (amount=0) that
+// require either an OAuth 2.0 access token or a Sign-In-With-X proof. The
+// paid-endpoint helper short-circuits the payment dance when a valid auth
+// header is present, granting access without settling on-chain.
+//
+// Auth credentials travel as standard HTTP headers — NOT inside the x402
+// PaymentPayload:
+//
+// OAuth 2.0 (Bearer): Authorization: Bearer <access-token>
+// Sign-In-With-X: SIGN-IN-WITH-X: <base64-encoded-siwx-proof>
+//
+// The base64 SIWX proof is JSON-encoded with the shape:
+// { "type": "siwe"|"siws", "message": "...", "signature": "..." }
+// matching the existing /api/auth/{siwe,siws} verification flows.
+
+import { verifyMessage, getAddress } from 'ethers';
+import { env } from '../env.js';
+import { authenticateBearer, hasScope } from '../auth.js';
+import { parseSiweMessage } from '../siwe.js';
+import { parseSiwsMessage, verifySiwsSignature } from '../siws.js';
+
+export const AUTH_HINTS_EXTENSION_KEY = 'auth-hints';
+export const SIWX_HEADER = 'sign-in-with-x';
+
+// JSON-Schema for the extension body, kept inline so the 402 response is
+// self-describing for validators that don't fetch the spec separately. Mirrors
+// the schema fragment from the auth-hints spec.
+const AUTH_HINTS_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['authRequirements'],
+ properties: {
+ authRequirements: {
+ type: 'array',
+ minItems: 1,
+ items: {
+ type: 'object',
+ required: ['acceptIndexes', 'methods'],
+ properties: {
+ acceptIndexes: {
+ type: 'array',
+ items: { type: 'integer', minimum: 0 },
+ description: 'Indexes into accepts[] this requirement applies to.',
+ },
+ methods: {
+ type: 'array',
+ minItems: 1,
+ items: {
+ type: 'object',
+ required: ['type'],
+ properties: {
+ type: { type: 'string' },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+};
+
+function buildOauth2Method({
+ tokenType = 'Bearer',
+ authorizationServer = env.APP_ORIGIN,
+ tokenEndpoint = `${env.APP_ORIGIN}/api/oauth/token`,
+ registrationEndpoint = `${env.APP_ORIGIN}/api/oauth/register`,
+} = {}) {
+ const method = {
+ type: 'oauth2',
+ tokenType,
+ authorizationServer,
+ tokenEndpoint,
+ };
+ if (registrationEndpoint) method.registrationEndpoint = registrationEndpoint;
+ return method;
+}
+
+function buildSiwxMethod() {
+ return { type: 'sign-in-with-x' };
+}
+
+// Validate that the requirements reference at least one accept entry and that
+// each method has a recognized shape. Throws when misconfigured so the route
+// fails closed at boot instead of silently emitting an invalid 402.
+function validateAuthRequirements(authRequirements) {
+ if (!Array.isArray(authRequirements) || authRequirements.length === 0) {
+ throw new Error('declareAuthHintsExtension: authRequirements must be a non-empty array');
+ }
+ for (const r of authRequirements) {
+ if (!Array.isArray(r.acceptIndexes) || r.acceptIndexes.length === 0) {
+ throw new Error('declareAuthHintsExtension: acceptIndexes must be a non-empty array');
+ }
+ if (!Array.isArray(r.methods) || r.methods.length === 0) {
+ throw new Error('declareAuthHintsExtension: methods must be a non-empty array');
+ }
+ for (const m of r.methods) {
+ if (!m || typeof m.type !== 'string') {
+ throw new Error('declareAuthHintsExtension: each method needs a string `type`');
+ }
+ }
+ }
+}
+
+/**
+ * Build the `auth-hints` extension entry for a 402 PaymentRequired body.
+ *
+ * Two calling conventions:
+ * • Pass `{ authRequirements: [...] }` to declare requirements verbatim.
+ * • Pass `{ oauth2, siwx }` as shorthand where each entry is
+ * `{ acceptIndexes: number[], ...methodFields }`. We expand each into a
+ * full authRequirements entry with one method.
+ *
+ * Returns an object suitable for spreading into `build402Body`'s `extensions`
+ * argument, e.g. `extensions: { ...declareAuthHintsExtension({...}) }`.
+ */
+export function declareAuthHintsExtension(input) {
+ if (!input || typeof input !== 'object') {
+ throw new Error('declareAuthHintsExtension: input is required');
+ }
+
+ let authRequirements;
+ if (Array.isArray(input.authRequirements)) {
+ authRequirements = input.authRequirements;
+ } else {
+ authRequirements = [];
+ if (input.oauth2) {
+ if (!Array.isArray(input.oauth2.acceptIndexes)) {
+ throw new Error('declareAuthHintsExtension: oauth2.acceptIndexes is required');
+ }
+ authRequirements.push({
+ acceptIndexes: input.oauth2.acceptIndexes,
+ methods: [buildOauth2Method(input.oauth2)],
+ });
+ }
+ if (input.siwx) {
+ if (!Array.isArray(input.siwx.acceptIndexes)) {
+ throw new Error('declareAuthHintsExtension: siwx.acceptIndexes is required');
+ }
+ authRequirements.push({
+ acceptIndexes: input.siwx.acceptIndexes,
+ methods: [buildSiwxMethod()],
+ });
+ }
+ }
+
+ validateAuthRequirements(authRequirements);
+
+ return {
+ [AUTH_HINTS_EXTENSION_KEY]: {
+ info: { authRequirements },
+ schema: AUTH_HINTS_SCHEMA,
+ },
+ };
+}
+
+// ─── Header verification ────────────────────────────────────────────────────
+
+function extractBearerToken(req) {
+ const h = req.headers.authorization || req.headers.Authorization || '';
+ if (typeof h !== 'string') return null;
+ if (!h.toLowerCase().startsWith('bearer ')) return null;
+ return h.slice(7).trim() || null;
+}
+
+function readSiwxHeader(req) {
+ const raw =
+ req.headers[SIWX_HEADER] ||
+ req.headers['SIGN-IN-WITH-X'] ||
+ req.headers['Sign-In-With-X'];
+ return typeof raw === 'string' && raw.length > 0 ? raw : null;
+}
+
+function decodeSiwxProof(raw) {
+ let json;
+ try {
+ json = Buffer.from(String(raw), 'base64').toString('utf8');
+ } catch {
+ return null;
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(json);
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== 'object') return null;
+ const { type, message, signature } = parsed;
+ if (typeof message !== 'string' || typeof signature !== 'string') return null;
+ if (type !== 'siwe' && type !== 'siws') return null;
+ return { type, message, signature };
+}
+
+// Domain check matches /api/auth/siwe + /api/auth/siws — the SIWX message
+// MUST be addressed to this deployment's host (or localhost in dev) so a
+// proof issued for another resource can't be replayed here.
+function siwxDomainOk(domain) {
+ if (!domain) return false;
+ let appHost;
+ try {
+ appHost = new URL(env.APP_ORIGIN).host;
+ } catch {
+ return false;
+ }
+ const vercelHost = process.env.VERCEL_URL || null;
+ const isLocalDev =
+ process.env.VERCEL_ENV !== 'production' && process.env.VERCEL_ENV !== 'preview';
+ const allowedHosts = new Set([appHost, vercelHost].filter(Boolean));
+ if (allowedHosts.has(domain)) return true;
+ if (isLocalDev && /^localhost(:\d+)?$/.test(domain)) return true;
+ return false;
+}
+
+function withinTemporalBounds(fields) {
+ const now = Date.now();
+ if (fields.expirationTime && Date.parse(fields.expirationTime) < now) return false;
+ if (fields.notBefore && Date.parse(fields.notBefore) > now) return false;
+ if (fields.issuedAt) {
+ const issued = Date.parse(fields.issuedAt);
+ if (Number.isFinite(issued)) {
+ const skew = 10 * 60 * 1000;
+ if (issued < now - skew) return false;
+ if (issued > now + skew) return false;
+ }
+ }
+ return true;
+}
+
+async function verifySiweProof({ message, signature }) {
+ const fields = parseSiweMessage(message);
+ if (!fields) return null;
+ if (!siwxDomainOk(fields.domain)) return null;
+ if (!withinTemporalBounds(fields)) return null;
+ let recovered;
+ try {
+ recovered = verifyMessage(message, signature);
+ } catch {
+ return null;
+ }
+ let claimed;
+ try {
+ claimed = getAddress(fields.address);
+ } catch {
+ return null;
+ }
+ if (recovered.toLowerCase() !== claimed.toLowerCase()) return null;
+ return {
+ method: 'sign-in-with-x',
+ chain: 'eip155',
+ address: claimed,
+ chainId: fields.chainId || null,
+ };
+}
+
+function verifySiwsProof({ message, signature }) {
+ const fields = parseSiwsMessage(message);
+ if (!fields) return null;
+ if (!siwxDomainOk(fields.domain)) return null;
+ if (!withinTemporalBounds(fields)) return null;
+ let valid;
+ try {
+ valid = verifySiwsSignature(message, signature, fields.address);
+ } catch {
+ return null;
+ }
+ if (!valid) return null;
+ return {
+ method: 'sign-in-with-x',
+ chain: 'solana',
+ address: fields.address,
+ chainId: fields.chainId || null,
+ };
+}
+
+/**
+ * Attempt to authenticate a request via the headers signaled by an `auth-hints`
+ * extension. Tries OAuth Bearer first (cheap, in-process verify), then SIWX.
+ *
+ * Returns `null` when no auth header was presented (so the caller can fall
+ * through to the regular x402 payment flow). Returns
+ * `{ ok: true, principal: {...} }` on success and
+ * `{ ok: false, reason: '...' }` when a header was presented but failed to
+ * verify — callers should reject the request rather than silently downgrading
+ * to the payment flow (otherwise an invalid Bearer would be quietly ignored).
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {object} [opts]
+ * @param {string} [opts.audience] — OAuth token audience (defaults to MCP resource).
+ * @param {string} [opts.requiredScope] — OAuth scope required for this route.
+ */
+export async function authenticateAuthHintsRequest(req, opts = {}) {
+ const bearer = extractBearerToken(req);
+ if (bearer) {
+ const audience = opts.audience || env.MCP_RESOURCE;
+ const principal = await authenticateBearer(bearer, { audience });
+ if (!principal) return { ok: false, reason: 'invalid_token' };
+ if (opts.requiredScope && !hasScope(principal.scope, opts.requiredScope)) {
+ return { ok: false, reason: 'insufficient_scope' };
+ }
+ return {
+ ok: true,
+ principal: {
+ method: 'oauth2',
+ source: principal.source,
+ userId: principal.userId,
+ scope: principal.scope,
+ clientId: principal.clientId || null,
+ },
+ };
+ }
+
+ const siwxRaw = readSiwxHeader(req);
+ if (siwxRaw) {
+ const proof = decodeSiwxProof(siwxRaw);
+ if (!proof) return { ok: false, reason: 'invalid_siwx_proof' };
+ const verified =
+ proof.type === 'siwe'
+ ? await verifySiweProof(proof)
+ : verifySiwsProof(proof);
+ if (!verified) return { ok: false, reason: 'invalid_siwx_signature' };
+ return { ok: true, principal: verified };
+ }
+
+ return null;
+}
+
+// ─── Helpers for building free accept entries paired with auth-hints ───────
+
+// Zero-amount EVM accept that signals "free when authenticated". The payment
+// dance for such entries is short-circuited in paid-endpoint.js when a valid
+// auth header is presented. The asset + payTo still need to be valid for
+// schema validators that don't know to special-case amount=0.
+export function freeEvmAcceptForAuth({ network, asset, payTo, authType }) {
+ return {
+ scheme: 'exact',
+ network,
+ amount: '0',
+ asset,
+ payTo,
+ maxTimeoutSeconds: 60,
+ extra: {
+ name: 'USD Coin',
+ version: '2',
+ decimals: 6,
+ authRequired: authType,
+ },
+ };
+}
+
+export const __test = {
+ AUTH_HINTS_SCHEMA,
+ buildOauth2Method,
+ buildSiwxMethod,
+ decodeSiwxProof,
+ siwxDomainOk,
+ withinTemporalBounds,
+};
diff --git a/api/x402/permit2-paid-demo.js b/api/x402/permit2-paid-demo.js
new file mode 100644
index 000000000..6a61f4d2f
--- /dev/null
+++ b/api/x402/permit2-paid-demo.js
@@ -0,0 +1,269 @@
+// GET /api/x402/permit2-paid-demo
+//
+// Paid demo endpoint that exercises the Permit2 + EIP-2612 gas-sponsoring path
+// end-to-end. Unlike the rest of /api/x402/*, this route does NOT advertise an
+// EIP-3009 fallback — the only accept entry is Permit2-with-EIP-2612 — so any
+// settling client is forced through `x402ExactPermit2Proxy.settleWithPermit`.
+//
+// Why: USE-18 needs a target that proves a fresh wallet with USDC but ZERO ETH
+// (no gas) can pay through the endpoint. Selling against a route that exposes
+// EIP-3009 first hides the bug it's meant to verify, because @x402/evm clients
+// will silently pick the EIP-3009 path when one is offered.
+//
+// The 402 challenge advertises:
+// 1. One `exact`+`permit2` accept on Base mainnet (USDC) — emitted only when
+// CDP credentials are set, because Permit2 settlement runs through CDP's
+// x402ExactPermit2Proxy.
+// 2. Both `eip2612GasSponsoring` and `erc20ApprovalGasSponsoring` extensions
+// at the top level (build402Body auto-declares them whenever any accept
+// opts into Permit2).
+//
+// Buyers using @x402/* SDK clients pay with no ETH. The settled response
+// surfaces the on-chain tx hash plus a Basescan link so the buyer can confirm
+// the EIP-2612 permit + Permit2 transfer landed in a single transaction.
+
+import { wrap, cors, error } from '../_lib/http.js';
+import {
+ NETWORK_BASE_MAINNET,
+ X402Error,
+ buildBazaarSchema,
+ encodePaymentResponseHeader,
+ resolveResourceUrl,
+ send402,
+ settlePayment,
+ verifyPayment,
+} from '../_lib/x402-spec.js';
+import { env } from '../_lib/env.js';
+
+const ROUTE = '/api/x402/permit2-paid-demo';
+const PRICE_ATOMICS = '1000'; // $0.001 USDC (6 decimals)
+
+const ROUTE_DESCRIPTION =
+ 'Permit2 + EIP-2612 Gas Sponsoring Demo — forces the gasless Permit2 path so ' +
+ 'a fresh wallet holding USDC but ZERO ETH can complete the flow. The CDP ' +
+ 'facilitator submits the EIP-2612 permit and the Permit2 transfer atomically ' +
+ 'in a single transaction via x402ExactPermit2Proxy.settleWithPermit. The ' +
+ 'response carries the on-chain tx hash + Basescan link so callers can confirm ' +
+ 'the permit + transfer landed together. Pay $0.001 USDC on Base mainnet.';
+
+const DISCOVERY_INPUT_EXAMPLE = {};
+
+const DISCOVERY_INPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ properties: {},
+ additionalProperties: false,
+};
+
+const DISCOVERY_OUTPUT_EXAMPLE = {
+ ok: true,
+ demo: 'permit2-eip2612-gas-sponsoring',
+ method: 'permit2',
+ supportsEip2612: true,
+ payer: '0x4022de2d36c334e73c7a108805cea11c0564f402',
+ network: 'eip155:8453',
+ asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
+ amountAtomics: '1000',
+ transaction: '0x9c0a7e5ad5c9c0bb6f04f6ad9c52f4f44bb6c5d9c0a7e5ad5c9c0bb6f04f6ad9',
+ explorer:
+ 'https://basescan.org/tx/0x9c0a7e5ad5c9c0bb6f04f6ad9c52f4f44bb6c5d9c0a7e5ad5c9c0bb6f04f6ad9',
+ settledAt: '2026-05-21T18:30:00.000Z',
+ proxy: '0x402085c248EeA27D92E8b30b2C58ed07f9E20001',
+};
+
+const DISCOVERY_OUTPUT_SCHEMA = {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: [
+ 'ok',
+ 'demo',
+ 'method',
+ 'payer',
+ 'network',
+ 'asset',
+ 'amountAtomics',
+ 'transaction',
+ 'explorer',
+ 'settledAt',
+ 'proxy',
+ ],
+ properties: {
+ ok: { type: 'boolean', const: true },
+ demo: { type: 'string', const: 'permit2-eip2612-gas-sponsoring' },
+ method: { type: 'string', const: 'permit2' },
+ supportsEip2612: { type: 'boolean' },
+ payer: { type: ['string', 'null'] },
+ network: { type: 'string' },
+ asset: { type: 'string' },
+ amountAtomics: { type: 'string' },
+ transaction: { type: 'string' },
+ explorer: { type: 'string', format: 'uri' },
+ settledAt: { type: 'string', format: 'date-time' },
+ proxy: {
+ type: 'string',
+ description:
+ 'Canonical x402ExactPermit2Proxy address that settled the EIP-2612 ' +
+ 'permit + Permit2 transfer atomically.',
+ },
+ },
+};
+
+const ROUTE_BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'GET', queryParams: DISCOVERY_INPUT_EXAMPLE },
+ output: { type: 'json', example: DISCOVERY_OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'GET',
+ queryParamsSchema: DISCOVERY_INPUT_SCHEMA,
+ outputSchema: DISCOVERY_OUTPUT_SCHEMA,
+ }),
+};
+
+// Canonical x402ExactPermit2Proxy address (same across all EVM chains per
+// the USE-18 spec). The facilitator submits settleWithPermit() against this
+// contract, atomically applying the EIP-2612 permit and executing the
+// Permit2 transfer in a single transaction.
+const X402_EXACT_PERMIT2_PROXY = '0x402085c248EeA27D92E8b30b2C58ed07f9E20001';
+
+// Single Permit2-forced accept entry — no EIP-3009 sibling. The Bazaar
+// browser modal in public/x402.js doesn't sign Permit2, so this endpoint is
+// SDK-only by design (paying through it requires @x402/evm or compatible).
+function buildRequirements(resourceUrl) {
+ if (!env.X402_PAY_TO_BASE) {
+ throw new X402Error(
+ 'no_payto_configured',
+ 'permit2-paid-demo: X402_PAY_TO_BASE is not set',
+ 500,
+ );
+ }
+ if (!env.CDP_API_KEY_ID || !env.CDP_API_KEY_SECRET) {
+ // Permit2 settlement is a CDP-only path — without CDP creds the
+ // facilitator can't call settleWithPermit. Surface a clean 402 so the
+ // client doesn't waste an EIP-2612 signature on a route we can't honor.
+ throw new X402Error(
+ 'permit2_facilitator_unavailable',
+ 'permit2-paid-demo requires CDP_API_KEY_ID + CDP_API_KEY_SECRET ' +
+ '(Permit2 settlement runs through CDP x402ExactPermit2Proxy)',
+ 402,
+ );
+ }
+ return [
+ {
+ scheme: 'exact',
+ network: NETWORK_BASE_MAINNET,
+ amount: PRICE_ATOMICS,
+ payTo: env.X402_PAY_TO_BASE,
+ asset: env.X402_ASSET_ADDRESS_BASE,
+ maxTimeoutSeconds: 60,
+ resource: resourceUrl,
+ // `name` + `version` MUST match Base USDC's on-chain EIP-712 domain;
+ // `assetTransferMethod: 'permit2'` is what @x402/evm's ExactEvmScheme
+ // keys on, and `supportsEip2612: true` tells the scheme to sign an
+ // EIP-2612 permit when its Permit2 allowance is insufficient so the
+ // facilitator can submit it via settleWithPermit.
+ extra: {
+ name: 'USD Coin',
+ version: '2',
+ decimals: 6,
+ assetTransferMethod: 'permit2',
+ supportsEip2612: true,
+ },
+ },
+ ];
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET');
+ return error(res, 405, 'method_not_allowed', 'use GET');
+ }
+
+ const resourceUrl = resolveResourceUrl(req, ROUTE);
+ let requirements;
+ try {
+ requirements = buildRequirements(resourceUrl);
+ } catch (err) {
+ if (err instanceof X402Error && err.status === 402) {
+ return send402(res, {
+ resourceUrl,
+ accepts: [],
+ description: ROUTE_DESCRIPTION,
+ bazaar: ROUTE_BAZAAR,
+ error: err.message,
+ });
+ }
+ return error(
+ res,
+ err.status || 500,
+ err.code || 'misconfigured',
+ err.message || 'permit2-paid-demo misconfigured',
+ );
+ }
+
+ const challenge = {
+ resourceUrl,
+ accepts: requirements,
+ description: ROUTE_DESCRIPTION,
+ bazaar: ROUTE_BAZAAR,
+ };
+
+ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];
+ if (!paymentHeader) return send402(res, challenge);
+
+ let verified;
+ try {
+ verified = await verifyPayment({ paymentHeader, requirements });
+ } catch (err) {
+ if (err.status === 402) return send402(res, { ...challenge, error: err.message });
+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);
+ }
+
+ // Guard against an SDK that ignored our `assetTransferMethod: 'permit2'`
+ // hint and sent an EIP-3009 payload anyway. We only advertise Permit2 on
+ // this route, so anything else is a client bug — fail with a clean 402
+ // rather than letting the facilitator reject the mismatched payload.
+ const inner = verified.paymentPayload?.payload;
+ if (!inner || typeof inner !== 'object' || !inner.permit2Authorization) {
+ return send402(res, {
+ ...challenge,
+ error:
+ 'permit2-paid-demo only accepts Permit2 payloads — the payload had no ' +
+ 'permit2Authorization. Use @x402/evm or another client that supports ' +
+ 'the Permit2 asset-transfer method with EIP-2612 gas sponsoring.',
+ });
+ }
+
+ let settled;
+ try {
+ settled = await settlePayment({
+ paymentPayload: verified.paymentPayload,
+ requirement: verified.requirement,
+ });
+ } catch (err) {
+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);
+ }
+
+ const txHash = settled.transaction;
+ const result = {
+ ok: true,
+ demo: 'permit2-eip2612-gas-sponsoring',
+ method: 'permit2',
+ supportsEip2612: true,
+ payer: settled.payer || verified.payer || null,
+ network: verified.requirement.network,
+ asset: verified.requirement.asset,
+ amountAtomics: verified.requirement.amount,
+ transaction: txHash,
+ explorer: `https://basescan.org/tx/${txHash}`,
+ settledAt: new Date().toISOString(),
+ proxy: X402_EXACT_PERMIT2_PROXY,
+ };
+
+ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify(result));
+});
diff --git a/api/x402/skill-marketplace.js b/api/x402/skill-marketplace.js
index b807d307d..ea219dfc7 100644
--- a/api/x402/skill-marketplace.js
+++ b/api/x402/skill-marketplace.js
@@ -180,6 +180,13 @@ export default paidEndpoint({
networks: ['base', 'solana'],
description: DESCRIPTION,
bazaar: BAZAAR,
+ siwx: {
+ statement: 'Sign in to refresh the three.ws skill marketplace without re-paying.',
+ // 24h grant so a returning agent can re-poll without paying; after the
+ // window expires they pay once more to keep the catalog "paid-fresh".
+ ttlSeconds: 24 * 3600,
+ expirationSeconds: 300,
+ },
async handler({ req }) {
const skill = req.query?.skill ? String(req.query.skill).trim() : null;
const limitRaw = parseInt(req.query?.limit, 10);
diff --git a/docs/club/RELEASE_CHECKLIST.md b/docs/club/RELEASE_CHECKLIST.md
new file mode 100644
index 000000000..54d88c665
--- /dev/null
+++ b/docs/club/RELEASE_CHECKLIST.md
@@ -0,0 +1,49 @@
+# /club release checklist
+
+Run on a clean checkout after `npm install && npm run build`. This file is
+human-signed; CI does not check it.
+
+## Local smoke
+- [ ] `npm run dev` boots, `/club` loads under 5s on broadband.
+- [ ] Venue renders authored GLB, no console errors.
+- [ ] All four dancers visible at backstage doors.
+- [ ] `npm test` green (unit + e2e).
+- [ ] `npm run test:e2e` green standalone.
+
+## Real wallet (mainnet)
+- [ ] Connect Phantom on Solana. Tip pole 1 for $0.001 USDC.
+- [ ] On-chain confirmation in Solscan within 5s.
+- [ ] Dancer 1 walks from backstage to pole.
+- [ ] Music for the chosen style fades up; ambience fades down.
+- [ ] Volumetric spotlight cone ramps up.
+- [ ] Tip row appears in the right-panel feed.
+- [ ] Open `/club` in a second browser; same tip row appears via SSE.
+
+## Cron payouts
+- [ ] Repeat tips until dancer 1's unpaid total exceeds 0.005 USDC.
+- [ ] Trigger `/api/cron/club-payouts` with `CRON_SECRET`.
+- [ ] On-chain payout signature recorded in `club_payouts`.
+- [ ] `club_tips.paid_at` set on swept rows.
+- [ ] Leaderboard "unpaid" column drops for dancer 1.
+
+## Mobile
+- [ ] iPhone 12 Safari: profile `medium`, ≥30 fps.
+- [ ] Pixel 6 Chrome: profile `medium`, ≥30 fps.
+
+## Deploy
+- [ ] Vercel preview deploy of the branch passes both x402 endpoints
+ reachable + SSE keepalive.
+- [ ] Promote to production.
+- [ ] Verify production OG card renders for `/club` via Twitter card
+ validator.
+- [ ] Verify x402 bazaar discovery: `curl -i https://three.ws/api/x402/dance-tip`
+ returns 402 with the discovery extension intact.
+
+## Secrets — reference only
+Never commit secret values to this file. The mainnet checklist relies on:
+
+- `PHANTOM_TEST_WALLET` (held by the release engineer; not stored in repo).
+- `CRON_SECRET` (Vercel env: `vercel env pull` to read locally).
+- `SOLANA_RPC_URL`, `BASE_RPC_URL` (Vercel env).
+- Treasury keypair env vars used by `/api/cron/club-payouts` (see
+ `vercel env ls`).
diff --git a/package-lock.json b/package-lock.json
index 23725199a..b9f4fbf1e 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -109,6 +109,7 @@
},
"devDependencies": {
"@gltf-transform/functions": "^4.3.0",
+ "@playwright/test": "^1.60.0",
"@x402/fetch": "^2.11.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
@@ -14884,6 +14885,22 @@
"url": "https://opencollective.com/pkgr"
}
},
+ "node_modules/@playwright/test": {
+ "version": "1.60.0",
+ "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.60.0.tgz",
+ "integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright": "1.60.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/@poppinss/colors": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@poppinss/colors/-/colors-4.1.6.tgz",
@@ -45903,12 +45920,12 @@
}
},
"node_modules/playwright": {
- "version": "1.59.1",
- "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz",
- "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==",
+ "version": "1.60.0",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.60.0.tgz",
+ "integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
"license": "Apache-2.0",
"dependencies": {
- "playwright-core": "1.59.1"
+ "playwright-core": "1.60.0"
},
"bin": {
"playwright": "cli.js"
@@ -45921,9 +45938,9 @@
}
},
"node_modules/playwright-core": {
- "version": "1.59.1",
- "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz",
- "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==",
+ "version": "1.60.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.60.0.tgz",
+ "integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
diff --git a/package.json b/package.json
index 7186328ad..c5c916b90 100644
--- a/package.json
+++ b/package.json
@@ -184,6 +184,7 @@
},
"devDependencies": {
"@gltf-transform/functions": "^4.3.0",
+ "@playwright/test": "^1.60.0",
"@x402/fetch": "^2.11.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
diff --git a/pages/a-edit.html b/pages/a-edit.html
index 4dae4f243..e8498c2a8 100644
--- a/pages/a-edit.html
+++ b/pages/a-edit.html
@@ -239,6 +239,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body>
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index 677702c53..ca49e1e8d 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -985,6 +985,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body>
diff --git a/pages/agent-home.html b/pages/agent-home.html
index 88c19c639..bdd555a32 100644
--- a/pages/agent-home.html
+++ b/pages/agent-home.html
@@ -768,6 +768,7 @@
}
</style>
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<a href="#main" class="skip-link">Skip to main content</a>
diff --git a/pages/app-demo.html b/pages/app-demo.html
index 85d9c04e3..bf53754c8 100644
--- a/pages/app-demo.html
+++ b/pages/app-demo.html
@@ -51,6 +51,7 @@
<link rel="stylesheet" href="/fonts/fonts.css" />
<script defer type="module" src="/src/app.js"></script>
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body class="app-demo-body">
<header>
diff --git a/pages/app.html b/pages/app.html
index 5834100fd..a2a73a31e 100644
--- a/pages/app.html
+++ b/pages/app.html
@@ -50,6 +50,7 @@
<link rel="stylesheet" href="/footer.css" />
<script defer type="module" src="/src/app.js"></script>
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<header>
diff --git a/pages/avatar-edit.html b/pages/avatar-edit.html
index 551402428..d0e6b07e0 100644
--- a/pages/avatar-edit.html
+++ b/pages/avatar-edit.html
@@ -9,6 +9,7 @@
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<style>
:root {
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index dbdd59d0b..faa1f8a88 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -11,6 +11,7 @@
<link rel="stylesheet" href="/nav.css" />
<script defer src="/footer-newsletter.js"></script>
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
diff --git a/pages/community.html b/pages/community.html
index 8cb9f455d..aacfd5ba4 100644
--- a/pages/community.html
+++ b/pages/community.html
@@ -10,6 +10,7 @@
<link rel="stylesheet" href="/community.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body class="features-page">
diff --git a/pages/create.html b/pages/create.html
index 406187efe..058a73a5c 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -496,6 +496,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
<style>
/* ── Site nav (shared with index.html) ── */
diff --git a/pages/creating.html b/pages/creating.html
index 070189005..b905d0760 100644
--- a/pages/creating.html
+++ b/pages/creating.html
@@ -11,6 +11,7 @@
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
diff --git a/pages/features.html b/pages/features.html
index 7a6b24ae8..33eb54010 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -44,6 +44,7 @@
<script defer src="/footer-newsletter.js"></script>
<script defer src="/home-polish.js"></script>
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
diff --git a/pages/home.html b/pages/home.html
index 7e451d06f..5afd6a908 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -54,6 +54,7 @@
<script defer src="/footer-newsletter.js"></script>
<script defer src="/home-polish.js"></script>
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
diff --git a/pages/marketplace.html b/pages/marketplace.html
index e9339d2a4..f156169ba 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -1102,6 +1102,7 @@
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body class="market-page">
diff --git a/pages/playground.html b/pages/playground.html
index 93a623d41..7654587c2 100644
--- a/pages/playground.html
+++ b/pages/playground.html
@@ -9,6 +9,7 @@
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script
type="module"
src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
diff --git a/pages/pose.html b/pages/pose.html
index 80a5dd60d..68bd7968a 100644
--- a/pages/pose.html
+++ b/pages/pose.html
@@ -19,6 +19,7 @@
<link rel="stylesheet" href="/footer.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
diff --git a/pages/profile.html b/pages/profile.html
index 2c6f48608..97ebc09dd 100644
--- a/pages/profile.html
+++ b/pages/profile.html
@@ -665,6 +665,7 @@
}
</style>
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
</head>
<body>
<header class="site-header">
diff --git a/pages/pump-coin-page.html b/pages/pump-coin-page.html
index 93b9ad27e..1072cba2c 100644
--- a/pages/pump-coin-page.html
+++ b/pages/pump-coin-page.html
@@ -65,6 +65,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body>
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index c488fb868..3853c42d1 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -24,6 +24,7 @@
<link rel="stylesheet" href="/footer.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/pump-dashboard.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
</head>
diff --git a/pages/pump-live.html b/pages/pump-live.html
index bc90de947..1f8c28246 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -139,6 +139,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body>
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index bb863168d..52d1296f4 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -8,6 +8,7 @@
<link rel="canonical" href="/pump-visualizer">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<style>
:root {
--vz-bg: #05060a;
diff --git a/pages/three-ws-launch-week.html b/pages/three-ws-launch-week.html
index cb24bafbb..bd90bc0c7 100644
--- a/pages/three-ws-launch-week.html
+++ b/pages/three-ws-launch-week.html
@@ -719,6 +719,7 @@
</style>
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
</head>
<body>
diff --git a/pages/tutorial.html b/pages/tutorial.html
index d70bdb9ac..c821e3ee5 100644
--- a/pages/tutorial.html
+++ b/pages/tutorial.html
@@ -32,6 +32,7 @@
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"
/>
+ <link rel="stylesheet" href="/mobile.css" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script defer src="/footer-newsletter.js"></script>
diff --git a/pages/tutorials.html b/pages/tutorials.html
index e11da75b2..d7c3fe572 100644
--- a/pages/tutorials.html
+++ b/pages/tutorials.html
@@ -31,6 +31,7 @@
<link rel="stylesheet" href="/home.css" />
<link rel="stylesheet" href="/footer.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<script defer src="/footer-newsletter.js"></script>
<script defer src="/tutorials-manifest.js"></script>
<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
diff --git a/pages/walk.html b/pages/walk.html
index db714b76c..08221a422 100644
--- a/pages/walk.html
+++ b/pages/walk.html
@@ -29,6 +29,7 @@
<link rel="stylesheet" href="/footer.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
diff --git a/public/mobile.css b/public/mobile.css
new file mode 100644
index 000000000..ccb24bae7
--- /dev/null
+++ b/public/mobile.css
@@ -0,0 +1,65 @@
+/* ── Site-wide mobile polish ─────────────────────────────────────────────
+ * Loaded after every page-specific stylesheet so the rules below win on
+ * equal specificity. Scope is intentionally narrow: cross-cutting iOS
+ * Safari / mobile-Chrome platform quirks that bite every page. Per-page
+ * mobile layout still lives in each page's own stylesheet.
+ */
+
+/* Tap-highlight + 300ms delay. Coarse-pointer media query keeps these off
+ * desktop, where tap-highlight is irrelevant and touch-action would
+ * suppress double-click-to-zoom in some contexts. */
+@media (hover: none) and (pointer: coarse) {
+ a,
+ button,
+ [role='button'],
+ summary,
+ input[type='submit'],
+ input[type='button'],
+ input[type='reset'] {
+ -webkit-tap-highlight-color: transparent;
+ touch-action: manipulation;
+ }
+ label,
+ select,
+ input[type='checkbox'],
+ input[type='radio'] {
+ -webkit-tap-highlight-color: transparent;
+ }
+}
+
+/* Horizontal-scroll guard. A few px of off-by-one overflow on one child
+ * shouldn't give the whole page a horizontal scrollbar on a phone.
+ * overflow-x: clip is safer than overflow: hidden because it does not
+ * also clamp vertical scrolling — and unlike hidden it cannot create a
+ * new scroll container that breaks position: sticky higher in the tree. */
+@media (max-width: 768px) {
+ html,
+ body {
+ overflow-x: clip;
+ }
+}
+
+/* iOS Safari zooms the viewport on focus when an input's computed
+ * font-size is < 16px. Bump unstyled inputs/textareas/selects so that
+ * tapping a search/email field doesn't punt the layout sideways. Pages
+ * that intentionally use small inputs use class selectors with higher
+ * specificity, so designed sizes still win where they matter. */
+@media (max-width: 768px) {
+ input:not([type='checkbox']):not([type='radio']):not([type='range']):not([type='color']),
+ textarea,
+ select {
+ font-size: max(16px, 1em);
+ }
+}
+
+/* Reusable safe-area utility for any fixed-bottom UI that doesn't already
+ * handle the iPhone home indicator. Apply via class — no automatic
+ * targeting, so existing layouts are untouched. */
+@supports (padding: env(safe-area-inset-bottom)) {
+ .mobile-safe-bottom {
+ padding-bottom: env(safe-area-inset-bottom);
+ }
+ .mobile-safe-top {
+ padding-top: env(safe-area-inset-top);
+ }
+}
diff --git a/public/x402.js b/public/x402.js
index 19b863e30..597c73fa8 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -31,6 +31,15 @@
// result. Vanilla JS, no bundler required.
const VERSION = '0.1.0';
+
+// SIWX ("Sign-In-With-X" / CAIP-122) lets a wallet that has already paid for
+// an endpoint re-enter it by signing a challenge instead of paying again. The
+// server advertises support by including `extensions['sign-in-with-x']` in the
+// 402 body; clients submit signed proofs via the `SIGN-IN-WITH-X` header. See
+// prompts/siwx/PLAN.md for the full architecture.
+const SIWX_HEADER = 'SIGN-IN-WITH-X';
+const SIWX_EXTENSION_KEY = 'sign-in-with-x';
+
const ORIGIN = (() => {
// Resolve the origin that hosts this script — used as the API origin for
// the prepare/encode helpers. Falls back to the merchant origin in same-
@@ -105,6 +114,116 @@ function b64decode(str) {
}
}
+// ─────────────────────────────────────────────────────────── SIWX helpers ────
+
+function extractSiwxExtension(body) {
+ const ext = body?.extensions?.[SIWX_EXTENSION_KEY];
+ if (!ext || !ext.info || !Array.isArray(ext.supportedChains) || !ext.supportedChains.length) return null;
+ return ext;
+}
+
+// Returns { chain, kind: 'evm' | 'solana' } or null. `chain` is the matching
+// entry from `ext.supportedChains` whose signature type matches the wallet kind.
+function pickSiwxChain(ext, walletKind) {
+ for (const chain of ext.supportedChains) {
+ if (walletKind === 'evm' && chain.type === 'eip191') return { chain, kind: 'evm' };
+ if (walletKind === 'solana' && chain.type === 'ed25519') return { chain, kind: 'solana' };
+ }
+ return null;
+}
+
+// Build the CAIP-122 message string. The server rebuilds the same string from
+// payload fields when verifying — any line-by-line drift makes the recovered
+// signer mismatch payload.address and the signature is rejected.
+//
+// EVM path mirrors EIP-4361 / siwe library's prepareMessage (chain ref =
+// numeric chainId extracted from "eip155:<n>"). Solana path mirrors SIWS
+// (chain ref = genesis hash extracted from "solana:<ref>"). Optional fields
+// are omitted entirely when absent from server info.
+function buildSiwxMessage(info, chain, address) {
+ const isEvm = chain.type === 'eip191';
+ const accountHeader = isEvm
+ ? `${info.domain} wants you to sign in with your Ethereum account:`
+ : `${info.domain} wants you to sign in with your Solana account:`;
+ const [, chainTail = ''] = String(chain.chainId).split(':');
+ const chainRef = isEvm ? String(parseInt(chainTail, 10)) : chainTail;
+
+ const lines = [accountHeader, address, ''];
+ if (info.statement) lines.push(info.statement, '');
+ lines.push(`URI: ${info.uri}`);
+ lines.push(`Version: ${info.version || '1'}`);
+ lines.push(`Chain ID: ${chainRef}`);
+ lines.push(`Nonce: ${info.nonce}`);
+ lines.push(`Issued At: ${info.issuedAt}`);
+ if (info.expirationTime) lines.push(`Expiration Time: ${info.expirationTime}`);
+ if (info.notBefore) lines.push(`Not Before: ${info.notBefore}`);
+ if (info.requestId !== undefined && info.requestId !== null) lines.push(`Request ID: ${info.requestId}`);
+ if (Array.isArray(info.resources) && info.resources.length) {
+ lines.push('Resources:');
+ for (const r of info.resources) lines.push(`- ${r}`);
+ }
+ return lines.join('\n');
+}
+
+// Base64-encoded JSON per x402 v2 spec (CHANGELOG-v2.md line 335). CAIP-122
+// fields are all ASCII/Latin-1, so the unescape+encodeURIComponent dance
+// matches what btoa expects without garbling unicode (none is sent anyway).
+function encodeSiwxHeaderValue(payload) {
+ const json = JSON.stringify(payload);
+ if (typeof Buffer !== 'undefined') return Buffer.from(json, 'utf8').toString('base64');
+ return btoa(unescape(encodeURIComponent(json)));
+}
+
+// Base58 (Bitcoin alphabet) — Solana's encoding for both addresses and
+// signatures. Inlined here to avoid pulling in a bundler dependency; this
+// matches what `bs58` does on the server side (api/_lib/siws.js).
+const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+function base58encode(bytes) {
+ if (!bytes || bytes.length === 0) return '';
+ let leadingZeros = 0;
+ while (leadingZeros < bytes.length && bytes[leadingZeros] === 0) leadingZeros++;
+ let n = 0n;
+ for (let i = 0; i < bytes.length; i++) n = (n << 8n) | BigInt(bytes[i]);
+ let out = '';
+ while (n > 0n) {
+ out = BASE58_ALPHABET[Number(n % 58n)] + out;
+ n /= 58n;
+ }
+ for (let i = 0; i < leadingZeros; i++) out = BASE58_ALPHABET[0] + out;
+ return out;
+}
+
+// EIP-55 checksum the address before signing. MetaMask returns addresses in
+// lowercase via eth_requestAccounts, but the server rebuilds the SIWE message
+// with a checksummed address (siwe library's prepareMessage always upgrades
+// case via getAddress). If we sign a lowercase-address message and send the
+// lowercase address in the payload, the server's recovered signer (from the
+// checksummed-address message it builds) differs from payload.address and
+// verification fails. So checksum here, then use the same string everywhere.
+//
+// Keccak-256 lives in @noble/hashes which the server already uses
+// (api/_lib/siws.js → @noble/curves). Pulled in dynamically via esm.sh only
+// when SIWX EVM sign-in is actually attempted, mirroring loadSolanaWeb3.
+let _evmChecksum = null;
+async function loadEvmChecksum() {
+ if (_evmChecksum) return _evmChecksum;
+ const sha3 = await import('https://esm.sh/@noble/[email protected]/sha3?bundle');
+ const keccak = sha3.keccak_256;
+ _evmChecksum = (addr) => {
+ const a = String(addr).toLowerCase().replace(/^0x/, '');
+ if (!/^[0-9a-f]{40}$/.test(a)) throw new Error(`invalid EVM address: ${addr}`);
+ const hashBytes = keccak(new TextEncoder().encode(a));
+ let hex = '';
+ for (let i = 0; i < hashBytes.length; i++) hex += hashBytes[i].toString(16).padStart(2, '0');
+ let out = '0x';
+ for (let i = 0; i < 40; i++) {
+ out += parseInt(hex[i], 16) >= 8 ? a[i].toUpperCase() : a[i];
+ }
+ return out;
+ };
+ return _evmChecksum;
+}
+
// ───────────────────────────────────────────────────────────────── styles ────
const STYLE_ID = 'x402-styles';
@@ -262,6 +381,29 @@ const STYLES = `
.x402-pay-btn:active:not(:disabled) { transform: translateY(1px); }
.x402-pay-btn:disabled { background: #c8ccd4; cursor: not-allowed; }
+.x402-pay-secondary {
+ width: 100%; padding: 12px 14px;
+ background: #ffffff; color: #0d0f15;
+ border: 1.5px solid #e2e5ec; border-radius: 11px;
+ font-size: 14px; font-weight: 600; font-family: inherit;
+ cursor: pointer; letter-spacing: -0.005em;
+ margin-top: 6px;
+ transition: border-color 0.12s, background 0.12s, transform 0.05s;
+}
+.x402-pay-secondary:hover:not(:disabled) { border-color: #0a84ff; background: #f7faff; }
+.x402-pay-secondary:active:not(:disabled) { transform: translateY(1px); }
+
+.x402-siwx-hint {
+ font-size: 11px; color: #5a6378; text-align: center;
+ margin-top: 8px; line-height: 1.4;
+}
+.x402-siwx-fallback {
+ font-size: 12px; color: #b45309; line-height: 1.45;
+ padding: 8px 10px; border-radius: 8px;
+ background: #fffbeb; border: 1px solid #fde68a;
+ margin-bottom: 6px;
+}
+
.x402-error-box {
padding: 12px 14px; border-radius: 10px;
background: #fef2f2; border: 1px solid #fecaca; color: #b91c1c;
@@ -337,6 +479,10 @@ const STYLES = `
.x402-pay-btn { background: #ffffff; color: #0d0f15; }
.x402-pay-btn:hover:not(:disabled) { background: #e7e9ee; }
.x402-pay-btn:disabled { background: #2a2e3d; color: #5a6378; }
+ .x402-pay-secondary { background: #1a1d29; border-color: #2a2e3d; color: #e6e8f0; }
+ .x402-pay-secondary:hover:not(:disabled) { background: #20243a; border-color: #0a84ff; }
+ .x402-siwx-hint { color: #8a90a8; }
+ .x402-siwx-fallback { background: #2a1d10; border-color: #78350f; color: #fcd34d; }
.x402-step-num { background: #14161f; border-color: #2a2e3d; color: #8a90a8; }
.x402-result { background: #1a1d29; border-color: #2a2e3d; color: #e6e8f0; }
.x402-receipt { background: linear-gradient(180deg, #0b1f17 0%, #14161f 100%); border-color: #14532d; }
@@ -461,6 +607,29 @@ class CheckoutModal {
const evmDetected = typeof window !== 'undefined' && window.ethereum;
const solanaAccept = this.challenge?.accepts.find((a) => isSolanaNetwork(a.network));
const evmAccept = this.challenge?.accepts.find(isEip3009Accept);
+
+ // SIWX-first path: when the 402 advertises sign-in-with-x AND we have a
+ // compatible wallet, lead with "Sign in with wallet" (primary) and
+ // demote pay to a secondary action. payFlowOverride is set true when
+ // the user explicitly chooses to pay (either by clicking the secondary
+ // button, or after a 401/402 siwx_not_paid retry told us this wallet
+ // hasn't actually paid for this resource yet).
+ if (this.siwx && !this.payFlowOverride) {
+ const siwxSolana = phantomDetected && solanaAccept ? pickSiwxChain(this.siwx, 'solana') : null;
+ const siwxEvm = evmDetected && evmAccept ? pickSiwxChain(this.siwx, 'evm') : null;
+ if (siwxSolana || siwxEvm) {
+ this.renderSiwxChoice({
+ siwxSolana,
+ siwxEvm,
+ solanaAccept,
+ evmAccept,
+ phantomDetected,
+ evmDetected,
+ });
+ return;
+ }
+ }
+
const buttons = [];
if (solanaAccept) {
buttons.push(`
@@ -480,8 +649,12 @@ class CheckoutModal {
</button>
`);
}
+ const fallbackBox = this.siwxFallbackNotice
+ ? `<div class="x402-siwx-fallback">${escapeHtml(this.siwxFallbackNotice)}</div>`
+ : '';
this.bodyEl.innerHTML = `
${this.renderSteps('connect', { discover: 'done' })}
+ ${fallbackBox}
<div class="x402-wallet-buttons">${buttons.join('')}</div>
`;
const onClick = (e) => {
@@ -494,6 +667,31 @@ class CheckoutModal {
this.bodyEl.querySelectorAll('[data-wallet]').forEach((b) => b.addEventListener('click', onClick));
}
+ renderSiwxChoice({ siwxSolana, siwxEvm, solanaAccept, evmAccept }) {
+ const priceText = formatAmount(this.accept.amount, this.accept.extra?.decimals ?? 6);
+ // One primary button — internally we pick the wallet kind that matches
+ // the supported SIWX chains AND the detected wallets. Phantom wins ties
+ // to match the existing modal's default preference.
+ const siwxTarget = siwxSolana
+ ? { kind: 'solana', chain: siwxSolana.chain, payAccept: solanaAccept }
+ : { kind: 'evm', chain: siwxEvm.chain, payAccept: evmAccept };
+ const siwxLabel = siwxTarget.kind === 'solana' ? 'Sign in with Phantom' : 'Sign in with wallet';
+ this.bodyEl.innerHTML = `
+ ${this.renderSteps('connect', { discover: 'done' })}
+ <button class="x402-pay-btn" data-action="siwx">${siwxLabel}</button>
+ <button class="x402-pay-secondary" data-action="pay">Pay ${priceText} USDC instead</button>
+ <div class="x402-siwx-hint">Already paid for this once? Sign in to re-enter without paying again.</div>
+ `;
+ this.bodyEl.querySelector('[data-action="siwx"]').addEventListener('click', () => {
+ if (siwxTarget.kind === 'solana') this.runSiwxSolana(siwxTarget.chain, siwxTarget.payAccept);
+ else this.runSiwxEvm(siwxTarget.chain, siwxTarget.payAccept);
+ });
+ this.bodyEl.querySelector('[data-action="pay"]').addEventListener('click', () => {
+ this.payFlowOverride = true;
+ this.renderConnect();
+ });
+ }
+
renderProgress(activeId, meta = {}) {
this.bodyEl.innerHTML = this.renderSteps(activeId, {
discover: 'done',
@@ -558,6 +756,9 @@ class CheckoutModal {
try {
const challenge = await discoverChallenge(this.opts);
this.challenge = challenge;
+ this.siwx = extractSiwxExtension(challenge);
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = null;
// Prefer Solana when Phantom is present, else first EIP-3009 EVM
// entry (skipping Permit2 siblings the modal can't sign for), else
// first accept.
@@ -739,6 +940,158 @@ class CheckoutModal {
this.renderError('verify', friendlyError(err));
}
}
+
+ async runSiwxEvm(chain, payAccept) {
+ this.renderProgress('connect', { text: 'Opening browser wallet…' });
+ try {
+ const eth = window.ethereum;
+ if (!eth) throw new Error('No EVM wallet detected');
+ const accounts = await eth.request({ method: 'eth_requestAccounts' });
+ const rawAddress = accounts?.[0];
+ if (!rawAddress) throw new Error('Wallet did not return an account');
+ const checksum = await loadEvmChecksum();
+ const address = checksum(rawAddress);
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const signature = await eth.request({
+ method: 'personal_sign',
+ params: [message, address],
+ });
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'eip191',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'eip191',
+ signature,
+ };
+ await this.executeSiwx(payload, payAccept, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async runSiwxSolana(chain, payAccept) {
+ this.renderProgress('connect', { text: 'Opening Phantom…' });
+ try {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider) throw new Error('Phantom wallet not detected');
+ const conn = await provider.connect();
+ const pubkey = conn?.publicKey || provider.publicKey;
+ const address = pubkey?.toString();
+ if (!address) throw new Error('Phantom did not return a public key');
+ this.payerAddress = address;
+ this.renderProgress('authorize', { text: `Sign sign-in message as ${address.slice(0, 6)}…${address.slice(-4)}` });
+
+ const message = buildSiwxMessage(this.siwx.info, chain, address);
+ const encoded = new TextEncoder().encode(message);
+ const signed = await provider.signMessage(encoded, 'utf8');
+ const sigBytes = signed?.signature instanceof Uint8Array ? signed.signature : new Uint8Array(signed?.signature || signed);
+ if (!sigBytes || !sigBytes.length) throw new Error('Phantom did not return a signature');
+ const signature = base58encode(sigBytes);
+
+ const info = this.siwx.info;
+ const payload = {
+ domain: info.domain,
+ address,
+ ...(info.statement ? { statement: info.statement } : {}),
+ uri: info.uri,
+ version: info.version || '1',
+ chainId: chain.chainId,
+ type: 'ed25519',
+ nonce: info.nonce,
+ issuedAt: info.issuedAt,
+ ...(info.expirationTime ? { expirationTime: info.expirationTime } : {}),
+ ...(info.notBefore ? { notBefore: info.notBefore } : {}),
+ ...(info.requestId !== undefined && info.requestId !== null ? { requestId: info.requestId } : {}),
+ ...(Array.isArray(info.resources) ? { resources: info.resources } : {}),
+ signatureScheme: 'siws',
+ signature,
+ };
+ await this.executeSiwx(payload, payAccept, chain.chainId);
+ } catch (err) {
+ this.renderError(this.payerAddress ? 'authorize' : 'connect', friendlyError(err));
+ }
+ }
+
+ async executeSiwx(payload, payAccept, chainId) {
+ this.renderProgress('verify', { text: 'Verifying sign-in…' });
+ const headerValue = encodeSiwxHeaderValue(payload);
+ let res;
+ try {
+ res = await fetch(this.opts.endpoint, {
+ method: this.opts.method || 'GET',
+ headers: {
+ ...(this.opts.headers || {}),
+ ...(this.opts.body && !this.opts.headers?.['content-type'] ? { 'content-type': 'application/json' } : {}),
+ [SIWX_HEADER]: headerValue,
+ },
+ body: this.opts.body ? (typeof this.opts.body === 'string' ? this.opts.body : JSON.stringify(this.opts.body)) : undefined,
+ });
+ } catch (err) {
+ this.renderError('verify', friendlyError(err));
+ return;
+ }
+
+ if (res.status === 200) {
+ const ct = res.headers.get('content-type') || '';
+ const text = await res.text();
+ let result;
+ if (ct.includes('json')) {
+ try { result = JSON.parse(text); } catch { result = text; }
+ } else {
+ result = text;
+ }
+ const siwx = { address: payload.address, network: chainId };
+ this.renderDone({ result, siwx });
+ this.resolve?.({
+ ok: true,
+ result,
+ siwx,
+ response: { status: res.status, headers: headersToObject(res.headers) },
+ });
+ return;
+ }
+
+ if (res.status === 401 || res.status === 402) {
+ // Most likely: signature verified but this wallet hasn't actually
+ // paid for the resource yet. Drop the SIWX offering and fall back
+ // to the normal payment flow with a one-line notice.
+ let parsed = null;
+ try { parsed = await res.clone().json(); } catch (_) {}
+ const code = parsed?.code || parsed?.error;
+ this.siwx = null;
+ this.payerAddress = null;
+ this.payFlowOverride = false;
+ this.siwxFallbackNotice = code === 'siwx_not_paid' || res.status === 402
+ ? "You haven't paid for this yet — pay now to unlock re-entry."
+ : 'Sign-in not accepted — please pay to continue.';
+ // Re-render the wallet picker. If we had collected the 402 challenge
+ // already, this just re-runs renderConnect; otherwise we re-discover.
+ if (!this.challenge || !Array.isArray(this.challenge.accepts) || !this.challenge.accepts.length) {
+ this.start();
+ } else {
+ this.renderConnect();
+ }
+ return;
+ }
+
+ const text = await res.text().catch(() => '');
+ throw new Error(`SIWX retry failed: HTTP ${res.status}${text ? ` · ${text.slice(0, 120)}` : ''}`);
+ }
}
// ───────────────────────────────────────────────────────── helpers ──────────
diff --git a/scripts/apply-siwx-migration.mjs b/scripts/apply-siwx-migration.mjs
index cd7468383..748ebf471 100644
--- a/scripts/apply-siwx-migration.mjs
+++ b/scripts/apply-siwx-migration.mjs
@@ -50,7 +50,7 @@ const statements = text
.filter((s) => s && !/^--/.test(s));
for (const s of statements) {
- await sql.query(s);
+ await sql(s, [], {});
console.log('OK:', s.slice(0, 80).replace(/\s+/g, ' '));
}
console.log('siwx tables ready');
diff --git a/scripts/inject-mobile-css.mjs b/scripts/inject-mobile-css.mjs
new file mode 100644
index 000000000..1291f9bce
--- /dev/null
+++ b/scripts/inject-mobile-css.mjs
@@ -0,0 +1,72 @@
+#!/usr/bin/env node
+/* Insert `<link rel="stylesheet" href="/mobile.css" />` into every real HTML
+ * page that has a viewport meta tag. Skips embed/widget/artifact contexts —
+ * those render inside hosts that own their own styling and should not
+ * inherit our mobile guardrails.
+ *
+ * Idempotent: re-running does nothing if the link is already present.
+ * Place strategy: insert immediately after the LAST <link rel="stylesheet">
+ * in the <head>, so the new rules cascade over page-specific CSS as intended.
+ */
+
+import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+const PAGES_DIR = new URL('../pages/', import.meta.url).pathname;
+const LINK = '<link rel="stylesheet" href="/mobile.css" />';
+
+const SKIP_PATTERNS = [
+ /embed/i,
+ /widget/i,
+ /badge/i,
+ /artifact/i,
+ /-kiosk/i,
+];
+
+function shouldSkip(filename) {
+ return SKIP_PATTERNS.some((re) => re.test(filename));
+}
+
+function injectLink(html) {
+ if (html.includes('/mobile.css')) return { html, changed: false };
+ // Find the last <link rel="stylesheet" ...> tag inside the document head.
+ // Use a tolerant regex: rel may come before or after href.
+ const stylesheetTag = /<link\b[^>]*\brel=["']stylesheet["'][^>]*\/?>/gi;
+ let lastMatch = null;
+ let m;
+ while ((m = stylesheetTag.exec(html)) !== null) lastMatch = m;
+ if (!lastMatch) return { html, changed: false };
+ const end = lastMatch.index + lastMatch[0].length;
+ // Preserve the indentation of the matched tag for the new line.
+ const lineStart = html.lastIndexOf('\n', lastMatch.index) + 1;
+ const indent = html.slice(lineStart, lastMatch.index).match(/^[\t ]*/)[0];
+ const insertion = `\n${indent}${LINK}`;
+ return { html: html.slice(0, end) + insertion + html.slice(end), changed: true };
+}
+
+const files = readdirSync(PAGES_DIR).filter((f) => f.endsWith('.html'));
+const stats = { changed: 0, skipped: 0, alreadyHas: 0, noViewport: 0 };
+for (const file of files) {
+ if (shouldSkip(file)) {
+ stats.skipped += 1;
+ continue;
+ }
+ const path = join(PAGES_DIR, file);
+ const orig = readFileSync(path, 'utf8');
+ if (!/<meta[^>]+name=["']viewport["']/i.test(orig)) {
+ stats.noViewport += 1;
+ continue;
+ }
+ const { html, changed } = injectLink(orig);
+ if (!changed) {
+ stats.alreadyHas += 1;
+ continue;
+ }
+ writeFileSync(path, html);
+ stats.changed += 1;
+ console.log(` + ${file}`);
+}
+
+console.log(
+ `\nmobile.css link: ${stats.changed} updated, ${stats.alreadyHas} already had it, ${stats.skipped} skipped (widget/embed), ${stats.noViewport} no viewport`,
+);