Skip to content

Commit dd9eb9d

Browse files
committed
Add Cloudflare Pages docs preview workflow with /preview-docs slash command
PRs from repo admins that touch docs auto-deploy a mkdocs preview to Cloudflare Pages; for everyone else, an admin or maintainer can comment `/preview-docs` to trigger one. A sticky PR comment carries the preview link, and a companion workflow deletes the deployments when the PR closes. Because mkdocs executes Python from the PR (mkdocstrings imports src/mcp), the build is gated by a permission check on the triggering actor and runs in a separate job with no secrets — the static site is handed to the Cloudflare deploy step via an artifact so PR code never shares a runner with the API token. The pull_request_target trigger is suppressed in zizmor with this rationale. :house: Remote-Dev: homespace
1 parent 8d0f928 commit dd9eb9d

3 files changed

Lines changed: 273 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
name: Docs Preview Cleanup
2+
3+
# Deletes Cloudflare Pages preview deployments for a PR when it closes.
4+
# Runs as pull_request_target so secrets are available for fork PRs; it never
5+
# checks out PR code, so there is no untrusted-code execution risk.
6+
7+
on:
8+
pull_request_target:
9+
types: [closed]
10+
11+
permissions: {}
12+
13+
jobs:
14+
cleanup:
15+
runs-on: ubuntu-latest
16+
steps:
17+
- name: Delete preview deployments for this PR
18+
env:
19+
CF_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
20+
CF_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
21+
CF_PROJECT: ${{ vars.CLOUDFLARE_PAGES_PROJECT }}
22+
BRANCH: pr-${{ github.event.pull_request.number }}
23+
run: |
24+
set -euo pipefail
25+
if [ -z "$CF_API_TOKEN" ] || [ -z "$CF_ACCOUNT_ID" ] || [ -z "$CF_PROJECT" ]; then
26+
echo "Cloudflare credentials/project not configured; skipping cleanup."
27+
exit 0
28+
fi
29+
base="https://api.cloudflare.com/client/v4/accounts/$CF_ACCOUNT_ID/pages/projects/$CF_PROJECT/deployments"
30+
# Collect matching ids across all pages first, then delete — deleting
31+
# mid-pagination would shift later pages and skip entries.
32+
ids=""
33+
for page in $(seq 1 50); do
34+
resp=$(curl -fsS -H "Authorization: Bearer $CF_API_TOKEN" "$base?env=preview&per_page=25&page=$page")
35+
ids="$ids $(jq -r --arg b "$BRANCH" '.result[]? | select(.deployment_trigger.metadata.branch == $b) | .id' <<<"$resp")"
36+
[ "$(jq '.result | length' <<<"$resp")" -lt 25 ] && break
37+
done
38+
deleted=0
39+
for id in $ids; do
40+
echo "Deleting deployment $id"
41+
curl -fsS -X DELETE -H "Authorization: Bearer $CF_API_TOKEN" "$base/$id?force=true" > /dev/null
42+
deleted=$((deleted + 1))
43+
done
44+
echo "Deleted $deleted deployment(s) for $BRANCH."

