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: SAML enterprise SSO, .glb proxy URLs, and pump curve 404 hardening

nirholas5ff4a27671d7
diff --git a/.env.example b/.env.example
index a71d3eee5..828c7432f 100644
--- a/.env.example
+++ b/.env.example
@@ -447,6 +447,55 @@ GITHUB_OAUTH_CLIENT_SECRET=
X_OAUTH_CLIENT_ID=
X_OAUTH_CLIENT_SECRET=
+# ── Enterprise SAML 2.0 SSO (three.ws is the Service Provider) ───────────────
+# Lets platform users sign in through your IdP (IBM Cloud App ID, Okta, Azure
+# AD, Google Workspace, …). When configured, an "SSO" button appears on /login.
+#
+# Setup:
+# 1. Register three.ws as a SAML app in your IdP using our SP details:
+# Entity ID / Audience : https://your-domain.com/api/auth/saml/metadata
+# ACS (Reply) URL : https://your-domain.com/api/auth/saml/acs
+# Or just hand the IdP our metadata document (it has everything):
+# https://your-domain.com/api/auth/saml/metadata
+# 2. Point us at the IdP — EITHER paste its metadata URL (simplest)…
+SAML_IDP_METADATA_URL=
+# …OR set the fields explicitly (these win if both are present):
+SAML_IDP_SSO_URL=
+# IdP signing certificate — PEM block or bare base64. Literal "\n" escapes are
+# fine (they're restored to newlines). Required for verifying assertions.
+SAML_IDP_CERT=
+# Optional: pins the expected assertion Issuer and enables IdP-initiated logout.
+SAML_IDP_ENTITY_ID=
+SAML_IDP_SLO_URL=
+#
+# IBM Cloud note: the IAM "Identity providers" screen makes IBM Cloud the SP and
+# expects YOUR IdP — it is not itself a SAML IdP for third-party apps. To use IBM
+# as the IdP here, create the SAML app in IBM Cloud App ID (or IBM Security
+# Verify) and use ITS metadata URL / SSO URL / signing cert above.
+#
+# SP entity ID override (defaults to the metadata URL above). Set only if your
+# IdP requires a specific Audience value.
+SAML_SP_ENTITY_ID=
+# Optional SP keypair (PEM) — when set, our AuthnRequests are signed and
+# encrypted assertions can be decrypted. Most IdPs don't require this.
+SAML_SP_PRIVATE_KEY=
+SAML_SP_CERT=
+# Security posture. The assertion must be signed by default; the response
+# envelope signature is opt-in (many IdPs only sign the assertion).
+SAML_WANT_ASSERTIONS_SIGNED=true
+SAML_WANT_RESPONSE_SIGNED=false
+SAML_SIGNATURE_ALGORITHM=sha256
+# NameID format to request: "unspecified" (default — let the IdP decide) or a
+# full URN, e.g. urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress.
+SAML_IDENTIFIER_FORMAT=unspecified
+# Accepted clock skew (ms) between us and the IdP. Default 5s.
+SAML_CLOCK_SKEW_MS=5000
+# SP-initiated only by default (replay-resistant). Set true to also accept
+# unsolicited IdP-initiated responses (no InResponseTo).
+SAML_ALLOW_IDP_INITIATED=false
+# Label on the /login SSO button.
+SAML_BUTTON_LABEL=Single sign-on (SSO)
+
# ── News-feed syndication (admin "Publish" → Dev.to / Medium) ────────────────
# Used by /api/admin/news (the local-only CMS) to mirror newly-saved posts
# to external publishers. When unset, syndication for that target is silently
diff --git a/api/_lib/env.js b/api/_lib/env.js
index ea9f98c4a..5b84e8e41 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -16,6 +16,15 @@ function trimSlash(s) {
return s ? s.replace(/\/$/, '') : s;
}
+// PEM / certificate env values are frequently stored with literal "\n" escapes
+// (Vercel/IBM/Okta dashboards collapse real newlines). Restore them so the
+// crypto libraries get a valid multi-line PEM. Returns undefined when unset.
+function pem(name) {
+ const v = process.env[name];
+ if (!v) return undefined;
+ return v.includes('\\n') ? v.replace(/\\n/g, '\n') : v;
+}
+
export const env = {
get APP_ORIGIN() {
return trimSlash(opt('PUBLIC_APP_ORIGIN', 'https://three.ws/'));
@@ -816,6 +825,80 @@ export const env = {
return Boolean(this.AIXBT_API_KEY);
},
+ // ── SAML 2.0 SSO (three.ws as Service Provider) ───────────────────────────
+ // Lets platform users sign in through an enterprise IdP (IBM Cloud App ID,
+ // Okta, Azure AD, …). Two ways to point at the IdP:
+ // 1. Paste its metadata URL → SAML_IDP_METADATA_URL (sso url + signing
+ // cert are fetched + cached server-side).
+ // 2. Set the fields directly → SAML_IDP_SSO_URL + SAML_IDP_CERT (+ entity
+ // id / slo url). Explicit fields win when both are present.
+ // Unset → /api/auth/saml/* returns "not configured" and the SSO button is
+ // hidden on /login. See .env.example for the full setup walkthrough.
+ get SAML_IDP_ENTITY_ID() {
+ return opt('SAML_IDP_ENTITY_ID');
+ },
+ get SAML_IDP_SSO_URL() {
+ return opt('SAML_IDP_SSO_URL');
+ },
+ get SAML_IDP_SLO_URL() {
+ return opt('SAML_IDP_SLO_URL');
+ },
+ // IdP signing certificate. Accepts a PEM block or a bare base64 body, with
+ // literal "\n" escapes (common in dashboard-pasted env vars) normalized to
+ // real newlines; api/_lib/saml.js strips it back to base64 for node-saml.
+ get SAML_IDP_CERT() {
+ return pem('SAML_IDP_CERT');
+ },
+ get SAML_IDP_METADATA_URL() {
+ return opt('SAML_IDP_METADATA_URL');
+ },
+
+ // SP (our) identity advertised to the IdP. EntityID defaults to our metadata
+ // URL; the ACS + SLO URLs are derived from APP_ORIGIN in api/_lib/saml.js.
+ get SAML_SP_ENTITY_ID() {
+ return opt('SAML_SP_ENTITY_ID', `${this.APP_ORIGIN}/api/auth/saml/metadata`);
+ },
+ // Optional SP keypair. When set, AuthnRequests are signed and encrypted
+ // assertions can be decrypted. PEM, with "\n" escapes tolerated.
+ get SAML_SP_PRIVATE_KEY() {
+ return pem('SAML_SP_PRIVATE_KEY');
+ },
+ get SAML_SP_CERT() {
+ return pem('SAML_SP_CERT');
+ },
+
+ // Security posture. The assertion (which carries identity) must be signed by
+ // default; the response envelope signature is opt-in since many IdPs only
+ // sign the assertion. Both can be required for stricter deployments.
+ get SAML_WANT_ASSERTIONS_SIGNED() {
+ return opt('SAML_WANT_ASSERTIONS_SIGNED', 'true') !== 'false';
+ },
+ get SAML_WANT_RESPONSE_SIGNED() {
+ return opt('SAML_WANT_RESPONSE_SIGNED', 'false') === 'true';
+ },
+ get SAML_SIGNATURE_ALGORITHM() {
+ return opt('SAML_SIGNATURE_ALGORITHM', 'sha256');
+ },
+ // NameID format requested in the AuthnRequest. Default: unspecified (omit the
+ // Format so the IdP returns whatever it's configured for — broadest compat).
+ // Set to e.g. urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress to pin it.
+ get SAML_IDENTIFIER_FORMAT() {
+ const v = opt('SAML_IDENTIFIER_FORMAT');
+ return v && v !== 'none' && v !== 'unspecified' ? v : null;
+ },
+ get SAML_CLOCK_SKEW_MS() {
+ return parseInt(opt('SAML_CLOCK_SKEW_MS', '5000'), 10);
+ },
+ // SP-initiated only by default (InResponseTo enforced → replay-resistant).
+ // Set true to also accept unsolicited IdP-initiated responses.
+ get SAML_ALLOW_IDP_INITIATED() {
+ return opt('SAML_ALLOW_IDP_INITIATED', 'false') === 'true';
+ },
+ // Label shown on the /login SSO button (e.g. "Sign in with Acme SSO").
+ get SAML_BUTTON_LABEL() {
+ return opt('SAML_BUTTON_LABEL', 'Single sign-on (SSO)');
+ },
+
getRpcUrl(chainId) {
return (
opt(`RPC_URL_${chainId}`) ||
diff --git a/api/_lib/saml.js b/api/_lib/saml.js
new file mode 100644
index 000000000..255464c45
--- /dev/null
+++ b/api/_lib/saml.js
@@ -0,0 +1,352 @@
+// SAML 2.0 Service Provider for three.ws.
+//
+// three.ws is the SP: platform users authenticate at an enterprise IdP (IBM
+// Cloud App ID, Okta, Azure AD, …) and the IdP POSTs a signed assertion back to
+// our ACS. We wrap @node-saml/node-saml for the protocol heavy-lifting —
+// XML-DSig signature verification, audience/condition/clock checks, and
+// InResponseTo replay protection — because hand-rolled SAML is precisely how SPs
+// get owned by signature-wrapping attacks.
+//
+// The one piece node-saml can't provide on its own in a serverless deployment
+// is shared state for InResponseTo: the /login lambda that issues an
+// AuthnRequest and the /acs lambda that consumes the response are different
+// instances, so request IDs live in Postgres (postgresCacheProvider) rather
+// than process memory.
+
+import { SAML, ValidateInResponseTo, generateServiceProviderMetadata } from '@node-saml/node-saml';
+import { XMLParser } from 'fast-xml-parser';
+import { env } from './env.js';
+import { sql } from './db.js';
+import { hmacSha256, constantTimeEquals, sha256 } from './crypto.js';
+
+// Request IDs are valid for one login round-trip; an hour is generous slack for
+// a user who lands on the IdP, authenticates, and is redirected back. Must match
+// the TTL the cache provider enforces in getAsync().
+const REQUEST_ID_TTL_SEC = 60 * 60;
+// How long a fetched IdP metadata document is trusted before re-fetching.
+const METADATA_TTL_MS = 60 * 60 * 1000;
+
+// ── SP endpoint URLs (all derived from APP_ORIGIN) ──────────────────────────
+
+export function spEntityId() {
+ return env.SAML_SP_ENTITY_ID;
+}
+export function acsUrl() {
+ return `${env.APP_ORIGIN}/api/auth/saml/acs`;
+}
+export function sloCallbackUrl() {
+ return `${env.APP_ORIGIN}/api/auth/saml/logout`;
+}
+
+// Cheap, fetch-free predicate for the /login UI flag — true when enough IdP
+// config exists to attempt a connection. The real resolution (which may fetch
+// metadata) happens in getSamlInstance().
+export function samlConfigured() {
+ return Boolean(
+ (env.SAML_IDP_CERT && env.SAML_IDP_SSO_URL) || env.SAML_IDP_METADATA_URL,
+ );
+}
+
+// ── IdP config resolution: explicit env fields, else parsed metadata URL ────
+
+let _idpCache = null; // { entityId, ssoUrl, sloUrl, cert, expiresAt }
+
+async function resolveIdpConfig() {
+ // Explicit fields take precedence and need no network round-trip.
+ if (env.SAML_IDP_CERT && env.SAML_IDP_SSO_URL) {
+ return {
+ entityId: env.SAML_IDP_ENTITY_ID || undefined,
+ ssoUrl: env.SAML_IDP_SSO_URL,
+ sloUrl: env.SAML_IDP_SLO_URL || undefined,
+ cert: normalizeCert(env.SAML_IDP_CERT),
+ };
+ }
+ const metadataUrl = env.SAML_IDP_METADATA_URL;
+ if (!metadataUrl) return null;
+
+ if (_idpCache && _idpCache.expiresAt > Date.now()) return _idpCache;
+ const parsed = await fetchAndParseMetadata(metadataUrl);
+ if (!parsed) return _idpCache || null; // serve stale config rather than break login on a transient fetch failure
+ _idpCache = { ...parsed, expiresAt: Date.now() + METADATA_TTL_MS };
+ return _idpCache;
+}
+
+async function fetchAndParseMetadata(url) {
+ try {
+ const res = await fetch(url, {
+ headers: { accept: 'application/samlmetadata+xml, application/xml, text/xml' },
+ });
+ if (!res.ok) return null;
+ return parseIdpMetadata(await res.text());
+ } catch {
+ return null;
+ }
+}
+
+// Parse an IdP's SAML 2.0 metadata XML into the fields node-saml needs. Exported
+// for the metadata-pasting setup path and for tests. Namespace prefixes (md:,
+// ds:) are stripped so traversal is uniform across IdP vendors.
+export function parseIdpMetadata(xml) {
+ let doc;
+ try {
+ doc = new XMLParser({
+ ignoreAttributes: false,
+ attributeNamePrefix: '@_',
+ removeNSPrefix: true,
+ }).parse(xml);
+ } catch {
+ return null;
+ }
+
+ const descriptors = toArray(doc?.EntityDescriptor ?? doc?.EntitiesDescriptor?.EntityDescriptor);
+ const entity = descriptors.find((e) => e?.IDPSSODescriptor) || descriptors[0];
+ const idp = entity?.IDPSSODescriptor;
+ if (!idp) return null;
+
+ const ssoUrl = pickBinding(idp.SingleSignOnService);
+ const sloUrl = pickBinding(idp.SingleLogoutService);
+
+ const certs = [];
+ for (const key of toArray(idp.KeyDescriptor)) {
+ if (key['@_use'] && key['@_use'] !== 'signing') continue; // skip encryption-only keys
+ for (const x509Data of toArray(key?.KeyInfo?.X509Data)) {
+ for (const cert of toArray(x509Data?.X509Certificate)) {
+ const body = typeof cert === 'object' ? cert?.['#text'] : cert;
+ if (body) certs.push(normalizeCert(body));
+ }
+ }
+ }
+
+ if (!ssoUrl || certs.length === 0) return null;
+ return {
+ entityId: entity['@_entityID'] || undefined,
+ ssoUrl,
+ sloUrl: sloUrl || undefined,
+ cert: certs.length === 1 ? certs[0] : certs,
+ };
+}
+
+// Prefer the HTTP-Redirect endpoint (what we use for AuthnRequest / LogoutRequest);
+// fall back to the first listed binding.
+function pickBinding(service) {
+ const list = toArray(service);
+ const redirect = list.find((s) => String(s?.['@_Binding'] || '').includes('HTTP-Redirect'));
+ return (redirect || list[0])?.['@_Location'] || null;
+}
+
+function toArray(v) {
+ return v == null ? [] : Array.isArray(v) ? v : [v];
+}
+
+// node-saml accepts either PEM or a bare base64 body; normalize to base64 so
+// metadata-sourced and env-sourced certs are handled identically.
+function normalizeCert(c) {
+ return String(c)
+ .replace(/-----BEGIN CERTIFICATE-----/g, '')
+ .replace(/-----END CERTIFICATE-----/g, '')
+ .replace(/\s+/g, '');
+}
+
+// ── Postgres-backed InResponseTo cache (shared across serverless instances) ──
+
+export const postgresCacheProvider = {
+ async saveAsync(key, value) {
+ // Best-effort sweep of abandoned login attempts so the table can't grow
+ // unbounded from users who start SSO and never return.
+ sql`delete from saml_request_ids where created_at < now() - ${`${REQUEST_ID_TTL_SEC * 2} seconds`}::interval`.catch(
+ () => {},
+ );
+ const rows = await sql`
+ insert into saml_request_ids (request_id, value)
+ values (${key}, ${value})
+ on conflict (request_id) do nothing
+ returning extract(epoch from created_at) * 1000 as created_ms
+ `;
+ if (!rows[0]) return null; // key already present — don't overwrite
+ return { value, createdAt: Number(rows[0].created_ms) };
+ },
+ async getAsync(key) {
+ if (key == null) return null;
+ const rows = await sql`
+ select value from saml_request_ids
+ where request_id = ${key}
+ and created_at > now() - ${`${REQUEST_ID_TTL_SEC} seconds`}::interval
+ limit 1
+ `;
+ return rows[0]?.value ?? null;
+ },
+ async removeAsync(key) {
+ if (key == null) return null;
+ const rows = await sql`
+ delete from saml_request_ids where request_id = ${key} returning request_id
+ `;
+ return rows[0]?.request_id ?? null;
+ },
+};
+
+// ── SAML instance ───────────────────────────────────────────────────────────
+
+// Build a configured SAML instance. Throws a 501 when the IdP isn't configured
+// so callers can surface "not configured" rather than a generic crash.
+export async function getSamlInstance() {
+ const idp = await resolveIdpConfig();
+ if (!idp || !idp.ssoUrl || !idp.cert) {
+ throw Object.assign(new Error('SAML SSO is not configured'), {
+ status: 501,
+ code: 'not_configured',
+ });
+ }
+
+ return new SAML({
+ // SP identity
+ issuer: spEntityId(),
+ callbackUrl: acsUrl(),
+ audience: spEntityId(),
+
+ // IdP
+ entryPoint: idp.ssoUrl,
+ idpCert: idp.cert,
+ ...(idp.entityId ? { idpIssuer: idp.entityId } : {}),
+ ...(idp.sloUrl ? { logoutUrl: idp.sloUrl } : {}),
+
+ // Security posture
+ wantAssertionsSigned: env.SAML_WANT_ASSERTIONS_SIGNED,
+ wantAuthnResponseSigned: env.SAML_WANT_RESPONSE_SIGNED,
+ signatureAlgorithm: env.SAML_SIGNATURE_ALGORITHM,
+ digestAlgorithm: env.SAML_SIGNATURE_ALGORITHM,
+ identifierFormat: env.SAML_IDENTIFIER_FORMAT,
+ acceptedClockSkewMs: env.SAML_CLOCK_SKEW_MS,
+ validateInResponseTo: env.SAML_ALLOW_IDP_INITIATED
+ ? ValidateInResponseTo.ifPresent
+ : ValidateInResponseTo.always,
+ requestIdExpirationPeriodMs: REQUEST_ID_TTL_SEC * 1000,
+ cacheProvider: postgresCacheProvider,
+ disableRequestedAuthnContext: true,
+
+ // Optional SP keypair — signs AuthnRequests and decrypts encrypted assertions.
+ ...(env.SAML_SP_PRIVATE_KEY
+ ? { privateKey: env.SAML_SP_PRIVATE_KEY, decryptionPvk: env.SAML_SP_PRIVATE_KEY }
+ : {}),
+ ...(env.SAML_SP_CERT ? { publicCert: env.SAML_SP_CERT } : {}),
+ });
+}
+
+// SP metadata XML for IdP registration. Deliberately does NOT require IdP config
+// — you fetch this first to set up the IdP side, before pasting IdP details back.
+export function generateSpMetadataXml() {
+ const cert = env.SAML_SP_CERT || null;
+ return generateServiceProviderMetadata({
+ issuer: spEntityId(),
+ callbackUrl: acsUrl(),
+ logoutCallbackUrl: sloCallbackUrl(),
+ decryptionCert: cert,
+ publicCerts: cert,
+ identifierFormat: env.SAML_IDENTIFIER_FORMAT,
+ wantAssertionsSigned: env.SAML_WANT_ASSERTIONS_SIGNED,
+ decryptionPvk: env.SAML_SP_PRIVATE_KEY || undefined,
+ privateKey: env.SAML_SP_PRIVATE_KEY || undefined,
+ signatureAlgorithm: env.SAML_SIGNATURE_ALGORITHM,
+ });
+}
+
+// ── RelayState (signed; carries the post-login redirect) ────────────────────
+
+export async function signRelayState(payload) {
+ const data = Buffer.from(JSON.stringify(payload)).toString('base64url');
+ const sig = await hmacSha256(env.JWT_SECRET, `saml-relay:${data}`);
+ return `${data}.${sig}`;
+}
+
+export async function verifyRelayState(state) {
+ if (!state || typeof state !== 'string') return null;
+ const dot = state.lastIndexOf('.');
+ if (dot < 0) return null;
+ const data = state.slice(0, dot);
+ const sig = state.slice(dot + 1);
+ const expected = await hmacSha256(env.JWT_SECRET, `saml-relay:${data}`);
+ if (!constantTimeEquals(sig, expected)) return null;
+ try {
+ return JSON.parse(Buffer.from(data, 'base64url').toString('utf8'));
+ } catch {
+ return null;
+ }
+}
+
+// Only allow same-origin relative redirects so RelayState can't be used as an
+// open-redirect vector. Rejects protocol-relative ("//evil.com") and absolute URLs.
+export function safeNextPath(next, fallback = '/dashboard') {
+ if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//')) return fallback;
+ return next;
+}
+
+// ── Identity extraction from a validated assertion ──────────────────────────
+
+// IdPs scatter the same claim across wildly different attribute names (friendly
+// name, OID, WS-Fed claim URI). Check the common spellings for each field.
+const EMAIL_KEYS = [
+ 'email',
+ 'mail',
+ 'emailaddress',
+ 'urn:oid:0.9.2342.19200300.100.1.3',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',
+ 'http://schemas.xmlsoap.org/claims/EmailAddress',
+];
+const NAME_KEYS = [
+ 'displayName',
+ 'displayname',
+ 'name',
+ 'cn',
+ 'urn:oid:2.16.840.1.113730.3.1.241',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/displayname',
+];
+const GIVEN_KEYS = [
+ 'givenName',
+ 'firstName',
+ 'urn:oid:2.5.4.42',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname',
+];
+const SUR_KEYS = [
+ 'sn',
+ 'surname',
+ 'lastName',
+ 'urn:oid:2.5.4.4',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname',
+];
+
+function firstAttr(profile, keys) {
+ for (const k of keys) {
+ const v = profile?.[k];
+ if (v == null) continue;
+ const val = Array.isArray(v) ? v[0] : v;
+ if (val != null && String(val).trim()) return String(val).trim();
+ }
+ return null;
+}
+
+export function extractSamlIdentity(profile) {
+ const issuer = profile.issuer || null;
+ const nameID = profile.nameID || null;
+ const nameIDFormat = profile.nameIDFormat || null;
+
+ let email = firstAttr(profile, EMAIL_KEYS);
+ // Fall back to the NameID when it's an email (either explicitly emailAddress
+ // format, or just shaped like one — many IdPs use email as the subject).
+ if (!email && nameID && /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(nameID)) {
+ email = nameID;
+ }
+ if (email) email = email.toLowerCase();
+
+ let name = firstAttr(profile, NAME_KEYS);
+ if (!name) {
+ const parts = [firstAttr(profile, GIVEN_KEYS), firstAttr(profile, SUR_KEYS)].filter(Boolean);
+ name = parts.length ? parts.join(' ') : null;
+ }
+
+ return { issuer, nameID, nameIDFormat, email, name, sessionIndex: profile.sessionIndex || null };
+}
+
+// Stable synthetic-email seed for IdPs that don't release an email claim.
+export async function subjectHash(issuer, nameID) {
+ return (await sha256(`${issuer || ''}|${nameID}`)).slice(0, 24);
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 30ba25878..b2050b04b 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -30,6 +30,28 @@ create unique index if not exists users_wallet_unique on users(wallet_address) w
create unique index if not exists users_username_unique on users(lower(username)) where username is not null;
create unique index if not exists users_privy_did_unique on users(privy_did) where privy_did is not null;
+-- SAML SSO subject link (set when a user signs in via an enterprise IdP).
+alter table users add column if not exists saml_name_id text;
+alter table users add column if not exists saml_issuer text;
+-- A SAML subject is unique per (IdP issuer, NameID). Partial unique so the same
+-- NameID from two different IdPs never collides and non-SSO users (null
+-- saml_name_id) are unconstrained.
+create unique index if not exists users_saml_subject_unique
+ on users(saml_issuer, saml_name_id) where saml_name_id is not null;
+
+-- ── saml_request_ids — SAML SSO InResponseTo replay protection ──────────────
+-- The /api/auth/saml/login lambda records each AuthnRequest ID here; the
+-- /api/auth/saml/acs lambda (a separate serverless instance) confirms the IdP's
+-- response echoes one we issued, then deletes it. Lives in Postgres rather than
+-- process memory so it survives across instances. Rows are swept on insert and
+-- removed on successful validation; abandoned logins expire by created_at.
+create table if not exists saml_request_ids (
+ request_id text primary key,
+ value text not null,
+ created_at timestamptz not null default now()
+);
+create index if not exists saml_request_ids_created on saml_request_ids(created_at);
+
-- ── user_subdomains — tracks `<label>.threews.sol` SNS claims ───────────────
-- Populated by /api/threews/subdomain POST; read by /api/threews/* + a few
-- on-ramp endpoints (u-og, x402/pay-by-name). Without it every /threews/claim
diff --git a/api/_lib/solana/sdk-bridge.js b/api/_lib/solana/sdk-bridge.js
index 86627c46c..6bd60776d 100644
--- a/api/_lib/solana/sdk-bridge.js
+++ b/api/_lib/solana/sdk-bridge.js
@@ -23,6 +23,16 @@ function toPubkey(mint) {
return mint instanceof PublicKey ? mint : new PublicKey(String(mint));
}
+// "Account does not exist or has no data" is the SDK's signal that a mint has no
+// bonding-curve account — the expected, documented result for any non-pump mint
+// (USDC, wSOL, a plain SPL token). Callers already turn that into a clean "no
+// curve" 404, so it is not a warning-worthy event. Logging it once per poll
+// turned a single curve-less mint into thousands of warning lines. Treat it as
+// benign and stay quiet; genuine RPC/parse failures still warn below.
+function isMissingAccount(err) {
+ return /account does not exist|has no data|could not find/i.test(String(err));
+}
+
async function fetchState(connection, mint) {
const { OnlinePumpSdk } = await loadSdk();
const sdk = new OnlinePumpSdk(connection);
@@ -47,7 +57,7 @@ export async function getTokenPrice(connection, mint) {
const { global, feeConfig, bondingCurve, mintSupply } = await fetchState(connection, pk);
return sdkGetTokenPrice({ global, feeConfig, mintSupply, bondingCurve });
} catch (err) {
- if (!err?.graduated) {
+ if (!err?.graduated && !isMissingAccount(err)) {
console.warn('[sdk-bridge] getTokenPrice failed: %s', String(err).slice(0, 120));
}
return null;
@@ -65,7 +75,9 @@ export async function getGraduationProgress(connection, mint) {
]);
return sdkGetGrad(global, bondingCurve);
} catch (err) {
- console.warn('[sdk-bridge] getGraduationProgress failed: %s', String(err).slice(0, 120));
+ if (!isMissingAccount(err)) {
+ console.warn('[sdk-bridge] getGraduationProgress failed: %s', String(err).slice(0, 120));
+ }
return null;
}
}
@@ -84,7 +96,9 @@ export async function getBuyQuote(connection, mint, solAmount) {
const impact = calculateBuyPriceImpact({ global, feeConfig, mintSupply, bondingCurve, solAmount: amount });
return { tokens, priceImpact: impact.impactBps / 100 };
} catch (err) {
- console.warn('[sdk-bridge] getBuyQuote failed: %s', String(err).slice(0, 120));
+ if (!isMissingAccount(err)) {
+ console.warn('[sdk-bridge] getBuyQuote failed: %s', String(err).slice(0, 120));
+ }
return null;
}
}
@@ -103,7 +117,9 @@ export async function getSellQuote(connection, mint, tokenAmount) {
const impact = calculateSellPriceImpact({ global, feeConfig, mintSupply, bondingCurve, tokenAmount: amount });
return { sol, priceImpact: impact.impactBps / 100 };
} catch (err) {
- console.warn('[sdk-bridge] getSellQuote failed: %s', String(err).slice(0, 120));
+ if (!isMissingAccount(err)) {
+ console.warn('[sdk-bridge] getSellQuote failed: %s', String(err).slice(0, 120));
+ }
return null;
}
}
@@ -125,7 +141,9 @@ export async function getBondingCurveState(connection, mint) {
isMayhemMode: Boolean(bc.isMayhemMode),
};
} catch (err) {
- console.warn('[sdk-bridge] getBondingCurveState failed: %s', String(err).slice(0, 120));
+ if (!isMissingAccount(err)) {
+ console.warn('[sdk-bridge] getBondingCurveState failed: %s', String(err).slice(0, 120));
+ }
return null;
}
}
diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.js
index eb033d5e8..5f94a3067 100644
--- a/api/agents/pumpfun.js
+++ b/api/agents/pumpfun.js
@@ -191,7 +191,9 @@ async function handleMetadata(req, res) {
if (!a) return error(res, 404, 'not_found', 'agent not found');
const origin = _env.APP_ORIGIN;
const image = a.meta?.image_url || `${origin}/api/agents/${a.id}/og`;
- const animation = a.avatar_id ? `${origin}/api/avatars/${a.avatar_id}/glb` : null;
+ // `.glb`-terminating proxy URL: marketplaces and glTF viewers that key off
+ // the file extension (not the Content-Type) need the trailing `.glb`.
+ const animation = a.avatar_id ? `${origin}/api/avatars/${a.avatar_id}/model.glb` : null;
const symbol = String(a.name || 'AGENT').toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 10) || 'AGENT';
return json(res, 200, {
name: a.name, symbol,
diff --git a/api/auth/saml/[action].js b/api/auth/saml/[action].js
new file mode 100644
index 000000000..f3d92df15
--- /dev/null
+++ b/api/auth/saml/[action].js
@@ -0,0 +1,240 @@
+// SAML 2.0 SSO endpoints — three.ws acts as the Service Provider.
+// Dispatched by the URL action segment (see vercel.json):
+// GET /api/auth/saml/metadata → SP metadata XML (give this to the IdP)
+// GET /api/auth/saml/login → build AuthnRequest, redirect to the IdP
+// POST /api/auth/saml/acs → consume the IdP's signed assertion, sign in
+// GET /api/auth/saml/logout → clear the local session
+//
+// The ACS is intentionally NOT behind our CSRF cookie check: it receives a
+// top-level form POST from the IdP (HTTP-POST binding). Its integrity comes from
+// the assertion's XML signature, the audience/condition checks, and InResponseTo
+// replay protection — all enforced by validatePostResponseAsync in node-saml.
+
+import { sql } from '../../_lib/db.js';
+import { createSession, sessionCookie, destroySession, getSessionUser } from '../../_lib/auth.js';
+import { cors, redirect, error, wrap, readForm } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { env } from '../../_lib/env.js';
+import { logAudit } from '../../_lib/audit.js';
+import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';
+import { generateReferralCode } from '../../_lib/referrals.js';
+import {
+ getSamlInstance,
+ generateSpMetadataXml,
+ samlConfigured,
+ signRelayState,
+ verifyRelayState,
+ safeNextPath,
+ extractSamlIdentity,
+ subjectHash,
+} from '../../_lib/saml.js';
+
+const loginUrl = (params) => `${env.APP_ORIGIN}/login${params ? `?${params}` : ''}`;
+
+// ── metadata ────────────────────────────────────────────────────────────────
+
+async function handleMetadata(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ const xml = generateSpMetadataXml();
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/samlmetadata+xml; charset=utf-8');
+ res.setHeader('content-disposition', 'inline; filename="three-ws-sp-metadata.xml"');
+ res.setHeader('cache-control', 'public, max-age=3600');
+ res.end(xml);
+}
+
+// ── login (SP-initiated) ────────────────────────────────────────────────────
+
+async function handleLogin(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!samlConfigured()) return redirect(res, loginUrl('error=sso_unavailable'));
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return redirect(res, loginUrl('error=rate_limited'));
+
+ const url = new URL(req.url, env.APP_ORIGIN);
+ const next = safeNextPath(url.searchParams.get('next'));
+
+ let saml;
+ try {
+ saml = await getSamlInstance();
+ } catch {
+ return redirect(res, loginUrl('error=sso_unavailable'));
+ }
+
+ const relayState = await signRelayState({ next, ts: Date.now() });
+ const authnUrl = await saml.getAuthorizeUrlAsync(relayState, undefined, {});
+ return redirect(res, authnUrl);
+}
+
+// ── acs (assertion consumer service) ────────────────────────────────────────
+
+async function handleAcs(req, res) {
+ // The IdP POSTs here as a top-level navigation; reject anything else.
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+ if (req.method !== 'POST') {
+ res.setHeader('allow', 'POST');
+ return error(res, 405, 'method_not_allowed', 'ACS accepts POST');
+ }
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return redirect(res, loginUrl('error=rate_limited'));
+ if (!samlConfigured()) return redirect(res, loginUrl('error=sso_unavailable'));
+
+ const form = await readForm(req);
+ const SAMLResponse = form.SAMLResponse;
+ const RelayState = form.RelayState;
+ if (!SAMLResponse) return redirect(res, loginUrl('error=saml_no_response'));
+
+ let saml;
+ try {
+ saml = await getSamlInstance();
+ } catch {
+ return redirect(res, loginUrl('error=sso_unavailable'));
+ }
+
+ let profile;
+ try {
+ ({ profile } = await saml.validatePostResponseAsync({ SAMLResponse, RelayState }));
+ } catch (err) {
+ // Signature, audience, condition, clock, or InResponseTo failure. The
+ // detail is logged server-side; the user gets a generic, safe message.
+ console.error('[saml] response validation failed:', err?.message);
+ return redirect(res, loginUrl('error=saml_invalid'));
+ }
+
+ const identity = profile ? extractSamlIdentity(profile) : null;
+ if (!identity?.nameID) return redirect(res, loginUrl('error=saml_no_subject'));
+
+ const relay = await verifyRelayState(RelayState);
+ const next = safeNextPath(relay?.next);
+
+ try {
+ const userId = await findOrCreateUser(identity);
+ await destroySession(req);
+ const token = await createSession({ userId, userAgent: req.headers['user-agent'], ip });
+ res.setHeader('set-cookie', sessionCookie(token));
+ logAudit({ userId, action: 'login', req, meta: { method: 'saml', issuer: identity.issuer } });
+ return redirect(res, `${env.APP_ORIGIN}${next}`);
+ } catch (err) {
+ if (err?.code === 'account_deleted') return redirect(res, loginUrl('error=account_deleted'));
+ console.error('[saml] provisioning failed:', err?.message);
+ return redirect(res, loginUrl('error=saml_error'));
+ }
+}
+
+// ── logout ──────────────────────────────────────────────────────────────────
+
+async function handleLogout(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ const sessionUser = await getSessionUser(req).catch(() => null);
+ await destroySession(req);
+ res.setHeader('set-cookie', sessionCookie('', { clear: true }));
+ if (sessionUser) logAudit({ userId: sessionUser.id, action: 'logout', req, meta: { method: 'saml' } });
+ return redirect(res, loginUrl('signed_out=1'));
+}
+
+// ── user provisioning ───────────────────────────────────────────────────────
+
+// Resolve the SAML subject to a three.ws user, in priority order:
+// 1. Existing SSO link (issuer + NameID).
+// 2. Existing account with the same verified email → link SSO to it. (Enterprise
+// IdPs attest the email, so this is safe account-linking, not takeover.)
+// 3. Just-in-time provision a new account.
+async function findOrCreateUser({ issuer, nameID, email, name }) {
+ const issuerKey = issuer || '';
+
+ const [bySaml] = await sql`
+ select id, deleted_at from users
+ where saml_issuer = ${issuerKey} and saml_name_id = ${nameID}
+ limit 1
+ `;
+ if (bySaml) {
+ if (bySaml.deleted_at) throw Object.assign(new Error('account deleted'), { code: 'account_deleted' });
+ return bySaml.id;
+ }
+
+ if (email) {
+ const [byEmail] = await sql`select id, deleted_at from users where email = ${email} limit 1`;
+ if (byEmail) {
+ if (byEmail.deleted_at) {
+ throw Object.assign(new Error('account deleted'), { code: 'account_deleted' });
+ }
+ await sql`
+ update users
+ set saml_issuer = ${issuerKey}, saml_name_id = ${nameID},
+ email_verified = true, updated_at = now()
+ where id = ${byEmail.id}
+ `;
+ return byEmail.id;
+ }
+ }
+
+ // Synthetic, non-deliverable address when the IdP releases no email — mirrors
+ // the wallet-login convention (…@wallet.local) so downstream code that keys
+ // off email still works.
+ const userEmail = email || `saml-${await subjectHash(issuer, nameID)}@sso.three.ws.local`;
+ const displayName = name || (email ? email.split('@')[0] : 'SSO User');
+ const userId = await insertSamlUser({
+ email: userEmail,
+ displayName,
+ issuer: issuerKey,
+ nameID,
+ emailVerified: Boolean(email),
+ });
+ queueMicrotask(() => seedDefaultAgent(userId));
+ return userId;
+}
+
+// Bounded retry around the unique referral_code index (mirrors api/auth/[action].js).
+// A 23505 on a non-referral constraint means a concurrent ACS won the race for
+// this subject/email — re-select and return that user instead of erroring.
+const MAX_REFERRAL_CODE_TRIES = 8;
+
+async function insertSamlUser({ email, displayName, issuer, nameID, emailVerified }) {
+ for (let i = 0; i < MAX_REFERRAL_CODE_TRIES; i += 1) {
+ const code = generateReferralCode();
+ try {
+ const [row] = await sql`
+ insert into users (email, display_name, referral_code, saml_issuer, saml_name_id, email_verified)
+ values (${email}, ${displayName}, ${code}, ${issuer}, ${nameID}, ${emailVerified})
+ returning id
+ `;
+ return row.id;
+ } catch (err) {
+ if (err?.code === '23505' && /referral_code/.test(err.message || '')) continue;
+ if (err?.code === '23505') {
+ const [existing] = await sql`
+ select id from users
+ where (saml_issuer = ${issuer} and saml_name_id = ${nameID}) or email = ${email}
+ limit 1
+ `;
+ if (existing) return existing.id;
+ }
+ throw err;
+ }
+ }
+ throw new Error('referral_code_generation_exhausted');
+}
+
+// ── dispatch ────────────────────────────────────────────────────────────────
+
+const DISPATCH = {
+ metadata: handleMetadata,
+ login: handleLogin,
+ acs: handleAcs,
+ logout: handleLogout,
+};
+
+export default wrap(async (req, res) => {
+ const action =
+ req.query?.action ?? new URL(req.url, env.APP_ORIGIN).pathname.split('/').filter(Boolean).pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown saml action: ${action}`);
+ return fn(req, res);
+});
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index d866f3352..377912aff 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -30,7 +30,15 @@ const PINATA_ENDPOINT = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export default wrap(async (req, res) => {
- const action = req.query?.action;
+ let action = req.query?.action;
+ // Expose the GLB proxy at a `.glb`-terminating URL as well. Standard glTF
+ // viewers, NFT marketplaces, and third-party avatar renderers sniff the URL
+ // extension rather than the `model/gltf-binary` Content-Type, and reject the
+ // bare `/api/avatars/:id/glb` for not ending in `.glb`. Routing any
+ // `/api/avatars/:id/<name>.glb` to the same handler makes our avatars load in
+ // those tools unchanged. (`glb-versions` has no `.glb` suffix, so it's never
+ // caught here.)
+ if (typeof action === 'string' && /\.glb$/i.test(action)) action = 'glb';
// Every sub-action below ends up querying `WHERE id = $1` against a uuid
// column. A malformed id leaks Postgres 22P02 to the caller as a 500;
// short-circuit with a clean 404 unless it's a demo-fixture id.
@@ -589,10 +597,10 @@ async function handleGlb(req, res) {
if (String(id).startsWith('avatar_demo_')) {
const demo = DEMO_AVATARS.find((a) => a.avatarId === id);
- if (!demo?.url) return error(res, 404, 'not_found', 'demo avatar has no glb');
+ if (!demo?.glbUrl) return error(res, 404, 'not_found', 'demo avatar has no glb');
// Demo avatars live in /public so the redirect target is same-origin
// and already CORS-clean.
- return redirect(res, demo.url);
+ return redirect(res, demo.glbUrl);
}
const avatar = await getAvatar({ id, requesterId: null });
diff --git a/api/config.js b/api/config.js
index 14b42d387..d45135b05 100644
--- a/api/config.js
+++ b/api/config.js
@@ -24,9 +24,19 @@ export default wrap(async (req, res) => {
const videoAvatarEnabled = !!(process.env.LONGCAT_WORKER_URL || '').trim();
+ // Enterprise SAML SSO — true when an IdP is wired (explicit cert + SSO URL,
+ // or a metadata URL to fetch them from). Drives the SSO button on /login.
+ // Cheap env-only check so this hot endpoint doesn't pull in the SAML lib.
+ const samlEnabled = Boolean(
+ (process.env.SAML_IDP_CERT && process.env.SAML_IDP_SSO_URL) ||
+ process.env.SAML_IDP_METADATA_URL,
+ );
+
return json(res, 200, {
walletConnectProjectId: process.env.VITE_WALLETCONNECT_PROJECT_ID || '',
privyAppId: process.env.VITE_PRIVY_APP_ID || process.env.PRIVY_APP_ID || '',
+ samlEnabled,
+ samlLabel: process.env.SAML_BUTTON_LABEL || 'Single sign-on (SSO)',
features: {
// /create/selfie + /scan use /api/avatars/reconstruct, which 501s
// unless an ML backend is wired. The pages read this to either show the
diff --git a/api/widgets/_demo-fixtures.js b/api/widgets/_demo-fixtures.js
index b495d9293..bee9f21ac 100644
--- a/api/widgets/_demo-fixtures.js
+++ b/api/widgets/_demo-fixtures.js
@@ -176,7 +176,7 @@ export const DEMO_WIDGETS = {
showControls: false,
autoRotate: false,
envPreset: 'neutral',
- mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
limit: 20,
refreshMs: 30_000,
},
@@ -214,7 +214,10 @@ export const DEMO_WIDGETS = {
autoRotate: true,
rotationSpeed: 0.4,
envPreset: 'neutral',
- mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ // $three — the platform token and a real pump.fun mint, so the demo
+ // shows a live bonding curve. A non-pump mint here has no curve and
+ // makes the widget poll /api/pump/curve into a permanent 404 loop.
+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
network: 'mainnet',
refreshMs: 15_000,
showUsd: true,
diff --git a/package-lock.json b/package-lock.json
index fd683722c..e901ec0ff 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -22,6 +22,7 @@
"packages/viewer-presets",
"packages/pumpfun-mcp",
"packages/ibm-watsonx-mcp",
+ "packages/ibm-x402-mcp",
"packages/threews-avatar-mcp"
],
"dependencies": {
@@ -54,6 +55,7 @@
"@neynar/nodejs-sdk": "^3.175.0",
"@nirholas/pump-sdk": "^1.0.0",
"@noble/curves": "^2.2.0",
+ "@node-saml/node-saml": "^5.1.0",
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
"@privy-io/js-sdk-core": "^0.67.0",
@@ -12885,6 +12887,38 @@
],
"license": "MIT"
},
+ "node_modules/@node-saml/node-saml": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/@node-saml/node-saml/-/node-saml-5.1.0.tgz",
+ "integrity": "sha512-t3cJnZ4aC7HhPZ6MGylGZULvUtBOZ6FzuUndaHGXjmIZHXnLfC/7L8a57O9Q9V7AxJGKAiRM5zu2wNm9EsvQpw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/debug": "^4.1.12",
+ "@types/qs": "^6.9.18",
+ "@types/xml-encryption": "^1.2.4",
+ "@types/xml2js": "^0.4.14",
+ "@xmldom/is-dom-node": "^1.0.1",
+ "@xmldom/xmldom": "^0.8.10",
+ "debug": "^4.4.0",
+ "xml-crypto": "^6.1.2",
+ "xml-encryption": "^3.1.0",
+ "xml2js": "^0.6.2",
+ "xmlbuilder": "^15.1.1",
+ "xpath": "^0.0.34"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/@node-saml/node-saml/node_modules/xmlbuilder": {
+ "version": "15.1.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz",
+ "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -21367,6 +21401,10 @@
"resolved": "packages/ibm-watsonx-mcp",
"link": true
},
+ "node_modules/@three-ws/ibm-x402-mcp": {
+ "resolved": "packages/ibm-x402-mcp",
+ "link": true
+ },
"node_modules/@three-ws/pumpfun-mcp": {
"resolved": "packages/pumpfun-mcp",
"link": true
@@ -21763,7 +21801,6 @@
"version": "6.15.0",
"resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.0.tgz",
"integrity": "sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==",
- "dev": true,
"license": "MIT"
},
"node_modules/@types/range-parser": {
@@ -21883,6 +21920,24 @@
"@types/node": "*"
}
},
+ "node_modules/@types/xml-encryption": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/@types/xml-encryption/-/xml-encryption-1.2.4.tgz",
+ "integrity": "sha512-I69K/WW1Dv7j6O3jh13z0X8sLWJRXbu5xnHDl9yHzUNDUBtUoBY058eb5s+x/WG6yZC1h8aKdI2EoyEPjyEh+Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/xml2js": {
+ "version": "0.4.14",
+ "resolved": "https://registry.npmjs.org/@types/xml2js/-/xml2js-0.4.14.tgz",
+ "integrity": "sha512-4YnrRemBShWRO2QjvUin8ESA41rH+9nQGLUGZV/1IDhi3SL9OhdpNC/MrulTWuptXKwhx/aDxE7toV0f/ypIXQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/yargs": {
"version": "17.0.35",
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
@@ -23614,6 +23669,24 @@
"@solana/sysvars": "^5.0"
}
},
+ "node_modules/@xmldom/is-dom-node": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@xmldom/is-dom-node/-/is-dom-node-1.0.1.tgz",
+ "integrity": "sha512-CJDxIgE5I0FH+ttq/Fxy6nRpxP70+e2O048EPe85J2use3XKdatVM7dDVvFNjQudd9B49NPoZ+8PG49zj4Er8Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ }
+ },
+ "node_modules/@xmldom/xmldom": {
+ "version": "0.8.13",
+ "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.8.13.tgz",
+ "integrity": "sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/@zauthx402/sdk": {
"version": "0.1.14",
"resolved": "https://registry.npmjs.org/@zauthx402/sdk/-/sdk-0.1.14.tgz",
@@ -50773,6 +50846,49 @@
"integrity": "sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==",
"license": "MIT"
},
+ "node_modules/xml-crypto": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/xml-crypto/-/xml-crypto-6.1.2.tgz",
+ "integrity": "sha512-leBOVQdVi8FvPJrMYoum7Ici9qyxfE4kVi+AkpUoYCSXaQF4IlBm1cneTK9oAxR61LpYxTx7lNcsnBIeRpGW2w==",
+ "license": "MIT",
+ "dependencies": {
+ "@xmldom/is-dom-node": "^1.0.1",
+ "@xmldom/xmldom": "^0.8.10",
+ "xpath": "^0.0.33"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/xml-crypto/node_modules/xpath": {
+ "version": "0.0.33",
+ "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.33.tgz",
+ "integrity": "sha512-NNXnzrkDrAzalLhIUc01jO2mOzXGXh1JwPgkihcLLzw98c0WgYDmmjSh1Kl3wzaxSVWMuA+fe0WTWOBDWCBmNA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6.0"
+ }
+ },
+ "node_modules/xml-encryption": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/xml-encryption/-/xml-encryption-3.1.0.tgz",
+ "integrity": "sha512-PV7qnYpoAMXbf1kvQkqMScLeQpjCMixddAKq9PtqVrho8HnYbBOWNfG0kA4R7zxQDo7w9kiYAyzS/ullAyO55Q==",
+ "license": "MIT",
+ "dependencies": {
+ "@xmldom/xmldom": "^0.8.5",
+ "escape-html": "^1.0.3",
+ "xpath": "0.0.32"
+ }
+ },
+ "node_modules/xml-encryption/node_modules/xpath": {
+ "version": "0.0.32",
+ "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.32.tgz",
+ "integrity": "sha512-rxMJhSIoiO8vXcWvSifKqhvV96GjiD5wYb8/QHdoRyQvraTpp4IEv944nhGausZZ3u7dhQXteZuZbaqfpB7uYw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6.0"
+ }
+ },
"node_modules/xml-name-validator": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
@@ -50827,6 +50943,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/xpath": {
+ "version": "0.0.34",
+ "resolved": "https://registry.npmjs.org/xpath/-/xpath-0.0.34.tgz",
+ "integrity": "sha512-FxF6+rkr1rNSQrhUNYrAFJpRXNzlDoMxeXN5qI84939ylEv3qqPFKa85Oxr6tDaJKqwW6KKyo2v26TSv3k6LeA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6.0"
+ }
+ },
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
@@ -51068,6 +51193,26 @@
"node": ">=20"
}
},
+ "packages/ibm-x402-mcp": {
+ "name": "@three-ws/ibm-x402-mcp",
+ "version": "1.0.0",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@x402/core": "^2.13.0",
+ "@x402/extensions": "^2.12.0",
+ "@x402/mcp": "^2.13.0",
+ "@x402/svm": "^2.13.0",
+ "zod": "^3.23.8",
+ "zod-to-json-schema": "3.25.2"
+ },
+ "bin": {
+ "ibm-x402-mcp": "src/index.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
"packages/pumpfun-mcp": {
"name": "@three-ws/pumpfun-mcp",
"version": "0.1.0",
diff --git a/package.json b/package.json
index 174577cb2..5fc32fa1b 100644
--- a/package.json
+++ b/package.json
@@ -142,6 +142,7 @@
"@neynar/nodejs-sdk": "^3.175.0",
"@nirholas/pump-sdk": "^1.0.0",
"@noble/curves": "^2.2.0",
+ "@node-saml/node-saml": "^5.1.0",
"@octokit/rest": "^22.0.1",
"@pixiv/three-vrm": "^3.5.3",
"@privy-io/js-sdk-core": "^0.67.0",
diff --git a/public/login.html b/public/login.html
index 92c2be3c6..f34cc0318 100644
--- a/public/login.html
+++ b/public/login.html
@@ -338,6 +338,9 @@
.privy-chain-btn:disabled { opacity: 0.4; cursor: default; }
#privy-wallet-status { margin: 6px 0 0; font-size: 12px; color: #888; }
+ /* ── Enterprise SSO (SAML) button ── */
+ .sso-btn { width: 100%; margin-top: 10px; }
+
/* ── No-wallet welcome banner ── */
.no-wallet-hint {
display: none;
@@ -556,6 +559,14 @@
</div>
<p id="privy-inline-err" hidden></p>
</div>
+
+ <!-- Enterprise SSO (SAML). Revealed by the script below only when an
+ identity provider is configured (GET /api/config → samlEnabled). -->
+ <button type="button" id="sso-btn" class="privy-chain-btn sso-btn" hidden>
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
+ <span id="sso-btn-label">Single sign-on (SSO)</span>
+ </button>
+
<div class="or-divider" id="privy-or-divider">or</div>
<label for="email">Email or username</label>
@@ -718,6 +729,51 @@
</footer>
<script type="module" src="/wallet-login.js"></script>
<script type="module" src="/src/privy-login.js"></script>
+ <script type="module">
+ // Reveal the enterprise SSO button only when an IdP is configured, and
+ // surface any ?error / ?signed_out the SAML endpoints redirected back with.
+ (async () => {
+ const params = new URLSearchParams(location.search);
+ const errEl = document.getElementById('err');
+ const SSO_MESSAGES = {
+ sso_unavailable: 'Single sign-on is not available right now.',
+ saml_invalid: 'Single sign-on could not be verified. Please try again.',
+ saml_no_response: 'No response received from your identity provider.',
+ saml_no_subject:
+ 'Your identity provider returned no identity. Contact your administrator.',
+ saml_error: 'Something went wrong completing single sign-on.',
+ account_deleted: 'This account has been deleted.',
+ rate_limited: 'Too many attempts. Please try again in a moment.',
+ };
+ const errCode = params.get('error');
+ if (errEl && errCode && SSO_MESSAGES[errCode]) {
+ errEl.textContent = SSO_MESSAGES[errCode];
+ errEl.style.display = 'block';
+ } else if (errEl && params.get('signed_out')) {
+ errEl.textContent = 'You have been signed out.';
+ errEl.style.color = '#9fd09f';
+ errEl.style.display = 'block';
+ }
+
+ const ssoBtn = document.getElementById('sso-btn');
+ if (!ssoBtn) return;
+ let cfg;
+ try {
+ cfg = await (await fetch('/api/config')).json();
+ } catch {
+ return; // config unreachable — leave SSO hidden
+ }
+ if (!cfg?.samlEnabled) return;
+ if (cfg.samlLabel) {
+ document.getElementById('sso-btn-label').textContent = cfg.samlLabel;
+ }
+ ssoBtn.hidden = false;
+ ssoBtn.addEventListener('click', () => {
+ const next = window.__loginNext || params.get('next') || '/dashboard';
+ window.location.href = '/api/auth/saml/login?next=' + encodeURIComponent(next);
+ });
+ })();
+ </script>
<script>
(function () {
const form = document.getElementById('f');
diff --git a/public/logo.png b/public/logo.png
new file mode 100644
index 000000000..fa17ee3b3
Binary files /dev/null and b/public/logo.png differ
diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.js
index ffba7e1e7..3fefd2bc6 100644
--- a/public/widgets-gallery/gallery.js
+++ b/public/widgets-gallery/gallery.js
@@ -195,7 +195,7 @@ function renderShowcase(w) {
w.type === 'live-trades-canvas'
? 'So11111111111111111111111111111111111111112'
: w.type === 'kol-trades'
- ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
+ ? 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'
: '',
kind: 'all',
format: 'iframe',
@@ -623,7 +623,7 @@ function renderShowcase(w) {
function defaultMint(type) {
if (type === 'live-trades-canvas') return 'So11111111111111111111111111111111111111112';
- if (type === 'kol-trades') return 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+ if (type === 'kol-trades') return 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
return '';
}
diff --git a/src/widgets/bonding-curve.js b/src/widgets/bonding-curve.js
index c1f9a3885..fe7e9d49d 100644
--- a/src/widgets/bonding-curve.js
+++ b/src/widgets/bonding-curve.js
@@ -433,6 +433,7 @@ export function mountBondingCurve(rootEl, opts = {}) {
rootEl.appendChild(wrap);
let destroyed = false;
+ let stopped = false; // set once a mint is known to have no bonding curve (404)
let timer = null;
let raf = null;
let displayedProgress = 0; // currently-rendered marker/percent position
@@ -492,7 +493,7 @@ export function mountBondingCurve(rootEl, opts = {}) {
}
async function poll() {
- if (destroyed || !mint) return;
+ if (destroyed || stopped || !mint) return;
try {
const [resp, solUsd] = await Promise.all([
fetch(`/api/pump/curve?mint=${encodeURIComponent(mint)}&network=${network}`),
@@ -500,12 +501,17 @@ export function mountBondingCurve(rootEl, opts = {}) {
]);
if (destroyed) return;
if (resp.status === 404) {
+ // A 404 is terminal: this mint has no bonding curve (graduated or
+ // not a pump.fun token) and never will. Stop the interval instead
+ // of re-polling forever — an interval against a curve-less mint is
+ // exactly what turned a misconfigured demo into a 404 storm.
view = computeView(null);
applyEmptyState(
card,
els,
'No active bonding curve — this token may have graduated or isn’t a pump.fun mint.',
);
+ stopPolling();
return;
}
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
@@ -522,8 +528,16 @@ export function mountBondingCurve(rootEl, opts = {}) {
}
}
+ function stopPolling() {
+ stopped = true;
+ if (timer) {
+ clearInterval(timer);
+ timer = null;
+ }
+ }
+
poll();
- timer = setInterval(poll, refreshMs);
+ if (!stopped) timer = setInterval(poll, refreshMs);
return {
destroy() {
diff --git a/tests/api/avatars-glb-proxy.test.js b/tests/api/avatars-glb-proxy.test.js
new file mode 100644
index 000000000..270e731cc
--- /dev/null
+++ b/tests/api/avatars-glb-proxy.test.js
@@ -0,0 +1,102 @@
+// Tests for the /api/avatars/:id/:action dispatcher's GLB proxy resolution.
+//
+// Two behaviours are covered, both offline via the demo-avatar fixture (the
+// demo branch 302-redirects without touching R2 or the DB):
+// 1. A `.glb`-terminating action (`model.glb`, `<uuid>.glb`, …) resolves to
+// the same GLB proxy as the bare `glb` action — so glТF viewers / NFT
+// marketplaces that sniff the URL extension can load three.ws avatars.
+// 2. The demo branch redirects to the fixture's `glbUrl` (regression guard:
+// it previously read a non-existent `demo.url` and 404'd every demo).
+//
+// DB, R2, auth, and the zauth SDK are mocked so the suite runs with no network.
+
+import { describe, it, expect, vi } from 'vitest';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+// Any DB/R2 access means the demo short-circuit was skipped — fail loudly.
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: () => { throw new Error('DB should not be queried for a demo avatar'); },
+}));
+vi.mock('../../api/_lib/r2.js', () => ({
+ r2: { send: () => { throw new Error('R2 should not be hit for a demo avatar'); } },
+ publicUrl: (key) => `https://cdn.test/${key}`,
+}));
+// No credentials on any request → every auth path resolves anonymous.
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => null,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+ hasScope: () => false,
+}));
+
+import handler from '../../api/avatars/[id]/[action].js';
+import { DEMO_AVATARS } from '../../api/_lib/demo-avatars.js';
+
+const DEMO = DEMO_AVATARS[0]; // avatar_demo_disk_cz → https://three.ws/avatars/cz.glb
+
+function makeReq({ id, action, method = 'GET' } = {}) {
+ return {
+ method,
+ url: `/api/avatars/${id}/${action}`,
+ headers: { host: 'three.ws' },
+ query: { id, action },
+ };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end() { this.writableEnded = true; this.headersSent = true; },
+ };
+}
+
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res);
+ return res;
+}
+
+describe('GET /api/avatars/:id/:action — GLB proxy resolution', () => {
+ it('redirects the bare `glb` action to the demo fixture glbUrl', async () => {
+ const res = await invoke({ id: DEMO.avatarId, action: 'glb' });
+ expect(res.statusCode).toBe(302);
+ expect(res.getHeader('location')).toBe(DEMO.glbUrl);
+ });
+
+ it('resolves a `model.glb` action to the same GLB proxy', async () => {
+ const res = await invoke({ id: DEMO.avatarId, action: 'model.glb' });
+ expect(res.statusCode).toBe(302);
+ expect(res.getHeader('location')).toBe(DEMO.glbUrl);
+ });
+
+ it('resolves a `<uuid>.glb` action (case-insensitive suffix) to the GLB proxy', async () => {
+ const res = await invoke({ id: DEMO.avatarId, action: `${DEMO.avatarId}.GLB` });
+ expect(res.statusCode).toBe(302);
+ expect(res.getHeader('location')).toBe(DEMO.glbUrl);
+ });
+
+ it('serves wildcard CORS so third-party hosts can fetch the bytes', async () => {
+ const res = await invoke({ id: DEMO.avatarId, action: 'model.glb' });
+ expect(res.getHeader('access-control-allow-origin')).toBe('*');
+ });
+
+ it('does not treat `glb-versions` as the glb proxy', async () => {
+ // glb-versions requires auth; with no session/bearer it must 401, proving
+ // the `.glb` normalization did not swallow it into the glb handler (which
+ // would have 302'd the demo instead).
+ const res = await invoke({ id: DEMO.avatarId, action: 'glb-versions' });
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s an unknown action', async () => {
+ const res = await invoke({ id: DEMO.avatarId, action: 'not-a-real-action' });
+ expect(res.statusCode).toBe(404);
+ });
+});
diff --git a/tests/api/saml.test.js b/tests/api/saml.test.js
new file mode 100644
index 000000000..37d2a05c6
--- /dev/null
+++ b/tests/api/saml.test.js
@@ -0,0 +1,150 @@
+// Unit tests for the SAML SP helper module (api/_lib/saml.js).
+// Pure functions — real HMAC/crypto, real node-saml, no network. db.js is mocked
+// so the cache provider never opens a real connection.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';
+process.env.JWT_SECRET ||= 'test-saml-secret-at-least-32-characters';
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+}));
+
+const saml = await import('../../api/_lib/saml.js');
+
+const IDP_META = `<?xml version="1.0"?>
+<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" entityID="https://idp.example.com/saml">
+ <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
+ <md:KeyDescriptor use="signing">
+ <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+ <ds:X509Data><ds:X509Certificate>MIIBfakeCERTbody==</ds:X509Certificate></ds:X509Data>
+ </ds:KeyInfo>
+ </md:KeyDescriptor>
+ <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/slo"/>
+ <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="https://idp.example.com/sso/post"/>
+ <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/sso/redirect"/>
+ </md:IDPSSODescriptor>
+</md:EntityDescriptor>`;
+
+describe('parseIdpMetadata', () => {
+ it('extracts entityID, redirect SSO URL, SLO URL, and signing cert', () => {
+ const r = saml.parseIdpMetadata(IDP_META);
+ expect(r.entityId).toBe('https://idp.example.com/saml');
+ expect(r.ssoUrl).toBe('https://idp.example.com/sso/redirect'); // prefers HTTP-Redirect
+ expect(r.sloUrl).toBe('https://idp.example.com/slo');
+ expect(r.cert).toBe('MIIBfakeCERTbody=='); // PEM headers/whitespace stripped
+ });
+
+ it('returns null for non-metadata XML', () => {
+ expect(saml.parseIdpMetadata('<foo/>')).toBeNull();
+ });
+
+ it('returns null when no signing cert is present', () => {
+ const noCert = IDP_META.replace(/<md:KeyDescriptor[\s\S]*?<\/md:KeyDescriptor>/, '');
+ expect(saml.parseIdpMetadata(noCert)).toBeNull();
+ });
+});
+
+describe('generateSpMetadataXml', () => {
+ it('advertises our ACS URL and SP entity ID without needing IdP config', () => {
+ const xml = saml.generateSpMetadataXml();
+ expect(xml).toContain('https://three.ws/api/auth/saml/acs');
+ expect(xml).toContain('https://three.ws/api/auth/saml/metadata');
+ });
+});
+
+describe('RelayState sign/verify', () => {
+ it('round-trips a payload', async () => {
+ const rs = await saml.signRelayState({ next: '/settings', ts: 7 });
+ expect(await saml.verifyRelayState(rs)).toEqual({ next: '/settings', ts: 7 });
+ });
+
+ it('rejects a tampered, malformed, or null RelayState', async () => {
+ const rs = await saml.signRelayState({ next: '/x' });
+ expect(await saml.verifyRelayState(rs.slice(0, -2) + 'zz')).toBeNull();
+ expect(await saml.verifyRelayState('garbage')).toBeNull();
+ expect(await saml.verifyRelayState(null)).toBeNull();
+ });
+});
+
+describe('safeNextPath', () => {
+ it('keeps same-origin relative paths', () => {
+ expect(saml.safeNextPath('/dashboard')).toBe('/dashboard');
+ });
+ it('rejects open-redirect vectors', () => {
+ expect(saml.safeNextPath('//evil.com')).toBe('/dashboard');
+ expect(saml.safeNextPath('https://evil.com')).toBe('/dashboard');
+ expect(saml.safeNextPath(undefined)).toBe('/dashboard');
+ expect(saml.safeNextPath('x', '/home')).toBe('/home');
+ });
+});
+
+describe('extractSamlIdentity', () => {
+ it('reads a lowercased email attribute and a display name', () => {
+ const id = saml.extractSamlIdentity({
+ issuer: 'i',
+ nameID: 'n',
+ nameIDFormat: 'unspecified',
+ email: '[email protected]',
+ displayName: 'Jane Doe',
+ sessionIndex: 'sx',
+ });
+ expect(id.email).toBe('[email protected]');
+ expect(id.name).toBe('Jane Doe');
+ expect(id.sessionIndex).toBe('sx');
+ });
+
+ it('falls back to an email-shaped NameID and given+surname', () => {
+ const id = saml.extractSamlIdentity({
+ issuer: 'i',
+ nameID: '[email protected]',
+ nameIDFormat: 'persistent',
+ givenName: 'Bob',
+ sn: 'Smith',
+ });
+ expect(id.email).toBe('[email protected]');
+ expect(id.name).toBe('Bob Smith');
+ });
+
+ it('leaves email null when the NameID is opaque', () => {
+ const id = saml.extractSamlIdentity({ issuer: 'i', nameID: 'opaque-123', nameIDFormat: 'persistent' });
+ expect(id.email).toBeNull();
+ });
+
+ it('reads OID and WS-Fed claim spellings', () => {
+ const id = saml.extractSamlIdentity({
+ issuer: 'i',
+ nameID: 'n',
+ nameIDFormat: 'unspecified',
+ 'urn:oid:0.9.2342.19200300.100.1.3': '[email protected]',
+ 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Claim Name',
+ });
+ expect(id.email).toBe('[email protected]');
+ expect(id.name).toBe('Claim Name');
+ });
+});
+
+describe('samlConfigured / getSamlInstance', () => {
+ beforeEach(() => {
+ delete process.env.SAML_IDP_SSO_URL;
+ delete process.env.SAML_IDP_CERT;
+ delete process.env.SAML_IDP_METADATA_URL;
+ delete process.env.SAML_IDP_ENTITY_ID;
+ });
+
+ it('is false and throws 501 when unconfigured', async () => {
+ expect(saml.samlConfigured()).toBe(false);
+ await expect(saml.getSamlInstance()).rejects.toMatchObject({ status: 501, code: 'not_configured' });
+ });
+
+ it('builds an instance from explicit IdP env fields', async () => {
+ process.env.SAML_IDP_SSO_URL = 'https://idp.example.com/sso/redirect';
+ process.env.SAML_IDP_CERT = 'MIIBfakeCERTbody==';
+ process.env.SAML_IDP_ENTITY_ID = 'https://idp.example.com/saml';
+ expect(saml.samlConfigured()).toBe(true);
+ const inst = await saml.getSamlInstance();
+ expect(typeof inst.getAuthorizeUrlAsync).toBe('function');
+ expect(typeof inst.validatePostResponseAsync).toBe('function');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 23ecfe559..d4da9fdfe 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1433,6 +1433,22 @@
"src": "/api/auth/x/callback",
"dest": "/api/auth/x/[action]?action=callback"
},
+ {
+ "src": "/api/auth/saml/metadata",
+ "dest": "/api/auth/saml/[action]?action=metadata"
+ },
+ {
+ "src": "/api/auth/saml/login",
+ "dest": "/api/auth/saml/[action]?action=login"
+ },
+ {
+ "src": "/api/auth/saml/acs",
+ "dest": "/api/auth/saml/[action]?action=acs"
+ },
+ {
+ "src": "/api/auth/saml/logout",
+ "dest": "/api/auth/saml/[action]?action=logout"
+ },
{
"src": "/api/auth/wallets",
"dest": "/api/auth/wallets/[action]"
@@ -1731,6 +1747,10 @@
"src": "/api/avatars/([^/]+)/og",
"dest": "/api/avatar-og?id=$1"
},
+ {
+ "src": "/api/avatars/([^/]+)/[^/]+\\.glb",
+ "dest": "/api/avatars/$1/glb"
+ },
{
"src": "/api/a/(\\d+)/(\\d+)/og",
"dest": "/api/a-og?chain=$1&id=$2"