v0.4.0: Remove free tier, add public demo endpoint with watermark
All checks were successful
Build & Deploy to Staging / Build & Deploy to Staging (push) Successful in 12m31s
Promote to Production / Deploy to Production (push) Successful in 2m26s

- Remove free account signup flow entirely
- Add POST /v1/demo/html and /v1/demo/markdown (public, no auth)
- Demo: 5 requests/hour per IP, 50KB body limit, watermarked PDFs
- Landing page: interactive playground replaces 'Get Free API Key'
- Pricing: Demo (free) + Pro (€9/mo), no more Free tier
- /v1/signup returns 410 Gone with redirect to demo/pro
- Keep /v1/recover for existing Pro users
- Update JSON-LD, API discovery, verify page text
This commit is contained in:
DocFast Bot 2026-02-20 07:32:45 +00:00
parent 9095175141
commit 53755d6093
6 changed files with 299 additions and 240 deletions

View file

@ -1,6 +1,6 @@
{
"name": "docfast-api",
"version": "0.3.4",
"version": "0.4.0",
"description": "Markdown/HTML to PDF API with built-in invoice templates",
"main": "dist/index.js",
"scripts": {

View file

@ -1,14 +1,5 @@
var signupEmail = '';
var recoverEmail = '';
function showState(state) {
['signupInitial', 'signupLoading', 'signupVerify', 'signupResult'].forEach(function(id) {
var el = document.getElementById(id);
if (el) el.classList.remove('active');
});
document.getElementById(state).classList.add('active');
}
function showRecoverState(state) {
['recoverInitial', 'recoverLoading', 'recoverVerify', 'recoverResult'].forEach(function(id) {
var el = document.getElementById(id);
@ -17,23 +8,7 @@ function showRecoverState(state) {
document.getElementById(state).classList.add('active');
}
function openSignup() {
document.getElementById('signupModal').classList.add('active');
showState('signupInitial');
document.getElementById('signupError').style.display = 'none';
document.getElementById('verifyError').style.display = 'none';
document.getElementById('signupEmail').value = '';
document.getElementById('verifyCode').value = '';
signupEmail = '';
setTimeout(function() { document.getElementById('signupEmail').focus(); }, 100);
}
function closeSignup() {
document.getElementById('signupModal').classList.remove('active');
}
function openRecover() {
closeSignup();
document.getElementById('recoverModal').classList.add('active');
showRecoverState('recoverInitial');
var errEl = document.getElementById('recoverError');
@ -50,92 +25,6 @@ function closeRecover() {
document.getElementById('recoverModal').classList.remove('active');
}
async function submitSignup() {
var errEl = document.getElementById('signupError');
var btn = document.getElementById('signupBtn');
var emailInput = document.getElementById('signupEmail');
var email = emailInput.value.trim();
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
errEl.textContent = 'Please enter a valid email address.';
errEl.style.display = 'block';
return;
}
errEl.style.display = 'none';
btn.disabled = true;
showState('signupLoading');
try {
var res = await fetch('/v1/signup/free', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: email })
});
var data = await res.json();
if (!res.ok) {
showState('signupInitial');
errEl.textContent = data.error || 'Something went wrong. Please try again.';
errEl.style.display = 'block';
btn.disabled = false;
return;
}
signupEmail = email;
document.getElementById('verifyEmailDisplay').textContent = email;
showState('signupVerify');
document.getElementById('verifyCode').focus();
btn.disabled = false;
} catch (err) {
showState('signupInitial');
errEl.textContent = 'Network error. Please try again.';
errEl.style.display = 'block';
btn.disabled = false;
}
}
async function submitVerify() {
var errEl = document.getElementById('verifyError');
var btn = document.getElementById('verifyBtn');
var codeInput = document.getElementById('verifyCode');
var code = codeInput.value.trim();
if (!code || !/^\d{6}$/.test(code)) {
errEl.textContent = 'Please enter a 6-digit code.';
errEl.style.display = 'block';
return;
}
errEl.style.display = 'none';
btn.disabled = true;
try {
var res = await fetch('/v1/signup/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: signupEmail, code: code })
});
var data = await res.json();
if (!res.ok) {
errEl.textContent = data.error || 'Verification failed.';
errEl.style.display = 'block';
btn.disabled = false;
return;
}
document.getElementById('apiKeyText').textContent = data.apiKey;
showState('signupResult');
var resultH2 = document.querySelector('#signupResult h2');
if (resultH2) { resultH2.setAttribute('tabindex', '-1'); resultH2.focus(); }
} catch (err) {
errEl.textContent = 'Network error. Please try again.';
errEl.style.display = 'block';
btn.disabled = false;
}
}
async function submitRecover() {
var errEl = document.getElementById('recoverError');
var btn = document.getElementById('recoverBtn');
@ -228,12 +117,6 @@ async function submitRecoverVerify() {
}
}
function copyKey() {
var key = document.getElementById('apiKeyText').textContent;
var btn = document.getElementById('copyBtn');
doCopy(key, btn);
}
function copyRecoveredKey() {
var key = document.getElementById('recoveredKeyText').textContent;
var btn = document.getElementById('copyRecoveredBtn');
@ -252,50 +135,30 @@ function doCopy(text, btn) {
try {
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text).then(showCopied).catch(function() {
// Fallback to execCommand
fallbackCopy(text, showCopied, showFailed);
});
} else {
fallbackCopy(text, showCopied, showFailed);
}
} catch(e) {
showFailed();
}
}
function fallbackCopy(text, onSuccess, onFail) {
try {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
ta.style.top = '-9999px';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.focus();
ta.select();
var success = document.execCommand('copy');
document.body.removeChild(ta);
if (success) {
showCopied();
} else {
showFailed();
}
} catch (err) {
showFailed();
}
});
} else {
// Direct fallback for non-secure contexts
var ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed';
ta.style.opacity = '0';
ta.style.top = '-9999px';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.focus();
ta.select();
var success = document.execCommand('copy');
document.body.removeChild(ta);
if (success) {
showCopied();
} else {
showFailed();
}
}
} catch(e) {
showFailed();
}
success ? onSuccess() : onFail();
} catch(e) { onFail(); }
}
async function checkout() {
@ -309,19 +172,71 @@ async function checkout() {
}
}
// === Demo Playground ===
async function generateDemo() {
var btn = document.getElementById('demoGenerateBtn');
var status = document.getElementById('demoStatus');
var result = document.getElementById('demoResult');
var errorEl = document.getElementById('demoError');
var html = document.getElementById('demoHtml').value.trim();
if (!html) {
errorEl.textContent = 'Please enter some HTML.';
errorEl.style.display = 'block';
result.style.display = 'none';
return;
}
errorEl.style.display = 'none';
result.style.display = 'none';
btn.disabled = true;
status.textContent = 'Generating PDF…';
try {
var res = await fetch('/v1/demo/html', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ html: html })
});
if (!res.ok) {
var data = await res.json();
errorEl.textContent = data.error || 'Something went wrong.';
errorEl.style.display = 'block';
btn.disabled = false;
status.textContent = '';
return;
}
var blob = await res.blob();
var url = URL.createObjectURL(blob);
var dl = document.getElementById('demoDownload');
dl.href = url;
result.style.display = 'block';
status.textContent = '';
btn.disabled = false;
} catch (err) {
errorEl.textContent = 'Network error. Please try again.';
errorEl.style.display = 'block';
btn.disabled = false;
status.textContent = '';
}
}
// === Init ===
document.addEventListener('DOMContentLoaded', function() {
// BUG-068: Open change email modal if navigated via #change-email hash
// BUG-068: Open change email modal if navigated via hash
if (window.location.hash === '#change-email') {
openEmailChange();
}
document.getElementById('btn-signup').addEventListener('click', openSignup);
document.getElementById('btn-signup-2').addEventListener('click', openSignup);
// Demo playground
document.getElementById('demoGenerateBtn').addEventListener('click', generateDemo);
// Checkout buttons
document.getElementById('btn-checkout').addEventListener('click', checkout);
document.getElementById('btn-close-signup').addEventListener('click', closeSignup);
document.getElementById('signupBtn').addEventListener('click', submitSignup);
document.getElementById('verifyBtn').addEventListener('click', submitVerify);
document.getElementById('copyBtn').addEventListener('click', copyKey);
var heroCheckout = document.getElementById('btn-checkout-hero');
if (heroCheckout) heroCheckout.addEventListener('click', checkout);
// Recovery modal
document.getElementById('btn-close-recover').addEventListener('click', closeRecover);
@ -337,13 +252,13 @@ document.addEventListener('DOMContentLoaded', function() {
el.addEventListener('click', function(e) { e.preventDefault(); openRecover(); });
});
document.getElementById('signupModal').addEventListener('click', function(e) {
if (e.target === this) closeSignup();
});
// Smooth scroll for hash links
document.querySelectorAll('a[href^="#"]').forEach(function(a) {
a.addEventListener('click', function(e) {
var target = this.getAttribute('href');
if (target === '#') return;
e.preventDefault();
var el = document.querySelector(this.getAttribute('href'));
var el = document.querySelector(target);
if (el) el.scrollIntoView({ behavior: 'smooth' });
});
});
@ -362,7 +277,6 @@ function showEmailChangeState(state) {
}
function openEmailChange() {
closeSignup();
closeRecover();
document.getElementById('emailChangeModal').classList.add('active');
showEmailChangeState('emailChangeInitial');
@ -472,7 +386,7 @@ async function submitEmailChangeVerify() {
}
}
// Add event listeners for email change (append to DOMContentLoaded)
// Email change event listeners
document.addEventListener('DOMContentLoaded', function() {
var closeBtn = document.getElementById('btn-close-email-change');
if (closeBtn) closeBtn.addEventListener('click', closeEmailChange);
@ -494,7 +408,7 @@ document.addEventListener('DOMContentLoaded', function() {
// === Accessibility: Escape key closes modals, focus trapping ===
(function() {
function getActiveModal() {
var modals = ['signupModal', 'recoverModal', 'emailChangeModal'];
var modals = ['recoverModal', 'emailChangeModal'];
for (var i = 0; i < modals.length; i++) {
var m = document.getElementById(modals[i]);
if (m && m.classList.contains('active')) return m;
@ -511,7 +425,6 @@ document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') closeActiveModal();
// Focus trap inside active modal
if (e.key === 'Tab') {
var modal = getActiveModal();
if (!modal) return;

2
public/app.min.js vendored

File diff suppressed because one or more lines are too long

View file

@ -16,10 +16,10 @@
<meta name="twitter:image" content="https://docfast.dev/og-image.png">
<link rel="canonical" href="https://docfast.dev/">
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"SoftwareApplication","name":"DocFast","url":"https://docfast.dev","applicationCategory":"DeveloperApplication","operatingSystem":"Web","description":"Convert HTML and Markdown to beautiful PDFs with a simple API call. Fast, reliable, developer-friendly.","offers":[{"@type":"Offer","price":"0","priceCurrency":"EUR","name":"Free","description":"100 PDFs/month"},{"@type":"Offer","price":"9","priceCurrency":"EUR","name":"Pro","description":"5,000 PDFs/month","billingIncrement":"P1M"}]}
{"@context":"https://schema.org","@type":"SoftwareApplication","name":"DocFast","url":"https://docfast.dev","applicationCategory":"DeveloperApplication","operatingSystem":"Web","description":"Convert HTML and Markdown to beautiful PDFs with a simple API call. Fast, reliable, developer-friendly.","offers":[{"@type":"Offer","price":"9","priceCurrency":"EUR","name":"Pro","description":"5,000 PDFs/month","billingIncrement":"P1M"}]}
</script>
<script type="application/ld+json">
{"@context":"https://schema.org","@type":"WebApplication","name":"DocFast","url":"https://docfast.dev","browserRequirements":"Requires JavaScript. Requires HTML5.","applicationCategory":"DeveloperApplication","operatingSystem":"All","offers":[{"@type":"Offer","price":"0","priceCurrency":"EUR","name":"Free Tier","description":"100 PDFs per month, all endpoints included"},{"@type":"Offer","price":"9","priceCurrency":"EUR","name":"Pro","description":"5,000 PDFs per month, priority support","billingIncrement":"P1M"}]}
{"@context":"https://schema.org","@type":"WebApplication","name":"DocFast","url":"https://docfast.dev","browserRequirements":"Requires JavaScript. Requires HTML5.","applicationCategory":"DeveloperApplication","operatingSystem":"All","offers":[{"@type":"Offer","price":"9","priceCurrency":"EUR","name":"Pro","description":"5,000 PDFs per month, priority support","billingIncrement":"P1M"}]}
</script>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>⚡</text></svg>">
<style>
@ -262,6 +262,10 @@ html, body {
#emailChangeResult.active { display: block; }
#emailChangeVerify.active { display: block; }
/* Demo playground */
.demo-playground { padding: 80px 0; }
.demo-playground textarea:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
/* Focus-visible for accessibility */
.btn:focus-visible, a:focus-visible, input:focus-visible, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
/* Skip to content */
@ -293,10 +297,10 @@ html, body {
<h1>HTML to <span class="gradient">PDF</span><br>in one API call</h1>
<p>Convert HTML, Markdown, or URLs to pixel-perfect PDFs. Built-in templates for invoices &amp; receipts. No headless browser headaches.</p>
<div class="hero-actions">
<button class="btn btn-primary" id="btn-signup" aria-label="Get free API key">Get Free API Key →</button>
<a href="/docs" class="btn btn-secondary">Read the Docs</a>
<a href="#demo" class="btn btn-primary" id="btn-try-demo">Try Demo →</a>
<button class="btn btn-secondary" id="btn-checkout-hero" aria-label="Get Pro API key">Get Pro API Key — €9/mo</button>
</div>
<p style="margin-top:16px;color:var(--muted);font-size:0.9rem;">Already have an account? <a href="#" class="open-recover" style="color:var(--accent);">Lost your API key? Recover it →</a></p>
<p style="margin-top:16px;color:var(--muted);font-size:0.9rem;">No signup needed for demo • <a href="#" class="open-recover" style="color:var(--accent);">Lost your API key? Recover it →</a></p>
<div class="code-section">
<div class="code-header">
@ -392,19 +396,19 @@ html, body {
<section class="pricing" id="pricing">
<div class="container">
<h2 class="section-title">Simple, transparent pricing</h2>
<p class="section-sub">Start free. Upgrade when you're ready. No surprise charges.</p>
<div class="pricing-grid">
<p class="section-sub">Try instantly with the demo. Go Pro when you're ready.</p>
<div class="pricing-grid" style="grid-template-columns:1fr 1fr;max-width:700px;">
<div class="price-card">
<div class="price-name">Free</div>
<div class="price-amount">€0<span> /mo</span></div>
<div class="price-desc">Perfect for side projects and testing</div>
<div class="price-name">Demo</div>
<div class="price-amount" style="font-size:2rem;">Free<span></span></div>
<div class="price-desc">Try it out — no signup needed</div>
<ul class="price-features">
<li>100 PDFs per month</li>
<li>All conversion endpoints</li>
<li>All templates included</li>
<li>Rate limiting: 10 req/min</li>
<li>5 PDFs per hour</li>
<li>HTML &amp; Markdown to PDF</li>
<li>Watermarked output</li>
<li>No API key required</li>
</ul>
<button class="btn btn-secondary" style="width:100%" id="btn-signup-2" aria-label="Get free API key">Get Free API Key</button>
<a href="#demo" class="btn btn-secondary" style="width:100%">Try Demo ↓</a>
</div>
<div class="price-card featured">
<div class="price-name">Pro</div>
@ -414,6 +418,7 @@ html, body {
<li>5,000 PDFs per month</li>
<li>All conversion endpoints</li>
<li>All templates included</li>
<li>Clean PDFs — no watermark</li>
<li>Priority support (<a href="mailto:support@docfast.dev">support@docfast.dev</a>)</li>
</ul>
<button class="btn btn-primary" style="width:100%" id="btn-checkout" aria-label="Get started with Pro plan">Get Started →</button>
@ -422,6 +427,36 @@ html, body {
</div>
</section>
<section class="demo-playground" id="demo">
<div class="container">
<h2 class="section-title">Try it now</h2>
<p class="section-sub">Generate a PDF right here — no signup, no API key. 5 free demos per hour.</p>
<div style="max-width:700px;margin:0 auto;">
<div class="code-header">
<div class="code-dots" aria-hidden="true"><span></span><span></span><span></span></div>
<span class="code-label">HTML → PDF playground</span>
</div>
<textarea id="demoHtml" aria-label="HTML input for demo PDF generation" style="width:100%;min-height:180px;padding:20px;background:var(--card);border:1px solid var(--border);border-top:none;color:var(--fg);font-family:'SF Mono','Fira Code',monospace;font-size:0.85rem;line-height:1.7;resize:vertical;border-radius:0;" spellcheck="false"><h1 style="color:#34d399;font-family:sans-serif;">Hello from DocFast!</h1>
<p style="font-family:sans-serif;font-size:18px;color:#333;">This is a demo PDF generated via the DocFast API.</p>
<ul style="font-family:sans-serif;color:#555;">
<li>HTML &amp; Markdown to PDF</li>
<li>Sub-second generation</li>
<li>EU hosted, GDPR compliant</li>
</ul></textarea>
<div style="display:flex;gap:12px;align-items:center;margin-top:16px;flex-wrap:wrap;">
<button class="btn btn-primary" id="demoGenerateBtn" aria-label="Generate demo PDF">Generate PDF →</button>
<span id="demoStatus" style="color:var(--muted);font-size:0.85rem;"></span>
</div>
<div id="demoResult" style="display:none;margin-top:16px;padding:16px;background:var(--card);border:1px solid var(--accent);border-radius:var(--radius);text-align:center;">
<p style="margin-bottom:12px;color:var(--fg);">✅ PDF generated!</p>
<a id="demoDownload" href="#" download="demo.pdf" class="btn btn-primary" style="display:inline-flex;">Download PDF ↓</a>
<p style="margin-top:12px;color:var(--muted);font-size:0.8rem;">Demo PDFs include a small watermark. <a href="#pricing">Upgrade to Pro</a> for clean output.</p>
</div>
<div id="demoError" style="display:none;margin-top:16px;padding:14px;background:rgba(248,113,113,0.06);border:1px solid rgba(248,113,113,0.15);border-radius:var(--radius);color:#f87171;font-size:0.9rem;"></div>
</div>
</div>
</section>
</main>
<footer aria-label="Footer">
@ -439,50 +474,6 @@ html, body {
</div>
</footer>
<!-- Signup Modal -->
<div class="modal-overlay" id="signupModal" role="dialog" aria-modal="true" aria-label="Sign up for API key">
<div class="modal">
<button class="close" id="btn-close-signup" aria-label="Close dialog">&times;</button>
<div id="signupInitial" class="active">
<h2>Get your free API key</h2>
<p>Enter your email to get started. No credit card required.</p>
<div class="signup-error" id="signupError"></div>
<input type="email" id="signupEmail" aria-label="Email address" placeholder="your.email@example.com" style="width:100%;padding:12px;border:1px solid var(--border);background:var(--bg);color:var(--fg);border-radius:8px;font-size:0.9rem;margin-bottom:16px;" required>
<button class="btn btn-primary" style="width:100%" id="signupBtn" aria-label="Generate API key">Generate API Key →</button>
<p style="margin-top:16px;color:var(--muted);font-size:0.8rem;text-align:center;">100 free PDFs/month • All endpoints included<br><a href="#" class="open-recover" style="color:var(--muted)">Lost your API key? Recover it →</a></p>
</div>
<div id="signupLoading">
<div class="spinner"></div>
<p style="color:var(--muted);margin:0">Generating your API key…</p>
</div>
<div id="signupVerify">
<h2>Enter verification code</h2>
<p>We sent a 6-digit code to <strong id="verifyEmailDisplay"></strong></p>
<div class="signup-error" id="verifyError"></div>
<input type="text" id="verifyCode" aria-label="Verification code" placeholder="123456" maxlength="6" pattern="[0-9]{6}" inputmode="numeric" style="width:100%;padding:14px;border:1px solid var(--border);background:var(--bg);color:var(--fg);border-radius:8px;font-size:1.4rem;letter-spacing:0.3em;text-align:center;margin-bottom:16px;font-family:monospace;" required>
<button class="btn btn-primary" style="width:100%" id="verifyBtn" aria-label="Verify code">Verify →</button>
<p style="margin-top:16px;color:var(--muted);font-size:0.8rem;text-align:center;">Code expires in 15 minutes</p>
</div>
<div id="signupResult" aria-live="polite">
<h2>🚀 Your API key is ready!</h2>
<div class="warning-box">
<span class="icon">⚠️</span>
<span>Save your API key securely. Lost it? <a href="#" class="open-recover" style="color:#fbbf24">Recover via email</a></span>
</div>
<div style="background:var(--bg);border:1px solid var(--accent);border-radius:8px;padding:14px;font-family:monospace;font-size:0.82rem;word-break:break-all;margin:16px 0;position:relative;">
<span id="apiKeyText"></span>
<button onclick="copyKey()" id="copyBtn" aria-label="Copy API key" style="position:absolute;top:8px;right:8px;background:var(--accent);color:var(--bg);border:none;border-radius:4px;padding:4px 12px;cursor:pointer;font-size:0.8rem;">Copy</button>
</div>
<p style="margin-top:20px;color:var(--muted);font-size:0.9rem;">100 free PDFs/month • <a href="/docs">Read the docs →</a></p>
</div>
</div>
</div>
<!-- Recovery Modal -->
<div class="modal-overlay" id="recoverModal" role="dialog" aria-modal="true" aria-label="Recover API key">
<div class="modal">

View file

@ -13,7 +13,7 @@ import rateLimit from "express-rate-limit";
import { convertRouter } from "./routes/convert.js";
import { templatesRouter } from "./routes/templates.js";
import { healthRouter } from "./routes/health.js";
import { signupRouter } from "./routes/signup.js";
import { demoRouter } from "./routes/demo.js";
import { recoverRouter } from "./routes/recover.js";
import { billingRouter } from "./routes/billing.js";
import { authMiddleware } from "./middleware/auth.js";
@ -58,7 +58,8 @@ app.use(compressionMiddleware);
app.use((req, res, next) => {
const isAuthBillingRoute = req.path.startsWith('/v1/signup') ||
req.path.startsWith('/v1/recover') ||
req.path.startsWith('/v1/billing');
req.path.startsWith('/v1/billing') ||
req.path.startsWith('/v1/demo');
if (isAuthBillingRoute) {
res.setHeader("Access-Control-Allow-Origin", "https://docfast.dev");
@ -96,7 +97,14 @@ app.use(limiter);
// Public routes
app.use("/health", healthRouter);
app.use("/v1/signup", signupRouter);
app.use("/v1/demo", express.json({ limit: "50kb" }), pdfRateLimitMiddleware, demoRouter);
app.use("/v1/signup", (_req, res) => {
res.status(410).json({
error: "Free accounts have been discontinued. Try our demo at POST /v1/demo/html or upgrade to Pro at https://docfast.dev",
demo_endpoint: "/v1/demo/html",
pro_url: "https://docfast.dev/#pricing"
});
});
app.use("/v1/recover", recoverRouter);
app.use("/v1/billing", billingRouter);
@ -173,7 +181,7 @@ p{color:#7a8194;margin-bottom:24px;line-height:1.6}
${apiKey ? `
<div class="warning"> Save your API key securely. You can recover it via email if needed.</div>
<div class="key-box" onclick="navigator.clipboard.writeText('${apiKey}');this.style.borderColor='#5eead4';setTimeout(()=>this.style.borderColor='#34d399',1500)">${apiKey}</div>
<div class="links">100 free PDFs/month · <a href="/docs">Read the docs </a></div>
<div class="links">Upgrade to Pro for 5,000 PDFs/month · <a href="/docs">Read the docs </a></div>
` : `<div class="links"><a href="/"> Back to DocFast</a></div>`}
</div></body></html>`;
}
@ -241,10 +249,11 @@ app.get("/api", (_req, res) => {
name: "DocFast API",
version: APP_VERSION,
endpoints: [
"POST /v1/signup/free — Get a free API key",
"POST /v1/convert/html",
"POST /v1/convert/markdown",
"POST /v1/convert/url",
"POST /v1/demo/html — Try HTML→PDF (no auth, watermarked, 5/hour)",
"POST /v1/demo/markdown — Try Markdown→PDF (no auth, watermarked, 5/hour)",
"POST /v1/convert/html — HTML→PDF (requires API key)",
"POST /v1/convert/markdown — Markdown→PDF (requires API key)",
"POST /v1/convert/url — URL→PDF (requires API key)",
"POST /v1/templates/:id/render",
"GET /v1/templates",
"POST /v1/billing/checkout — Start Pro subscription",

146
src/routes/demo.ts Normal file
View file

@ -0,0 +1,146 @@
import { Router, Request, Response } from "express";
import rateLimit from "express-rate-limit";
import { renderPdf } from "../services/browser.js";
import { markdownToHtml, wrapHtml } from "../services/markdown.js";
import logger from "../services/logger.js";
const router = Router();
const WATERMARK_HTML = `<div style="position:fixed;bottom:0;left:0;right:0;background:rgba(52,211,153,0.92);color:#0b0d11;text-align:center;padding:8px;font-family:sans-serif;font-size:12px;font-weight:bold;z-index:999999;letter-spacing:0.3px;">Generated by DocFast — docfast.dev | Upgrade to Pro for clean PDFs</div>`;
function injectWatermark(html: string): string {
if (html.includes("</body>")) {
return html.replace("</body>", WATERMARK_HTML + "</body>");
}
return html + WATERMARK_HTML;
}
// 5 requests per hour per IP
const demoLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 5,
message: { error: "Demo limit reached (5/hour). Get a Pro API key at https://docfast.dev for unlimited access." },
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => req.ip || req.socket.remoteAddress || "unknown",
});
router.use(demoLimiter);
interface DemoBody {
html?: string;
markdown?: string;
css?: string;
format?: string;
landscape?: boolean;
margin?: { top?: string; right?: string; bottom?: string; left?: string };
printBackground?: boolean;
filename?: string;
}
function sanitizeFilename(name: string): string {
return name.replace(/[\x00-\x1f"\\\r\n]/g, "").trim() || "document.pdf";
}
// POST /v1/demo/html
router.post("/html", async (req: Request & { acquirePdfSlot?: () => Promise<void>; releasePdfSlot?: () => void }, res: Response) => {
let slotAcquired = false;
try {
const ct = req.headers["content-type"] || "";
if (!ct.includes("application/json")) {
res.status(415).json({ error: "Unsupported Content-Type. Use application/json." });
return;
}
const body: DemoBody = typeof req.body === "string" ? { html: req.body } : req.body;
if (!body.html) {
res.status(400).json({ error: "Missing 'html' field" });
return;
}
if (req.acquirePdfSlot) {
await req.acquirePdfSlot();
slotAcquired = true;
}
const fullHtml = body.html.includes("<html")
? injectWatermark(body.html)
: injectWatermark(wrapHtml(body.html, body.css));
const pdf = await renderPdf(fullHtml, {
format: body.format || "A4",
landscape: body.landscape || false,
printBackground: body.printBackground !== false,
margin: body.margin || { top: "0", right: "0", bottom: "0", left: "0" },
});
const filename = sanitizeFilename(body.filename || "demo.pdf");
res.setHeader("Content-Type", "application/pdf");
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", pdf.length);
res.send(pdf);
} catch (err: any) {
if (err.message === "QUEUE_FULL") {
res.status(503).json({ error: "Server busy. Please try again in a moment." });
} else if (err.message === "PDF_TIMEOUT") {
res.status(504).json({ error: "PDF generation timed out." });
} else {
logger.error({ err }, "Demo HTML conversion failed");
res.status(500).json({ error: "PDF generation failed." });
}
} finally {
if (slotAcquired && req.releasePdfSlot) req.releasePdfSlot();
}
});
// POST /v1/demo/markdown
router.post("/markdown", async (req: Request & { acquirePdfSlot?: () => Promise<void>; releasePdfSlot?: () => void }, res: Response) => {
let slotAcquired = false;
try {
const ct = req.headers["content-type"] || "";
if (!ct.includes("application/json")) {
res.status(415).json({ error: "Unsupported Content-Type. Use application/json." });
return;
}
const body: DemoBody = typeof req.body === "string" ? { markdown: req.body } : req.body;
if (!body.markdown) {
res.status(400).json({ error: "Missing 'markdown' field" });
return;
}
if (req.acquirePdfSlot) {
await req.acquirePdfSlot();
slotAcquired = true;
}
const htmlContent = markdownToHtml(body.markdown);
const fullHtml = injectWatermark(wrapHtml(htmlContent, body.css));
const pdf = await renderPdf(fullHtml, {
format: body.format || "A4",
landscape: body.landscape || false,
printBackground: body.printBackground !== false,
margin: body.margin || { top: "0", right: "0", bottom: "0", left: "0" },
});
const filename = sanitizeFilename(body.filename || "demo.pdf");
res.setHeader("Content-Type", "application/pdf");
res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
res.setHeader("Content-Length", pdf.length);
res.send(pdf);
} catch (err: any) {
if (err.message === "QUEUE_FULL") {
res.status(503).json({ error: "Server busy. Please try again in a moment." });
} else if (err.message === "PDF_TIMEOUT") {
res.status(504).json({ error: "PDF generation timed out." });
} else {
logger.error({ err }, "Demo markdown conversion failed");
res.status(500).json({ error: "PDF generation failed." });
}
} finally {
if (slotAcquired && req.releasePdfSlot) req.releasePdfSlot();
}
});
export { router as demoRouter };