CiteStat API Reference

Base URL: https://citestat.com (production) / http://localhost:3170 (development)

Authentication

Three auth methods, checked in order:

MethodHeader / ParamTenant
API KeyAuthorization: Bearer aiseo_xxx or ?api_key=aiseo_xxxKey's tenant
Session cookieSet by auth.erpfit.com SSO (.erpfit.com cookie) or local /api/auth/sign-in/emailUser's tenant
None—public (free tier)

Tier Limits

TierCredits/dayRate limitAPI Keys
Free105/min—
Pro10020/min5
AgencyUnlimited120/min5
InternalUnlimited120/minUnlimited
Credit costs: SEO scan = 1 credit, Content audit = 1 credit, AI render = 2 credits, Crawl = 5 credits. Note: The tier is the tenant's plan on every auth path (local key, auth.erpfit.com key, SSO session). Paid plans are activated by hand after a bank transfer (scripts/billing/activate.ts). A paid plan lasts one month per transfer and reads as free after tierExpiresAt; renewal notices are e-mailed before and after the end.
Note: Free tier gives 10 credits/day (resets daily). Exceeding quota returns HTTP 429 {"error":"Daily credit limit reached","code":"credit_limit","tier","used","limit"} (code tells it apart from the per-minute rate limit). Rate limits are per-endpoint per-IP.

Core Endpoints

POST /api/scan

Run an SEO audit on a single URL. Returns scores, findings, and grade.

Auth: API key (Authorization: Bearer <key>, create one at /dashboard/api-keys) or session — anonymous → 401 Cost: 1 credit (Free 10/day, Pro 100/day, Agency unlimited) Rate limit: 10 req/min per IP

The web scan result shows this call for the URL just scanned (block "Run this check from your own tools").

curl -X POST https://citestat.com/api/scan \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com", "skipPerf": false}'

Request body:

FieldTypeRequiredDescription
urlstringYesURL to audit
skipPerfbooleanNoSkip PageSpeed Insights checks (faster). The rules engine then does not run its Core Web Vitals / page-weight rules (LCP, CLS, INP, TBT, FCP, transfer size): an unmeasured metric neither passes nor fails, so rulesEngine.ruleChecks is lower. INP comes only from CrUX field data

Response: 200 OK

{
  "url": "https://example.com",
  "timestamp": "2026-06-05T10:30:00Z",
  "totalScore": 78,
  "grade": "B",
  "headline": {"base": 78, "thinContentDeduction": 0, "wordCount": 1240},
  "scanId": "clxyz...",
  "reportUrl": "/api/report/clxyz...",
  "publicReportUrl": "/api/report/p/abc123def456ghi789jkl012",
  "scores": [
    {"category": "On-Page", "score": 18, "maxScore": 20, "findings": [...]},
    {"category": "Performance (CWV)", "score": 15, "maxScore": 20, "findings": [...]},
    {"category": "Technical", "score": 12, "maxScore": 15, "findings": [...]},
    {"category": "Structured Data", "score": 10, "maxScore": 15, "findings": [...]},
    {"category": "GEO & AI", "score": 8, "maxScore": 15, "findings": [...]},
    {"category": "Content", "score": 15, "maxScore": 15, "findings": [...]}
  ],
  "findings": [
    {"category": "On-Page", "severity": "pass", "title": "Title tag optimal length", "detail": "56 characters"},
    {"category": "Technical", "severity": "critical", "title": "Missing HTTPS redirect", "detail": "HTTP version accessible", "fix": "Add 301 redirect"},
    {"category": "GEO", "severity": "low", "title": "Brand is not a known entity", "detail": "No Wikidata item has this domain as its official website ...", "fix": "...", "wikiSlug": "knowledge-graph"},
    {"category": "Technical", "severity": "low", "title": "No DMARC record", "detail": "_dmarc.example.com has no v=DMARC1 record ...", "fix": "...", "wikiSlug": "email-authentication"},
    {"category": "Technical", "severity": "low", "title": "Hosted in United States (AS64500 Example Hosting)", "detail": "IP 203.0.113.7 · United States · AS64500 Example Hosting. The page is written for visitors in Vietnam ... IP Geolocation by DB-IP (db-ip.com, CC BY 4.0).", "fix": "...", "wikiSlug": "hosting-location"},
    {"category": "Technical", "severity": "pass", "title": "Not on malware / phishing blocklists", "detail": "example.com is not named on 2 public blocklists. These are not Google's lists ... Sources: Phishing.Database (MIT); UT1 blacklists (CC BY-SA 4.0).", "wikiSlug": "malware-phishing"}
  ],
  "rulesEngine": {
    "total": 78,
    "grade": "B",
    "categories": [...],
    "ruleChecks": 312
  },
  "aiCitation": {
    "citability": 34,
    "citation": "The 2-3 sentences an AI Overview would quote (≤300 chars)",
    "passagesTotal": 14,
    "passages": [{"heading": "People also ask", "wordCount": 135, "citabilityScore": 50, "extractedAs": ["featured_snippet", "bing_copilot"]}],
    "locked": true
  },
  "nextPages": {
    "source": "sitemap",
    "total": 144,
    "sitemaps": null,
    "pages": ["https://example.com/pricing", "https://example.com/blog"]
  },
  "fieldData": {
    "scope": "page",
    "id": "https://example.com/",
    "assessment": "failed",
    "metrics": [{"key": "lcp", "p75": 2546, "rating": "needs-improvement", "goodShare": 0.7384, "poorShare": 0.0931, "core": true}]
  }
}

