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.

fix(routes): route /api/auth/github/token to the PAT connect action

nirholas0a4dee684512
diff --git a/tests/api/draft-mint-evm-leg.test.js b/tests/api/draft-mint-evm-leg.test.js
new file mode 100644
index 000000000..491c0eef4
--- /dev/null
+++ b/tests/api/draft-mint-evm-leg.test.js
@@ -0,0 +1,213 @@
+// Unit tests for the draft mint's chain legs themselves (api/_lib/draft-mint.js),
+// as opposed to the orchestration around them (tests/api/draft-mint.test.js,
+// which injects both legs as fakes and therefore never executes their bodies).
+//
+// The ERC-8004 leg's broadcast branch is the dangerous one to leave uncovered:
+// it runs AFTER register(string) has already landed on chain, so a defect there
+// cannot be undone by retrying. Everything below the leg (RPC, wallet custody,
+// pinning, ethers' signer/contract) is a boundary and is injected; the calldata
+// encoder stays real so the register(string) selector is genuinely exercised.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const REGISTRY = '0x8004A818BFB912233c491871b3d84c89A494BD9e';
+const AGENT_WALLET = '0x1111111111111111111111111111111111111111';
+
+const sqlMock = vi.fn(async (strings) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/FROM agent_identities ai/.test(q)) {
+ return [{ id: 'agent-1', user_id: 'u1', meta: { encrypted_wallet_key: 'enc:agent-1' } }];
+ }
+ if (/SELECT meta FROM agent_identities/.test(q)) return [{ meta: { keep: 'me' } }];
+ return [];
+});
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...args) => sqlMock(...args),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+vi.mock('../../api/_lib/agent-identity.js', () => ({
+ resolveOrCreateAgentForAvatar: vi.fn(async () => null),
+}));
+vi.mock('../../api/_lib/erc8004-chains.js', () => ({
+ CHAIN_BY_ID: {
+ 84532: { name: 'Base Sepolia', registry: REGISTRY, explorer: 'https://sepolia.basescan.org' },
+ },
+}));
+vi.mock('../../api/_lib/ipfs-pin.js', () => ({
+ pinToIPFS: vi.fn(async () => ({ uri: 'ipfs://bafyDraftCard' })),
+}));
+vi.mock('../../api/_lib/r2.js', () => ({
+ putObject: vi.fn(async () => {}),
+ publicUrl: (key) => `https://cdn.three.ws/${key}`,
+ thumbnailUrl: (key) => (key ? `https://cdn.three.ws/${key}` : null),
+}));
+
+const providerMock = {
+ getBalance: vi.fn(async () => 10n ** 18n),
+ estimateGas: vi.fn(async () => 120_000n),
+};
+vi.mock('../../api/_lib/evm/rpc.js', () => ({
+ evmFallbackProvider: vi.fn(async () => providerMock),
+}));
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ getOrCreateAgentEvmWallet: vi.fn(async () => ({ address: AGENT_WALLET })),
+ recoverAgentKey: vi.fn(async () => `0x${'ab'.repeat(32)}`),
+}));
+
+const receipt = {
+ hash: `0x${'fe'.repeat(32)}`,
+ blockNumber: 9_100_200,
+ logs: [{ topics: [], data: '0x' }],
+};
+const registerCalls = [];
+
+// Only the signer/contract boundary is replaced. Interface, parseEther and
+// formatEther stay real so the encoded calldata under test is the real thing.
+vi.mock('ethers', async (importOriginal) => {
+ const actual = await importOriginal();
+ class Wallet {
+ constructor(key, provider) {
+ this.address = `0x${'22'.repeat(20)}`;
+ this.provider = provider;
+ }
+ sendTransaction = vi.fn(async () => ({ wait: async () => ({}) }));
+ }
+ class Contract {
+ constructor(address, abi, signer) {
+ this.target = address;
+ this.signer = signer;
+ this.interface = {
+ parseLog: () => ({ name: 'Registered', args: ['42'] }),
+ };
+ this['register(string)'] = async (uri) => {
+ registerCalls.push(uri);
+ return { wait: async () => receipt };
+ };
+ }
+ }
+ return { ...actual, Wallet, Contract };
+});
+
+const { evmDraftMint, solanaDraftMint } = await import('../../api/_lib/draft-mint.js');
+
+const agent = {
+ id: 'agent-1',
+ user_id: 'u1',
+ name: 'Me',
+ description: 'A reconstructed agent',
+ meta: {},
+ avatar_id: 'avatar-1',
+ thumbnail_key: 'u/u1/a/thumb.png',
+ storage_key: 'u/u1/a/model.glb',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ registerCalls.length = 0;
+ vi.unstubAllEnvs();
+});
+
+describe('evmDraftMint', () => {
+ it('skips a chain the registry map does not cover', async () => {
+ const out = await evmDraftMint({ agent, userId: 'u1', chainId: 999_999 });
+ expect(out).toEqual({ status: 'skipped', reason: 'unsupported_chain', chainId: 999_999 });
+ });
+
+ it('short-circuits to already when the agent carries this chain registration', async () => {
+ const minted = {
+ ...agent,
+ meta: { onchain: { chain: 'eip155:84532', onchain_id: '7', tx_hash: '0xdead' } },
+ };
+ const out = await evmDraftMint({ agent: minted, userId: 'u1', chainId: 84532 });
+ expect(out).toEqual({ status: 'already', chainId: 84532, onchainId: '7', txHash: '0xdead' });
+ expect(registerCalls).toHaveLength(0);
+ });
+
+ it('dry-runs with real register(string) calldata when no treasury key is configured', async () => {
+ vi.stubEnv('EVM_TREASURY_PRIVATE_KEY', '');
+ const out = await evmDraftMint({ agent, userId: 'u1', chainId: 84532 });
+
+ expect(out.status).toBe('dry_run');
+ expect(out.missing).toBe('EVM_TREASURY_PRIVATE_KEY');
+ expect(out.to).toBe(REGISTRY);
+ expect(out.from).toBe(AGENT_WALLET);
+ expect(out.metadataUri).toBe('ipfs://bafyDraftCard');
+ // f2c298be is the real keccak selector for register(string).
+ expect(out.data.startsWith('0xf2c298be')).toBe(true);
+ expect(out.data).toContain(Buffer.from('ipfs://bafyDraftCard').toString('hex'));
+ expect(out.estimatedGas).toBe('120000');
+ // A dry run must never broadcast.
+ expect(registerCalls).toHaveLength(0);
+ });
+
+ it('reports the on-chain id after a real registration', async () => {
+ // Regression guard: this branch runs only after register(string) has
+ // already been broadcast, so a bad reference here throws with the
+ // transaction irreversibly on chain and the avatar stamp never written.
+ vi.stubEnv('EVM_TREASURY_PRIVATE_KEY', `0x${'11'.repeat(32)}`);
+ const out = await evmDraftMint({ agent, userId: 'u1', chainId: 84532 });
+
+ expect(out.status).toBe('minted');
+ expect(out.onchainId).toBe('42');
+ expect(out.txHash).toBe(receipt.hash);
+ expect(out.chainId).toBe(84532);
+ expect(out.chain).toBe('Base Sepolia');
+ expect(out.registry).toBe(REGISTRY);
+ expect(out.owner).toBe(AGENT_WALLET);
+ expect(out.metadataUri).toBe('ipfs://bafyDraftCard');
+ expect(out.explorer).toBe(`https://sepolia.basescan.org/tx/${receipt.hash}`);
+ expect(registerCalls).toEqual(['ipfs://bafyDraftCard']);
+ });
+
+ it('persists the draft registration as an index row and a merged meta.onchain block', async () => {
+ vi.stubEnv('EVM_TREASURY_PRIVATE_KEY', `0x${'11'.repeat(32)}`);
+ await evmDraftMint({ agent, userId: 'u1', chainId: 84532 });
+
+ const queries = sqlMock.mock.calls.map(([strings]) => strings.join('?'));
+ expect(queries.some((q) => /INSERT INTO\s+erc8004_agents_index/.test(q))).toBe(true);
+
+ const updateCall = sqlMock.mock.calls.find(([strings]) =>
+ /UPDATE agent_identities/.test(strings.join('?')),
+ );
+ expect(updateCall).toBeTruthy();
+ const meta = JSON.parse(updateCall[1]);
+ expect(meta.keep).toBe('me'); // pre-existing meta survives the merge
+ expect(meta.onchain).toMatchObject({
+ chain: 'eip155:84532',
+ family: 'evm',
+ onchain_id: '42',
+ tx_hash: receipt.hash,
+ contract_or_mint: REGISTRY,
+ wallet: AGENT_WALLET.toLowerCase(),
+ draft: true,
+ });
+ });
+
+ it('does not broadcast when the agent has no recoverable custody key', async () => {
+ vi.stubEnv('EVM_TREASURY_PRIVATE_KEY', `0x${'11'.repeat(32)}`);
+ sqlMock.mockImplementationOnce(async () => [{ id: 'agent-1', meta: {} }]);
+ const out = await evmDraftMint({ agent, userId: 'u1', chainId: 84532 });
+ expect(out).toEqual({ status: 'skipped', reason: 'no_evm_key', chainId: 84532 });
+ expect(registerCalls).toHaveLength(0);
+ });
+});
+
+describe('solanaDraftMint', () => {
+ it('short-circuits a devnet draft without loading the mint stack', async () => {
+ const out = await solanaDraftMint({
+ agent: { ...agent, meta: { devnet: { sol_mint_address: 'DevAsset111' } } },
+ network: 'devnet',
+ });
+ expect(out).toEqual({ status: 'already', network: 'devnet', asset: 'DevAsset111' });
+ });
+
+ it('keeps devnet and mainnet drafts in separate namespaces', async () => {
+ // A devnet asset must never satisfy the mainnet idempotency check, or an
+ // operator flipping the flag to mainnet would silently mint nothing.
+ const devnetOnly = { ...agent, meta: { devnet: { sol_mint_address: 'DevAsset111' } } };
+ const out = await solanaDraftMint({ agent: devnetOnly, network: 'mainnet' });
+ expect(out.status).not.toBe('already');
+ });
+});
diff --git a/tests/api/x-memory-seed-consent.test.js b/tests/api/x-memory-seed-consent.test.js
index fb08cd81f..86b87b47f 100644
--- a/tests/api/x-memory-seed-consent.test.js
+++ b/tests/api/x-memory-seed-consent.test.js
@@ -322,6 +322,72 @@ describe('POST /api/agents/:id/memory/seed/x consent gate', () => {
});
});
+// A connection can be narrower than the read the disclosure describes: the
+// owner unticked a permission on X's screen, or connected through a surface
+// that asks for a different scope set. Consent granted against such a
+// connection would be consent to something that cannot happen, so the gate
+// refuses before the grant is recorded rather than after the X API rejects it.
+describe('POST /api/agents/:id/memory/seed/x connection scope gate', () => {
+ it('refuses a connection that cannot read the profile and posts', async () => {
+ dbState.connection = liveConnection({ scopes: 'tweet.write offline.access' });
+ const res = await call({
+ method: 'POST',
+ body: { consent: { accepted: true, scope_version: X_SEED_SCOPE_VERSION } },
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(res.json).toMatchObject({ error: 'insufficient_scope' });
+ expect(res.json.missing_scopes).toEqual(['tweet.read', 'users.read']);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ expect(xSeed).not.toHaveBeenCalled();
+ expect(dbState.queries.some((c) => /INSERT INTO x_memory_consents/i.test(c.q))).toBe(false);
+ });
+
+ it('lets a connection whose scopes were never recorded through', async () => {
+ // Connections predating scope recording store an empty string. Blocking
+ // them would break seeding for every account connected before that landed.
+ dbState.connection = liveConnection({ scopes: '' });
+ dbState.consent = liveConsent();
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ if (String(url).includes('/2/users/me')) {
+ return {
+ ok: true,
+ json: async () => ({
+ data: {
+ id: 'x-account-42',
+ username: 'qauser',
+ name: 'QA User',
+ description: 'Builds agent tooling on Solana',
+ public_metrics: { followers_count: 300, following_count: 120 },
+ },
+ }),
+ };
+ }
+ return { ok: true, json: async () => ({ data: [] }) };
+ }));
+ llmComplete.mockResolvedValue({ text: JSON.stringify(['Builds agent tooling.']) });
+
+ const res = await call({ method: 'POST', body: {} });
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('tells the status endpoint which scopes a narrow connection is short of', async () => {
+ dbState.connection = liveConnection({ scopes: 'users.read offline.access' });
+ const res = await call();
+
+ expect(res.json).toMatchObject({ scopes_ok: false });
+ expect(res.json.missing_scopes).toEqual(['tweet.read']);
+ expect(res.json.required_scopes).toEqual(['tweet.read', 'users.read']);
+ });
+
+ it('reports a read-only connection as able to seed', async () => {
+ dbState.connection = liveConnection({ scopes: 'tweet.read users.read offline.access' });
+ const res = await call();
+ expect(res.json).toMatchObject({ scopes_ok: true });
+ expect(res.json.missing_scopes).toEqual([]);
+ });
+});
+
describe('POST /api/agents/:id/memory/seed/x seeding', () => {
const profilePayload = {
data: {
diff --git a/tests/api/x-scopes.test.js b/tests/api/x-scopes.test.js
new file mode 100644
index 000000000..e61688045
--- /dev/null
+++ b/tests/api/x-scopes.test.js
@@ -0,0 +1,129 @@
+// The X OAuth scope sets and the guards each lane holds a connection to.
+//
+// What this pins is a privacy property, not a formatting one: an owner who
+// connects X only to seed an agent's memory must never be asked for permission
+// to post as them. That is true only while the read set stays free of write
+// scopes, an unrecognised scope name falls back to the full set (so a typo can
+// never silently narrow a posting connect), and the guards read a connection's
+// recorded scopes the same way on both sides.
+
+import { describe, it, expect } from 'vitest';
+import {
+ X_SCOPE_SETS,
+ X_DEFAULT_SCOPE_SET,
+ X_SEED_REQUIRED_SCOPES,
+ X_POST_REQUIRED_SCOPES,
+ resolveScopeSet,
+ parseScopes,
+ missingScopes,
+ hasScopes,
+ isReadOnlyConnection,
+} from '../../api/_lib/x-scopes.js';
+
+const WRITE_SCOPES = ['tweet.write', 'media.write', 'like.write', 'follows.write', 'dm.write'];
+
+describe('scope sets', () => {
+ it('asks for nothing that writes in the read set', () => {
+ for (const scope of X_SCOPE_SETS.read) {
+ expect(WRITE_SCOPES).not.toContain(scope);
+ expect(scope.endsWith('.write')).toBe(false);
+ }
+ });
+
+ it('covers everything seeding reads in the read set', () => {
+ for (const required of X_SEED_REQUIRED_SCOPES) {
+ expect(X_SCOPE_SETS.read).toContain(required);
+ }
+ });
+
+ it('covers both lanes in the full set', () => {
+ for (const required of [...X_SEED_REQUIRED_SCOPES, ...X_POST_REQUIRED_SCOPES]) {
+ expect(X_SCOPE_SETS.full).toContain(required);
+ }
+ });
+
+ it('keeps offline.access in both sets so connections survive a token expiry', () => {
+ expect(X_SCOPE_SETS.read).toContain('offline.access');
+ expect(X_SCOPE_SETS.full).toContain('offline.access');
+ });
+});
+
+describe('resolveScopeSet', () => {
+ it('resolves the read set by name', () => {
+ const set = resolveScopeSet('read');
+ expect(set.name).toBe('read');
+ expect(set.value).toBe('tweet.read users.read offline.access');
+ });
+
+ it('resolves the full set by name', () => {
+ expect(resolveScopeSet('full').name).toBe('full');
+ });
+
+ it('tolerates case and surrounding space in a query param', () => {
+ expect(resolveScopeSet(' READ ').name).toBe('read');
+ });
+
+ it('falls back to the full set for anything unrecognised', () => {
+ for (const input of [undefined, null, '', 'write', 'admin', 42, {}, 'constructor', '__proto__']) {
+ expect(resolveScopeSet(input).name).toBe(X_DEFAULT_SCOPE_SET);
+ }
+ });
+
+ it('hands back a space-separated value ready for the authorize URL', () => {
+ const set = resolveScopeSet('full');
+ expect(set.value.split(' ')).toEqual([...set.scopes]);
+ });
+});
+
+describe('parseScopes', () => {
+ it('reads the space-separated string X returns', () => {
+ expect(parseScopes('tweet.read users.read offline.access')).toEqual([
+ 'tweet.read', 'users.read', 'offline.access',
+ ]);
+ });
+
+ it('tolerates commas and repeated whitespace', () => {
+ expect(parseScopes('tweet.read, users.read')).toEqual(['tweet.read', 'users.read']);
+ });
+
+ it('reads an array unchanged and an absent value as empty', () => {
+ expect(parseScopes(['tweet.read'])).toEqual(['tweet.read']);
+ expect(parseScopes(null)).toEqual([]);
+ expect(parseScopes(undefined)).toEqual([]);
+ expect(parseScopes(' ')).toEqual([]);
+ });
+});
+
+describe('missingScopes', () => {
+ it('names exactly what a narrow connection lacks', () => {
+ expect(missingScopes('users.read offline.access', X_SEED_REQUIRED_SCOPES)).toEqual(['tweet.read']);
+ expect(missingScopes('tweet.read users.read', X_POST_REQUIRED_SCOPES)).toEqual(['tweet.write']);
+ });
+
+ it('finds nothing missing when the connection covers the lane', () => {
+ expect(missingScopes(X_SCOPE_SETS.read.join(' '), X_SEED_REQUIRED_SCOPES)).toEqual([]);
+ expect(missingScopes(X_SCOPE_SETS.full.join(' '), X_POST_REQUIRED_SCOPES)).toEqual([]);
+ });
+
+ it('treats unrecorded scopes as unknown rather than as nothing granted', () => {
+ // Connections made before the callback stored scopes must keep working.
+ expect(missingScopes('', X_SEED_REQUIRED_SCOPES)).toEqual([]);
+ expect(missingScopes(null, X_POST_REQUIRED_SCOPES)).toEqual([]);
+ expect(hasScopes('', X_POST_REQUIRED_SCOPES)).toBe(true);
+ });
+});
+
+describe('isReadOnlyConnection', () => {
+ it('recognises a connection made for seeding', () => {
+ expect(isReadOnlyConnection(X_SCOPE_SETS.read.join(' '))).toBe(true);
+ });
+
+ it('does not call a posting connection read-only', () => {
+ expect(isReadOnlyConnection(X_SCOPE_SETS.full.join(' '))).toBe(false);
+ });
+
+ it('does not guess about a connection with no recorded scopes', () => {
+ expect(isReadOnlyConnection('')).toBe(false);
+ expect(isReadOnlyConnection(null)).toBe(false);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 8d230df54..b532a3a8d 100644
--- a/vercel.json
+++ b/vercel.json
@@ -2935,6 +2935,10 @@
"src": "/api/auth/github/callback",
"dest": "/api/auth/github/[action]?action=callback"
},
+ {
+ "src": "/api/auth/github/token",
+ "dest": "/api/auth/github/[action]?action=token"
+ },
{
"src": "/api/auth/github/status",
"dest": "/api/auth/github/[action]?action=status"