# Website blog CMS: plan

Status: **approved 9 Nov 2026** (decisions below are the owner's answers).
**All four sprints built 9 Nov 2026** (B1, B2 backend; W1 website; F1 web app), none
committed yet. See "Progress" and "Going live" at the end.

## Goal

The marketing team writes, schedules and updates posts for
https://hostelcare.co.in/resources/blog/ inside the HostelCare web app, without a
developer. Publishing a post rebuilds and deploys the website by itself through
the website pipeline (`hostelcare-website/.github/workflows/deploy.yml`, live
since 9 Nov), and the editor sees when it is live.

This copies the design already running for GymCare (`gympro-backend`
`docs/blog-cms-plan.md`, website on `gymcare-website-astro` `origin/deploy`),
adapted to HostelCare's stack, and fixes the problems found in the GymCare build
(listed at the end).

## How it works

```
 Editor (web app)            API server                      GitHub              hostelcare.co.in
 ──────────────────          ───────────────────────         ───────────         ────────────────
 write / save draft  ──▶  BlogPost (+ revision per save)
 Publish             ──▶  checks pass → status published
                          or scheduled (publishAt later)
                          job every 60 s: due scheduled
                          posts → published
                          one pending BlogBuild ──────▶  workflow_dispatch
                                                         deploy.yml on `deploy`
                                                         Astro build reads  ◀── GET /api/blog-cms/feed
                                                         (feed token), copies       (published posts,
                                                         images in, builds          image links valid
                                                         pages, rsync ─────────────▶ 10 min)
                          job polls the run ◀──────────  success / failure
 list shows "Live" / "Failed, try again"
```

- **Fully static site, as today.** Posts are fetched only at build time; the site
  never calls the API at runtime for the blog, so the API being slow can't slow
  the site.
- **Markdown is the stored format** (GFM). The editor is visual (TipTap) with a
  Markdown view; images can only come from the media library.
- **No raw HTML** reaches the site: the server refuses HTML tags in the body and
  the website renders Markdown without raw HTML, so an editor can't inject
  scripts into the public site.
- **Images stay private in S3.** The feed hands the build short-lived links; the
  build downloads each image, converts it to WebP at sensible sizes with `sharp`
  (already in the website's packages) and serves it from hostelcare.co.in. No
  public bucket, no hot-linking, and images load as fast as the rest of the site.

## Decisions (owner, 9 Nov 2026)

| # | Question | Decision |
|---|---|---|
| D1 | Who can write posts? | A new platform role **`CONTENT_EDITOR`** (no tenant, web only, same sign-in rules as `CRM_USER`, walled off to `/api/blog-cms` and `/api/auth`), plus SUPER_ADMIN. Super admin creates and deactivates editors. |
| D2 | The six existing hand-built posts | **Leave them as they are** for now; they keep their custom layouts. Their slugs are reserved. Optional later: import them (sprint X2). |
| D3 | Post address | **`/resources/blog/<slug>/`**, the same as today, so the blog index, sitemap and breadcrumbs stay one place. |
| D4 | Images | **Copied into the site at build** (above). Bucket stays private. |
| D5 | Word (.docx) import | **Now**, as GymCare: upload a .docx and get a draft (backend part in B1, the button in F1). |
| D6 | Packages | **The same as GymCare.** Web app: `@tiptap/core`, `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit`, `@tiptap/extensions`, `@tiptap/extension-image`, `@tiptap/extension-table`, `@tiptap/markdown` (3.x), `react-markdown` 10, `remark-gfm` 4, `dompurify` 3. Backend: `mammoth`, `turndown`, `turndown-plugin-gfm` for the Word import (uploads use the existing `express.raw` pattern, so no `multer`). Nothing new on the website or mobile. |

## Sprints

### B1 — Backend: posts, media, editors, feed

- **Migration (additive):** `Role` gets `CONTENT_EDITOR`; new platform-level
  tables (no `tenantId`, so `prismaUnscoped`, like the CRM):
  - `BlogPost` — slug (unique, locked once first published), title, metaTitle,
    description, bodyMd, coverKey + coverAlt, authorName (default "HostelCare
    Team"), keywords[], toc (H2 → short sidebar label), faqs [{q,a}], cta
    {heading,text}?, status `DRAFT | REVIEW | SCHEDULED | PUBLISHED | ARCHIVED`,
    publishAt, publishedAt, contentUpdatedAt, createdById, updatedById,
    lastBuildId. Index (status, publishAt).
  - `BlogPostRevision` — postId, userId, snapshot JSON, note; one per save.
  - `BlogMedia` — key, filename, mime, size, width, height, alt, uploadedById.
  - `BlogBuild` — state `PENDING | QUEUED | BUILDING | LIVE | FAILED`, reason,
    requestedById, dispatchedAt, runId, runUrl, attempts, lastError, finishedAt.
- **Role wall:** `authenticate.ts` gets `CONTENT_EDITOR_PREFIXES =
  ['/api/blog-cms', '/api/auth']`, the same mechanism as `CRM_USER`. Mobile and
  tenant routes refuse the role.
- **Routes `/api/blog-cms/*`** (SUPER_ADMIN or CONTENT_EDITOR unless noted):
  posts list (paged, status filter, search) / get / create / update / archive /
  restore; `review`, `publish` (now or at `publishAt`), `unpublish`; revisions
  list + restore; `check-slug`; media list (paged) / upload / edit alt / delete;
  `builds/latest`, `builds` (try again); editors CRUD (SUPER_ADMIN only).
- **Every rule on the server, and on every save of a live or scheduled post** (not
  only at publish), so a live post can never be saved into a state that breaks the
  website build:
  - title 3–160; slug `^[a-z0-9]+(-[a-z0-9]+)*$`, 3–80, unique, not reserved;
    metaTitle ≤ 60; description 70–160; keywords 1–20; cover + alt; body ≥ 200
    characters with at least two `##` sections; no `#` heading; no HTML tags;
    links only `https:`, `mailto:`, `tel:` or site-relative; images only from the
    media library.
  - Drafts may be incomplete; publish returns 422 with the list of problems.
- **Reserved slugs:** the six hand-built posts, and `check-slug` also asks the
  live site (`HEAD https://hostelcare.co.in/resources/blog/<slug>/`), so a page
  added to the website later is caught without editing a list.
- **Media:** upload JPEG/PNG/WebP ≤ 5 MB, type sniffed from the bytes, width and
  height read in the browser (the backend has no image library, and resizing
  happens in the website build), stored under `platform/website-blog/` in the
  existing bucket.
  Delete is refused while any post (archived included) uses the image.
- **Feed `GET /api/blog-cms/feed`:** header `X-Blog-Feed-Token` checked
  timing-safe against `BLOG_FEED_TOKEN`; 503 when unset; rate-limited; `no-store`.
  Returns published posts due now, each with image links valid 10 minutes, plus a
  `count`.
- **Tests:** isolation tests in throwaway schemas — an editor can't reach any
  tenant or CRM route; tenant users and CRM users can't reach `/api/blog-cms`; the
  feed refuses a wrong or missing token; a live post can't be saved invalid; the
  slug of a live post can't change.

### B2 — Backend: build trigger and scheduling

- `github-actions.service.ts`: `workflow_dispatch` on
  `BLOG_GITHUB_REPO`/`BLOG_GITHUB_WORKFLOW` at `BLOG_GITHUB_REF`; find the run
  and poll it. One pending build at a time, so several publishes share one
  deploy; nothing is dispatched while another build is running (the website
  workflow also queues runs itself).
- Job in the style of `crm-jobs.ts` (pm2 runs one process): every 60 s release
  due scheduled posts (one build for all of them) and poll builds; off with
  `DISABLE_BLOG_PUBLISH_JOB=true`.
- "Try again" moves every post of the failed build to the new build, so their
  status clears when it succeeds (GymCare bug 4).
- Dates shown and scheduled in IST.

### W1 — Website: CMS posts on the site

- **Loader** (`src/content.config.js`, moving the existing `use-cases` and
  `guides` collections there unchanged): a `blog` collection fetched from the
  feed at build time, validated with zod.
  - In the GitHub build (`CI=true`) a missing token, an unreachable API or an
    invalid post **fails the build**; the live site stays as it is. Locally,
    without a token, it builds with no CMS posts and says so.
  - Downloads each image and writes WebP sizes into `dist/assets/blog/cms/`.
- **Post page** `src/pages/resources/blog/[slug]/index.astro`, the same look as
  the hand-built posts: breadcrumb, hero with date and reading time, cover image,
  sidebar "In this article" from the H2s, body, FAQ, call to action
  (`TrialLink` / book-demo), BlogPosting + BreadcrumbList + FAQPage JSON-LD,
  canonical and OG tags. The build fails if a CMS slug clashes with a hand-built
  page.
- **Blog index:** CMS and hand-built posts together, newest first, ItemList
  JSON-LD with all of them; `src/data/blog.js` stays for the hand-built ones.
- **Sitemap:** `public/sitemap.xml` becomes `src/pages/sitemap.xml.js` (the same
  static entries plus every CMS post with its `lastmod`).
- **Workflow:** `BLOG_FEED_TOKEN` secret in the `prod` environment, required by
  the Build step like the two variables; the summary lists how many CMS posts
  were built; Verify also loads each CMS post page.

### F1 — Web app: editor screens

- In `hostelcare-frontend`, a **Website blog** section for SUPER_ADMIN, and the
  same screens as the whole app for a `CONTENT_EDITOR` (their own small shell,
  like the CRM user's):
  - **Posts:** paged list (`usePaginatedList`), status filter, search, "on the
    site" state per post, latest-build strip with "Try again".
  - **Editor:** title → slug (locked once live), TipTap with Markdown view,
    "Ready to publish?" checklist mirroring the server rules, SEO panel with
    counters, keywords, author, cover + alt, FAQs, CTA, publish now or schedule
    (IST), unpublish, archive, history with restore, Ctrl/Cmd+S, unsaved-changes
    warning. Uses the app's `fields.tsx`, `useFormErrors` and `PLACEHOLDER`
    conventions.
  - **Preview** in the website's own styles (the site's Tailwind classes for
    headings, FAQ and CTA), so what the editor sees matches the page.
  - **Images:** library with upload, alt text, copy, delete (refused while used).
  - **Editors** (SUPER_ADMIN): add, deactivate, resend sign-in.

### Word import (in B1 and F1)

- `POST /api/blog-cms/import/docx` (≤ 15 MB): mammoth → HTML → turndown (GFM) →
  Markdown, as GymCare: an SEO table gives slug / meta title / description /
  keywords, the H1 the title, a byline the author, an FAQ section the FAQs, a
  short closing section with demo/WhatsApp/pricing/call/book the CTA,
  `[bracketed]` notes come back as import notes. Embedded images go to the media
  library with the same type and size checks as uploads. Creates a draft; if
  that fails, the images it uploaded are removed again.

### X2 — Optional later

- **X2 Move the six hand-built posts into the CMS**, keeping their URLs.

## Order and deploys

1. **B1** backend → deploy (feed and screens' API exist; nothing visible yet).
2. **W1** website (needs B1's feed) and **F1** web app can run side by side.
3. **B2** last, so publishing only starts triggering deploys once the site can
   render the posts.

Every step is additive: no change to tenant data, hostel/PG/dormitory/Enterprise
screens or the mobile app.

## One-time setup (owner)

- **API server `.env`:** `BLOG_FEED_TOKEN` (long random value),
  `BLOG_GITHUB_TOKEN` (fine-grained token, repository
  `rajkumariparihar/hostelcare-website` only, permission Actions: read and
  write), `BLOG_GITHUB_REPO=rajkumariparihar/hostelcare-website`,
  `BLOG_GITHUB_WORKFLOW=deploy.yml`, `BLOG_GITHUB_REF=deploy`,
  `WEBSITE_URL=https://hostelcare.co.in`.
- **GitHub, website repo → Environments → prod → secret** `BLOG_FEED_TOKEN`, the
  same value.
- Create the first content editor from the super admin screen.

## GymCare problems this plan avoids

| GymCare | Here |
|---|---|
| A live post could be saved invalid, then every website build failed | All rules re-checked on every save of a live or scheduled post |
| Some rules (two sections, a keyword, lengths, slug lock) only in the UI | All on the server; the UI mirrors them |
| Missing feed secret silently built the site without CMS posts | Required in the GitHub build; the build fails instead |
| "Try again" left posts showing failed | Posts move to the retry build |
| Cover not shown on the post page; preview looked different | Cover on the page; preview uses the site's styles |
| Image delete could break an archived post; docx images unchecked | Delete refused while any post uses it; imports checked |
| Raw HTML passed through to the public site | Refused on save and not rendered |
| Reserved slugs kept by hand | Live-site check plus build-time clash check |
| CMS posts always listed first, missing from JSON-LD, UTC dates | One list by date, all in JSON-LD, IST dates |
| S3 bucket had to be public; images hot-linked and unoptimised | Private bucket; images copied and converted at build |

## Progress

### B1 + B2 — backend (built 9 Nov 2026)

B2 was built with B1: it does nothing until `BLOG_GITHUB_TOKEN` is set on the
server, so publishing can't start website deploys before W1 is live.

- **Migration** `20261218090000_blog_cms`: role value `CONTENT_EDITOR`, enums
  `BlogPostStatus` / `BlogBuildState`, tables `BlogPost`, `BlogPostRevision`,
  `BlogMedia`, `BlogBuild`. Additive only.
- **Role:** fenced in `authenticate.ts` to `/api/blog-cms` and `/api/auth`;
  `alwaysTwoStep()` in `lib/permissions.ts` gives it the CRM user's sign-in rules
  (always a code, can't switch it off, email changed only by the super admin).
- **Module** `src/modules/blog-cms/`: `blog-rules.ts` (every rule), `blog-posts`,
  `blog-media`, `blog-builds`, `blog-github`, `blog-editors`, `blog-docx`,
  `blog-jobs` (every minute; `DISABLE_BLOG_PUBLISH_JOB`), `blog-cms.routes.ts`
  at `/api/blog-cms`. Images: `uploads.service.ts` `putBlogObject` /
  `presignBlogObject` / `deleteBlogObject` under `platform/website-blog/`.
- **Endpoints:** `GET /feed` (header `X-Blog-Feed-Token`); `GET|POST
  /invites/:token[/accept]` (public); `GET|POST /posts`, `GET /posts/check-slug`,
  `GET|PATCH|DELETE /posts/:id`, `POST /posts/:id/{review,publish,unpublish,restore}`,
  `GET /posts/:id/revisions`, `POST /posts/:id/revisions/:revId/restore`;
  `GET|POST /media` (raw image body, `?filename=&alt=`), `PATCH|DELETE /media/:id`;
  `POST /import/docx` (raw .docx body, `?filename=`); `GET /builds/latest`,
  `POST /builds` (try again); `/editors` (super admin): list, add, edit,
  `send-link`, `deactivate`, `reactivate`, `sign-out`. A post that isn't ready
  answers 422 `NOT_READY` with `details.problems[]`.
- **Images in posts** are written as `/assets/blog/cms/<mediaId>.webp`, the path
  the website will serve; post responses carry `mediaUrls` (id → ten-minute
  link) so the editor can show them. The feed lists every image a live post
  uses with a 15-minute download link for the build.
- **Word import** found two bugs GymCare's copy also has: mammoth's style map
  needs single quotes (GymCare's Title/Quote mapping never applied), and Word
  tables have no header row, so the SEO table stayed raw HTML. Both fixed here.
- **Tests:** `src/tests/blog-cms.test.ts` (18 cases, own throwaway schema
  `hc_blog_test`, S3/GitHub/site stand-ins, a real `.docx` fixture) runs inside
  `npm run test:isolation`; `npm run audit:permissions` has the new role on every
  route and the blog's own cases (2,892 passed). `npm run smoke`: 2,158 passed,
  12 failed — the same 12 fail on 6418dde without these changes (student sheet
  import and the trial journey), so they are not from the blog.
- **Packages:** `mammoth`, `turndown`, `turndown-plugin-gfm` (+ `@types/turndown`).

### W1 — website (built 9 Nov 2026, hostelcare-website)

- `src/content/cms-blog-loader.js`: the `blog` collection (registered in the
  existing `src/content/config.js`). Reads the feed with `BLOG_FEED_TOKEN`
  (API from `BLOG_API_URL`, else `PUBLIC_LEAD_API`), downloads every image and
  converts it with `sharp` (Astro's own; nothing new installed) to
  `public/assets/blog/cms/<id>.webp` (git-ignored), max 1600 px wide, real
  sizes written into the pages. Refuses HTML the site doesn't publish after
  rendering (script, iframe, on…=, javascript: …). With `CI=true` any problem
  fails the build; locally without a token it builds without CMS posts.
- `src/pages/resources/blog/[slug]/index.astro`: the hand-built posts' look, plus
  the cover, "Updated" date, reading time, sidebar from the `##` headings (with
  the editor's labels), FAQ, CTA, BlogPosting/BreadcrumbList/FAQPage JSON-LD,
  og:image (new optional `ogImage` on `Layout.astro`). A CMS slug equal to a
  hand-built page stops the build.
- Blog index renders hand-built (`src/data/blog.js`, now with card details) and
  CMS posts together, newest first, via `BlogCard.astro`, with Blog JSON-LD.
- `public/sitemap.xml` moved to `src/data/sitemap-static.xml`;
  `src/pages/sitemap.xml.js` serves it plus every CMS post.
- `deploy.yml`: `BLOG_FEED_TOKEN` (prod secret) required in the Build step, CMS
  post count in the summary, Verify loads `/resources/blog/` and every CMS post.
- Checked: build without a token = the same 64 pages and the same sitemap; build
  against a stand-in feed in the backend's shape = 66 pages, images converted,
  sitemap + index right; raw HTML in a post, no token, a wrong token and an API
  that doesn't answer each stop the build with exit code 1.

### F1 — web app (built 9 Nov 2026, hostelcare-frontend)

- `/blog` workspace (`src/pages/blog/BlogApp.tsx`, loaded only when opened: a
  784 KB chunk, the main bundle is unchanged), where a `CONTENT_EDITOR` lands
  after sign-in; the super admin opens it from "Website blog" in their menu.
  `/blog/invite/:token` is the writer's set-password page (the CRM's page, now
  shared through an `InviteSource`).
- `src/features/blog/`: `BlogPostsSection` (status tabs with counts, search,
  pages, website state per post, build strip with "Try again", new post, Word
  import), `BlogPostEditor` (title/address with live check and lock,
  TipTap body, FAQs, CTA, "Ready to publish?" list, search fields with
  counters, keywords, cover from the library, author, sidebar labels,
  history with restore, review / unpublish / delete / restore, publish now or
  scheduled, Ctrl/Cmd+S, unsaved-changes warning, the server's problem list on
  a refused save), `MarkdownEditor` (TipTap 3 + `@tiptap/markdown`, pasted HTML
  cleaned with DOMPurify, images stored as `/assets/blog/cms/<id>.webp` and
  shown through their links), `PostPreview` (react-markdown + remark-gfm in the
  website's styles), `MediaLibrary` (+ picker), `blogChecks` (+ tests).
- Writers: the CRM users panel takes a `TeamAdapter`, so the same panel lists
  blog writers. API calls: `blogApi` in `src/lib/api.ts`.
- Checked in the browser against a throwaway API (schema `hc_blog_ui`, S3 off,
  since dropped): invite → set password → sign in with the emailed code →
  lands in the blog with only Posts/Images/Profile; Word import through the
  button → draft with notes; publish refused until ready, then published with
  the address locked; clearing the description on the live post refused with
  the reason; typing + Cmd+S saved clean Markdown with history; preview;
  super admin "Website blog" → Writers panel; phone width. Not checked in the
  browser: real image upload and display (needs S3), a real website build
  from a published post (needs the GitHub token).
- Fixed while checking: a loaded post with FAQs looked "changed" (Postgres
  reorders JSON keys); the problem list's heading read "[object Object]".

## Going live (owner, in this order)

1. Commit and merge the backend; deploy. The migration adds the role and the
   four tables. Nothing shows yet.
2. API server `.env`: `BLOG_FEED_TOKEN` (32+ random characters) and the GitHub
   settings (see "One-time setup"); restart (a deploy does it).
3. Website repo → Environments → prod → secret `BLOG_FEED_TOKEN`, same value.
   Then merge the website to `deploy`. From now on every website deploy needs
   the API's feed to answer.
4. Merge the web app; deploy. Super admin → Website blog → Writers → invite.
