@jonmilner/local-ci 0.7.0 → 0.9.0

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/README.md CHANGED
@@ -10,23 +10,18 @@ pnpm add -D @jonmilner/local-ci
10
10
 
11
11
  Needs `gh` logged in with the `repo` scope (`gh auth login --scopes repo`, or `gh auth refresh --scopes repo`).
12
12
 
13
- Add the hook, for example as `.githooks/pre-push` with `git config core.hooksPath .githooks`:
13
+ Point `core.hooksPath` at the repo's hooks directory (Vite+ repos get `.vite-hooks/_` from `vp config` in `prepare`; elsewhere, for example, `git config core.hooksPath .githooks`), then write the hooks and commit them:
14
14
 
15
15
  ```sh
16
- #!/bin/sh
17
- exec pnpm exec local-ci pre-push "$@"
16
+ pnpm exec local-ci hooks install
18
17
  ```
19
18
 
20
- To lint commit messages as you write them, add `.githooks/commit-msg`:
21
-
22
- ```sh
23
- #!/bin/sh
24
- exec local-ci commit-msg "$1"
25
- ```
19
+ That writes `pre-push` and `commit-msg` shims, each one line that calls local-ci, so every repo runs the same checks and none hand-writes its hooks. `local-ci pre-push` refuses a push when either is missing.
26
20
 
27
21
  ## Commands
28
22
 
29
- - `local-ci pre-push`: the hook. For each commit pushed to a branch (deletes and tags are skipped) that has not already passed, runs the check command. The pushed commit must be `HEAD` with a clean working tree (`git status --porcelain` empty), so the result reflects the commit; otherwise the push is refused. A failing check blocks the push. When every commit passes, it starts `local-ci post <sha>` in the background, aimed at the pushed remote, and lets the push go ahead.
23
+ - `local-ci hooks install`: writes executable `#!/bin/sh` `pre-push` and `commit-msg` shims into the hooks directory: `core.hooksPath`, resolved against the repo root, with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, and an absolute path into the main checkout mapped onto the current worktree. Each shim is one line: `pnpm exec local-ci pre-push "$@"` and `pnpm exec local-ci commit-msg "$1"` in a repo with a `package.json`, a global `local-ci …` without one, or `"local-ci": { "exec": "<command>" }` in `package.json` in place of `pnpm exec local-ci` (this repo runs local-ci from source that way). An existing shell hook keeps its other lines and gains the shim line, at the end, only when no line already runs `local-ci pre-push` (or `commit-msg`), so a line with an env prefix such as `LOCAL_CI_COMMAND=… local-ci pre-push "$@"` counts. It prints each file it wrote, or `hooks up to date`; a second run changes nothing. It exits 1 without `core.hooksPath` or with one outside the repo's tracked files (including `.git/hooks`), and for an existing hook in another language (a `node` or `python` shebang), naming the line to add by hand. Run it by hand and commit the result; `prepare` does not run it.
24
+ - `local-ci pre-push`: the hook. It first checks that both hook files are in place, as `local-ci hooks install` would leave them, and refuses the push otherwise (``hooks out of date: <file> must run local-ci; run `<command> hooks install` and commit the result``), so a repo's hooks can't drift. For each commit pushed to a branch (deletes and tags are skipped) that has not already passed, runs the check command. The pushed commit must be `HEAD` with a clean working tree (`git status --porcelain` empty), so the result reflects the commit; otherwise the push is refused. A failing check blocks the push. When every commit passes, it starts `local-ci post <sha>` in the background, aimed at the pushed remote, and lets the push go ahead.
30
25
  - `local-ci commit-msg <file>`: lints the commit message in `<file>` with `@jonmilner/commitlint-config`, for a git `commit-msg` hook (git passes `.git/COMMIT_EDITMSG`). `local-ci commit-msg -` reads the message from stdin, for PR titles. Comment lines (starting with `#`) and everything after a `# ------------------------ >8 ------------------------` scissors line are stripped first; merge commits, `fixup!`/`squash!` and reverts are skipped. Each error or warning goes to stderr as `commit-msg: <message> [<rule>]`, followed by the offending header; it exits 1 when there are errors (warnings alone exit 0), and 2 when no file is given. It makes no network, git or GitHub calls.