**aiCitation** (additive, 2026-10-21) is the AI Content Render preview, computed from the HTML the scan already fetched (no extra credit). passages is ranked best first: the free plan gets the best one only (locked: true when the page has more), paid plans up to 20. citability (0-100) is our own heuristic built from the passages, freshness, author, semantic HTML and images (/wiki/citability), not a forecast of real citations. Absent if the simulation failed. POST /api/render still returns the full simulation.

**credits** (additive, 2026-10-21; also on POST /api/content-audit) is today's use against the caller's plan, counted after this scan was saved: {"tier": "free", "used": 3, "limit": 10} (limit: null = unlimited plan). Absent when the scan could not be saved. The home page shows it under the result with links to the full report and PDF.

**nextPages** (additive, 2026-10-21) is up to 5 more pages of the same site to scan, from the sitemap and links the scan already fetched (no extra request, no credit). source: "sitemap" → total is the number of pages in the sitemap; source: "links" (sitemap index, or no sitemap) → internal links of the scanned page, total: null; sitemaps counts child sitemaps of an index. Shallowest first, never the scanned page, robots.txt-disallowed URLs left out. null when there is no other page.

**fieldData** (additive, 2026-10-24) is Google's real-user data for the page (Chrome UX Report, 28 days, 75th percentile), taken from the PageSpeed Insights call the scan already makes (no extra request, no credit, every plan). metrics in order lcp, inp, cls (the Core Web Vitals, core: true), then fcp, ttfb; p75 is ms, CLS unitless; goodShare/poorShare are 0-1. assessment is Google's rule: "passed" when LCP, INP and CLS are all good (INP may be missing), null when LCP or CLS is missing. scope: "origin" = the page has too few Chrome visits, so the numbers are the whole site's (id is then the origin). null = PageSpeed ran but CrUX has no data for the site; absent = performance was skipped or PageSpeed failed. Shown only — totalScore does not use it.

**How totalScore is derived** (headlineScore, packages/core/scoring.ts — one derivation for API, lazy report, CLI, MCP): totalScore = max(0, rulesEngine.total − thinContentDeduction), where the deduction is 40 points under 50 words, 30 under 200, 15 under 300, and 0 from 300 words. grade is totalScore on the A+/A/B/C/D/F scale. Every category point moves totalScore one-for-one — there are no caps. The MCP tools seo_scan, seo_compare and seo_report run the same pipeline (packages/core/seo-scan.ts), so they return this number, not their own. Without a rules-engine result (the standalone CLI), the base is the share of points earned over the non-skipped scores categories, so a skipPerf scan leaves Performance out instead of counting it as 0. A scores[] entry with skipped: true measured nothing — Performance without PageSpeed, and AI & Readability on a page under 50 words (SCAN-SHORT-01) — and reads N/A, not 0. headline shows the parts: base (the rules-engine total or the fallback share), thinContentDeduction and the wordCount it used.

