Pluto core gets an optional standalone CMS. Blog posts are Markdown files with YAML frontmatter in a GitHub repo. Editors change them in the Pluto admin. The public site reads them live through the GitHub API, with a cache. Users with push access to the repo are editors. They sign in with a GitHub App. A draft is a post with `status: draft` in its frontmatter.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Git Cms?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/plutocms-git-cms)
# Git CMS
Pluto core gets an optional standalone CMS. Blog posts are Markdown files with YAML frontmatter in
a GitHub repo. Editors change them in the Pluto admin. The public site reads them live through the
GitHub API, with a cache. Users with push access to the repo are editors. They sign in with a
GitHub App. A draft is a post with `status: draft` in its frontmatter.
## On unless a backend layer is present
`plutoGithub.enabled` is `'auto'` by default. It also accepts `true` and `false`. When the CMS is
off, the `pluto-github` module adds nothing: no runtime config key, handler, plugin, page, middleware
or import.
- `'auto'`: on, unless a backend layer is present. With a backend layer it is off, with no log.
- `true`: on. With a backend layer, the module logs this error and stays off:
> The standalone CMS cannot run with the supabase layer. Remove plutoGithub.enabled or the supabase
> layer.
- `false`: off. The module returns before any other work.
- Any other value: the module logs an error and stays off.
A backend layer is any of these (`index.ts` checks them, then passes `hasBackendLayer` to
`resolvePlutoGithubOptions`):
- A layer with `$meta.name === 'supabase'`.
- The `@nuxtjs/supabase` module.
- A layer with `$meta.plutoBackend: true`. This is the generic marker. Nuxt keeps custom `$meta`
keys in `layer.config`. A new backend layer sets it in its `nuxt.config.ts`.
A supabase app sees no change and no log line.
During `nuxt prepare`, an auto-enabled CMS logs no error. A build or a dev server logs it.
## Defaults
An explicit option always wins. `resolvePlutoGithubOptions(options, ctx)` is pure. The module passes
`ctx = { dev, hasBackendLayer, env: process.env, gitOrigin }`.
- `storage`: the env var `PLUTO_GITHUB_STORAGE`, else `fs` in dev and `github` in production.
- `github.repo`: the env var `NUXT_PLUTO_GITHUB_REPO`, then `PLUTO_GITHUB_REPO`, then Vercel's
`VERCEL_GIT_REPO_OWNER` + `VERCEL_GIT_REPO_SLUG`, then Netlify's `REPOSITORY_URL` (a GitHub URL
only), then (dev only) the `origin` remote of the git repo that holds `rootDir`.
- `github.appSlug`: `NUXT_PLUTO_GITHUB_APP_SLUG`, then `PLUTO_GITHUB_APP_SLUG`.
- `github.branch`: `main`.
- With the `github` storage and no repo, the module logs one error ("The standalone CMS needs a
GitHub repo...") and stays off. It never throws.
`modules/pluto-github/git-remote.ts` has `parseGithubRepoUrl` (https, `git@`, `ssh://`, `git://` URLs
of github.com), `parseGitConfigOrigin` and `readGitOrigin`. `readGitOrigin` walks up from
`rootDir` to the `.git` dir, follows a worktree `gitdir:` pointer, and reads `config`. It runs
no shell command. Tests: `test/github-git-remote.test.ts`, `test/pluto-github-options.test.ts`.
## Files
- `modules/pluto-github/index.ts` — the Nuxt module (config key `plutoGithub`).
- `modules/pluto-github/git-remote.ts` — the git `origin` reader (Node `fs` only).
- `modules/pluto-github/options.ts` — pure helpers: `resolvePlutoGithubOptions`, `normalizeGithubDir`,
`PLUTO_GITHUB_SECRET_ENV`. No Nuxt imports, so plain Vitest can test them.
- `shared/types/github.d.ts` — the `@nuxt/schema` types for `plutoGithub`.
- `test/pluto-github-options.test.ts` — the unit tests.
- `runtime/server/utils/{session,github-oauth,auth-flow,rate-limit,github-config,github-setup}.ts`,
`runtime/server/github/app-token.ts`, `runtime/server/api/auth/**`,
`runtime/server/plugins/pluto-github.ts` — the authentication and the wiring (see "Authentication"
and "Wiring"). The CSRF check is in core (`server/utils/pluto-origin.ts`).
- `runtime/app/{composables,plugins}/` — the client side.
- `runtime/server/{api/build-status.get,utils/build-status}.ts`, `runtime/shared/{build-status,build-poller}.ts`,
`runtime/app/composables/pluto-github-build-status.ts` and `app/components/Pluto/Github/PlutoGithubBuildStatus.vue` —
the build status (see "Build status").
- `app/components/Pluto/Github/` — the sign-in form (`PlutoGithubSignIn`), the dashboard warning and the
editor widget.
- `runtime/server/utils/{markdown,sanitize-html}.ts` and the adapter's `toPublic` — the public
read side (see "Public read"). The routes are core's public API.
## Options
| Option | Default | Rule |
| ------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | `'auto'` | `'auto'`, `true` or `false`. See "On unless a backend layer is present". |
| `storage` | `'fs'` in dev, `'github'` in production | `'github'` or `'fs'`. `'fs'` is valid in dev only. |
| `github.repo` | found (see "Defaults") | `owner/name`. Required when storage is `github`. |
| `github.branch` | `'main'` | The branch to read and commit to. |
| `github.appSlug` | the env var, else `''` | The slug of the GitHub App. |
| `github.apiUrl` | `'https://api.github.com'` | The API base URL. |
| `dir` | `'content'` | Relative path. No `..`, no leading `/`, no drive letter. The module changes `\` to `/` and removes a trailing `/`. |
| `commit.skipDeploy` | `false` | `false` (hybrid): only a commit that changes no published content (a draft that stays a draft) gets `[skip ci]`, so a published change deploys and refreshes the build snapshot. `true`: add `[skip ci]` to every commit message (no build after a save; the snapshot gets old). See "Hybrid" and "Skip a deploy on Vercel". |
| `commit.local` | `true` | Local mode (`fs`, dev only): commit each save to the local Git repo of the project. No repo: Pluto only writes the files. |
| `cache.headTtl` | `60` | Seconds. Zero or more. |
| `cache.storage` | `'cache'` | The Nitro storage mount for the cache. |
| `postType` | `true` | Register the fixed post content type, on the server and on the client. A layer that brings its own types sets it to `false`. |
A bad option turns the CMS off and logs an error. The module does not throw.
## Secrets
The secrets are run-time env vars. The module does not check them at build time. Set them as
`NUXT_PLUTO_GITHUB_<NAME>`, for example `NUXT_PLUTO_GITHUB_SESSION_PASSWORD`. The module puts an empty
string in `runtimeConfig.plutoGithub` for each one, so Nuxt can override it.
Required: `SESSION_PASSWORD`, `APP_ID`, `CLIENT_ID`, `CLIENT_SECRET`,
`PRIVATE_KEY`. Optional: `READ_TOKEN`, `ALLOWED_USERS`.
### Old env names (before 0.28)
Until 0.27 the env vars were `NUXT_PLUTO_CMS_*` and `PLUTO_CMS_*`. 0.28 read them as a fallback.
Pluto no longer reads them: a host that still has an old name has no value for the new one.
Test: `test/pluto-github-options.test.ts` ("old env names").
## Runtime config
When on, the module writes `runtimeConfig.plutoGithub` (the secrets) and
`runtimeConfig.public.plutoGithub` (`enabled`, `repo`, `branch`, `appSlug`, `storage`, `dir`, `postType`, `skipDeploy`).
## Storage
The storage layer is in `modules/pluto-github/runtime/server/`. The Nitro plugin wires it in (see
"Wiring"). Every runtime file uses explicit imports. The pure helpers run in plain Vitest.
- `store/types.ts` — the `PlutoGithubStore` contract: `head`, `listDir`, `listTree`, `readFile`, `commit`. A
commit takes `expectedHeadOid`. A stale value throws `PlutoGithubConflictError`. PR 4 maps it to 409.
- `store/errors.ts` — `PlutoGithubStoreError` with a `code`: `conflict`, `auth`, `forbidden`,
`rate-limit`, `not-found`, `github`. The code has no HTTP link. PR 4 maps it.
- `store/memory.ts` — an in-memory store for tests.
- `store/fs.ts` — a dev store over a local dir. The head is a hash of the file listing. It refuses
any path outside the root. With `gitCommit` (from `commit.local`), each write is also a commit in
the local Git repo (local Git publishing, see below).
- `store/local-git.ts` — `commitLocalFiles(root, paths, message)`: `git add -A` and
`git commit -- <paths>` for the changed paths only, so the author's other staged changes stay
staged. It runs the repo hooks and uses the repo author. It returns `committed: false` with
`not-a-repo`, `no-git` or `no-changes` instead of failing. The fs store writes the files first:
a failed commit (a hook, no author) only logs a warning, and a missing repo or Git logs one
warning per process. The local commit drops the `[skip ci]` marker: the author's own push of
these commits must deploy. Tests: `test/github-local-git.test.ts` (a temp Git repo).
- `store/github.ts` — `createGithubStore`. `head` uses the REST sha call with an ETag and a TTL.
`listDir` is one GraphQL call. `listTree(dir, head, auth)` reads every `.md` file under a dir with
one GraphQL call that nests `... on Tree { entries }` six levels deep. The cache key is
`tree:<dir>@<head>`. The fs store reads the dir recursively. The memory store filters by path
prefix. All three skip dot dirs and dot files. `commit` uses `createCommitOnBranch` and sets the cached head at once.
- `github/client.ts` — `githubRest` and `githubGraphql`. They take an injectable `fetch`
transport. The default uses `ofetch`. They throw typed errors.
- `utils/github-cache.ts` — the head with a TTL, the dir index by `<dir>@<headOid>`, parsed blobs by
blob id, and single-flight. The backend is a Map by default.
`utils/github-cache-nitro.ts` gives a backend over Nitro `useStorage`.
- `utils/markdown-file.ts` — parse and write Markdown with YAML frontmatter. It uses the `yaml`
core schema, so a tag never runs code.
- `utils/blob-sha.ts` — `gitBlobSha` and `listingOid`.
- `utils/github-paths.ts` — `assertSafeSlug`, `assertSafeContentId`, `contentFilePath`,
`contentDirPath` and `slugifyTitle`. The path helpers take `{ nested }` as the last argument.
- `test/fixtures/fake-github.ts` — an in-memory GitHub that counts calls by kind.
## The page type
The core option `plutoPages: { enabled: true }` (default `false`) makes the Git CMS register
`plutoGithubPageType` (`runtime/shared/page-type.ts`), on the server (`registerGithubContent`, which
reads `runtimeConfig.public.plutoPages.enabled`) and on the client (the `pluto-github` plugin). The
default is `false`, so a site that does not use pages has no empty menu item. The type comes from
`definePlutoPageType` in core `shared/utils/page-type.ts` (the content model skill, "Pages"). The Git CMS
adds only its storage: `source: 'pages'`, `files: { nested: true }`, its columns and capabilities.
- Name `page`, `source: 'pages'`, `files: { nested: true }`: the id is the path under
`content/pages` without `.md` (`about`, `about/team`). The `slug` field (label "Path") holds the whole id.
- Fields: `title` (required), `slug`, `description`, `layout` (select: `default` or `full`, written as frontmatter), `body` (`richtext`, `widget: 'blocks'`, canvas layout).
- Status draft or published (`liveOnSave`, `trash`), `api: { public: true }`. No scheduling.
- Capabilities `pages:read_drafts`, `pages:publish`, `pages:delete`. Push users get them through the
registered types (`mapRepoPermission`). The plugin lists them in the capability registry with the
keys `pluto.github.capabilities.readPageDrafts`, `publishPages` and `deletePages`.
- The public item has `blocks` and no `html` (see the blocks-field skill). `usePage(path)` reads it.
Render it with `<PlutoBlocks :value="page.blocks" />`. A site adds a catch-all route
(`pages/[...path].vue`) for the paths.
- Texts: `content.page.*` (the type) in the locale files, like `content.post.*`.
- Tests: `test/github-page-type.test.ts`, `test/pluto-github-options.test.ts`, `test/github-client-rules.test.ts`.
## The menu and area types
The core options `plutoMenus: { enabled: true }` and `plutoAreas: { enabled: true }` (default `false`) make the
Git CMS register `plutoGithubMenuType` and `plutoGithubAreaType` (`runtime/shared/menu-type.ts`,
`area-type.ts`), like the page type: on the server (`registerGithubContent`, with `config.menus` and
`config.areas`) and on the client (the `pluto-github` plugin). The types come from `definePlutoMenuType` and
`definePlutoAreaType` in core (the content model skill, "Menus and areas").
- `source: 'menus'` and `source: 'areas'`: the files are `content/menus/<handle>.md` and
`content/areas/<handle>.md`. Flat, no status, `api: { public: true }`. The id is the handle.
- Capabilities `menus:write` and `areas:write` (write and delete). Push users get them through the registered
types. The plugin lists them with the keys `pluto.github.capabilities.manageMenus` and `manageAreas`.
- The public item has `blocks` and no `html`. `usePlutoMenu(handle)` and `usePlutoArea(handle)` read them.
- Texts: `content.menu.*` and `content.area.*`.
- Tests: `test/pluto-menus-areas.test.ts`.
## Adapter
`runtime/server/adapter.ts` has `createMarkdownContentAdapter`. It is a `PlutoContentAdapter` over a
`PlutoGithubStore`. The Nitro plugin registers it (see "Wiring"). Options:
`store`, `dir`, `getAccess`, `commit.skipDeploy`, `cache`, `retries` (default 2).
`runtime/shared/post-type.ts` has `plutoGithubPostType`, the built-in `post` content type.
`runtime/shared/term-types.ts` has `plutoGithubTagType` and `plutoGithubCategoryType`, registered with
`post` when `postType` is on (see the tags-and-categories skill). `runtime/shared/author-type.ts` has
`plutoGithubAuthorType` (`content/authors/<slug>.md`, capability `authors:manage`), registered
the same way (see the authors skill). The post has the fields `authors`, `categories` and
`tags`: lists of ids (the file names) in the frontmatter. The option
`getTypes` gives the registered types (default: the core registry).
File layout:
- A file is `<dir>/<type.source>/<slug>.md`. The post type uses `source: 'posts'`.
- The item `id` is the slug. It is the file name. It is not a frontmatter key.
- A slug uses lowercase letters, numbers and single dashes. The create call makes it from the title
when the payload has none.
Frontmatter mapping:
- The first `richtext` field is the Markdown body.
- Every other field, except the slug field, is a frontmatter key. The key is the field column
(`fieldColumn`), the same rule as the other adapters.
- The status key and the timestamp keys come from `type.status` and `type.timestamps`. The adapter
sets the timestamps. A payload cannot set them. The adapter sets `publishedAt` on the first
publish only. Without a `timestamps` setting, the keys are `createdAt` and `updatedAt`.
- An update keeps frontmatter keys that the type does not know.
- An empty list (`[]`) leaves the frontmatter: the key is removed, as for an empty value.
- `list` takes `query.ids` (only these ids) and matches a filter on a list field when the list has
the value.
- A rename (a new slug) or a delete of an item also rewrites the items that reference it, in the same
commit. The adapter reads every type that has a `reference` field with this item's type as
`target` (`getTypes`), drafts too. It replaces the id, or removes it (a list that ends empty
drops its key), and keeps the body, the unknown keys and the `updatedAt` stamp. The commit message
ends with `(N references)`. A referencing file that changes during the commit gives 409. The
rewrite needs no write capability on the referencing type.
- A file with no status key counts as the default status (`draft` for posts).
- Every returned item has `_version`. It is the blob id of the file. A list item has no body.
The excerpt field stays in the list item.
Access rules:
- `getAccess(event)` returns `{ capabilities, auth }`, or `null` for an anonymous caller.
- `readFile(ctx, relativePath)` reads a raw file of the type folder (`{ text, version }`, `version` is
the blob id). It works over the `github` and `fs` stores. `typeRelativePath` (`utils/github-paths.ts`)
refuses `..`, absolute paths, drive letters, backslashes, `%`, control characters and empty or `.`
segments (the adapter then returns `null`). A `.md` file follows the rules of `get` (usable id, visible).
`get` adds `_frontmatter`: the whole frontmatter after the `read` hook.
- A layer that serves public pages calls the core util `markPublicRead(event)` (auto-imported;
`markGithubAnonymous` is the same call inside the module). The test is `test/github-adapter-read-file.test.ts`.
- An anonymous caller sees published items only. This holds for `list`, `get` and `countCreated`,
even when the query asks for drafts.
- The adapter itself does not refuse an anonymous `list` or `get` of a type with no `status`:
every item is visible. The admin routes of core refuse the anonymous caller before they call the
adapter (`authorizeContentRead`, see the content-model skill). The adapter has
`requireSignedIn(event)` for this: a 401 when `getAccess` is `null`. Public reads go through the
public API, which marks the request as public.
- A signed-in caller sees drafts only with the type read capability (`posts:read_drafts`). The
capability `*` counts as every capability.
- Every write needs access (401). It needs the write or delete capability (403). A change of the
published state needs the publish capability. `authorize` fails closed in the same way.
Conflict handling:
- An update with a stale `_version` gives 409 (`pluto.errors.conflict`). A missing `_version`
skips this check.
- A create or rename to a taken slug gives 409 (`pluto.github.errors.slugTaken`).
- A rename is one commit: it adds the new path and deletes the old one.
- A commit uses a fresh head as `expectedHeadOid`. When the head is stale, the adapter retries up
to 2 times, but only if the target file did not change. Otherwise it gives 409.
- Commit messages: `content(post): create "slug"`, `update`, `publish`, `unpublish`,
`rename "a" -> "b"`, `delete`. `[skip ci]` is added to every commit when `skipDeploy` is on. When it
is off (the default), `[skip ci]` is added only to a commit that changes no published content: a create, update,
rename or delete of an item that is a draft before and after (`messageOf(type, verb, publicChange)`).
A publish, an unpublish, and any change of a published item deploy. A type with no status is always
public. Tests: `test/github-adapter.test.ts` ("skip marker").
Store errors map to HTTP errors with `pluto.github.errors.*` keys: conflict 409, auth 401, forbidden
403, rate limit 503 with a `Retry-After` header, not found 404, GitHub failure 502.
### Revisions
The adapter implements `listRevisions` and `getRevision` (see the content-model skill,
"Revisions"). A revision is a commit that changed the file of the item.
- The store has two optional methods: `history(path, { limit, cursor }, auth)` (the commits that
changed a file, newest first: `{ commits: PlutoGithubCommitInfo[], nextCursor? }`) and
`readAt(path, commitOid, auth)` (the file at a commit, or `null`).
- GitHub: one GraphQL query, `history(path:)` on the branch, 1 to 50 per page with the GraphQL
cursor. The author is the Git author name, with the GitHub login and avatar when GitHub knows
the user. `readAt` reads the blob `<commit>:<path>` (single-flight, no index cache).
- fs: `localFileHistory` and `localFileAt` (`store/local-git.ts`): `git log -n --skip -- path`
and `git show <oid>:./<path>` in the project dir. The cursor is the skip count. A commit id
must be hex, so it can never act as an option. No Git repo, or no Git: an empty history.
- Memory (tests): a copy of the text files after each commit. Commit ids `c1`, `c2`, ...
- The build snapshot has none. `withBuildSnapshot` and `withSnapshotFallback` pass both
methods to the GitHub store (an editor always has a token).
- Both adapter methods need a signed-in caller with the type write capability (401, 403). A draft
revision follows the rule of `get`: without the read capability it is `null`.
- The action comes from a Pluto commit message (`content(post): update "slug"`). Another commit
(a push by hand) shows its first line, without `[skip ci]`.
- Renames are not followed: the history of an item starts at its last rename.
Tests: `test/github-revisions.test.ts` (the adapter over the memory store, a nested id, the
snapshot, the GitHub GraphQL calls, and `fs` in a temp Git repo).
### Nested content types
A type with `files: { nested: true }` stores its items in nested folders. A docs site needs this.
`files` is plain data and pure functions, so the type is safe on the server and on the client.
Only the file adapters read it.
```ts
files: {
nested: true, // ids are paths: '1.start/2.install'
exclude: ['index', 'drafts/'], // an id, or a folder with a trailing slash
frontmatter: { read, write }, // pure (frontmatter) => frontmatter
}
```
- The id is the path under the type folder, without `.md`. Each segment is a slug with an optional
numeric prefix (`^(?:\d+\.)?[a-z0-9]+(?:-[a-z0-9]+)*$`). An id has at most 6 segments and 255
characters. `..`, an empty segment and a dot segment are refused. A flat type keeps the old rule
(one slug) exactly.
- `source: ''` means the content dir itself. Only a nested type can use it.
- The adapter lists, gets, creates, updates and removes through `store.listTree`. The slug field
holds the whole id, so a new path in the slug field creates the item in a folder. An update with
a new path moves the file in one commit (add and delete). A move onto a taken path gives 409.
- The default sort of a nested type is `compareContentIds` (shared util, auto-imported): in each
segment `index` comes first, then the numeric prefix as a number, then the name. Set
`defaultSort: { field: 'id', direction: 'asc' }` for a nested type that also has timestamps.
- `frontmatter.read` runs on a copy after a file is parsed. Add the flat keys that the fields
read, for example `navTitle` from `navigation.title`. A field that a hook maps is a normal field
with that flat key as its `column`. `frontmatter.write` runs before a file is written. Fold the
flat keys back and drop them. Keys that the type does not know must stay.
- The public API (`/api/pluto/v1/content/<type>/<id>`) takes the rest of the path as the id, so it
reads a nested item too (each segment encoded on its own).
### No commit for an unchanged file
For every type, an update whose new file text equals the stored text makes no commit. The
`updated` timestamp alone does not count as a change. The call returns the stored item with the
same `_version`. A hand-written file with a different YAML layout is not equal, so the first real
save rewrites it.
### Push users
A user with push access gets the read, write, publish and delete capabilities of every registered
content type (`listContentTypes()`). The post type is the fallback when no type is registered.
The contract test suite is `test/contracts/content-adapter.contract.ts`
(`runContentAdapterContract`). Run it against any new adapter over the post type.
`test/github-nested-adapter.test.ts` runs it on a nested type too.
## Wiring
When the CMS is on (see "On unless a backend layer is present"), and only then, the module adds:
- Four server routes under `/api/_pluto/auth/` (see "Authentication").
- A Nitro plugin, `plugins/pluto-github.ts`. It picks the store (`github` with the Nitro cache, or `fs`
rooted at the project dir in dev), registers the `post` type when `postType` is on, and registers
the Markdown adapter. `getAccess(event)` gives the signed-in user (their GitHub token and
capabilities) or `null`.
- A build snapshot, for a site that reads from GitHub (not dev, not static): the module bundles
every `.md` file of the content dir as Nitro server assets (`pluto-content`,
`runtime/shared/snapshot.ts`). The host builds from a checkout, so the files are there. When the
server has no read token and no App credentials (a first deploy, before the setup), the store is
`withBuildSnapshot` (`store/snapshot.ts`): an anonymous read goes to the snapshot (read only), a
call with a user token goes to GitHub. It warns once. With credentials it is
`withSnapshotFallback` (hybrid): an anonymous read goes to GitHub, and when GitHub fails (any error
but a conflict: an outage, a rate limit, a bad App key, the network) the same read goes to the
snapshot, so the public pages stay up. The snapshot ignores the head id, so a GitHub head can come
before a snapshot read. A call with a user token never falls back (the admin must not edit old
content). It warns at most once in 5 minutes. With no snapshot either, the token provider answers 503 `pluto.github.errors.notConfigured`
("Set up the GitHub App in /admin"), not the generic `githubUnavailable`. Media files are not in
the snapshot: they are in `public/`, so the host serves them. GraphQL needs a token even for a
public repo, so without the snapshot a fresh deploy reads nothing, public or private.
Tests: `test/github-snapshot.test.ts`, `test/github-module.test.ts`.
- A client plugin, `runtime/app/plugins/pluto-github.ts`. It calls `definePlutoExtension` with the
auth driver, the post content type, the post capabilities, the permissions driver and the
public-repo dashboard widget. The post type and the post capabilities are registered only when
`postType` is on (the module copies the option to `runtimeConfig.public.plutoGithub.postType`; a
missing value counts as on). The warning shows only when the repo is public and a registered type
has a `status` (`showPublicRepoWarning`). Core loads the capabilities when the session appears.
- The auto-import dir `runtime/app/composables` (`usePlutoGithubSession`).
The module adds no page, no route middleware and no navbar. Core owns the `/admin` parent route,
the `/admin/login` page, the route guard and the navbar. The CMS is the reference auth driver.
See the [admin shell](../admin-shell/SKILL.md) skill.
The module puts the non-secret server settings in the private `runtimeConfig.plutoGithub`: `apiUrl`,
`skipDeploy`, `headTtl`, `cacheStorage`, `postType`, `fsRoot`. `utils/github-config.ts` reads all
config in one place (`getGithubConfig`). A test mocks that file.
The `fs` store root is the project dir (the same layout as the repo), so a post is at
`<project>/content/posts/<slug>.md`.
The Vue files are in `app/components/Pluto/Github/`, because Tailwind scans the `app/` dir of a layer
only: `PlutoGithubSignIn` and `PlutoGithubPublicRepoWarning`. They use explicit imports for the session composable, so the type
check works when the CMS is off.
## Authentication
A user signs in with a GitHub App (the user-to-server OAuth web flow). Only users with push access
to the content repo can sign in.
### Flow
1. `GET /api/_pluto/auth/github/login?redirect=/path`. The `redirect` must be a path on this site:
one `/` at the start, not `//`, no `\`, no control character, no other origin. Any other value
becomes `/admin/home`. The route makes `state` (32 random bytes, base64url) and a PKCE verifier.
It saves `{ state, verifier, redirect }` in a separate sealed session, `pluto-github-oauth`, which
lives 10 minutes. Then it answers 302 to `github.com/login/oauth/authorize` with `client_id`,
`redirect_uri`, `state`, `code_challenge` and `code_challenge_method=S256`.
2. `GET /api/_pluto/auth/github/callback`. The route reads and clears the oauth session first, so
`state` works once. It compares `state` in constant time. A mismatch gives 302
`/admin/login?error=state`. Then it trades the code for tokens (with the client secret and the
PKCE verifier), reads `/user`, and reads `/repos/{owner}/{repo}` with the USER token:
- 404 (the user or the App cannot see the repo): `?error=not_installed`.
- Permission is not admin, maintain or push: `?error=forbidden`.
- The login is not in `allowedUsers` (when it is set): `?error=forbidden`.
- Any other failure: `?error=github`. The user cancels at GitHub: `?error=denied`.
- Else it starts the session and answers 302 to the saved `redirect` (checked again).
3. `GET /api/_pluto/auth/session` answers `{ user, capabilities, repo: { name, private } }` or
`{ user: null }`. It never has a token. A session that is over also answers `{ user: null }`.
4. `POST /api/_pluto/auth/logout` deletes the cookie and answers 204. It works even when the
session password is missing.
Every auth response has `Cache-Control: no-store`. The login and callback routes allow 20 requests
a minute for each IP, then answer 429 (`utils/rate-limit.ts`). The counter is in memory, one per
server instance. It is a brake, not a gate. The IP is the socket address, or `x-forwarded-for`.
### Session
`utils/session.ts` uses h3 `useSession`. The cookie is `pluto-github-session`: sealed, httpOnly,
SameSite=Lax, Secure when not in dev, `maxAge` 7 days from the sign-in. A session header is off.
The password is `runtimeConfig.plutoGithub.sessionPassword` and needs 32 characters or more. In
production a missing or short password makes the sign-in routes answer 500
(`pluto.github.errors.authNotConfigured`) and logs one error. In dev it uses a random password for the
process, so a restart signs everyone out.
The cookie holds `{ user: { id, login, name, avatarUrl }, token, refreshToken, expiresAt,
refreshExpiresAt, permission, capabilities, checkedAt, repoPrivate }`. It is sealed, not stored on
the server, so a logout does not revoke a copy of the cookie. The token expiry and the permission
check below limit that.
Exports: `getGithubSession(event)`, `requireGithubSession(event)` (401
`pluto.github.errors.signInRequired`), `requireGithubCapability(event, cap)` (403), `setGithubSession`,
`clearGithubSession`. A request with no cookie reads as signed out and sets no cookie. Each request
reads the session once.
- Refresh: when `expiresAt` is less than 5 minutes away, the session refreshes the user token with
the refresh token. GitHub rotates the refresh token. The first refresh wins. Requests that run at
the same time share it. A request that arrives within 60 seconds with the old cookie reuses the
result (memory of this process only). If GitHub refuses the refresh token, the session clears and
the answer is 401. If GitHub does not answer, the answer is 503 and the session stays.
- Permission check: when `checkedAt` is older than 10 minutes, the session reads the repo again
with the user token and updates the capabilities. If push access is gone, or GitHub rejects the
token, the session clears and the answer is 401. If GitHub does not answer, the answer is 503.
- Capabilities: admin and maintain give `['*']`. Push gives the keys of the registered types: the post type
(`plutoGithubPostType.capabilities`: `posts:read_drafts`, `posts:publish`, `posts:delete`) and the page type
when it is on, and the menu and area types when they are on. The
adapter and `requireGithubCapability` treat `*` as every capability. GitHub still enforces the real
permission on each commit, because the commit uses the user token.
- Dev `fs` store: in dev with `storage: 'fs'`, a request from this machine gets a fixed user
`local` with `['*']`. The check reads the socket address. A request is not local if it has
`x-forwarded-for` or `forwarded`, or if its `Host` is not `localhost`, `127.0.0.1` or `[::1]`. So a
tunnel or a DNS-rebinding page gets no access. Every other request is signed out.
### Anonymous reads
An anonymous caller sees published posts only. The store reads with a server token
(`github/app-token.ts`):
1. `runtimeConfig.plutoGithub.readToken` (a read-only token), when set.
2. Else an installation token of the App. The code signs an App JWT (RS256, `iat` now minus 60
seconds, `exp` now plus 540 seconds, `iss` the app id). The private key may use literal `\n`
escapes. It reads `GET /repos/{o}/{r}/installation`, then `POST
/app/installations/{id}/access_tokens` for this repo with `contents: read`. It caches the token
in memory until 5 minutes before it ends.
3. With neither set, an anonymous read answers 503 (`pluto.github.errors.githubUnavailable`) and logs
the cause once. The server does not fail at boot.
A signed-in user reads and writes with their own token.
### CSRF
SameSite=Lax is the first guard. Core's server middleware `server/middleware/pluto-origin.ts` is the
second; it runs for every layer, with or without the CMS. For a request that
is not GET, HEAD or OPTIONS to `/api/_pluto/**`, the `Origin` header (or `Referer` when `Origin` is
absent) must have the same `host:port` as the `Host` header. A mismatch, a bad value such as
`Origin: null`, or no header at all gives 403 (`pluto.errors.crossOrigin`). The check uses the
`Host` header and ignores `x-forwarded-host`: Nitro has no setting that trusts a proxy, and a client
can fake that header. A proxy in front of the app must pass the public `Host` header. GET routes
never change state.
### Client
- `usePlutoGithubSession()` gives `{ user, capabilities, repo, loggedIn, status, ready, refresh,
logout }`. It uses `useFetch` with the key `pluto-github-session` and `server: false`, so the
server HTML of a public page never holds a user (a CDN may cache it). The admin is client-only.
- The auth driver (`id: 'pluto-github-auth'`) maps the session: `user()` gives `id`, `name`, `username`
(the GitHub login) and `avatarUrl`. `loggedIn()` reads `usePlutoGithubSession().loggedIn`. The
session loads in the browser only, so `loggedIn()` is `false` on the server and in the first
client render. This keeps the hydration stable. The navbar appears after hydration. `ready()`
waits for the first session read, `refresh()` reads it again and `signOut()` posts to the logout
route.
- Core's route guard sends a signed-out user on `/admin/**` (not `/admin/login`) to
`/admin/login?redirect=<fullPath>`. A signed-in user on `/admin/login` goes to the redirect or to
`/admin/home`. This is a UI guard only. The server checks every request.
- The login page is core's `/admin/login`. The driver gives the title and the description
(`pluto.github.login.*`) and the `signIn` component, `PlutoGithubSignIn`. It has one "Sign in with
GitHub" button. It is a full page load to the login route. It shows an error for `forbidden`, `not_installed` (with a link to
`https://github.com/apps/<appSlug>/installations/new` when `github.appSlug` is set), `state` and
any other value.
- Core renders the navbar. It shows on `/admin/**` (not the login page), and on public pages for
staff. The user menu has Settings and Sign out. In the local dev flow (`fs` store, local request)
the dev user is signed in with no GitHub step, so the bar shows.
- A public layout that offsets its own header should use `usePlutoAdminBar().visible`. The core
blog template still uses `usePlutoGithubSession().loggedIn` with `useMounted()`. It keeps working.
- When the repo is public, the dashboard shows a warning: drafts are visible on GitHub.
- All text uses the keys `pluto.github.*` in `i18n/locales/en.json` and `pt-BR.json`.
### What the tests cover
`test/github-auth.test.ts` (flow, redirect check, session, refresh, re-check, logout, dev user),
`test/github-origin.test.ts`, `test/github-app-token.test.ts`, `test/github-wiring.test.ts` (the adapter
registered as the Nitro plugin does it, anonymous 401, drafts hidden, a push user creates),
`test/github-admin-read-access.test.ts` (the admin read routes refuse an anonymous caller, a push user
reads, the public API still answers) and
`test/github-module.test.ts`. The fixtures are `test/fixtures/fake-github.ts` (it also fakes `/user`,
`/repos/{o}/{r}`, the OAuth token endpoint and the App endpoints), `github-auth-harness.ts` (an h3
app with a cookie jar), `github-test-config.ts` and `kit-mock.ts`.
## GitHub App setup
This is the manual path. The site can create the App for you: see "Setup from the site".
1. Create a GitHub App (Settings, Developer settings, GitHub Apps).
2. Repository permissions: Contents read and write, Metadata read. For the build status of the edit form also: Checks read, Commit statuses read, Deployments read.
3. Callback URL: `<site>/api/_pluto/auth/github/callback`. Add one for local tests if needed.
4. Turn "Expire user authorization tokens" ON. The session refreshes tokens that expire.
5. Turn "Request user authorization (OAuth) during installation" OFF. Turn webhooks off.
6. Generate a client secret and a private key (PEM).
7. Install the App on the content repo only.
8. Set the env vars of the app:
- `NUXT_PLUTO_GITHUB_SESSION_PASSWORD`: 32 characters or more, random.
- `NUXT_PLUTO_GITHUB_APP_ID`
- `NUXT_PLUTO_GITHUB_CLIENT_ID`
- `NUXT_PLUTO_GITHUB_CLIENT_SECRET`
- `NUXT_PLUTO_GITHUB_PRIVATE_KEY`: the PEM, a PEM with literal `\n` escapes, or the base64 of the PEM.
- Optional `NUXT_PLUTO_GITHUB_READ_TOKEN`: a read-only token. It replaces the installation
token for anonymous reads.
- Optional `NUXT_PLUTO_GITHUB_ALLOWED_USERS`: GitHub logins, comma-separated, without case. When
set, only these users can sign in, even with push access.
9. Set `PLUTO_GITHUB_REPO` (or `plutoGithub.github.repo`) when the default does not find the repo. For the "not installed" link, set `PLUTO_GITHUB_APP_SLUG` (or `plutoGithub.github.appSlug`).
A public repo shows its drafts on GitHub. Use a private repo for drafts. The dashboard warns about
this only when a registered content type has a status (a type with no status has no drafts).
For GitHub Enterprise Server, set `plutoGithub.github.apiUrl` to `https://<host>/api/v3`. The OAuth
pages use `https://<host>`. Any other API URL uses `https://github.com`.
### Hybrid
The default. A save is live at once: the server reads GitHub at run time, with the cache. A save of
published content also starts a build (no `[skip ci]`), and the build bundles the content again
(the snapshot). When GitHub fails, the public pages serve that snapshot (`withSnapshotFallback`). A
draft save and a media commit keep `[skip ci]`: a draft is not public, and the `/media/**` route
serves a new file until the next published save deploys it. A static output (GitHub Pages) changes
only with a build, so it needs the default too. `commit.skipDeploy: true` turns the build off: a
save is still live, but the snapshot and a static output get old.
### Skip a deploy on Vercel
`commit.skipDeploy` adds `[skip ci]` to the commit message. GitHub Actions and many CI tools read
that marker. Vercel does not read `[skip ci]` in a commit message. This is not confirmed by Vercel
docs: treat it as a rule of thumb and test it on your project. To skip a Vercel build, use an
Ignored Build Step script. It is a command that decides, from the project settings, whether
to build. With the default (`commit.skipDeploy: false`), draft saves and media commits carry
`[skip ci]`: a Vercel Ignored Build Step can read the commit message to skip them too.
## Setup from the site
The author creates the GitHub App from the site, with the GitHub App Manifest flow. No manual form
and no copy of five secrets. The manual steps of "GitHub App setup" stay as the fallback.
### Routes
All routes are GET, under `/api/_pluto/github/setup/`. The module adds them when the CMS is on. They use the same
rate limit as the sign-in routes (20 a minute for each IP) and send `Cache-Control: no-store`.
- `status`: `{ ready: true }` for an anonymous caller of a site that is set up. `ready` needs the
app id, the client id, the client secret, a private key that parses and a session password of 32
characters or more. A caller that may see more gets
`{ ready, repo, storage, callbackUrl, canCreateApp, checks: [{ id, ok }] }`: the dev local
request, a signed-in user, and anyone while `ready` is false (the login page needs it). The check
ids are `repo`, `sessionPassword`, `appId`, `clientId`, `clientSecret`, `privateKey` and
`installation`. `installation` runs only when the repo, the app id and the key are fine: it signs
an App JWT and reads `GET /repos/{repo}/installation`. `repo` is not part of `ready`. The answer
holds booleans and public names only, never a secret.
- `github/start`: answers an HTML page with a form that posts the manifest to GitHub. The form
submits itself, and has a button for a browser without JavaScript. The form action is
`https://github.com/settings/apps/new?state=<state>` for a user owner and
`https://github.com/organizations/<org>/settings/apps/new?state=<state>` for an organization
(`GET /users/<owner>` gives the `type`; a failed lookup counts as a user). GitHub Enterprise Server
uses the host of `github.apiUrl` (`oauthBaseUrl`). `state` is random. It goes in the plain cookie
`pluto-github-setup` (httpOnly, SameSite=Lax, 10 minutes, path `/api/_pluto/github/setup`, Secure on
https). It is not the sealed session: in production the session password may not exist yet.
- `github/callback?code&state`: compares `state` with the cookie in constant time, and clears the
cookie first (the state works once). Then it sends `POST <apiUrl>/app-manifests/{code}/conversions`
with no auth and answers a server-rendered HTML page. A bad `state` or `code` gives 400 and a
failed conversion gives 502, both with a page that links to `start`. Nothing is stored. The
secrets go only to the browser that ran the flow, and no log holds a value.
The origin of the site is `getRequestURL(event, { xForwardedHost: true, xForwardedProto: true }).origin`.
### Who can run it
`start` and `callback` run for the dev local request (`import.meta.dev` and `isLocalRequest`, the rule
of the dev local user), or for any request while `ready` is false. When the site is set up, in
production, both answer 404. The secrets only go to the browser that runs the flow.
### The manifest
`buildAppManifest` (in `utils/github-app-setup.ts`) builds it:
- `name`: "<site name> CMS", 34 characters or less. The site name is `public.websiteName`, else the
repo name. The author can change it on GitHub.
- `url`: the origin. No `hook_attributes`: the App has no webhook, and GitHub refuses a local hook
URL even when the hook is off.
- `redirect_url`: `<origin>/api/_pluto/github/setup/callback`.
- `callback_urls`: `<origin>/api/_pluto/auth/github/callback`, plus
`http://localhost:3000/api/_pluto/auth/github/callback` when the origin is not local.
- `public: false`, `default_permissions: { contents: 'write', metadata: 'read', checks: 'read', statuses: 'read', deployments: 'read' }`,
`default_events: []`, `request_oauth_on_install: false`.
### The result page
The page has the env block in a textarea with a Copy button, the install link
(`https://github.com/apps/<slug>/installations/new`) and the next steps. The block has
`NUXT_PLUTO_GITHUB_APP_ID`, `NUXT_PLUTO_GITHUB_CLIENT_ID`,
`NUXT_PLUTO_GITHUB_CLIENT_SECRET`, `NUXT_PLUTO_GITHUB_PRIVATE_KEY` (the base64 of the PEM, on
one line), `PLUTO_GITHUB_APP_SLUG`, and `NUXT_PLUTO_GITHUB_SESSION_PASSWORD` (new random) when the site has
no valid one. The pages are plain HTML with inline CSS, light and dark with `prefers-color-scheme`.
They use the server translator (`usePlutoServerTranslator`) with the first tag of `Accept-Language`
(`pluto.github.setup.page.*`).
In development (the dev local request), the route also writes the values into `<rootDir>/.env`:
`updateEnvText` replaces a key that exists, appends the others, keeps the other lines and their
order, and handles a multi-line quoted value. The page says so, and warns when `.gitignore` does not
ignore `.env`. If the write fails, the page tells the author to copy the block. The module gives
`runtimeConfig.plutoGithub.rootDir` in development only. `PLUTO_GITHUB_APP_SLUG` is read when Nuxt starts,
so a dev server needs a restart.
### Private key formats
`normalizePem` (`github/app-token.ts`) accepts a PEM with real line breaks, a PEM with literal `\n`
and the base64 of the PEM (no `-----BEGIN` in the value: it decodes, and uses the result when it has
`-----BEGIN`).
### In the admin
- The login card (`PlutoGithubSignIn`): when the status says `ready: false`, it shows
`PlutoGithubSetupPanel`: a warning, then the actions first (the **Create the GitHub App** button
when `canCreateApp`, an **Install the App** link when the installation check fails and the slug
is known, and a link to the quickstart), then the checklist with a short fix for each missing
item. The checklist is folded (`UCollapsible`, the trigger shows "2 of 6 done",
`pluto.github.setup.progress`). It opens by itself only when the panel has no action button. The
Sign in button is disabled while `ready` is false. A failed status read keeps it on.
- The **GitHub** tab of Settings: `/admin/settings/github`. The `settingsPages` entry (id `github`,
order 150, no capability) is in the CMS client plugin. The module adds the route with
`extendPages`, as a child of `settings`, from `app/components/Pluto/Github/PlutoGithubSettingsPage.vue`.
It shows the same panel (the Create button, then the folded checklist) and the callback URL to use
(with a Copy button).
- `usePlutoGithubSetup()` (`runtime/app/composables/pluto-github-setup.ts`) reads the status after
hydration (`server: false`, key `pluto-github-setup`).
### Files and tests
- `utils/github-app-setup.ts`: the pure helpers (manifest, form action, conversion parser, env
entries and block, `.env` updater, `.gitignore` check, key check, setup checks).
- `utils/github-setup-pages.ts`: the pure HTML pages (`escapeHtml`, start, result, error).
- `utils/github-setup-flow.ts`: the handlers (access rule, status, start, callback, `.env` write).
- `api/setup/status.get.ts`, `api/setup/start.get.ts`, `api/setup/callback.get.ts`.
- Tests: `test/github-app-setup.test.ts` (pure helpers), `test/github-setup.test.ts` (the routes with
the real locale files), and the key formats in `test/github-app-token.test.ts`.
## Editor
The admin edits the body of a post with a Markdown editor. The widget is
`app/components/Pluto/Github/PlutoFieldMarkdown.vue`. It is a `richtext` field widget. It follows
the widget contract of the content-model skill: the props `field`, `modelValue` and `disabled`,
and the event `update:modelValue`. `PlutoContentField` gives it the translated field text.
- It uses `UEditor` (Nuxt UI, Tiptap) with `content-type="markdown"`. The model value is a
Markdown string. The editor sends `editor.getMarkdown()` on each change. The adapter stores that
string as the file body.
- `UEditorToolbar` has the built-in items: undo, redo, Paragraph and headings 1 to 4 (one menu), bulleted and numbered
lists, quote, code block, bold, italic, strikethrough and inline code. The items come from
`usePlutoMarkdownToolbar({ link, image })` (`app/composables/pluto-markdown-toolbar.ts`), so
another editor can share them. The link button is a slot (`PlutoGithubEditorLink.vue`, a
popover with the URL). The image extension is on, so an image in the Markdown stays. The image
button (`PlutoMediaEditorButton`, the media picker) shows when the app has a media library. The
mention extension is off.
- Blocks, like the other editors: a bubble toolbar over a selection (`usePlutoMarkdownBubbleItems`:
the marks and the link slot; `bubbleShouldShow` keeps the rule of Tiptap, but not for a selected
block). A caret in a link opens the link popover (`PlutoEditorLinkMenu`, a `BubbleMenu`): its
address and its text, applied on Enter or when a field loses the focus, the "Open in a new tab"
box, Open, and Remove (the text stays). The box sets the `target` of the link mark; the caret
stays. The link is `PlutoLink` (app/utils/pluto-link.ts), in place of the starter kit link
(`link: false`): it has no default target (the starter kit gives every link `_blank`, which
Markdown cannot hold), a pasted link keeps only `_blank`, and it reads and writes the MDC
attribute `[text](url){target="_blank"}` (an inline tokenizer, and the mark closing). The shared
matcher is `shared/markdown/link-target.ts`: `renderMarkdown` keeps the attribute through
`stripMdc` (other forms such as `{target=_blank .x}` too) and renders `target="_blank"` with
`rel="noopener noreferrer"` (`plutoBlankLinkExtension`); the sanitizer keeps `target` only as
`_blank` and sets that `rel`; `findUnsafeMarkdown` does not count the exact form as attributes, so
the post stays in Visual mode. Test: `test/markdown-link-target.test.ts`. The link popover never
takes the focus (a click in a link is for its text). A click on a
video (a pointerdown on `.pluto-embed-node` less than 1 s before `onShow`) focuses the address
of its popover with the text selected; a block selected with the keys keeps the focus in the text.
Escape in a field goes back to the text. A click on an image opens its popover (`PlutoEditorImageMenu`): alt text, Replace (media picker), Open, Remove. The link, video and image popovers share `PlutoEditorBubble` (a `BubbleMenu` with the panel and an arrow that it places after each move, `onUpdate`, on the side and at the start of the target). Every floating thing of the editor has an arrow: Reka poppers by the admin defaults; the bubble toolbar (`placement: top`, `flip: false`) and the Markdown bubble with `.pluto-editor-arrow-bottom`; the "/" menu (it ignores its `ui` prop) by CSS on `.ProseMirror ~ div > [role=listbox]`, `flip: false` and a `size` that shortens it near the bottom. Popovers open at `bottom-start`: a centered one can overflow a narrow column, and focusing
its field scrolls the column sideways. The menus take `Editor` from `@tiptap/core` and find a
mark range by hand: `getMarkRange` of core types against another copy of `prosemirror-model`.
The compose panel has a left gutter (`ps-14`) and `pe-4`. With the preview off, the column is
centered (`max-w-3xl`); when the panel has room for the buttons beside it (an `@container`,
`@min-[55rem]`), the padding is `ps-4` on both sides and the buttons use the free space, so the
column stays in the middle. The editor element reaches into the gutter (`-ms-14 ps-14`): Tiptap
hides the handle when the pointer leaves the editor, so without it the buttons vanished on the
way to them. The text
has no side padding, so it starts at the left edge of the toolbar, under the title. In the gutter,
`UEditorDragHandle` (the default `left-start` placement, no flip, its `hover` event) shows the grip of a block
(drag to move; a click opens Duplicate and Delete, `pluto.github.editor.duplicate`, `remove`), or the
"+" of an empty line. The "+" opens a dropdown with the block items (paragraph, headings 1 to 4,
lists, quote, code block, the site components) and runs the chosen item on that line. No "/" is
typed. `/` in an empty line
opens `UEditorSuggestionMenu` (`usePlutoMarkdownSuggestionItems`: paragraph, headings 1 to 4,
lists, quote, code block, then the content components with the `plutoComponent` handler, passed
to `UEditor` with `handlers`). `PlutoTrailingParagraph` (`app/utils/`) keeps an empty line at the
end (not in the undo history), and the widget trims the blank lines at the end of the Markdown, so
an open post stays unchanged. `UEditor` loads its model value again (`setContent`) whenever it
differs from its own `getMarkdown()`, so the widget gives it back its own last Markdown
(`editorValue`) while the value is one that the widget gave. The widget gives the value at most
every 200 ms while the author types, and at once on blur (`plutoFlushOnBlur`) and unmount; the
Markdown code editor does the same (`flushValue`, `emitted`). `PlutoThrottledState` (`app/utils/`)
swaps the `reactiveState` ref of the Tiptap Vue editor for one that renders at most every 120 ms
(the state itself stays current): every toolbar button reads it, so each key rendered both
toolbars again (63 ms a key on a long post; 7 ms after). Never bind the trimmed value: the editor
reloads at each key, a reload drops a space at the end of a line, and the caret leaves the line
(Backspace in a heading selected and deleted it). The text has `pt-12`, so the bubble toolbar of the first line does
not sit under the main toolbar. Core sets `vite.resolve.dedupe` for the ProseMirror packages: a
nested copy of `prosemirror-model` broke the slash menu.
- The editable area has a minimum height (`min-h-96`) in a bordered box with a sticky toolbar, so
a click anywhere in the box puts the cursor in the text. The post type shows the widget through
the post editor (see below).
- With the `canvas` prop, the widget has no label, no border and no mode switch. The toolbar is `-mx-2` (as wide as the focused title) and a
separate rounded bar (white with a soft shadow in light mode, the dark sidebar color in dark mode;
see the admin-theme skill), sticky at `top-2`. The text has `pt-8` under it, and fills the rest
of the height of the compose panel (it does not scroll on
its own: the compose panel scrolls). The post editor uses it for the Visual mode.
- The toolbar is `PlutoMarkdownToolbar` (`app/components/Pluto/Markdown/`): one row. The buttons
that do not fit go into a **More tools** popover (`i-lucide-ellipsis`, `pluto.markdown.moreTools`)
at the end of the row, as the same buttons; the item slots (link, image, component) work in both
places. It measures one button and one separator, then counts (`useElementSize`). A layer can use
it for its own Tiptap editor (props `editor`, `items`, `ariaLabel`; the item slots).
- The text comes from `pluto.github.editor.*` in `en.json` and `pt-BR.json`.
- The client plugin registers the widget as a `contentFieldWidgets` entry for
`fieldType: 'richtext'`, in CMS mode only. It uses `defineAsyncComponent`, so Tiptap loads on the
edit page only. Core has no `richtext` widget, so nothing else competes for the type.
### Source mode
The widget has a Visual/Source switch. Source is `PlutoMarkdownSource`: a monospace textarea that
grows with the text, with `spellcheck="false"`. It never parses or rewrites the text.
- `PlutoTextField.editor?: 'auto' | 'visual' | 'source'` (a `richtext` field, default `auto`)
picks the first mode. `visual` and `source` are fixed. `auto` opens Source when the text has
syntax that the visual editor cannot keep. `pickMarkdownEditorMode(editor, text)` is the pure
rule.
- `findUnsafeMarkdown(text)` (`shared/utils/markdown-syntax.ts`, auto-imported) lists that syntax,
one issue `{ kind, line }` per kind: `mdc-block` (`::note`), `mdc-inline` (`:icon{}`,
`:kbd[x]`), `attributes` (`](..){..}`, `]{..}`, and inline code followed by `{..}`), `html`,
`table`, `task-list`, `footnote` and `fence-meta` (a code fence with more than a language). Text
in a code fence or in inline code is ignored.
- The Visual button is off while the text has such syntax, with a tooltip
(`pluto.github.editor.unsafe`). It turns on again when the author removes the syntax in Source. An
explicit `editor: 'visual'` still opens Visual: the author of the type owns that choice.
- `PlutoMarkdownSource` props: `modelValue`, `disabled`, `placeholder`, `rows` (18), `maxRows`,
`ariaLabel`, `fill` (fill the height of the parent; the text scrolls and the box does not
grow). Slot `toolbar` (slot props `insert`, `focus`). Exposed: `insert(text, { block })` (it
replaces the selection and puts the caret after the text; `block` adds a blank line before and
after), `focus()` and `goToLine(line)` (the caret goes to the start of the line, from 0, and the
line scrolls to the top). `insertMarkdownText` is the pure helper. The CMS module registers the
short name `PlutoMarkdownSource` (only when the CMS is on) with `addComponent`, because the
folder name would make the auto name `PlutoGithubPlutoMarkdownSource`. A
layer uses it to build its own field widget.
- i18n keys: `pluto.github.editor.visual`, `source`, `unsafe`, `mode`.
### Post editor (`post-canvas`)
The `post` type edits its body in the post editor, like the page editor of the docs
layer. The type sets `widget: 'post-canvas'` on the `content` field and `form: { layout:
'canvas', canvasField: 'content', leftPanel: { label: 'pluto.post.outline', … } }`. Core owns the
editor (`app/components/Pluto/Post/`), so any layer with a Markdown `richtext` body can use it.
`@plutocms/supabase-blog` uses it too.
- `PlutoFieldPostCanvas.vue` is the widget. Core registers it by name only
(`widget: 'post-canvas'`), so it never competes for `richtext`. Outside a canvas form it shows
the `richtext` widget as a normal field.
- One scroll area and one text column serve both the Visual and the Markdown mode. The column is
`ps-14 pe-4`, and centered at `max-w-3xl` when the preview is off. The scrollbars of the editor and
of the aside have no track (`scrollbar-thumb-(--ui-border-accented)`). The editor keeps the room of
the scrollbar (`scrollbar-gutter-stable`).
- The canvas is one `USplitter` in both modes (stacked under `lg`): the compose panel and the
preview. The cookie `pluto-post-split` keeps the sizes; the items read it only when the preview
opens (`splitStart`): items rebuilt from the cookie at each move gave the splitter new default
sizes, which ended the drag after one pixel. The compose panel has a footer with
the Visual/Markdown switch (`PlutoPostModeSwitch.vue`, `@mousedown.prevent` so the text keeps
the focus; a switch focuses the other mode at the caret, `whenTextReady(..., force)`), the Zen
buttons, and, at the end, the **Preview** switch (`USwitch`). While the editor of a mode loads,
a skeleton (toolbar and lines, `textReady`) covers its area. With the preview off, the splitter
has the compose panel alone (its size is not saved). The text keeps a readable width
(`max-w-3xl`, in the middle) with or without the preview (`columnClass`, a container query on
the compose panel). On desktop
the cookie `pluto-post-preview` keeps the choice (default off: the editor gets the room; the docs editor keeps its preview on); under `lg` it starts off.
- Zen mode (`app/composables/pluto-zen.ts`): `usePlutoZen()` gives `active` (`useState`, for the
page) and `hideToolbar` (cookie `pluto-zen-toolbar`). `usePlutoZenPanel(open)` closes a panel
while it is on and opens it again after if it was open (a panel opened during Zen stays open);
the admin layout uses it for the sidebar (`v-model:collapsed`), the form for its left panel and
its aside. The form ends Zen mode when it unmounts, after its panels restore (so no closed state
stays in their cookies). With `hideToolbar`, the canvas root has
`data-pluto-zen-toolbar="hidden"` and `pluto-layer.css` hides `[data-pluto-editor-toolbar]`.
- The left panel (the Outline) starts closed. The rail of the form (the `#rail` slot of
`PlutoViewAdminPanel`, see the admin-view-chrome skill) has its button (`i-lucide-list-tree`),
and its header has an X (`PlutoViewLeftCollapse`).
- The compose panel has the background of the text (`bg-default`). Above the editor (both modes)
is the title of the item: `PlutoPostTitle`, a large bold field (`UTextarea`, `variant="none"`,
`autoresize`) with no label, no border, no side padding (it starts at the left edge of the
toolbar) and the placeholder "Add a title"
(`pluto.post.titlePlaceholder`). Enter goes to the text. A validation message shows under it. The title hints that it is
editable: the text is at 70% opacity (100% on hover and focus), a soft background shows only on
focus, the cursor is a pointer at rest, and a pencil icon shows in the left gutter on hover (hidden
on focus). The alerts of the form show above it (`claimAlerts`).
The widget takes the `titleField` of the type out of the right panel (`claimFields` of the
canvas host), and writes it with `usePlutoContentForm().updateField`, so the slug still follows
the title on a new item.
- **Visual** mode shows the `richtext` widget of the app
(`usePlutoContentFieldWidget({ ...field, widget: undefined })`) with the `canvas` prop. The
title, the widget toolbar and the text scroll together in the compose panel. A `richtext`
widget of a layer must accept `canvas`: no label, no border, a sticky toolbar bar, and a root
that grows (`flex-1`) so the text fills the rest of the height.
- **Markdown** mode shows `PlutoMarkdownCodeEditor` (`bare`: the toolbar of the Visual editor, no
box, no side padding; the editor grows with the text and the parent scrolls), loaded on demand.
See "Markdown code editor" below.
- The caret is one unit for both modes: its offset in the Markdown (`app/utils/pluto-caret.ts`). Visual to
Markdown: a private-use marker at the caret, the document written as Markdown, the marker found
(`plutoMarkdownCaret`). Markdown to Visual: the marker in the text, parsed, the same text block
of the editor (video lines do not count) at the same offset (`plutoVisualCaret`). A switch of mode
keeps the caret; localStorage (`pluto-caret:<type>:<id>`) keeps it between visits as an offset
and the 24 characters before it (`plutoCaretAnchor`, `plutoFindCaret`: the file on disk can be
written a little differently from the editor), saved a second after the caret stops, on a switch
and on `pagehide`; an item opens with the caret there and the focus. A new item focuses its text.
- Visual is off while `findUnsafeMarkdown` finds syntax, or when the app has no `richtext`
widget. The cookie `pluto-post-editor-mode` keeps the last mode.
- The left panel (`PlutoPostOutline.vue`, in the `PlutoViewSidePanel` shell) lists the headings, each with the icon of its level (`i-lucide-heading-1` to `-6`) (`plutoMarkdownHeadings(text)` in
`shared/utils/markdown-headings.ts`: ATX and setext headings, not in a code fence, in the order
of the rendered `h1` to `h6`). A click scrolls the preview to the heading, and goes to it in the
editor: the caret goes to the end of the heading, and the heading scrolls 16px under the sticky
toolbar of the widget (the widget marks its toolbar with `data-pluto-editor-toolbar`). In Markdown
mode the caret goes to its line (`goToLine`); in Visual mode the editor uses the nth heading of
`.ProseMirror`. The heading that holds the caret is the active item of the outline
(`aria-current="location"`).
- The other fields are in the right panel.
#### Markdown code editor
`app/components/Pluto/Markdown/PlutoMarkdownCodeEditor.vue` is the Markdown editor on CodeMirror 6
(it came from the docs layer, which uses it too). The text shows its format as the author
types, and the marks stay visible, dimmed. Headings are bold and yellow (every line keeps one size).
From the syntax tree of the visible lines (`markdownLook`): inline code is a tinted pill, its
backticks too; a quote line has a bar at its left; a list mark is primary and semibold. MDC lines
(components, slots, YAML props) are colored like code (`mdcLineKinds` and `mdcLineTokens`,
`shared/utils/mdc-lines.ts`, tested in `test/markdown-format.test.ts`): dimmed colons, braces and
`=`, the component name in primary, attribute and prop keys, string and literal values and slot
names in the `--pluto-code-*` colors; nothing of the Markdown look shows inside them. A code block is a tinted box with 12px at its
sides and rounded corners (`cm-pluto-code-first`/`-last` on its first and last line), and its code
has the colors of its language: the language is `markdownWithCode`, built from `markdownLanguage`
with `parseCode` (`@lezer/markdown`) and `@codemirror/language-data`, which loads a language the
first time a fence names it (not `markdown()`, which imports the HTML language). The colors are the
`--pluto-code-*` variables of `pluto-layer.css` (`codeStyle`), the same as the Visual mode. The
Visual mode has `PlutoCodeBlock` (`app/utils/pluto-code-block.ts`): `CodeBlockLowlight` (lowlight,
the `common` grammars) with the node view `PlutoEditorCodeBlock`, a language select at its top
right (shown on hover, or while the caret is in the block; `PLUTO_CODE_LANGUAGES`, an alias such
as `ts` shows as its language and stays as written; Plain text is a fence with no info). The
widget turns the code block of the StarterKit off (`starter-kit="{ codeBlock: false }"`). Pin
`@tiptap/extension-code-block-lowlight` to the Tiptap version of core: it wants exact peers. A toolbar has the quick
formats with their shortcuts (`formatMarkdown`, `shared/utils/markdown-format.ts`, tested in
`test/markdown-format.test.ts`). It has search and history.
- Props: `modelValue`, `disabled`, `placeholder`, `ariaLabel`, `fill`, `minLines` (18),
`monospace` (all the text in the monospace font at 14px; the post editor sets it). Slots:
`toolbar` (slot props `insert`, `focus`) and `toolbar-end`. Exposed: `insert`, `focus`,
`reveal(start, end)` and `goToLine(line)` (the caret goes to the end of the line, from 0).
- Event `cursorLine`: the line of the caret, from 0.
- With `bare`, the editor has no box and no side padding (a CodeMirror theme with `Prec.high`, not a
Tailwind `!` class: a layered important utility beats every unlayered rule, and a quote line
needs its own padding), and it grows with the text (the parent scrolls). Its toolbar is the one
of the Visual editor, in the same sticky rounded bar (`data-pluto-editor-toolbar`), with the same
groups, icons and `pluto.github.editor.*` labels: undo and redo (off with no step), the headings
menu (Paragraph, H1 to H4: `headingMarkdown`), the lists menu, quote, code block, the inline
formats and link, the image (the media picker, `` as a block) and the component menu
(`writeEmptyComponent` as a block). The entries are data (`PlutoMarkdownToolbarItem`, rendered by
`PlutoMarkdownToolbarEntry`); the ones that do not fit go into a More popover, like
`PlutoMarkdownToolbar`. A bubble toolbar (bold, italic, strike, code, link) shows over a
selection. The `.cm-scroller` keeps the room of the scrollbar only with `fill`. The docs layer
does not use `bare` and keeps the quick formats toolbar.
- It uses `markdownLanguage`, not `markdown()`, which would add the HTML, CSS and JavaScript
languages.
- Load it on demand (`defineAsyncComponent`, or `LazyPlutoMarkdownCodeEditor`): CodeMirror is
about 110 KB gzip.
- i18n keys: `pluto.markdown.formatting`, `pluto.markdown.format.*`.
#### Preview
The preview is an iframe of `/_pluto/post-preview` (`PLUTO_POST_PREVIEW_PATH`), so the post shows
with the CSS of the site. It is not under `/_pluto/preview`, because the visual block editor owns
that page. `isPlutoPreviewPath` covers both paths (no admin bar, no index).
- `PlutoPostPreviewFrame.vue` sends the text to the frame with `postMessage`. The frame renders it
with `plutoPostPreviewHtml` (an auto-import; app code must not import `shared/markdown/` with a
relative path, because the server build of pluto keeps its own `shared/` external), which calls
`renderMarkdown` (`shared/markdown/render.ts`: marked, MDC stripped, the allowlist
sanitizer), the same code as the public API. The render waits 150 ms after a change. A frame
that does not answer in 12 s shows an error with a retry.
- The protocol is in `shared/utils/post-preview-protocol.ts`. The parent sends `render`
(`contentType`, `item` without the body, `markdown`), `scroll-to` (a heading index), `inset`
(`end`, 0 to 200 px) and `color-mode` (`mode`: `light` or `dark`, the resolved mode of the admin,
on `ready` and on each change; the page sets the class and `color-scheme` of `<html>`, not the
stored preference, which the admin shares). The frame sends `ready`. Both sides accept a message only from the same
origin, and only from the parent window or the frame.
- While the right panel is closed (`panelToggles.right`), the editor sends `inset` `{ end: 40 }`:
the page sets `padding-inline-end` on `<html>`, so the open button floats over the margin of
the page, not over the post. The page has the thin scrollbar of the docs layer preview.
- A "Preview" badge (`pluto.post.previewBadge`) sits at the top right of the frame (moved left
while the open button shows). It fades out while the pointer is on the preview
(`group-hover`), so it never hides the page.
- The post types set `previewUrl` for a published post, so the form shows "View Post"
(`pluto.form.viewItem`): `/posts/<slug>`, the post page of both blog templates (the GitHub
CMS and `@plutocms/supabase-blog` use the same path).
- The menus of the visual Markdown toolbar (Heading, the link popover) are
`dark:bg-neutral-950` through `UTheme`, so they stand apart from the editor box in dark mode.
- The page shows `PlutoPostPreview` with the props `contentType` and `item`. `item` is a
`PlutoPreviewItem` (`toPreviewItem`, `shared/utils/content-preview.ts`): the form item in the
shape of the public API. It has `html` (the rendered body), the dates as `createdAt`,
`updatedAt` and `publishedAt` (from `type.timestamps` and `status.publishedAtColumn`, else
`<key>At`, else `<key>_at`), and each media field holds its record (an array for `multiple`,
else one record or `null`). The page reads the records with `usePlutoMedia().get`, once per id
(`previewMediaIds`). So the post component of a site renders the preview item as it is. The
default (`app/components/Pluto/Post/PlutoPostPreview.vue`) shows the title, the date, the
excerpt and the body. An app replaces it with its own `components/PlutoPostPreview.vue` with the
same props, to use the layout of its post page. Test: `test/content-preview.test.ts`. Put `data-pluto-post-body` on the element of the
body: `scroll-to` finds the headings in it. The blog templates have one.
- i18n keys: `pluto.post.*` (`outline`, `outlineEmpty`, `outlineEmptyHint`, `mode`, `visual`,
`markdown`, `visualBlocked`, `previewTitle`, `previewBadge`, `previewLoading`, `previewFailedTitle`,
`previewFailed`).
Limits of the editor:
- The visual editor knows CommonMark and strikethrough. It has no node for MDC, a GFM table, a
task list or raw HTML. Source mode is the way to edit a post that has them. The public page
still renders tables and task lists from the stored Markdown.
- The editor can write the Markdown with other marks than the author used (for example `-`
for a bullet). The text means the same.
- No test mounts the widget. The repo has no Vue component test setup.
## Public read
The public site reads published posts through core's public API: `GET /api/pluto/v1/content/post`
and `GET /api/pluto/v1/content/post/<slug>`, with `usePlutoPublicList` and `usePlutoPublicItem`.
See "The public API" in the content-model skill for the routes, the query, the answer, the cache
and CORS. The post type sets `api: { public: true }`. A public read is anonymous by design: core
calls `markPublicRead` (the same mark as `markGithubAnonymous`) before it reads. `getGithubAccess` then
returns `null` and the session cookie is never opened. So the answer is the same for every visitor,
drafts never show (not even to a signed-in editor), and the response never sets a cookie.
### What the Markdown adapter adds
The adapter implements `timestampKeys` (the `createdAt`, `updatedAt` and `publishedAt` frontmatter
keys of the type) and `toPublic`:
- A list item has no body. It has `excerpt`: the `excerpt` value of the item when it has text, else
`markdownToPlainText(body, 200)`.
- One item keeps the Markdown body and adds `html`: the body rendered and sanitized.
- `list` applies `query.filters` by the text of each item value (a list matches when it has the value).
Every CMS type gets this, also the docs types of the Nuxt Content layer.
### Rendering
`utils/markdown.ts` has `renderMarkdown(md)`, `markdownToPlainText(md, maxLength)` and `stripMdc(md)`.
`renderMarkdown` first runs `stripMdc`: the MDC syntax of Nuxt Content goes (`::name` and `::` lines, the
YAML props block right after an open line, `#slot` lines inside a component, inline `:component{…}`, and
`{…}` attributes after a span or a link) and the text stays, so a docs page has clean `html` and a clean
`excerpt` on the public API. Code in a fence does not change. A heading needs a space after `#`, so a
`#slot` line never looks like one.
`renderMarkdown` uses `marked` with GFM. The `html` renderer returns an empty string, so raw HTML
in Markdown never reaches the output. A URL alone on its line gets `data-pluto-embed` (see the
content-model skill, "Embeds"). Then `sanitizeHtml` runs on the result. The rendered HTML is
cached by blob id (`html:2:<oid>`, the `_version` of the item; `HTML_CACHE_KEY` has a version to
change when the renderer gives other HTML), and the fallback excerpt too
(`excerpt:<oid>`), through the cache of "Storage". A blob id never changes, so an entry never goes
stale.
`utils/sanitize-html.ts` is an allowlist sanitizer on `ultrahtml`. It is a port of
`richtext-sanitize.ts` of `@plutocms/supabase-blog`, with the same tests
(`test/github-sanitize-html.test.ts`).
- Kept elements: `p h1-h6 strong b em i s del u code pre blockquote ul ol li hr br a img table thead
tbody tr th td input`.
- Dropped with their children: `script style iframe object embed template noscript svg math link
meta base form button select textarea audio video source track canvas applet frame frameset
portal`. Any other element is unwrapped: the tag goes and the text stays.
- Kept attributes: `a`: `href`, `title`. `img`: `src`, `alt`, `title`, `width`, `height`. `code`: a
`class` of the form `language-*`. `input`: only a checkbox, with `checked` and `disabled` as
flags. `th` and `td`: `align` (left, center, right). Every other attribute goes, so `on*` and
`style` go.
- URLs: no scheme (relative, `#`, `?`), `http:`, `https:` and `mailto:` pass. `data:` passes only
for `image/png`, `jpeg`, `gif`, `webp` and `avif`. Other schemes go. The check decodes entities
and strips control characters first, so `javascript:` fails. A bad `href` or `src` is
removed and the element stays.
- Attribute values are escaped, so a quote cannot start a new attribute.
- The original sanitizer adds no `rel` or `target` to a link, and this port does the same.
### `PlutoHtml`
`app/components/Pluto/PlutoHtml.vue`, a core component for every backend. Props: `html: string`,
`tag = 'article'`, `class`. It sets the server-sanitized HTML of a public item as `innerHTML`, with
the same pattern as `PlutoProse` (a plain camelCase `innerHTML` prop, not `v-html`, so SSR keeps
it). It never parses or sanitizes on the client. The typography is the base of the Nuxt UI editor
theme (semantic tokens such as `text-highlighted` and `border-default`), plus table styles. The
Git CMS and `@plutocms/supabase-blog` both send sanitized `html`, so one site page works with
either backend. Pass only the `html` of a public item to it.
Use on a site page:
```vue
<script setup lang="ts">
const route = useRoute()
const { data } = await usePlutoPublicItem<{ title: string; html: string }>(
'post',
String(route.params.slug)
)
</script>
<template><PlutoHtml v-if="data" :html="data.data.html" /></template>
```
For a list page:
```vue
<script setup lang="ts">
const { data } = await usePlutoPublicList('post', { limit: 10 })
</script>
<template>
<article v-for="post in data?.data" :key="post.id">
<h2>{{ post.title }}</h2>
<p>{{ post.excerpt }}</p>
</article>
</template>
```
### What the tests cover
`test/github-markdown.test.ts` (GFM, XSS vectors, plain text), `test/github-sanitize-html.test.ts`
(the allowlist), `test/github-public.test.ts` (the posts through the public API: drafts, excerpt,
paging, sort, filters, 400 and 404, the cache header, no cookie, anonymous with a session) and
`test/github-module.test.ts` (no public route and no middleware in the module).
## Build status
After a save, the site can take some minutes to change. The edit form shows the build of the newest
commit of the content branch that did not skip CI, next to the Save button. A draft save skips the
deploy, so that commit has the builds that serve the site. A draft that was never public in the page
(`isPublicItem` of `client-rules.ts`, read when the item of the page has loaded and after each save) shows no status and
calls nothing. It shows only for GitHub storage with
`commit.skipDeploy` false (the default: a save then starts a deploy). With the `fs` store, or with
`skipDeploy` on, nothing shows. The module copies `skipDeploy` to `runtimeConfig.public.plutoGithub`,
and `showBuildStatus` (`runtime/shared/client-rules.ts`) is the test.
### Route
`GET /api/_pluto/github/build-status`. It needs a signed-in user (401 otherwise)
and reads with the token of that user. The answer has `Cache-Control: no-store`. The `fs` store
answers `none` with no GitHub call.
It reads the 20 newest commits of the branch (`GET /repos/{repo}/commits?sha={branch}&per_page=20`)
and picks the newest one with no skip marker (`pickDeployCommit`; `hasSkipMarker` reads `[skip ci]`,
`[ci skip]`, `[no ci]`, `[skip actions]` and `[actions skip]`, in any case, like GitHub Actions). With
no such commit, the newest one. Then, for that sha, three sources at the same time:
- check runs (`/commits/{sha}/check-runs`): GitHub Actions and apps. `html_url` is the Action run.
- commit statuses (`/commits/{sha}/status`): for example Vercel. `target_url` is the build page.
- deployments (`/deployments?sha=`), the newest of each environment, and the latest status of each
one (`/deployments/{id}/statuses?per_page=1`). At most 5 environments.
The sources of one user and sha stay in memory for 3 seconds, so several tabs share the calls. A
403 or 404 on a source means that the App cannot read it. The source is skipped and its kind is in
`unavailable`. A GitHub rate limit gives 503 with `Retry-After`, a rejected token 401, any other
failure 502 (the same `pluto.github.errors.*` keys as the adapter).
The answer (`PlutoBuildStatus`, `runtime/shared/build-status.ts`):
```ts
{ sha, shortSha, message /* first line */, committedAt?, state: 'none' | 'pending' | 'success' | 'failure',
items: [{ kind: 'check' | 'status' | 'deployment', name, state: 'pending' | 'success' | 'failure',
url?, startedAt?, completedAt?, description? }],
unavailable?: ('check' | 'status' | 'deployment')[] }
```
### The reducer
`reduceBuildStatus({ checkRuns, statuses, deployments })` is pure (`runtime/shared/build-status.ts`).
- Check run: not `completed` is pending. `success`, `neutral` and `skipped` are a success. Every
other conclusion (`failure`, `cancelled`, `timed_out`, `action_required`, `stale`) is a failure.
- Commit status: `success`, `pending`, and `failure` or `error` (a failure). Unknown is pending.
- Deployment: `success` and `inactive` are a success. `failure` and `error` fail. `queued`,
`pending`, `in_progress` and a deployment with no status yet are pending.
- Commit state: `none` with no item. `pending` while any item is pending (even if another failed).
Else `failure` when any item failed. Else `success`.
- `url` keeps an `http` or `https` URL only.
### The item in the toolbar
`app/components/Pluto/Github/PlutoGithubBuildStatus.vue` is a `contentToolbarItems` entry with
`contentType: '*'` and `order: 50` (see the admin-view-chrome skill). The CMS client plugin
registers it, lazy, only when `showBuildStatus` is true.
- A type with `liveOnSave` (see the content-model skill) shows a save at once: after a save the item
shows the check and "Live" without waiting for the first answer. While the state is `pending` a
small spinner shows by the state, and the popover says "Static build in progress". When the
build fails, the item keeps "Live", the state button gets a warning tint, and the popover says "The
static build failed. The site serves the change at run time until a build passes." On open, the item
shows "Live" once the status is known. Without `liveOnSave` nothing changes. The post type sets
`liveOnSave`: the site reads the posts at run time.
- Pending: a spinner and "Publishing…". Success: a check mark and "Live". Failure: an error icon
and "Build failed". `none`, and a failed read: nothing. The text hides below `md`.
- The state ("Live", "Publishing…", ...) is the button that opens a popover (`UPopover`), with no
separate Info icon: the commit (short sha, message, time) and each
item with its state, time, description and a link button ("View the Action" for a check run,
"View the build" for a status or a deployment). `unavailable` adds a hint about the App
permissions.
- Polling (`createBuildPoller`, `runtime/shared/build-poller.ts`, with the rules in `shouldPoll`):
one read when the item of the edit page has loaded (`editing && !loading` of the form) and after each save (`usePlutoContentForm().onSaved`, which
forgets the old answer first). Then every 5 seconds while the state is `pending`. It stops when
the state is final, after 15 minutes, and while the page is hidden (it reads again when the page
shows). After a save, `none` is not final for 60 seconds, because GitHub needs some seconds to
create the checks. Errors back off (10 s, 20 s, up to 60 s). It stops on 401 or 403, and after 5
errors in a row.
- `usePlutoGithubBuildStatus()` (`runtime/app/composables/pluto-github-build-status.ts`) holds the state
for one component: `status`, `failed`, `check()`, `afterSave()`, `stop()`.
### GitHub App permissions
The App needs read access to **Checks**, **Commit statuses** and **Deployments**. The App manifest
of the setup flow asks for them (`checks`, `statuses`, `deployments`: `read`). An App that was
created before this feature lacks them: GitHub answers 403, the sources are `unavailable`, and no
item shows. Add the three permissions in the App settings, and accept them on the installation.
### Tests
`test/github-build-status.test.ts` (reducer, URL and headline helpers, `shouldPoll`,
`showBuildStatus`), `test/github-build-poller.test.ts` (the loop, with fake timers) and
`test/github-build-status-route.test.ts` (the route with a fake GitHub).
## Status
All parts of v1 are built: the module, the stores, the Markdown content adapter, GitHub App
sign-in and the session, the editor, the public read routes, `PlutoHtml`, and the user docs
(the "Standalone mode" section of README.md). The starter is the `pluto-core-blog-template`
repository (`create-pluto -t core-blog`).
PKCE for GitHub App user tokens is sent but not proven against live GitHub yet. If GitHub
ignores the PKCE fields, `state` still guards the flow.
The GitHub App can be created from the site (see "Setup from the site").
Media: the GitHub driver of the core media library stores each file and its record in the repo
(`public/media/`, `<dir>/media/<id>.md`). The post type has a `cover` field. See the media
skill.
Planned: settings stored in the repository, a password provider, and configurable collections.
## Users page
The CMS lists the people with write access to the content repo, read only. GitHub owns the access,
so the page links to `https://github.com/<repo>/settings/access` (**Manage access on GitHub**).
- Nav: the client plugin adds the `users` nav item (order 950, between Media and Settings, label
`pluto.github.users.title`, `i-lucide-users`). No capability: every user who can sign in has push
access, and can see the collaborators on GitHub too.
- Page: `/admin/users` (route name `admin-users`), a child of `/admin` that the module adds with
`extendPages`, from `app/components/Pluto/Github/PlutoGithubUsersPage.vue`. Columns: the user
(avatar, login, a "You" badge), the GitHub role (Admin, Maintain, Write), and what it gives in
Pluto (Administrator for admin and maintain, Editor for write). A user that `ALLOWED_USERS` blocks
gets a "Cannot sign in" badge, and an info alert says that the list is set.
- Route: `GET /api/_pluto/github/users` (`utils/github-users.ts`). It needs a signed-in user (401),
and answers `Cache-Control: no-store`. It reads
`GET /repos/{repo}/collaborators?affiliation=all&permission=push&per_page=100`, page by page (at
most 10 pages), with the token of the user. The call needs Metadata read, which every App has.
The answer is `PlutoGithubUsersResponse` (`runtime/shared/repo-users.ts`):
`{ repo, users, restricted, reason? }`. The list stays in memory for 30 seconds per repo. GitHub
errors map like the build status (`toHttpError` of `utils/build-status.ts`).
- Local mode (`fs` store, or the dev local user): the dev user has no GitHub token, so the route
reads with the read token or an App installation token (`createAppTokenProvider`). `reason`:
`no-repo` (no repo known), `no-app` (no App and no read token; no call), `app-error` (the App gave
no token: not installed on the repo, or a wrong key). The page shows an alert for each, with a
link to the GitHub tab of Settings for the App.
- Pure helpers: `repoRoleOf` (the highest of admin, maintain, push; `null` below push) and
`toRepoUsers` (drops the users who cannot push, sorts admin, maintain, write, then by login, and
sets `canSignIn` from `allowedUsers`).
- Text: `pluto.github.users.*`. Test: `test/github-users.test.ts`.
## Backend badge
The CMS client plugin registers the `backend` entry of the navbar badge (see the admin-shell
skill): `kind: 'git'`, label "Local" (`fs` store, icon `i-lucide-git-branch`) or "GitHub"
(icon `i-lucide-github`), and the popover
`PlutoGithubBackendDetails` (`app/components/Pluto/Github/`).
- GitHub mode: the repo (with a Private or Public badge from the session), the branch, and links to
the repo and its commits on github.com.
- Local mode: the branch, the repo (when `github.repo` is known), the commits that are not pushed
and a **Push** button. A push that fails shows the reason (`pluto.github.local.errors.*`).
### Local Git routes
The module adds them in a dev build with the `fs` store only. Each handler also checks
`config.dev`, the `fs` store and `isLocalRequest` (the rule of the dev local user), else 404. They
answer `Cache-Control: no-store`. The POST route is under `/api/_pluto/`, so core's origin check
(CSRF) applies.
- `GET /api/_pluto/github/local/status`: `readLocalGitStatus(root)` (`store/local-git.ts`). It runs no
network call. The answer is `{ repo: false, reason: 'not-a-repo' | 'no-git' }` or
`{ repo: true, branch, upstream, remote, ahead }`. `ahead` counts `@{u}..HEAD` with an upstream, and
the commits on no remote branch (`HEAD --not --remotes`) without one. `remote` is the remote of the
upstream, else `origin`, else the first remote.
- `POST /api/_pluto/github/local/push`: `pushLocalGit(root)`. `git push`, or
`git push --set-upstream -- <remote> <branch>` for a branch with no upstream. It runs with
`GIT_TERMINAL_PROMPT=0` (Git never waits for a password in the terminal; a credential helper of
the system can still open a window) and a 120 s timeout. It answers the new status. A failure is
a `LocalPushFailure` with a reason, sent as a Pluto error with the key
`pluto.github.local.errors.<reason>`: `notARepo`, `detached`, `noRemote` (409), `rejected` (409;
pull first), `auth` (502), `timeout` (504), `failed` (502). `pushErrorReason(stderr)` sorts the
text of Git.
`usePlutoGithubLocalGit()` (`runtime/app/composables/pluto-github-local-git.ts`) holds the shared
state (`status`, `pushing`, `ahead`, `refresh()`, `push()`). In local mode the plugin reads it on
each admin navigation, when the tab shows again, every 15 seconds while an admin page shows, and
when the popover opens. A save commits on the server, so the count follows within that time.
Tests: `test/github-local-git.test.ts` (status, push to a bare remote, a rejected push, a detached
HEAD, `pushErrorReason`) and `test/github-local-git-routes.test.ts` (local only, 404 otherwise, the
origin check, the error key).
## Deploy tab
The **Deploy** tab of Settings puts the site on a host. The `settingsPages` entry (id `deploy`,
order 160, `i-lucide-rocket`) is in the CMS client plugin. The module adds the route
`/admin/settings/deploy` (`admin-settings-deploy`) with `extendPages`, from
`app/components/Pluto/Github/PlutoGithubDeployPage.vue`.
- **The site and the admin** (the whole app on a host): Vercel
(`https://vercel.com/new/import?s=<repo URL>`, else `vercel.com/new`), Netlify
(`app.netlify.com/start`; Netlify has no import link for one repo) and a Node host (the docs).
After the first deploy, the setup of the login page creates the GitHub App.
- **A static site** (the admin stays local, see "Static build"): GitHub Pages and Cloudflare Pages
(the build command `npx nuxt generate` and the output `.output/public`, with Copy buttons).
- GitHub Pages: four steps with a check icon each. (1) The workflow file: in local mode **Add the
workflow**, after a dialog; outside local mode the workflow to copy. (2) Set Source to GitHub Actions
in the Pages settings of the repo (a link). (3) Push (in local mode a Push button with the count of
the Git badge). (4) The last deploy, with **Check again** and a link to the build log.
The tab runs no CLI. Do not add one: the user may not have the GitHub CLI. Pluto writes files and
reads public facts. The author does each change on GitHub in the GitHub settings, from a link.
### The workflow
`runtime/shared/pages-workflow.ts` (pure): `renderPagesWorkflow({ branch, packageManager, dir })`,
`detectPackageManager(files)` (the lock file: `bun.lock`/`bun.lockb`, `pnpm-lock.yaml`, `yarn.lock`,
else npm), `defaultPagesUrl(repo)` and `PAGES_WORKFLOW_PATH` (`.github/workflows/pluto-pages.yml`).
The workflow runs on a push to the branch and by hand (`workflow_dispatch`, so the workflow page has
**Run workflow**): checkout, `configure-pages@v5`, the setup and install of the package manager,
`nuxt generate --preset github_pages` with `PLUTO_BASE_URL: ${{ steps.pages.outputs.base_path }}`,
`upload-pages-artifact@v3` (`.output/public`), then `deploy-pages@v4`. Permissions:
`contents: read`, `pages: write`, `id-token: write`. It needs no secret. It runs `generate`, not
`build`: Nuxt Icon sees a static build only through `nuxt generate`. Then it reads icons from the
Iconify API and bundles the custom collections. With `nuxt build` it asks the missing
`/api/_nuxt_icon` route, and the icons of a page opened in the browser stay blank.
**Scheduled posts on GitHub Pages.** A static site has no server task, so the workflow also runs
every hour (`schedule: cron '17 * * * *'`). The `publish` job (only on the schedule, `contents:
write`) checks out the branch and runs `PUBLISH_SCHEDULED_SCRIPT` with plain Node (no install): every
`.md` file under `PLUTO_CONTENT_DIR` (`plutoGithub.dir`; dot folders skipped) with `status: scheduled`
and a `publishedAt` that has come gets `status: published` (only that line changes), and it writes
`published=<n>`. Then it commits (`content: publish <n> scheduled`, as `github-actions[bot]`) and
pushes. The `build` job needs `publish` and runs on a push, by hand, or on the schedule only when
`published` is not 0; it checks out the branch, so it builds the new commit (a push with the token
of the workflow starts no other workflow). The keys are the ones of the built-in post type. A
branch with a protection rule that refuses the push of the bot stops the publish. The Deploy page
shows an older workflow as old (`workflow.current`), so a site gets the new file with **Add the
workflow** (local mode) or by copy.
### Routes
- `GET /api/_pluto/github/deploy/status` (signed-in user): `PlutoDeployStatus`
(`runtime/shared/deploy.ts`): `repo`, `branch`, `local`, `packageManager`, `workflow` (`path`,
`text`; in local mode also `exists` and `current`), `deploy`, `pagesUrl`, `host`, and outside
local mode `siteHost` (the request host).
- `deploy` (`readPagesDeploy`): the newest deployment of the `github-pages` environment
(`/repos/<repo>/deployments?environment=github-pages&per_page=1`) and its newest status.
`success` (also `inactive`), `failure` (`failure`, `error`), `pending` (any other state, or no
status), `none` (no deployment), `unknown` (no answer). `url` is `environment_url`: the live
address, a custom domain included. `logUrl` is `log_url` or `target_url`. It reads with a token
first, then with no token: a public repo needs none (the Pages API itself needs a token even for a
public repo, so Pluto does not read it). The token: the signed-in user's on a live admin; in local
mode the read token or the App token (`localReadToken`, shared with the Users page). It never
throws.
- `POST /api/_pluto/github/deploy/pages`: local mode on this computer only (a dev build, the `fs`
store, `isLocalRequest`), else 404. It writes the workflow when it is missing or old and commits
it (`ci: deploy the site to GitHub Pages`, with `commitLocalFiles`; a failed commit only logs).
It changes nothing on GitHub. The answer: `{ status, committed }`. The author pushes to deploy
(the Git badge counts the new commit).
- `DELETE /api/_pluto/github/deploy/pages`: local mode only, else 404. It deletes the workflow and
commits the removal (`ci: stop deploying the site to GitHub Pages`). It changes nothing on GitHub.
The answer: `{ status, committed }` (`committed: false` when there was no file). The card shows
**Remove GitHub Pages** in local mode when the file exists, after a dialog. Then an alert gives a
Push button and the Pages settings link: the last site stays online until the author selects
**Unpublish site** there.
- `GET /api/_pluto/github/deploy/dns?domain=<domain>` (signed-in user): `checkPagesDomain` with
`node:dns/promises` (`resolveCname`, `resolve4`, `resolve6`). `ok` when every address is a
GitHub Pages address (`GITHUB_PAGES_A`, `GITHUB_PAGES_AAAA`; a CNAME to `<owner>.github.io`
resolves to them too), `other` (`found` lists the CNAME targets and the addresses), `missing` (no
record). A bad domain gives 400 `pluto.github.deploy.domain.errors.invalid`.
**Add the workflow** opens a dialog first: Pluto writes and commits the file, it changes nothing on
GitHub, and nothing is online before a push.
### Domain
The **Domain** section of the tab is `PlutoGithubDeployDomain.vue`. Pure helpers are in
`runtime/shared/domain.ts`.
- A full-site host serves its own domain. The module reads the host at build time
(`detectDeployHost(process.env)`: `VERCEL` with `VERCEL_PROJECT_PRODUCTION_URL`, `NETLIFY=true` with
`SITE_NAME`) into the private config (`host`, `hostSite`). On a known host, the section shows
"This app runs on <host> at <domain>" and one link. Else it links to all three hosts.
`hostDomainSettingsUrl`: Vercel `vercel.com/d?to=/[team]/[project]/settings/domains` (Vercel asks
for the team and the project), Netlify `app.netlify.com/projects/<site>/domain-management`,
Cloudflare the Workers and Pages list.
- GitHub Pages: GitHub ignores a `CNAME` file when an Action builds the site, so Pluto writes none.
The domain is in the Pages settings of the repo. The section shows the current custom domain (the
host of `deploy.url` when it is not `*.github.io`), a domain field (`normalizeDomain`: lowercase;
it removes a scheme and a trailing `/`; it refuses an IP address, a path, a port or one label) and
four steps: type the domain in the Pages settings (a link); add the DNS records (a CNAME to
`<owner>.github.io` for a subdomain, the four A and four AAAA records for an apex domain;
`isApexDomain` guesses and a toggle switches) and **Check the DNS**; build again (a link to the
workflow page, because a new domain changes the base path); turn on Enforce HTTPS when the
certificate is ready.
Text: `pluto.github.deploy.*` (with `confirm.*` and `domain.*`), `pluto.settings.tabs.deploy`,
`pluto.common.copy` and `copied`, and `pluto.github.local.push` and `ahead`. Tests:
`test/github-deploy.test.ts` (the workflow as YAML for each package manager, the domain helpers, the
status in local mode and on a live admin, the last deploy with no token, with the read token of a
private repo and with the user token, the setup with no write to GitHub, 404 outside local mode, and
the DNS check with a fake `node:dns/promises`).
Not checked live yet: a real push that runs the workflow on GitHub.
## Static build
A site can be a set of static files, for example on GitHub Pages. The admin then stays on the
author's machine (local mode) or on a Node host, and each push of content rebuilds the site.
Two modules of core share the work. `modules/pluto-static` does what every static build needs,
with any backend. The Git module does what the Git CMS needs.
- A static build: not dev, and `nuxt.options._generate` (`nuxt generate`) or `nitro.static` is set,
or the Nitro preset (`nitro.preset`, else `NITRO_PRESET`) is static: `static`, `github_pages` (or
`github-pages`), or a name that ends with `_static` (`isStaticBuild`, `isStaticPreset` of
`modules/pluto-static/static-build.ts`). The Git module uses the same `isStaticBuild`.
### The pluto-static module (every backend)
- Base path: a project site of GitHub Pages lives under `/<repo>/`. The workflow gives the path in
`PLUTO_BASE_URL`, and the module writes it (`normalizeBasePath`) in `app.baseURL` and
`runtimeConfig.app.baseURL`. Do not use `NUXT_APP_BASE_URL` for this: the prerenderer then reads
the base at run time too, the paths do not match, and every page is a 16-byte "Redirecting..."
file. `@nuxt/image` adds the base to `PlutoImage` and prerenders the sizes (`/_ipx/...`).
`PlutoHtml` adds it to the site paths of a post body (`withBaseInHtml` of
`shared/utils/html-base.ts`). Nuxt does not add it to the links of `app.head`: the module does,
for a site path such as the favicon (`/favicon.svg`; `withBaseInHeadLinks`). A full URL or
`//host` stays.
- Site URL: a static build has no request at run time, so core cannot take the origin from the
request. `public.websiteUrl` (env `NUXT_PUBLIC_WEBSITE_URL`) is the address of the site, and
`usePlutoSite().root` and `getPlutoSiteRoot(event)` use it with the base path (the path of
`websiteUrl` may hold `/<repo>` or not). Without it, a static build has no root: `og:image` is left
out, and a layer that needs absolute URLs (a sitemap, a canonical) leaves them out too. The
GitHub Pages workflow sets `NUXT_PUBLIC_WEBSITE_URL` from `steps.pages.outputs.base_url` next to
`PLUTO_BASE_URL`. On Vercel and Netlify the build default comes from `VERCEL_PROJECT_PRODUCTION_URL`
and `URL`. See the content-model skill ("Site composables").
- `nitro.prerender.ignore` gets `/admin`, `/api/_pluto` and `/_pluto` (the preview pages).
- The public index: the one server route of a static build, `/api/pluto/v1/index.json`
(`modules/pluto-static/runtime/public-index.get.ts`, `buildPublicIndex` of
`server/utils/pluto-public-api.ts`). It is in `nitro.prerender.routes`, so the output has it as a
file: per public type, its `titleField` and all its published items, in the list shape and the
default sort. The module sets `public.plutoPublicApi.static`. Then, in the browser,
`usePlutoPublicList` (and `usePosts`, and every `useList`) gives `useFetch` its own `$fetch`: it
loads the index once and answers with `queryPublicIndex` (`shared/utils/public-index.ts`, the
rules of the Git adapter: the search in the title, the `filter[field]` equality, the sort with a
missing value last, `limit` and `offset`). A filter on an object (a relation that `toPublic`
expands, such as `category: { id, label }`) compares its `id`. So a search and the pages after
the first work with no server, also on a direct load of `?page=2` or `?q=`. The prerender keeps
the real API. One item and the surround need no index: each page is prerendered, and its payload
has them.
- A server build or dev gets nothing.
### The Git module
- The options take `ctx.static`: the `fs` store is the default and is valid, and no repo is needed.
The store reads the files of the checkout (`fsRoot` is the project dir), so the build needs no
token and no secret. `localCommit` is off.
- The module adds the Nitro plugin (the public API reads the files while the pages prerender), the
client plugin and the pages, but no server route: every `addRoute` call (sign-in, setup, users,
build status, local Git, `/media/**`) does nothing in a static build. The admin is client-only and
is never crawled.
- `public.plutoGithub.static` is true, and `usePlutoGithubSession` then asks for no session
(`immediate: false`): nobody signs in on a static site, and the request would get a 404.
- Drafts are not public, so they are never in the output.
### Checked
- A static build with `PLUTO_BASE_URL`, served under the sub path: the home page, a post, the
cover, an inline image and the links work, and no request fails. After a page change in the
browser, the icons of the new page load from the Iconify API (`nuxt generate` only; with
`nuxt build --preset github_pages` they ask `/api/_nuxt_icon` and stay blank).
- The public index: under `/templates/blog/`, the next page, a direct `?page=2`, a search, and a
direct `?q=` answer from the index, with no failed request.
- Tests: `test/static-module.test.ts`, `test/github-module.test.ts` ("a static build"),
`test/pluto-github-options.test.ts`, `test/html-base.test.ts`, `test/public-index.test.ts`.
## Rules found in live testing
- **Admin layout.** Core's `app/pages/admin.vue` parent route sets `layout: 'admin'` for every
`/admin/**` page. The module sets no layout. `/admin/login` sets the `auth` layout itself. The
login page path is `app/pages/admin/(auth)/login.vue`. The supabase layer ships the same path.
- **The dev local user and `nuxt dev`.** `nuxt dev` proxies each request to its Nitro worker. The
worker socket has no remote address, and the dev proxy appends the real client address as the
LAST `x-forwarded-for` entry. `isLocalRequest` accepts that case only when the last entry is a
loopback address and `Host` names this machine. A spoofed `x-forwarded-for` does not help a
remote client: the proxy still appends its real address last.
- **The `fs` store head.** The store root is the project dir, so the head reads only the content
dir (`headDir`). It never reads `node_modules`, build output or dot dirs. Reading the whole
project on each request made the dev server stall.