Compare commits

...

18 Commits

Author SHA1 Message Date
Shreyaschorge
20c6113b8f fix qoutes 2025-09-18 21:01:36 +05:30
Shreyaschorge
343d64a77c Enfore resolutions 2025-09-18 20:58:47 +05:30
veganbeef
c5ca1618ed bump @neynar/react version 2025-09-09 23:36:13 -07:00
veganbeef
db735d7568 fix: frame_* to miniapp_* 2025-09-09 23:20:35 -07:00
veganbeef
ccd27f53b3 fix: build failure 2025-09-09 23:07:53 -07:00
veganbeef
f14493e35b fix: deploy script dependency issue 2025-09-09 22:53:03 -07:00
veganbeef
3af6ee0e71 upgrade to @neynar/react v1.2.12 2025-09-09 22:25:23 -07:00
veganbeef
54646a5035 fix: support yarn and pnpm 2025-09-08 16:23:24 -07:00
veganbeef
be7d6b76ae fix: update @neynar/react version and add overrides for qix vulnerable packages 2025-09-08 16:00:14 -07:00
veganbeef
09ef2e374e feat: bump @neynar/react version 2025-08-21 11:31:40 -07:00
veganbeef
1cce5835d4 feat: bump neynar/react version 2025-08-11 17:21:09 -07:00
veganbeef
55c7c4b129 feat: udpate script to support --return-url flag [NEYN-6533] 2025-08-07 16:11:45 -07:00
veganbeef
055dc4adbd feat: integrate returnUrl to config [NEYN-6533] 2025-08-07 16:02:46 -07:00
veganbeef
98579bcea9 fix: constants format 2025-07-23 19:29:00 -07:00
veganbeef
ea7ee37e71 fix: siwn csrf config 2025-07-23 19:23:03 -07:00
veganbeef
feb9f3e161 fix: authkit provider 2025-07-23 18:57:24 -07:00
veganbeef
8c5b8d8329 move conditional next-auth code to alternate files 2025-07-23 18:54:08 -07:00
Shreyaschorge
d0f8c75a2e Merge pull request #24 from neynarxyz/sc/fix-401-for-siwn-auth
fix:401 for SIWN and remove farcaster login mechanism
2025-07-21 16:24:59 +05:30
17 changed files with 1191 additions and 793 deletions

View File

@@ -4,8 +4,3 @@ KV_REST_API_TOKEN=''
KV_REST_API_URL=''
NEXT_PUBLIC_URL='http://localhost:3000'
NEXTAUTH_URL='http://localhost:3000'
NEXTAUTH_SECRET=""
NEYNAR_API_KEY=""
NEYNAR_CLIENT_ID=""
USE_TUNNEL="false"

View File