**How rulesEngine.total is derived** (scoreResults, packages/core/rules-engine.ts): every rule counts in one of 8 weighted groups — technical 25 %, meta-tags 20 %, content 15 %, performance 15 %, common-files 10 %, structured-data 5 %, links 5 %, security 5 % — scored over the weights of all its rules. A rule file's own category maps to its group (scoreGroup(), packages/core/scoring.ts): meta/onpage/webmaster → meta-tags; crawl/mobile/ indexnow/geo → technical; robots-txt/sitemap/well-known → common-files; accessibility → content; schema → structured-data. Rules marked report_only (a feature was detected, e.g. name="bingbot") never score. rulesEngine.categories still lists the rule files' own categories. Until 2026-10-29 (SCAN-WEIGHT-01) only categories named like a group counted, so title, viewport, robots.txt and sitemap rules never moved the total.

Severity levels: critical, high, medium, low, pass


POST /api/content-audit

Dedicated content quality audit with detailed suggestions. Runs all content check modules plus additional checks (thin content, media richness, formatting, topic depth, CTA, outbound authority, content type classification).

Auth: API key or session Rate limit: 10 req/min per IP

curl -X POST https://citestat.com/api/content-audit \
  -H "Authorization: Bearer aiseo_xxx" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/blog/my-post", "locale": "en"}'

Request body:

FieldTypeRequiredDescription
urlstringYesPage URL to audit
keyphrasestringNoTarget keyphrase for density/distribution checks
localestringNovi or en (default: from Accept-Language)

Response: 200 OK — ContentAuditResult with sections, findings, and detailed suggestions.

Each finding may include a suggestions array with action, what, why, how, example, priority, and effort fields.


POST /api/keywords

Keyword ideas from Google or YouTube autocomplete, tuned for the Vietnamese market. Expands a seed through question templates (cách …, … là gì, how to …) — a free "People Also Ask" approximation — and optionally seed a … seed z. Monthly search volumes come from Google Ads Keyword Planner (KW-01): vi → Vietnam + Vietnamese, en → United States + English, 12-month average.

Auth: API key or session Rate limit: 10 req/min per IP. Upstream calls are throttled to 1/s and cached 7 days, so a cold seed takes ~11 s (default modes) or ~37 s with alphabet; a cached seed returns at once.

curl -X POST https://citestat.com/api/keywords \
  -H "Authorization: Bearer aiseo_xxx" \
  -H "Content-Type: application/json" \
  -d '{"seed": "cà phê phin", "lang": "vi"}'

Request body:

FieldTypeRequiredDescription
seedstringYesSeed keyword, 1–80 characters
langstringNovi (Vietnam, default) or en (US)
sourcestringNogoogle (default) or youtube
modesstring[]NoSubset of base, questions, alphabet (default: ["base","questions"])

Response: 200 OK

{
  "seed": "cà phê phin", "lang": "vi", "source": "google", "modes": ["base", "questions"],
  "ideas": [{ "keyword": "cách pha cà phê phin ngon", "modifier": "questions", "query": "cách cà phê phin", "isQuestion": true,
              "volume": { "avgMonthlySearches": 2400, "competition": "LOW", "competitionIndex": 12 } }],
  "questions": ["cách pha cà phê phin ngon"],
  "queriesRun": 11,
  "errors": [],
  "seedVolume": { "avgMonthlySearches": 6600, "competition": "HIGH", "competitionIndex": 68 },
  "volumes": { "status": "ok", "source": "google-ads-keyword-planner", "geo": "VN", "lockedCount": 0 }
}

Volumes: volumes.status is ok or unavailable (planner not configured or failed — the ideas still return). On ok, seedVolume and each shown idea's volume are an object, or null when Google has no data for that phrase. The Free plan gets volumes for the seed and the first 3 ideas; the other ideas carry no volume key and volumes.lockedCount counts them. Pro and Agency get every idea. Volumes are cached 7 days per keyword.

The source is unofficial: a failed upstream query is listed in errors and the rest still return. 502 only when every query failed.


POST /api/crawl

Multi-page site crawl. Discovers pages from sitemap + internal links, runs rules engine on each.

Each page is scored with the same rules context as POST /api/scan: the site files (robots.txt, sitemap, llms.txt, security.txt, ads.txt, favicon) and the http→https / www redirect probes are measured once for the site, the page's own technology detection and E-E-A-T links are set per page. A crawl runs no PageSpeed, so the Core Web Vitals rules are not scored (they are never counted as passing at an unmeasured 0). siteWideScore is the rules-engine score over every scanned page's results.

Auth: API key or session Rate limit: 10 req/min per IP

curl -X POST https://citestat.com/api/crawl \
  -H "Authorization: Bearer aiseo_xxx" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com", "maxPages": 10}'

Request body:

