Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Add update checks and an update workflow for deployers
Claude8af777a87089
diff --git a/.github/workflows/update-signudoc.yml b/.github/workflows/update-signudoc.ymlnew file mode 100644index 0000000..6dc07c1--- /dev/null+++ b/.github/workflows/update-signudoc.yml@@ -0,0 +1,298 @@+# Keeps a copy of SignuDoc up to date with the project's releases.+#+# The Vercel Deploy button copies SignuDoc into a repository of your own,+# and Vercel deploys every push to it. This workflow, run in that copy,+# brings in the latest SignuDoc release and opens a pull request with it.+# Vercel builds a preview of the pull request; merging it deploys the new+# version, and the production build applies any database changes.+#+# It runs every Monday and whenever you press "Run workflow" on the+# Actions tab. Your own changes to the code are kept: the release is merged+# with them, and when both changed the same lines the run stops and lists+# the files instead of opening a pull request.+#+# It needs no setup, with two optional extras (docs/self-hosting.md, "Keep+# your install up to date"):+# - So it can open the pull request itself: Settings, Actions, General,+# "Allow GitHub Actions to create and approve pull requests". Without+# it the run pushes the branch and links to the page that opens one.+# - A SIGNUDOC_UPDATE_TOKEN secret (a fine-grained token for this one+# repository with Contents, Pull requests and Workflows read and+# write). GitHub does not let a workflow's own token change files in+# .github/workflows, so without it those files stay as they are and+# the pull request says which ones differ from the release.+#+# Set the repository variable SIGNUDOC_AUTO_MERGE to 1 to have the weekly+# run merge an update that applies cleanly straight into your production+# branch instead of opening a pull request.+#+# In the SignuDoc repository itself the job is skipped.++name: Update SignuDoc++on:+ schedule:+ - cron: "17 7 * * 1"+ workflow_dispatch:+ inputs:+ version:+ description: "Release to update to, such as v0.2.0. Leave empty for the latest."+ required: false+ default: ""+ merge:+ description: "Merge straight into the production branch instead of opening a pull request (only when nothing clashes)."+ type: boolean+ default: false++permissions:+ contents: write+ pull-requests: write++concurrency:+ group: update-signudoc+ cancel-in-progress: false++jobs:+ update:+ name: Bring in the latest release+ # Expressions compare strings without regard to case.+ if: github.repository != 'NYLLON-SOFTWARE/SignuDoc'+ runs-on: ubuntu-latest+ timeout-minutes: 15+ env:+ UPSTREAM: NYLLON-SOFTWARE/SignuDoc+ UPSTREAM_GIT_URL: https://github.com/NYLLON-SOFTWARE/SignuDoc.git+ GH_TOKEN: ${{ secrets.SIGNUDOC_UPDATE_TOKEN || github.token }}+ HAS_UPDATE_TOKEN: ${{ secrets.SIGNUDOC_UPDATE_TOKEN != '' }}+ REQUESTED_VERSION: ${{ inputs.version }}+ MERGE_NOW: ${{ inputs.merge == true || vars.SIGNUDOC_AUTO_MERGE == '1' }}+ BASE_BRANCH: ${{ github.event.repository.default_branch }}+ steps:+ - uses: actions/checkout@v6+ with:+ fetch-depth: 0+ ref: ${{ github.event.repository.default_branch }}+ token: ${{ secrets.SIGNUDOC_UPDATE_TOKEN || github.token }}++ - name: Merge the release into a branch+ id: merge+ shell: bash+ run: |+ set -euo pipefail++ summary() { printf '%s\n' "$@" >> "$GITHUB_STEP_SUMMARY"; }+ stop() { echo "::error::$1"; summary "**$1**"; exit 1; }++ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"++ # Which release.+ if [ -n "${REQUESTED_VERSION:-}" ]; then+ tag="$REQUESTED_VERSION"+ case "$tag" in v*) ;; *) tag="v$tag" ;; esac+ if ! [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then+ stop "\"$REQUESTED_VERSION\" is not a release version such as v0.2.0."+ fi+ release_json=$(gh api "repos/$UPSTREAM/releases/tags/$tag") ||+ stop "SignuDoc has no release $tag."+ else+ release_json=$(gh api "repos/$UPSTREAM/releases/latest") ||+ stop "The latest SignuDoc release could not be read from GitHub."+ fi+ tag=$(jq -r '.tag_name' <<< "$release_json")+ if ! [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then+ stop "The release tag \"$tag\" is not a version number."+ fi+ release_url=$(jq -r '.html_url' <<< "$release_json")+ jq -r '.body // ""' <<< "$release_json" > "$RUNNER_TEMP/notes-full.md"+ head -c 40000 "$RUNNER_TEMP/notes-full.md" > "$RUNNER_TEMP/notes.md"++ # The project's history, kept apart from this repository's own+ # branches and tags.+ git fetch --quiet --no-tags "$UPSTREAM_GIT_URL" \+ "+refs/heads/main:refs/signudoc/main" \+ "+refs/tags/*:refs/signudoc/tags/*"+ target=$(git rev-parse --verify "refs/signudoc/tags/$tag^{commit}") ||+ stop "Release $tag has no matching tag in $UPSTREAM."++ # Which SignuDoc commit this copy last took. The newest of:+ # - the commit named by an earlier run of this workflow,+ # - a commit both histories share (a fork, or a manual merge),+ # - the commit the Deploy button copied, found by its files.+ candidates=()+ while read -r sha; do+ if git cat-file -e "$sha^{commit}" 2> /dev/null; then candidates+=("$sha"); fi+ done < <(git log --max-count=200 --format=%B HEAD |+ sed -n 's/^SignuDoc-Commit: \([0-9a-f]\{40\}\)[[:space:]]*$/\1/p')+ if shared=$(git merge-base HEAD "$target" 2> /dev/null); then+ candidates+=("$shared")+ fi+ if [ "${#candidates[@]}" -eq 0 ]; then+ mapfile -t roots < <(git rev-list --max-parents=0 HEAD)+ [ "${#roots[@]}" -eq 1 ] ||+ stop "This repository's history has ${#roots[@]} starting points, so the SignuDoc version it came from cannot be found. Update by hand (docs/self-hosting.md)."+ root_tree=$(git rev-parse "${roots[0]}^{tree}")+ copied=$(git log --format='%H %T' refs/signudoc/main "$target" |+ awk -v tree="$root_tree" '$2 == tree { print $1; exit }' || true)+ if [ -z "$copied" ]; then+ # The first commit was changed before it was pushed. Take the+ # SignuDoc commit with the fewest differing files.+ fewest=""+ while read -r sha; do+ count=$(git diff --no-renames --name-only "${roots[0]}" "$sha" | wc -l)+ if [ -z "$fewest" ] || [ "$count" -lt "$fewest" ]; then+ copied="$sha"+ fewest="$count"+ fi+ [ "$count" -eq 0 ] && break+ done < <(git rev-list --max-count=500 refs/signudoc/main "$target")+ summary "Your first commit matches no SignuDoc commit exactly. Using the closest one, ${copied:0:7}, which differs in $fewest files."+ fi+ candidates+=("$copied")+ fi+ base="${candidates[0]}"+ for sha in "${candidates[@]}"; do+ if git merge-base --is-ancestor "$base" "$sha"; then base="$sha"; fi+ done++ if git merge-base --is-ancestor "$target" "$base"; then+ summary "Already up to date with SignuDoc $tag."+ echo "Already up to date with SignuDoc $tag."+ exit 0+ fi++ branch="signudoc-update/$tag"+ if git ls-remote --exit-code --heads origin "$branch" > /dev/null; then+ open_pr=$(gh pr list --head "$branch" --state open --json url --jq '.[0].url // ""')+ if [ -n "$open_pr" ]; then+ summary "SignuDoc $tag is waiting in $open_pr."+ else+ summary "The branch $branch already exists. Open a pull request from it ($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/compare/$BASE_BRANCH...$branch?expand=1), or delete it and run this again."+ fi+ exit 0+ fi++ # Three-way merge: what SignuDoc changed since $base, applied on+ # top of this repository, keeping this repository's own changes.+ set +e+ merge_output=$(git merge-tree --write-tree --name-only --no-messages \+ --merge-base="$base" HEAD "$target")+ merge_status=$?+ set -e+ if [ "$merge_status" -eq 1 ]; then+ summary "## SignuDoc $tag clashes with changes in this repository" "" \+ "These files were changed both here and in SignuDoc, in the same places:" ""+ tail -n +2 <<< "$merge_output" | sed '/^$/d; s/^/- `/; s/$/`/' >> "$GITHUB_STEP_SUMMARY"+ summary "" "To update by hand, see \"Keep your install up to date\" in docs/self-hosting.md. Use \`${base}\` as the SignuDoc commit this repository is based on."+ stop "SignuDoc $tag clashes with this repository's own changes. See the run summary."+ elif [ "$merge_status" -ne 0 ]; then+ stop "git could not merge SignuDoc $tag."+ fi+ merged_tree=$(head -n 1 <<< "$merge_output")++ git checkout --quiet -b "$branch"+ git read-tree -u --reset "$merged_tree"++ # GitHub refuses a push that changes workflow files unless the+ # token may change workflows, which a workflow's own token may not.+ if [ "$HAS_UPDATE_TOKEN" != "true" ]; then+ while IFS=$'\t' read -r change path; do+ [ -n "$path" ] || continue+ if [ "$change" = "A" ]; then+ git rm --quiet --force -- "$path"+ else+ git checkout HEAD -- "$path"+ fi+ done < <(git diff --cached --no-renames --name-status HEAD -- .github/workflows)+ fi++ if git diff --cached --quiet HEAD; then+ summary "Nothing to change: this repository already has everything in SignuDoc $tag."+ exit 0+ fi++ kept_workflows=""+ if [ "$HAS_UPDATE_TOKEN" != "true" ]; then+ kept_workflows=$(git diff --no-renames --name-only "$target" -- .github/workflows)+ fi+ new_migrations=$(git diff --cached --no-renames --name-only --diff-filter=A HEAD -- db/migrations)++ git commit --quiet --file - << MESSAGE+ Update SignuDoc to $tag++ Brings in SignuDoc $tag ($release_url).++ SignuDoc-Version: $tag+ SignuDoc-Commit: $target+ MESSAGE++ {+ echo "SignuDoc **$tag** is ready to deploy. [Release notes]($release_url)."+ echo+ echo "Merging this pull request deploys it. Vercel has built a preview from this branch; check it below before merging."+ if [ -n "$new_migrations" ]; then+ echo+ echo "### Database changes"+ echo+ echo "This version changes the database. The production build applies the change when you merge:"+ echo+ sed 's/^/- `/; s/$/`/' <<< "$new_migrations"+ echo+ echo "Preview builds leave the database alone, so pages that need the change may fail in the preview. Once applied, a database change stays if you roll the site back."+ fi+ if [ -n "$kept_workflows" ]; then+ echo+ echo "### Workflow files not updated"+ echo+ echo "GitHub does not let this workflow change files in \`.github/workflows\`, so these still differ from SignuDoc $tag. Copy them from the release by hand, or add a \`SIGNUDOC_UPDATE_TOKEN\` secret (docs/self-hosting.md) and run the update again:"+ echo+ sed 's/^/- `/; s/$/`/' <<< "$kept_workflows"+ fi+ echo+ echo "### What's new in $tag"+ echo+ cat "$RUNNER_TEMP/notes.md"+ echo+ echo "---"+ echo+ echo "Opened by the Update SignuDoc workflow."+ echo+ echo "SignuDoc-Version: $tag"+ echo "SignuDoc-Commit: $target"+ } > "$RUNNER_TEMP/pr-body.md"++ {+ echo "branch=$branch"+ echo "tag=$tag"+ } >> "$GITHUB_OUTPUT"++ - name: Deploy or open a pull request+ if: steps.merge.outputs.branch != ''+ shell: bash+ env:+ BRANCH: ${{ steps.merge.outputs.branch }}+ TAG: ${{ steps.merge.outputs.tag }}+ run: |+ set -euo pipefail++ summary() { printf '%s\n' "$@" >> "$GITHUB_STEP_SUMMARY"; }++ if [ "$MERGE_NOW" = "true" ]; then+ # The branch was made from the production branch's tip, so this+ # is a fast-forward unless someone pushed in the meantime.+ git push origin "HEAD:refs/heads/$BASE_BRANCH"+ summary "SignuDoc $TAG was merged into \`$BASE_BRANCH\`. Vercel is deploying it."+ exit 0+ fi++ git push --quiet origin "HEAD:refs/heads/$BRANCH"+ if url=$(gh pr create --base "$BASE_BRANCH" --head "$BRANCH" \+ --title "Update SignuDoc to $TAG" --body-file "$RUNNER_TEMP/pr-body.md"); then+ summary "Opened $url. Merge it to deploy SignuDoc $TAG."+ else+ compare="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/compare/$BASE_BRANCH...$BRANCH?expand=1"+ summary "The branch \`$BRANCH\` has SignuDoc $TAG, but this workflow may not open pull requests here." "" \+ "Open one yourself: $compare" "" \+ "To let the workflow do it next time: Settings, Actions, General, \"Allow GitHub Actions to create and approve pull requests\"."+ echo "::warning::Open the pull request yourself: $compare"+ fidiff --git a/README.md b/README.mdindex d57385e..ea5172a 100644--- a/README.md+++ b/README.md@@ -200,6 +200,8 @@ DocuSign's figures are its US list prices for annual plans in November 2026: $304. **Open your new site.** Name your organization, give the email address people should write to for help, and create the first account, which is the administrator.5. **Set up the address you send from.** Under Settings, Organization, enter an address at your own domain. The site lists the DNS records to add and checks them for you.+**Taking new versions.** Settings, SignuDoc, **Check for updates** tells you when a new release is out and what is in it. A workflow that comes with your copy then opens a pull request with the release in your GitHub repository; merge it and Vercel deploys the update. See [Keep your install up to date](docs/self-hosting.md#keep-your-install-up-to-date).+There is nothing to type in Vercel and no terminal to open. Until step 5 is done, email reaches only the address on your Resend account, so you can try the whole product straight away by sending a document to yourself. The [self-hosting guide](docs/self-hosting.md) covers your own domain, locking down a new install, keeping it up to date, running in the EU, and every optional setting.### Try it on your computerdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 6c250c9..53fba6c 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -64,25 +64,49 @@ After this, preview deployments have no database and open on the page that asks### Keep your install up to date-The Deploy button makes a copy of this repository, and a copy does not receive new versions by itself. To take a new version, bring the changes into your copy and push. Vercel builds the push, and the build applies any new database migrations.+The Deploy button makes a copy of this repository in your GitHub account, and Vercel deploys every push to it. A copy does not receive new versions by itself: an update means bringing a new [release](https://github.com/NYLLON-SOFTWARE/SignuDoc/releases) into your copy. Vercel then builds it, and the production build applies any new database migrations.++**See whether there is one.** Sign in as the administrator and open Settings. The SignuDoc section shows the version the site runs; **Check for updates** asks GitHub for the latest release and shows what is new in it.++**Take it with the update workflow.** Your copy has a GitHub Actions workflow, `.github/workflows/update-signudoc.yml`, that does the git work for you:++1. In your repository on GitHub, open **Actions**, then **Update SignuDoc**, and press **Run workflow**. (Settings in SignuDoc links straight there.) It also runs by itself every Monday.+2. It merges the release with your copy on a branch named `signudoc-update/<version>` and opens a pull request. Vercel builds a preview of that branch.+3. Look at the preview, then merge the pull request. Vercel deploys it to your site.++Using it costs nothing: a run takes well under a minute, and private repositories get 2,000 free Actions minutes a month.++What the workflow does and does not do:++- **Your changes are kept.** It does a three-way merge between the SignuDoc version your copy is based on, your copy, and the new release, so code you changed stays changed. Where you and SignuDoc changed the same lines, it stops without touching anything and lists the files in the run's summary. Then update by hand, below.+- **It never force-pushes** and never changes your production branch unless you ask it to (below). Everything arrives as a pull request.+- **Database changes wait for the merge.** Preview builds do not touch the database (they share it with production unless you set `MIGRATE_ON_PREVIEW=1`), so a preview of an update that changes the database may show errors on pages that need the change. The pull request says when an update changes the database. Merging applies it during the production build. A database change stays if you later roll the site back to an older deployment, so do not roll back across an update that changed the database.+- **Files in `.github/workflows` are left alone.** GitHub does not let a workflow's own token change workflow files. When a release changes one, the pull request lists it, and you can copy it from the release by hand. To have the workflow update them too, add the token below.++Two optional settings in your repository on GitHub:++- **Let the workflow open the pull request.** In Settings, Actions, General, under Workflow permissions, tick **Allow GitHub Actions to create and approve pull requests**. Without it the workflow pushes the branch and its summary links to the page where you open the pull request with one click.+- **`SIGNUDOC_UPDATE_TOKEN`**, a repository secret (Settings, Secrets and variables, Actions). Make a [fine-grained personal access token](https://github.com/settings/personal-access-tokens/new) for your copy only, with read and write access to Contents, Pull requests and Workflows. The workflow uses it instead of its own token, so it can update workflow files and does not need the setting above.++To skip the pull request, run the workflow with **Merge straight into the production branch** ticked, or set the repository variable `SIGNUDOC_AUTO_MERGE` to `1` to have the weekly run do that. It only does so when the release merges cleanly. Vercel then deploys the update without anyone looking at it first.++**A copy made before version 0.2.0** does not have the workflow yet. Add it once: in your repository on GitHub choose **Add file**, **Create new file**, name it `.github/workflows/update-signudoc.yml`, paste in [the workflow](https://raw.githubusercontent.com/NYLLON-SOFTWARE/SignuDoc/main/.github/workflows/update-signudoc.yml), and commit it to your production branch. Settings in SignuDoc links to the right page. Then run it as above.++**Updating by hand.** A copy made by the Deploy button has none of this project's history, so a plain `git merge` refuses to merge "unrelated histories". Tell git which SignuDoc commit your copy started from, then merge as usual:```bashgit clone https://github.com/<your-account>/signudoc.gitcd signudoc-git remote add upstream https://github.com/NYLLON-SOFTWARE/SignuDoc.git-git fetch upstream-git merge upstream/main+git fetch https://github.com/NYLLON-SOFTWARE/SignuDoc.git main --tags+# The SignuDoc commit your copy started from. The workflow's summary+# names it when it stops, or use the release tag you deployed, e.g. v0.1.0.+git replace --graft "$(git rev-list --max-parents=0 HEAD)" v0.1.0+git merge v0.2.0+# Fix any clashes, commit, then:git push```-If git answers `refusing to merge unrelated histories`, your copy was made without this project's history. As long as you have not changed the code yourself, take the new version as it is:--```bash-git reset --hard upstream/main-git push --force-with-lease-```--After that first time, `git merge upstream/main` works as above.+The graft only lives in your local clone. The merge itself is a normal commit that links the two histories, so later updates merge without it.### Optional settingsdiff --git a/next.config.ts b/next.config.tsindex 3a709c7..5ba5f17 100644--- a/next.config.ts+++ b/next.config.ts@@ -1,7 +1,16 @@+import { readFileSync } from "node:fs";+import type { NextConfig } from "next";+// The version this deployment runs, compared with the latest release by+// "Check for updates" in Settings (src/lib/software-update.ts).+const { version } = JSON.parse(readFileSync("./package.json", "utf8")) as {+ version: string;+};+const nextConfig: NextConfig = {env: {+ NEXT_PUBLIC_SIGNUDOC_VERSION: version,// Whether Vercel BotID is on, decided once at build time so the browser// code that adds its proof and the server code that checks it cannot// disagree. It only works on Vercel, and is opt-in with BOTID=1. Seediff --git a/src/app/(app)/settings/page.tsx b/src/app/(app)/settings/page.tsxindex 53e7cca..193d84e 100644--- a/src/app/(app)/settings/page.tsx+++ b/src/app/(app)/settings/page.tsx@@ -1,9 +1,11 @@import { OrganizationSettings } from "@/components/settings/organization-settings";import { SettingsShell } from "@/components/settings/settings-shell";+import { UpdatesPanel } from "@/components/settings/updates-panel";import { isAdminUser } from "@/lib/auth/admin";import { getAuthSession } from "@/lib/auth/server";import { toOrganizationSettingsView } from "@/lib/organization-settings";import { readStoredSettings, resolveSettings } from "@/lib/settings";+import { getUpdateStatus } from "@/lib/software-update";export default async function SettingsPage() {const session = await getAuthSession();@@ -26,6 +28,7 @@ export default async function SettingsPage() {)}/>) : null}+ {isAdmin ? <UpdatesPanel initialStatus={getUpdateStatus(null)} /> : null}</div>);}diff --git a/src/app/api/admin/updates/route.ts b/src/app/api/admin/updates/route.tsnew file mode 100644index 0000000..f767598--- /dev/null+++ b/src/app/api/admin/updates/route.ts@@ -0,0 +1,54 @@+import { NextResponse } from "next/server";++import { requireAdminSession } from "@/lib/auth/admin";+import { logRouteError } from "@/lib/security/logging";+import {+ applyRateLimit,+ buildRateLimitKey,+} from "@/lib/security/route-controls";+import { getClientIpAddress, getRequestPathname } from "@/lib/security/request";+import { checkForUpdate, getUpdateStatus } from "@/lib/software-update";++// "Check for updates" in the SignuDoc section of Settings: whether a newer+// release than the running version has been published. The page itself+// shows the running version without asking GitHub.++/** Asks GitHub for the latest release (answer cached on the server). */+export async function POST(request: Request) {+ const sessionResult = await requireAdminSession(request);++ if (sessionResult instanceof Response) {+ return sessionResult;+ }++ const userId = sessionResult.user.id;+ const rateLimitResponse = await applyRateLimit({+ category: "update_check",+ key: buildRateLimitKey(["update-check", userId]),+ limit: 30,+ request,+ userId,+ windowMs: 10 * 60 * 1000,+ });++ if (rateLimitResponse) {+ return rateLimitResponse;+ }++ try {+ return NextResponse.json(getUpdateStatus(await checkForUpdate()));+ } catch (error) {+ logRouteError(error, {+ category: "update_check_failure",+ ipAddress: getClientIpAddress(request.headers),+ message: "Unexpected failure while checking for updates.",+ path: getRequestPathname(request),+ userId,+ });++ return NextResponse.json(+ { error: "Updates could not be checked. Please try again." },+ { status: 500 },+ );+ }+}diff --git a/src/components/settings/updates-panel.tsx b/src/components/settings/updates-panel.tsxnew file mode 100644index 0000000..35687fc--- /dev/null+++ b/src/components/settings/updates-panel.tsx@@ -0,0 +1,287 @@+"use client";++import { useState } from "react";++import { ShellButton } from "@/components/shared/form-shell";+import type { UpdateStatus } from "@/lib/software-update";++// The SignuDoc section of Settings, for the administrator: the version this+// install runs, a button that asks GitHub whether a newer one is out, and+// how to take it. Updating happens in the install's own GitHub repository,+// not here: a workflow there opens a pull request, and Vercel deploys it.++const linkClassName =+ "font-semibold text-(--accent-ink) underline decoration-[rgb(var(--accent-rgb)/0.35)] underline-offset-4";++export function UpdatesPanel({+ initialStatus,+}: {+ initialStatus: UpdateStatus;+}) {+ const [status, setStatus] = useState(initialStatus);+ const [isChecking, setIsChecking] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const check = status.check;++ async function checkNow() {+ setIsChecking(true);+ setError(null);++ try {+ const response = await fetch("/api/admin/updates", { method: "POST" });+ const payload = (await response.json().catch(() => null)) as+ (UpdateStatus & { error?: undefined }) | { error: string } | null;++ if (!response.ok || !payload || "error" in payload) {+ setError(+ (payload && "error" in payload && payload.error) ||+ "Updates could not be checked. Please try again.",+ );+ return;+ }++ setStatus(payload);+ } catch {+ setError("Updates could not be checked. Please try again.");+ } finally {+ setIsChecking(false);+ }+ }++ return (+ <section+ className="panel scroll-mt-6 p-6 sm:p-8"+ data-animate="enter"+ data-animate-delay="2"+ id="signudoc"+ >+ <div className="space-y-6">+ <div className="space-y-2">+ <p className="section-eyebrow">Administrator</p>+ <h2 className="text-2xl font-extrabold tracking-[-0.03em] text-(--fg)">+ SignuDoc+ </h2>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ This site runs SignuDoc version{" "}+ <span+ className="font-bold text-(--fg)"+ data-testid="running-version"+ >+ {status.current}+ </span>+ {status.commit ? (+ <>+ {" "}+ (commit <code className="text-(--fg)">{status.commit}</code>)+ </>+ ) : null}+ . New versions are published on{" "}+ <a+ className={linkClassName}+ href={status.releasesUrl}+ rel="noreferrer"+ target="_blank"+ >+ GitHub+ </a>+ .+ </p>+ </div>++ <ShellButton+ className="w-fit"+ loading={isChecking}+ onClick={checkNow}+ variant="secondary"+ >+ {isChecking ? "Checking..." : "Check for updates"}+ </ShellButton>++ {error ? (+ <p className="notice notice-danger" role="alert">+ {error}+ </p>+ ) : null}++ {check && !error ? (+ check.ok ? (+ check.updateAvailable ? (+ <div className="space-y-4" role="status">+ <p className="notice notice-accent">+ <strong>{check.latest.name}</strong> is out. This site runs{" "}+ {check.current}.+ </p>+ {check.latest.notes ? (+ <div className="space-y-2">+ <h3 className="text-base font-extrabold text-(--fg)">+ What's new+ </h3>+ <div className="max-h-80 space-y-1 overflow-y-auto rounded-2xl bg-(--surface) px-5 py-4 text-sm leading-6 text-(--secondary)">+ <ReleaseNotes notes={check.latest.notes} />+ </div>+ </div>+ ) : null}+ <a+ className={linkClassName}+ href={check.latest.url}+ rel="noreferrer"+ target="_blank"+ >+ Read the release on GitHub+ </a>+ </div>+ ) : (+ <p className="notice notice-success" role="status">+ You are up to date. {check.latest.version} is the latest+ release.+ </p>+ )+ ) : (+ <p className="notice notice-warning" role="status">+ {check.error}{" "}+ <a+ className={linkClassName}+ href={status.releasesUrl}+ rel="noreferrer"+ target="_blank"+ >+ See the releases+ </a>+ </p>+ )+ ) : null}++ <HowToUpdate status={status} />+ </div>+ </section>+ );+}++/**+ * Release notes are Markdown. They are shown as plain text, with headings+ * and list items picked out and the rest of the markup dropped: nothing in+ * them becomes HTML or a link.+ */+function ReleaseNotes({ notes }: { notes: string }) {+ const clean = (text: string) =>+ text+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")+ .replace(/[*_`]{1,3}([^*_`]+)[*_`]{1,3}/g, "$1");++ return notes.split(/\r?\n/).map((line, index) => {+ const heading = /^#{1,6}\s+(.*)$/.exec(line);+ const item = /^\s*[-*+]\s+(.*)$/.exec(line);++ if (heading) {+ return (+ <p className="pt-2 font-bold text-(--fg) first:pt-0" key={index}>+ {clean(heading[1])}+ </p>+ );+ }++ if (item) {+ return (+ <p className="flex gap-2 pl-1" key={index}>+ <span aria-hidden="true">•</span>+ <span>{clean(item[1])}</span>+ </p>+ );+ }++ return line.trim() ? <p key={index}>{clean(line)}</p> : null;+ });+}++function HowToUpdate({ status }: { status: UpdateStatus }) {+ const repository = status.repository;++ return (+ <div className="space-y-3 border-t border-(--border) pt-6">+ <h3 className="text-lg font-extrabold tracking-[-0.02em] text-(--fg)">+ How to update+ </h3>+ {repository && !repository.isUpstream ? (+ <>+ <ol className="max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-(--secondary)">+ <li>+ In your repository{" "}+ <a+ className={linkClassName}+ href={repository.url}+ rel="noreferrer"+ target="_blank"+ >+ {repository.owner}/{repository.slug}+ </a>+ , open the Update SignuDoc workflow and press{" "}+ <strong className="text-(--fg)">Run workflow</strong>. It also+ runs by itself once a week.+ </li>+ <li>+ It opens a pull request with the new version, and Vercel builds a+ preview of it. Your own changes to the code are kept; if they+ clash with the update, the workflow says which files.+ </li>+ <li>+ Merge the pull request. Vercel deploys it, and the build applies+ any database changes the new version needs.+ </li>+ </ol>+ <a+ className="btn-quiet min-h-12 w-fit px-5 text-sm"+ href={repository.actionsUrl}+ rel="noreferrer"+ target="_blank"+ >+ Open the update workflow+ </a>+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ No such workflow? Copies made before version 0.2.0 do not have it.{" "}+ <a+ className={linkClassName}+ href={repository.addWorkflowUrl}+ rel="noreferrer"+ target="_blank"+ >+ Create the file+ </a>{" "}+ in your repository once and paste in{" "}+ <a+ className={linkClassName}+ href={status.workflowSourceUrl}+ rel="noreferrer"+ target="_blank"+ >+ its contents+ </a>+ . The{" "}+ <a+ className={linkClassName}+ href={status.docsUrl}+ rel="noreferrer"+ target="_blank"+ >+ update guide+ </a>{" "}+ has the details.+ </p>+ </>+ ) : (+ <p className="max-w-2xl text-sm leading-6 text-(--secondary)">+ Bring the new release into the repository this site is built from,+ then deploy it. The{" "}+ <a+ className={linkClassName}+ href={status.docsUrl}+ rel="noreferrer"+ target="_blank"+ >+ update guide+ </a>{" "}+ shows how, including a GitHub workflow that does it for you.+ </p>+ )}+ </div>+ );+}diff --git a/src/lib/software-update.test.ts b/src/lib/software-update.test.tsnew file mode 100644index 0000000..46fb19a--- /dev/null+++ b/src/lib/software-update.test.ts@@ -0,0 +1,194 @@+import assert from "node:assert/strict";+import { beforeEach, test } from "node:test";++import {+ checkForUpdate,+ clearUpdateCheckCache,+ compareVersions,+ getDeployRepository,+ getRunningCommit,+ getRunningVersion,+ toReleaseInfo,+} from "./software-update.ts";++beforeEach(() => clearUpdateCheckCache());++function release(overrides: Record<string, unknown> = {}) {+ return {+ body: "## Added\n- Update checks",+ draft: false,+ html_url: "https://github.com/NYLLON-SOFTWARE/SignuDoc/releases/tag/v0.2.0",+ name: "SignuDoc 0.2.0",+ prerelease: false,+ published_at: "2026-11-15T10:00:00Z",+ tag_name: "v0.2.0",+ ...overrides,+ };+}++function fakeFetch(response: () => Response) {+ let calls = 0;+ const impl = (() => {+ calls += 1;+ return Promise.resolve(response());+ }) as unknown as typeof fetch;++ return { calls: () => calls, impl };+}++test("versions compare by number, and a pre-release comes first", () => {+ assert.ok(compareVersions("0.1.0", "0.2.0") < 0);+ assert.ok(compareVersions("0.10.0", "0.9.9") > 0);+ assert.equal(compareVersions("v1.2.3", "1.2.3"), 0);+ assert.ok(compareVersions("1.0.0-beta.1", "1.0.0") < 0);+ assert.equal(compareVersions("not a version", "1.0.0"), 0);+});++test("the running version and commit come from the build", () => {+ assert.equal(+ getRunningVersion({ NEXT_PUBLIC_SIGNUDOC_VERSION: "0.2.0" }),+ "0.2.0",+ );+ assert.equal(getRunningVersion({}), "0.0.0");+ assert.equal(+ getRunningCommit({+ VERCEL_GIT_COMMIT_SHA: "8678487b2550620e9f8141f6c78c333421127d9c",+ }),+ "8678487",+ );+ assert.equal(getRunningCommit({ VERCEL_GIT_COMMIT_SHA: "<script>" }), null);+});++test("the deploy repository comes from Vercel's git variables", () => {+ const repository = getDeployRepository({+ VERCEL_ENV: "production",+ VERCEL_GIT_COMMIT_REF: "main",+ VERCEL_GIT_PROVIDER: "github",+ VERCEL_GIT_REPO_OWNER: "acme",+ VERCEL_GIT_REPO_SLUG: "signudoc",+ });++ assert.deepEqual(repository, {+ actionsUrl:+ "https://github.com/acme/signudoc/actions/workflows/update-signudoc.yml",+ addWorkflowUrl:+ "https://github.com/acme/signudoc/new/main?filename=.github%2Fworkflows%2Fupdate-signudoc.yml",+ branch: "main",+ isUpstream: false,+ owner: "acme",+ slug: "signudoc",+ url: "https://github.com/acme/signudoc",+ });+});++test("no deploy repository off GitHub, or with odd names", () => {+ assert.equal(getDeployRepository({}), null);+ assert.equal(+ getDeployRepository({+ VERCEL_GIT_PROVIDER: "gitlab",+ VERCEL_GIT_REPO_OWNER: "acme",+ VERCEL_GIT_REPO_SLUG: "signudoc",+ }),+ null,+ );+ assert.equal(+ getDeployRepository({+ VERCEL_GIT_PROVIDER: "github",+ VERCEL_GIT_REPO_OWNER: "acme/../x",+ VERCEL_GIT_REPO_SLUG: "signudoc",+ }),+ null,+ );+});++test("a preview deployment still points at main, and upstream is recognised", () => {+ const repository = getDeployRepository({+ VERCEL_ENV: "preview",+ VERCEL_GIT_COMMIT_REF: "signudoc-update/v0.2.0",+ VERCEL_GIT_PROVIDER: "github",+ VERCEL_GIT_REPO_OWNER: "nyllon-software",+ VERCEL_GIT_REPO_SLUG: "signudoc",+ });++ assert.equal(repository?.branch, "main");+ assert.equal(repository?.isUpstream, true);+});++test("release info is read from GitHub's answer", () => {+ assert.deepEqual(toReleaseInfo(release()), {+ name: "SignuDoc 0.2.0",+ notes: "## Added\n- Update checks",+ publishedAt: "2026-11-15T10:00:00Z",+ url: "https://github.com/NYLLON-SOFTWARE/SignuDoc/releases/tag/v0.2.0",+ version: "0.2.0",+ });+ assert.equal(toReleaseInfo(release({ prerelease: true })), null);+ assert.equal(toReleaseInfo(release({ tag_name: "latest" })), null);+ // A link anywhere else is replaced with the project's own.+ assert.equal(+ toReleaseInfo(release({ html_url: "https://evil.example/x" }))?.url,+ "https://github.com/NYLLON-SOFTWARE/SignuDoc/releases/tag/v0.2.0",+ );+});++test("a newer release is an update, and the answer is cached", async () => {+ const github = fakeFetch(() => Response.json(release()));+ const first = await checkForUpdate({+ current: "0.1.0",+ fetchImpl: github.impl,+ });+ const second = await checkForUpdate({+ current: "0.1.0",+ fetchImpl: github.impl,+ });++ assert.equal(first.ok && first.updateAvailable, true);+ assert.deepEqual(second, first);+ assert.equal(github.calls(), 1);+});++test("the same release is not an update", async () => {+ const github = fakeFetch(() => Response.json(release()));+ const result = await checkForUpdate({+ current: "0.2.0",+ fetchImpl: github.impl,+ });++ assert.equal(result.ok && result.updateAvailable, false);+});++test("failures are reported, not thrown, and retried sooner", async () => {+ let now = 1_000_000;+ const limited = fakeFetch(() => new Response("{}", { status: 403 }));+ const result = await checkForUpdate({+ current: "0.1.0",+ fetchImpl: limited.impl,+ now: () => now,+ });++ assert.equal(result.ok, false);+ assert.match(!result.ok ? result.error : "", /limiting/);++ now += 6 * 60 * 1000;+ const offline = fakeFetch(() => {+ throw new TypeError("fetch failed");+ });+ const later = await checkForUpdate({+ current: "0.1.0",+ fetchImpl: offline.impl,+ now: () => now,+ });++ assert.equal(offline.calls(), 1);+ assert.match(!later.ok ? later.error : "", /could not be reached/);++ const none = fakeFetch(() => new Response("{}", { status: 404 }));++ clearUpdateCheckCache();+ const missing = await checkForUpdate({+ current: "0.1.0",+ fetchImpl: none.impl,+ });++ assert.match(!missing.ok ? missing.error : "", /no published release/);+});diff --git a/src/lib/software-update.ts b/src/lib/software-update.tsnew file mode 100644index 0000000..d6b7129--- /dev/null+++ b/src/lib/software-update.ts@@ -0,0 +1,329 @@+// Whether a newer SignuDoc has been released, for the SignuDoc section of+// Settings. The running version is baked in at build time (next.config.ts);+// the latest one is the newest GitHub Release of the project, read from+// GitHub's public API without a token. That API allows 60 requests an hour+// per address, and a Vercel function shares its address with others, so the+// answer is kept for a while and a failure is reported, never thrown.++export const UPSTREAM_OWNER = "NYLLON-SOFTWARE";+export const UPSTREAM_REPO = "SignuDoc";+export const UPSTREAM_SLUG = `${UPSTREAM_OWNER}/${UPSTREAM_REPO}`;+export const UPSTREAM_RELEASES_URL = `https://github.com/${UPSTREAM_SLUG}/releases`;+export const UPDATE_WORKFLOW_FILE = "update-signudoc.yml";+export const UPDATE_WORKFLOW_PATH = `.github/workflows/${UPDATE_WORKFLOW_FILE}`;+export const UPDATE_DOCS_URL = `https://github.com/${UPSTREAM_SLUG}/blob/main/docs/self-hosting.md#keep-your-install-up-to-date`;+export const UPDATE_WORKFLOW_SOURCE_URL = `https://raw.githubusercontent.com/${UPSTREAM_SLUG}/main/${UPDATE_WORKFLOW_PATH}`;++const LATEST_RELEASE_API = `https://api.github.com/repos/${UPSTREAM_SLUG}/releases/latest`;+const SUCCESS_TTL_MS = 30 * 60 * 1000;+const FAILURE_TTL_MS = 5 * 60 * 1000;+const REQUEST_TIMEOUT_MS = 8_000;+// Release notes are shown as text in Settings; a very long one is cut.+const MAX_NOTES_LENGTH = 20_000;++export type ReleaseInfo = {+ name: string;+ notes: string;+ publishedAt: string | null;+ url: string;+ version: string;+};++export type DeployRepository = {+ /** The Actions page of the update workflow in the install's own copy. */+ actionsUrl: string;+ /** Adds the update workflow to a copy made before it existed. */+ addWorkflowUrl: string;+ branch: string;+ isUpstream: boolean;+ owner: string;+ slug: string;+ url: string;+};++export type UpdateCheck =+ | {+ checkedAt: string;+ current: string;+ latest: ReleaseInfo;+ ok: true;+ updateAvailable: boolean;+ }+ | {+ checkedAt: string;+ current: string;+ error: string;+ ok: false;+ };++export type UpdateStatus = {+ check: UpdateCheck | null;+ commit: string | null;+ current: string;+ docsUrl: string;+ releasesUrl: string;+ repository: DeployRepository | null;+ workflowSourceUrl: string;+};++type Env = Record<string, string | undefined>;++/** The version this deployment was built from, from package.json. */+export function getRunningVersion(env?: Env): string {+ // Spelled out in full so the build can put the value in its place.+ const value = env+ ? env.NEXT_PUBLIC_SIGNUDOC_VERSION+ : process.env.NEXT_PUBLIC_SIGNUDOC_VERSION;++ return value?.trim() || "0.0.0";+}++/** The commit this deployment was built from, when Vercel says. */+export function getRunningCommit(env: Env = process.env): string | null {+ const sha = env.VERCEL_GIT_COMMIT_SHA?.trim();++ return sha && /^[0-9a-f]{7,40}$/i.test(sha) ? sha.slice(0, 7) : null;+}++const NAME_PART = /^[A-Za-z0-9_.-]{1,100}$/;++/**+ * The GitHub repository Vercel deploys this install from: the copy the+ * Deploy button made. Vercel exposes it in its system environment+ * variables. Null when the install is not deployed from GitHub on Vercel.+ */+export function getDeployRepository(+ env: Env = process.env,+): DeployRepository | null {+ if (env.VERCEL_GIT_PROVIDER !== "github") {+ return null;+ }++ const owner = env.VERCEL_GIT_REPO_OWNER?.trim() ?? "";+ const slug = env.VERCEL_GIT_REPO_SLUG?.trim() ?? "";++ if (!NAME_PART.test(owner) || !NAME_PART.test(slug)) {+ return null;+ }++ // Production deployments are built from the production branch. A preview+ // is built from some other branch, and the workflow belongs on the+ // production one, which is main unless the deployer changed it.+ const ref = env.VERCEL_GIT_COMMIT_REF?.trim() ?? "";+ const branch =+ env.VERCEL_ENV === "production" && /^[A-Za-z0-9_./-]{1,200}$/.test(ref)+ ? ref+ : "main";+ const url = `https://github.com/${owner}/${slug}`;++ return {+ actionsUrl: `${url}/actions/workflows/${UPDATE_WORKFLOW_FILE}`,+ addWorkflowUrl: `${url}/new/${encodeURIComponent(branch)}?filename=${encodeURIComponent(UPDATE_WORKFLOW_PATH)}`,+ branch,+ isUpstream:+ `${owner}/${slug}`.toLowerCase() === UPSTREAM_SLUG.toLowerCase(),+ owner,+ slug,+ url,+ };+}++type ParsedVersion = { core: [number, number, number]; pre: string | null };++export function parseVersion(value: string): ParsedVersion | null {+ const match =+ /^v?(\d{1,9})\.(\d{1,9})\.(\d{1,9})(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(+ value.trim(),+ );++ if (!match) {+ return null;+ }++ return {+ core: [Number(match[1]), Number(match[2]), Number(match[3])],+ pre: match[4] ?? null,+ };+}++/** Negative when a is older than b, positive when newer, 0 when equal. */+export function compareVersions(a: string, b: string): number {+ const left = parseVersion(a);+ const right = parseVersion(b);++ if (!left || !right) {+ return 0;+ }++ for (let index = 0; index < 3; index += 1) {+ const difference = left.core[index] - right.core[index];++ if (difference !== 0) {+ return difference;+ }+ }++ // 1.0.0-beta comes before 1.0.0. Pre-releases are not compared further.+ if (left.pre && !right.pre) {+ return -1;+ }++ if (!left.pre && right.pre) {+ return 1;+ }++ return 0;+}++export function toReleaseInfo(payload: unknown): ReleaseInfo | null {+ if (!payload || typeof payload !== "object") {+ return null;+ }++ const record = payload as Record<string, unknown>;+ const tag = typeof record.tag_name === "string" ? record.tag_name : "";+ const parsed = parseVersion(tag);++ if (!parsed || record.draft === true || record.prerelease === true) {+ return null;+ }++ const version = parsed.core.join(".") + (parsed.pre ? `-${parsed.pre}` : "");+ const htmlUrl = typeof record.html_url === "string" ? record.html_url : "";+ // Only ever link to the project's own releases.+ const url = htmlUrl.startsWith(`https://github.com/${UPSTREAM_SLUG}/`)+ ? htmlUrl+ : `${UPSTREAM_RELEASES_URL}/tag/${encodeURIComponent(tag)}`;+ const body = typeof record.body === "string" ? record.body.trim() : "";+ const name =+ typeof record.name === "string" && record.name.trim()+ ? record.name.trim()+ : `SignuDoc ${version}`;++ return {+ name: name.slice(0, 200),+ notes:+ body.length > MAX_NOTES_LENGTH+ ? `${body.slice(0, MAX_NOTES_LENGTH)}\n\n…`+ : body,+ publishedAt:+ typeof record.published_at === "string" ? record.published_at : null,+ url,+ version,+ };+}++type CacheEntry = { expiresAt: number; value: UpdateCheck };++const cacheHolder = globalThis as typeof globalThis & {+ __signudocUpdateCheck?: CacheEntry;+};++export function clearUpdateCheckCache() {+ delete cacheHolder.__signudocUpdateCheck;+}++/**+ * Asks GitHub for the latest release and compares it with the running+ * version. Kept for 30 minutes (5 after a failure), shared by every+ * administrator of the install.+ */+export async function checkForUpdate({+ current = getRunningVersion(),+ fetchImpl = fetch,+ now = Date.now,+}: {+ current?: string;+ fetchImpl?: typeof fetch;+ now?: () => number;+} = {}): Promise<UpdateCheck> {+ const cached = cacheHolder.__signudocUpdateCheck;++ if (cached && cached.expiresAt > now() && cached.value.current === current) {+ return cached.value;+ }++ const value = await fetchLatest(current, fetchImpl, now);++ cacheHolder.__signudocUpdateCheck = {+ expiresAt: now() + (value.ok ? SUCCESS_TTL_MS : FAILURE_TTL_MS),+ value,+ };++ return value;+}++async function fetchLatest(+ current: string,+ fetchImpl: typeof fetch,+ now: () => number,+): Promise<UpdateCheck> {+ const checkedAt = new Date(now()).toISOString();+ const fail = (error: string): UpdateCheck => ({+ checkedAt,+ current,+ error,+ ok: false,+ });++ let response: Response;++ try {+ response = await fetchImpl(LATEST_RELEASE_API, {+ cache: "no-store",+ headers: {+ accept: "application/vnd.github+json",+ "user-agent": "SignuDoc-update-check",+ "x-github-api-version": "2022-11-28",+ },+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ } catch {+ return fail("GitHub could not be reached. Try again in a few minutes.");+ }++ if (response.status === 404) {+ return fail("SignuDoc has no published release yet.");+ }++ if (response.status === 403 || response.status === 429) {+ return fail(+ "GitHub is limiting how often this server can ask. Try again later, or look at the releases page.",+ );+ }++ if (!response.ok) {+ return fail(+ `GitHub answered with an error (${response.status}). Try again later.`,+ );+ }++ const latest = toReleaseInfo(await response.json().catch(() => null));++ if (!latest) {+ return fail("GitHub's answer could not be read. Try again later.");+ }++ return {+ checkedAt,+ current,+ latest,+ ok: true,+ updateAvailable: compareVersions(current, latest.version) < 0,+ };+}++export function getUpdateStatus(+ check: UpdateCheck | null,+ env?: Env,+): UpdateStatus {+ return {+ check,+ commit: getRunningCommit(env ?? process.env),+ current: getRunningVersion(env),+ docsUrl: UPDATE_DOCS_URL,+ releasesUrl: UPSTREAM_RELEASES_URL,+ repository: getDeployRepository(env ?? process.env),+ workflowSourceUrl: UPDATE_WORKFLOW_SOURCE_URL,+ };+}diff --git a/src/lib/update-workflow.test.ts b/src/lib/update-workflow.test.tsnew file mode 100644index 0000000..ccf9715--- /dev/null+++ b/src/lib/update-workflow.test.ts@@ -0,0 +1,460 @@+import assert from "node:assert/strict";+import { execFileSync, spawnSync } from "node:child_process";+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { after, test } from "node:test";++// Runs the two shell steps of .github/workflows/update-signudoc.yml against+// throwaway repositories: a pretend SignuDoc with two releases, and a copy+// made the way the Vercel Deploy button makes one (a single commit holding+// the files of the first release, with none of its history). `gh` is a+// stub that answers the release questions and records the pull request.++const repoRoot = path.resolve(import.meta.dirname, "..", "..");+const workflow = readFileSync(+ path.join(repoRoot, ".github/workflows/update-signudoc.yml"),+ "utf8",+);++/** The `run: |` blocks of the workflow, in order, dedented. */+function runBlocks(): string[] {+ const lines = workflow.split("\n");+ const blocks: string[] = [];++ for (let index = 0; index < lines.length; index += 1) {+ const match = /^(\s*)run: \|\s*$/.exec(lines[index]);++ if (!match) {+ continue;+ }++ const body: string[] = [];+ let indent: number | null = null;++ for (index += 1; index < lines.length; index += 1) {+ const line = lines[index];++ if (line.trim() === "") {+ body.push("");+ continue;+ }++ const lineIndent = line.length - line.trimStart().length;++ if (lineIndent <= match[1].length) {+ index -= 1;+ break;+ }++ indent ??= lineIndent;+ body.push(line.slice(indent));+ }++ blocks.push(body.join("\n"));+ }++ return blocks;+}++const [mergeStep, publishStep] = runBlocks();+const scratch = mkdtempSync(path.join(tmpdir(), "signudoc-update-"));++after(() => rmSync(scratch, { force: true, recursive: true }));++const gitEnv = {+ ...process.env,+ GIT_AUTHOR_EMAIL: "[email protected]",+ GIT_AUTHOR_NAME: "Test",+ GIT_COMMITTER_EMAIL: "[email protected]",+ GIT_COMMITTER_NAME: "Test",+ GIT_CONFIG_GLOBAL: "/dev/null",+ GIT_CONFIG_NOSYSTEM: "1",+};++function git(cwd: string, ...args: string[]): string {+ return execFileSync("git", args, {+ cwd,+ encoding: "utf8",+ env: gitEnv,+ }).trim();+}++function write(dir: string, file: string, content: string) {+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });+ writeFileSync(path.join(dir, file), content);+}++let counter = 0;++/** A pretend SignuDoc: v0.1.0, then v0.2.0 with a migration and CI change. */+function makeUpstream() {+ const dir = path.join(scratch, `upstream-${String((counter += 1))}`);++ mkdirSync(dir);+ git(dir, "init", "--quiet", "--initial-branch=main");+ write(dir, "package.json", '{ "version": "0.1.0" }\n');+ write(dir, "src/app.ts", "export const a = 1;\nexport const b = 2;\n");+ write(dir, "db/migrations/001_init.sql", "create table t ();\n");+ write(dir, ".github/workflows/ci.yml", "name: CI\n");+ git(dir, "add", ".");+ git(dir, "commit", "--quiet", "-m", "First");+ git(dir, "tag", "v0.1.0");+ write(dir, "package.json", '{ "version": "0.2.0" }\n');+ write(dir, "src/app.ts", "export const a = 1;\nexport const b = 3;\n");+ write(dir, "db/migrations/002_more.sql", "alter table t add c int;\n");+ write(dir, ".github/workflows/ci.yml", "name: CI\non: push\n");+ git(dir, "add", ".");+ git(dir, "commit", "--quiet", "-m", "Second");+ git(dir, "tag", "v0.2.0");++ return dir;+}++/** A Deploy-button copy of v0.1.0: one commit, no shared history. */+function makeCopy(+ upstream: string,+ change?: (dir: string) => void,+ changeFirstCommit?: (dir: string) => void,+) {+ const origin = path.join(scratch, `origin-${String((counter += 1))}.git`);+ const work = path.join(scratch, `copy-${String(counter)}`);++ git(scratch, "init", "--quiet", "--bare", "--initial-branch=main", origin);+ git(scratch, "init", "--quiet", "--initial-branch=main", work);+ execFileSync(+ "sh",+ ["-c", `git -C "${upstream}" archive v0.1.0 | tar -x -C "${work}"`],+ {+ env: gitEnv,+ },+ );+ changeFirstCommit?.(work);+ git(work, "add", ".");+ git(work, "commit", "--quiet", "-m", "Initial commit");++ if (change) {+ change(work);+ git(work, "add", ".");+ git(work, "commit", "--quiet", "-m", "Our change");+ }++ git(work, "remote", "add", "origin", origin);+ git(work, "push", "--quiet", "origin", "main");++ return { origin };+}++/** A fresh checkout of the copy, as actions/checkout makes one. */+function checkout(origin: string) {+ const dir = path.join(scratch, `checkout-${String((counter += 1))}`);++ git(scratch, "clone", "--quiet", origin, dir);++ return dir;+}++function makeGhStub(upstream: string) {+ const bin = path.join(scratch, `bin-${String((counter += 1))}`);+ const log = path.join(bin, "gh.log");++ mkdirSync(bin);+ writeFileSync(+ path.join(bin, "gh"),+ `#!/usr/bin/env bash+echo "$*" >> "${log}"+release() {+ printf '{"tag_name":"%s","html_url":"https://github.com/NYLLON-SOFTWARE/SignuDoc/releases/tag/%s","body":"Notes for %s"}' "$1" "$1" "$1"+}+case "$1 $2" in+ "api repos/NYLLON-SOFTWARE/SignuDoc/releases/latest") release v0.2.0 ;;+ "api repos/NYLLON-SOFTWARE/SignuDoc/releases/tags/"*)+ tag="\${2##*/}"+ git -C "${upstream}" rev-parse -q --verify "refs/tags/$tag" > /dev/null || exit 1+ release "$tag" ;;+ "pr list") echo "" ;;+ "pr create") echo "https://github.com/acme/signudoc/pull/1" ;;+ *) echo "unexpected gh $*" >&2; exit 2 ;;+esac+`,+ );+ chmodSync(path.join(bin, "gh"), 0o755);++ return { bin, log };+}++type RunResult = {+ output: Record<string, string>;+ status: number | null;+ stderr: string;+ summary: string;+};++function runUpdate(+ dir: string,+ upstream: string,+ options: { hasToken?: boolean; mergeNow?: boolean; version?: string } = {},+): RunResult & { gh: string; prBody: string } {+ const gh = makeGhStub(upstream);+ const temp = mkdtempSync(path.join(scratch, "runner-"));+ const summaryFile = path.join(temp, "summary.md");+ const outputFile = path.join(temp, "output");++ writeFileSync(summaryFile, "");+ writeFileSync(outputFile, "");++ const env = {+ ...gitEnv,+ BASE_BRANCH: "main",+ GITHUB_OUTPUT: outputFile,+ GITHUB_REPOSITORY: "acme/signudoc",+ GITHUB_SERVER_URL: "https://github.com",+ GITHUB_STEP_SUMMARY: summaryFile,+ HAS_UPDATE_TOKEN: options.hasToken ? "true" : "false",+ MERGE_NOW: options.mergeNow ? "true" : "false",+ PATH: `${gh.bin}:${process.env.PATH ?? ""}`,+ REQUESTED_VERSION: options.version ?? "",+ RUNNER_TEMP: temp,+ UPSTREAM: "NYLLON-SOFTWARE/SignuDoc",+ UPSTREAM_GIT_URL: upstream,+ };+ const first = spawnSync("bash", ["-c", mergeStep], {+ cwd: dir,+ encoding: "utf8",+ env,+ });+ const output = Object.fromEntries(+ readFileSync(outputFile, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => line.split("=", 2) as [string, string]),+ );+ let status = first.status;+ let stderr = first.stderr;++ if (status === 0 && output.branch) {+ const second = spawnSync("bash", ["-c", publishStep], {+ cwd: dir,+ encoding: "utf8",+ env: { ...env, BRANCH: output.branch, TAG: output.tag },+ });++ status = second.status;+ stderr += second.stderr;+ }++ let ghLog = "";++ try {+ ghLog = readFileSync(gh.log, "utf8");+ } catch {+ // gh was never called.+ }++ let prBody = "";++ try {+ prBody = readFileSync(path.join(temp, "pr-body.md"), "utf8");+ } catch {+ // No pull request was prepared.+ }++ return {+ gh: ghLog,+ output,+ prBody,+ status,+ stderr,+ summary: readFileSync(summaryFile, "utf8"),+ };+}++function show(origin: string, ref: string, file: string): string {+ return git(origin, "show", `${ref}:${file}`);+}++test("a Deploy-button copy gets a pull request with the new release", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.output.branch, "signudoc-update/v0.2.0");+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "src/app.ts"),+ "export const a = 1;\nexport const b = 3;",+ );+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "db/migrations/002_more.sql"),+ "alter table t add c int;",+ );+ // The commit names the release, so the next run knows where it stands.+ assert.match(+ git(origin, "log", "-1", "--format=%B", "signudoc-update/v0.2.0"),+ new RegExp(`SignuDoc-Commit: ${git(upstream, "rev-parse", "v0.2.0")}`),+ );+ // One new commit on top of the copy, none of SignuDoc's own history.+ assert.equal(+ git(origin, "rev-list", "--count", "signudoc-update/v0.2.0"),+ "2",+ );+ assert.match(+ result.gh,+ /pr create --base main --head signudoc-update\/v0\.2\.0/,+ );+ assert.match(+ result.summary,+ /Opened https:\/\/github\.com\/acme\/signudoc\/pull\/1/,+ );+});++test("without a token, workflow files are left alone and listed", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", ".github/workflows/ci.yml"),+ "name: CI",+ );+ assert.match(+ result.prBody,+ /Workflow files not updated[\s\S]*- `\.github\/workflows\/ci\.yml`/,+ );+ assert.match(+ result.prBody,+ /Database changes[\s\S]*- `db\/migrations\/002_more\.sql`/,+ );+ assert.match(result.prBody, /Notes for v0\.2\.0/);+});++test("with a token, workflow files are updated too", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream, { hasToken: true });++ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", ".github/workflows/ci.yml"),+ "name: CI\non: push",+ );+});++test("the deployer's own changes are kept", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream, (dir) => {+ write(+ dir,+ "src/app.ts",+ "// ours\nexport const a = 1;\nexport const b = 2;\n",+ );+ write(dir, "src/ours.ts", "export const ours = true;\n");+ });+ const result = runUpdate(checkout(origin), upstream);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "src/app.ts"),+ "// ours\nexport const a = 1;\nexport const b = 3;",+ );+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "src/ours.ts"),+ "export const ours = true;",+ );+});++test("a first commit that matches no release still finds its base", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream, undefined, (dir) => {+ write(dir, "README.md", "Our install\n");+ });+ const result = runUpdate(checkout(origin), upstream);++ assert.equal(result.status, 0, result.stderr);+ assert.match(result.summary, /Using the closest one/);+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "README.md"),+ "Our install",+ );+ assert.equal(+ show(origin, "signudoc-update/v0.2.0", "package.json"),+ '{ "version": "0.2.0" }',+ );+});++test("a clash stops the run and names the files", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream, (dir) => {+ write(dir, "src/app.ts", "export const a = 1;\nexport const b = 99;\n");+ });+ const result = runUpdate(checkout(origin), upstream);++ assert.equal(result.status, 1);+ assert.match(result.summary, /clashes/);+ assert.match(result.summary, /- `src\/app\.ts`/);+ assert.equal(git(origin, "branch", "--list", "signudoc-update/*"), "");+});++test("once the pull request is merged, the next run is up to date", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);++ assert.equal(runUpdate(checkout(origin), upstream).status, 0);+ // Merged the way GitHub's squash button does: a new commit, same files.+ const dir = checkout(origin);++ git(dir, "merge", "--quiet", "--squash", "origin/signudoc-update/v0.2.0");+ git(+ dir,+ "commit",+ "--quiet",+ "-m",+ `Update SignuDoc to v0.2.0 (#1)\n\nSignuDoc-Commit: ${git(upstream, "rev-parse", "v0.2.0")}`,+ );+ git(dir, "push", "--quiet", "origin", "main");+ git(dir, "push", "--quiet", "origin", "--delete", "signudoc-update/v0.2.0");++ const again = runUpdate(checkout(origin), upstream);++ assert.equal(again.status, 0, again.stderr);+ assert.equal(again.output.branch, undefined);+ assert.match(again.summary, /Already up to date with SignuDoc v0\.2\.0/);+});++test("a copy that is already on the latest release is up to date", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream, { version: "0.1.0" });++ assert.equal(result.status, 0, result.stderr);+ assert.match(result.summary, /Already up to date with SignuDoc v0\.1\.0/);+});++test("merge-now pushes straight to the production branch", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream, { mergeNow: true });++ assert.equal(result.status, 0, result.stderr);+ assert.equal(show(origin, "main", "package.json"), '{ "version": "0.2.0" }');+ assert.doesNotMatch(result.gh, /pr create/);+});++test("a version that is not a release is refused", () => {+ const upstream = makeUpstream();+ const { origin } = makeCopy(upstream);+ const result = runUpdate(checkout(origin), upstream, {+ version: "main; rm -rf /",+ });++ assert.equal(result.status, 1);+ assert.match(result.summary, /is not a release version/);+});