@@ -11,6 +11,7 @@ let noWallet = false;
let noTunnel = false;
let sponsoredSigner = false;
let seedPhrase = null;
let returnUrl = null;
// Check for -y flag
const yIndex = args.indexOf('-y');
@@ -74,6 +75,19 @@ if (yIndex !== -1) {
console.error('Error: --seed-phrase requires a seed phrase');
process.exit(1);
}
} else if (arg === '-r' || arg === '--return-url') {
if (i + 1 < args.length) {
returnUrl = args[i + 1];
if (returnUrl.startsWith('-')) {
console.error('Error: Return URL cannot start with a dash (-)');
process.exit(1);
}
args.splice(i, 2); // Remove both the flag and its value
i--; // Adjust index since we removed 2 elements
} else {
console.error('Error: -r/--return-url requires a return URL');
process.exit(1);
}
}
}
@@ -85,7 +99,7 @@ if (autoAcceptDefaults && !projectName) {
process.exit(1);
}
init(projectName, autoAcceptDefaults, apiKey, noWallet, noTunnel, sponsoredSigner, seedPhrase).catch((err) => {
init(projectName, autoAcceptDefaults, apiKey, noWallet, noTunnel, sponsoredSigner, seedPhrase, returnUrl).catch((err) => {
console.error('Error:', err);
process.exit(1);
});

View File

@@ -63,7 +63,16 @@ async function queryNeynarApp(apiKey) {
}
// Export the main CLI function for programmatic use
export async function init(projectName = null, autoAcceptDefaults = false, apiKey = null, noWallet = false, noTunnel = false, sponsoredSigner = false, seedPhrase = null) {
export async function init(
projectName = null,
autoAcceptDefaults = false,
apiKey = null,
noWallet = false,
noTunnel = false,
sponsoredSigner = false,
seedPhrase = null,
returnUrl = null
) {
printWelcomeMessage();
// Ask about Neynar usage
@@ -246,6 +255,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
enableAnalytics: true,
seedPhrase: seedPhraseValue,
useSponsoredSigner: useSponsoredSignerValue,
returnUrl: returnUrl,
};
} else {
// If autoAcceptDefaults is false but we have a projectName, we still need to ask for other options
@@ -505,7 +515,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
'@farcaster/miniapp-wagmi-connector': '^1.0.0',
'@farcaster/mini-app-solana': '>=0.0.17 <1.0.0',
'@farcaster/quick-auth': '>=0.0.7 <1.0.0',
'@neynar/react': '^1.2.5',
'@neynar/react': '^1.2.13',
'@radix-ui/react-label': '^2.1.1',
'@solana/wallet-adapter-react': '^0.15.38',
'@tanstack/react-query': '^5.61.0',
@@ -535,11 +545,13 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
"crypto": "^1.0.1",
"eslint": "^8",
"eslint-config-next": "15.0.3",
"inquirer": "^10.2.2",
"localtunnel": "^2.0.2",
"pino-pretty": "^13.0.0",
"postcss": "^8",
"tailwindcss": "^3.4.1",
"ts-node": "^10.9.2",
"tsx": "^4.20.5",
"typescript": "^5"
};
@@ -554,6 +566,40 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
packageJson.dependencies['next-auth'] = '^4.24.11';
}
// Add security overrides for vulnerable packages (compatible with npm, Yarn, and pnpm)
const securityOverrides = {
"backslash": "0.2.0",
"chalk-template": "1.1.0",
"supports-hyperlinks": "4.1.0",
"has-ansi": "6.0.0",
"simple-swizzle": "0.2.2",
"color-string": "2.1.0",
"error-ex": "1.3.2",
"color-name": "2.0.0",
"is-arrayish": "0.3.2",
"slice-ansi": "7.1.0",
"color-convert": "3.1.0",
"wrap-ansi": "9.0.0",
"ansi-regex": "6.2.0",
"supports-color": "10.2.0",
"strip-ansi": "7.1.0",
"chalk": "5.6.0",
"ansi-styles": "6.2.1",
"axios@^1": ">=1 <2",
"axios@^0": ">=0 <1",
};
// npm v8.3+ overrides
packageJson.overrides = securityOverrides;
// Yarn (v1 and Berry) resolutions
packageJson.resolutions = securityOverrides;
// pnpm overrides (namespaced)
packageJson.pnpm = {
overrides: securityOverrides
};
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
// Handle .env file
@@ -610,13 +656,14 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
USE_WALLET: /^export const USE_WALLET\s*:\s*boolean\s*=\s*(true|false);$/m,
ANALYTICS_ENABLED:
/^export const ANALYTICS_ENABLED\s*:\s*boolean\s*=\s*(true|false);$/m,
RETURN_URL: /^export const RETURN_URL\s*:\s*string\s*\|\s*undefined\s*=\s*(undefined|['"`][^'"`]*['"`]);$/m,
};
// Update APP_NAME
constantsContent = safeReplace(
constantsContent,
patterns.APP_NAME,
`export const APP_NAME = '${escapeString(answers.projectName)}';`,
`export const APP_NAME: string = '${escapeString(answers.projectName)}';`,
'APP_NAME'
);
@@ -624,7 +671,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.APP_DESCRIPTION,
`export const APP_DESCRIPTION = '${escapeString(
`export const APP_DESCRIPTION: string = '${escapeString(
answers.description
)}';`,
'APP_DESCRIPTION'
@@ -634,7 +681,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.APP_PRIMARY_CATEGORY,
`export const APP_PRIMARY_CATEGORY = '${escapeString(
`export const APP_PRIMARY_CATEGORY: string = '${escapeString(
answers.primaryCategory || ''
)}';`,
'APP_PRIMARY_CATEGORY'
@@ -648,7 +695,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.APP_TAGS,
`export const APP_TAGS = ${tagsString};`,
`export const APP_TAGS: string[] = ${tagsString};`,
'APP_TAGS'
);
@@ -656,7 +703,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.APP_BUTTON_TEXT,
`export const APP_BUTTON_TEXT = '${escapeString(
`export const APP_BUTTON_TEXT: string = '${escapeString(
answers.buttonText || ''
)}';`,
'APP_BUTTON_TEXT'
@@ -666,7 +713,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.USE_WALLET,
`export const USE_WALLET = ${answers.useWallet};`,
`export const USE_WALLET: boolean = ${answers.useWallet};`,
'USE_WALLET'
);
@@ -674,10 +721,19 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
constantsContent = safeReplace(
constantsContent,
patterns.ANALYTICS_ENABLED,
`export const ANALYTICS_ENABLED = ${answers.enableAnalytics};`,
`export const ANALYTICS_ENABLED: boolean = ${answers.enableAnalytics};`,
'ANALYTICS_ENABLED'
);
// Update RETURN_URL
const returnUrlValue = answers.returnUrl ? `'${escapeString(answers.returnUrl)}'` : 'undefined';
constantsContent = safeReplace(
constantsContent,
patterns.RETURN_URL,
`export const RETURN_URL: string | undefined = ${returnUrlValue};`,
'RETURN_URL'
);
fs.writeFileSync(constantsPath, constantsContent);
} else {
console.log('⚠️ constants.ts not found, skipping constants update');
@@ -693,6 +749,7 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
);
}
if (answers.seedPhrase) {
console.log('✅ Writing SEED_PHRASE and NEXTAUTH_SECRET to .env.local');
fs.appendFileSync(envPath, `\nSEED_PHRASE="${answers.seedPhrase}"`);
// Add NextAuth secret for SIWN
fs.appendFileSync(
@@ -747,9 +804,12 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
fs.rmSync(binPath, { recursive: true, force: true });
}
// Remove NeynarAuthButton directory, NextAuth API routes, and auth directory if SIWN is not enabled (no seed phrase)
// Handle SIWN-related files based on whether seed phrase is provided
if (!answers.seedPhrase) {
console.log('\nRemoving NeynarAuthButton directory, NextAuth API routes, and auth directory (SIWN not enabled)...');
// Remove SIWN-related files when SIWN is not enabled (no seed phrase)
console.log('\nRemoving SIWN-related files (SIWN not enabled)...');
// Remove NeynarAuthButton directory
const neynarAuthButtonPath = path.join(projectPath, 'src', 'components', 'ui', 'NeynarAuthButton');
if (fs.existsSync(neynarAuthButtonPath)) {
fs.rmSync(neynarAuthButtonPath, { recursive: true, force: true });
@@ -772,19 +832,56 @@ export async function init(projectName = null, autoAcceptDefaults = false, apiKe
fs.rmSync(authFilePath, { force: true });
}
// Replace NeynarAuthButton import in ActionsTab.tsx with null component
// Remove SIWN-specific files
const actionsTabNeynarAuthPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.NeynarAuth.tsx');
if (fs.existsSync(actionsTabNeynarAuthPath)) {
fs.rmSync(actionsTabNeynarAuthPath, { force: true });
}
const layoutNeynarAuthPath = path.join(projectPath, 'src', 'app', 'layout.NeynarAuth.tsx');
if (fs.existsSync(layoutNeynarAuthPath)) {
fs.rmSync(layoutNeynarAuthPath, { force: true });
}
const providersNeynarAuthPath = path.join(projectPath, 'src', 'app', 'providers.NeynarAuth.tsx');
if (fs.existsSync(providersNeynarAuthPath)) {
fs.rmSync(providersNeynarAuthPath, { force: true });
}
} else {
// Move SIWN-specific files to replace the regular versions when SIWN is enabled
console.log('\nMoving SIWN-specific files to replace regular versions (SIWN enabled)...');
// Move ActionsTab.NeynarAuth.tsx to ActionsTab.tsx
const actionsTabNeynarAuthPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.NeynarAuth.tsx');
const actionsTabPath = path.join(projectPath, 'src', 'components', 'ui', 'tabs', 'ActionsTab.tsx');
if (fs.existsSync(actionsTabNeynarAuthPath)) {
if (fs.existsSync(actionsTabPath)) {
let actionsTabContent = fs.readFileSync(actionsTabPath, 'utf8');
fs.rmSync(actionsTabPath, { force: true }); // Delete original
}
fs.renameSync(actionsTabNeynarAuthPath, actionsTabPath);
console.log('✅ Moved ActionsTab.NeynarAuth.tsx to ActionsTab.tsx');
}
// Replace the dynamic import of NeynarAuthButton with a null component
actionsTabContent = actionsTabContent.replace(
/const NeynarAuthButton = dynamic\([\s\S]*?\);/,
'// NeynarAuthButton disabled - SIWN not enabled\nconst NeynarAuthButton = () => {\n return null;\n};'
);
// Move layout.NeynarAuth.tsx to layout.tsx
const layoutNeynarAuthPath = path.join(projectPath, 'src', 'app', 'layout.NeynarAuth.tsx');
const layoutPath = path.join(projectPath, 'src', 'app', 'layout.tsx');
if (fs.existsSync(layoutNeynarAuthPath)) {
if (fs.existsSync(layoutPath)) {
fs.rmSync(layoutPath, { force: true }); // Delete original
}
fs.renameSync(layoutNeynarAuthPath, layoutPath);
console.log('✅ Moved layout.NeynarAuth.tsx to layout.tsx');
}
fs.writeFileSync(actionsTabPath, actionsTabContent);
console.log('✅ Replaced NeynarAuthButton import in ActionsTab.tsx with null component');
// Move providers.NeynarAuth.tsx to providers.tsx
const providersNeynarAuthPath = path.join(projectPath, 'src', 'app', 'providers.NeynarAuth.tsx');
const providersPath = path.join(projectPath, 'src', 'app', 'providers.tsx');
if (fs.existsSync(providersNeynarAuthPath)) {
if (fs.existsSync(providersPath)) {
fs.rmSync(providersPath, { force: true }); // Delete original
}
fs.renameSync(providersNeynarAuthPath, providersPath);
console.log('✅ Moved providers.NeynarAuth.tsx to providers.tsx');
}
}

1125
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@neynar/create-farcaster-mini-app",
"version": "1.7.14",
"version": "1.8.13",
"type": "module",
"private": false,
"access": "public",
@@ -35,7 +35,7 @@
"build:raw": "next build",
"start": "next start",
"lint": "next lint",
"deploy:vercel": "node --loader ts-node/esm scripts/deploy.ts",
"deploy:vercel": "tsx scripts/deploy.ts",
"deploy:raw": "vercel --prod",
"cleanup": "node scripts/cleanup.js"
},
@@ -51,5 +51,17 @@
"@neynar/nodejs-sdk": "^2.19.0",
"@types/node": "^22.13.10",
"typescript": "^5.6.3"
},
"overrides": {
"chalk": "5.3.0",
"strip-ansi": "6.0.1",
"wrap-ansi": "8.1.0",
"ansi-styles": "6.2.3",
"color-convert": "2.0.1",
"color-name": "1.1.4",
"is-core-module": "2.13.1",
"error-ex": "1.3.2",
"simple-swizzle": "0.2.2",
"has-ansi": "5.0.1"
}
}