FieldTypeRequiredDescription
urlstringYesSite root URL
maxPagesnumberNoMax pages to crawl (default 10, max 50)

Response: 200 OK — Per-page scores + site-wide issues (duplicate titles, thin content, etc.)


POST /api/render

Simulate how AI search engines extract and cite content from a page.

Auth: None required Rate limit: 10 req/min per IP

curl -X POST https://citestat.com/api/render \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com"}'

Request body:

FieldTypeRequiredDescription
urlstringYesURL to analyze
htmlbooleanNoReturn rendered HTML instead of JSON

Response: 200 OK

{
  "overallCitability": 72,
  "passages": [
    {"heading": "What is SEO?", "wordCount": 245, "citabilityScore": 85}
  ],
  "semanticHtml": {"score": 68},
  "freshnessSignals": {"freshness": "recent"},
  "authorSignals": {"name": "John Doe", "hasSchema": true},
  "aiOverview": {
    "bestPassage": {...},
    "citation": "According to...",
    "score": 78
  },
  "featuredSnippet": {"type": "paragraph"},
  "peopleAlsoAsk": ["How to check SEO?", ...]
}

Reports

GET /api/report/:id

Returns the full HTML report for a scan.

Auth (SEC-08, 2026-10-25): the scan's own account — a session or an API key (Authorization: Bearer, no credit). No session/key → 401 (the body's hint names the share link); another account → 403. Scans with no owner (tenant public) stay open. To give a report to someone without an account, send its publicReportUrl.

curl -H "Authorization: Bearer YOUR_API_KEY" https://citestat.com/api/report/clxyz...

GET /api/report/p/:token

Returns the HTML report via public share token. No authentication required.

Reports are auto-published on creation — the publicReportUrl is returned in scan responses.

curl https://citestat.com/api/report/p/abc123def456ghi789jkl012

GET /api/report/p/:token/pdf

The PDF of the same shared report. No authentication required.

GET /api/report/sample

The example report: the newest completed SEO scan of CiteStat's own home page, unbranded, with an "Example report" banner that links to a scan and to /pricing. No authentication. 404 when no such scan is saved. Never serves another site.

Query: lang=en|vi (default en); from=<place> is ignored by the API and only counted in the logs.

curl https://citestat.com/api/report/sample?lang=en

GET /api/report/:id/pdf

Returns a PDF version of the scan report.

Auth: as GET /api/report/:id.

curl -H "Authorization: Bearer YOUR_API_KEY" -o report.pdf https://citestat.com/api/report/clxyz.../pdf

White-label (Agency, 2026-10-24): when the scan's account is on a plan with white-label reports and has set a brand (PUT /api/dashboard/report-brand), all four report routes carry that name (and site) in place of CiteStat / ERPFit. A lapsed plan's reports read as ours again; the stored brand is kept.


History

Every History route needs an API key or a session and returns your own scans only — another account's scans of the same domain are not listed, and another account's scan id answers 404. No credit is spent. Anonymous → 401 (these routes were open until 2026-10-20).

GET /api/sites/:domain/history

Paginated scan history for a domain.

curl -H "Authorization: Bearer $KEY" "https://citestat.com/api/sites/example.com/history?limit=20&offset=0"

Response:

{
  "domain": "example.com",
  "scans": [{"id": "...", "url": "...", "score": 78, "grade": "B", "scannedAt": "..."}],
  "total": 42,
  "limit": 20,
  "offset": 0
}

GET /api/sites/:domain/latest

Most recent scan for a domain.

GET /api/scans/:id

Full scan result by ID (includes result JSON with all findings).

GET /api/sites/:domain/diff

Diff the two most recent scans for a domain. Returns scoreDelta, gradeChanged, per-category deltas, newFindings, resolvedFindings (both sorted by severity), and unchangedCount. 404 if fewer than two scans exist.

GET /api/scans/:id/diff

Diff a scan against another (?against=ID) or, by default, its predecessor scan for the same site. Same diff shape as above. 404 if there is no earlier scan.


Search Console (GSC)

Real search-performance data. Requires server-side Google OAuth credentials (GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET) and a per-tenant connection. See docs/260607-gsc-foundation.md for setup.

GET /api/google/status

Session auth. Reports { configured, connected, email, scope } for the signed-in user's tenant.

GET /api/google/connect

Session auth. Redirects to the Google consent screen. On approval, the callback stores the tenant's tokens.

GET /api/google/callback

