#!/usr/bin/env node import { mkdir, realpath } from 'node:fs/promises'; import { dirname, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import sharp from 'sharp'; const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const permittedPrivateRoot = resolve(repositoryRoot, 'content/private'); const fail = () => { throw new Error('SOCIAL-PREVIEW-PATH-001'); }; const canonicalizeForWrite = async (path) => { const absolute = resolve(path); let cursor = dirname(absolute); const suffix = []; while (true) { try { return resolve(await realpath(cursor), ...suffix, absolute.slice(dirname(absolute).length + 1)); } catch (error) { if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) fail(); const parent = dirname(cursor); if (parent === cursor) fail(); suffix.unshift(cursor.slice(parent.length + 1)); cursor = parent; } } }; const isInside = (path, root) => path === root || path.startsWith(`${root}${sep}`); export const generateSocialPreview = async (outputPath) => { if (typeof outputPath !== 'string' || outputPath.trim() === '') fail(); const output = await canonicalizeForWrite(outputPath); const privateRoot = await canonicalizeForWrite(permittedPrivateRoot); if (!isInside(output, privateRoot) && !isInside(output, '/tmp')) fail(); const svg = Buffer.from(` Luca Pîslaru System Administrator & Full-Stack Developer `); await mkdir(dirname(output), { recursive: true }); await sharp(svg, { density: 72 }) .flatten({ background: '#070910' }) .png({ compressionLevel: 9, adaptiveFiltering: false, palette: false }) .toFile(output); return output; }; const parseOutput = (argv) => { if (argv.length !== 2 || argv[0] !== '--output') fail(); return argv[1]; }; if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { generateSocialPreview(parseOutput(process.argv.slice(2))).catch((error) => { process.stderr.write(`${error instanceof Error ? error.message : 'SOCIAL-PREVIEW-001'}\n`); process.exitCode = 1; }); }