feat: add data privacy settings screen and initialize backend service infrastructure
This commit is contained in:
176
server/index.js
176
server/index.js
@@ -1,9 +1,8 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const dotenv = require('dotenv');
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const Stripe = require('stripe');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const dotenv = require('dotenv');
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
|
||||
const loadEnvFiles = (filePaths) => {
|
||||
const mergedFileEnv = {};
|
||||
@@ -50,41 +49,19 @@ const {
|
||||
syncRevenueCatWebhookEvent,
|
||||
storeEndpointResponse,
|
||||
} = require('./lib/billing');
|
||||
const {
|
||||
analyzePlantHealth,
|
||||
getHealthModel,
|
||||
getScanModel,
|
||||
identifyPlant,
|
||||
const {
|
||||
analyzePlantHealth,
|
||||
getHealthModel,
|
||||
getScanModel,
|
||||
identifyPlant,
|
||||
isConfigured: isOpenAiConfigured,
|
||||
} = require('./lib/openai');
|
||||
const { applyCatalogGrounding, normalizeText } = require('./lib/scanGrounding');
|
||||
const { ensureStorageBucket, uploadImage, isStorageConfigured } = require('./lib/storage');
|
||||
} = require('./lib/openai');
|
||||
const { applyCatalogGrounding, normalizeText } = require('./lib/scanGrounding');
|
||||
const { ensureStorageBucketWithRetry, uploadImage, isStorageConfigured } = require('./lib/storage');
|
||||
|
||||
const app = express();
|
||||
const port = Number(process.env.PORT || 3000);
|
||||
const plantsPublicDir = path.join(__dirname, 'public', 'plants');
|
||||
const stripeSecretKey = (process.env.STRIPE_SECRET_KEY || '').trim();
|
||||
if (!stripeSecretKey) {
|
||||
console.error('STRIPE_SECRET_KEY is not set. Payment endpoints will fail.');
|
||||
}
|
||||
const stripe = new Stripe(stripeSecretKey || 'sk_test_placeholder_key_not_configured');
|
||||
|
||||
const resolveStripeModeFromKey = (key, livePrefix, testPrefix) => {
|
||||
const normalized = String(key || '').trim();
|
||||
if (normalized.startsWith(livePrefix)) return 'LIVE';
|
||||
if (normalized.startsWith(testPrefix)) return 'TEST';
|
||||
return 'MOCK';
|
||||
};
|
||||
|
||||
const getStripeSecretMode = () =>
|
||||
resolveStripeModeFromKey(process.env.STRIPE_SECRET_KEY, 'sk_live_', 'sk_test_');
|
||||
|
||||
const getStripePublishableMode = () =>
|
||||
resolveStripeModeFromKey(
|
||||
process.env.STRIPE_PUBLISHABLE_KEY || process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY,
|
||||
'pk_live_',
|
||||
'pk_test_',
|
||||
);
|
||||
const app = express();
|
||||
const port = Number(process.env.PORT || 3000);
|
||||
const plantsPublicDir = path.join(__dirname, 'public', 'plants');
|
||||
|
||||
const SCAN_PRIMARY_COST = 1;
|
||||
const SCAN_REVIEW_COST = 1;
|
||||
@@ -323,35 +300,6 @@ const isAuthorizedRevenueCatWebhook = (request) => {
|
||||
return normalized === revenueCatWebhookSecret || normalized === `Bearer ${revenueCatWebhookSecret}`;
|
||||
};
|
||||
|
||||
// Webhooks must be BEFORE express.json() to preserve raw body where required.
|
||||
app.post('/api/webhook', express.raw({ type: 'application/json' }), (request, response) => {
|
||||
const signature = request.headers['stripe-signature'];
|
||||
let event;
|
||||
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(
|
||||
request.body,
|
||||
signature,
|
||||
process.env.STRIPE_WEBHOOK_SECRET,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(`Webhook Error: ${error.message}`);
|
||||
response.status(400).send(`Webhook Error: ${error.message}`);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'payment_intent.succeeded':
|
||||
console.log('PaymentIntent succeeded.');
|
||||
break;
|
||||
default:
|
||||
console.log(`Unhandled event type: ${event.type}`);
|
||||
break;
|
||||
}
|
||||
|
||||
response.json({ received: true });
|
||||
});
|
||||
|
||||
app.post('/api/revenuecat/webhook', express.json({ limit: '1mb' }), async (request, response) => {
|
||||
try {
|
||||
if (!isAuthorizedRevenueCatWebhook(request)) {
|
||||
@@ -371,13 +319,12 @@ app.use(express.json({ limit: '10mb' }));
|
||||
app.get('/', (_request, response) => {
|
||||
response.status(200).json({
|
||||
service: 'greenlns-api',
|
||||
status: 'ok',
|
||||
endpoints: [
|
||||
'GET /health',
|
||||
'POST /api/payment-sheet',
|
||||
'GET /api/plants',
|
||||
'POST /api/plants/rebuild',
|
||||
'POST /auth/signup',
|
||||
status: 'ok',
|
||||
endpoints: [
|
||||
'GET /health',
|
||||
'GET /api/plants',
|
||||
'POST /api/plants/rebuild',
|
||||
'POST /auth/signup',
|
||||
'POST /auth/login',
|
||||
'GET /v1/billing/summary',
|
||||
'POST /v1/billing/sync-revenuecat',
|
||||
@@ -406,7 +353,6 @@ const getDatabaseHealthTarget = () => {
|
||||
};
|
||||
|
||||
app.get('/health', (_request, response) => {
|
||||
const stripeSecret = (process.env.STRIPE_SECRET_KEY || '').trim();
|
||||
response.status(200).json({
|
||||
ok: true,
|
||||
uptimeSec: Math.round(process.uptime()),
|
||||
@@ -414,13 +360,10 @@ app.get('/health', (_request, response) => {
|
||||
openAiConfigured: isOpenAiConfigured(),
|
||||
dbReady: Boolean(db),
|
||||
dbPath: getDatabaseHealthTarget(),
|
||||
stripeConfigured: Boolean(stripeSecret),
|
||||
stripeMode: getStripeSecretMode(),
|
||||
stripePublishableMode: getStripePublishableMode(),
|
||||
scanModel: getScanModel(),
|
||||
healthModel: getHealthModel(),
|
||||
});
|
||||
});
|
||||
scanModel: getScanModel(),
|
||||
healthModel: getHealthModel(),
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/plants', async (request, response) => {
|
||||
try {
|
||||
@@ -480,37 +423,6 @@ app.post('/api/plants/rebuild', async (request, response) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/payment-sheet', async (request, response) => {
|
||||
try {
|
||||
const amount = Number(request.body?.amount || 500);
|
||||
const currency = request.body?.currency || 'usd';
|
||||
|
||||
const paymentIntent = await stripe.paymentIntents.create({
|
||||
amount,
|
||||
currency,
|
||||
automatic_payment_methods: { enabled: true },
|
||||
});
|
||||
|
||||
const customer = await stripe.customers.create();
|
||||
const ephemeralKey = await stripe.ephemeralKeys.create(
|
||||
{ customer: customer.id },
|
||||
{ apiVersion: '2023-10-16' },
|
||||
);
|
||||
|
||||
response.json({
|
||||
paymentIntent: paymentIntent.client_secret,
|
||||
ephemeralKey: ephemeralKey.secret,
|
||||
customer: customer.id,
|
||||
publishableKey: process.env.STRIPE_PUBLISHABLE_KEY || process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY || 'pk_test_mock_key',
|
||||
});
|
||||
} catch (error) {
|
||||
response.status(400).json({
|
||||
code: 'PAYMENT_SHEET_ERROR',
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/v1/billing/summary', async (request, response) => {
|
||||
try {
|
||||
const userId = ensureRequestAuth(request);
|
||||
@@ -900,29 +812,19 @@ app.post('/auth/login', async (request, response) => {
|
||||
|
||||
// ─── Startup ───────────────────────────────────────────────────────────────
|
||||
|
||||
const start = async () => {
|
||||
db = await openDatabase();
|
||||
await ensurePlantSchema(db);
|
||||
await ensureBillingSchema(db);
|
||||
await ensureAuthSchema(db);
|
||||
await seedBootstrapCatalogIfNeeded();
|
||||
if (isStorageConfigured()) {
|
||||
await ensureStorageBucket().catch((err) => console.warn('MinIO bucket setup failed:', err.message));
|
||||
}
|
||||
|
||||
const stripeMode = getStripeSecretMode();
|
||||
const stripePublishableMode = getStripePublishableMode();
|
||||
const maskKey = (key) => {
|
||||
const k = String(key || '').trim();
|
||||
if (k.length < 12) return k ? '(too short to mask)' : '(not set)';
|
||||
return `${k.slice(0, 7)}...${k.slice(-4)}`;
|
||||
};
|
||||
console.log(`Stripe Mode: ${stripeMode} | Secret: ${maskKey(process.env.STRIPE_SECRET_KEY)}`);
|
||||
console.log(`Stripe Publishable Mode: ${stripePublishableMode} | Key: ${maskKey(process.env.STRIPE_PUBLISHABLE_KEY || process.env.EXPO_PUBLIC_STRIPE_PUBLISHABLE_KEY)}`);
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
console.log(`GreenLens server listening at http://localhost:${port}`);
|
||||
});
|
||||
const start = async () => {
|
||||
db = await openDatabase();
|
||||
await ensurePlantSchema(db);
|
||||
await ensureBillingSchema(db);
|
||||
await ensureAuthSchema(db);
|
||||
await seedBootstrapCatalogIfNeeded();
|
||||
if (isStorageConfigured()) {
|
||||
await ensureStorageBucketWithRetry().catch((err) => console.warn('MinIO bucket setup failed:', err.message));
|
||||
}
|
||||
|
||||
const server = app.listen(port, () => {
|
||||
console.log(`GreenLens server listening at http://localhost:${port}`);
|
||||
});
|
||||
|
||||
const gracefulShutdown = async () => {
|
||||
try {
|
||||
|
||||
@@ -15,10 +15,10 @@ const isStorageConfigured = () => Boolean(MINIO_ENDPOINT && MINIO_ACCESS_KEY &&
|
||||
const getMinioPublicUrl = () =>
|
||||
getTrimmedEnv('MINIO_PUBLIC_URL', `http://${MINIO_ENDPOINT}:${MINIO_PORT}`).replace(/\/$/, '');
|
||||
|
||||
const getClient = () => {
|
||||
if (!isStorageConfigured()) {
|
||||
throw new Error('Image storage is not configured.');
|
||||
}
|
||||
const getClient = () => {
|
||||
if (!isStorageConfigured()) {
|
||||
throw new Error('Image storage is not configured.');
|
||||
}
|
||||
|
||||
return new Minio.Client({
|
||||
endPoint: MINIO_ENDPOINT,
|
||||
@@ -26,13 +26,15 @@ const getClient = () => {
|
||||
useSSL: MINIO_USE_SSL,
|
||||
accessKey: MINIO_ACCESS_KEY,
|
||||
secretKey: MINIO_SECRET_KEY,
|
||||
});
|
||||
};
|
||||
|
||||
const ensureStorageBucket = async () => {
|
||||
const client = getClient();
|
||||
const exists = await client.bucketExists(MINIO_BUCKET);
|
||||
if (!exists) {
|
||||
});
|
||||
};
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const ensureStorageBucket = async () => {
|
||||
const client = getClient();
|
||||
const exists = await client.bucketExists(MINIO_BUCKET);
|
||||
if (!exists) {
|
||||
await client.makeBucket(MINIO_BUCKET);
|
||||
const policy = JSON.stringify({
|
||||
Version: '2012-10-17',
|
||||
@@ -46,13 +48,35 @@ const ensureStorageBucket = async () => {
|
||||
],
|
||||
});
|
||||
await client.setBucketPolicy(MINIO_BUCKET, policy);
|
||||
console.log(`MinIO bucket '${MINIO_BUCKET}' created with public read policy.`);
|
||||
}
|
||||
};
|
||||
|
||||
const uploadImage = async (base64Data, contentType = 'image/jpeg') => {
|
||||
const client = getClient();
|
||||
const rawExtension = contentType.split('/')[1] || 'jpg';
|
||||
console.log(`MinIO bucket '${MINIO_BUCKET}' created with public read policy.`);
|
||||
}
|
||||
};
|
||||
|
||||
const ensureStorageBucketWithRetry = async (options = {}) => {
|
||||
const attempts = Number(options.attempts || 5);
|
||||
const delayMs = Number(options.delayMs || 2000);
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 1; attempt <= attempts; attempt += 1) {
|
||||
try {
|
||||
await ensureStorageBucket();
|
||||
return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt === attempts) break;
|
||||
console.warn(
|
||||
`MinIO bucket setup attempt ${attempt}/${attempts} failed: ${error.message}. Retrying in ${delayMs}ms...`,
|
||||
);
|
||||
await sleep(delayMs);
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError;
|
||||
};
|
||||
|
||||
const uploadImage = async (base64Data, contentType = 'image/jpeg') => {
|
||||
const client = getClient();
|
||||
const rawExtension = contentType.split('/')[1] || 'jpg';
|
||||
const extension = rawExtension === 'jpeg' ? 'jpg' : rawExtension;
|
||||
const filename = `${Date.now()}-${crypto.randomBytes(8).toString('hex')}.${extension}`;
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
@@ -65,8 +89,9 @@ const uploadImage = async (base64Data, contentType = 'image/jpeg') => {
|
||||
return { url, filename };
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
ensureStorageBucket,
|
||||
uploadImage,
|
||||
isStorageConfigured,
|
||||
};
|
||||
module.exports = {
|
||||
ensureStorageBucket,
|
||||
ensureStorageBucketWithRetry,
|
||||
uploadImage,
|
||||
isStorageConfigured,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user