OAuth redirect target (Google calls this). Redirects back to the dashboard with ?google=connected|error|expired.

GET /api/google/properties

Session auth. Lists the connected account's verified Search Console properties as { properties: [{ siteUrl, domain }] } — the dashboard's site picker for opportunities. Status codes: 503 not configured, 409 not connected.

DELETE /api/google/disconnect

Session auth. Removes the tenant's Google connection.

GET /api/sites/:domain/performance

API key or session auth. Returns a Search Analytics summary (totals, top queries, top pages, daily trend) for the domain. Query params: days (7–90, default 28), refresh=true to force a live pull (otherwise serves a cached snapshot under 24h old). Status codes: 503 not configured, 409 not connected, 404 no matching Search Console property for the domain.

POST /api/sites/:domain/inspect

API key or session auth. Inspects URLs for indexation status via the GSC URL Inspection API. Body: { url: "..." } for a single URL or { urls: [...] } for batch (max 100). Paths without scheme are expanded using the domain. Returns per-URL verdict, coverage state, robots/indexing state, last crawl time, and fetch status. Rate-limited to ~2,000 requests/day per GSC property. Status codes: 503 not configured, 409 not connected, 404 no property.

GET /api/sites/:domain/opportunities

API key or session auth. Detects SEO opportunities from live GSC data. Query param: days (7–90, default 28). Returns four opportunity types: striking-distance (position 5–20, high impressions), CTR gap (below expected CTR curve), zero-click (impressions but 0 clicks), and keyword cannibalization (same query on multiple pages in one language section — / and /en/ are alternates, not rivals). Sorted by estimated traffic upside; an item worth under one click is dropped.

"High impressions" is relative to the site: the minimums (striking-distance 100, CTR gap 50 + 5 clicks upside, zero-click 50, cannibalization 100) hold from 20,000 impressions in the period and scale down to 20% of that for a smaller site. The response carries the values used: thresholds: { siteImpressions, scale, strikingImpressions, ctrGapImpressions, ctrGapUpside, zeroClickImpressions, cannibalizationImpressions }.

Optional page=<url> (the scan detail sends the scanned URL): the response adds page: { page, clicks, impressions, ctr, position, topQueries[≤5] } | null (null = no impression for that URL in the period; scheme, www., fragment and trailing slash are ignored when matching) and lists that page's opportunities first, each with onPage: true (the rest onPage: false, upside order kept). Same three Search Analytics pulls, same 1 credit.

GET /api/sites/:domain/gsc-diff

API key or session auth. Compares the two most recent GSC performance snapshots for the domain. Returns totals deltas, new/lost/improved/declined queries and pages. Requires at least 2 stored snapshots (from /api/sites/:domain/performance calls).

POST /api/sites/:domain/rank-findings

API key or session auth. Re-ranks SEO findings by traffic weight. Body: { findings: [{ category, title, severity, affectedUrls? }] }. Returns findings sorted by severity × trafficWeight, where trafficWeight (0.3–2.0) is derived from the affected pages' GSC impressions.


Bing Webmaster Tools

Bing's index feeds Microsoft Copilot's AI citations. Auth is a Bing Webmaster API key — stored per-tenant via connect, or the server-wide BING_WEBMASTER_API_KEY. The env key is the owner's personal Bing key, so its fallback is gated to the owner tenant (BING_OWNER_EMAIL, default olragon@gmail.com); every other tenant must connect its own key. A tenant's own key always wins. Connect/disconnect/status are session-only; the data + submit endpoints accept an API key or session.

GET /api/bing/status

Session auth. { configured, connected, ownKey, label, connectedAt } — configured/connected reflect whether the server env key is present; ownKey is true when this tenant stored its own key.

POST /api/bing/connect

Session auth. Body { apiKey, label? }. Validates the key against Bing (GetUserSites) before storing. Returns { connected, verifiedSites }.

DELETE /api/bing/disconnect

Session auth. Drops the tenant's stored key.

API key or session. Bing inbound links + referring-domain rollup ({ totalInboundLinks, referringDomains, topLinkedPages, topInboundLinks, topReferringDomains }). refresh=true forces a live pull (else a cached snapshot under 24h). 409 not connected, 404 no verified Bing property.

driver=commoncrawl (default bing) answers for any domain from the Common Crawl web graph instead — { domain, driver, backlinks: { inCrawl, harmonicCentralityRank, pagerankRank, nHosts, referringDomains, topReferringDomains, meta: { release } } }. It reads a local DuckDB only; a server without one answers 503 { code: "cc_unavailable" }. Production carries a slim ranks file (BL-SCORE-03): both ranks are set, nHosts and the referring-domain fields are null there. Unknown driver → 400.

