Download server.js from Frenchbane/ok-id-pro: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/datasets/Frenchbane/ok-id-pro/resolve/main/server.js
- Command line
-
hf download hf://datasets/Frenchbane/ok-id-pro/server.js
-
curl -L -o server.js https://huggingface.co/datasets/Frenchbane/ok-id-pro/resolve/main/server.js
15.7 kB
| // server.js – Full OK-ID Pro Backend | |
| const express = require('express'); | |
| const puppeteer = require('puppeteer'); | |
| const sharp = require('sharp'); | |
| const mongoose = require('mongoose'); | |
| const multer = require('multer'); | |
| const path = require('path'); | |
| const fs = require('fs').promises; | |
| const axios = require('axios'); | |
| const { faker } = require('@faker-js/faker'); | |
| const cors = require('cors'); | |
| const helmet = require('helmet'); | |
| const rateLimit = require('express-rate-limit'); | |
| const { body, validationResult } = require('express-validator'); | |
| const argon2 = require('argon2'); | |
| const jwt = require('jsonwebtoken'); | |
| const winston = require('winston'); | |
| require('dotenv').config(); | |
| const app = express(); | |
| const PORT = process.env.PORT || 3000; | |
| const MONGO_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/okid_db'; | |
| const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret'; | |
| const ADMIN_TOKEN = process.env.ADMIN_TOKEN || 'admin-secret'; | |
| // ==================== LOGGING ==================== | |
| const logger = winston.createLogger({ | |
| level: 'info', | |
| format: winston.format.combine( | |
| winston.format.timestamp(), | |
| winston.format.json() | |
| ), | |
| transports: [ | |
| new winston.transports.File({ filename: 'logs/error.log', level: 'error' }), | |
| new winston.transports.File({ filename: 'logs/combined.log' }), | |
| ], | |
| }); | |
| if (process.env.NODE_ENV !== 'production') { | |
| logger.add(new winston.transports.Console({ format: winston.format.simple() })); | |
| } | |
| // ==================== MIDDLEWARE ==================== | |
| app.use(helmet()); | |
| app.use(cors({ origin: process.env.CORS_ORIGIN || '*' })); | |
| app.use(express.json({ limit: '10mb' })); | |
| app.use(express.static('public')); | |
| app.use('/fonts', express.static(path.join(__dirname, 'public/fonts'))); | |
| // Rate limiting | |
| const limiter = rateLimit({ | |
| windowMs: 15 * 60 * 1000, | |
| max: 100, | |
| message: { error: 'Too many requests, please try again later.' }, | |
| }); | |
| app.use('/api/', limiter); | |
| // ==================== DATABASE ==================== | |
| mongoose.connect(MONGO_URI) | |
| .then(() => logger.info('MongoDB connected')) | |
| .catch(err => logger.error('MongoDB connection error:', err)); | |
| // ==================== MODELS ==================== | |
| const UserSchema = new mongoose.Schema({ | |
| username: { type: String, unique: true, required: true, trim: true }, | |
| email: { type: String, unique: true, required: true, trim: true }, | |
| password: { type: String, required: true }, | |
| role: { type: String, enum: ['user', 'admin'], default: 'user' }, | |
| activation: { | |
| isActive: { type: Boolean, default: true }, | |
| plan: { type: String, enum: ['trial', 'basic', 'unlimited'], default: 'trial' }, | |
| expiresAt: { type: Date, default: null }, | |
| renderQuota: { type: Number, default: 10 }, | |
| }, | |
| favorites: [{ type: String }], | |
| recents: [{ templateId: String, viewedAt: { type: Date, default: Date.now } }], | |
| createdAt: { type: Date, default: Date.now }, | |
| }); | |
| UserSchema.pre('save', async function(next) { | |
| if (!this.isModified('password')) return next(); | |
| try { | |
| this.password = await argon2.hash(this.password); | |
| next(); | |
| } catch (err) { | |
| next(err); | |
| } | |
| }); | |
| UserSchema.methods.comparePassword = async function(candidate) { | |
| return argon2.verify(this.password, candidate); | |
| }; | |
| const User = mongoose.model('User', UserSchema); | |
| const JobSchema = new mongoose.Schema({ | |
| userId: { type: String, required: true, index: true }, | |
| jobName: { type: String, required: true }, | |
| templateId: { type: String, required: true }, | |
| templateTitle: { type: String, default: '' }, | |
| formData: { type: Object, default: {} }, | |
| folder: { type: String, default: '' }, | |
| tags: [{ type: String }], | |
| deletedAt: { type: Date, default: null }, | |
| updatedAt: { type: Date, default: Date.now }, | |
| createdAt: { type: Date, default: Date.now }, | |
| }); | |
| JobSchema.index({ userId: 1, deletedAt: 1 }); | |
| const Job = mongoose.model('Job', JobSchema); | |
| // ==================== AUTH MIDDLEWARE ==================== | |
| const authMiddleware = (req, res, next) => { | |
| const authHeader = req.headers.authorization; | |
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | |
| return res.status(401).json({ error: 'Unauthorized' }); | |
| } | |
| const token = authHeader.split(' ')[1]; | |
| try { | |
| const decoded = jwt.verify(token, JWT_SECRET); | |
| req.user = decoded; | |
| next(); | |
| } catch (err) { | |
| res.status(401).json({ error: 'Invalid token' }); | |
| } | |
| }; | |
| const adminMiddleware = (req, res, next) => { | |
| if (req.user?.role !== 'admin') { | |
| return res.status(403).json({ error: 'Admin access required' }); | |
| } | |
| next(); | |
| }; | |
| // ==================== AUTH ROUTES ==================== | |
| app.post('/api/auth/register', | |
| [ | |
| body('username').trim().isLength({ min: 3 }).withMessage('Username must be at least 3 characters'), | |
| body('email').isEmail().withMessage('Invalid email'), | |
| body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters'), | |
| ], | |
| async (req, res) => { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() }); | |
| try { | |
| const { username, email, password } = req.body; | |
| const existing = await User.findOne({ $or: [{ username }, { email }] }); | |
| if (existing) return res.status(409).json({ error: 'User already exists' }); | |
| const user = new User({ username, email, password }); | |
| await user.save(); | |
| const token = jwt.sign({ sub: user._id, username, role: user.role }, JWT_SECRET, { expiresIn: '7d' }); | |
| res.json({ token, user: { username, email, role: user.role, activation: user.activation } }); | |
| } catch (err) { | |
| logger.error(err); | |
| res.status(500).json({ error: 'Registration failed' }); | |
| } | |
| } | |
| ); | |
| app.post('/api/auth/login', | |
| [ | |
| body('email').isEmail().withMessage('Invalid email'), | |
| body('password').notEmpty().withMessage('Password required'), | |
| ], | |
| async (req, res) => { | |
| const errors = validationResult(req); | |
| if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() }); | |
| try { | |
| const { email, password } = req.body; | |
| const user = await User.findOne({ email }); | |
| if (!user || !(await user.comparePassword(password))) { | |
| return res.status(401).json({ error: 'Invalid credentials' }); | |
| } | |
| const token = jwt.sign({ sub: user._id, username: user.username, role: user.role }, JWT_SECRET, { expiresIn: '7d' }); | |
| res.json({ token, user: { username: user.username, email, role: user.role, activation: user.activation } }); | |
| } catch (err) { | |
| logger.error(err); | |
| res.status(500).json({ error: 'Login failed' }); | |
| } | |
| } | |
| ); | |
| app.get('/api/auth/me', authMiddleware, async (req, res) => { | |
| try { | |
| const user = await User.findById(req.user.sub).select('-password'); | |
| if (!user) return res.status(404).json({ error: 'User not found' }); | |
| res.json({ user: { username: user.username, email: user.email, role: user.role, activation: user.activation } }); | |
| } catch (err) { | |
| res.status(500).json({ error: 'Failed to fetch user' }); | |
| } | |
| }); | |
| // ==================== TEMPLATE API ==================== | |
| app.get('/api/templates', async (req, res) => { | |
| try { | |
| const dir = path.join(__dirname, 'templates'); | |
| const folders = await fs.readdir(dir, { withFileTypes: true }); | |
| const result = []; | |
| for (const f of folders.filter(f => f.isDirectory())) { | |
| try { | |
| const configRaw = await fs.readFile(path.join(dir, f.name, 'config.json'), 'utf8'); | |
| const config = JSON.parse(configRaw); | |
| result.push({ | |
| id: f.name, | |
| title: config.title || f.name, | |
| category: config.category || 'Other', | |
| description: config.description || '', | |
| dimensions: config.meta?.dimensions || '', | |
| fontCount: config.meta?.fontFaces?.length || 0, | |
| colorCount: config.meta?.colors?.length || 0, | |
| thumbnail: `/templates/${f.name}/thumb.png`, | |
| }); | |
| } catch (e) { /* skip invalid */ } | |
| } | |
| res.json(result); | |
| } catch (err) { | |
| res.status(500).json({ error: 'Failed to list templates' }); | |
| } | |
| }); | |
| app.get('/api/templates/:id', async (req, res) => { | |
| try { | |
| const id = req.params.id; | |
| const dir = path.join(__dirname, 'templates', id); | |
| const configRaw = await fs.readFile(path.join(dir, 'config.json'), 'utf8'); | |
| const config = JSON.parse(configRaw); | |
| const svg = await fs.readFile(path.join(dir, 'main.svg'), 'utf8'); | |
| res.json({ config, svg }); | |
| } catch (err) { | |
| res.status(404).json({ error: 'Template not found' }); | |
| } | |
| }); | |
| // ==================== ADMIN UPLOAD ==================== | |
| const upload = multer({ storage: multer.memoryStorage() }); | |
| app.post('/api/admin/upload', authMiddleware, adminMiddleware, upload.fields([ | |
| { name: 'config', maxCount: 1 }, | |
| { name: 'svg', maxCount: 1 } | |
| ]), async (req, res) => { | |
| const { templateId } = req.body; | |
| if (!templateId) return res.status(400).json({ error: 'templateId required' }); | |
| try { | |
| const dir = path.join(__dirname, 'templates', templateId); | |
| await fs.mkdir(dir, { recursive: true }); | |
| await fs.writeFile(path.join(dir, 'config.json'), req.files['config'][0].buffer); | |
| await fs.writeFile(path.join(dir, 'main.svg'), req.files['svg'][0].buffer); | |
| res.json({ success: true, message: `Template ${templateId} uploaded` }); | |
| } catch (err) { | |
| logger.error(err); | |
| res.status(500).json({ error: 'Upload failed' }); | |
| } | |
| }); | |
| // ==================== JOBS API ==================== | |
| app.get('/api/jobs', authMiddleware, async (req, res) => { | |
| try { | |
| const { folder, tag, trash, q } = req.query; | |
| const query = { userId: req.user.sub, deletedAt: null }; | |
| if (trash === '1') query.deletedAt = { $ne: null }; | |
| if (folder) query.folder = folder; | |
| if (tag) query.tags = tag; | |
| if (q) query.jobName = { $regex: q, $options: 'i' }; | |
| const jobs = await Job.find(query).sort({ updatedAt: -1 }); | |
| res.json(jobs); | |
| } catch (err) { | |
| res.status(500).json({ error: 'Failed to load jobs' }); | |
| } | |
| }); | |
| app.post('/api/jobs/save', authMiddleware, async (req, res) => { | |
| try { | |
| const { jobName, templateId, templateTitle, formData, folder, tags } = req.body; | |
| if (!jobName || !templateId) return res.status(400).json({ error: 'Job name and template required' }); | |
| const job = await Job.findOneAndUpdate( | |
| { userId: req.user.sub, jobName, deletedAt: null }, | |
| { templateId, templateTitle: templateTitle || templateId, formData, folder: folder || '', tags: tags || [], updatedAt: new Date() }, | |
| { upsert: true, new: true } | |
| ); | |
| res.json({ success: true, job }); | |
| } catch (err) { | |
| res.status(500).json({ error: 'Save failed' }); | |
| } | |
| }); | |
| app.delete('/api/jobs/:id', authMiddleware, async (req, res) => { | |
| try { | |
| const job = await Job.findOneAndUpdate( | |
| { _id: req.params.id, userId: req.user.sub, deletedAt: null }, | |
| { deletedAt: new Date() }, | |
| { new: true } | |
| ); | |
| if (!job) return res.status(404).json({ error: 'Job not found' }); | |
| res.json({ success: true }); | |
| } catch (err) { | |
| res.status(500).json({ error: 'Delete failed' }); | |
| } | |
| }); | |
| // ==================== SMART SERVICES ==================== | |
| app.get('/api/service/random-identity', (req, res) => { | |
| res.json({ | |
| first: faker.person.firstName(), | |
| middle: faker.person.middleName(), | |
| last: faker.person.lastName(), | |
| address: faker.location.streetAddress(false), | |
| city: faker.location.city(), | |
| state: faker.location.state({ abbreviated: true }), | |
| zipcode: faker.location.zipCode('#####'), | |
| ssn: faker.helpers.replaceSymbolWithNumber('###-##-####'), | |
| iss: faker.date.past().toISOString().split('T')[0], | |
| }); | |
| }); | |
| app.get('/api/service/zip-lookup/:zip', async (req, res) => { | |
| try { | |
| const resp = await axios.get(`http://api.zippopotam.us/us/${req.params.zip}`); | |
| const p = resp.data.places[0]; | |
| res.json({ city: p['place name'], state: p['state abbreviation'] }); | |
| } catch (err) { | |
| res.status(404).json({ error: 'Zip code not found' }); | |
| } | |
| }); | |
| // ==================== RENDERING ENGINE ==================== | |
| function bindSvgData(svg, data) { | |
| let out = svg; | |
| for (const key in data) { | |
| const val = data[key] || ''; | |
| out = out.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), val); | |
| const idPattern = new RegExp(`(id="svg_${key}"[^>]*>)[^<]*(</text>|</tspan>)`, 'g'); | |
| out = out.replace(idPattern, `$1${val}$2`); | |
| } | |
| // Apply text edits if stored | |
| if (data._textEdits && typeof data._textEdits === 'object') { | |
| for (const [id, text] of Object.entries(data._textEdits)) { | |
| const pattern = new RegExp(`(id="${id}"[^>]*>)[^<]*(</text>|</tspan>)`, 'g'); | |
| out = out.replace(pattern, `$1${text}$2`); | |
| } | |
| } | |
| return out; | |
| } | |
| app.post('/render', authMiddleware, async (req, res) => { | |
| const { templateId, data, format, dpi } = req.body; | |
| if (!templateId || !data) { | |
| return res.status(400).json({ error: 'Missing templateId or data' }); | |
| } | |
| // Quota check | |
| const user = await User.findById(req.user.sub); | |
| if (user && user.role !== 'admin' && user.activation.plan !== 'unlimited') { | |
| if (user.activation.renderQuota <= 0) { | |
| return res.status(402).json({ error: 'Render quota exceeded. Upgrade your plan.' }); | |
| } | |
| } | |
| let browser; | |
| try { | |
| browser = await puppeteer.launch({ | |
| headless: 'new', | |
| args: ['--no-sandbox', '--disable-setuid-sandbox'] | |
| }); | |
| const page = await browser.newPage(); | |
| const tResp = await axios.get(`http://localhost:${PORT}/api/templates/${templateId}`); | |
| const svg = bindSvgData(tResp.data.svg, data); | |
| const html = `<!DOCTYPE html> | |
| <html style="margin:0;height:100%;"> | |
| <head> | |
| <link rel="stylesheet" href="http://localhost:${PORT}/fonts/fonts.css"> | |
| <style>body{margin:0;display:flex;justify-content:center;align-items:center;background:#111;}</style> | |
| </head> | |
| <body>${svg}</body> | |
| </html>`; | |
| await page.setContent(html, { waitUntil: 'networkidle0' }); | |
| const bbox = await page.evaluate(() => { | |
| const svg = document.querySelector('svg'); | |
| if (svg) { | |
| const r = svg.getBoundingClientRect(); | |
| return { width: Math.ceil(r.width), height: Math.ceil(r.height) }; | |
| } | |
| return { width: 1000, height: 1000 }; | |
| }); | |
| const scale = (parseInt(dpi) || 300) / 72; | |
| await page.setViewport({ | |
| width: Math.ceil(bbox.width * scale), | |
| height: Math.ceil(bbox.height * scale), | |
| deviceScaleFactor: scale, | |
| }); | |
| const screenshot = await page.screenshot({ | |
| type: 'png', | |
| clip: { x: 0, y: 0, width: Math.ceil(bbox.width * scale), height: Math.ceil(bbox.height * scale) } | |
| }); | |
| await browser.close(); | |
| browser = null; | |
| if (user && user.role !== 'admin' && user.activation.plan !== 'unlimited') { | |
| user.activation.renderQuota -= 1; | |
| await user.save(); | |
| } | |
| const fmt = format === 'jpg' ? 'jpeg' : (format === 'webp' ? 'webp' : 'png'); | |
| const processed = await sharp(screenshot) | |
| .toFormat(fmt) | |
| .withMetadata({ density: parseInt(dpi) || 300 }) | |
| .toBuffer(); | |
| res.type(`image/${format === 'jpg' ? 'jpeg' : format}`).send(processed); | |
| } catch (err) { | |
| if (browser) await browser.close(); | |
| logger.error('Render error:', err); | |
| res.status(500).json({ error: 'Render failed', message: err.message }); | |
| } | |
| }); | |
| // ==================== HEALTH CHECK ==================== | |
| app.get('/health', (req, res) => { | |
| res.json({ status: 'OK', uptime: process.uptime() }); | |
| }); | |
| // ==================== ERROR HANDLER ==================== | |
| app.use((err, req, res, next) => { | |
| logger.error(err.stack); | |
| res.status(err.status || 500).json({ error: err.message || 'Internal Server Error' }); | |
| }); | |
| // ==================== START SERVER ==================== | |
| app.listen(PORT, () => { | |
| logger.info(`OK-ID Pro server running on http://localhost:${PORT}`); | |
| }); |