.github/workflows/docs-preview.yml

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
name: Docs Preview
2+
3+
# Builds the mkdocs site for a PR and deploys it to Cloudflare Pages.
4+
#
5+
# Security: mkdocs executes Python from the PR (mkdocstrings imports src/mcp,
6+
# `!!python/name:` directives). The build is gated by `authorize` (admin sender
7+
# for auto-preview, admin/maintainer commenter for /preview-docs) and isolated
8+
# from Cloudflare secrets — `build` runs PR code with no secrets and hands the
9+
# static site to `deploy` via an artifact, so PR code never shares a runner
10+
# with the Cloudflare token.
11+
#
12+
# Required configuration:
13+
# - secrets.CLOUDFLARE_API_TOKEN (scope: Account → Cloudflare Pages → Edit)
14+
# - secrets.CLOUDFLARE_ACCOUNT_ID
15+
# - vars.CLOUDFLARE_PAGES_PROJECT (existing Pages project, e.g. mcp-python-sdk-docs)
16+
17+
on:
18+
pull_request_target:
19+
types: [opened, reopened, synchronize]
20+
paths:
21+
- docs/**
22+
- docs_src/**
23+
- mkdocs.yml
24+
- pyproject.toml
25+
issue_comment:
26+
types: [created]
27+
28+
permissions: {}
29+
30+
concurrency:
31+
group: docs-preview-pr-${{ github.event.pull_request.number || github.event.issue.number }}
32+
cancel-in-progress: true
33+
34+
jobs:
35+
authorize:
36+
if: >-
37+
github.event_name == 'pull_request_target' ||
38+
(github.event.issue.pull_request && startsWith(github.event.comment.body, '/preview-docs'))
39+
runs-on: ubuntu-latest
40+
permissions:
41+
contents: read
42+
pull-requests: read
43+
outputs:
44+
authorized: ${{ steps.check.outputs.authorized }}
45+
pr_number: ${{ steps.check.outputs.pr_number }}
46+
head_sha: ${{ steps.check.outputs.head_sha }}
47+
slash_attempt: ${{ steps.check.outputs.slash_attempt }}
48+
steps:
49+
- name: Determine authorization
50+
id: check
51+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
52+
with:
53+
script: |
54+
const { owner, repo } = context.repo;
55+
56+
async function permissionFor(username) {
57+
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username });
58+
return { level: data.permission, role: data.role_name };
59+
}
60+
61+
let authorized = false;
62+
let prNumber = '';
63+
let headSha = '';
64+
let slashAttempt = false;
65+
66+
if (context.eventName === 'pull_request_target') {
67+
// Gate on the *sender* (whoever caused this run — on synchronize that
68+
// is the pusher), not the PR author, so a non-admin pushing to an
69+
// admin-opened branch does not get an automatic build.
70+
const actor = context.payload.sender.login;
71+
prNumber = String(context.payload.pull_request.number);
72+
headSha = context.payload.pull_request.head.sha;
73+
const perm = await permissionFor(actor);
74+
authorized = perm.level === 'admin';
75+
core.info(`pull_request_target by ${actor} (level=${perm.level}, role=${perm.role}) → authorized=${authorized}`);
76+
} else {
77+
// issue_comment: the job-level `if:` already guarantees this is a PR
78+
// comment starting with /preview-docs.
79+
slashAttempt = true;
80+
const actor = context.payload.comment.user.login;
81+
prNumber = String(context.payload.issue.number);
82+
const perm = await permissionFor(actor);
83+
authorized = perm.level === 'admin' || perm.role === 'maintain';
84+
if (authorized) {
85+
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: Number(prNumber) });
86+
if (pr.state !== 'open') {
87+
authorized = false;
88+
core.info(`PR #${prNumber} is ${pr.state}; refusing to preview.`);
89+
} else {
90+
headSha = pr.head.sha;
91+
}
92+
}
93+
core.info(`/preview-docs by ${actor} (level=${perm.level}, role=${perm.role}) → authorized=${authorized}`);
94+
}
95+
96+
core.setOutput('authorized', String(authorized));
97+
core.setOutput('pr_number', prNumber);
98+
core.setOutput('head_sha', headSha);
99+
core.setOutput('slash_attempt', String(slashAttempt));
100+
101+
build:
102+
needs: authorize
103+
if: needs.authorize.outputs.authorized == 'true'
104+
runs-on: ubuntu-latest
105+
permissions:
106+
contents: read
107+
steps:
108+
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
109+
with:
110+
ref: ${{ needs.authorize.outputs.head_sha }}
111+
persist-credentials: false
112+
113+
- name: Install uv
114+
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
115+
with:
116+
enable-cache: true
117+
version: 0.9.5
118+
119+
- run: uv sync --frozen --group docs
120+
- run: uv run --frozen --no-sync mkdocs build
121+
122+
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
123+
with:
124+
name: site
125+
path: site/
126+
retention-days: 1
127+
128+
deploy:
129+
needs: [authorize, build]
130+
if: needs.authorize.outputs.authorized == 'true'
131+
runs-on: ubuntu-latest
132+
permissions: {}
133+
outputs:
134+
deployment_url: ${{ steps.wrangler.outputs.deployment-url }}
135+
alias_url: ${{ steps.wrangler.outputs.pages-deployment-alias-url }}
136+
steps:
137+
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
138+
with:
139+
name: site
140+
path: site
141+
142+
- name: Deploy to Cloudflare Pages
143+
id: wrangler
144+
uses: cloudflare/wrangler-action@ebbaa1584979971c8614a24965b4405ff95890e0 # v4.0.0
145+
with:
146+
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
147+
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
148+
packageManager: npm
149+
command: >-
150+
pages deploy ./site
151+
--project-name=${{ vars.CLOUDFLARE_PAGES_PROJECT }}
152+
--branch=pr-${{ needs.authorize.outputs.pr_number }}
153+
--commit-hash=${{ needs.authorize.outputs.head_sha }}
154+
--commit-dirty=true
155+
156+
comment:
157+
needs: [authorize, build, deploy]
158+
if: >-
159+
always() &&
160+
needs.deploy.result != 'cancelled' &&
161+
(needs.authorize.outputs.authorized == 'true' || needs.authorize.outputs.slash_attempt == 'true')
162+
runs-on: ubuntu-latest
163+
permissions:
164+
pull-requests: write
165+
steps:
166+
- name: Post or update preview comment
167+
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
168+
env:
169+
AUTHORIZED: ${{ needs.authorize.outputs.authorized }}
170+
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
171+
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
172+
DEPLOY_RESULT: ${{ needs.deploy.result }}
173+
DEPLOYMENT_URL: ${{ needs.deploy.outputs.deployment_url }}
174+
ALIAS_URL: ${{ needs.deploy.outputs.alias_url }}
175+
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
176+
with:
177+
script: |
178+
const { owner, repo } = context.repo;
179+
const env = process.env;
180+
const issue_number = Number(env.PR_NUMBER);
181+
const marker = '<!-- docs-preview -->';
182+
183+
async function upsert(body) {
184+
const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number, per_page: 100 });
185+
const existing = comments.find(c => c.user?.type === 'Bot' && c.body?.includes(marker));
186+
if (existing) {
187+
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
188+
} else {
189+
await github.rest.issues.createComment({ owner, repo, issue_number, body });
190+
}
191+
}
192+
193+
if (env.AUTHORIZED !== 'true') {
194+
await github.rest.issues.createComment({
195+
owner, repo, issue_number,
196+
body: `@${context.actor} — only repository admins or maintainers can run \`/preview-docs\` (and the PR must be open).`,
197+
});
198+
return;
199+
}
200+
201+
if (env.DEPLOY_RESULT !== 'success') {
202+
await upsert(
203+
`${marker}\n### 📚 Documentation preview\n\n` +
204+
`❌ Preview build **failed** for \`${env.HEAD_SHA.slice(0, 7)}\` — [workflow logs](${env.RUN_URL}).`
205+
);
206+
return;
207+
}
208+
209+
const previewUrl = env.ALIAS_URL || env.DEPLOYMENT_URL;
210+
const ts = new Date().toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' UTC');
211+
await upsert(
212+
`${marker}\n### 📚 Documentation preview\n\n` +
213+
`| | |\n|---|---|\n` +
214+
`| **Preview** | ${previewUrl} |\n` +
215+
`| **Deployment** | ${env.DEPLOYMENT_URL} |\n` +
216+
`| **Commit** | \`${env.HEAD_SHA.slice(0, 7)}\` |\n` +
217+
`| **Triggered by** | @${context.actor} |\n` +
218+
`| **Updated** | ${ts} |\n`
219+
);

.github/zizmor.yml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
rules:
2+
dangerous-triggers:
3+
ignore:
4+
# Both preview workflows use pull_request_target so secrets are available
5+
# for fork PRs. docs-preview.yml gates PR-code execution behind an
6+
# admin/maintainer permission check and isolates the build (which runs
7+
# PR Python via mkdocstrings) from Cloudflare secrets via an artifact
8+
# handoff. docs-preview-cleanup.yml never checks out PR code at all.
9+
- docs-preview.yml
10+
- docs-preview-cleanup.yml

0 commit comments

Comments
 (0)