View File

@@ -115,8 +115,9 @@ async function checkRequiredEnvVars(): Promise<void> {
`${newLine}${varConfig.name}="${value.trim()}"`,
);
}
}
// Ask about SIWN if SEED_PHRASE is provided
// Ask about SIWN if SEED_PHRASE is provided (moved outside the loop)
if (process.env.SEED_PHRASE && !process.env.SPONSOR_SIGNER) {
const { sponsorSigner } = await inquirer.prompt([
{
@@ -140,7 +141,7 @@ async function checkRequiredEnvVars(): Promise<void> {
console.log('✅ Sponsor signer preference stored in .env.local');
}
// Ask about required chains
// Ask about required chains (moved outside the loop)
const { useRequiredChains } = await inquirer.prompt([
{
type: 'confirm',
@@ -189,6 +190,68 @@ async function checkRequiredEnvVars(): Promise<void> {
fs.writeFileSync(constantsPath, constantsContent);
console.log('✅ Required chains updated in constants.ts');
}
// Ask for account association
console.log(
`\n⚠ To complete your mini app manifest, you need to sign it using the Farcaster developer portal.`,
);
console.log(
'1. Go to: https://farcaster.xyz/~/developers/mini-apps/manifest',
);
console.log(
'2. Enter your app domain (you\'ll get this after deployment)',
);
console.log(
'3. Click "Transfer Ownership" and follow the instructions to sign the manifest.',
);
console.log(
'4. Copy the resulting accountAssociation JSON.',
);
console.log('5. Paste it below when prompted.');
console.log(
'\nNote: If you don\'t have the accountAssociation yet, you can press Ctrl+C to skip and add it later.',
);
try {
const { userAccountAssociation } = await inquirer.prompt([
{
type: 'editor',
name: 'userAccountAssociation',
message: 'Paste the accountAssociation JSON here (or press Ctrl+C to skip):',
validate: (input: string) => {
if (!input.trim()) {
return 'You can press Ctrl+C to skip this step';
}
try {
const parsed = JSON.parse(input);
if (parsed.header && parsed.payload && parsed.signature) {
return true;
}
return 'Invalid accountAssociation: must have header, payload, and signature';
} catch (e) {
return 'Invalid JSON';
}
},
},
]);
const parsedAccountAssociation = JSON.parse(userAccountAssociation);
// Write APP_ACCOUNT_ASSOCIATION to constants.ts
if (fs.existsSync(constantsPath)) {
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
// Replace the APP_ACCOUNT_ASSOCIATION line
const newAccountAssociation = `export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = ${JSON.stringify(parsedAccountAssociation, null, 2)};`;
constantsContent = constantsContent.replace(
/^export const APP_ACCOUNT_ASSOCIATION\s*:\s*AccountAssociation \| undefined\s*=\s*[^;]*;/m,
newAccountAssociation,
);
fs.writeFileSync(constantsPath, constantsContent);
console.log('✅ APP_ACCOUNT_ASSOCIATION updated in constants.ts');
}
} catch (error) {
console.log('\n Skipping account association for now. You can add it later by updating APP_ACCOUNT_ASSOCIATION in src/lib/constants.ts');
}
}
@@ -879,54 +942,16 @@ async function deployToVercel(useGitHub = false): Promise<void> {
'\n📝 You can manage your project at https://vercel.com/dashboard',
);
// Prompt user to sign manifest in browser and paste accountAssociation
// Remind user about account association if not already set
console.log(
`\n⚠️ To complete your mini app manifest, you must sign it using the Farcaster developer portal.`,
`\n💡 Remember: If you haven't already signed your manifest, go to:`,
);
console.log(
'1. Go to: https://farcaster.xyz/~/developers/mini-apps/manifest?domain=' +
domain,
` https://farcaster.xyz/~/developers/mini-apps/manifest?domain=${domain}`,
);
console.log(
'2. Click "Transfer Ownership" and follow the instructions to sign the manifest.',
' to complete the ownership transfer and update APP_ACCOUNT_ASSOCIATION in src/lib/constants.ts',
);
console.log(
'3. Copy the resulting accountAssociation JSON from the browser.',
);
console.log('4. Paste it below when prompted.');
const { userAccountAssociation } = await inquirer.prompt([
{
type: 'editor',
name: 'userAccountAssociation',
message: 'Paste the accountAssociation JSON here:',
validate: (input: string) => {
try {
const parsed = JSON.parse(input);
if (parsed.header && parsed.payload && parsed.signature) {
return true;
}
return 'Invalid accountAssociation: must have header, payload, and signature';
} catch (e) {
return 'Invalid JSON';
}
},
},
]);
const parsedAccountAssociation = JSON.parse(userAccountAssociation);
// Write APP_ACCOUNT_ASSOCIATION to src/lib/constants.ts
const constantsPath = path.join(projectRoot, 'src', 'lib', 'constants.ts');
let constantsContent = fs.readFileSync(constantsPath, 'utf8');
// Replace the APP_ACCOUNT_ASSOCIATION line using a robust, anchored, multiline regex
const newAccountAssociation = `export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined = ${JSON.stringify(parsedAccountAssociation, null, 2)};`;
constantsContent = constantsContent.replace(
/^export const APP_ACCOUNT_ASSOCIATION\s*:\s*AccountAssociation \| undefined\s*=\s*[^;]*;/m,
newAccountAssociation,
);
fs.writeFileSync(constantsPath, constantsContent);
console.log('\n✅ APP_ACCOUNT_ASSOCIATION updated in src/lib/constants.ts');
} catch (error: unknown) {
if (error instanceof Error) {
console.error('\n❌ Deployment failed:', error.message);

View File

@@ -7,6 +7,7 @@ export async function GET() {
return NextResponse.json(config);
} catch (error) {
console.error('Error generating metadata:', error);
return NextResponse.json({ error: error.message }, { status: 500 });
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
return NextResponse.json({ error: errorMessage }, { status: 500 });
}
}

View File

@@ -56,7 +56,7 @@ export async function POST(request: NextRequest) {
// Only handle notifications if Neynar is not enabled
// When Neynar is enabled, notifications are handled through their webhook
switch (event.event) {
case "frame_added":
case "miniapp_added":
if (event.notificationDetails) {
await setUserNotificationDetails(fid, event.notificationDetails);
await sendMiniAppNotification({
@@ -69,7 +69,7 @@ export async function POST(request: NextRequest) {
}
break;
case "frame_removed":
case "miniapp_removed":
await deleteUserNotificationDetails(fid);
break;

View File

@@ -0,0 +1,29 @@
import type { Metadata } from 'next';
import { getSession } from '~/auth';
import '~/app/globals.css';
import { Providers } from '~/app/providers';
import { APP_NAME, APP_DESCRIPTION } from '~/lib/constants';
export const metadata: Metadata = {
title: APP_NAME,
description: APP_DESCRIPTION,
};
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const session = await getSession();
return (
<html lang="en">
<body>
<Providers session={session}>
{children}
</Providers>
</body>
</html>
);
}

View File

@@ -14,25 +14,10 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
// Only get session if sponsored signer is enabled or seed phrase is provided
const sponsorSigner = process.env.SPONSOR_SIGNER === 'true';
const hasSeedPhrase = !!process.env.SEED_PHRASE;
const shouldUseSession = sponsorSigner || hasSeedPhrase;
let session = null;
if (shouldUseSession) {
try {
const { getSession } = await import('~/auth');
session = await getSession();
} catch (error) {
console.warn('Failed to get session:', error);
}
}
return (
<html lang="en">
<body>
<Providers session={session} shouldUseSession={shouldUseSession}>
<Providers>
{children}
</Providers>
</body>

View File

@@ -0,0 +1,44 @@
'use client';
import dynamic from 'next/dynamic';
import type { Session } from 'next-auth';
import { SessionProvider } from 'next-auth/react';
import { AuthKitProvider } from '@farcaster/auth-kit';
import { MiniAppProvider } from '@neynar/react';
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
import { ANALYTICS_ENABLED, RETURN_URL } from '~/lib/constants';
const WagmiProvider = dynamic(
() => import('~/components/providers/WagmiProvider'),
{
ssr: false,
}
);
export function Providers({
session,
children,
}: {
session: Session | null;
children: React.ReactNode;
}) {
const solanaEndpoint =
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
return (
<SessionProvider session={session}>
<WagmiProvider>
<MiniAppProvider
analyticsEnabled={ANALYTICS_ENABLED}
backButtonEnabled={true}
returnUrl={RETURN_URL}
>
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
<AuthKitProvider config={{}}>
{children}
</AuthKitProvider>
</SafeFarcasterSolanaProvider>
</MiniAppProvider>
</WagmiProvider>
</SessionProvider>
);
}

View File

@@ -3,8 +3,7 @@
import dynamic from 'next/dynamic';
import { MiniAppProvider } from '@neynar/react';
import { SafeFarcasterSolanaProvider } from '~/components/providers/SafeFarcasterSolanaProvider';
import { ANALYTICS_ENABLED } from '~/lib/constants';
import React, { useState, useEffect } from 'react';
import { ANALYTICS_ENABLED, RETURN_URL } from '~/lib/constants';
const WagmiProvider = dynamic(
() => import('~/components/providers/WagmiProvider'),
@@ -13,117 +12,22 @@ const WagmiProvider = dynamic(
}
);
// Helper component to conditionally render auth providers
function AuthProviders({
children,
session,
shouldUseSession,
}: {
children: React.ReactNode;
session: any;
shouldUseSession: boolean;
}) {
const [authComponents, setAuthComponents] = useState<{
SessionProvider: React.ComponentType<any> | null;
AuthKitProvider: React.ComponentType<any> | null;
loaded: boolean;
}>({
SessionProvider: null,
AuthKitProvider: null,
loaded: false,
});
useEffect(() => {
if (!shouldUseSession) {
setAuthComponents({
SessionProvider: null,
AuthKitProvider: null,
loaded: true,
});
return;
}
const loadAuthComponents = async () => {
try {
// Dynamic imports for auth modules
let SessionProvider = null;
let AuthKitProvider = null;
try {
const nextAuth = await import('next-auth/react');
SessionProvider = nextAuth.SessionProvider;
} catch (error) {
console.warn('NextAuth not available:', error);
}
try {
const authKit = await import('@farcaster/auth-kit');
AuthKitProvider = authKit.AuthKitProvider;
} catch (error) {
console.warn('Farcaster AuthKit not available:', error);
}
setAuthComponents({
SessionProvider,
AuthKitProvider,
loaded: true,
});
} catch (error) {
console.error('Error loading auth components:', error);
setAuthComponents({
SessionProvider: null,
AuthKitProvider: null,
loaded: true,
});
}
};
loadAuthComponents();
}, [shouldUseSession]);
if (!authComponents.loaded) {
return <></>;
}
if (!shouldUseSession || !authComponents.SessionProvider) {
return <>{children}</>;
}
const { SessionProvider, AuthKitProvider } = authComponents;
if (AuthKitProvider) {
return (
<SessionProvider session={session}>
<AuthKitProvider config={{}}>{children}</AuthKitProvider>
</SessionProvider>
);
}
return <SessionProvider session={session}>{children}</SessionProvider>;
}
export function Providers({
session,
children,
shouldUseSession = false,
}: {
session: any | null;
children: React.ReactNode;
shouldUseSession?: boolean;
}) {
const solanaEndpoint =
process.env.SOLANA_RPC_ENDPOINT || 'https://solana-rpc.publicnode.com';
return (
<WagmiProvider>
<MiniAppProvider
analyticsEnabled={ANALYTICS_ENABLED}
backButtonEnabled={true}
returnUrl={RETURN_URL}
>
<SafeFarcasterSolanaProvider endpoint={solanaEndpoint}>
<AuthProviders session={session} shouldUseSession={shouldUseSession}>
{children}
</AuthProviders>
</SafeFarcasterSolanaProvider>
</MiniAppProvider>
</WagmiProvider>

View File

@@ -274,7 +274,7 @@ export const authOptions: AuthOptions = {
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
: process.env.VERCEL_URL
? `https://${process.env.VERCEL_URL}`
: `http://localhost:${process.env.PORT ?? 3000}`;
: process.env.NEXTAUTH_URL || `http://localhost:${process.env.PORT ?? 3000}`;
const domain = getDomainFromUrl(baseUrl);
@@ -339,26 +339,26 @@ export const authOptions: AuthOptions = {
name: `next-auth.session-token`,
options: {
httpOnly: true,
sameSite: 'none',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/',
secure: true,
secure: process.env.NODE_ENV === 'production',
},
},
callbackUrl: {
name: `next-auth.callback-url`,
options: {
sameSite: 'none',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/',
secure: true,
secure: process.env.NODE_ENV === 'production',
},
},
csrfToken: {
name: `next-auth.csrf-token`,
options: {
httpOnly: true,
sameSite: 'none',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
path: '/',
secure: true,
secure: process.env.NODE_ENV === 'production',
},
},
},

View File

@@ -14,7 +14,7 @@ import {
signOut as backendSignOut,
useSession,
} from 'next-auth/react';
import sdk, { SignIn as SignInCore } from '@farcaster/frame-sdk';
import sdk, { SignIn as SignInCore } from '@farcaster/miniapp-sdk';
type User = {
fid: number;
@@ -569,6 +569,8 @@ export function NeynarAuthButton() {
} else {
console.error('❌ Backend sign-in error:', e);
}
} finally {
setSignersLoading(false);
}
}, [nonce]);

View File

@@ -0,0 +1,208 @@
'use client';
import { useCallback, useState } from 'react';
import { useMiniApp } from '@neynar/react';
import { ShareButton } from '../Share';
import { Button } from '../Button';
import { SignIn } from '../wallet/SignIn';
import { type Haptics } from '@farcaster/miniapp-sdk';
import { APP_URL } from '~/lib/constants';
import { NeynarAuthButton } from '../NeynarAuthButton';
/**
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
*
* This component provides the main interaction interface for users to:
* - Share the mini app with others
* - Sign in with Farcaster
* - Send notifications to their account
* - Trigger haptic feedback
* - Add the mini app to their client
* - Copy share URLs
*
* The component uses the useMiniApp hook to access Farcaster context and actions.
* All state is managed locally within this component.
*
* @example
* ```tsx
* <ActionsTab />
* ```
*/
export function ActionsTab() {
// --- Hooks ---
const { actions, added, notificationDetails, haptics, context } =
useMiniApp();
// --- State ---
const [notificationState, setNotificationState] = useState({
sendStatus: '',
shareUrlCopied: false,
});
const [selectedHapticIntensity, setSelectedHapticIntensity] =
useState<Haptics.ImpactOccurredType>('medium');
// --- Handlers ---
/**
* Sends a notification to the current user's Farcaster account.
*
* This function makes a POST request to the /api/send-notification endpoint
* with the user's FID and notification details. It handles different response
* statuses including success (200), rate limiting (429), and errors.
*
* @returns Promise that resolves when the notification is sent or fails
*/
const sendFarcasterNotification = useCallback(async () => {
setNotificationState((prev) => ({ ...prev, sendStatus: '' }));
if (!notificationDetails || !context) {
return;
}
try {
const response = await fetch('/api/send-notification', {
method: 'POST',
mode: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fid: context.user.fid,
notificationDetails,
}),
});
if (response.status === 200) {
setNotificationState((prev) => ({ ...prev, sendStatus: 'Success' }));
return;
} else if (response.status === 429) {
setNotificationState((prev) => ({
...prev,
sendStatus: 'Rate limited',
}));
return;
}
const responseText = await response.text();
setNotificationState((prev) => ({
...prev,
sendStatus: `Error: ${responseText}`,
}));
} catch (error) {
setNotificationState((prev) => ({
...prev,
sendStatus: `Error: ${error}`,
}));
}
}, [context, notificationDetails]);
/**
* Copies the share URL for the current user to the clipboard.
*
* This function generates a share URL using the user's FID and copies it
* to the clipboard. It shows a temporary "Copied!" message for 2 seconds.
*/
const copyUserShareUrl = useCallback(async () => {
if (context?.user?.fid) {
const userShareUrl = `${APP_URL}/share/${context.user.fid}`;
await navigator.clipboard.writeText(userShareUrl);
setNotificationState((prev) => ({ ...prev, shareUrlCopied: true }));
setTimeout(
() =>
setNotificationState((prev) => ({ ...prev, shareUrlCopied: false })),
2000
);
}
}, [context?.user?.fid]);
/**
* Triggers haptic feedback with the selected intensity.
*
* This function calls the haptics.impactOccurred method with the current
* selectedHapticIntensity setting. It handles errors gracefully by logging them.
*/
const triggerHapticFeedback = useCallback(async () => {
try {
await haptics.impactOccurred(selectedHapticIntensity);
} catch (error) {
console.error('Haptic feedback failed:', error);
}
}, [haptics, selectedHapticIntensity]);
// --- Render ---
return (
<div className="space-y-3 px-6 w-full max-w-md mx-auto">
{/* Share functionality */}
<ShareButton
buttonText="Share Mini App"
cast={{
text: 'Check out this awesome frame @1 @2 @3! 🚀🪐',
bestFriends: true,
embeds: [`${APP_URL}/share/${context?.user?.fid || ''}`],
}}
className="w-full"
/>
{/* Authentication */}
<SignIn />
{/* Neynar Authentication */}
<NeynarAuthButton />
{/* Mini app actions */}
<Button
onClick={() =>
actions.openUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
}
className="w-full"
>
Open Link
</Button>
<Button onClick={actions.addMiniApp} disabled={added} className="w-full">
Add Mini App to Client
</Button>
{/* Notification functionality */}
{notificationState.sendStatus && (
<div className="text-sm w-full">
Send notification result: {notificationState.sendStatus}
</div>
)}
<Button
onClick={sendFarcasterNotification}
disabled={!notificationDetails}
className="w-full"
>
Send notification
</Button>
{/* Share URL copying */}
<Button
onClick={copyUserShareUrl}
disabled={!context?.user?.fid}
className="w-full"
>
{notificationState.shareUrlCopied ? 'Copied!' : 'Copy share URL'}
</Button>
{/* Haptic feedback controls */}
<div className="space-y-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300">
Haptic Intensity
</label>
<select
value={selectedHapticIntensity}
onChange={(e) =>
setSelectedHapticIntensity(
e.target.value as Haptics.ImpactOccurredType
)
}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value={'light'}>Light</option>
<option value={'medium'}>Medium</option>
<option value={'heavy'}>Heavy</option>
<option value={'soft'}>Soft</option>
<option value={'rigid'}>Rigid</option>
</select>
<Button onClick={triggerHapticFeedback} className="w-full">
Trigger Haptic Feedback
</Button>
</div>
</div>
);
}

View File

@@ -1,6 +1,5 @@
'use client';
import dynamic from 'next/dynamic';
import { useCallback, useState } from 'react';
import { useMiniApp } from '@neynar/react';
import { ShareButton } from '../Share';
@@ -9,15 +8,6 @@ import { SignIn } from '../wallet/SignIn';
import { type Haptics } from '@farcaster/miniapp-sdk';
import { APP_URL } from '~/lib/constants';
// Import NeynarAuthButton
const NeynarAuthButton = dynamic(
() =>
import('../NeynarAuthButton').then((module) => ({
default: module.NeynarAuthButton,
})),
{ ssr: false }
);
/**
* ActionsTab component handles mini app actions like sharing, notifications, and haptic feedback.
*
@@ -148,9 +138,6 @@ export function ActionsTab() {
{/* Authentication */}
<SignIn />
{/* Neynar Authentication */}
{NeynarAuthButton && <NeynarAuthButton />}
{/* Mini app actions */}
<Button
onClick={() =>

View File

@@ -80,7 +80,7 @@ export const APP_ACCOUNT_ASSOCIATION: AccountAssociation | undefined =
* Text displayed on the main action button.
* Used for the primary call-to-action in the mini app.
*/
export const APP_BUTTON_TEXT = 'Launch Mini App';
export const APP_BUTTON_TEXT: string = 'Launch Mini App';
// --- Integration Configuration ---
/**
@@ -102,7 +102,7 @@ export const APP_WEBHOOK_URL: string =
* When false, wallet functionality is completely hidden from the UI.
* Useful for mini apps that don't require wallet integration.
*/
export const USE_WALLET = false;
export const USE_WALLET: boolean = false;
/**
* Flag to enable/disable analytics tracking.
@@ -111,7 +111,7 @@ export const USE_WALLET = false;
* When false, analytics collection is disabled.
* Useful for privacy-conscious users or development environments.
*/
export const ANALYTICS_ENABLED = true;
export const ANALYTICS_ENABLED: boolean = true;
/**
* Required chains for the mini app.
@@ -125,6 +125,14 @@ export const ANALYTICS_ENABLED = true;
*/
export const APP_REQUIRED_CHAINS: string[] = [];
/**
* Return URL for the mini app.
*
* If provided, the mini app will be rendered with a return URL to be rendered if the
* back button is pressed from the home page.
*/
export const RETURN_URL: string | undefined = undefined;
// PLEASE DO NOT UPDATE THIS
export const SIGNED_KEY_REQUEST_VALIDATOR_EIP_712_DOMAIN = {
name: 'Farcaster SignedKeyRequestValidator',