diff --git a/.gitignore b/.gitignore index 766c9e9..62be0b1 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,9 @@ apps/site/public/r/ apps/site/dist/ apps/site/.astro/ apps/site/src/paraglide/ + +# the npm publish token: a secret, machine-local, never committed. `scripts/npm-token.sh` +# creates it on demand and `scripts/release.mjs` reads it. Ignored by name rather +# than by a pattern, so an unrelated file can never be swept up by a wildcard. +npm_release.token +npm_release.token.export diff --git a/AGENTS.md b/AGENTS.md index c0b8587..b0b1846 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,10 +83,19 @@ or a disconnected mock is preparatory work, not a finished component. new component, or a release PR updates both. ```bash +bash scripts/npm-token.sh # store the npm publish token (gitignored, mode 600) pnpm release # build + verify, then print what it would publish pnpm release -- --yes # publish core → react → cli, then deploy the registry ``` +Publishing needs a granular npm token with _Read and write_ + _Bypass 2FA_; the account's +2FA is a passkey, which the CLI cannot answer. `scripts/npm-token.sh` collects and +validates it into `npm_release.token`, and `release.mjs` reads that file and passes the +token to npm through the child process's environment — never as an argv flag, which +`ps` and CI logs would expose. The script can confirm the token _authenticates_; nothing +short of a real publish can confirm it may _publish_, so `release.mjs` publishes `core` +first and a permission failure lands before anything is half-released. + Three things about that order are load-bearing: - **The registry is deployed by hand after the publish**, not before. A user who runs diff --git a/CHANGELOG.md b/CHANGELOG.md index f6b9e7f..d6c80ad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ All notable changes to BotUI are recorded here. The format follows - `pnpm i18n` compiles the message catalogs. `apps/site/src/paraglide` is generated and gitignored, so `typecheck` and `verify` now run this first: from a clean clone they used to fail on imports that were not on disk yet. +- **Publishing to npm needed a token, and this account's 2FA is a passkey**, which the CLI cannot answer — WebAuthn needs a browser. `scripts/npm-token.sh` collects a granular access token, validates it against the registry, and stores it in `npm_release.token` (gitignored, mode 600); it re-prompts on its own once the token expires or is revoked. `release.mjs` reads that file and hands the token to npm through the child process's environment rather than an argv flag, because argv is readable through `ps` and command lines land in CI logs. A project `.npmrc` would have applied the token to every npm command in the repo, `npm install` included. ### Fixed diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index d5bca15..44fefa8 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -35,6 +35,11 @@ BotUI 的所有值得注意的变更都记录在此。格式遵循 和 `verify` 现在会先跑这一步:全新 clone 时它们原本会因为引用尚不存在的文件而失败。 - `apps/site/test/playground.test.tsx` 驱动真实控件:10 个测试派发 input 事件并断言场确实变了。 一个渲染出来但不干活的滑杆,在截图和 DOM dump 里和一个正常工作的滑杆无法区分。 +- **发布到 npm 需要一个 token,而这个账号的 2FA 是 passkey**,CLI 无法完成 WebAuthn 挑战(那需要浏览器)。 + `scripts/npm-token.sh` 收集 granular access token、向 registry 校验、并存进 `npm_release.token` + (已 gitignore,权限 600);token 过期或被撤销后它会自行重新询问。`release.mjs` 读取该文件, + 通过子进程的环境变量把 token 交给 npm,而不是作为 argv 参数 —— argv 能被 `ps` 读到,命令行也会进 + CI 日志。项目级 `.npmrc` 同样可行,但那会让 token 对仓库里每一条 npm 命令生效,连 `npm install` 一起。 ### 修复 diff --git a/README.md b/README.md index be3969b..a27bb81 100644 --- a/README.md +++ b/README.md @@ -109,10 +109,24 @@ The generated registry is never committed. A hand-maintained JSON carrying a cop ## Releasing ```bash -pnpm release # build + verify, then print what it would publish -pnpm release -- --yes # publish, in dependency order +bash scripts/npm-token.sh # once: store your npm publish token (gitignored, mode 600) +pnpm release # build + verify, then print what it would publish +pnpm release -- --yes # publish, in dependency order ``` +Publishing needs an npm **granular access token** with _Read and write_ and _Bypass 2FA_ +ticked. Without the bypass flag the token cannot publish at all — a passkey or +authenticator-app 2FA cannot be answered by the CLI, because WebAuthn needs a browser. +Create one at , then run +`scripts/npm-token.sh`: it validates the token against the registry, stores it in +`npm_release.token`, and re-prompts automatically once the token expires or is revoked. +`release.mjs` picks the file up on its own — the token is never a command-line argument, +so it cannot leak into `ps` output or a CI log. + +> Bypass-2FA tokens lose the ability to publish directly in **January 2027**. The durable +> replacement is [OIDC trusted publishing](https://docs.npmjs.com/trusted-publishers), +> where GitHub Actions holds no long-lived npm credential at all. + The registry is what `npx` installs from, so it is deployed _after_ the npm publish — a version on npm whose registry item does not exist yet would install nothing. diff --git a/scripts/npm-token.sh b/scripts/npm-token.sh new file mode 100755 index 0000000..9203020 --- /dev/null +++ b/scripts/npm-token.sh @@ -0,0 +1,312 @@ +#!/usr/bin/env bash +# +# A wizard walks a human through a manual procedure, step by step. +# Generated by the /wizard skill. +# +# Everything above the "STAGES" marker is the wizard library: do not hand-edit +# it. Author the per-step stages below the marker. + +set -euo pipefail + +# ────────────────────────────────────────────────────────────────────────── +# Wizard library: delightful, consistent UX, identical across every wizard. +# ────────────────────────────────────────────────────────────────────────── + +if [[ -t 1 ]] && command -v tput >/dev/null 2>&1 && [[ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]]; then + BOLD=$(tput bold); DIM=$(tput dim); RESET=$(tput sgr0) + BLUE=$(tput setaf 4); GREEN=$(tput setaf 2); YELLOW=$(tput setaf 3); RED=$(tput setaf 1) +else + BOLD=""; DIM=""; RESET=""; BLUE=""; GREEN=""; YELLOW=""; RED="" +fi + +# Author sets this at the top of the stages section. +TOTAL_STAGES=0 + +_STAGE_INDEX=0 +ENV_FILE="${ENV_FILE:-.env}" +WRITTEN_ENV=() # KEYs written to ENV_FILE this run +WRITTEN_SECRET=() # secret NAMEs set this run +SKIPPED=() # things we couldn't do (e.g. gh missing) + +# _clear wipes the terminal so only the current step is on screen. No-op when +# output isn't a terminal, so piped logs stay readable. +_clear() { + [[ -t 1 ]] || return 0 + if command -v tput >/dev/null 2>&1; then tput clear; else printf '\033[2J\033[3J\033[H'; fi +} + +# banner "Title" shows the opening frame: what this wizard does. +banner() { + _clear + printf '\n%s%s %s%s\n' "$BOLD" "$BLUE" "$1" "$RESET" + printf '%s %s stages%s\n\n' "$DIM" "$TOTAL_STAGES" "$RESET" + printf '%s You drive the browser; this wizard tells you exactly what to do and\n' "$DIM" + printf ' captures the values you copy back. Stop any time with Ctrl-C and re-run\n' + printf ' later, since it remembers values already saved.%s\n' "$RESET" + pause "Ready to start?" +} + +# stage "Name" clears the screen, then announces a stage and shows progress. +# Clearing keeps only the current step on screen. +stage() { + _clear + _STAGE_INDEX=$((_STAGE_INDEX + 1)) + printf '\n%s%s▸ Stage %s/%s · %s%s\n' \ + "$BOLD" "$BLUE" "$_STAGE_INDEX" "$TOTAL_STAGES" "$1" "$RESET" +} + +# say "..." prints a plain instruction line. +say() { printf ' %s\n' "$1"; } +# step "..." is a numbered-feeling action the human takes in the browser. +step() { printf ' %s•%s %s\n' "$BLUE" "$RESET" "$1"; } +note() { printf ' %s%s%s\n' "$DIM" "$1" "$RESET"; } +warn() { printf ' %s⚠ %s%s\n' "$YELLOW" "$1" "$RESET"; } + +# open_url URL opens it in the human's browser, cross-platform incl. WSL. +open_url() { + local url="$1" + printf ' %s↗ opening%s %s\n' "$GREEN" "$RESET" "$url" + { if command -v wslview >/dev/null 2>&1; then wslview "$url" + elif command -v explorer.exe >/dev/null 2>&1; then explorer.exe "$url" + elif command -v xdg-open >/dev/null 2>&1; then xdg-open "$url" + elif command -v open >/dev/null 2>&1; then open "$url" + else warn "couldn't open a browser; visit it manually: $url"; fi + } >/dev/null 2>&1 || warn "couldn't open a browser, so visit it manually: $url" +} + +# pause "msg" waits for the human to confirm they've done the manual part. +pause() { + printf ' %s%s%s ' "$DIM" "${1:-Press Enter to continue}" "$RESET" + read -r _ || true +} + +# confirm "question" is a y/N gate; returns success on yes. +confirm() { + local reply="" + printf ' %s? %s [y/N] ' "$YELLOW" "$1" + read -r reply || true + [[ "$reply" =~ ^[Yy] ]] +} + +# _existing KEY: current value of KEY in ENV_FILE, if any. +_existing() { + [[ -f "$ENV_FILE" ]] || return 1 + local line; line=$(grep -E "^${1}=" "$ENV_FILE" | tail -n1) || return 1 + printf '%s' "${line#*=}" +} + +# ask KEY "Prompt" reads a value into $KEY. Offers the existing .env value as +# a default on re-runs (Enter keeps it). Visible input (non-secret). +ask() { + local key="$1" prompt="$2" current input + current=$(_existing "$key" || true) + if [[ -n "$current" ]]; then + printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET" + else + printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET" + fi + read -r input || true + [[ -z "$input" && -n "$current" ]] && input="$current" + printf -v "$key" '%s' "$input" +} + +# ask_secret KEY "Prompt" is like ask, but input is hidden. +ask_secret() { + local key="$1" prompt="$2" current input + current=$(_existing "$key" || true) + if [[ -n "$current" ]]; then + printf ' %s%s%s %s[Enter keeps current]%s ' "$BOLD" "$prompt" "$RESET" "$DIM" "$RESET" + else + printf ' %s%s%s ' "$BOLD" "$prompt" "$RESET" + fi + read -rs input || true + printf '\n' + [[ -z "$input" && -n "$current" ]] && input="$current" + printf -v "$key" '%s' "$input" +} + +# write_env KEY VALUE upserts KEY=VALUE into ENV_FILE (creates it; replaces +# any existing line). Idempotent. +write_env() { + local key="$1" value="$2" tmp + touch "$ENV_FILE" + tmp=$(mktemp) + grep -vE "^${key}=" "$ENV_FILE" > "$tmp" || true + printf '%s=%s\n' "$key" "$value" >> "$tmp" + mv "$tmp" "$ENV_FILE" + WRITTEN_ENV+=("$key") + printf ' %s✓ wrote%s %s → %s\n' "$GREEN" "$RESET" "$key" "$ENV_FILE" +} + +# set_secret NAME VALUE sets a GitHub Actions repo secret via gh. Falls back +# to a warning (and records it) if gh is unavailable or unauthenticated. +set_secret() { + local name="$1" value="$2" + if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then + if printf '%s' "$value" | gh secret set "$name" >/dev/null 2>&1; then + WRITTEN_SECRET+=("$name") + printf ' %s✓ set%s GitHub secret %s\n' "$GREEN" "$RESET" "$name" + return + fi + fi + SKIPPED+=("GitHub secret $name (set it manually: gh secret set $name)") + warn "skipped GitHub secret $name: gh not ready; set it later" +} + +# set_var NAME VALUE sets a GitHub Actions repo variable (non-secret). +set_var() { + local name="$1" value="$2" + if command -v gh >/dev/null 2>&1 && gh auth status >/dev/null 2>&1; then + if gh variable set "$name" --body "$value" >/dev/null 2>&1; then + printf ' %s✓ set%s GitHub variable %s\n' "$GREEN" "$RESET" "$name" + return + fi + fi + SKIPPED+=("GitHub variable $name") + warn "skipped GitHub variable $name, gh not ready; set it later" +} + +# finish clears, then shows a closing summary of everything configured. +finish() { + _clear + printf '\n%s%s ✓ Setup complete%s\n' "$BOLD" "$GREEN" "$RESET" + (( ${#WRITTEN_ENV[@]} )) && note "wrote ${#WRITTEN_ENV[@]} value(s) to $ENV_FILE: ${WRITTEN_ENV[*]}" + (( ${#WRITTEN_SECRET[@]} )) && note "set ${#WRITTEN_SECRET[@]} GitHub secret(s): ${WRITTEN_SECRET[*]}" + if (( ${#SKIPPED[@]} )); then + printf '\n'; warn "still to do by hand:" + for s in "${SKIPPED[@]}"; do note " - $s"; done + fi + printf '\n' +} + + +# ────────────────────────────────────────────────────────────────────────── +# STAGES: author this section. +# ────────────────────────────────────────────────────────────────────────── + +# The wizard's own knobs, overridable from the environment so this script can be +# driven by a test or a future CI job rather than a person at a keyboard. +TOKEN_FILE="${TOKEN_FILE:-npm_release.token}" +EXPECTED_USER="${EXPECTED_USER:-botharness}" +# npm's error text is how a rejected token is told from a missing one, and the +# difference decides whether we prompt or warn. Both spellings below were observed +# against registry.npmjs.org: +# rejected → E401 / 401 Unauthorized +# no creds → "need auth This command requires you to be logged in" +# The network cases are here so an offline machine asks for a token instead of +# silently rejecting a perfectly good saved one. +REJECTED_PATTERN='401|E401|Unauthorized|ENEEDAUTH|ENOTFOUND|ETIMEDOUT|ENETUNREACH|EAI_AGAIN' + +# token_is_valid TOKEN — succeed only if the registry accepts this token AND it +# belongs to the account we publish as. Checking the user matters: a valid token +# for someone else would sail past a bare `npm whoami` and publish as them. +token_is_valid() { + local candidate="$1" whoami_out + whoami_out=$(npm whoami --//registry.npmjs.org/:_authToken="$candidate" 2>&1) || true + printf '%s' "$whoami_out" | grep -qE "$REJECTED_PATTERN" && return 1 + # `npm whoami` is the one call that actually discriminates: a fake token gets + # E401 and a real one gets the username. Nothing here can prove the token may + # PUBLISH, and the obvious candidates cannot be trusted to — `npm access` and + # `npm profile` are unknown subcommands that exit 0, so they "succeed" for a + # token that is pure fiction. Only whoami's output was verified to differ. + [[ "$whoami_out" == "$EXPECTED_USER" ]] +} + +read_token() { + [[ -f "$TOKEN_FILE" ]] || return 1 + # trailing whitespace/newlines are easy to paste in and silently break the header + tr -d '[:space:]' < "$TOKEN_FILE" +} + +store_token() { + local value="$1" dir tmp + dir=$(dirname "$TOKEN_FILE") + mkdir -p "$dir" + tmp=$(mktemp "${dir}/.npmtok.XXXXXX") + # written via a temp file in the same directory so the secret is never briefly + # world-readable, then moved into place; umask covers the window before chmod + ( umask 077; printf '%s\n' "$value" > "$tmp" ) + chmod 600 "$tmp" + mv "$tmp" "$TOKEN_FILE" + printf ' %s✓ saved%s %s (mode 600)\n' "$GREEN" "$RESET" "$TOKEN_FILE" +} + +TOTAL_STAGES=2 + +banner "npm release token" + +# ── Stage 1: reuse a saved token, or ask for one ─────────────────────────── +stage "The publish token" +say "Releasing to npm needs a token with write access, because this account's 2FA" +say "is a passkey and the CLI cannot answer a WebAuthn challenge." +note "A saved token is reused automatically; you are only asked when there isn't" +note "a usable one. Ctrl-C at any time — nothing is lost but this run." + +SAVED="" +if [[ -f "$TOKEN_FILE" ]]; then + note "found $TOKEN_FILE" + CANDIDATE=$(read_token || true) + if [[ -n "$CANDIDATE" ]] && token_is_valid "$CANDIDATE"; then + say "That token still works as $EXPECTED_USER." + SAVED="$CANDIDATE" + else + warn "the saved token was rejected — expired, revoked, or from another account." + note "npm tokens can be listed at https://www.npmjs.com/settings/access-tokens" + fi +else + note "no $TOKEN_FILE yet" +fi + +if [[ -z "$SAVED" ]]; then + say "" + say "If you don't have one yet, create it here:" + open_url "https://www.npmjs.com/settings/access-tokens/new" + step "Packages: scope @botharness (or the three package names, one per row)" + step "Permissions: Read and write" + step "Tick 'Bypass 2FA' — without it the token cannot publish, and npm says so" + step "Set the shortest expiry you can live with; bypass tokens lose direct" + step " publishing in January 2027, so plan to move to OIDC trusted publishing" + step "Generate token, then copy it (it is shown only once)" + say "" + ask_secret TOKEN "Paste the token (input hidden):" + say "" + if [[ -z "$TOKEN" ]]; then + say "Nothing pasted. Re-run this script when you have one:" >&2 + note " bash scripts/npm-token.sh" >&2 + exit 1 + fi + if ! token_is_valid "$TOKEN"; then + warn "npm rejected that token." + say "Usual causes, in the order worth checking:" >&2 + note " - 'Bypass 2FA' was left unticked (the default is OFF)" >&2 + note " - the token was copied with a trailing space or newline" >&2 + note " - it belongs to a different npm account than $EXPECTED_USER" >&2 + note " - it has already expired" >&2 + exit 1 + fi + store_token "$TOKEN" + SAVED="$TOKEN" +fi + +# ── Stage 2: report what we know, and what we cannot know ───────────────── +stage "Ready to publish" +printf ' %s✓%s token accepted by the registry as %s\n' "$GREEN" "$RESET" "$EXPECTED_USER" +say "" +say "What this script could NOT check, so you are not misled:" +note " Whether the token can publish. The registry has no such endpoint, and the" +note " commands that look like they would answer it (npm access, npm profile)" +note " are unknown commands that exit 0 — a fake token passes them. Only a real" +note " publish proves it, which is why the release publishes core first: a" +note " permission failure lands on the first package, before anything is" +note " half-released." +note "" +warn "If 'Bypass 2FA' was unticked, the publish fails with a 403. Re-create the" +warn "token with it ticked if that happens." +say "" +say "Publish with it:" +printf ' %spnpm release -- --yes%s\n' "$BOLD" "$RESET" +note "scripts/release.mjs reads $TOKEN_FILE on its own — no env var, no flag." +note "The token is never printed, never passed on a command line (so it cannot" +note "leak into ps or a CI log), and never written outside $TOKEN_FILE." + +finish diff --git a/scripts/release.mjs b/scripts/release.mjs index 0b365f1..3fe0a5b 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -21,6 +21,21 @@ const tag = process.argv.includes("--tag") ? process.argv[process.argv.indexOf("--tag") + 1] : undefined; +// The token goes into the environment of the publish processes only. It is not +// attached to the build/verify calls above: those need no credentials, and there +// is no reason for a secret to exist in a process that isn't publishing. +let publishEnv = process.env; +const token = readToken(); +if (token && yes) { + publishEnv = { + ...process.env, + // npm/pnpm both read npm config from the environment, so this is the seam that + // needs no .npmrc. The key is the registry URL, verbatim — npm's config keys + // are case-sensitive and this one is not a normal identifier. + "npm_config_//registry.npmjs.org/:_authToken": token, + }; +} + // dependency order, and the reason for it const ORDER = [ { @@ -32,8 +47,37 @@ const ORDER = [ { dir: "packages/cli", name: "@botharness/botui", why: "the installer; depends on nothing" }, ]; -const pnpm = (args, cwd) => - execFileSync("pnpm", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] }); +const pnpm = (args, cwd, env) => + execFileSync("pnpm", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], env }); + +/** + * The publish token, if this machine has one. + * + * This account's 2FA is a passkey, which the CLI cannot answer — WebAuthn needs a + * browser — so publishing has to go through a granular access token with "Bypass + * 2FA" ticked. `scripts/npm-token.sh` collects one and writes it to + * `npm_release.token` (gitignored, mode 600). + * + * It reaches npm as `npm_config_//registry.npmjs.org/:_authToken` in the child + * process's environment, verified against the registry: the real token answers + * `npm whoami` and a fake one gets E401. An argument would have been simpler but + * argv is world-readable through `ps` and command lines land in CI logs. The + * project `.npmrc` route was rejected on purpose — this repo has none on + * purpose, and adding one would apply the token to every npm command run here, + * `npm install` included, which is a wider blast radius than a release needs. + * + * Absent is not an error here: `npm publish` then reports precisely why, which + * is a better message than this script could invent, and a dry run needs no token. + */ +function readToken() { + const file = process.env.NPM_TOKEN_FILE ?? join(root, "npm_release.token"); + try { + const token = readFileSync(file, "utf8").trim(); + return token || undefined; + } catch { + return undefined; + } +} // the registry is what a user installs, so it has to be current BEFORE anything goes // to npm — otherwise `npx @botharness/botui` resolves a version whose registry item @@ -53,7 +97,7 @@ for (const pkg of ORDER) { } const args = ["--filter", pkg.name, "publish", "--access", "public", "--no-git-checks"]; if (tag) args.push("--tag", tag); - process.stdout.write(pnpm(args, root)); + process.stdout.write(pnpm(args, root, publishEnv)); } process.stdout.write(