@monte3l/groundwork 1.0.0-rc.6 → 1.0.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monte3l/groundwork",
3
- "version": "1.0.0-rc.6",
3
+ "version": "1.0.0-rc.8",
4
4
  "description": "CLI that writes a TypeScript toolchain and Claude Code setup into an empty directory, or -- against an existing project -- read-only surveys it and reports the differences. No prompts, and no network access beyond the package install.",
5
5
  "keywords": [
6
6
  "typescript",
@@ -74,7 +74,7 @@ export const TYPESCRIPT_DOMAIN_GLOBS = [
74
74
  "bin/lib/*.json",
75
75
  ".github/workflows/*.yml",
76
76
  ".github/dependabot.yml",
77
- ".github/release-tools/**",
77
+ "tools/release/**",
78
78
  ".changeset/**",
79
79
  ".gitleaks.toml",
80
80
  "REUSE.toml",
@@ -29,7 +29,7 @@ name: Release
29
29
  # pnpm shim below, with `--ignore-scripts`. `pack` holds nothing beyond
30
30
  # `contents: read`.
31
31
  #
32
- # "Staged" publish (vs. a "direct" one) means `npm stage publish` uploads the
32
+ # "Staged" publish (vs. a "direct" one) means a staged publish uploads the
33
33
  # tarball and creates the version, but it isn't installable yet until a
34
34
  # maintainer separately approves it with 2FA (`npm stage approve`) -- npm's
35
35
  # own stronger default over a direct `npm publish`, which would make the
@@ -162,7 +162,7 @@ jobs:
162
162
  needs: pack
163
163
  runs-on: ubuntu-latest
164
164
  timeout-minutes: 15
165
- # Gates the git tag, the GitHub Release, and `npm stage publish` behind a
165
+ # Gates the git tag, the GitHub Release, and the staged publish behind a
166
166
  # required reviewer -- without this, all three already exist by the time
167
167
  # a maintainer even sees there's a staged version to approve with
168
168
  # `npm stage approve`. The environment (created once, by hand, via
@@ -185,25 +185,22 @@ jobs:
185
185
  package-manager-cache: false
186
186
  # Only the changesets CLI is needed here, not any package's lifecycle scripts.
187
187
  - run: pnpm install --frozen-lockfile --ignore-scripts
188
- # `npm stage publish` needs npm >= 11.15.0. The pinned npm (12.2.0)
189
- # declares engines Node ^22.22.2 || ^24.15.0 || >=26. .node-version's
190
- # `24` meets that on GitHub-hosted runners, whose cached 24.x is recent;
191
- # a self-hosted runner with an older cached 24.x does not. Pinned to an
192
- # exact version, not a range or `latest`: this job holds the OIDC token,
193
- # and an unpinned package-manager install is exactly what OpenSSF
194
- # Scorecard's Pinned-Dependencies check flags. `.github/release-tools/`
195
- # pins the exact tarball via its committed lockfile's integrity hash, and
196
- # `npm ci` verifies the install against it -- bumping the pin is then
197
- # a normal reviewed PR (a lockfile diff), not a hand-edited version
198
- # string.
199
- - run: npm ci --ignore-scripts --prefix .github/release-tools
200
- - run: echo "$GITHUB_WORKSPACE/.github/release-tools/node_modules/.bin" >> "$GITHUB_PATH"
188
+ # Staged publishing goes through libnpmpublish (npm's own publish
189
+ # library, bin/npm-stage-publish.mjs), not the npm CLI: the CLI bundles
190
+ # its own dependencies, which no override can patch. Pinned to exact
191
+ # versions, not a range or `latest`: this job holds the OIDC token, and
192
+ # an unpinned package install is exactly what OpenSSF Scorecard's
193
+ # Pinned-Dependencies check flags. `tools/release/` pins every tarball
194
+ # via its committed lockfile's integrity hash, and `npm ci` verifies the
195
+ # install against it -- bumping the pin is then a normal reviewed PR (a
196
+ # lockfile diff), not a hand-edited version string.
197
+ - run: npm ci --ignore-scripts --prefix tools/release
201
198
  # changesets publishes through `pnpm publish` in a pnpm-managed
202
199
  # project. This puts a `pnpm` ahead of the real one that forwards
203
- # everything except `publish`, which goes to `npm stage publish`
200
+ # everything except `publish`, which goes to a staged publish
204
201
  # instead (see bin/pnpm-publish-shim.mjs -- the trusted publisher only
205
202
  # allows staged publishing, npm's own default since 2026-09-03).
206
- - name: Route publish through the npm CLI
203
+ - name: Route publish through the staged publisher
207
204
  run: |
208
205
  shim_dir="$RUNNER_TEMP/pnpm-shim"
209
206
  mkdir -p "$shim_dir"
@@ -213,8 +210,28 @@ jobs:
213
210
  echo "$shim_dir" >> "$GITHUB_PATH"
214
211
  - uses: changesets/action/publish@ae32849d5ba541f9ae29e40e22a623bc13562f51 # v2
215
212
  id: publish
213
+ env:
214
+ RELEASE_TOOLS_DIR: ${{ github.workspace }}/tools/release
215
+ STAGED_IDS_FILE: ${{ runner.temp }}/staged-ids.txt
216
216
  with:
217
217
  pack-dir-artifact-id: ${{ needs.pack.outputs.pack-dir-artifact-id }}
218
+ # changesets swallows the publisher's stdout, so the stage id to approve
219
+ # would never reach this log. The publisher records it in a file; print
220
+ # it here, plus an annotation on the run page, whether or not an earlier
221
+ # step failed. `npm stage approve <id>` (2FA) is still a maintainer step.
222
+ - name: Show the staged ids to approve
223
+ if: always()
224
+ env:
225
+ STAGED_IDS_FILE: ${{ runner.temp }}/staged-ids.txt
226
+ run: |
227
+ if [ -s "$STAGED_IDS_FILE" ]; then
228
+ while read -r id stage; do
229
+ echo "staged $id with id $stage -- approve with: npm stage approve $stage"
230
+ echo "::notice title=Staged $id::npm stage approve $stage"
231
+ done < "$STAGED_IDS_FILE"
232
+ else
233
+ echo "no staged version was recorded by this run"
234
+ fi
218
235
  # npm provenance alone already meets most supply-chain "signed
219
236
  # releases" criteria (a Sigstore-backed, OIDC-issued attestation with
220
237
  # no long-lived key). These three steps add a second, independent
@@ -223,12 +240,12 @@ jobs:
223
240
  # rebuilt), attested, and attached. `if:` guards all three on
224
241
  # `publish` actually having published -- `select-mode` only decides
225
242
  # the job should run, not that a version was new.
226
- # `continue-on-error: true` on all three: `npm stage publish` has
243
+ # `continue-on-error: true` on all three: the staged publish has
227
244
  # already succeeded by this point, so a failure here (a transient
228
245
  # download error, say) must never fail the whole job and leave a
229
246
  # staged, tagged, unreleased version behind -- this block is
230
- # best-effort supplementary evidence, the same status as the
231
- # "List pending stages" step below.
247
+ # best-effort supplementary evidence. (The stage id to approve is
248
+ # printed, and added to the job summary, by the publish step itself.)
232
249
  - name: Fetch the packed tarball back out of the pack job's artifact
233
250
  if: steps.publish.outputs.published == 'true'
234
251
  continue-on-error: true
@@ -280,13 +297,3 @@ jobs:
280
297
  fi
281
298
  gh release upload "$tag" \
282
299
  "$tarball" --clobber --repo "${{ github.repository }}"
283
- # Staging succeeds unattended; going live needs a maintainer's 2FA
284
- # (`npm stage approve <id>`, on the CLI or npmjs.com -- never
285
- # automatable, by design). Best-effort convenience only: this job
286
- # never logs in with a token (it publishes purely via the OIDC
287
- # exchange scoped to the publish call itself), so `npm stage list` may
288
- # print nothing useful -- `|| true` means that possibility never fails
289
- # the job.
290
- - name: List pending stages (best effort)
291
- if: always()
292
- run: npm stage list --package "$(node -p "require('./package.json').name")" || true
@@ -3,8 +3,8 @@
3
3
  // SPDX-License-Identifier: NOASSERTION
4
4
 
5
5
  /**
6
- * Translates the one `pnpm publish` invocation changesets makes for a packed
7
- * tarball into the equivalent `npm stage publish`, for `pnpm-publish-shim.mjs`.
6
+ * Parses the one `pnpm publish` invocation changesets makes for a packed
7
+ * tarball, for `pnpm-publish-shim.mjs` and `npm-stage-publish.mjs`.
8
8
  *
9
9
  * Changesets runs (see its `lib/pnpm.ts`):
10
10
  * pnpm publish <tarball> [--json] --access <a> --tag <t> --no-git-checks [--otp <c>]
@@ -13,25 +13,24 @@
13
13
  * is refused rather than guessed at: if changesets ever starts passing a flag
14
14
  * this does not understand, publishing must stop, not silently do something else.
15
15
  *
16
- * Staged, not direct: a trusted publisher created since 2026-09-03 defaults to
17
- * `npm stage publish` only, npm's own default (and explicit recommendation) --
18
- * a maintainer must separately run `npm stage approve <id>` (2FA, never
19
- * automatable) before a staged version actually goes live. `npm stage publish`
20
- * accepts the same `--access`/`--tag`/`--otp`/`--provenance` flags as
21
- * `npm publish` ("parity with npm publish" per npm's own CLI reference); the
22
- * command itself is `npm stage publish`, not a flag on `npm publish`.
16
+ * Staged, not direct: a trusted publisher created since 2026-09-03 only allows a
17
+ * staged publish -- a maintainer must separately run `npm stage approve <id>`
18
+ * (2FA, never automatable) before a staged version actually goes live.
23
19
  */
24
20
 
25
21
  const DROPPED = new Set(["--json", "--no-git-checks"]);
26
22
  const WITH_VALUE = new Set(["--access", "--tag", "--otp"]);
27
23
 
28
24
  /**
25
+ * Splits the arguments after `pnpm publish` into the tarball and the
26
+ * `[flag, value]` pairs changesets passes, refusing anything else.
27
+ *
29
28
  * @param {string[]} args the arguments following `pnpm publish`
30
- * @returns {string[]} the argument vector for `npm stage publish`
29
+ * @returns {{ tarball: string, pairs: [string, string][] }}
31
30
  */
32
- export function toNpmStagePublishArgs(args) {
31
+ function scanPublishArgs(args) {
33
32
  let tarball;
34
- const flags = [];
33
+ const pairs = [];
35
34
 
36
35
  for (let i = 0; i < args.length; i += 1) {
37
36
  const arg = args[i];
@@ -42,7 +41,7 @@ export function toNpmStagePublishArgs(args) {
42
41
  if (value === undefined || value.startsWith("--")) {
43
42
  throw new Error(`${arg} needs a value`);
44
43
  }
45
- flags.push(arg, value);
44
+ pairs.push([arg, value]);
46
45
  i += 1;
47
46
  continue;
48
47
  }
@@ -61,12 +60,21 @@ export function toNpmStagePublishArgs(args) {
61
60
  "no tarball given: this shim only publishes packed tarballs (changesets' --from-pack-dir mode)",
62
61
  );
63
62
  }
63
+ return { tarball, pairs };
64
+ }
64
65
 
65
- // Provenance is requested explicitly rather than relied on: npm's automatic
66
- // attestation for trusted publishing has been reported not to engage without it.
67
- // "stage", "publish" are two separate words (the npm-stage subcommand), not
68
- // "stage-publish" or a flag -- see npm's own CLI reference for npm-stage.
69
- return ["stage", "publish", tarball, ...flags, "--provenance"];
66
+ /**
67
+ * Parses the one `pnpm publish` invocation changesets makes, as named values
68
+ * for `npm-stage-publish.mjs` (which calls libnpmpublish instead of the npm CLI).
69
+ *
70
+ * @param {string[]} args the arguments following `pnpm publish`
71
+ * @returns {{ tarball: string, access?: string, tag?: string, otp?: string }}
72
+ */
73
+ export function parsePublishArgs(args) {
74
+ const { tarball, pairs } = scanPublishArgs(args);
75
+ const out = { tarball };
76
+ for (const [flag, value] of pairs) out[flag.slice(2)] = value;
77
+ return out;
70
78
  }
71
79
 
72
80
  /**
@@ -0,0 +1,114 @@
1
+ // SPDX-FileCopyrightText: Copyright the __PROJECT_NAME__ contributors
2
+ // SPDX-License-Identifier: NOASSERTION
3
+
4
+ /**
5
+ * Reads `package/package.json` out of an npm tarball using Node built-ins only,
6
+ * for `npm-stage-publish.mjs`. A tarball reader library (pacote, tar) would drag
7
+ * node-gyp and an HTTP client into the pinned release-tools tree, which is the
8
+ * exact surface this repo moved away from the npm CLI to shrink.
9
+ *
10
+ * Handles what `pnpm pack`/`npm pack` emit: a gzipped ustar archive whose
11
+ * entries live under a top-level directory. It never throws on malformed
12
+ * input other than through the documented `Error`s below.
13
+ */
14
+ import { gunzipSync } from "node:zlib";
15
+
16
+ const BLOCK = 512;
17
+
18
+ /** NUL-terminated ASCII field of a ustar header. */
19
+ function field(buf, start, length) {
20
+ const end = buf.indexOf(0, start);
21
+ const stop = end === -1 || end > start + length ? start + length : end;
22
+ return buf.toString("utf8", start, stop);
23
+ }
24
+
25
+ /**
26
+ * @param {Buffer} tgz
27
+ * @returns {Buffer} the decompressed archive
28
+ */
29
+ function gunzip(tgz) {
30
+ try {
31
+ return gunzipSync(tgz);
32
+ } catch (error) {
33
+ throw new Error(
34
+ `tarball is not valid gzip: ${error instanceof Error ? error.message : String(error)}`,
35
+ { cause: error },
36
+ );
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Walks the archive and returns the body of the first regular file whose
42
+ * path (under its top-level directory) satisfies `wanted`.
43
+ *
44
+ * @param {Buffer} tar
45
+ * @param {(relativeName: string) => boolean} wanted
46
+ * @returns {{ name: string, body: Buffer } | undefined}
47
+ */
48
+ function findEntry(tar, wanted) {
49
+ let offset = 0;
50
+ while (offset + BLOCK <= tar.length) {
51
+ const name = field(tar, offset, 100);
52
+ if (name === "") break; // end-of-archive padding
53
+ const size = parseInt(field(tar, offset + 124, 12).trim(), 8);
54
+ if (!Number.isSafeInteger(size) || size < 0) {
55
+ throw new Error(`corrupt tar header for ${name}: bad size`);
56
+ }
57
+ const prefix = field(tar, offset + 345, 155);
58
+ const type = String.fromCharCode(tar[offset + 156] ?? 0);
59
+ const body = offset + BLOCK;
60
+ const fullName = prefix === "" ? name : `${prefix}/${name}`;
61
+ const match = /^[^/]+\/([^/]+)$/.exec(fullName);
62
+ if (
63
+ (type === "0" || type === "\0") &&
64
+ match?.[1] !== undefined &&
65
+ wanted(match[1])
66
+ ) {
67
+ if (body + size > tar.length) {
68
+ throw new Error(`corrupt tarball: ${match[1]} is truncated`);
69
+ }
70
+ return { name: match[1], body: tar.subarray(body, body + size) };
71
+ }
72
+ offset = body + Math.ceil(size / BLOCK) * BLOCK;
73
+ }
74
+ return undefined;
75
+ }
76
+
77
+ /**
78
+ * @param {Buffer} tgz the gzipped tarball
79
+ * @returns {object} the parsed manifest
80
+ * @throws {Error} when the input is not a gzip, has no package.json, or the
81
+ * manifest is not valid JSON
82
+ */
83
+ export function readTarballManifest(tgz) {
84
+ const entry = findEntry(gunzip(tgz), (n) => n === "package.json");
85
+ if (entry === undefined)
86
+ throw new Error("tarball has no package/package.json");
87
+ try {
88
+ return JSON.parse(entry.body.toString("utf8"));
89
+ } catch (error) {
90
+ throw new Error(
91
+ `package.json in the tarball is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,
92
+ { cause: error },
93
+ );
94
+ }
95
+ }
96
+
97
+ /**
98
+ * The README the registry shows for a version. npm's own publish reads it
99
+ * from the tarball and adds it to the version metadata; libnpmpublish does
100
+ * not, so without this the published page has no README.
101
+ *
102
+ * @param {Buffer} tgz the gzipped tarball
103
+ * @returns {{ filename: string, content: string } | undefined} undefined when
104
+ * the tarball ships no README
105
+ */
106
+ export function readTarballReadme(tgz) {
107
+ const tar = gunzip(tgz);
108
+ const entry =
109
+ findEntry(tar, (n) => /^readme\.md$/i.test(n)) ??
110
+ findEntry(tar, (n) => /^readme(\.[^/]+)?$/i.test(n));
111
+ return entry === undefined
112
+ ? undefined
113
+ : { filename: entry.name, content: entry.body.toString("utf8") };
114
+ }
@@ -0,0 +1,228 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-FileCopyrightText: Copyright the __PROJECT_NAME__ contributors
3
+ // SPDX-License-Identifier: NOASSERTION
4
+
5
+ /**
6
+ * Stages a packed tarball on npm through trusted publishing (GitHub OIDC), for
7
+ * `pnpm-publish-shim.mjs`. Replaces `npm stage publish`.
8
+ *
9
+ * ## Why not the npm CLI
10
+ *
11
+ * The npm CLI bundles its own dependencies (undici, ip-address,
12
+ * brace-expansion, ...) inside its tarball, where neither `overrides` nor
13
+ * `npm audit fix` can reach them, so an advisory against one stays open until
14
+ * npm itself re-releases. npm's own publish library, `libnpmpublish`, is an
15
+ * ordinary dependency tree that audit tooling can fix, so the release job
16
+ * uses it instead of the CLI.
17
+ *
18
+ * ## What it does
19
+ *
20
+ * 1. Gets a GitHub OIDC id token for `npm:<registry host>`.
21
+ * 2. Exchanges it at `/-/npm/v1/oidc/token/exchange/package/<name>` for a
22
+ * short-lived npm token scoped to this package (ported from npm's
23
+ * `lib/utils/oidc.js`).
24
+ * 3. Calls `libnpmpublish.publish(..., { stage: true, provenance: true })`.
25
+ *
26
+ * Unlike the npm CLI, whose OIDC step silently falls back to "no auth" on any
27
+ * failure, every failure here exits non-zero with the reason. Tokens are never
28
+ * printed.
29
+ *
30
+ * ## Inputs
31
+ *
32
+ * `RELEASE_TOOLS_DIR` names the directory holding the `npm ci`-installed
33
+ * libnpmpublish and npm-registry-fetch (the release-tools lockfile).
34
+ * `STAGED_IDS_FILE`, when set, receives one `<name>@<version> <stage id>` line per
35
+ * staged version, because the caller (changesets) swallows this script's stdout.
36
+ * `NPM_CONFIG_REGISTRY` overrides the registry (as in npm; the tests point it at a
37
+ * local server; default npmjs.org).
38
+ */
39
+ import process from "node:process";
40
+ import { readFileSync, appendFileSync } from "node:fs";
41
+ import { createRequire } from "node:module";
42
+ import { join } from "node:path";
43
+ import { parsePublishArgs } from "./lib/npm-publish-args.mjs";
44
+ import {
45
+ readTarballManifest,
46
+ readTarballReadme,
47
+ } from "./lib/read-tarball-manifest.mjs";
48
+
49
+ /**
50
+ * @param {string} message
51
+ * @returns {never}
52
+ */
53
+ function fail(message) {
54
+ console.error(`npm-stage-publish: ${message}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ /**
59
+ * @param {Record<string, string | undefined>} env
60
+ * @param {string} registry
61
+ * @returns {Promise<string>} the GitHub OIDC id token
62
+ */
63
+ async function githubIdToken(env, registry) {
64
+ if (env.NPM_ID_TOKEN) return env.NPM_ID_TOKEN;
65
+ const requestUrl = env.ACTIONS_ID_TOKEN_REQUEST_URL;
66
+ const requestToken = env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
67
+ if (!requestUrl || !requestToken) {
68
+ fail(
69
+ "no GitHub OIDC token available: the job needs `permissions: id-token: write`",
70
+ );
71
+ }
72
+ let json;
73
+ try {
74
+ const url = new URL(requestUrl);
75
+ url.searchParams.append("audience", `npm:${new URL(registry).hostname}`);
76
+ const response = await fetch(url, {
77
+ headers: {
78
+ Accept: "application/json",
79
+ Authorization: `Bearer ${requestToken}`,
80
+ },
81
+ });
82
+ if (!response.ok) {
83
+ fail(`GitHub refused the OIDC token request (HTTP ${response.status})`);
84
+ }
85
+ json = await response.json();
86
+ } catch (error) {
87
+ fail(
88
+ `GitHub OIDC token request failed: ${error instanceof Error ? error.message : String(error)}`,
89
+ );
90
+ }
91
+ if (typeof json?.value !== "string" || json.value === "") {
92
+ fail("GitHub's OIDC response carried no token");
93
+ }
94
+ return json.value;
95
+ }
96
+
97
+ const args = process.argv.slice(2);
98
+ let parsed;
99
+ try {
100
+ parsed = parsePublishArgs(args);
101
+ } catch (error) {
102
+ fail(error instanceof Error ? error.message : String(error));
103
+ }
104
+
105
+ const toolsDir = process.env.RELEASE_TOOLS_DIR;
106
+ if (!toolsDir) fail("RELEASE_TOOLS_DIR is not set");
107
+ const requireTools = createRequire(join(toolsDir, "package.json"));
108
+ let publish;
109
+ let npmFetch;
110
+ try {
111
+ ({ publish } = requireTools("libnpmpublish"));
112
+ npmFetch = requireTools("npm-registry-fetch");
113
+ } catch (error) {
114
+ fail(
115
+ `cannot load libnpmpublish from ${toolsDir} (run npm ci --ignore-scripts --prefix there first): ${error instanceof Error ? error.message : String(error)}`,
116
+ );
117
+ }
118
+
119
+ const registry =
120
+ process.env.NPM_CONFIG_REGISTRY ?? "https://registry.npmjs.org/";
121
+ const registryUrl = new URL(registry);
122
+ const authKey = `//${registryUrl.host}${registryUrl.pathname}:_authToken`;
123
+
124
+ let manifest;
125
+ let tarball;
126
+ try {
127
+ tarball = readFileSync(parsed.tarball);
128
+ manifest = readTarballManifest(tarball);
129
+ // npm's own publish adds the README to the version metadata; libnpmpublish
130
+ // does not, so do it here or the package page shows none.
131
+ const readme = readTarballReadme(tarball);
132
+ if (readme !== undefined && manifest.readme === undefined) {
133
+ manifest.readme = readme.content;
134
+ manifest.readmeFilename = readme.filename;
135
+ }
136
+ } catch (error) {
137
+ fail(
138
+ `cannot read ${parsed.tarball}: ${error instanceof Error ? error.message : String(error)}`,
139
+ );
140
+ }
141
+ if (
142
+ typeof manifest?.name !== "string" ||
143
+ typeof manifest?.version !== "string"
144
+ ) {
145
+ fail(`${parsed.tarball}: package.json has no name and version`);
146
+ }
147
+
148
+ // npm refuses a prerelease published without an explicit dist-tag, because it
149
+ // would otherwise land on `latest`. Refuse here too, before any token is used.
150
+ if (/^\d+\.\d+\.\d+-/.test(manifest.version) && parsed.tag === undefined) {
151
+ fail(
152
+ `${manifest.name}@${manifest.version} is a prerelease: pass --tag so it does not land on latest`,
153
+ );
154
+ }
155
+
156
+ const idToken = await githubIdToken(process.env, registry);
157
+
158
+ let npmToken;
159
+ try {
160
+ const exchange = await npmFetch.json(
161
+ new URL(
162
+ `/-/npm/v1/oidc/token/exchange/package/${manifest.name.replace(/\//g, "%2f")}`,
163
+ registry,
164
+ ),
165
+ { registry, method: "POST", [authKey]: idToken },
166
+ );
167
+ npmToken = exchange?.token;
168
+ } catch (error) {
169
+ fail(
170
+ `npm refused the OIDC token exchange for ${manifest.name} (check the trusted publisher config): ${error?.body?.message ?? (error?.statusCode ? `HTTP ${error.statusCode}` : undefined) ?? (error instanceof Error ? error.message : String(error))}`,
171
+ );
172
+ }
173
+ if (typeof npmToken !== "string" || npmToken === "") {
174
+ fail("npm's token exchange response carried no token");
175
+ }
176
+
177
+ let result;
178
+ try {
179
+ result = await publish(manifest, tarball, {
180
+ registry,
181
+ [authKey]: npmToken,
182
+ stage: true,
183
+ provenance: true,
184
+ // publishConfig in the manifest is not merged as npm does: changesets
185
+ // passes --access/--tag explicitly and provenance is always on.
186
+ access: parsed.access ?? null,
187
+ defaultTag: parsed.tag ?? "latest",
188
+ ...(parsed.otp === undefined ? {} : { otp: parsed.otp }),
189
+ });
190
+ } catch (error) {
191
+ fail(
192
+ `staging ${manifest.name}@${manifest.version} failed (the registry may still hold a staged version -- run npm stage list before re-running): ${error instanceof Error ? error.message : String(error)}`,
193
+ );
194
+ }
195
+
196
+ const stageId = result?.stageId;
197
+ if (typeof stageId !== "string" || stageId === "") {
198
+ fail(`staging ${manifest.name}@${manifest.version} returned no stage id`);
199
+ }
200
+ const id = `${manifest.name}@${manifest.version}`;
201
+ console.log(`+ ${id} (staged with id ${stageId})`);
202
+ console.log(`approve with: npm stage approve ${stageId}`);
203
+ if (process.env.GITHUB_STEP_SUMMARY) {
204
+ // Best effort: the version is already staged, so a summary write failure
205
+ // must not turn this run red and leave changesets without its tag.
206
+ try {
207
+ appendFileSync(
208
+ process.env.GITHUB_STEP_SUMMARY,
209
+ `### Staged ${id}\n\nApprove with 2FA: \`npm stage approve ${stageId}\`\n`,
210
+ );
211
+ } catch (error) {
212
+ console.error(
213
+ `npm-stage-publish: staged ${id} (${stageId}) but could not write the step summary: ${error instanceof Error ? error.message : String(error)}`,
214
+ );
215
+ }
216
+ }
217
+ if (process.env.STAGED_IDS_FILE) {
218
+ // changesets captures this process's stdout, so nothing printed above reaches
219
+ // the job log. Leave the id in a file the workflow prints in a later step.
220
+ // Best effort, like the summary: the version is already staged.
221
+ try {
222
+ appendFileSync(process.env.STAGED_IDS_FILE, `${id} ${stageId}\n`);
223
+ } catch (error) {
224
+ console.error(
225
+ `npm-stage-publish: staged ${id} (${stageId}) but could not record it in ${process.env.STAGED_IDS_FILE}: ${error instanceof Error ? error.message : String(error)}`,
226
+ );
227
+ }
228
+ }
@@ -5,14 +5,17 @@
5
5
  /**
6
6
  * Put ahead of the real `pnpm` on PATH by the release workflow's `publish`
7
7
  * job. Everything passes straight through to pnpm except `publish`, which
8
- * this rewrites into `npm stage publish` instead.
8
+ * this rewrites into a staged publish (`npm-stage-publish.mjs`, libnpmpublish) instead.
9
9
  *
10
10
  * ## Why it exists
11
11
  *
12
- * `changeset publish` in a pnpm-managed project publishes through
13
- * `pnpm publish`. A trusted publisher created since 2026-09-03 defaults to
14
- * `npm stage publish` only, npm's own explicit recommendation (see this
15
- * pack's adoptNotes), so the publish is rerouted to `npm stage publish`.
12
+ * `changeset publish` in a pnpm workspace publishes through `pnpm publish`.
13
+ * This shim reroutes that call to a staged publish through libnpmpublish
14
+ * (not the npm CLI, whose bundled dependencies carry unfixable advisories --
15
+ * see `npm-stage-publish.mjs`), because
16
+ * the trusted publisher only allows staged publishing
17
+ * (npm's default for any trusted publisher created since 2026-09-03 -- see
18
+ * this pack's adoptNotes).
16
19
  *
17
20
  * ## What it translates
18
21
  *
@@ -22,23 +25,26 @@
22
25
  * everything else it does around it -- the publish plan, ordering, git tags,
23
26
  * GitHub Releases -- instead of reimplementing any of that. A consequence
24
27
  * worth knowing: those git tags and Releases are created the moment
25
- * `npm stage publish` succeeds, which is *before* the package is actually
28
+ * the staged publish succeeds, which is *before* the package is actually
26
29
  * live -- staging still needs a maintainer to run `npm stage approve <id>`
27
30
  * (2FA, never automatable).
28
31
  *
29
32
  * ## What it refuses
30
33
  *
31
- * `toNpmStagePublishArgs` (see `./lib/npm-publish-args.mjs`) accepts only the
34
+ * `parsePublishArgs` (see `./lib/npm-publish-args.mjs`) accepts only the
32
35
  * flag shape changesets actually passes and throws on anything it does not
33
36
  * recognise, rather than guessing a translation for an unfamiliar flag.
34
37
  *
35
38
  * `PNPM_SHIM_DIR` names this shim's own directory so it can be dropped from
36
39
  * PATH when looking for the real pnpm (otherwise it would find itself).
40
+ * Delete this, and the workflow step that installs it, once pnpm's publish
41
+ * authenticates against npmjs.com.
37
42
  */
38
43
  import process from "node:process";
39
44
  import { spawnSync } from "node:child_process";
40
45
  import { delimiter } from "node:path";
41
- import { pathWithout, toNpmStagePublishArgs } from "./lib/npm-publish-args.mjs";
46
+ import { fileURLToPath } from "node:url";
47
+ import { pathWithout, parsePublishArgs } from "./lib/npm-publish-args.mjs";
42
48
 
43
49
  const args = process.argv.slice(2);
44
50
 
@@ -46,8 +52,12 @@ let command;
46
52
  let commandArgs;
47
53
  if (args[0] === "publish") {
48
54
  try {
49
- command = "npm";
50
- commandArgs = toNpmStagePublishArgs(args.slice(1));
55
+ parsePublishArgs(args.slice(1)); // refuse an unfamiliar shape here, before spawning
56
+ command = process.execPath;
57
+ commandArgs = [
58
+ fileURLToPath(new URL("./npm-stage-publish.mjs", import.meta.url)),
59
+ ...args.slice(1),
60
+ ];
51
61
  } catch (error) {
52
62
  console.error(
53
63
  `pnpm-publish-shim: ${error instanceof Error ? error.message : String(error)}`,
@@ -73,4 +83,8 @@ if (result.error) {
73
83
  );
74
84
  process.exit(1);
75
85
  }
86
+ if (result.signal) {
87
+ console.error(`pnpm-publish-shim: ${command} was killed by ${result.signal}`);
88
+ process.exit(1);
89
+ }
76
90
  process.exit(result.status ?? 1);
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "release-tools",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "description": "Pins the exact libnpmpublish (npm's own staged-publish library) and npm-registry-fetch versions the release workflow's publish job installs, so the pin is verified by a committed lockfile's integrity hash rather than a bare version string in YAML.",
6
+ "dependencies": {
7
+ "libnpmpublish": "12.0.1",
8
+ "npm-registry-fetch": "20.0.1"
9
+ }
10
+ }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "name": "publishing",
4
- "description": "A release pipeline for a project that ships an npm package. Release half: release.yml (changesets version-PR / staged, provenance-attested npm publish via trusted publishing OIDC, including a direct check-publish-version.mjs call right before packing), .changeset/config.json + README.md, the pnpm-to-npm-stage-publish shim, and one build-group gate (check-dts-deps.mjs). Also ships check-license-headers.mjs and a REUSE.toml template as a lint-group gate (secret scanning and Scorecard are the separate `supply-chain` pack). Not adopt-capable: the release flow assumes decisions (registry access, npm trusted-publisher setup, a GitHub App for the version PR) too project-specific to install blind -- see adoptNotes.",
4
+ "description": "A release pipeline for a project that ships an npm package. Release half: release.yml (changesets version-PR / staged, provenance-attested npm publish via trusted publishing OIDC, including a direct check-publish-version.mjs call right before packing), .changeset/config.json + README.md, the pnpm-to-staged-publish shim (libnpmpublish, not the npm CLI), and one build-group gate (check-dts-deps.mjs). Also ships check-license-headers.mjs and a REUSE.toml template as a lint-group gate (secret scanning and Scorecard are the separate `supply-chain` pack). Not adopt-capable: the release flow assumes decisions (registry access, npm trusted-publisher setup, a GitHub App for the version PR) too project-specific to install blind -- see adoptNotes.",
5
5
  "modes": ["fresh"],
6
6
  "budget": {
7
7
  "agents": 0,
@@ -37,5 +37,5 @@
37
37
  "node bin/check-license-headers.mjs --fix",
38
38
  "git add -A"
39
39
  ],
40
- "adoptNotes": "REQUIRED right after install, before the first pnpm verify -- two one-time steps, or pnpm verify fails immediately, not from a real regression but from two setup gaps this pack cannot close itself: (1) `pnpm add -D @changesets/cli` -- the wiring contract only extends package.json's scripts, never its dependencies (see templates/packs/README.md), so the wired `changeset`/`version:packages` scripts reference a binary knip's own unlisted-binaries check correctly flags as missing until this is installed; (2) `git add -A`, then `node bin/check-license-headers.mjs --fix`, then `git add -A` again and commit the result (the gate only checks git-tracked files, so a fresh project with nothing staged passes it vacuously and fails on every file at its first push) -- templates/core has never had a license-header gate before this pack, so every one of its own files (hooks, bin/ scripts, CI workflows, the placeholder src/tests, and the workflows of any other installed pack such as `github` or `supply-chain`) is missing the SPDX header this pack's own license-headers gate now requires, the same one-time cost this repo itself paid when it adopted the same gate (see CLAUDE.md's Definition of Done). In a hand-copied install the CLI does not substitute tokens, so replace every literal `__PROJECT_NAME__` in the copied files (REUSE.toml, the SPDX headers in bin/, the workflows) with the project's real name first. Fresh mode only: a release pipeline encodes decisions (whether the package is actually public, which registry, whether a GitHub App backs the version PR) this pack cannot survey or guess at safely, so it is staged like every other pack (at .groundwork/packs/publishing/) but never auto-installed in adopt mode -- if an adopted project wants it, copy .groundwork/packs/publishing/files/ by hand, dropping the `.staged` suffix from every name (or copy templates/packs/publishing/files/ from this repo directly) and work through the one-time setup below. check-publish-version.mjs is deliberately NOT one of this pack's wired verify steps: with changesets, package.json's version on the release branch is always the one just published between releases, so a version-already-published check running on every ordinary push (via pnpm verify / pre-push) would fail every single time until the next version PR lands -- it is instead invoked directly as a step inside release.yml's pack job, the one place \"is this version about to collide with an already-published one\" is actually the right question to ask. The two remaining verify-group gates (dts-deps, license-headers) install anywhere a bin/verify.mjs-shaped gate runner exists; wire them into the project's real one if it differs. Both check-publish-version.mjs and check-dts-deps.mjs no-op (checked: 0, not a failure) on a package.json with `private: true` (the baseline's own default) or (check-dts-deps.mjs only) with no dist/**/*.d.ts yet -- flip `private` to `false` (and set a real `name`) once the package is actually meant to publish. The pack assumes a public package: `.changeset/config.json` ships `access: public`, npm refuses `restricted` for an unscoped name, and the publish shim always passes `--provenance`, which npm ties to a public source repository -- a private scoped package needs `access: restricted` and provenance removed from bin/lib/npm-publish-args.mjs. `@changesets/changelog-github` (and its `repo` option) is a drop-in swap for `.changeset/config.json`'s plain default changelog generator, once this project's GitHub repository is known, for changelog entries that link back to the originating PR/commit -- see `.changeset/README.md`. One-time setup before release.yml's first real run (distinct from the two pnpm-verify prerequisites above), distilled from this repo's own .claude/rules/releases.md: (1) npm cannot configure a trusted publisher for a package that doesn't exist yet -- publish once by hand with a temporary token first; (2) the trusted publisher is bound to the exact workflow filename `release.yml` -- renaming or moving it breaks publishing until reconfigured on npmjs.com; (3) set the trusted publisher's allowed actions to staged-only (`npm stage publish`, npm's own default and recommendation since 2026-09-03) -- a maintainer runs `npm stage approve <id>` (2FA, never automatable) before a version actually installs; (4) create an `npm-publish` GitHub environment (via `gh api`, not committed as JSON) with a required reviewer, restricted to the release branch, so the `publish` job itself pauses before the git tag/Release/stage-publish exist; (5) if branch protection requires status checks on every PR with no bypass actor, the version-PR job needs a GitHub App installation token (`APP_CLIENT_ID`/`APP_PRIVATE_KEY` repo secrets), not the default GITHUB_TOKEN, or those checks never trigger and the PR can never merge -- if this project has no such rule, `github-token: ${{ secrets.GITHUB_TOKEN }}` is enough and the app-token step can be dropped. release.yml pins `.github/release-tools/` (the npm CLI version) but the baseline's dependabot.yml only covers the github-actions ecosystem, so that pin goes stale unless you add an `npm` entry with `directory: \"/.github/release-tools\"` to the project's own .github/dependabot.yml. Security note, as of 2026-10-08: the npm pinned in the shipped `.github/release-tools/package-lock.json` (12.2.0) bundles undici 6.28.0, ip-address 10.5.0, brace-expansion 5.0.9, postcss-selector-parser 7.1.4 and http-cache-semantics 4.2.0, which carry open advisories; every npm release found (11.20.0, 11.21.0, 12.2.0) bundles the same versions, and overrides cannot change bundled dependencies. Reading the npm tarballs and lockfile, no reach was found from what the shipped workflow runs (`npm ci --ignore-scripts`, `npm stage publish <tarball>` and `npm stage list`; the tarball is packed earlier by pnpm, not npm, and the shipped workflow configures no proxy; if your runner sets one, for example HTTPS_PROXY on a self-hosted runner behind an egress proxy, the ip-address advisories may apply), the minimatch callers on those commands (Arborist, and tuf-js under sigstore) take their patterns from your own lockfile and from signed registry metadata, postcss-selector-parser is called only by `npm query` and `npm sbom`, and http-cache-semantics sits behind make-fetch-happen's private (`shared: false`) cache, but that is analysis, not a run of the code. Re-check on the day of each release and bump the pinned npm as soon as a release bundling undici >= 6.28.1, ip-address >= 10.7.1, brace-expansion >= 5.0.12 and postcss-selector-parser >= 7.1.6 exists; fixes are open upstream as npm/cli#10088 and #10089. http-cache-semantics has no fixed release (4.3.0 is outside the advisory's range, but upstream closed the report as not planned), so a bump past 4.2.0 only clears its alert. The secret-scanning and Scorecard workflows that used to ship here are now the separate `supply-chain` pack."
40
+ "adoptNotes": "REQUIRED right after install, before the first pnpm verify -- two one-time steps, or pnpm verify fails immediately, not from a real regression but from two setup gaps this pack cannot close itself: (1) `pnpm add -D @changesets/cli` -- the wiring contract only extends package.json's scripts, never its dependencies (see templates/packs/README.md), so the wired `changeset`/`version:packages` scripts reference a binary knip's own unlisted-binaries check correctly flags as missing until this is installed; (2) `git add -A`, then `node bin/check-license-headers.mjs --fix`, then `git add -A` again and commit the result (the gate only checks git-tracked files, so a fresh project with nothing staged passes it vacuously and fails on every file at its first push) -- templates/core has never had a license-header gate before this pack, so every one of its own files (hooks, bin/ scripts, CI workflows, the placeholder src/tests, and the workflows of any other installed pack such as `github` or `supply-chain`) is missing the SPDX header this pack's own license-headers gate now requires, the same one-time cost this repo itself paid when it adopted the same gate (see CLAUDE.md's Definition of Done). In a hand-copied install the CLI does not substitute tokens, so replace every literal `__PROJECT_NAME__` in the copied files (REUSE.toml, the SPDX headers in bin/, the workflows) with the project's real name first. Fresh mode only: a release pipeline encodes decisions (whether the package is actually public, which registry, whether a GitHub App backs the version PR) this pack cannot survey or guess at safely, so it is staged like every other pack (at .groundwork/packs/publishing/) but never auto-installed in adopt mode -- if an adopted project wants it, copy .groundwork/packs/publishing/files/ by hand, dropping the `.staged` suffix from every name (or copy templates/packs/publishing/files/ from this repo directly) and work through the one-time setup below. check-publish-version.mjs is deliberately NOT one of this pack's wired verify steps: with changesets, package.json's version on the release branch is always the one just published between releases, so a version-already-published check running on every ordinary push (via pnpm verify / pre-push) would fail every single time until the next version PR lands -- it is instead invoked directly as a step inside release.yml's pack job, the one place \"is this version about to collide with an already-published one\" is actually the right question to ask. The two remaining verify-group gates (dts-deps, license-headers) install anywhere a bin/verify.mjs-shaped gate runner exists; wire them into the project's real one if it differs. Both check-publish-version.mjs and check-dts-deps.mjs no-op (checked: 0, not a failure) on a package.json with `private: true` (the baseline's own default) or (check-dts-deps.mjs only) with no dist/**/*.d.ts yet -- flip `private` to `false` (and set a real `name`) once the package is actually meant to publish. The pack assumes a public package: `.changeset/config.json` ships `access: public`, npm refuses `restricted` for an unscoped name, and the publisher always requests provenance, which npm ties to a public source repository -- a private scoped package needs `access: restricted` and the `provenance: true` option removed from the libnpmpublish call in bin/npm-stage-publish.mjs. `@changesets/changelog-github` (and its `repo` option) is a drop-in swap for `.changeset/config.json`'s plain default changelog generator, once this project's GitHub repository is known, for changelog entries that link back to the originating PR/commit -- see `.changeset/README.md`. One-time setup before release.yml's first real run (distinct from the two pnpm-verify prerequisites above), distilled from this repo's own .claude/rules/releases.md: (1) npm cannot configure a trusted publisher for a package that doesn't exist yet -- publish once by hand with a temporary token first; (2) the trusted publisher is bound to the exact workflow filename `release.yml` -- renaming or moving it breaks publishing until reconfigured on npmjs.com; (3) set the trusted publisher's allowed actions to staged-only (staged publishing only, npm's own default and recommendation since 2026-09-03) -- a maintainer runs `npm stage approve <id>` (2FA, never automatable) before a version actually installs; (4) create an `npm-publish` GitHub environment (via `gh api`, not committed as JSON) with a required reviewer, restricted to the release branch, so the `publish` job itself pauses before the git tag/Release/stage-publish exist; (5) if branch protection requires status checks on every PR with no bypass actor, the version-PR job needs a GitHub App installation token (`APP_CLIENT_ID`/`APP_PRIVATE_KEY` repo secrets), not the default GITHUB_TOKEN, or those checks never trigger and the PR can never merge -- if this project has no such rule, `github-token: ${{ secrets.GITHUB_TOKEN }}` is enough and the app-token step can be dropped. release.yml pins `tools/release/` (the exact libnpmpublish and npm-registry-fetch versions the publish job installs; it stages through them, not the npm CLI, because the CLI's bundled dependencies cannot be patched by an override) but the baseline's dependabot.yml only covers the github-actions ecosystem, so that pin goes stale unless you add an `npm` entry with `directory: \"/tools/release\"` to the project's own .github/dependabot.yml. The staged id to approve is printed by the workflow's \"Show the staged ids to approve\" step (and annotated on the run), and the `npm stage approve <id>` command is also written to the job summary. The secret-scanning and Scorecard workflows that used to ship here are now the separate `supply-chain` pack."
41
41
  }
@@ -1,9 +0,0 @@
1
- {
2
- "name": "release-tools",
3
- "version": "0.0.0",
4
- "private": true,
5
- "description": "Pins the exact npm version the release workflow's publish job installs, so the pin is verified by a committed lockfile's integrity hash rather than a bare version string in YAML.",
6
- "dependencies": {
7
- "npm": "12.2.0"
8
- }
9
- }