Loading...
Loading...
Expert in integrating third-party APIs with proper authentication, error handling, rate limiting, and retry logic. Specializes in Auth.js v5, GPT-5 model orchestration, Stripe SDK v13+, and architectural context packing for large codebases. Optimized for 2026 standards with Edge-first performance and autonomous agent integration.
npx skill4agent add yuniorglez/gemini-elite-core api-proAUTH_AUTH_# .env.local
AUTH_SECRET=your_signing_secret_here # REQUIRED: Used for JWT signing
AUTH_URL=https://myapp.com/api/auth # Base URL for the auth system
AUTH_GOOGLE_ID=google_client_id # Provider specific
AUTH_GOOGLE_SECRET=google_client_secret
AUTH_GITHUB_ID=github_client_id
AUTH_GITHUB_SECRET=github_client_secret// auth.ts
import NextAuth from "next-auth"
import Google from "next-auth/providers/google"
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [Google],
// 2026 Best Practice: Use JWT strategy for stateless, Edge-compatible sessions
session: { strategy: "jwt" },
pages: {
signIn: "/auth/signin",
error: "/auth/error",
},
callbacks: {
async jwt({ token, user, account }) {
// Persist the OAuth access_token to the token right after signin
if (account && user) {
token.accessToken = account.access_token;
token.id = user.id;
}
return token;
},
async session({ session, token }) {
// Send properties to the client, like an access_token from a provider.
session.accessToken = token.accessToken as string;
session.user.id = token.id as string;
return session;
},
// The authorized callback is used to verify if the request is authorized via Next.js Middleware.
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user
const isApiRoute = nextUrl.pathname.startsWith("/api")
const isPublicPath = nextUrl.pathname === "/public"
if (isApiRoute && !isLoggedIn) return false
if (isPublicPath) return true
return isLoggedIn
},
},
})middleware.tsimport { generateText } from "ai"
import { gpt5 } from "@ai-sdk/openai"
/**
* Executes a complex task using GPT-5 Reasoning.
* reasoningTokens: Specifies the intensity of the "thought" process.
*/
async function executeAutonomousTask(goal: string) {
// 1. Planning with GPT-5 Reasoning
const plan = await generateText({
model: gpt5("gpt-5-reasoning"),
system: "You are a master architect. Plan the solution step-by-step.",
prompt: goal,
// Higher maxTokens for the "thought" process (RT - Reasoning Tokens)
maxTokens: 8000
})
console.log("GPT-5 Thought Process Completed. Executing Plan...");
// 2. Execution with specialised sub-agents
const result = await processPlanSteps(plan.text)
return result
}import { o3 } from "@ai-sdk/research"
/**
* Conducts iterative deep research on a codebase or technical topic.
*/
const researchAgent = async (topic: string) => {
const deepResearch = await o3.conductResearch({
query: topic,
maxDepth: 10,
allowedTools: ["search", "arxiv", "github", "file_reader"],
autonomousMode: true,
// Reporting interval for progress updates
onProgress: (update) => {
console.log(`[Research Progress]: ${update.message}`);
}
})
return deepResearch.summary
}import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2025-10-14', // Ensure 2026 compatibility
});
async function cleanupStaleSubscriptions() {
// list() returns an auto-paging iterable
const subscriptions = stripe.subscriptions.list({
status: 'past_due',
limit: 100, // Still use limit for request chunking
});
// Native async iterator handles cursors automatically
for await (const sub of subscriptions) {
console.log(`Processing sub: ${sub.id}`);
// Check if sub is older than 30 days
const thirtyDaysAgo = Math.floor(Date.now() / 1000) - (30 * 24 * 60 * 60);
if (sub.created < thirtyDaysAgo) {
console.log(`Cancelling sub: ${sub.id} for customer ${sub.customer}`);
await stripe.subscriptions.cancel(sub.id);
}
}
}/**
* Retrieve a payment intent with full customer and payment method details.
* The SDK automatically types the expanded fields.
*/
const paymentIntent = await stripe.paymentIntents.retrieve('pi_123', {
expand: ['customer', 'payment_method'],
});
// Accessing expanded data safely with type narrowing
if (paymentIntent.customer && typeof paymentIntent.customer !== 'string') {
console.log(`Customer Email: ${paymentIntent.customer.email}`);
}package.json{
"name": "squaads-monorepo",
"workspaces": [
"apps/*",
"packages/*",
"skills/*",
"agents/*"
],
"scripts": {
"dev": "bun --filter \"*\" dev",
"test": "bun test --recursive",
"build": "bun x tsc --noEmit && bun run build:all"
}
}# Ensure no phantom dependencies
pnpm install --frozen-lockfile
# Run a command in all packages
pnpm -r exec bun run lint# Generate context for GPT-5 or o3 models
# This includes all logic while excluding noise
bun x repomix --include "src/**/*.ts,lib/**/*.ts,package.json" \
--exclude "node_modules,dist,.next,tests" \
--output codebase-summary.md// scripts/generate-index.ts
import { glob } from "bun";
/**
* Generates a lightweight index of all functions and classes.
* This file is what the agent reads first to "know where to look".
*/
async function generateIndex() {
const files = glob.scan("src/**/*.ts");
const index = [];
for await (const file of files) {
const content = await Bun.file(file).text();
const matches = content.matchAll(/(export (class|function|interface) (\w+))/g);
for (const match of matches) {
index.push({ symbol: match[3], type: match[2], path: file });
}
}
await Bun.write("CODEBASE_INDEX.json", JSON.stringify(index, null, 2));
}import { CircuitBreaker } from 'opossum';
/**
* Standard API Fetcher with integrated Resilience.
*/
const apiCall = async (endpoint: string) => {
const response = await fetch(endpoint, {
signal: AbortSignal.timeout(5000) // Hard 5s timeout
});
if (!response.ok) {
if (response.status === 429) throw new Error('RATE_LIMITED');
throw new Error(`API_ERROR_${response.status}`);
}
return response.json();
};
const breaker = new CircuitBreaker(apiCall, {
timeout: 6000,
errorThresholdPercentage: 50, // Open circuit if 50% calls fail
resetTimeout: 30000, // Wait 30s before trying again
capacity: 10 // Max 10 concurrent requests
});
breaker.on('open', () => console.error('!!! CIRCUIT BREAKER OPEN - FAILING FAST !!!'));
breaker.fallback(() => ({ status: 'unavailable', cached: true, data: [] }));
async function fetchWithResilience(url: string) {
try {
return await breaker.fire(url);
} catch (err) {
console.log("Handled Error via Circuit Breaker Fallback");
return breaker.fallback();
}
}crypto.subtle/**
* Verifies a webhook signature using Web Crypto API.
* Optimized for Vercel Edge / Cloudflare Workers.
*/
async function verifySignature(payload: string, signature: string, secret: string) {
const encoder = new TextEncoder();
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify']
);
const verified = await crypto.subtle.verify(
'HMAC',
key,
hexToBytes(signature),
encoder.encode(payload)
);
return verified;
}
function hexToBytes(hex: string) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return bytes;
}// Use separate client instances for different API services
const billingClient = new APIClient({ timeout: 2000, maxConnections: 5 });
const searchClient = new APIClient({ timeout: 10000, maxConnections: 20 });
// If searchClient hangs, billingClient remains responsive.grep# Find all occurrences of AUTH_SECRET in the src directory
git grep "AUTH_SECRET" -- src/
# Find where a specific function is used across the whole repo
git grep -w "calculateTotal"# patterns.txt
dangerouslySetInnerHTML
process.env.SECRET
eval\(
# Run search
grep -f patterns.txt -r ./src/**
* Orchestrator: Uses GPT-5 for Planning and o3 for execution.
*/
class AgentOrchestrator {
async runMission(task: string) {
// 1. Plan with GPT-5 (Reasoning)
const plan = await gpt5.generatePlan(task);
// 2. Execute Research steps with o3
for (const step of plan.researchSteps) {
const data = await o3.deepResearch(step.query);
this.updateKnowledge(data);
}
// 3. Final synthesis with GPT-5
return gpt5.synthesize(this.knowledgeBase);
}
}AUTH_anyzodhttpfetchuser_id: 123X-RateLimit-Remainingfs.readFileSynccodebase-context.md.gitignore| File | Description |
|---|---|
| Deep dive into Auth.js v5 and Edge integration. |
| GPT-5 family and o3-deep-research agentic patterns. |
| Stripe SDK v13+ features (auto-pagination, etc.). |
| Repomix context packing and large codebase indexing. |
| Advanced retry strategies and circuit breakers. |
| Patterns for Next.js 16 Server Components & Actions. |
AUTH_URLAUTH_URL=${VERCEL_URL}AUTH_SECRETzodimport { z } from 'zod';
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.string().email(),
tier: z.enum(['free', 'pro', 'enterprise']),
});
type User = z.infer<typeof UserSchema>;
/**
* Standard API Client with Validation and Logging.
*/
export class SecureAPIClient {
private baseURL: string;
private apiKey: string;
constructor() {
this.baseURL = process.env.API_BASE_URL!;
this.apiKey = process.env.API_SECRET_KEY!;
if (!this.apiKey) throw new Error("CRITICAL: API_SECRET_KEY is missing");
}
private async request<T>(endpoint: string, schema: z.ZodSchema<T>, options: RequestInit = {}): Promise<T> {
const startTime = Date.now();
const response = await fetch(`${this.baseURL}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'X-Client-Version': '2026.1.0',
...options.headers,
},
});
const duration = Date.now() - startTime;
console.log(`[API] ${options.method || 'GET'} ${endpoint} - ${response.status} (${duration}ms)`);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(`API Request Failed: ${response.status} - ${JSON.stringify(errorData)}`);
}
const data = await response.json();
// Validate at the boundary - 2026 Mandatory Rule
const result = schema.safeParse(data);
if (!result.success) {
console.error("[SCHEMA_VALIDATION_ERROR]", result.error);
throw new Error("API returned invalid data format");
}
return result.data;
}
async getUser(id: string): Promise<User> {
return this.request(`/users/${id}`, UserSchema);
}
}| Category | Requirement | Done? |
|---|---|---|
| Security | Auth.js v5 implemented with | [ ] |
| Security | Webhook signatures verified using | [ ] |
| Resilience | Circuit Breakers active for all 3rd party SDKs? | [ ] |
| Performance | API routes marked as | [ ] |
| Observability | Request/Response duration logged with Correlation IDs? | [ ] |
| AI Readiness | Repomix config updated to exclude | [ ] |
| Types | Zod schemas exist for every API entry/exit point? | [ ] |
| Financial | Stripe auto-pagination used for all bulk syncs? | [ ] |
auth-next.md