Free early-access launch: LAUNCH_MODE policy, CRO, pipeline hardening, AI-SEO, ops

- launch.ts policy: LAUNCH_MODE=free_early_access default; effective access =
  published && (free || early); intended tier (access) never rewritten
- Billing off server-side: /api/subscribe 503 honest copy; subscribe CTAs
  render disabled 'قريباً' from first paint; /subscription early-access panel
  + /api/notify (LaunchNotifications) with honest 503 when mail transport off
- Signup trust: verification email at signup (Users afterChange), no
  confirm-password, 429 message fidelity, typo suggestion, live password hint
- Agent pipeline: pickFields strips access/readingMinutes, sourceId dedup,
  secret-scan 422 (pattern names only), string-content rejected (was silently
  replaced), publish stays explicit opt-in
- lexical.ts: root unwrap fix — lexicalToText/countLexicalWords returned 0
  for real serialized trees (secret scan + readingMinutes were inert)
- llms-full.txt: fetchIndexDocs(true) — bodies were never selected
- Content honesty: contentType/authorName/sourceId fields + migration,
  readingMinutes computed at write (160 wpm) + backfill script, byline,
  'حُدّث' freshness
- SEO/AI-SEO: metadata rewrite (published-only, og:image 1200x630), Article +
  BreadcrumbList + FAQPage + Organization JSON-LD, isAccessibleForFree honest,
  table renderer, robots AI-crawler policy (10 named bots), llms.txt +
  llms-full.txt, /topics/* hubs + sitemap, noindex auth pages, www 301
- Ops: backup-db.sh (restore rehearsed on VPS), docs copies (launch
  readiness + marketing audit + owner-inputs for L-03), GLOSSARY.md entries

Verified: tsc --noEmit 0, npm run build 0, local smoke (ghost VIP read,
subscribe/notify/agent APIs, signup token, 429 on 6th, llms/topics/sitemap,
og:image/JSON-LD)
This commit is contained in:
AHMED
2026-10-10 18:03:45 +03:00
parent 82414e8a93
commit 0161924088
57 changed files with 4042 additions and 402 deletions
+11
View File
@@ -27,3 +27,14 @@ export function minutesLabel(n: number | null | undefined): string {
if (value === 2) return 'دقيقتان'
return `${formatNumber(value)} ${value % 100 >= 3 && value % 100 <= 10 ? 'دقائق' : 'دقيقة'}`
}
/* Content-type badge labels (L-09). Null for unset/unknown — no byline invented. */
export function contentTypeLabel(value: string | null | undefined): string | null {
switch (value) {
case 'note': return 'ملاحظة تقنية'
case 'tutorial': return 'دليل عملي'
case 'case_study': return 'تجربة موثقة'
case 'comparison': return 'مقارنة'
default: return null
}
}
+17
View File
@@ -0,0 +1,17 @@
/* Single source of launch policy (L-01/L-02).
Free early access is a server-side policy, never a data rewrite: the
intended VIP tier stays in the DB (`access: 'vip'`) and only becomes
enforced again when billing turns on. Rollback / paid transition =
set LAUNCH_MODE=paid + the Stripe env vars and redeploy. No timers,
no date logic — idempotent by construction. */
export const billingEnabled = (): boolean =>
process.env.LAUNCH_MODE === 'paid' &&
Boolean(process.env.STRIPE_SECRET_KEY) &&
Boolean(process.env.STRIPE_WEBHOOK_SECRET)
export const freeEarlyAccess = (): boolean => !billingEnabled()
/* Configurable Arabic reading rate (words/minute); revisit after reader
feedback. Used by the Posts beforeChange hook and the backfill script. */
export const READING_WORDS_PER_MINUTE = 160
+133
View File
@@ -0,0 +1,133 @@
/**
* Helpers over serialized Lexical richText JSON (Payload's editor state).
* A serialized tree is `{ root: { children: [...] } }`; text lives on
* `{ text }` nodes, nesting happens via `{ children }`.
*/
export type Node = {
type?: string
text?: string
children?: Node[]
tag?: string
url?: string
listType?: string
code?: string
headerState?: number
}
/** Root `children` of a serialized tree, narrowed at runtime. */
function rootChildren(data: unknown): Node[] | null {
if (data === null || typeof data !== 'object' || !('root' in data)) return null
const root: unknown = data.root // unknown via `in` narrowing — no shape assumed
if (root === null || typeof root !== 'object' || !('children' in root)) return null
const children: unknown = root.children
if (!Array.isArray(children)) return null
// Boundary: the array is the editor's serialized node list; every access
// below goes through Node's all-optional contract, so nothing unchecked.
const nodes: Node[] = children
return nodes
}
/** Concatenated text of every text node (secret scanning, llms extraction). */
export function lexicalToText(content: unknown): string {
let out = ''
const walk = (node: unknown): void => {
if (node === null || typeof node !== 'object') return
if ('text' in node && typeof node.text === 'string') out += node.text + '\n'
if ('children' in node && Array.isArray(node.children)) {
for (const child of node.children) walk(child)
}
}
// Serialized trees wrap nodes in `root` — walk it, not the wrapper.
if (content !== null && typeof content === 'object' && 'root' in content) {
walk((content as { root: unknown }).root)
} else {
walk(content)
}
return out
}
/** Count whitespace-delimited words across all text nodes of a Lexical tree. */
export function countLexicalWords(content: unknown): number {
let words = 0
const walk = (node: unknown): void => {
if (node === null || typeof node !== 'object') return
if ('text' in node && typeof node.text === 'string') {
words += node.text.trim().split(/\s+/).filter(Boolean).length
}
if ('children' in node && Array.isArray(node.children)) {
for (const child of node.children) walk(child)
}
}
// Same root unwrap as lexicalToText.
if (content !== null && typeof content === 'object' && 'root' in content) {
walk((content as { root: unknown }).root)
} else {
walk(content)
}
return words
}
export function innerText(nodes?: Node[]): string {
return (nodes || []).map(n => (n.type === 'text' ? n.text || '' : innerText(n.children))).join('')
}
/** H2 headings — TOC and the paid-mode paywall preview. */
export function extractH2s(data: unknown): string[] {
const children = rootChildren(data)
if (!children) return []
return children
.filter(n => n.type === 'heading' && (n.tag || 'h2') === 'h2')
.map(n => innerText(n.children))
}
function tagLevel(tag?: string): number {
const n = Number.parseInt((tag ?? 'h2').replace('h', ''), 10)
return Number.isFinite(n) && n >= 1 && n <= 6 ? n : 2
}
/**
* Plain-text rendering for llms-full.txt: headings → `## `, paragraphs and
* list items → lines, code → fenced blocks, table rows → `| a | b |`.
*/
export function lexicalToPlain(data: unknown): string {
const children = rootChildren(data)
if (!children) return ''
const lines: string[] = []
for (const n of children) {
switch (n.type) {
case 'heading':
lines.push(`${'#'.repeat(tagLevel(n.tag))} ${innerText(n.children)}`.trim())
break
case 'paragraph':
lines.push(innerText(n.children).trim())
break
case 'list':
for (const item of n.children || []) lines.push(`- ${innerText(item.children).trim()}`)
break
case 'listitem':
lines.push(`- ${innerText(n.children).trim()}`)
break
case 'code':
lines.push('```\n' + (n.code ?? innerText(n.children)) + '\n```')
break
case 'table':
for (const row of n.children || []) {
const cells = (row.children || []).map(cell => innerText(cell.children).trim().replace(/\|/g, '\\|'))
lines.push(`| ${cells.join(' | ')} |`)
}
break
case 'quote':
lines.push(`> ${innerText(n.children).trim()}`)
break
case 'horizontalrule':
lines.push('---')
break
default: {
const text = innerText(n.children).trim()
if (text) lines.push(text)
}
}
}
return lines.filter(line => line !== '').join('\n\n')
}
+61
View File
@@ -0,0 +1,61 @@
import { getPayload } from 'payload'
import configPromise from '@payload-config'
import { TOPICS, topicsFor, type TopicKey } from '@/lib/topics'
export type IndexDoc = {
id: number | string
title: string
slug: string
dek: string
access: 'free' | 'vip'
category: string
level: string
publishedAt: string | null
updatedAt: string | null
/** Present only when requested via fetchIndexDocs(true). */
content?: unknown
}
/** Published posts, public read path — no overrideAccess (drafts stay hidden,
* and the content field's own read ACL decides body availability). */
export async function fetchIndexDocs(withContent = false): Promise<IndexDoc[]> {
const payload = await getPayload({ config: configPromise })
const { docs } = await payload.find({
collection: 'posts',
where: { status: { equals: 'published' } },
depth: 0,
limit: 500,
sort: '-publishedAt',
select: {
title: true,
slug: true,
dek: true,
access: true,
category: true,
level: true,
publishedAt: true,
updatedAt: true,
...(withContent ? { content: true } : {}),
},
})
return docs as unknown as IndexDoc[]
}
export const SITE_TITLE = 'أنور بآي — أدلة الذكاء الاصطناعي العملي بالعربية'
export const SITE_INTRO = 'دليلك العربي للذكاء الاصطناعي العملي: وكلاء، نماذج، وأدوات.'
/** Topic-grouped markdown index lines; a post can appear under several topics. */
export function renderIndexSections(docs: IndexDoc[], markVip: boolean): string {
const lines: string[] = []
for (const topic of TOPICS) {
const items = docs.filter(doc => topicsFor(doc).includes(topic.key))
if (items.length === 0) continue
lines.push(`## ${topic.label}`, '')
for (const doc of items) {
const suffix = markVip && doc.access === 'vip' ? ' (دليل للأعضاء)' : ''
lines.push(`- [${doc.title}${suffix}](/posts/${doc.slug}): ${doc.dek}`)
}
lines.push('')
}
return lines.join('\n')
}
+39
View File
@@ -1,3 +1,42 @@
/* Generic text-only send over the same Cloudflare Email Sending REST call —
used by /api/notify for the launch-notification confirmation. Single-shot,
honest { sent: false } on any failure; no retry. */
export async function sendMail(to: string, subject: string, text: string): Promise<{ sent: boolean }> {
const apiToken = process.env.CLOUDFLARE_API_TOKEN
const accountId = process.env.CLOUDFLARE_ACCOUNT_ID
if (!apiToken || !accountId) return { sent: false }
try {
const res = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/email/sending/send`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
to,
from: { address: process.env.MAIL_FROM ?? 'noreply@anwarpy.ai', name: 'أنور بي آي' },
subject,
text,
}),
})
if (!res.ok) {
console.error('cloudflare email sending failed:', res.status, await res.text())
return { sent: false }
}
const json = (await res.json()) as { success?: boolean }
if (!json.success) {
console.error('cloudflare email sending rejected:', JSON.stringify(json))
return { sent: false }
}
return { sent: true }
} catch (err) {
console.error('cloudflare email sending threw:', err)
return { sent: false }
}
}
/* Cloudflare Email Sending (REST) — activates only when CLOUDFLARE_API_TOKEN
and CLOUDFLARE_ACCOUNT_ID are set. Without them, sendVerificationEmail
returns { sent: false } and the UI degrades to a clear status message; the
+31
View File
@@ -0,0 +1,31 @@
/**
* L-05: reject agent content that looks like a leaked credential before it
* is stored or published. `scanForSecrets` returns matched PATTERN NAMES
* only — never the matched values (those must not be echoed anywhere).
*/
const PATTERNS: readonly (readonly [string, RegExp])[] = [
['aws_access_key', /AKIA[0-9A-Z]{16}/],
['pem_private_key', /-----BEGIN [A-Z ]*PRIVATE KEY-----/],
['openai_api_key', /sk-[A-Za-z0-9]{20,}/],
['github_token', /ghp_[A-Za-z0-9]{36}/],
['generic_credential', /(?:password|passwd|api[_-]?key|secret)\s*[:=]\s*\S+/i],
] as const
export function scanForSecrets(text: string): string[] {
const names: string[] = []
for (const [name, re] of PATTERNS) {
if (re.test(text)) names.push(name)
}
return names
}
/** Scan the strings an agent can set; returns pattern names across all targets. */
export function scanAgentPayload(targets: (string | undefined | null)[]): string[] {
const names = new Set<string>()
for (const target of targets) {
if (typeof target !== 'string') continue
for (const name of scanForSecrets(target)) names.add(name)
}
return [...names]
}