@decohere/ci-tools 0.0.1-dev.20261120.336 → 0.0.1-dev.20261122.343

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": "@decohere/ci-tools",
3
- "version": "0.0.1-dev.20261120.336",
3
+ "version": "0.0.1-dev.20261122.343",
4
4
  "description": "CI utility scripts for badge generation, coverage reporting, pages artifact assembly, and GitHub API tooling",
5
5
  "keywords": [
6
6
  "typescript",
@@ -3,6 +3,10 @@
3
3
  * Finds packages in this workspace that aren't on npm yet. A first publish needs an owner's npm
4
4
  * login, so CI can't do it. On a PR that's only a notice, so a contributor can propose a package
5
5
  * with no npm access. In the merge queue it fails, because Publish could not upload that package.
6
+ *
7
+ * A name on npm that Publish has never published may lack its Trusted Publishers, which only a
8
+ * logged-in owner can see. That gets a warning, not a failure: a package an owner has just set up
9
+ * has no version from Publish either, until it merges.
6
10
  */
7
11
  import { resolve } from "node:path";
8
12
  import { pathToFileURL } from "node:url";
@@ -10,6 +14,18 @@ import { listPublishablePackages } from "./publish-verify.mjs";
10
14
 
11
15
  const REGISTRY = "https://registry.npmjs.org";
12
16
 
17
+ /**
18
+ * Publish runs on GitHub Actions with provenance, so npm keeps an attestation for each version it
19
+ * publishes; a version an owner published by hand has none.
20
+ *
21
+ * @param {{ versions?: Record<string, { dist?: { attestations?: unknown } }> }} packument
22
+ */
23
+ function publishedFromCi(packument) {
24
+ return Object.values(packument.versions ?? {}).some(
25
+ (version) => version.dist?.attestations != null,
26
+ );
27
+ }
28
+
13
29
  /**
14
30
  * @param {{
15
31
  * packages: string[],
@@ -32,10 +48,22 @@ export async function checkFirstPublish(options) {
32
48
  if (!response.ok && response.status !== 404) {
33
49
  throw new Error(`Could not check ${name} on npm: ${response.status}`);
34
50
  }
35
- return { name, missing: response.status === 404 };
51
+ if (response.status === 404) return { name, missing: true, fromCi: false };
52
+ return { name, missing: false, fromCi: publishedFromCi(await response.json()) };
36
53
  }),
37
54
  );
38
55
 
56
+ const neverFromCi = results
57
+ .filter((result) => !result.missing && !result.fromCi)
58
+ .map((result) => result.name);
59
+ if (neverFromCi.length > 0) {
60
+ const names = neverFromCi.join(" ");
61
+ log(
62
+ `::warning::On npm, but never published by Publish: ${names}. Unless an owner has run ` +
63
+ `\`pnpm npm:bootstrap --otp <code> ${names}\`, it may have no Trusted Publisher, and Publish will fail on it.`,
64
+ );
65
+ }
66
+
39
67
  const missing = results.filter((result) => result.missing).map((result) => result.name);
40
68
  if (missing.length === 0) {
41
69
  log(`All ${packages.length} packages are on npm.`);
@@ -1,29 +1,44 @@
1
1
  /**
2
- * First-publish a new package name (public) and give it its Trusted Publisher,
3
- * so `publish.yml` can release it over OIDC from then on.
2
+ * Sets up npm so CI can publish and promote every package: the name exists, `publish.yml` is a
3
+ * Trusted Publisher (to publish), and `promote-latest.yml` is one (to move `latest`, with only the
4
+ * dist-tag permission). Run it after adding a package, or any time: each step is skipped when it is
5
+ * already done, so with nothing to do it changes nothing.
4
6
  *
5
- * pnpm npm:bootstrap [--otp <code>] [--dry-run] [--channel dev] [<package-name>...]
7
+ * npm login
8
+ * pnpm npm:bootstrap --otp <code> [--dry-run] [--channel dev] [<package-name>...]
6
9
  *
7
- * Without names: every publishable package whose name is not on npm yet.
8
- * Run from the repo root after `npm login` to the org. Each step is skipped when
9
- * it is already done (the name exists, the Trusted Publisher is set).
10
+ * Without names: every publishable package. Everything is read first, in parallel, and then only
11
+ * the missing steps run, so one OTP code (about 30 seconds) can cover them. npm wants the code even
12
+ * to read a package's Trusted Publishers, so it is required, also for `--dry-run`.
10
13
  *
11
- * npm runs on this terminal, so it does its own 2FA: it asks for a code, or
12
- * opens the browser for web authentication. `--otp` hands it a code up front
13
- * through `NPM_CONFIG_OTP`; `npm trust` takes no `--otp` flag of its own.
14
+ * The first publish and the `publish.yml` publisher go through npm's CLI. The `promote-latest.yml`
15
+ * publisher is copied from a package that has it, through the registry endpoint `npm trust` uses,
16
+ * because `npm trust` has no flag for the dist-tag permission (`manageDistTags`). npm doesn't
17
+ * document that endpoint. The calls use the npm login in the user's npmrc, which is never printed.
14
18
  */
15
19
  import { spawnSync } from "node:child_process";
20
+ import { readFileSync } from "node:fs";
16
21
  import { resolve } from "node:path";
17
22
  import { parseArgs } from "node:util";
18
23
  import { pathToFileURL } from "node:url";
19
- import { listPublishablePackages, npmNameExists } from "./publish-verify.mjs";
24
+ import { listPublishablePackages } from "./publish-verify.mjs";
20
25
 
21
- /** The Trusted Publisher every package gets: `publish.yml`'s npm job. */
22
- export const TRUSTED_PUBLISHER = {
23
- repo: "typesmiths/decohere",
24
- file: "publish.yml",
25
- environment: "npm-publish",
26
- };
26
+ const REGISTRY = "https://registry.npmjs.org";
27
+ const REPOSITORY = "typesmiths/decohere";
28
+
29
+ /** The Trusted Publisher that publishes: `publish.yml`'s npm job. */
30
+ export const PUBLISH_WORKFLOW = "publish.yml";
31
+ const PUBLISH_ENVIRONMENT = "npm-publish";
32
+ /** The Trusted Publisher that moves `latest`: `promote-latest.yml`, dist-tags only. */
33
+ export const PROMOTE_WORKFLOW = "promote-latest.yml";
34
+
35
+ /**
36
+ * @typedef {{ type?: string, claims?: { repository?: string, workflow_ref?: { file?: string } }, permissions?: string[] }} TrustEntry
37
+ * @typedef {{ name: string, dir: string, version?: string }} Package
38
+ * @typedef {{ capture?: boolean, otp?: string }} NpmOptions
39
+ * `capture` keeps stdout to read it (npm can then not prompt for 2FA); otherwise npm owns the terminal.
40
+ * @typedef {(args: string[], options?: NpmOptions) => { status: number, output: string }} Npm
41
+ */
27
42
 
28
43
  /** @param {string | undefined} version */
29
44
  export function needsPrereleaseTag(version) {
@@ -34,7 +49,7 @@ export function needsPrereleaseTag(version) {
34
49
  * npm arguments for a name-only first publish. Scoped names default to restricted,
35
50
  * so `--access public`. `./` stops npm reading the path as a GitHub `owner/repo`.
36
51
  *
37
- * @param {{ dir: string, version?: string }} pkg
52
+ * @param {Package} pkg
38
53
  * @param {string} channel
39
54
  */
40
55
  export function publishArgs(pkg, channel) {
@@ -49,32 +64,77 @@ export function trustArgs(name) {
49
64
  "github",
50
65
  name,
51
66
  "--file",
52
- TRUSTED_PUBLISHER.file,
67
+ PUBLISH_WORKFLOW,
53
68
  "--repo",
54
- TRUSTED_PUBLISHER.repo,
69
+ REPOSITORY,
55
70
  "--env",
56
- TRUSTED_PUBLISHER.environment,
71
+ PUBLISH_ENVIRONMENT,
57
72
  "--allow-publish",
58
73
  "--yes",
59
74
  ];
60
75
  }
61
76
 
62
- /** @param {string} output `npm trust list <name> --json` */
63
- export function hasTrustedPublisher(output) {
64
- return output.includes(TRUSTED_PUBLISHER.file) && output.includes(TRUSTED_PUBLISHER.repo);
65
- }
66
-
67
77
  /**
68
- * @typedef {{ capture?: boolean, otp?: string }} NpmOptions
69
- * `capture` keeps stdout to read it (npm can then not prompt for 2FA);
70
- * otherwise npm owns the terminal.
78
+ * @param {TrustEntry[]} entries
79
+ * @param {string} workflow
71
80
  */
81
+ function findEntry(entries, workflow) {
82
+ return entries.find(
83
+ (entry) =>
84
+ entry.claims?.workflow_ref?.file === workflow && entry.claims?.repository === REPOSITORY,
85
+ );
86
+ }
87
+
88
+ /** @param {string} name */
89
+ const encoded = (name) => name.replace("/", "%2f");
72
90
 
73
91
  /**
74
- * @param {string[]} args
75
- * @param {NpmOptions} [options]
76
- * @returns {{ status: number, output: string }}
92
+ * The registry calls, as the logged-in owner.
93
+ *
94
+ * @param {{ token: string, otp?: string, fetch: typeof globalThis.fetch }} options
77
95
  */
96
+ function registry({ token, otp, fetch }) {
97
+ const headers = {
98
+ authorization: `Bearer ${token}`,
99
+ "content-type": "application/json",
100
+ ...(otp ? { "npm-otp": otp } : {}),
101
+ };
102
+ const trustUrl = (/** @type {string} */ name) =>
103
+ `${REGISTRY}/-/package/${encoded(name)}/trust`;
104
+ return {
105
+ /** @param {string} name */
106
+ async exists(name) {
107
+ const response = await fetch(`${REGISTRY}/${encoded(name)}`, { headers });
108
+ if (response.status === 404) return false;
109
+ if (!response.ok) throw new Error(`reading ${name}: ${response.status}`);
110
+ return true;
111
+ },
112
+ /** @param {string} name @returns {Promise<TrustEntry[]>} */
113
+ async trust(name) {
114
+ const response = await fetch(trustUrl(name), { headers });
115
+ if (!response.ok) {
116
+ throw new Error(
117
+ `reading ${name}'s Trusted Publishers: ${response.status} ${await response.text()}`,
118
+ );
119
+ }
120
+ return response.json();
121
+ },
122
+ /** @param {string} name @param {TrustEntry} entry */
123
+ async addTrust(name, entry) {
124
+ const body = [
125
+ { type: entry.type, claims: entry.claims, permissions: entry.permissions },
126
+ ];
127
+ const response = await fetch(trustUrl(name), {
128
+ method: "POST",
129
+ headers,
130
+ body: JSON.stringify(body),
131
+ });
132
+ return response.ok ? null : `${response.status} ${await response.text()}`;
133
+ },
134
+ };
135
+ }
136
+
137
+ /** @param {string[]} args @param {NpmOptions} [options] */
78
138
  function runNpm(args, { capture = false, otp } = {}) {
79
139
  const result = spawnSync("npm", args, {
80
140
  encoding: "utf8",
@@ -84,13 +144,28 @@ function runNpm(args, { capture = false, otp } = {}) {
84
144
  return { status: result.status ?? 1, output: result.stdout ?? "" };
85
145
  }
86
146
 
147
+ /**
148
+ * The login `npm login` saved. npm won't print it (`npm config get` refuses), so it is read from
149
+ * the user's npmrc.
150
+ *
151
+ * @param {Npm} npm
152
+ * @returns {string | undefined}
153
+ */
154
+ function readLoginToken(npm) {
155
+ const userconfig = npm(["config", "get", "userconfig"], { capture: true }).output.trim();
156
+ if (userconfig.length === 0) return undefined;
157
+ const npmrc = readFileSync(userconfig, "utf8");
158
+ return /^\/\/registry\.npmjs\.org\/:_authToken=(.+)$/m.exec(npmrc)?.[1]?.trim();
159
+ }
160
+
87
161
  /**
88
162
  * @param {{
89
163
  * argv?: string[],
90
164
  * root?: string,
91
165
  * io?: {
92
- * npm?: (args: string[], options?: NpmOptions) => { status: number, output: string },
93
- * nameExists?: (name: string) => boolean,
166
+ * npm?: Npm,
167
+ * fetch?: typeof globalThis.fetch,
168
+ * token?: () => string | undefined,
94
169
  * log?: (line: string) => void,
95
170
  * },
96
171
  * }} [options]
@@ -108,68 +183,130 @@ export async function runBootstrap(options = {}) {
108
183
  });
109
184
  const io = options.io ?? {};
110
185
  const npm = io.npm ?? runNpm;
111
- const nameExists = io.nameExists ?? ((name) => npmNameExists(name));
112
186
  const log = io.log ?? ((line) => process.stdout.write(`${line}\n`));
113
187
  const dryRun = values["dry-run"];
188
+ const otp = values.otp;
114
189
 
115
- // Even on a dry run: the names are private, so `npm view` 404s without a login
116
- // and every package would look unpublished.
117
- if (npm(["whoami"]).status !== 0) {
190
+ const token =
191
+ npm(["whoami"], { capture: true }).status === 0
192
+ ? (io.token ?? (() => readLoginToken(npm)))()
193
+ : undefined;
194
+ if (token == null) {
118
195
  log("Not logged in to npm: run `npm login` first.");
119
196
  return 1;
120
197
  }
121
198
 
199
+ if (otp == null) {
200
+ log(
201
+ "Pass a code from your authenticator: pnpm npm:bootstrap --otp <code>. npm wants one even to read Trusted Publishers.",
202
+ );
203
+ return 1;
204
+ }
205
+
122
206
  const publishable = listPublishablePackages(options.root ?? process.cwd());
123
207
  const unknown = positionals.filter((name) => !publishable.some((pkg) => pkg.name === name));
124
208
  if (unknown.length > 0) {
125
209
  log(`Not a publishable package in projects/: ${unknown.join(", ")}`);
126
210
  return 1;
127
211
  }
128
- const packages =
212
+ const chosen =
129
213
  positionals.length > 0
130
214
  ? publishable.filter((pkg) => positionals.includes(pkg.name))
131
- : publishable.filter((pkg) => !nameExists(pkg.name));
132
- if (packages.length === 0) {
133
- log("Every package name is on npm already. Name one to check its Trusted Publisher.");
215
+ : publishable;
216
+
217
+ // Every package is read, not only the chosen ones: the promote publisher is copied from one that has it.
218
+ const npmRegistry = registry({ token, otp, fetch: io.fetch ?? globalThis.fetch });
219
+ let state;
220
+ try {
221
+ state = await Promise.all(
222
+ publishable.map(async (pkg) => {
223
+ const exists = await npmRegistry.exists(pkg.name);
224
+ return { pkg, exists, trust: exists ? await npmRegistry.trust(pkg.name) : [] };
225
+ }),
226
+ );
227
+ } catch (error) {
228
+ log(`Nothing changed. ${String(error)}`);
229
+ return 1;
230
+ }
231
+
232
+ const plans = state
233
+ .filter(({ pkg }) => chosen.includes(pkg))
234
+ .map(({ pkg, exists, trust }) => ({
235
+ pkg,
236
+ publish: !exists,
237
+ publishTrust: findEntry(trust, PUBLISH_WORKFLOW) == null,
238
+ promoteTrust: findEntry(trust, PROMOTE_WORKFLOW) == null,
239
+ }))
240
+ .filter((plan) => plan.publish || plan.publishTrust || plan.promoteTrust);
241
+ if (plans.length === 0) {
242
+ log(`Nothing to do: ${chosen.length} packages can be published and promoted from CI.`);
134
243
  return 0;
135
244
  }
136
245
 
137
- // A code npm rejects (they last about 30 seconds) makes npm ask for a new one.
246
+ const promoteSource = state
247
+ .map(({ trust }) => findEntry(trust, PROMOTE_WORKFLOW))
248
+ .find((entry) => entry != null);
249
+ if (promoteSource == null && plans.some((plan) => plan.promoteTrust)) {
250
+ log(
251
+ `No package has a Trusted Publisher for ${PROMOTE_WORKFLOW} to copy. On npmjs.com, in the settings of ` +
252
+ `@decohere/cli, add one: GitHub Actions, organization typesmiths, repository decohere, workflow ` +
253
+ `${PROMOTE_WORKFLOW}, no environment, Allow npm publish off, Allow npm dist-tag on. Then run this again. ` +
254
+ "Nothing changed.",
255
+ );
256
+ return 1;
257
+ }
258
+
138
259
  /** @param {string[]} args */
139
- const change = (args) => {
260
+ const runChange = (args) => {
140
261
  if (dryRun) {
141
- log(`[dry run] npm ${args.join(" ")}`);
262
+ log(` [dry run] npm ${args.join(" ")}`);
142
263
  return true;
143
264
  }
144
- return npm(args, { otp: values.otp }).status === 0;
265
+ return npm(args, { otp }).status === 0;
145
266
  };
146
267
 
147
- for (const pkg of packages) {
268
+ for (const plan of plans) {
269
+ const { pkg } = plan;
148
270
  log(`\n${pkg.name} (projects/${pkg.dir}, ${pkg.version})`);
149
271
 
150
- if (nameExists(pkg.name)) {
272
+ if (!plan.publish) {
151
273
  log(" name is on npm: skip the first publish");
152
- } else if (!change(publishArgs(pkg, values.channel))) {
153
- log(` first publish failed: stopping`);
274
+ } else if (!runChange(publishArgs(pkg, values.channel))) {
275
+ log(" first publish failed: stopping");
154
276
  return 1;
155
277
  }
156
278
 
157
- const listed = dryRun
158
- ? { status: 1, output: "" }
159
- : npm(["trust", "list", pkg.name, "--json"], { capture: true, otp: values.otp });
160
- if (listed.status === 0 && hasTrustedPublisher(listed.output)) {
161
- log(" Trusted Publisher is set: skip");
162
- } else if (!change(trustArgs(pkg.name))) {
163
- log(" Trusted Publisher failed: stopping");
279
+ if (!plan.publishTrust) {
280
+ log(` Trusted Publisher for ${PUBLISH_WORKFLOW} is set: skip`);
281
+ } else if (!runChange(trustArgs(pkg.name))) {
282
+ log(` Trusted Publisher for ${PUBLISH_WORKFLOW} failed: stopping`);
164
283
  return 1;
165
284
  }
285
+
286
+ if (!plan.promoteTrust) {
287
+ log(` Trusted Publisher for ${PROMOTE_WORKFLOW} is set: skip`);
288
+ } else if (dryRun) {
289
+ log(` [dry run] copy the Trusted Publisher for ${PROMOTE_WORKFLOW} to ${pkg.name}`);
290
+ } else {
291
+ // Checked above: some package has it.
292
+ const failure = await npmRegistry.addTrust(
293
+ pkg.name,
294
+ /** @type {TrustEntry} */ (promoteSource),
295
+ );
296
+ if (failure != null) {
297
+ log(
298
+ ` Trusted Publisher for ${PROMOTE_WORKFLOW} failed: ${failure}. Run this again with a new code.`,
299
+ );
300
+ return 1;
301
+ }
302
+ log(` Trusted Publisher for ${PROMOTE_WORKFLOW}: set`);
303
+ }
166
304
  }
167
305
 
306
+ if (dryRun) return 0;
168
307
  log(
169
- "\nFor each new package, also run `pnpm npm:trust-promote --otp <code>`, so Promote to latest can move its tag.",
170
- );
171
- log(
172
- "\nDone. Add the PR to the merge queue. If Publish already failed on this, rerun it: `gh run rerun --failed <run-id>`.",
308
+ "\nDone: these packages can be published and promoted from CI. If Publish already failed on one, " +
309
+ "rerun it: `gh run rerun --failed <run-id>`. Otherwise add the PR to the merge queue.",
173
310
  );
174
311
  return 0;
175
312
  }
@@ -1,19 +1,32 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { checkFirstPublish } from "../../src/github/first-publish-check.mjs";
3
3
 
4
- function fakeRegistry(statusByName) {
4
+ /** A version Publish made: npm attaches a provenance attestation to it. */
5
+ const FROM_CI = {
6
+ "0.0.1-dev.6": {
7
+ dist: { attestations: { url: "https://registry.npmjs.org/-/npm/v1/attestations/x" } },
8
+ },
9
+ };
10
+ /** A version an owner published by hand. */
11
+ const BY_HAND = { "0.0.1-dev.5": { dist: {} } };
12
+
13
+ /** Each name answers with its status, and its versions (Publish's by default). */
14
+ function fakeRegistry(statusByName, versionsByName = {}) {
5
15
  return async (url) => {
6
16
  const name = decodeURIComponent(new URL(url).pathname.slice(1));
7
- return new Response("{}", { status: statusByName[name] ?? 200 });
17
+ const versions = versionsByName[name] ?? FROM_CI;
18
+ return new Response(JSON.stringify({ name, versions }), {
19
+ status: statusByName[name] ?? 200,
20
+ });
8
21
  };
9
22
  }
10
23
 
11
- async function check(statusByName, blocking) {
24
+ async function check(statusByName, blocking, versionsByName) {
12
25
  const messages = [];
13
26
  const code = await checkFirstPublish({
14
27
  packages: ["@decohere/cli", "@decohere/shiny"],
15
28
  blocking,
16
- fetch: fakeRegistry(statusByName),
29
+ fetch: fakeRegistry(statusByName, versionsByName),
17
30
  log: (message) => messages.push(message),
18
31
  });
19
32
  return { code, output: messages.join("\n") };
@@ -43,6 +56,17 @@ describe("checkFirstPublish", () => {
43
56
  expect(output).toContain("pnpm npm:bootstrap --otp <code> @decohere/shiny");
44
57
  });
45
58
 
59
+ // How @decohere/http-fastify got through: its name was made by hand, with no Trusted Publisher.
60
+ it("warns, without failing, about a name on npm that Publish has never published", async () => {
61
+ const { code, output } = await check({}, true, { "@decohere/shiny": { ...BY_HAND } });
62
+
63
+ expect(code).toBe(0);
64
+ expect(output).toContain("::warning::");
65
+ expect(output).toContain("@decohere/shiny");
66
+ expect(output).toContain("pnpm npm:bootstrap --otp <code> @decohere/shiny");
67
+ expect(output).not.toContain("@decohere/cli");
68
+ });
69
+
46
70
  it("doesn't mistake an npm outage for a new package", async () => {
47
71
  await expect(check({ "@decohere/shiny": 503 }, false)).rejects.toThrow(
48
72
  "Could not check @decohere/shiny on npm: 503",
@@ -3,12 +3,17 @@ import { afterEach, describe, expect, it } from "vitest";
3
3
  import { runBootstrap } from "../../src/github/npm-bootstrap.mjs";
4
4
 
5
5
  const root = "/workspace";
6
+ const LOGIN = "the-secret-login";
6
7
 
7
8
  function seedWorkspace() {
8
9
  vol.fromJSON({
9
10
  [`${root}/package.json`]: JSON.stringify({ version: "0.0.1-dev.5" }),
10
- [`${root}/projects/scribe/scribe/package.json`]: JSON.stringify({
11
- name: "@decohere/scribe",
11
+ [`${root}/projects/cli/package.json`]: JSON.stringify({
12
+ name: "@decohere/cli",
13
+ version: "0.0.1-dev.5",
14
+ }),
15
+ [`${root}/projects/http/http-fastify/package.json`]: JSON.stringify({
16
+ name: "@decohere/http-fastify",
12
17
  version: "0.0.1-dev.5",
13
18
  }),
14
19
  [`${root}/projects/scribe/scribe-console/package.json`]: JSON.stringify({
@@ -18,39 +23,75 @@ function seedWorkspace() {
18
23
  });
19
24
  }
20
25
 
26
+ const claims = (file) => ({ repository: "typesmiths/decohere", workflow_ref: { file } });
27
+ const PUBLISH = {
28
+ id: "p1",
29
+ type: "github",
30
+ claims: { ...claims("publish.yml"), environment: "npm-publish" },
31
+ permissions: ["createPackage"],
32
+ };
33
+ const PROMOTE = {
34
+ id: "p2",
35
+ type: "github",
36
+ claims: claims("promote-latest.yml"),
37
+ permissions: ["createStagedPackage", "manageDistTags"],
38
+ };
39
+ const FULL = [PUBLISH, PROMOTE];
40
+
21
41
  /**
22
- * A fake registry: `published` names exist, and `trusted` names have a Trusted
23
- * Publisher. Each call is recorded as its arguments, plus the code npm would
24
- * get through NPM_CONFIG_OTP.
42
+ * A fake npm and registry. `packages` maps each name on npm to its Trusted Publishers; a name not
43
+ * in it isn't on npm. npm calls are recorded as their arguments plus the code npm would get through
44
+ * NPM_CONFIG_OTP; registry writes as the name, body and code.
25
45
  */
26
- function fakeNpm({ published = [], trusted = [], loggedIn = true } = {}) {
46
+ function fakeNpm({ packages = {}, loggedIn = true, failPosting = [] } = {}) {
27
47
  const calls = [];
48
+ const posts = [];
28
49
  const npm = (args, { otp } = {}) => {
29
50
  calls.push(`${args.join(" ")}${otp ? ` [otp ${otp}]` : ""}`);
30
- if (args[0] === "whoami") {
31
- return { status: loggedIn ? 0 : 1, output: "" };
51
+ if (args[0] === "whoami") return { status: loggedIn ? 0 : 1, output: "" };
52
+ // A first publish creates the name, with no Trusted Publishers yet.
53
+ if (args[0] === "publish") packages[`@decohere/${args[1].split("/").at(-1)}`] = [];
54
+ return { status: 0, output: "" };
55
+ };
56
+ const fetch = async (url, init = {}) => {
57
+ const headers = new Headers(init.headers);
58
+ if (headers.get("authorization") !== `Bearer ${LOGIN}`) {
59
+ return new Response("unauthorized", { status: 401 });
32
60
  }
33
- if (args[0] === "trust" && args[1] === "list") {
34
- return trusted.includes(args[2])
35
- ? { status: 0, output: '[{"repository":"typesmiths/decohere","file":"publish.yml"}]' }
36
- : { status: 0, output: "[]" };
61
+ const trust = /\/-\/package\/(.+)\/trust$/.exec(url);
62
+ const name = decodeURIComponent(trust?.[1] ?? new URL(url).pathname.slice(1));
63
+ if (!(name in packages)) return new Response("not found", { status: 404 });
64
+ if (trust == null) return new Response(JSON.stringify({ name }));
65
+ // Like npm: Trusted Publishers need a code, even to read them.
66
+ if (headers.get("npm-otp") == null) {
67
+ return new Response('{"message":"Unauthorized"}', {
68
+ status: 401,
69
+ headers: { "www-authenticate": "OTP" },
70
+ });
37
71
  }
38
- return { status: 0, output: "" };
72
+ if (init.method === "POST") {
73
+ if (failPosting.includes(name)) return new Response("denied", { status: 403 });
74
+ posts.push({ name, body: JSON.parse(String(init.body)), otp: headers.get("npm-otp") });
75
+ return new Response("[]");
76
+ }
77
+ return new Response(JSON.stringify(packages[name]));
39
78
  };
40
- return { npm, calls, nameExists: (name) => published.includes(name) };
79
+ return { npm, fetch, calls, posts };
41
80
  }
42
81
 
43
- function run(argv, registry) {
82
+ async function run(argv, registry) {
44
83
  const lines = [];
45
- return runBootstrap({
84
+ const code = await runBootstrap({
46
85
  argv,
47
86
  root,
48
87
  io: {
49
88
  npm: registry.npm,
50
- nameExists: registry.nameExists,
89
+ fetch: registry.fetch,
90
+ token: () => LOGIN,
51
91
  log: (line) => lines.push(line),
52
92
  },
53
- }).then((code) => ({ code, lines }));
93
+ });
94
+ return { code, output: lines.join("\n") };
54
95
  }
55
96
 
56
97
  afterEach(() => {
@@ -58,9 +99,11 @@ afterEach(() => {
58
99
  });
59
100
 
60
101
  describe("npm-bootstrap", () => {
61
- it("first-publishes unpublished names public, then sets the Trusted Publisher", async () => {
102
+ it("gives a new package its name and both Trusted Publishers, with one code", async () => {
62
103
  seedWorkspace();
63
- const registry = fakeNpm({ published: ["@decohere/scribe"] });
104
+ const registry = fakeNpm({
105
+ packages: { "@decohere/cli": FULL, "@decohere/http-fastify": FULL },
106
+ });
64
107
 
65
108
  const { code } = await run(["--otp", "123456"], registry);
66
109
 
@@ -68,47 +111,158 @@ describe("npm-bootstrap", () => {
68
111
  expect(registry.calls).toEqual([
69
112
  "whoami",
70
113
  "publish ./projects/scribe/scribe-console --access public --tag dev [otp 123456]",
71
- "trust list @decohere/scribe-console --json [otp 123456]",
72
114
  "trust github @decohere/scribe-console --file publish.yml --repo typesmiths/decohere --env npm-publish --allow-publish --yes [otp 123456]",
73
115
  ]);
116
+ expect(registry.posts).toEqual([
117
+ {
118
+ name: "@decohere/scribe-console",
119
+ otp: "123456",
120
+ body: [{ type: "github", claims: PROMOTE.claims, permissions: PROMOTE.permissions }],
121
+ },
122
+ ]);
74
123
  });
75
124
 
76
- it("skips the steps that are already done", async () => {
125
+ // http-fastify: its name was made by hand, with no Trusted Publisher.
126
+ it("sets up a name that is on npm but has no Trusted Publishers, without publishing it", async () => {
77
127
  seedWorkspace();
78
128
  const registry = fakeNpm({
79
- published: ["@decohere/scribe-console"],
80
- trusted: ["@decohere/scribe-console"],
129
+ packages: {
130
+ "@decohere/cli": FULL,
131
+ "@decohere/http-fastify": [],
132
+ "@decohere/scribe-console": FULL,
133
+ },
81
134
  });
82
135
 
83
- const { code } = await run(["@decohere/scribe-console"], registry);
136
+ const { code, output } = await run(["--otp", "1"], registry);
84
137
 
85
138
  expect(code).toBe(0);
86
- expect(registry.calls).toEqual(["whoami", "trust list @decohere/scribe-console --json"]);
139
+ expect(registry.calls).toEqual([
140
+ "whoami",
141
+ "trust github @decohere/http-fastify --file publish.yml --repo typesmiths/decohere --env npm-publish --allow-publish --yes [otp 1]",
142
+ ]);
143
+ expect(registry.posts.map((post) => post.name)).toEqual(["@decohere/http-fastify"]);
144
+ expect(output).toContain("name is on npm: skip the first publish");
145
+ });
146
+
147
+ it("adds only the promote publisher to a package that has the publish one", async () => {
148
+ seedWorkspace();
149
+ const registry = fakeNpm({
150
+ packages: {
151
+ "@decohere/cli": FULL,
152
+ "@decohere/http-fastify": [PUBLISH],
153
+ "@decohere/scribe-console": FULL,
154
+ },
155
+ });
156
+
157
+ const { code, output } = await run(["--otp", "1"], registry);
158
+
159
+ expect(code).toBe(0);
160
+ expect(registry.calls).toEqual(["whoami"]);
161
+ expect(registry.posts.map((post) => post.name)).toEqual(["@decohere/http-fastify"]);
162
+ expect(output).toContain("Trusted Publisher for publish.yml is set: skip");
163
+ });
164
+
165
+ it("changes nothing when every package is set up", async () => {
166
+ seedWorkspace();
167
+ const registry = fakeNpm({
168
+ packages: {
169
+ "@decohere/cli": FULL,
170
+ "@decohere/http-fastify": FULL,
171
+ "@decohere/scribe-console": FULL,
172
+ },
173
+ });
174
+
175
+ const { code, output } = await run(["--otp", "1"], registry);
176
+
177
+ expect(code).toBe(0);
178
+ expect(registry.calls).toEqual(["whoami"]);
179
+ expect(registry.posts).toEqual([]);
180
+ expect(output).toBe("Nothing to do: 3 packages can be published and promoted from CI.");
181
+ });
182
+
183
+ it("works only on the packages named", async () => {
184
+ seedWorkspace();
185
+ const registry = fakeNpm({
186
+ packages: { "@decohere/cli": FULL, "@decohere/http-fastify": [] },
187
+ });
188
+
189
+ await run(["--otp", "1", "@decohere/http-fastify"], registry);
190
+
191
+ expect(registry.calls.join("\n")).not.toContain("scribe-console");
192
+ expect(registry.posts.map((post) => post.name)).toEqual(["@decohere/http-fastify"]);
193
+ });
194
+
195
+ it("says where to set up the promote publisher when no package has one, changing nothing", async () => {
196
+ seedWorkspace();
197
+ const registry = fakeNpm({
198
+ packages: { "@decohere/cli": [PUBLISH], "@decohere/http-fastify": [PUBLISH] },
199
+ });
200
+
201
+ const { code, output } = await run(["--otp", "1"], registry);
202
+
203
+ expect(code).toBe(1);
204
+ expect(output).toContain("Allow npm dist-tag on");
205
+ expect(registry.calls).toEqual(["whoami"]);
206
+ expect(registry.posts).toEqual([]);
207
+ });
208
+
209
+ it("stops, saying to run it again, when the registry refuses a change", async () => {
210
+ seedWorkspace();
211
+ const registry = fakeNpm({
212
+ packages: {
213
+ "@decohere/cli": FULL,
214
+ "@decohere/http-fastify": [PUBLISH],
215
+ "@decohere/scribe-console": FULL,
216
+ },
217
+ failPosting: ["@decohere/http-fastify"],
218
+ });
219
+
220
+ const { code, output } = await run(["--otp", "1"], registry);
221
+
222
+ expect(code).toBe(1);
223
+ expect(output).toContain("403 denied. Run this again with a new code.");
87
224
  });
88
225
 
89
226
  /** `npm trust` rejects `--otp`: the code goes through the environment. */
90
- it("never passes the code as an argument, and lets npm ask when none is given", async () => {
227
+ it("never passes the code as an argument, and gives it to the registry", async () => {
91
228
  seedWorkspace();
92
- const withCode = fakeNpm({ published: ["@decohere/scribe"] });
93
- await run(["--otp", "604381"], withCode);
94
- expect(withCode.calls.join("\n")).not.toContain("--otp");
229
+ const registry = fakeNpm({ packages: { "@decohere/cli": FULL } });
95
230
 
96
- const withoutCode = fakeNpm({ published: ["@decohere/scribe"] });
97
- expect((await run([], withoutCode)).code).toBe(0);
98
- expect(withoutCode.calls.join("\n")).not.toContain("otp");
231
+ await run(["--otp", "604381"], registry);
232
+
233
+ expect(registry.calls.join("\n")).not.toContain("--otp");
234
+ expect(registry.posts.map((post) => post.otp)).toEqual(["604381", "604381"]);
99
235
  });
100
236
 
101
- it("prints the commands on a dry run, calling npm only to check the login", async () => {
237
+ // npm wants a code even to read Trusted Publishers.
238
+ it("asks for a code before reading anything", async () => {
102
239
  seedWorkspace();
103
- const registry = fakeNpm({ published: ["@decohere/scribe"] });
240
+ const registry = fakeNpm({ packages: { "@decohere/cli": FULL } });
241
+
242
+ const { code, output } = await run([], registry);
243
+
244
+ expect(code).toBe(1);
245
+ expect(output).toContain("--otp <code>");
246
+ expect(registry.calls).toEqual(["whoami"]);
247
+ });
248
+
249
+ it("prints what it would do on a dry run, changing nothing", async () => {
250
+ seedWorkspace();
251
+ const registry = fakeNpm({
252
+ packages: { "@decohere/cli": FULL, "@decohere/http-fastify": [] },
253
+ });
104
254
 
105
- const { code, lines } = await run(["--dry-run"], registry);
255
+ const { code, output } = await run(["--dry-run", "--otp", "1"], registry);
106
256
 
107
257
  expect(code).toBe(0);
108
258
  expect(registry.calls).toEqual(["whoami"]);
109
- expect(lines).toContain(
259
+ expect(registry.posts).toEqual([]);
260
+ expect(output).toContain(
110
261
  "[dry run] npm publish ./projects/scribe/scribe-console --access public --tag dev",
111
262
  );
263
+ expect(output).toContain(
264
+ "[dry run] copy the Trusted Publisher for promote-latest.yml to @decohere/http-fastify",
265
+ );
112
266
  });
113
267
 
114
268
  it("stops when not logged in, or for a name that is not a package", async () => {
@@ -118,8 +272,20 @@ describe("npm-bootstrap", () => {
118
272
  expect(loggedOut.calls).toEqual(["whoami"]);
119
273
 
120
274
  const typo = fakeNpm();
121
- const { code, lines } = await run(["@decohere/scribe-consol"], typo);
275
+ const { code, output } = await run(["--otp", "1", "@decohere/scribe-consol"], typo);
122
276
  expect(code).toBe(1);
123
- expect(lines).toEqual(["Not a publishable package in projects/: @decohere/scribe-consol"]);
277
+ expect(output).toBe("Not a publishable package in projects/: @decohere/scribe-consol");
278
+ });
279
+
280
+ it("never prints the login", async () => {
281
+ seedWorkspace();
282
+ const registry = fakeNpm({
283
+ packages: { "@decohere/cli": FULL, "@decohere/http-fastify": [PUBLISH] },
284
+ failPosting: ["@decohere/http-fastify"],
285
+ });
286
+
287
+ const { output } = await run(["--otp", "1"], registry);
288
+
289
+ expect(output).not.toContain(LOGIN);
124
290
  });
125
291
  });
@@ -1,139 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * Gives every public @decohere package the Trusted Publisher `promote-latest.yml` needs, by copying
4
- * it from one package an owner set up on npmjs.com. `npm trust` has no flag for the "Allow npm
5
- * dist-tag" permission (`manageDistTags` in the registry), so this calls the same registry endpoint
6
- * it uses. npm doesn't document that endpoint. It only adds entries, and packages that already have
7
- * one are skipped.
8
- *
9
- * Reads the owner's npm login from NPM_TOKEN, and never prints it.
10
- *
11
- * NPM_TOKEN="$(sed -n 's#^//registry.npmjs.org/:_authToken=##p' ~/.npmrc)" \
12
- * pnpm npm:trust-promote --otp <code> [--from @decohere/cli]
13
- */
14
- import { resolve } from "node:path";
15
- import { pathToFileURL } from "node:url";
16
- import { parseArgs } from "node:util";
17
- import { listPublishablePackages } from "./publish-verify.mjs";
18
-
19
- export const PROMOTE_WORKFLOW = "promote-latest.yml";
20
- const REGISTRY = "https://registry.npmjs.org";
21
-
22
- /**
23
- * @typedef {{ type?: string, claims?: { workflow_ref?: { file?: string } }, permissions?: string[] }} TrustEntry
24
- */
25
-
26
- /**
27
- * @param {TrustEntry[]} entries
28
- * @returns {TrustEntry | undefined}
29
- */
30
- function findPromoteEntry(entries) {
31
- return entries.find((entry) => entry.claims?.workflow_ref?.file === PROMOTE_WORKFLOW);
32
- }
33
-
34
- /**
35
- * @param {{
36
- * packages: string[],
37
- * from: string,
38
- * token: string,
39
- * otp: string,
40
- * fetch: typeof globalThis.fetch,
41
- * log?: (message: string) => void,
42
- * }} options
43
- * @returns {Promise<number>} exit code
44
- */
45
- export async function copyPromoteTrust(options) {
46
- const { packages, from, token, otp, fetch } = options;
47
- const log = options.log ?? console.log;
48
- const headers = {
49
- authorization: `Bearer ${token}`,
50
- "npm-otp": otp,
51
- "content-type": "application/json",
52
- };
53
- const trustUrl = (name) => `${REGISTRY}/-/package/${name.replace("/", "%2f")}/trust`;
54
-
55
- const list = async (name) => {
56
- const response = await fetch(trustUrl(name), { headers });
57
- if (!response.ok) {
58
- throw new Error(`reading ${name}: ${response.status} ${await response.text()}`);
59
- }
60
- return /** @type {TrustEntry[]} */ (await response.json());
61
- };
62
-
63
- let source;
64
- try {
65
- source = findPromoteEntry(await list(from));
66
- } catch (error) {
67
- log(`Nothing changed. ${String(error)}`);
68
- return 1;
69
- }
70
- if (source == null) {
71
- log(
72
- `${from} has no Trusted Publisher for ${PROMOTE_WORKFLOW}. On npmjs.com, in its settings, add ` +
73
- `one: GitHub Actions, organization typesmiths, repository decohere, workflow ${PROMOTE_WORKFLOW}, ` +
74
- "no environment, Allow npm publish off, Allow npm dist-tag on. Then run this again. " +
75
- "If you set it up on another package, pass that one with --from. Nothing changed.",
76
- );
77
- return 1;
78
- }
79
- log(`Copying from ${from}, with permissions: ${(source.permissions ?? []).join(", ")}`);
80
-
81
- const entry = { type: source.type, claims: source.claims, permissions: source.permissions };
82
- const others = packages.filter((name) => name !== from);
83
- const failures = [];
84
- // All at once, so one OTP code covers them before it expires.
85
- await Promise.all(
86
- others.map(async (name) => {
87
- try {
88
- if (findPromoteEntry(await list(name)) != null) {
89
- log(`already set: ${name}`);
90
- return;
91
- }
92
- const response = await fetch(trustUrl(name), {
93
- method: "POST",
94
- headers,
95
- body: JSON.stringify([entry]),
96
- });
97
- if (!response.ok) {
98
- failures.push(`${name}: ${response.status} ${await response.text()}`);
99
- return;
100
- }
101
- log(`set: ${name}`);
102
- } catch (error) {
103
- failures.push(`${name}: ${String(error)}`);
104
- }
105
- }),
106
- );
107
-
108
- if (failures.length > 0) {
109
- log(`Failed:\n${failures.join("\n")}\nRun it again with a new code to finish.`);
110
- return 1;
111
- }
112
- log(`Done: ${packages.length} packages have a Trusted Publisher for ${PROMOTE_WORKFLOW}.`);
113
- return 0;
114
- }
115
-
116
- if (process.argv[1] != null && import.meta.url === pathToFileURL(process.argv[1]).href) {
117
- const { values } = parseArgs({
118
- options: {
119
- otp: { type: "string" },
120
- from: { type: "string", default: "@decohere/cli" },
121
- },
122
- });
123
- const token = process.env.NPM_TOKEN;
124
- if (!token || !values.otp) {
125
- console.error(
126
- `Usage: NPM_TOKEN="$(sed -n 's#^//registry.npmjs.org/:_authToken=##p' ~/.npmrc)" pnpm npm:trust-promote --otp <code>`,
127
- );
128
- process.exit(1);
129
- }
130
- process.exit(
131
- await copyPromoteTrust({
132
- packages: listPublishablePackages(resolve(".")).map((pkg) => pkg.name),
133
- from: values.from,
134
- token,
135
- otp: values.otp,
136
- fetch: globalThis.fetch,
137
- }),
138
- );
139
- }