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: implement CoinCommunities user authentication and session management with X OAuth

nirholasae82e506abdf
diff --git a/api/_lib/coin-communities.js b/api/_lib/coin-communities.js
index 02fc8c263..6fa2041f8 100644
--- a/api/_lib/coin-communities.js
+++ b/api/_lib/coin-communities.js
@@ -84,15 +84,67 @@ export function serverHeaders() {
/** Capability snapshot the browser uses to decide which Town affordances to show. */
export function capabilities() {
+ const configured = isConfigured();
return {
- configured: isConfigured(),
- canPost: canPostServer(),
+ configured,
+ // User posting (X sign-in → link wallet → postMessage) needs only the API
+ // key (plus a whitelisted OAuth redirect, which the dashboard owns).
+ canPostUser: configured,
+ // Server attribution (postMessageServer) needs the server key-pair.
+ canPostServer: canPostServer(),
+ // Either path means the composer should be live rather than locked.
+ canPost: configured || canPostServer(),
baseUrl: ccBaseUrl(),
defaultToken:
(isValidToken(process.env.CC_DEFAULT_TOKEN) && process.env.CC_DEFAULT_TOKEN) || null,
};
}
+// ─── CoinCommunities user session (X-OAuth) ──────────────────────────────────
+// A signed-in CoinCommunities user is identified by a JWT we keep in an
+// httpOnly cookie scoped to the proxy path, so user-scoped writes (postMessage,
+// wallet linking) are forwarded server-side without the token ever being
+// readable by page scripts. The API key still rides every request globally.
+
+const AT_COOKIE = 'cc_at';
+const RT_COOKIE = 'cc_rt';
+const AT_TTL = 60 * 60; // 1h — access token
+const RT_TTL = 60 * 60 * 24 * 30; // 30d — refresh token
+
+function cookieAttrs(maxAge) {
+ // Scoped to the proxy so it's never sent with page or unrelated API requests.
+ return `Path=/api/community; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}`;
+}
+
+/** Persist a CoinCommunities user session to httpOnly cookies. */
+export function setUserSession(res, { accessToken, refreshToken }) {
+ const cookies = [];
+ if (accessToken) cookies.push(`${AT_COOKIE}=${accessToken}; ${cookieAttrs(AT_TTL)}`);
+ if (refreshToken) cookies.push(`${RT_COOKIE}=${refreshToken}; ${cookieAttrs(RT_TTL)}`);
+ if (cookies.length) res.setHeader('set-cookie', cookies);
+}
+
+/** Clear the CoinCommunities user session cookies. */
+export function clearUserSession(res) {
+ res.setHeader('set-cookie', [
+ `${AT_COOKIE}=; Path=/api/community; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
+ `${RT_COOKIE}=; Path=/api/community; HttpOnly; Secure; SameSite=Lax; Max-Age=0`,
+ ]);
+}
+
+/** Read the current user's access token from the request cookies, if any. */
+export function userToken(req) {
+ const cookie = req.headers.cookie || '';
+ const m = cookie.match(new RegExp(`(?:^|;\\s*)${AT_COOKIE}=([^;]+)`));
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+/** Per-call headers that attach a user's bearer JWT for user-scoped operations. */
+export function userAuthHeaders(req) {
+ const token = userToken(req);
+ return token ? { Authorization: `Bearer ${token}` } : null;
+}
+
/**
* Normalize a TopCommunity into the world-card shape the lobby renders. Keeps
* the browser ignorant of the upstream schema so a field rename upstream is a
diff --git a/api/community/auth/callback.js b/api/community/auth/callback.js
new file mode 100644
index 000000000..98c7eca14
--- /dev/null
+++ b/api/community/auth/callback.js
@@ -0,0 +1,66 @@
+// GET /api/community/auth/callback?challengeCode=… (X OAuth redirect target)
+//
+// X redirects the popup here after the user authorizes. We exchange the
+// one-time challenge code for the user's CoinCommunities session server-side,
+// set httpOnly cookies, then hand control back to the opener via postMessage
+// and close the popup. Falls back to the legacy accessToken-in-redirect shape.
+import { text, wrap } from '../../_lib/http.js';
+import { env } from '../../_lib/env.js';
+import { cc, setUserSession, UnconfiguredError } from '../../_lib/coin-communities.js';
+
+function page({ ok, user = null, message = '' }) {
+ // The opener verifies event.origin === APP_ORIGIN before trusting this.
+ const payload = JSON.stringify({ type: 'cc-auth', ok, user, message });
+ return `<!doctype html><meta charset="utf-8"><title>Signing in…</title>
+<body style="margin:0;display:grid;place-items:center;height:100vh;font:15px system-ui;background:#0a0e1c;color:#cdd9f5">
+<div>${ok ? 'Signed in — you can close this window.' : 'Sign-in failed. You can close this window.'}</div>
+<script>
+(function(){
+ var msg = ${payload};
+ try { if (window.opener) window.opener.postMessage(msg, ${JSON.stringify(env.APP_ORIGIN)}); } catch (e) {}
+ setTimeout(function(){ try { window.close(); } catch (e) {} }, 350);
+})();
+</script>`;
+}
+
+export default wrap(async (req, res) => {
+ const url = new URL(req.url, 'http://x');
+ const challengeCode = url.searchParams.get('challengeCode');
+ const accessToken = url.searchParams.get('accessToken');
+ const refreshToken = url.searchParams.get('refreshToken');
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return text(res, 503, page({ ok: false, message: 'not configured' }), {
+ 'content-type': 'text/html; charset=utf-8',
+ });
+ }
+ throw err;
+ }
+
+ try {
+ let session;
+ if (challengeCode) {
+ const { data, error: apiErr } = await api.twitterChallengeExchange({
+ body: { challengeCode },
+ });
+ if (apiErr || !data?.accessToken) throw new Error(apiErr?.message || 'exchange failed');
+ session = data;
+ } else if (accessToken) {
+ session = { accessToken, refreshToken, user: null };
+ } else {
+ throw new Error('missing challenge code');
+ }
+ setUserSession(res, session);
+ return text(res, 200, page({ ok: true, user: session.user }), {
+ 'content-type': 'text/html; charset=utf-8',
+ });
+ } catch (err) {
+ return text(res, 200, page({ ok: false, message: err.message || 'sign-in failed' }), {
+ 'content-type': 'text/html; charset=utf-8',
+ });
+ }
+});
diff --git a/api/community/auth/url.js b/api/community/auth/url.js
new file mode 100644
index 000000000..46861d048
--- /dev/null
+++ b/api/community/auth/url.js
@@ -0,0 +1,41 @@
+// GET /api/community/auth/url
+// Returns the X (Twitter) OAuth URL the browser opens to sign a user into
+// CoinCommunities. The redirect lands on our same-origin callback, which
+// completes the exchange and sets the session cookie. The redirect URL must be
+// whitelisted in the CoinCommunities dashboard.
+import { cors, error, json, method, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+import { cc, UnconfiguredError } from '../../_lib/coin-communities.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ const redirectUrl = `${env.APP_ORIGIN}/api/community/auth/callback`;
+ const { data, error: apiErr } = await api.twitterAuthUrl({ query: { redirectUrl } });
+ if (apiErr || !data?.authUrl) {
+ // 400 here typically means the redirect isn't whitelisted in the dashboard.
+ const msg =
+ apiErr?.statusCode === 400
+ ? `OAuth redirect not whitelisted. Add ${redirectUrl} in your CoinCommunities dashboard.`
+ : apiErr?.message || 'failed to build auth URL';
+ return error(res, apiErr?.statusCode === 400 ? 400 : 502, 'auth_url_failed', msg);
+ }
+
+ res.setHeader('cache-control', 'no-store');
+ return json(res, 200, { data: { authUrl: data.authUrl } });
+});
diff --git a/api/community/logout.js b/api/community/logout.js
new file mode 100644
index 000000000..c7326a096
--- /dev/null
+++ b/api/community/logout.js
@@ -0,0 +1,10 @@
+// POST /api/community/logout — clears the CoinCommunities user session cookies.
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { clearUserSession } from '../_lib/coin-communities.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ clearUserSession(res);
+ return json(res, 200, { data: { ok: true } });
+});
diff --git a/api/community/me.js b/api/community/me.js
new file mode 100644
index 000000000..fcb5a9e76
--- /dev/null
+++ b/api/community/me.js
@@ -0,0 +1,61 @@
+// GET /api/community/me
+// Returns the signed-in CoinCommunities user (from the session cookie) plus
+// their linked wallets, so Town knows whether the composer can post directly or
+// needs an X sign-in / wallet link first. Unauthenticated → { user: null }.
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import {
+ cc,
+ userAuthHeaders,
+ clearUserSession,
+ UnconfiguredError,
+} from '../_lib/coin-communities.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ res.setHeader('cache-control', 'no-store');
+
+ const headers = userAuthHeaders(req);
+ if (!headers) return json(res, 200, { data: { user: null } });
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ const { data, error: apiErr } = await api.userMe({ headers });
+ if (apiErr) {
+ // Expired/invalid session — clear it so the client falls back to sign-in.
+ if (apiErr.statusCode === 401) {
+ clearUserSession(res);
+ return json(res, 200, { data: { user: null } });
+ }
+ return error(res, 502, 'upstream_error', apiErr.message || 'failed to load user');
+ }
+
+ let wallets = [];
+ const w = await api.getWallets({ headers });
+ if (!w.error)
+ wallets = (w.data?.wallets ?? []).map((x) => ({
+ address: x.address,
+ chainType: x.chainType,
+ }));
+
+ const user = data?.user
+ ? {
+ id: data.user.id,
+ username: data.user.username,
+ avatar: data.user.profileImageUrl || null,
+ followers: data.user.followerCount ?? 0,
+ }
+ : null;
+ const solWallet = wallets.find((x) => x.chainType === 'svm')?.address || null;
+
+ return json(res, 200, { data: { user, wallets, solWallet } });
+});
diff --git a/api/community/messages.js b/api/community/messages.js
index 1d0cf3187..d4940201e 100644
--- a/api/community/messages.js
+++ b/api/community/messages.js
@@ -1,10 +1,12 @@
// /api/community/messages?token=<mint>
// GET — recent messages for a coin's community (public read).
-// POST — post a message, attributed server-side via the server key-pair.
-// Available only when CC_SERVER_KEY/SECRET are set AND the caller
-// supplies the posting user's twitterId + linked wallet. Otherwise
-// returns 403 posting_locked, which the composer renders as its
-// designed locked state — not a broken submit.
+// POST — post a message. Two real paths, preferred in this order:
+// 1. User-scoped: a signed-in CoinCommunities user (session cookie)
+// posts as themselves from their linked wallet (api.postMessage).
+// 2. Server attribution: when the server key-pair is configured and a
+// twitterId is supplied (api.postMessageServer).
+// Neither available → 403 posting_locked, which the composer renders
+// as its designed locked state rather than a broken submit.
import { z } from 'zod';
import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
@@ -13,17 +15,18 @@ import {
canPostServer,
isValidToken,
serverHeaders,
+ userAuthHeaders,
toTownMessage,
UnconfiguredError,
} from '../_lib/coin-communities.js';
const CHAINS = ['solana', 'ethereum', 'base', 'bsc'];
-const postSchema = z.object({
+const baseSchema = z.object({
content: z.string().trim().min(1).max(2000),
walletAddress: z.string().trim().min(1).max(120),
- twitterId: z.string().trim().min(1).max(64),
chainId: z.enum(CHAINS).default('solana'),
+ twitterId: z.string().trim().min(1).max(64).optional(),
});
function getApi(res) {
@@ -66,17 +69,12 @@ async function handlePost(req, res, token) {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- if (!canPostServer()) {
- return error(
- res,
- 403,
- 'posting_locked',
- 'server posting is not configured for this deployment',
- );
+ const userHeaders = userAuthHeaders(req);
+ if (!userHeaders && !canPostServer()) {
+ return error(res, 403, 'posting_locked', 'sign in with X to post in this world');
}
- const body = await readJson(req).catch(() => null);
- const parsed = postSchema.safeParse(body);
+ const parsed = baseSchema.safeParse(await readJson(req).catch(() => null));
if (!parsed.success) {
return error(
res,
@@ -89,26 +87,41 @@ async function handlePost(req, res, token) {
const api = getApi(res);
if (!api) return;
- const { content, walletAddress, twitterId, chainId } = parsed.data;
- const { data, error: apiErr } = await api.postMessageServer({
- path: { token_address: token },
- body: { content, walletAddress, twitterId, chainId },
- headers: serverHeaders(),
- });
- if (apiErr) {
- // 403 from upstream means the wallet isn't linked / lacks token balance —
- // surface it verbatim so the composer can tell the user exactly why.
- const status = apiErr.statusCode === 403 ? 403 : 502;
- return error(res, status, 'post_failed', apiErr.message || 'failed to post message');
+ const { content, walletAddress, chainId, twitterId } = parsed.data;
+
+ let result;
+ if (userHeaders) {
+ // Post as the signed-in user from their linked wallet.
+ result = await api.postMessage({
+ path: { token_address: token },
+ body: { content, walletAddress, chainId },
+ headers: userHeaders,
+ });
+ } else {
+ // Server attribution requires the user's twitterId.
+ if (!twitterId) {
+ return error(res, 400, 'validation_error', 'twitterId required for server posting');
+ }
+ result = await api.postMessageServer({
+ path: { token_address: token },
+ body: { content, walletAddress, twitterId, chainId },
+ headers: serverHeaders(),
+ });
}
- return json(res, 200, {
- data: { message: data?.message ? toTownMessage(data.message) : null },
- });
+ if (result.error) {
+ // 403 → wallet not linked / insufficient token balance. Surface verbatim
+ // so the composer can tell the user exactly what to fix.
+ const status = result.error.statusCode === 403 ? 403 : 502;
+ return error(res, status, 'post_failed', result.error.message || 'failed to post message');
+ }
+
+ const msg = result.data?.message;
+ return json(res, 200, { data: { message: msg ? toTownMessage(msg) : null } });
}
export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['GET', 'POST'])) return;
const token = new URL(req.url, 'http://x').searchParams.get('token');
diff --git a/api/community/wallet/challenge.js b/api/community/wallet/challenge.js
new file mode 100644
index 000000000..3d5662580
--- /dev/null
+++ b/api/community/wallet/challenge.js
@@ -0,0 +1,44 @@
+// POST /api/community/wallet/challenge { address }
+// Requests a sign-in challenge to link a Solana wallet (chainType 'svm') to the
+// signed-in CoinCommunities user. Returns the message the wallet must sign.
+import { z } from 'zod';
+import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+
+const schema = z.object({ address: z.string().trim().min(32).max(60) });
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const headers = userAuthHeaders(req);
+ if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+
+ const parsed = schema.safeParse(await readJson(req).catch(() => null));
+ if (!parsed.success) return error(res, 400, 'validation_error', 'address required');
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ const { data, error: apiErr } = await api.walletChallenge({
+ body: { address: parsed.data.address, chainType: 'svm' },
+ headers,
+ });
+ if (apiErr || !data?.message) {
+ return error(res, 502, 'upstream_error', apiErr?.message || 'failed to create challenge');
+ }
+
+ res.setHeader('cache-control', 'no-store');
+ return json(res, 200, { data: { message: data.message, nonce: data.nonce } });
+});
diff --git a/api/community/wallet/link.js b/api/community/wallet/link.js
new file mode 100644
index 000000000..4c4016aa3
--- /dev/null
+++ b/api/community/wallet/link.js
@@ -0,0 +1,56 @@
+// POST /api/community/wallet/link { address, signature }
+// Links a Solana wallet to the signed-in CoinCommunities user using the
+// signature over the message from /wallet/challenge. Lets the user post from
+// that wallet (subject to the community's token-balance gate).
+import { z } from 'zod';
+import { cors, error, json, method, readJson, wrap } from '../../_lib/http.js';
+import { clientIp, limits } from '../../_lib/rate-limit.js';
+import { cc, userAuthHeaders, UnconfiguredError } from '../../_lib/coin-communities.js';
+
+const schema = z.object({
+ address: z.string().trim().min(32).max(60),
+ signature: z.string().trim().min(1).max(200),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const headers = userAuthHeaders(req);
+ if (!headers) return error(res, 401, 'unauthorized', 'sign in with X first');
+
+ const parsed = schema.safeParse(await readJson(req).catch(() => null));
+ if (!parsed.success) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ parsed.error.issues[0]?.message || 'invalid body',
+ );
+ }
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ const { data, error: apiErr } = await api.linkWallet({
+ body: { address: parsed.data.address, chainType: 'svm', signature: parsed.data.signature },
+ headers,
+ });
+ if (apiErr) {
+ // 401 invalid signature, 409 already linked, 400 no pending challenge.
+ const status = [400, 401, 409].includes(apiErr.statusCode) ? apiErr.statusCode : 502;
+ return error(res, status, 'link_failed', apiErr.message || 'failed to link wallet');
+ }
+
+ return json(res, 200, { data: { address: data?.wallet?.address || parsed.data.address } });
+});
diff --git a/public/features.json b/public/features.json
index eeca39ce4..870a18be8 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-05-29T21:17:01.683Z",
+ "generated_at": "2026-05-30T01:04:04.148Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/community/town-auth.js b/src/community/town-auth.js
new file mode 100644
index 000000000..71bf08b8e
--- /dev/null
+++ b/src/community/town-auth.js
@@ -0,0 +1,134 @@
+// Town auth — the browser half of posting as yourself in a coin world.
+//
+// Posting flow, all real, no shortcuts:
+// 1. Sign in to CoinCommunities with X (OAuth popup → same-origin callback
+// sets an httpOnly session cookie; we just await the postMessage).
+// 2. Ensure a Solana wallet is linked: connect Phantom, sign the challenge
+// message, link it via the proxy.
+// 3. Post — the proxy forwards the session cookie as the user bearer.
+//
+// Session/token handling lives entirely server-side (cookies); this module only
+// orchestrates the user-facing steps and never sees the JWT.
+
+const BASE = '/api/community';
+
+async function json(path, init) {
+ const res = await fetch(`${BASE}${path}`, { credentials: 'include', ...init });
+ let body = null;
+ try {
+ body = await res.json();
+ } catch {
+ /* fall through */
+ }
+ if (!res.ok || body?.error) {
+ const err = new Error(body?.error_description || body?.error || `HTTP ${res.status}`);
+ err.status = res.status;
+ err.code = body?.error;
+ throw err;
+ }
+ return body?.data ?? null;
+}
+
+/** Current CoinCommunities session, or { user: null } when signed out. */
+export function getSession() {
+ return json('/me');
+}
+
+/**
+ * Open the X OAuth popup and resolve once the same-origin callback reports
+ * success. Rejects on user-close or failure.
+ */
+export async function signInWithX() {
+ const { authUrl } = await json('/auth/url');
+ const w = 520;
+ const h = 680;
+ const left = window.screenX + (window.outerWidth - w) / 2;
+ const top = window.screenY + (window.outerHeight - h) / 2;
+ const popup = window.open(
+ authUrl,
+ 'cc-x-oauth',
+ `width=${w},height=${h},left=${left},top=${top}`,
+ );
+ if (!popup) throw new Error('Popup blocked — allow popups to sign in.');
+
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const onMessage = (e) => {
+ if (e.origin !== location.origin) return;
+ if (e.data?.type !== 'cc-auth') return;
+ cleanup();
+ if (e.data.ok) resolve(e.data.user || null);
+ else reject(new Error(e.data.message || 'Sign-in failed'));
+ };
+ const poll = setInterval(() => {
+ if (popup.closed && !settled) {
+ cleanup();
+ reject(new Error('Sign-in cancelled'));
+ }
+ }, 500);
+ const cleanup = () => {
+ settled = true;
+ clearInterval(poll);
+ window.removeEventListener('message', onMessage);
+ try {
+ popup.close();
+ } catch {
+ /* already closed */
+ }
+ };
+ window.addEventListener('message', onMessage);
+ });
+}
+
+/** Connect Phantom (or any window.solana provider) and return its address. */
+async function connectSolana() {
+ const provider = window.phantom?.solana || window.solana;
+ if (!provider?.connect) {
+ throw new Error('No Solana wallet found — install Phantom to post.');
+ }
+ const resp = await provider.connect();
+ const address = (resp?.publicKey || provider.publicKey)?.toString();
+ if (!address) throw new Error('Could not read wallet address.');
+ return { provider, address };
+}
+
+/**
+ * Ensure the signed-in user has a linked Solana wallet, linking one via a
+ * signed challenge if needed. Returns the wallet address to post from.
+ */
+export async function ensureSolanaWallet(session) {
+ if (session?.solWallet) return session.solWallet;
+
+ const { provider, address } = await connectSolana();
+ const { message } = await json('/wallet/challenge', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address }),
+ });
+
+ const encoded = new TextEncoder().encode(message);
+ const signed = await provider.signMessage(encoded, 'utf8');
+ const sigBytes = signed?.signature ?? signed;
+ const bs58 = (await import('bs58')).default;
+ const signature = bs58.encode(sigBytes);
+
+ const linked = await json('/wallet/link', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ address, signature }),
+ });
+ return linked?.address || address;
+}
+
+/** Post content to a coin world as the signed-in user from their linked wallet. */
+export function postAsUser(token, content, walletAddress) {
+ return json(`/messages?token=${encodeURIComponent(token)}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ content, walletAddress, chainId: 'solana' }),
+ });
+}
+
+export function logout() {
+ return json('/logout', { method: 'POST' }).catch(() => {});
+}
diff --git a/src/community/town-client.js b/src/community/town-client.js
index d834b1f1d..ed5cb839e 100644
--- a/src/community/town-client.js
+++ b/src/community/town-client.js
@@ -45,23 +45,6 @@ export async function fetchMessages(token, { limit = 50, before } = {}) {
return data?.messages ?? [];
}
-/**
- * Post a message. Only succeeds where server-side attribution is configured
- * (capabilities.canPost) and a linked posting identity is supplied. Throws with
- * a `posting_locked` code otherwise so the composer can render its locked state.
- */
-export async function postMessage(
- token,
- { content, walletAddress, twitterId, chainId = 'solana' },
-) {
- const data = await call(`/messages?token=${encodeURIComponent(token)}`, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ content, walletAddress, twitterId, chainId }),
- });
- return data?.message ?? null;
-}
-
/**
* Subscribe to a coin community's realtime stream. Returns a disposer.
* The realtime module is dynamically imported so it's a separate chunk.
diff --git a/src/community/town.js b/src/community/town.js
index 9378f368f..7a233c312 100644
--- a/src/community/town.js
+++ b/src/community/town.js
@@ -10,7 +10,8 @@
// Self-contained: styles are injected once, nothing here depends on the build
// pipeline's CSS handling, and it appends to <body> without touching walk.js.
-import { fetchCapabilities, fetchMessages, connectRealtime, postMessage } from './town-client.js';
+import { fetchCapabilities, fetchMessages, connectRealtime } from './town-client.js';
+import { getSession, signInWithX, ensureSolanaWallet, postAsUser, logout } from './town-auth.js';
const MAX_BUBBLES = 4;
const BUBBLE_TTL_MS = 7000;
@@ -258,8 +259,8 @@ export class Town {
_buildComposer() {
this.composer.innerHTML = '';
if (!this.caps?.canPost) {
- // Designed locked state — explains why and what unlocks it, never a
- // dead input. Reads/realtime above are fully live regardless.
+ // Designed locked state — only when the deployment has no CoinCommunities
+ // credentials at all. The live feed above stays open regardless.
const lock = el('div', 'town__locked');
lock.appendChild(el('span', 'town__lock-icon', '🔒'));
const t = el('div', 'town__lock-text');
@@ -268,13 +269,14 @@ export class Town {
el(
'span',
null,
- 'Connect this world to start posting. The live feed stays open to everyone.',
+ 'This world isn’t connected for posting yet. The live feed stays open to everyone.',
),
);
lock.appendChild(t);
this.composer.appendChild(lock);
return;
}
+
const form = el('form', 'town__form');
const ta = el('textarea', 'town__input');
ta.placeholder = `Say something in $${this.meta.symbol || 'this world'}…`;
@@ -285,8 +287,15 @@ export class Town {
ta.style.height = 'auto';
ta.style.height = `${Math.min(ta.scrollHeight, 120)}px`;
});
+ ta.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ this._submit(ta, this.sendBtn);
+ }
+ });
const send = el('button', 'town__send', 'Post');
send.type = 'submit';
+ this.sendBtn = send;
form.appendChild(ta);
form.appendChild(send);
form.addEventListener('submit', (e) => {
@@ -294,35 +303,96 @@ export class Town {
this._submit(ta, send);
});
this.composer.appendChild(form);
+
+ // Identity row — sign-in CTA when signed out, user chip when signed in.
+ this.authRow = el('div', 'town__auth');
+ this.composer.appendChild(this.authRow);
+ this._renderAuthRow();
+ }
+
+ _renderAuthRow() {
+ if (!this.authRow) return;
+ this.authRow.innerHTML = '';
+ const user = this.session?.user;
+ if (user) {
+ const chip = el('span', 'town__userchip');
+ if (user.avatar) {
+ const img = el('img');
+ img.src = user.avatar;
+ img.alt = '';
+ chip.appendChild(img);
+ }
+ chip.appendChild(el('span', 'town__uname', `@${user.username}`));
+ this.authRow.appendChild(el('span', 'town__authnote', 'posting as'));
+ this.authRow.appendChild(chip);
+ const out = el('button', 'town__signout', 'sign out');
+ out.type = 'button';
+ out.addEventListener('click', async () => {
+ await logout();
+ this.session = { user: null };
+ this._renderAuthRow();
+ });
+ this.authRow.appendChild(out);
+ } else {
+ this.authRow.appendChild(el('span', 'town__authnote', 'Sign in to post —'));
+ const btn = el('button', 'town__xbtn', 'Sign in with 𝕏');
+ btn.type = 'button';
+ btn.addEventListener('click', () => this._ensureSignedIn(btn));
+ this.authRow.appendChild(btn);
+ }
+ }
+
+ async _ensureSignedIn(trigger) {
+ if (this.session?.user) return this.session;
+ const label = trigger?.textContent;
+ if (trigger) {
+ trigger.disabled = true;
+ trigger.textContent = 'Opening 𝕏…';
+ }
+ try {
+ await signInWithX();
+ this.session = await getSession();
+ this._renderAuthRow();
+ return this.session;
+ } catch (err) {
+ this._composerError(err.message || 'Sign-in failed.');
+ throw err;
+ } finally {
+ if (trigger) {
+ trigger.disabled = false;
+ trigger.textContent = label;
+ }
+ }
}
async _submit(ta, send) {
const content = ta.value.trim();
if (!content) return;
- // Posting identity (wallet + linked X id) comes from the platform's
- // auth layer. Until that's wired through, surface the precise blocker
- // rather than silently failing.
- const identity = window.__townIdentity;
- if (!identity?.walletAddress || !identity?.twitterId) {
- this._composerError('Connect your wallet and X account to post.');
- return;
- }
send.disabled = true;
ta.disabled = true;
+ const restore = () => {
+ send.disabled = false;
+ ta.disabled = false;
+ };
try {
- const posted = await postMessage(this.token, {
- content,
- walletAddress: identity.walletAddress,
- twitterId: identity.twitterId,
- });
+ // 1. Signed in with X?
+ let session = this.session;
+ if (!session?.user) session = await this._ensureSignedIn();
+ // 2. Linked Solana wallet? (connects Phantom + links on first post)
+ send.textContent = 'Linking wallet…';
+ const walletAddress = await ensureSolanaWallet(session);
+ this.session = { ...session, solWallet: walletAddress };
+ // 3. Post.
+ send.textContent = 'Posting…';
+ const posted = await postAsUser(this.token, content, walletAddress);
ta.value = '';
ta.style.height = 'auto';
- if (posted) this._prepend(posted); // realtime will dedupe by id
+ if (posted) this._prepend(posted); // realtime dedupes by id
} catch (err) {
this._composerError(err.message || 'Could not post.');
} finally {
- send.disabled = false;
- ta.disabled = false;
+ restore();
+ send.textContent = 'Post';
}
}
@@ -408,13 +478,16 @@ export class Town {
// ── Lifecycle ──────────────────────────────────────────────────────────
async _load() {
this._setStatus('connecting');
- // Capabilities + first page of messages in parallel.
- const [caps, msgs] = await Promise.allSettled([
+ // Capabilities, first page of messages, and any existing session — all in
+ // parallel so the composer renders the right identity state immediately.
+ const [caps, msgs, sess] = await Promise.allSettled([
fetchCapabilities(),
fetchMessages(this.token, { limit: 50 }),
+ getSession(),
]);
this.caps = caps.status === 'fulfilled' ? caps.value : null;
+ this.session = sess.status === 'fulfilled' ? sess.value : { user: null };
this._buildComposer();
if (msgs.status === 'rejected') {
@@ -603,6 +676,17 @@ const STYLES = `
.town__lock-text{display:flex;flex-direction:column;gap:2px;font-size:12px;color:#9fb0d4}
.town__lock-text strong{color:#dde6fb;font-size:12.5px}
.town__cerr{margin-top:8px;font-size:12px;color:#ffb4ad}
+.town__auth{display:flex;align-items:center;gap:7px;margin-top:9px;font-size:12px;color:#8093ba;flex-wrap:wrap}
+.town__authnote{opacity:.85}
+.town__xbtn{padding:6px 12px;border-radius:9px;border:1px solid rgba(120,150,220,.28);
+ background:rgba(255,255,255,.06);color:#eaf0ff;cursor:pointer;font-weight:650;font-size:12px;transition:background .2s}
+.town__xbtn:hover{background:rgba(255,255,255,.13)}.town__xbtn:disabled{opacity:.6;cursor:default}
+.town__userchip{display:inline-flex;align-items:center;gap:5px;padding:3px 9px 3px 3px;border-radius:999px;
+ background:rgba(91,140,255,.16);border:1px solid rgba(120,150,220,.25);color:#cfe0ff;font-weight:650}
+.town__userchip img{width:18px;height:18px;border-radius:50%;object-fit:cover}
+.town__uname{font-size:12px}
+.town__signout{background:none;border:0;color:#7f8db0;cursor:pointer;font-size:11.5px;text-decoration:underline;padding:0;margin-left:2px}
+.town__signout:hover{color:#aab8db}
.town-bubbles{position:fixed;top:84px;left:50%;transform:translateX(-50%);z-index:35;
display:flex;flex-direction:column;gap:8px;align-items:center;pointer-events:none;width:min(560px,92vw)}
.town-bubble{display:flex;gap:9px;align-items:center;max-width:100%;padding:8px 14px 8px 8px;border-radius:999px;