GET /api/sites/:domain/bing-performance

API key or session. Bing search performance (totals, topQueries, topPages, dailyTrend). Same caching + status codes as backlinks.

POST /api/sites/:domain/bing/submit

API key or session. Body { urls: [] } (or single url). Submits to Bing for (re)crawl via SubmitUrl/SubmitUrlBatch. Returns { submitted, siteUrl }.


Domain Authority

GET /api/sites/:domain/authority

API key or session; costs a credit like a scan. CiteStat Authority 0–100 for any domain, built from free signals only: Common Crawl link-graph ranks (where the server has the DuckDB), the Cloudflare Radar popularity bucket, and phishing blocklists (TOX-01) as a penalty. Cached 24 h per domain; refresh=true re-reads. Invalid domain → 400.

{
  "domain": "vnexpress.net",
  "authority": {
    "score": 71, "confidence": "low", "percentile": null,
    "components": { "radar": 71.3 },
    "flags": ["uncalibrated"],
    "calibration": { "id": "prior-261016", "rho": null, "n": 0 }
  },
  "signals": { "radar": { "bucketRank": 20000 }, "spamListed": false },
  "consulted": { "cc": null, "opr": false, "radar": true, "blocklists": ["phishing-database", "ut1-phishing"] },
  "blocklistHits": [],
  "errors": [],
  "computedAt": "2026-10-19T04:00:00.000Z"
}
  • consulted says which sources answered — read confidence with it. cc: null

means this server has no link graph, so there is no percentile and confidence stays low; it is not a "not in graph" verdict (that is the flag not-in-link-graph). Without the link graph a domain outside Radar's top 200k gets score: null, confidence: "none" — no source ranked it, so no number.

  • flags: not-in-link-graph (cap 20), link-graph-only (cap 70),

pagerank-divergence (×0.85, link-scheme fingerprint), spam-listed (×0.7), uncalibrated (prior curves, not yet fitted to a Moz DA sample).

  • calibration.validation (optional, BL-SCORE-02): how well the score's ORDER agrees

with an independent link index — { "against": "majestic-million", "id", "rho", "n" }, Spearman rho vs Majestic Million referring subnets on a sample of the top 1M domains. It validates order, not the 0–100 level, and says nothing about domains outside the top 1M.

  • It is not Moz DA or Ahrefs DR and must not be shown as either.

IndexNow

(Re)crawl notification for Bing / Yandex / Seznam / Naver / Yep / Amazon / Internet Archive — one submission is shared with all of them; a 200 means "received", not "indexed" (Google does not consume IndexNow). One host key per site; the site owner publishes <key>.txt at their root and CiteStat submits on their behalf. All endpoints take an API key or session.

www is its own host. IndexNow treats www.example.com and example.com as two hosts: the payload host, the key file and every URL must be the same one. :domain names the site (bare); host in the responses is the exact host the key serves.

GET /api/sites/:domain/indexnow

Current key state: { configured, host, keyLocation, keyFile, verified, verifiedAt }.

POST /api/sites/:domain/indexnow/key

Generate + store a host key (or bring your own via body { key?, keyLocation? }). Without a keyLocation, the key goes on the host the site's home page lands on: a site whose apex redirects to www gets https://www.<domain>/<key>.txt. A brought keyLocation must be on <domain> or www.<domain> (else 400). Returns { key, host, keyLocation, keyFile, instructions } — publish the file, then verify.

POST /api/sites/:domain/indexnow/verify

Fetches keyLocation (public addresses only) and confirms it serves exactly the key. A file that only answers after a redirect to the other host (apex → www) does not verify. Marks the key verified on success. { ok, statusCode, error? }.

POST /api/sites/:domain/indexnow/submit

Body { urls: [] }. Submits to api.indexnow.org. Enforces ≤10 000 URLs and that every URL is on the key's exact host (an apex URL in a www site's batch is refused before the POST, with the reason). Returns { ok, submitted, statusCode, engines }.

DELETE /api/sites/:domain/indexnow

Drops the site's IndexNow key.


Dashboard API

All dashboard endpoints require session authentication (cookie-based via better-auth).

GET /api/dashboard/overview

