Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

publish-site: check the gh account before the site is mirrored, not after (#518)

nyblnet870f34ec46f3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ee04bc29..3af36e1c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -972,6 +972,13 @@ jobs:
# and simply trusts more than it should.
run: node scripts/test-relay-auth.ts
+ - name: publish account gate — the release account is checked before the site goes live
+ # publish-site.mjs mirrored and pushed the site and THEN failed to
+ # create the GitHub release, three releases running, because gh was
+ # the work profile (a job/temp worktree). The gate runs before rsync;
+ # this rig pins the rule and the order.
+ run: node scripts/test-publish-account.ts
+
- name: client vouch rig — the other half of read-only
# Drives a REAL OnlineTransport (kernel's and dash's twin) through a
# fake socket in a signed room. Every copy holds the room key, so a
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 37efb86f..fae5c223 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -177,6 +177,19 @@ matters. Neither needs the signing key.
BENTO_SITE_DIR=~/devel/bento-site node scripts/publish-site.mjs "release vX.Y.Z"
```
+ **Build anywhere; publish from a path under `~/devel`.** The shell picks
+ the `gh` profile by directory (a chpwd hook), and a job or temp worktree
+ — `~/.claude-andy/jobs/…/tmp`, `/tmp/rel` — maps to the WORK profile,
+ which cannot create a release on this repo. `publish-site.mjs` checks the
+ active `gh` account against the repo owner **before it mirrors anything**
+ and, on a mismatch, prints the exact command to run from `~/devel/bento`
+ and exits non-zero. Three releases were created by hand before this check
+ existed because the site went live first and the release step failed
+ after. So: `cd ~/devel/bento` (or any checkout under `~/devel`) and run
+ the publish from there, pointing `BENTO_SITE_DIR` at the site repo. A
+ collaborator with release rights who is not the owner can be allowed with
+ `BENTO_RELEASE_ACCOUNTS=name1,name2`.
+
This mirrors the assembled `site/` tree into `../bento-site` (or
`$BENTO_SITE_DIR`) and pushes it. **`site/` is fully generated — never edit
it by hand.** The authored sources are tracked in *this* repo and assembled
@@ -217,9 +230,10 @@ matters. Neither needs the signing key.
an existing release is left alone and only a missing asset is uploaded, so
re-running publish is safe.
- It is deliberately **not** best-effort. If `gh` is unauthenticated, or the
- asset is missing afterwards, publish exits non-zero and tells you the exact
- command to run. This used to be a manual step, and it was silently missed
+ It is deliberately **not** best-effort. The account is checked before the
+ mirror (step 5); if `gh` is unauthenticated or the wrong account, nothing
+ is published; if the asset is missing afterwards, publish exits non-zero
+ and tells you the exact command to run. This used to be a manual step, and it was silently missed
for v1.0.10 — the site was live and self-updating while the repo showed no
release at all. Documentation didn't prevent that, so the check now does.
7. **Verify against the LIVE channel, not the local build.** These are the
diff --git a/scripts/gh-account.mjs b/scripts/gh-account.mjs
new file mode 100644
index 00000000..2cdda555
--- /dev/null
+++ b/scripts/gh-account.mjs
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Which GitHub account is `gh` speaking as, and is it the one that may
+// create a release on this repo? Pure: the rule takes strings and returns a
+// verdict, so scripts/test-publish-account.ts drives it without a network
+// or a keyring; publish-site.mjs supplies the strings.
+//
+// WHY THIS EXISTS. Three releases running, publish-site.mjs mirrored and
+// pushed the site and THEN `gh release create` failed: the release worktree
+// lived under ~/.claude-andy/jobs/…/tmp, where the shell's chpwd hook selects
+// the WORK gh profile — a different account, no scope for this repo — and
+// gh's config follows the environment the script was launched from, not the
+// repo it is pointed at. Each time the lead created the release by hand from
+// ~/devel/bento. The account is now checked BEFORE the rsync: a mismatch
+// prints the exact command to run from a path under ~/devel and exits
+// non-zero with nothing published. Publishing the site and then failing the
+// release is the one order that must never happen — the update channel goes
+// live while the repo shows no release.
+
+/** The owner of a GitHub remote: [email protected]:owner/repo.git,
+ * https://github.com/owner/repo(.git), ssh://[email protected]/owner/repo. */
+export function ownerOfRemote(url) {
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(String(url ?? '').trim())
+ return m ? m[1] : null
+}
+
+/** The active account in `gh auth status` output (either format gh has
+ * used: "Logged in to github.com account NAME (…)" with an "Active account:
+ * true" line, or the older "Logged in to github.com as NAME (…)"). */
+export function activeAccount(statusText) {
+ const text = String(statusText ?? '')
+ const blocks = text.split(/\n(?=\s*(?:✓|X|-|\S)\s*Logged in)/)
+ for (const b of blocks) {
+ const m = /Logged in to github\.com (?:account|as) ([A-Za-z0-9-]+)/.exec(b)
+ if (!m) continue
+ if (/Active account:\s*false/i.test(b)) continue
+ return m[1]
+ }
+ const any = /Logged in to github\.com (?:account|as) ([A-Za-z0-9-]+)/.exec(text)
+ return any ? any[1] : null
+}
+
+/**
+ * May this account create a release on this repo? The owner, or a name the
+ * caller lists as a collaborator with release rights. A null account (not
+ * logged in, or unparsable) never may.
+ */
+export function accountMayRelease(account, owner, collaborators = []) {
+ if (!account || !owner) return false
+ const a = account.toLowerCase()
+ return a === owner.toLowerCase() || collaborators.some((c) => String(c).toLowerCase() === a)
+}
+
+/** The sentence publish-site prints on a mismatch: what gh is, what it must
+ * be, and the exact command — from a path the shell maps to the right
+ * profile. */
+export function mismatchMessage({ account, owner, repoRoot, cmd }) {
+ return [
+ `gh is authenticated as ${account ?? 'nobody'}; a release on this repo needs ${owner}.`,
+ ` Nothing was published (this check runs before the site is mirrored).`,
+ ` The shell picks the gh profile by directory — run the publish from a path under ~/devel, not from a job or temp worktree:`,
+ ` cd ${repoRoot} && ${cmd}`,
+ ` (or: gh auth switch --user ${owner}, then re-run from here).`,
+ ].join('\n')
+}
diff --git a/scripts/publish-site.mjs b/scripts/publish-site.mjs
index 096cee7b..37db2c9f 100755
--- a/scripts/publish-site.mjs
+++ b/scripts/publish-site.mjs
@@ -31,6 +31,7 @@ import { fileURLToPath } from 'node:url'
import { gatePackIndex } from './sign-packs.mjs'
import { walk, plannedDeletions, groupDeletions, supersededPacks } from './site-inventory.mjs'
import { APPS, RELEASE_MARKER, tagFor } from './apps.mjs'
+import { accountMayRelease, activeAccount, mismatchMessage, ownerOfRemote } from './gh-account.mjs'
const root = dirname(dirname(fileURLToPath(import.meta.url)))
const site = join(root, 'site')
@@ -317,6 +318,28 @@ if (!existsSync(join(site, 'guestbook.bento.html'))) {
}
}
+// ---- the gh account, BEFORE anything is published ------------------------
+//
+// Publishing has two halves — mirror the site, then create the GitHub
+// release — and the second needs gh to be the repo owner's account. Three
+// releases running it was not (a job/temp worktree, where the shell's chpwd
+// hook selects the work profile), and the failure came AFTER the site was
+// live. So: which account is gh, and may it release here? Checked here, with
+// nothing mirrored yet; the message names the command to run from ~/devel.
+// scripts/gh-account.mjs holds the rule; scripts/test-publish-account.ts the
+// cases. --dry skips it (a dry run publishes nothing either way); every real
+// publish runs it, because every real publish ends in the release step.
+if (!dry) {
+ const owner = ownerOfRemote((() => { try { return capture('git', ['-C', root, 'remote', 'get-url', 'origin']) } catch { return '' } })())
+ const status = (() => { try { return capture('gh', ['auth', 'status'], { stdio: ['ignore', 'pipe', 'pipe'] }) } catch (e) { return String(e?.stdout ?? '') + String(e?.stderr ?? '') } })()
+ const account = activeAccount(status)
+ const allowed = (process.env.BENTO_RELEASE_ACCOUNTS ?? '').split(',').map((s) => s.trim()).filter(Boolean)
+ if (!owner) console.warn('⚠ could not read the repo owner from origin — skipping the gh account check')
+ else if (!accountMayRelease(account, owner, allowed)) {
+ die(mismatchMessage({ account, owner, repoRoot: root.startsWith(process.env.HOME ?? '') ? root : '~/devel/bento', cmd: `node scripts/publish-site.mjs ${args.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(' ')}` }))
+ } else console.log(`• gh account: ${account} ✓ (may release on ${owner})`)
+}
+
if (dry) rsyncFlags.push('-n', '-v', '--itemize-changes')
console.log(`• ${dry ? 'DRY-RUN ' : ''}mirroring ${site}/ → ${dest}/`)
run('rsync', [...rsyncFlags, `${site}/`, `${dest}/`])
diff --git a/scripts/test-publish-account.ts b/scripts/test-publish-account.ts
new file mode 100644
index 00000000..230180ce
--- /dev/null
+++ b/scripts/test-publish-account.ts
@@ -0,0 +1,74 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// The gh account gate publish-site.mjs runs BEFORE mirroring the site
+// (scripts/gh-account.mjs):
+//
+// node scripts/test-publish-account.ts
+//
+// WHAT THIS PROVES. The owner is read from any GitHub remote spelling; the
+// active account is read from both formats of `gh auth status` (and an
+// inactive account is not mistaken for the active one); the rule refuses a
+// mismatched owner, nobody, and accepts the owner or a listed collaborator
+// case-insensitively; the message names the command to run from a path
+// under ~/devel. And the gate sits BEFORE the rsync in publish-site.mjs —
+// the whole point: the site must never go live and the release then fail.
+
+import { readFileSync } from 'node:fs'
+import { accountMayRelease, activeAccount, mismatchMessage, ownerOfRemote } from './gh-account.mjs'
+
+let failures = 0, checks = 0
+const ok = (cond: boolean, msg: string) => { checks++; if (!cond) { failures++; console.log(` FAIL ${msg}`) } else console.log(` ok ${msg}`) }
+
+console.log('\nownerOfRemote')
+ok(ownerOfRemote('[email protected]:nyblnet/bento.git') === 'nyblnet', 'ssh scp form')
+ok(ownerOfRemote('https://github.com/nyblnet/bento') === 'nyblnet' && ownerOfRemote('https://github.com/nyblnet/bento.git/') === 'nyblnet', 'https, with and without .git and a trailing slash')
+ok(ownerOfRemote('ssh://[email protected]/Some-Org/repo.git') === 'Some-Org', 'ssh url form, dashes kept')
+ok(ownerOfRemote('https://gitlab.com/x/y') === null && ownerOfRemote('') === null && ownerOfRemote(undefined) === null, 'not GitHub, empty, undefined → null')
+
+console.log('\nactiveAccount')
+const NEW = `github.com
+ ✓ Logged in to github.com account work-andy (keyring)
+ - Active account: false
+ - Git operations protocol: https
+ ✓ Logged in to github.com account nyblnet (keyring)
+ - Active account: true
+ - Token scopes: 'gist', 'read:org', 'repo', 'workflow'`
+ok(activeAccount(NEW) === 'nyblnet', 'the ACTIVE account in the multi-account format, not the first listed')
+const OLD = `github.com
+ ✓ Logged in to github.com as nyblnet (oauth_token)
+ ✓ Git operations for github.com configured to use https protocol.`
+ok(activeAccount(OLD) === 'nyblnet', 'the older single-account format')
+ok(activeAccount('You are not logged into any GitHub hosts. Run gh auth login to authenticate.') === null && activeAccount('') === null, 'not logged in → null')
+const WORK = `github.com
+ ✓ Logged in to github.com account work-andy (keyring)
+ - Active account: true`
+ok(activeAccount(WORK) === 'work-andy', 'the work profile reads as the work account')
+
+console.log('\naccountMayRelease')
+ok(accountMayRelease('nyblnet', 'nyblnet') === true && accountMayRelease('NyblNet', 'nyblnet') === true, 'the owner may, case-insensitively')
+ok(accountMayRelease('work-andy', 'nyblnet') === false, 'a mismatched owner is REFUSED (the three failed releases)')
+ok(accountMayRelease(null, 'nyblnet') === false && accountMayRelease('nyblnet', null) === false, 'nobody may; no owner, nobody may')
+ok(accountMayRelease('helper', 'nyblnet', ['Helper']) === true && accountMayRelease('other', 'nyblnet', ['helper']) === false, 'a listed collaborator may (BENTO_RELEASE_ACCOUNTS), an unlisted one may not')
+
+console.log('\nmismatchMessage')
+const msg = mismatchMessage({ account: 'work-andy', owner: 'nyblnet', repoRoot: '/Users/andy/devel/bento', cmd: 'node scripts/publish-site.mjs "release v1.2.3"' })
+ok(/authenticated as work-andy/.test(msg) && /needs nyblnet/.test(msg), 'names what gh is and what it must be')
+ok(/Nothing was published/.test(msg), 'says nothing was published')
+ok(/cd \/Users\/andy\/devel\/bento && node scripts\/publish-site\.mjs "release v1\.2\.3"/.test(msg), 'gives the exact command from the repo root')
+ok(/gh auth switch --user nyblnet/.test(msg), 'and the switch alternative')
+
+console.log('\npublish-site.mjs — the gate sits before the mirror')
+{
+ const src = readFileSync(new URL('./publish-site.mjs', import.meta.url), 'utf8')
+ const gate = src.indexOf('accountMayRelease(account, owner, allowed)')
+ const mirror = src.indexOf("run('rsync'")
+ const release = src.indexOf("run('gh', ['release', 'create'")
+ ok(gate > 0 && mirror > 0 && gate < mirror, 'the account check runs BEFORE rsync')
+ ok(release > mirror, 'and the release step stays after it (the order the check protects)')
+ ok(/if \(!dry\) \{\n const owner = ownerOfRemote/.test(src), 'a dry run skips the check (nothing is published either way); every real publish runs it')
+ ok(/die\(mismatchMessage\(/.test(src), 'a mismatch dies with the message, not a warning')
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)