31
26
  - `local-ci post <sha>`: waits up to 3 minutes for GitHub to have the commit, posts status `check` = `success` (`<command> passed on <hostname>`), then posts `pr-title` on it for an open PR that contains it (waiting up to 30s for GitHub to link them). A PR opened after the push, or a retitled one, needs `local-ci pr-title` run by hand.
32
27
  - `local-ci pr-title [<pr>]`: lints the PR title (the current branch's PR by default) with `@jonmilner/commitlint-config` and posts status `pr-title` on its head commit, `failure` with the first error when the title does not pass.
@@ -36,7 +31,7 @@ exec local-ci commit-msg "$1"
36
31
  2. At the merge commit (or the default branch, with no changesets pending), it runs `local-ci status`, then `pnpm release` with the npm token, then pushes the tags `changeset publish` created.
37
32
  3. It checks each published `name@version` with `npm view`, waiting up to 5 minutes in all for the registry to list them. A timeout or `npm view` error here exits non-zero, but the publish already ran: check with the `npm view` command the error gives before rerunning.
38
33
 
39
- A failure after the push closes the PR and deletes `release/<short-sha>`; Ctrl-C (SIGINT), SIGTERM, SIGHUP (closing the terminal) or Ctrl-\\ (SIGQUIT) stops the running step (killing `pnpm release` and the publish it started), does the same cleanup, then exits 128 + the signal number, e.g. 130 for Ctrl-C (a second signal exits at once, killing the publish outright). A run killed outright leaves its temp worktree and local branch, which the next run removes; its PR and remote branch stay open for you to close. Step 2 runs even with no changesets pending, so a rerun after a failed publish finishes the job. If npm refuses the publish because it already has the version (a rerun while the registry still lags), it says so with the `npm view` command to check, instead of blaming the token; rerun once npm lists it. With nothing pending and every version already on npm it prints `nothing to release`. The repo needs changesets and a root `release` script (for example `pnpm build && changeset publish`). The npm token comes from the macOS Keychain (service `local-ci-npm`) and is passed only in `pnpm release`'s environment, never written to `.npmrc` or logged; see [npm publish token](../../docs/new-machine.md#npm-publish-token).
34
+ A failure after the push closes the PR and deletes `release/<short-sha>`; Ctrl-C (SIGINT), SIGTERM, SIGHUP (closing the terminal) or Ctrl-\\ (SIGQUIT) stops the running step (killing `pnpm release` and the publish it started), does the same cleanup, then exits 128 + the signal number, e.g. 130 for Ctrl-C (a second signal exits at once, killing the publish outright). A run killed outright leaves its temp worktree and local branch, which the next run removes; its PR and remote branch stay open for you to close. Step 2 runs even with no changesets pending, so a rerun after a failed publish finishes the job. If npm refuses the publish because it already has the version (a rerun while the registry still lags), it says so with the `npm view` command to check, instead of blaming the token; rerun once npm lists it. With nothing pending and every version already on npm it prints `nothing to release`. The repo needs changesets and a root `release` script (for example `pnpm build && changeset publish`). The npm token is `$NPM_TOKEN_JONMILNER` if set, else `secret get NPM_TOKEN_JONMILNER` (with neither, it stops before changing anything); within 14 days of the expiry date `secret list` gives it, the run prints a one-line warning and carries on. The token is passed only in `pnpm release`'s environment, never written to `.npmrc` or logged; see [npm publish token](../../docs/new-machine.md#npm-publish-token).
40
35
 
41
36
  - `local-ci renovate`: posts `check` and `pr-title` on Renovate PRs, which no push from this machine ever covers. It finds every open PR the Renovate app opened in the `gh` user's repos (`gh search prs --author app/renovate`) and takes only those on a `renovate/**` branch of the repo itself; any other PR is left to its own push. For each, from the clone at `~/git/<repo>` (`LOCAL_CI_PROJECTS` overrides `~/git`) whose `origin` is that repo, it:
42
37
  - skips a repo with no such clone, logging why;
@@ -57,7 +52,7 @@ exec local-ci commit-msg "$1"
57
52
  { "local-ci": { "command": "pnpm lint && pnpm test" } }
58
53
  ```
59
54
 
60
- A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example in the hook: `LOCAL_CI_COMMAND=./scripts/check.sh exec local-ci pre-push "$@"`.
55
+ A repo without a `package.json` sets `LOCAL_CI_COMMAND`, for example on the hook's line: `LOCAL_CI_COMMAND=./scripts/check.sh local-ci pre-push "$@"`.
61
56
 
62
57
  ## State
63
58
 
package/dist/cli.js CHANGED
@@ -2,16 +2,17 @@
2
2
  import { execFileSync, spawn } from "node:child_process";
3
3
  import { closeSync, openSync, readFileSync } from "node:fs";
4
4
  import { hostname } from "node:os";
5
- import { basename, dirname, resolve } from "node:path";
5
+ import { basename, dirname, join, relative, resolve } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { commitMsg } from "./commit-msg.js";
8
- import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, statePaths, } from "./config.js";
8
+ import { appendLog, checkRunMessage, logLine, passedCommand, recordPass, releaseEnabled, resolveCommand, shimCommand, statePaths, } from "./config.js";
9
9
  import { exec, run } from "./exec.js";
10
10
  import { assertGhAuth, checkStatus, postStatus, prTitleStatus, viewPr, waitForCommit, waitForOpenPr, } from "./github.js";
11
+ import { hooksDir, installHooks, missingHooks } from "./hooks.js";
11
12
  import { installRenovateAgent, renovateLog, rotateLog, uninstallRenovateAgent } from "./launchd.js";
12
13
  import { LockHeld, takeLock, waitForLock } from "./lock.js";
13
14
  import { cannotCheckInPlace, githubRepo, parsePrePush, shasToCheck } from "./push.js";
14
- import { release } from "./release.js";
15
+ import { release, takeEnvToken } from "./release.js";
15
16
  import { projectsDir, renovate } from "./renovate.js";
16
17
  import { lintTitle } from "./title.js";
17
18
  const USAGE = `Usage:
@@ -20,6 +21,7 @@ const USAGE = `Usage:
20
21
  local-ci pr-title [<pr>] lint the PR title and post the pr-title status
21
22
  local-ci commit-msg <file|->
22
23
  lint a commit message file (git commit-msg hook) or stdin (-)
24
+ local-ci hooks install write the repo's pre-push and commit-msg hook shims
23
25
  local-ci status [<sha>] post check for <sha> (default HEAD), running the check if needed
24
26
  local-ci release version pending changesets through a PR, publish to npm and push tags
25
27
  local-ci renovate check each open Renovate PR in your repos and post check and pr-title
@@ -197,9 +199,36 @@ async function runLocked({ root, passed, log: logFile }, sha) {
197
199
  throw new CheckFailed(command, sha);
198
200
  recordPass(passed, sha, command);
199
201
  }
202
+ /** The repo root, its hooks directory, and the command its hook shims run local-ci with. */
203
+ async function hooksTarget(root) {
204
+ // `git config --get` exits 1 when the key is unset.
205
+ const hooksPath = await git("config", "--type=path", "--get", "core.hooksPath").catch(() => "");
206
+ // A linked worktree's main checkout is the directory holding the common `.git` dir.
207
+ const common = resolve(root, await git("rev-parse", "--git-common-dir"));
208
+ const mainRoot = basename(common) === ".git" ? dirname(common) : root;
209
+ return { dir: hooksDir(root, hooksPath || undefined, mainRoot), command: shimCommand(root) };
210
+ }
211
+ /** Throws, naming the fix, unless both hook files run local-ci, so no repo's hooks drift. */
212
+ async function assertHooks(root) {
213
+ const { dir, command } = await hooksTarget(root);
214
+ const missing = missingHooks(dir, command).map((hook) => relative(root, join(dir, hook)));
215
+ if (missing.length) {
216
+ throw new Error(`hooks out of date: ${missing.join(" and ")} must run local-ci; run \`${command} hooks install\` and commit the result`);
217
+ }
218
+ }
219
+ async function runHooks([subcommand, ...extra]) {
220
+ if (subcommand !== "install" || extra.length) {
221
+ throw new Error(`hooks: expected install\n${USAGE}`);
222
+ }
223
+ const { root } = await repo();
224
+ const { dir, command } = await hooksTarget(root);
225
+ const changes = installHooks(root, dir, command);
226
+ out(changes.length ? changes.join("\n") : "hooks up to date");
227
+ }
200
228
  async function prePush(remoteUrl) {
201
- await assertGhAuth(exec);
202
229
  const current = await repo();
230
+ await assertHooks(current.root);
231
+ await assertGhAuth(exec);
203
232
  const shas = shasToCheck(parsePrePush(readFileSync(0, "utf8")));
204
233
  // Check every commit before posting any, so a refused push posts nothing.
205
234
  for (const sha of shas)
@@ -270,12 +299,21 @@ async function status(ref = "HEAD") {
270
299
  await post(current, sha);
271
300
  }
272
301
  async function runRelease() {
302
+ // First, before any child process runs.
303
+ const envToken = takeEnvToken();
273
304
  const { root, lock } = await repo();
274
305
  // Off by default, so a repo that publishes some other way can't release by accident.
275
306
  if (!releaseEnabled(root))
276
307
  return out("release not enabled");
277
308
  await assertGhAuth(exec);
278
- out(await release(exec, { root, lock, cli: fileURLToPath(import.meta.url), prTitle, log }));
309
+ out(await release(exec, {
310
+ root,
311
+ lock,
312
+ cli: fileURLToPath(import.meta.url),
313
+ prTitle,
314
+ log,
315
+ envToken,
316
+ }));
279
317
  }
280
318
  async function runRenovate([flag, ...extra]) {
281
319
  const cli = fileURLToPath(import.meta.url);
@@ -309,6 +347,8 @@ async function main([command, ...args]) {
309
347
  process.exitCode = 1;
310
348
  return;
311
349
  }
350
+ if (command === "hooks")
351
+ return runHooks(args);
312
352
  if (command === "release")
313
353
  return runRelease();
314
354
  if (command === "renovate")
package/dist/config.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  export declare const DEFAULT_COMMAND = "pnpm check";
2
2
  /** The check command: `local-ci.command` in package.json, else `LOCAL_CI_COMMAND`, else `pnpm check`. */
3
3
  export declare function resolveCommand(root: string, env?: NodeJS.ProcessEnv): string;
4
+ /**
5
+ * The command hook shims run local-ci with: `local-ci.exec` in package.json, else
6
+ * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
7
+ */
8
+ export declare function shimCommand(root: string): string;
4
9
  /** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
5
10
  export declare function releaseEnabled(root: string): boolean;
6
11
  export declare function stateDir(env?: NodeJS.ProcessEnv): string;
package/dist/config.js CHANGED
@@ -17,6 +17,16 @@ export function resolveCommand(root, env = process.env) {
17
17
  return command;
18
18
  return env.LOCAL_CI_COMMAND?.trim() || DEFAULT_COMMAND;
19
19
  }
20
+ /**
21
+ * The command hook shims run local-ci with: `local-ci.exec` in package.json, else
22
+ * `pnpm exec local-ci` in a repo with a package.json, else a global `local-ci`.
23
+ */
24
+ export function shimCommand(root) {
25
+ if (!existsSync(join(root, "package.json")))
26
+ return "local-ci";
27
+ const { exec } = localCiConfig(root);
28
+ return typeof exec === "string" && exec.trim() ? exec.trim() : "pnpm exec local-ci";
29
+ }
20
30
  /** Whether `local-ci release` is switched on, with `"local-ci": { "release": true }` in package.json. */
21
31
  export function releaseEnabled(root) {
22
32
  return localCiConfig(root).release === true;
@@ -0,0 +1,29 @@
1
+ /** The git hooks local-ci owns, each with the arguments its shim passes on. */
2
+ declare const HOOKS: {
3
+ readonly "pre-push": "\"$@\"";
4
+ readonly "commit-msg": "\"$1\"";
5
+ };
6
+ export type Hook = keyof typeof HOOKS;
7
+ /**
8
+ * The directory holding the repo's hook files: `core.hooksPath` resolved against the repo root,
9
+ * with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, which holds the hooks it runs.
10
+ * An absolute path into the main checkout (`mainRoot`) maps onto `root`, so a linked worktree
11
+ * finds its own copy of the tracked hooks.
12
+ */
13
+ export declare function hooksDir(root: string, hooksPath: string | undefined, mainRoot?: string): string;
14
+ /** The line a shim adds to run local-ci's `hook` with `command`, e.g. `pnpm exec local-ci pre-push "$@"`. */
15
+ export declare function shimLine(hook: Hook, command: string): string;
16
+ /**
17
+ * Whether `content` has a line, other than a comment, that runs `local-ci <hook>` or
18
+ * `<command> <hook>`. Anything may come before it on the line, such as `LOCAL_CI_COMMAND=… `.
19
+ */
20
+ export declare function runsHook(content: string, hook: Hook, command: string): boolean;
21
+ /** The hooks in `dir` whose file is missing or has no line running local-ci for it. */
22
+ export declare function missingHooks(dir: string, command: string): Hook[];
23
+ /**
24
+ * Writes an executable `#!/bin/sh` shim for each hook into `dir`, or adds its line to the end of an
25
+ * existing shell script, keeping every other line. Throws for an existing hook in another language.
26
+ * Returns what changed, with paths relative to `root`; none when every hook was already in place.
27
+ */
28
+ export declare function installHooks(root: string, dir: string, command: string): string[];
29
+ export {};
package/dist/hooks.js ADDED
@@ -0,0 +1,92 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ /** The git hooks local-ci owns, each with the arguments its shim passes on. */
4
+ const HOOKS = { "pre-push": '"$@"', "commit-msg": '"$1"' };
5
+ const HOOK_NAMES = Object.keys(HOOKS);
6
+ /**
7
+ * The directory holding the repo's hook files: `core.hooksPath` resolved against the repo root,
8
+ * with a Vite+ (or husky) `<dir>/_` dispatcher mapped to `<dir>`, which holds the hooks it runs.
9
+ * An absolute path into the main checkout (`mainRoot`) maps onto `root`, so a linked worktree
10
+ * finds its own copy of the tracked hooks.
11
+ */
12
+ export function hooksDir(root, hooksPath, mainRoot = root) {
13
+ if (!hooksPath) {
14
+ throw new Error("core.hooksPath is not set; point it at the repo's hooks directory (`vp config` does in a Vite+ repo, or `git config core.hooksPath .githooks`), then run local-ci hooks install");
15
+ }
16
+ let resolved = resolve(root, hooksPath);
17
+ if (isAbsolute(hooksPath) && !within(root, resolved) && within(mainRoot, resolved)) {
18
+ resolved = join(root, relative(mainRoot, resolved));
19
+ }
20
+ const dir = basename(resolved) === "_" ? dirname(resolved) : resolved;
21
+ const inside = relative(root, dir);
22
+ if (!within(root, dir) || inside === ".git" || inside.startsWith(`.git${sep}`)) {
23
+ throw new Error(`core.hooksPath ${hooksPath} is outside the repo's tracked files; local-ci's hooks must be committed, so point it at a directory in the repo`);
24
+ }
25
+ return dir;
26
+ }
27
+ /** Whether `path` is strictly inside `dir`. */
28
+ function within(dir, path) {
29
+ const inside = relative(dir, path);
30
+ return Boolean(inside) && !inside.startsWith("..") && !isAbsolute(inside);
31
+ }
32
+ /** The line a shim adds to run local-ci's `hook` with `command`, e.g. `pnpm exec local-ci pre-push "$@"`. */
33
+ export function shimLine(hook, command) {
34
+ return `${command} ${hook} ${HOOKS[hook]}`;
35
+ }
36
+ /** A shebang for a shell that can run the shim line. */
37
+ const SHELL = /^#!.*\b(?:sh|bash|dash|zsh|ksh)\b/;
38
+ const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
39
+ /**
40
+ * Whether `content` has a line, other than a comment, that runs `local-ci <hook>` or
41
+ * `<command> <hook>`. Anything may come before it on the line, such as `LOCAL_CI_COMMAND=… `.
42
+ */
43
+ export function runsHook(content, hook, command) {
44
+ const runner = [...new Set(["local-ci", command])].map(escape).join("|");
45
+ const pattern = new RegExp(`(?:^|[\\s/])(?:${runner})\\s+${hook}(?:\\s|$)`);
46
+ return content
47
+ .split("\n")
48
+ .some((line) => !line.trimStart().startsWith("#") && pattern.test(line));
49
+ }
50
+ /** The hooks in `dir` whose file is missing or has no line running local-ci for it. */
51
+ export function missingHooks(dir, command) {
52
+ return HOOK_NAMES.filter((hook) => {
53
+ const file = join(dir, hook);
54
+ return !existsSync(file) || !runsHook(readFileSync(file, "utf8"), hook, command);
55
+ });
56
+ }
57
+ /**
58
+ * Writes an executable `#!/bin/sh` shim for each hook into `dir`, or adds its line to the end of an
59
+ * existing shell script, keeping every other line. Throws for an existing hook in another language.
60
+ * Returns what changed, with paths relative to `root`; none when every hook was already in place.
61
+ */
62
+ export function installHooks(root, dir, command) {
63
+ mkdirSync(dir, { recursive: true });
64
+ const changes = [];
65
+ for (const hook of HOOK_NAMES) {
66
+ const file = join(dir, hook);
67
+ const shown = relative(root, file);
68
+ const before = existsSync(file) ? readFileSync(file, "utf8") : "";
69
+ if (before.startsWith("#!") && !SHELL.test(before)) {
70
+ throw new Error(`${shown} is not a shell script; add \`${shimLine(hook, command)}\` to it by hand`);
71
+ }
72
+ let after = before;
73
+ if (!runsHook(after, hook, command)) {
74
+ const separator = after && !after.endsWith("\n") ? "\n" : "";
75
+ after = `${after}${separator}${shimLine(hook, command)}\n`;
76
+ }
77
+ // Git runs a hook file directly unless a dispatcher like Vite+'s runs it with sh.
78
+ if (!after.startsWith("#!"))
79
+ after = `#!/bin/sh\n${after}`;
80
+ if (after !== before)
81
+ writeFileSync(file, after);
82
+ const { mode } = statSync(file);
83
+ const executable = (mode & 0o100) !== 0;
84
+ if (!executable)
85
+ chmodSync(file, mode | 0o755);
86
+ if (after !== before)
87
+ changes.push(before ? `updated ${shown}` : `wrote ${shown}`);
88
+ else if (!executable)
89
+ changes.push(`made ${shown} executable`);
90
+ }
91
+ return changes;
92
+ }
package/dist/release.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { type Exec } from "./exec.ts";
2
2
  import { type WaitOptions } from "./github.ts";
3
- /** The macOS Keychain generic password that holds the npm token. */
4
- export declare const TOKEN_SERVICE = "local-ci-npm";
3
+ /** The npm token's name, both as an environment variable and in the `secret` store. */
4
+ export declare const TOKEN_NAME = "NPM_TOKEN_JONMILNER";
5
+ /** How many days ahead of the token's expiry a release starts warning. */
6
+ export declare const EXPIRY_WARN_DAYS = 14;
5
7
  /** npm and pnpm read a registry token from this variable; it is set only for `pnpm release`. */
6
8
  export declare const TOKEN_ENV = "NPM_CONFIG_//registry.npmjs.org/:_authToken";
7
9
  export interface Package {
@@ -16,8 +18,28 @@ export declare function versionCommand(dir: string): string[];
16
18
  export declare function publicPackages(exec: Exec, dir: string): Promise<Package[]>;
17
19
  /** Whether npm has this exact version. A 404 means no; any other error is thrown. */
18
20
  export declare function isPublished(exec: Exec, pkg: Package): Promise<boolean>;
19
- /** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
20
- export declare function readToken(exec: Exec): Promise<string>;
21
+ export interface Token {
22
+ value: string;
23
+ /** Where it came from, for the message when npm rejects it. */
24
+ source: string;
25
+ }
26
+ /**
27
+ * The warning for a token in the `secret` store that expires within EXPIRY_WARN_DAYS or has
28
+ * expired, from `secret list` (names and expiry dates, never values). Nothing when `secret list`
29
+ * fails or gives the token no expiry, since the warning is advice and local-ci needs no store.
30
+ */
31
+ export declare function expiryWarning(exec: Exec, now?: Date): Promise<string | undefined>;
32
+ /**
33
+ * The npm token: $NPM_TOKEN_JONMILNER if set, else `secret get NPM_TOKEN_JONMILNER`, warning
34
+ * through `log` when the stored one is near expiry. Fails with the setup doc when neither has it.
35
+ * Removes the variable from `env`, so only `pnpm release` gets the token, not every child.
36
+ */
37
+ /**
38
+ * Takes $NPM_TOKEN_JONMILNER out of `env`, so no child the release runs (git, npm, the pre-push
39
+ * hook) inherits it; only `pnpm release` gets the token, under npm's own variable.
40
+ */
41
+ export declare function takeEnvToken(env?: NodeJS.ProcessEnv): string | undefined;
42
+ export declare function readToken(exec: Exec, log: (message: string) => void, env?: NodeJS.ProcessEnv, now?: Date): Promise<Token>;
21
43
  /**
22
44
  * Polls npm until each package is visible. The registry can take minutes to list a version
23
45
  * after a publish, so a timeout here means the publish ran but npm hasn't caught up yet.
@@ -32,6 +54,8 @@ export interface ReleaseContext {
32
54
  /** Lints the PR title and posts `pr-title`, resolving false when the title fails. */
33
55
  prTitle: (pr: string) => Promise<boolean>;
34
56
  log: (message: string) => void;
57
+ /** $NPM_TOKEN_JONMILNER, taken out of process.env by takeEnvToken before the CLI ran anything. */
58
+ envToken?: string;
35
59
  }
36
60
  /**
37
61
  * Versions pending changesets through a merged PR, publishes what npm lacks, pushes the tags and
package/dist/release.js CHANGED
@@ -5,8 +5,10 @@ import { basename, dirname, join } from "node:path";
5
5
  import { run } from "./exec.js";
6
6
  import { defaultSleep, waitForStatuses } from "./github.js";
7
7
  import { takeLock } from "./lock.js";
8
- /** The macOS Keychain generic password that holds the npm token. */
9
- export const TOKEN_SERVICE = "local-ci-npm";
8
+ /** The npm token's name, both as an environment variable and in the `secret` store. */
9
+ export const TOKEN_NAME = "NPM_TOKEN_JONMILNER";
10
+ /** How many days ahead of the token's expiry a release starts warning. */
11
+ export const EXPIRY_WARN_DAYS = 14;
10
12
  /** npm and pnpm read a registry token from this variable; it is set only for `pnpm release`. */
11
13
  export const TOKEN_ENV = "NPM_CONFIG_//registry.npmjs.org/:_authToken";
12
14
  const SETUP_DOC = "https://github.com/jonmilner/config/blob/main/docs/new-machine.md#npm-publish-token";
@@ -56,19 +58,74 @@ async function unpublished(exec, packages) {
56
58
  const published = await Promise.all(packages.map((pkg) => isPublished(exec, pkg)));
57
59
  return packages.filter((_, index) => !published[index]);
58
60
  }
59
- /** Reads the npm token from the Keychain, failing with the setup doc when it is missing. */
60
- export async function readToken(exec) {
61
- let token = "";
61
+ const ROTATE = `secret set ${TOKEN_NAME} --expires <YYYY-MM-DD>`;
62
+ const DAY_MS = 86_400_000;
63
+ /**
64
+ * The warning for a token in the `secret` store that expires within EXPIRY_WARN_DAYS or has
65
+ * expired, from `secret list` (names and expiry dates, never values). Nothing when `secret list`
66
+ * fails or gives the token no expiry, since the warning is advice and local-ci needs no store.
67
+ */
68
+ export async function expiryWarning(exec, now = new Date()) {
69
+ let listing;
62
70
  try {
63
- token = (await exec("security", ["find-generic-password", "-s", TOKEN_SERVICE, "-w"])).trim();
71
+ listing = await exec("secret", ["list"]);
64
72
  }
65
73
  catch {
66
- // Not found, or the Keychain is locked: either way there is no token to use.
74
+ return undefined;
75
+ }
76
+ const line = listing.split("\n").find((entry) => entry.startsWith(`${TOKEN_NAME}\t`));
77
+ const date = /\texpire[sd] (\d{4}-\d{2}-\d{2})\b/.exec(line ?? "")?.[1];
78
+ if (!date)
79
+ return undefined;
80
+ const [year, month, day] = date.split("-").map(Number);
81
+ // Calendar days in the local date, as `secret list` counts them, so the time of day doesn't matter.
82
+ const today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
83
+ const days = Math.round((Date.UTC(year, month - 1, day) - today) / DAY_MS);
84
+ if (days < 0) {
85
+ return `warning: the npm token ${TOKEN_NAME} expired ${date}, so npm will likely reject it; rotate it with: ${ROTATE} (${SETUP_DOC})`;
86
+ }
87
+ if (days > EXPIRY_WARN_DAYS)
88
+ return undefined;
89
+ const left = days === 0 ? "today" : `in ${days} day${days === 1 ? "" : "s"}`;
90
+ return `warning: the npm token ${TOKEN_NAME} expires ${date} (${left}); rotate it with: ${ROTATE} (${SETUP_DOC})`;
91
+ }
92
+ /**
93
+ * The npm token: $NPM_TOKEN_JONMILNER if set, else `secret get NPM_TOKEN_JONMILNER`, warning
94
+ * through `log` when the stored one is near expiry. Fails with the setup doc when neither has it.
95
+ * Removes the variable from `env`, so only `pnpm release` gets the token, not every child.
96
+ */
97
+ /**
98
+ * Takes $NPM_TOKEN_JONMILNER out of `env`, so no child the release runs (git, npm, the pre-push
99
+ * hook) inherits it; only `pnpm release` gets the token, under npm's own variable.
100
+ */
101
+ export function takeEnvToken(env = process.env) {
102
+ const value = env[TOKEN_NAME];
103
+ delete env[TOKEN_NAME];
104
+ return value;
105
+ }
106
+ export async function readToken(exec, log, env = process.env, now = new Date()) {
107
+ const fromEnv = env[TOKEN_NAME]?.trim();
108
+ delete env[TOKEN_NAME];
109
+ if (fromEnv)
110
+ return { value: fromEnv, source: `$${TOKEN_NAME}` };
111
+ let value = "";
112
+ let reason = "";
113
+ try {
114
+ value = (await exec("secret", ["get", TOKEN_NAME])).trim();
115
+ }
116
+ catch (error) {
117
+ // Not installed, no such name, or the store won't decrypt: none of them gives a token.
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ // Only the spawn's own ENOENT; one in secret's stderr is a file it lacks, shown as is.
120
+ reason = /\bspawn secret ENOENT\b/.test(message) ? "secret is not installed" : message;
67
121
  }
68
- if (!token) {
69
- throw new Error(`no npm token in the macOS Keychain (service ${TOKEN_SERVICE}). Create and store one: ${SETUP_DOC}`);
122
+ if (!value) {
123
+ throw new Error(`no npm token: $${TOKEN_NAME} is unset and \`secret get ${TOKEN_NAME}\` gave none${reason ? ` (${reason})` : ""}. Store one with \`${ROTATE}\`: ${SETUP_DOC}`);
70
124
  }
71
- return token;
125
+ const warning = await expiryWarning(exec, now);
126
+ if (warning)
127
+ log(warning);
128
+ return { value, source: `\`secret get ${TOKEN_NAME}\`` };
72
129
  }
73
130
  /** The hint for checking each package on npm by hand. */
74
131
  const npmView = (packages) => packages.length
@@ -85,7 +142,7 @@ function publish(dir, token, packages, signal) {
85
142
  // Its own session and group, so an interrupt stops the publish it started, not just pnpm.
86
143
  detached: true,
87
144
  // CI makes changesets fail on an OTP request instead of prompting on an ignored stdin.
88
- env: { ...process.env, CI: "true", [TOKEN_ENV]: token },
145
+ env: { ...process.env, CI: "true", [TOKEN_ENV]: token.value },
89
146
  stdio: ["ignore", "pipe", "pipe"],
90
147
  });
91
148
  // The group no longer gets the terminal's signals, so these are the only things that stop it.
@@ -141,7 +198,7 @@ function publish(dir, token, packages, signal) {
141
198
  reject(new Error(publishOver
142
199
  ? `npm already has a version this run tried to publish, so it refused to publish over it; the registry may still be catching up on an earlier publish. Rerun once npm lists it; ${npmView(packages)}`
143
200
  : authError
144
- ? `npm rejected the token in the Keychain (service ${TOKEN_SERVICE}); it may have expired or lack "bypass 2FA". Rotate it: ${SETUP_DOC}`
201
+ ? `npm rejected the token from ${token.source}; it may have expired or lack "bypass 2FA". Rotate it with \`${ROTATE}\`: ${SETUP_DOC}`
145
202
  : `pnpm release failed (${code === null ? killed : `exit ${code}`})`));
146
203
  });
147
204
  });
@@ -307,7 +364,7 @@ export async function release(exec, context) {
307
364
  }
308
365
  // Read it before changing anything, so a missing token stops the run with nothing to undo.
309
366
  await live();
310
- const token = await readToken(exec);
367
+ const token = await readToken(exec, log, { [TOKEN_NAME]: context.envToken });
311
368
  if (pending.length) {
312
369
  branch = `release/${await stepGit(dir, "rev-parse", "--short", "HEAD")}`;
313
370
  await pruneStale(stepGit, root, dir, branch);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jonmilner/local-ci",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Run a repo's check in a pre-push hook and post the result as GitHub commit statuses",
5
5
  "license": "MIT",
6
6
  "repository": {