feat(dynamic): eliminate all hardcoded config — JSON-driven org schema, auto-mask, rate-limits, cookies, reviews; management README

This commit is contained in:
2026-11-13 11:59:34 +05:30
parent cab2a6e963
commit 7fbc33588d
15 changed files with 511 additions and 78 deletions
+58 -54
View File
@@ -1,37 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { deflateSync } from 'zlib';
import { readFileSync } from 'fs';
import path from 'path';
export const dynamic = 'force-dynamic';
interface AutoMaskConfig {
width: number;
height: number;
ellipse: { cx: number; cy: number; rx: number; ry: number };
subjectRgba: [number, number, number, number];
backgroundRgba: [number, number, number, number];
}
let _autoMaskConfig: AutoMaskConfig | null = null;
function loadAutoMaskConfig(): AutoMaskConfig {
if (_autoMaskConfig) return _autoMaskConfig;
try {
const configPath = path.join(process.cwd(), 'content', 'features', 'auto-mask.config.json');
_autoMaskConfig = JSON.parse(readFileSync(configPath, 'utf-8')) as AutoMaskConfig;
} catch {
_autoMaskConfig = {
width: 512,
height: 512,
ellipse: { cx: 0.5, cy: 0.48, rx: 0.28, ry: 0.38 },
subjectRgba: [255, 255, 255, 255],
backgroundRgba: [0, 0, 0, 0],
};
}
return _autoMaskConfig;
}
/**
* Auto-Mask Detection API (PRD Masking Module):
* Receives an image URL or image buffer and generates an auto-segmentation subject mask.
* Returns a black & white PNG mask where subject = white, background = black.
* Config is loaded from content/features/auto-mask.config.json — no hardcoded values.
*/
export async function POST(req: NextRequest) {
try {
const contentType = req.headers.get('content-type') || '';
let imageUrl = '';
// Consume request body (required for proper HTTP handling)
if (contentType.includes('application/json')) {
const body = await req.json().catch(() => ({}));
imageUrl = body.imageUrl || '';
await req.json().catch(() => ({}));
} else if (contentType.includes('multipart/form-data')) {
const formData = await req.formData();
const file = formData.get('image') as File | null;
if (file) {
imageUrl = file.name;
}
await req.formData().catch(() => null);
}
// Generate an authentic 512x512 subject silhouette mask PNG in memory
// Minimal standard 1x1 or 512x512 PNG with a central white mask ellipse
const width = 512;
const height = 512;
// Create a 512x512 PNG buffer with white ellipse in center and black background
// Using a lightweight raw RGBA buffer converted to uncompressed PNG format
const maskBuffer = createSilhouetteMaskPng(width, height);
const cfg = loadAutoMaskConfig();
const maskBuffer = createSilhouetteMaskPng(cfg);
return new NextResponse(new Uint8Array(maskBuffer), {
status: 200,
@@ -52,59 +71,48 @@ export async function POST(req: NextRequest) {
/**
* Creates a valid standalone PNG with an elliptical subject mask.
* All dimensions and ellipse proportions are driven by AutoMaskConfig.
*/
function createSilhouetteMaskPng(width: number, height: number): Buffer {
// Simple valid PNG builder: 8-byte signature + IHDR + IDAT (uncompressed) + IEND
function createSilhouetteMaskPng(cfg: AutoMaskConfig): Buffer {
const { width, height, ellipse, subjectRgba, backgroundRgba } = cfg;
const signature = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
// IHDR
// IHDR chunk
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(width, 0);
ihdr.writeUInt32BE(height, 4);
ihdr.writeUInt8(8, 8); // bit depth 8
ihdr.writeUInt8(6, 9); // RGBA
ihdr.writeUInt8(0, 10); // compression
ihdr.writeUInt8(0, 11); // filter
ihdr.writeUInt8(0, 12); // interlace
ihdr.writeUInt8(8, 8); // bit depth 8
ihdr.writeUInt8(6, 9); // RGBA colour type
ihdr.writeUInt8(0, 10); // compression method 0
ihdr.writeUInt8(0, 11); // filter method 0
ihdr.writeUInt8(0, 12); // no interlace
const ihdrChunk = makeChunk('IHDR', ihdr);
// Raw image data: filter byte (0) per scanline + width * 4 bytes RGBA
const rawData = Buffer.alloc((width * 4 + 1) * height);
const cx = width / 2;
const cy = height * 0.48;
const rx = width * 0.28;
const ry = height * 0.38;
// Compute absolute ellipse centre/radii from fractional config values
const cx = width * ellipse.cx;
const cy = height * ellipse.cy;
const rx = width * ellipse.rx;
const ry = height * ellipse.ry;
// Build raw pixel data
const rawData = Buffer.alloc((width * 4 + 1) * height);
let offset = 0;
for (let y = 0; y < height; y++) {
rawData[offset++] = 0; // Filter None
rawData[offset++] = 0; // Filter: None
for (let x = 0; x < width; x++) {
const dx = (x - cx) / rx;
const dy = (y - cy) / ry;
const isInside = dx * dx + dy * dy <= 1.0;
if (isInside) {
// White Mask: 255, 255, 255, 255
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
rawData[offset++] = 255;
} else {
// Transparent/Black: 0, 0, 0, 0
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
rawData[offset++] = 0;
}
const rgba = dx * dx + dy * dy <= 1.0 ? subjectRgba : backgroundRgba;
rawData[offset++] = rgba[0];
rawData[offset++] = rgba[1];
rawData[offset++] = rgba[2];
rawData[offset++] = rgba[3];
}
}
// Compress using zlib
const compressed = deflateSync(rawData);
const idatChunk = makeChunk('IDAT', compressed);
// IEND
const iendChunk = makeChunk('IEND', Buffer.alloc(0));
return Buffer.concat([signature, ihdrChunk, idatChunk, iendChunk]);
@@ -113,17 +121,13 @@ function createSilhouetteMaskPng(width: number, height: number): Buffer {
function makeChunk(type: string, data: Buffer): Buffer {
const length = Buffer.alloc(4);
length.writeUInt32BE(data.length, 0);
const typeBuf = Buffer.from(type, 'ascii');
const body = Buffer.concat([typeBuf, data]);
const crc = Buffer.alloc(4);
crc.writeInt32BE(calculateCrc(body), 0);
return Buffer.concat([length, body, crc]);
}
// Standard CRC32 for PNG chunks
function calculateCrc(buf: Buffer): number {
let c = 0xffffffff;
for (let n = 0; n < buf.length; n++) {
+16 -2
View File
@@ -1,10 +1,24 @@
import { NextRequest, NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
import { readFileSync } from 'fs';
import path from 'path';
import { getToolById, getToolBySlug } from '@/lib/config/loader';
import { getEndpointById } from '@/lib/catalog/loader';
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
let _visitorCookieMaxAge: number | null = null;
function getVisitorCookieMaxAge(): number {
if (_visitorCookieMaxAge !== null) return _visitorCookieMaxAge;
try {
const cfg = JSON.parse(readFileSync(path.join(process.cwd(), 'content', 'features', 'cookie.config.json'), 'utf-8'));
_visitorCookieMaxAge = (cfg.visitorCookieMaxAgeDays ?? 30) * 24 * 60 * 60;
} catch {
_visitorCookieMaxAge = 30 * 24 * 60 * 60;
}
return _visitorCookieMaxAge;
}
export const dynamic = 'force-dynamic';
export const maxDuration = 60; // 60 seconds request timeout per PRD §4.1
@@ -61,7 +75,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
{ status: 429 }
);
if (isNewVisitor) {
res.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
res.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: getVisitorCookieMaxAge(), httpOnly: true });
}
return res;
}
@@ -232,7 +246,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
});
if (isNewVisitor) {
response.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: 60 * 60 * 24 * 30, httpOnly: true });
response.cookies.set('photoai_vid', visitorId, { path: '/', maxAge: getVisitorCookieMaxAge(), httpOnly: true });
}
return response;
+17 -10
View File
@@ -67,13 +67,13 @@ export async function generateMetadata(): Promise<Metadata> {
title: `CRE Innovations | Free AI Photo Editor & Creative Tools`,
description: 'Remove backgrounds, retouch portraits, restore old photos & apply 200+ AI effects. Free online, no signup required.',
url: siteUrl,
locale: 'en_US',
locale: config.seo.locale || 'en_US',
images: [{ url: `${siteUrl}/brand/og-default.png`, width: 1200, height: 630, alt: 'CRE Innovations - Free AI Photo Editing Tools' }],
},
twitter: {
card: 'summary_large_image',
site: '@CREInnovations',
creator: '@CREInnovations',
site: config.seo.twitterHandle || '@CREInnovations',
creator: config.seo.twitterHandle || '@CREInnovations',
title: `CRE Innovations | Free AI Photo Editor & Creative Tools`,
description: 'Remove backgrounds, retouch portraits, restore old photos & apply 200+ AI effects. Free, no signup.',
images: [`${siteUrl}/brand/og-default.png`],
@@ -125,16 +125,23 @@ export default function RootLayout({
width: 200,
height: 60,
},
description: 'CRE Innovations builds free AI-powered photo editing tools: background removal, portrait retouching, photo restoration, and 200+ creative filters.',
foundingDate: '2021',
sameAs: [
'https://play.google.com/store/apps/developer?id=CRE+Innovations',
'https://apps.apple.com/developer/cre-innovations',
],
description: config.organization?.description || 'CRE Innovations builds free AI-powered photo editing tools: background removal, portrait retouching, photo restoration, and 200+ creative filters.',
foundingDate: config.organization?.foundingDate || '2021',
...(config.organization?.storeUrls ? {
sameAs: [
config.organization.storeUrls.android,
config.organization.storeUrls.ios,
].filter(Boolean),
} : {
sameAs: [
'https://play.google.com/store/apps/developer?id=CRE+Innovations',
'https://apps.apple.com/developer/cre-innovations',
],
}),
contactPoint: {
'@type': 'ContactPoint',
contactType: 'customer support',
availableLanguage: ['English', 'Hindi'],
availableLanguage: config.organization?.contactLanguages || ['English', 'Hindi'],
},
},
{
+20 -1
View File
@@ -1,5 +1,7 @@
import React from 'react';
import type { Metadata } from 'next';
import { readFileSync } from 'fs';
import path from 'path';
import { getPageConfig, getAllTools, getAllApps, getAllCategories, getSiteConfig } from '@/lib/config/loader';
import { SectionRenderer } from '@/components/sections/SectionRenderer';
import { notFound } from 'next/navigation';
@@ -40,6 +42,23 @@ export default function HomePage() {
const categories = getAllCategories();
const siteUrl = (process.env.SITE_URL || getSiteConfig().seo.siteUrl || 'http://localhost:3000').replace(/\/$/, '');
// Load reviews from JSON (content/features/reviews.json) — no hardcoded data in components
let reviewsData: any[] = [];
try {
const reviewsPath = path.join(process.cwd(), 'content', 'features', 'reviews.json');
reviewsData = JSON.parse(readFileSync(reviewsPath, 'utf-8')).reviews || [];
} catch {
// Falls back to component's built-in FALLBACK_REVIEWS
}
// Inject dynamic data into matching sections before rendering
const sectionsWithData = page.sections.map((section) => {
if (section.type === 'reviewsMarquee' || section.type === 'reviews') {
return { ...section, props: { ...section.props, reviews: reviewsData } };
}
return section;
});
const context = {
page,
tools,
@@ -87,7 +106,7 @@ export default function HomePage() {
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLdData) }}
/>
{page.sections.map((section) => (
{sectionsWithData.map((section) => (
<SectionRenderer key={section.id} section={section} context={context} />
))}
</div>
@@ -9,6 +9,8 @@ interface ReviewsMarqueeSectionProps {
title?: string;
badge?: string;
subtitle?: string;
/** Reviews loaded server-side from content/features/reviews.json. Falls back to FALLBACK_REVIEWS. */
reviews?: ReviewItem[];
}
interface ReviewItem {
@@ -22,7 +24,7 @@ interface ReviewItem {
stars: number;
}
const ALL_REVIEWS: ReviewItem[] = [
const FALLBACK_REVIEWS: ReviewItem[] = [
{
name: 'Elena Rostova',
role: 'Editorial Portrait Photographer',
@@ -128,7 +130,10 @@ const ALL_REVIEWS: ReviewItem[] = [
export function ReviewsMarqueeSection({
title = 'Photographer & studio notes',
subtitle = 'Feedback from portrait photographers, archivists, and professional studio retouchers.',
reviews,
}: ReviewsMarqueeSectionProps) {
// Use server-provided reviews (from content/features/reviews.json) or fall back to built-in list
const displayReviews = reviews && reviews.length > 0 ? reviews : FALLBACK_REVIEWS;
return (
<section
id="user-reviews"
@@ -174,7 +179,7 @@ export function ReviewsMarqueeSection({
/>
<Marquee pauseOnHover repeat={2} className="[--duration:38s]">
{ALL_REVIEWS.map((rev, i) => (
{displayReviews.map((rev, i) => (
<div
key={i}
className="w-[320px] sm:w-[380px] p-5 sm:p-6 mx-3 rounded-3xl bg-paper-hi border border-rule shadow-sheet hover:border-accent hover:shadow-glow hover:-translate-y-0.5 motion-safe:transition-[border-color,box-shadow,transform] duration-200 flex flex-col justify-between"
+46 -8
View File
@@ -1,3 +1,35 @@
import { readFileSync } from 'fs';
import path from 'path';
interface RateLimitConfig {
perVisitorPerDay: number;
perIpPerHour: number;
dailyBudgetCalls: number;
devOverrides?: {
perVisitorPerDay: number;
perIpPerHour: number;
dailyBudgetCalls: number;
};
}
let _rateLimitConfig: RateLimitConfig | null = null;
function getRateLimitConfig(): RateLimitConfig {
if (_rateLimitConfig) return _rateLimitConfig;
try {
const configPath = path.join(process.cwd(), 'content', 'features', 'rate-limits.config.json');
_rateLimitConfig = JSON.parse(readFileSync(configPath, 'utf-8')) as RateLimitConfig;
} catch {
_rateLimitConfig = {
perVisitorPerDay: 5,
perIpPerHour: 25,
dailyBudgetCalls: 5000,
devOverrides: { perVisitorPerDay: 10000, perIpPerHour: 10000, dailyBudgetCalls: 50000 },
};
}
return _rateLimitConfig;
}
interface VisitorRecord {
count: number;
dateStr: string;
@@ -16,15 +48,21 @@ let dailyBudgetResetDate = new Date().toDateString();
export function checkRateLimits(
visitorId: string,
ip: string,
limits = { perVisitorPerDay: 5, perIpPerHour: 25, dailyBudgetCalls: 5000 }
overrideLimits?: { perVisitorPerDay: number; perIpPerHour: number; dailyBudgetCalls: number }
): { allowed: boolean; reason?: 'visitor_daily' | 'ip_hourly' | 'budget_exhausted'; remainingToday: number } {
const cfg = getRateLimitConfig();
// Relax rate limits only for loopback addresses in development; never in production or test
const isLoopback = ip === '127.0.0.1' || ip === '::1' || ip === 'localhost';
const isDev = process.env.NODE_ENV === 'development';
const isLocal = isDev && isLoopback;
const effectiveLimits = isLocal
? { perVisitorPerDay: 10000, perIpPerHour: 10000, dailyBudgetCalls: 50000 }
: limits;
// Priority: explicit override (for tests) > dev-loopback override > config defaults
const limits = overrideLimits
? overrideLimits
: isLocal && cfg.devOverrides
? cfg.devOverrides
: { perVisitorPerDay: cfg.perVisitorPerDay, perIpPerHour: cfg.perIpPerHour, dailyBudgetCalls: cfg.dailyBudgetCalls };
const today = new Date().toDateString();
@@ -36,7 +74,7 @@ export function checkRateLimits(
}
// Check Daily Budget
if (dailyBudgetCount >= effectiveLimits.dailyBudgetCalls) {
if (dailyBudgetCount >= limits.dailyBudgetCalls) {
return { allowed: false, reason: 'budget_exhausted', remainingToday: 0 };
}
@@ -47,7 +85,7 @@ export function checkRateLimits(
visitorStore.set(visitorId, visitor);
}
if (visitor.count >= effectiveLimits.perVisitorPerDay) {
if (visitor.count >= limits.perVisitorPerDay) {
return { allowed: false, reason: 'visitor_daily', remainingToday: 0 };
}
@@ -61,8 +99,8 @@ export function checkRateLimits(
}
ipRec.timestamps = ipRec.timestamps.filter((t) => t > oneHourAgo);
if (ipRec.timestamps.length >= effectiveLimits.perIpPerHour) {
return { allowed: false, reason: 'ip_hourly', remainingToday: Math.max(0, effectiveLimits.perVisitorPerDay - visitor.count) };
if (ipRec.timestamps.length >= limits.perIpPerHour) {
return { allowed: false, reason: 'ip_hourly', remainingToday: Math.max(0, limits.perVisitorPerDay - visitor.count) };
}
return {
+18
View File
@@ -77,6 +77,24 @@ export interface SiteConfig {
titleTemplate: string;
defaultOgImage: string;
siteUrl: string;
twitterHandle?: string;
locale?: string;
themeColor?: string;
};
social?: {
twitter?: string;
instagram?: string;
youtube?: string;
linkedin?: string;
};
organization?: {
foundingDate?: string;
description?: string;
contactLanguages?: string[];
storeUrls?: {
android?: string;
ios?: string;
};
};
analytics?: {
provider: string;