Stats cards: domains, scans this month, API keys, tier info, recent scans. usage.tierExpiresAt (ISO date or null) and usage.planDaysLeft give a monthly plan's end. After an unrenewed end, usage.lapsedTier (pro/agency) and usage.lapsedAt (ISO date) name the plan that ended; both are null otherwise. Users of a paid tenant get a renewal e-mail 7 days and 1 day before the end and once after it (packages/db/renewal.ts).

GET /api/dashboard/domains

List user's domains with last scan score and schedule info.

POST /api/dashboard/domains

Add a domain. Body: {"url": "https://example.com"}

DELETE /api/dashboard/domains/:id

Remove a domain.

GET /api/dashboard/domains/:id/scans

Paginated scan history for a specific domain. Query: ?limit=20&offset=0 Response: { domain, tier, scans: [{ id, url, kind, seoScore, seoGrade, scannedAt, durationMs, field? }], total, limit, offset }. Additive 2026-10-24: tier (the account's plan) and, on SEO scans, field — that scan's saved real-user p75 { scope: "page"|"origin", id, assessment, lcp?, inp?, cls? } or null (same shape as the trend route's points[].field). The domain page draws its real-user trend from it.

GET /api/dashboard/domains/:id/schedule

The domain's recurring scan (SCHED-01) — session, own tenant only, no credit. Response: { domain, cadence: "daily"|"weekly"|"monthly"|null, lastRunAt, nextRunAt, tier, allowed, cadences }. allowed is true on plans sold with recurring scans (Agency).

PUT /api/dashboard/domains/:id/schedule

Body { "cadence": "daily" | "weekly" | "monthly" | null } (null = off). Same response as GET. 400 other values (no free-form cron) · 403 { code: "plan_required" } switching ON without the plan (OFF is always allowed) · 409 { code: "schedule_limit" } over 50 active per account · 404 not your domain. A scheduled scan runs within 15 minutes of switching on, then once per cadence; it uses 1 credit and the account's users get an e-mail when the score falls 5+ points below the previous scan.

GET /api/dashboard/report-brand

The account's white-label report brand (REPORT-02 slice 19) — session, own tenant only, no credit. Response: { brand: { name, url } | null, tier, allowed }. allowed is true on plans sold with "White-label reports" (Agency).

PUT /api/dashboard/report-brand

Body { "name": "Saigon Growth", "url": "growth.example.com" } (url optional; a bare domain becomes https://…; only http/https). { "name": "" } clears. Same response as GET. 400 name over 60 characters, bad url or body · 403 { code: "plan_required" } setting a name without the plan (clearing is always allowed).

GET /api/dashboard/scans/:id

Scan detail with full result JSON. Tenant ownership enforced. Also returns siteId and (additive, 2026-10-24) tier — the account's current plan, used by the web UI to pick the Core Web Vitals follow-up.

GET /api/dashboard/scans/:id/trend

Score trend for the scan's site: this scan and up to 9 earlier ones of the same kind, oldest first. kind is "seo" (/api/scan) or "content" (/api/content-audit) — two score scales, never mixed. Shown under every scan and content-audit result (home + scan detail); free plans also see the Pro offer. No credit. /api/sites/:domain/{history,latest,diff} return SEO scans only; dashboard domain scan lists carry kind on each row. Additive (2026-10-24): each point of an SEO trend carries field — that scan's Chrome UX Report p75 for the Core Web Vitals (lcp/inp ms, cls), with scope (page | origin), the CrUX id and assessment; null when the scan saved no field data. Content-audit points have no field.

{"domain": "example.com", "siteId": "...", "kind": "seo", "tier": "free", "total": 12,
 "points": [{"id": "...", "score": 62, "grade": "C", "scannedAt": "...", "field": null},
            {"id": "...", "score": 71, "grade": "B", "scannedAt": "...",
             "field": {"scope": "page", "id": "https://example.com/", "assessment": "failed", "lcp": 2546, "inp": 158, "cls": 0.11}}]}

GET /api/dashboard/api-keys

List API keys (masked, with usage info).

POST /api/dashboard/api-keys

Create API key. Body: {"name": "my-key"}. Returns full key once.

PATCH /api/dashboard/api-keys/:id

Update key name or enabled status. Body: {"enabled": false}

DELETE /api/dashboard/api-keys/:id

Delete an API key.

GET /api/dashboard/metrics

30-day analytics: scan trend, top domains, API logs, endpoint breakdown, quota usage.


Admin API

Requires Authorization: Bearer {AISEO_ADMIN_SECRET}. The bearer path is OFF unless AISEO_ADMIN_SECRET is set (16+ chars) — there is no default. A signed-in user with role: "admin" also passes.

POST /api/admin/tenants

Create a tenant. Body: {"name": "Acme", "slug": "acme", "tier": "free"}. A paid tier (pro, agency) is refused here — set it with PATCH /api/admin/tenants/:id/tier so it gets an end date and a ledger row.

POST /api/admin/api-keys

Create an API key for a tenant. Body: {"tenantId": "...", "name": "prod", "rateLimit": 100}

GET /api/admin/tenants/:id/usage

Tenant usage stats and tier limits.

GET /api/admin/tiers

List all tier definitions and limits.

PATCH /api/admin/tenants/:id/tier

Set a tenant's plan — the same path as scripts/billing/activate.ts. Body: {"tier": "pro", "months": 1, "bankRef": "FT26291ABC"}. A paid tier needs bankRef (the bank transaction ID); it sets the plan's end date and writes one plan_payment ledger row in one transaction. A bankRef already in the ledger → 409 and nothing changes. free / unlimited need no bankRef and clear the end date. A new paid term e-mails every user of the tenant an activation notice (plan, amount, bank ref, end date; not a VAT invoice); the response's notice = {sent: [...], failed: [...]} (null for an unpaid tier or a duplicate) — a failed address means the plan IS active and the client must be told by hand.

GET /api/admin/billing

Transfers to expect (offline ordering, no order records): awaiting[] = paid plans ending within 7 days (state: "ending") or lapsed within 30 days ("lapsed"), soonest first, each with amountVnd, memo, emails and the activate command to run once the transfer shows on the statement. active = {count, monthlyVnd} of running paid plans. recentPayments[] = the last 20 ledger rows. CLI: scripts/billing/due.ts.


Queue

GET /ws/scan/:jobId

Poll job status (WebSocket upgrade available via Bun.serve).

GET /api/queue/status

Queue health: {"pending": 0, "running": 1}


Auth

Primary auth is auth.erpfit.com SSO — the browser redirects to auth.erpfit.com/sign-in, which sets a shared .erpfit.com session cookie. Local better-auth sign-up/sign-in is available as a fallback.

POST /api/auth/sign-up/email

Register (local fallback). Body: {"name": "...", "email": "...", "password": "..."}

POST /api/auth/sign-in/email

Login (local fallback). Body: {"email": "...", "password": "..."}. Sets session cookie.

POST /api/auth/sign-out

Logout. Clears session cookie.

GET /api/auth/me

Check current session. Returns {"user": {...}} or {"user": null}.


MCP (Model Context Protocol)

POST /api/mcp

MCP Streamable HTTP endpoint. Requires API key auth.

# Initialize session
curl -X POST https://citestat.com/api/mcp \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'

Tools: seo_scan, seo_render, seo_compare, seo_report, seo_schedule.

Credits: seo_scan / seo_report 1, seo_compare 1 per URL — the same as POST /api/scan, and each scan is saved to the key's account. A call that today's remaining credits cannot cover returns a tool result with isError: true (no scan runs). Usage lists each call as /api/mcp/<tool>.

See MCP docs for full tool reference.

GET /api/mcp

Returns MCP server info (no auth required).

DELETE /api/mcp

Closes an MCP session. Send Mcp-Session-Id header.


CLI

Install the CiteStat CLI:

curl -fsSL https://citestat.com/install.sh | sh

The CLI can also serve as an MCP stdio server: aiseo mcp

See aiseo --help for all commands.


Pricing page beacon

POST /api/pay-step

Internal: the pricing page sends it with navigator.sendBeacon on a trusted click on a payment step. Body (form-encoded): step=qr|copy|mail&plan=pro|agency|none. The server logs one journal line, [pay] <step> plan=<plan> ua=<bot|browser|none>, which scripts/growth/funnel.ts counts. It stores nothing: no IP, no UA string, no API-log row. It always answers 204 with no body, also for a body it does not accept. No API key. (FUNNEL-PAY-01)


Health

GET /api/health

Returns {"status": "ok", "db": "connected"} or 503 if DB is down.


Error Responses

StatusMeaning
400Bad request (missing/invalid params)
401Invalid API key or unauthorized
403Access denied (wrong tenant)
404Not found
429Rate limit or daily credit quota exceeded
500Server error

All errors return: {"error": "description"}