Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ bunx bun-docx read doc.docx # run without installing

Every command works directly on the `.docx` file. Only `docx render` (page images, for checking layout) needs Word (macOS/Windows) or LibreOffice installed.

**Upgrading:** `docx upgrade` replaces a standalone binary in place, using the installer embedded in the binary at build time (never fetched), pinned to a release tag and SHA-256-verified. `docx upgrade --to v0.27.0` pins a version; `--dry-run` reports what would change. It won't touch an npm install (use your package manager) or a renamed binary. On Windows it needs Git Bash (for `sh`); a running `.exe` can be renamed but not overwritten, so the verified binary is swapped in and the old one is left as `docx.exe.old` until the next upgrade.
**Upgrading:** `docx upgrade` replaces a standalone binary in place, using the installer embedded in the binary at build time (never fetched), pinned to a release tag and SHA-256-verified. `docx upgrade --to v0.27.0` pins a version; `--dry-run` reports what would change. It won't touch an npm install (use your package manager) or a renamed binary, and it honors the admin pins `DOCX_CLI_NO_UPDATE=1` / `DOCX_CLI_VERSION`. On Windows it needs Git Bash (for `sh`); a running `.exe` can be renamed but not overwritten, so the verified binary is swapped in and the old one is left as `docx.exe.old` until the next upgrade.

### Use it from your own code

Expand Down
2 changes: 1 addition & 1 deletion REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ docx styles --catalog [--json] # built-in styles you can a
docx styles set FILE --at STYLEID [--bold --color HEX --size PT --font NAME --font-east-asia NAME --font-complex-script NAME --space-before PT --indent-left IN …] # restyle every paragraph/run that uses the style
docx styles create FILE STYLEID [--type paragraph|character] [--name "…"] [--based-on STYLEID] [--next STYLEID] [formatting] # define a new custom style
docx render FILE [--out DIR] [--engine word|libreoffice|auto] [--dpi N] [--pages 1-N] [--format png|jpg]
docx upgrade [--to TAG] [--dry-run] # update the installed binary in place (no FILE)
docx upgrade [--to TAG] [--dry-run] # update the installed binary in place (no FILE); refused under DOCX_CLI_NO_UPDATE=1, or for any target but DOCX_CLI_VERSION

docx comments list FILE [--open] [--thread cN]
docx footnotes list FILE
Expand Down
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Block all of them and every command except remote image insertion still works.
- `DOCX_CLI_VERSION=v0.27.0`: bootstrap installs exactly that release when `docx` is missing and never updates a binary that's already present.
- `DOCX_CLI_NO_UPDATE=1`: bootstrap never updates a binary that's already present. (A missing one still installs, from the latest release; set `DOCX_CLI_VERSION` too to control which.)

These variables govern `bootstrap.sh`, the path the skill sends agents down when either one is set. They don't stop someone from running `docx upgrade` or `npm install -g bun-docx` directly; restrict those through your normal software policy if you need to.
`docx upgrade` honors them too: with `DOCX_CLI_NO_UPDATE=1` it refuses every upgrade, and with `DOCX_CLI_VERSION` it refuses any target except that tag (so `docx upgrade --to v0.27.0` installs the pin and nothing else does). Both refusals exit nonzero, name the variable, and apply to `--dry-run`. The variables don't stop `npm install -g bun-docx` or a hand-run `install.sh`; restrict those through your normal software policy if you need to.

Offline, bootstrap keeps the working binary and exits 0.

Expand Down
7 changes: 7 additions & 0 deletions skills/docx-cli/references/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ The updated release workflow ad-hoc signs and verifies macOS binaries before
generating `SHA256SUMS`; existing release assets are unchanged. Ad-hoc signing
does not provide Developer ID identity or Apple notarization.

## `docx upgrade` refuses with `DOCX_CLI_NO_UPDATE` or `DOCX_CLI_VERSION`

An administrator has pinned the version. `upgrade` honors the same variables as
`bootstrap.sh`: `DOCX_CLI_NO_UPDATE=1` refuses every upgrade, and
`DOCX_CLI_VERSION=vX.Y.Z` allows only `docx upgrade --to vX.Y.Z`. Keep using the
installed binary; don't unset the variable or install around it with npm.

## `docx upgrade` on Windows says `sh` is not on PATH

Upgrade runs its embedded installer with `sh`, so on Windows run it from Git
Expand Down
12 changes: 11 additions & 1 deletion src/cli/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,9 @@ embedded text equals the file on disk.
Install-method detection is `import.meta.path.startsWith("/$bunfs/")` (Bun's virtual FS
for a compiled single-file executable; `~BUN` on Windows). Standalone β†’ self-replace via
install.sh's rename, which works over a running binary on POSIX. Package-manager install
β†’ print `bun add -g bun-docx` and change nothing. Windows locks a running `.exe`
β†’ print `bun add -g bun-docx` (`bun-docx@X.Y.Z` when the target is a tag, so the
advisory can't install latest around a `--to` or a `DOCX_CLI_VERSION` pin) and change
nothing. Windows locks a running `.exe`
against overwrite but not rename, so there install.sh gets `PREFIX=<dir>/.docx-upgrade`
and, only once it exits 0 (downloaded AND checksum-verified), `swapIn`
([upgrade/swap-in.ts](upgrade/swap-in.ts)) renames the running binary to `docx.exe.old`
Expand Down Expand Up @@ -122,6 +124,14 @@ would redirect both the binary and the `SHA256SUMS` it is checked against to ano
repo β€” the checksum gate would then bless the attacker's own manifest. A bare `0.23.0`
(what `docx --version` prints) is normalized to `v0.23.0` rather than 404ing.

Admin pins ([upgrade/admin-pin.ts](upgrade/admin-pin.ts)) mirror bootstrap.sh:
`DOCX_CLI_NO_UPDATE=1` refuses every upgrade, `DOCX_CLI_VERSION` refuses any target but
the pinned tag (`--to` that tag is how the pin gets installed), and a malformed pin is a
USAGE error. The check runs BEFORE the install-method and `--dry-run` branches β€” a dry
run previews the refusal, and an npm install under a pin must not be told to
`bun add -g` around it. SKILL.md tells agents these variables mean "an admin pinned the
version", so `upgrade` ignoring them (issue #57) was a hole in that promise.

[install-script.d.ts](upgrade/install-script.d.ts) declares the `*.sh` module shape for
tsc (Bun itself needs nothing), colocated with its only consumer the way
`core/render/assets.d.ts` is.
Expand Down
51 changes: 51 additions & 0 deletions src/cli/upgrade/admin-pin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { toReleaseTag } from "./release-tag";

/** Why an administrator's environment forbids this upgrade, or null when it doesn't.
* `DOCX_CLI_NO_UPDATE=1` and `DOCX_CLI_VERSION` are the fleet controls SECURITY.md
* documents and bootstrap.sh honors; the skill tells agents they mean "an admin has
* pinned the version". If `upgrade` ignored them, the pin would hold only until an
* agent (or a human) reached for the other door. So, mirroring bootstrap:
* - `DOCX_CLI_NO_UPDATE=1` refuses every upgrade;
* - `DOCX_CLI_VERSION` refuses any target other than the pinned tag β€” `--to` that
* tag is how the admin's pin gets installed, so that one stays allowed;
* - a malformed `DOCX_CLI_VERSION` is a usage error, as in bootstrap (exit 2) β€” and,
* as there, it is validated FIRST, so `DOCX_CLI_NO_UPDATE=1` doesn't mask it.
* Checked before the install-method and `--dry-run` branches: a dry run previews what
* would happen, and what would happen is this refusal. */
export function adminPinRefusal(
env: Record<string, string | undefined>,
target: string,
installed: string,
): AdminPinRefusal | null {
const raw = env.DOCX_CLI_VERSION;
const pin = raw ? toReleaseTag(raw) : null;
if (raw && pin === null) {
return {
code: "USAGE",
error: `DOCX_CLI_VERSION=${JSON.stringify(raw)} is not a release tag (e.g. v0.27.0)`,
hint: "Fix or unset DOCX_CLI_VERSION in the environment; nothing was changed.",
};
}
if (env.DOCX_CLI_NO_UPDATE === "1") {
return {
code: "UPGRADE_FAILED",
error: `upgrades are disabled by DOCX_CLI_NO_UPDATE=1 β€” docx ${installed} was left in place`,
hint: "An administrator has pinned this install. Keep using it, and ask them to update it.",
};
}
if (pin === null || target === pin) return null;
return {
code: "UPGRADE_FAILED",
error: `DOCX_CLI_VERSION=${raw} pins docx to ${pin}, so upgrading to ${target} is refused β€” docx ${installed} was left in place`,
hint:
`v${installed}` === pin
? `docx ${installed} already matches the pin; nothing to upgrade.`
: `Install the pinned release with: docx upgrade --to ${pin}`,
};
}

type AdminPinRefusal = {
code: "USAGE" | "UPGRADE_FAILED";
error: string;
hint: string;
};
41 changes: 20 additions & 21 deletions src/cli/upgrade/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import {
writeStderr,
writeStdout,
} from "../respond";
import { adminPinRefusal } from "./admin-pin";
import { toReleaseTag } from "./release-tag";
import { withoutStagingPathHint } from "./staging-path-hint";
import { swapIn } from "./swap-in";

Expand All @@ -37,6 +39,11 @@ where a running .exe can be renamed but not overwritten, the verified new
binary is swapped in and the old one is left as docx.exe.old; the next upgrade
deletes it.

Admin pins are honored, as the skill's bootstrap.sh honors them:
DOCX_CLI_NO_UPDATE=1 refuses every upgrade, and DOCX_CLI_VERSION=vX.Y.Z refuses
any target but that tag (so only "docx upgrade --to vX.Y.Z" proceeds). Both
apply to --dry-run too.

It runs the same installer published as a release asset β€” embedded in this
binary, not downloaded β€” so the new binary is pinned to a release tag and its
SHA-256 is verified against that release's SHA256SUMS before it replaces
Expand All @@ -45,19 +52,11 @@ anything.
Output:
Success one-line ack (--verbose β†’ {ok, operation, from, to, path})
--dry-run {operation, dryRun, from, to, path}
Not upgraded {code, error, hint} + nonzero exit (npm install, a renamed
binary, or a failed install) β€” the binary is left untouched
Not upgraded {code, error, hint} + nonzero exit (an admin pin, an npm
install, a renamed binary, or a failed install) β€” the binary
is left untouched
`;

/** A release tag, and nothing that can steer the URL somewhere else. `--to` is
* interpolated into install.sh's release URL, and curl NORMALIZES `..` β€” so an
* unvalidated value ("../../../../other/repo/releases/download/v1") redirects both
* the binary AND the SHA256SUMS it is checked against to an attacker's repo, making
* the checksum gate verify the attacker's own manifest. Agents drive this CLI over
* untrusted document content, so the value must be constrained here, at the CLI
* ingress, per "the CLI surface is concerned with parsing user input". */
const RELEASE_TAG = /^v?\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/;

export async function run(args: string[]): Promise<number> {
const parsed = await tryParseArgs(
args,
Expand Down Expand Up @@ -85,30 +84,30 @@ export async function run(args: string[]): Promise<number> {
}

const requested = parsed.values.to as string | undefined;
if (requested !== undefined && !RELEASE_TAG.test(requested)) {
const target = requested === undefined ? "latest" : toReleaseTag(requested);
if (target === null) {
return fail(
"USAGE",
`--to must be a release tag like v0.23.0 (got ${JSON.stringify(requested)})`,
"Tags are listed at https://github.com/kklimuk/docx-cli/releases",
);
}
// `docx --version` prints "0.23.0" but the release is tagged "v0.23.0"; accept what
// the tool itself printed rather than 404ing on the most likely typo.
const target =
requested === undefined
? "latest"
: requested.startsWith("v")
? requested
: `v${requested}`;

const refusal = adminPinRefusal(Bun.env, target, VERSION);
if (refusal) return fail(refusal.code, refusal.error, refusal.hint);

if (!isStandaloneBinary()) {
// Self-replacing a package-manager-owned install would strand the manager's
// metadata on bytes it never wrote and put a second `docx` on PATH. Nonzero:
// nothing was upgraded, and weak agents read the exit code, not the prose.
// Name the target in the advisory: a bare `bun add -g bun-docx` installs latest,
// which would route around the DOCX_CLI_VERSION pin (or the --to) just accepted.
const packageSpec =
target === "latest" ? "bun-docx" : `bun-docx@${target.slice(1)}`;
return fail(
"UPGRADE_FAILED",
`docx ${VERSION} was installed from the npm registry, which owns updates`,
"bun add -g bun-docx # or: npm install -g bun-docx",
`bun add -g ${packageSpec} # or: npm install -g ${packageSpec}`,
);
}

Expand Down
17 changes: 17 additions & 0 deletions src/cli/upgrade/release-tag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** A release tag, and nothing that can steer the URL somewhere else. `--to` (and the
* admin's `DOCX_CLI_VERSION` pin) are interpolated into install.sh's release URL, and
* curl NORMALIZES `..` β€” so an unvalidated value
* ("../../../../other/repo/releases/download/v1") redirects both the binary AND the
* SHA256SUMS it is checked against to an attacker's repo, making the checksum gate
* verify the attacker's own manifest. Agents drive this CLI over untrusted document
* content, so the value must be constrained at the CLI ingress, per "the CLI surface
* is concerned with parsing user input". bootstrap.sh applies the same pattern. */
const RELEASE_TAG = /^v?\d+\.\d+\.\d+(?:[-.][0-9A-Za-z.-]+)?$/;

/** The canonical `vX.Y.Z` tag for a validated value, or null when it isn't one.
* `docx --version` prints "0.23.0" but the release is tagged "v0.23.0"; accept what
* the tool itself printed rather than 404ing on the most likely typo. */
export function toReleaseTag(value: string): string | null {
if (!RELEASE_TAG.test(value)) return null;
return value.startsWith("v") ? value : `v${value}`;
}
132 changes: 129 additions & 3 deletions tests/cli/upgrade.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
import { describe, expect, test } from "bun:test";
import { afterAll, beforeEach, describe, expect, test } from "bun:test";
import { join } from "node:path";
import installScript from "../../skills/docx-cli/scripts/install.sh" with {
type: "text",
};
import { adminPinRefusal } from "../../src/cli/upgrade/admin-pin";
import { withoutStagingPathHint } from "../../src/cli/upgrade/staging-path-hint";
import { swapIn } from "../../src/cli/upgrade/swap-in";
import { runCli, tempWorkspace } from "./harness";

// The admin pins change what EVERY `upgrade` run does β€” in-process and the compiled
// binary spawned below (handed Bun.env explicitly) β€” and a managed machine, the very
// population they exist for, may set them in the environment the suite runs in. Clear
// them before each test so only a test that sets one sees one; restore them after.
const PIN_VARS = ["DOCX_CLI_NO_UPDATE", "DOCX_CLI_VERSION"];
const ambientPins = snapshotEnv(PIN_VARS);
beforeEach(() => {
for (const name of PIN_VARS) delete Bun.env[name];
});
afterAll(() => restoreEnv(ambientPins));

function snapshotEnv(names: string[]): Record<string, string | undefined> {
return Object.fromEntries(names.map((name) => [name, Bun.env[name]]));
}

function restoreEnv(values: Record<string, string | undefined>): void {
for (const [name, value] of Object.entries(values)) {
if (value === undefined) delete Bun.env[name];
else Bun.env[name] = value;
}
}

describe("upgrade", () => {
// The whole point of the design: `upgrade` reuses the installer rather than
// reimplementing the platform table, download, and checksum logic in TypeScript.
Expand Down Expand Up @@ -85,6 +108,104 @@ describe("upgrade", () => {
});
});

// DOCX_CLI_NO_UPDATE / DOCX_CLI_VERSION are the fleet controls SECURITY.md documents
// and bootstrap.sh honors; the skill tells agents they mean "an admin pinned the
// version". `upgrade` ignoring them (issue #57) let the pin hold only until something
// reached for the other door. The check precedes the install-method branch, so the
// in-process (npm-shaped) run reaches it exactly as a standalone binary would.
describe("upgrade (admin pins)", () => {
// The file-level beforeEach has already cleared both pins; this sets only `vars`,
// and restores exactly the names it set, whatever they are.
async function withEnv(
vars: Record<string, string>,
...argv: string[]
): Promise<Awaited<ReturnType<typeof runCli>>> {
const saved = snapshotEnv(Object.keys(vars));
restoreEnv(vars);
try {
return await runCli("upgrade", ...argv);
} finally {
restoreEnv(saved);
}
}

test.each([
[[]],
[["--dry-run"]],
[["--to", "v0.27.0"]],
])("DOCX_CLI_NO_UPDATE=1 refuses every upgrade (%p)", async (argv) => {
const result = await withEnv(
{ DOCX_CLI_NO_UPDATE: "1" },
...(argv as string[]),
);
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain("DOCX_CLI_NO_UPDATE=1");
expect(result.stdout).not.toContain('"dryRun"');
// Not the npm advisory: installing via npm would also defeat the pin.
expect(result.stdout).not.toContain("bun add -g");
});

test.each([
[[]],
[["--dry-run"]],
[["--to", "v0.28.0"]],
])("DOCX_CLI_VERSION refuses a target other than the pin (%p)", async (argv) => {
const result = await withEnv(
{ DOCX_CLI_VERSION: "0.27.0" },
...(argv as string[]),
);
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain(
"DOCX_CLI_VERSION=0.27.0 pins docx to v0.27.0",
);
expect(result.stdout).toContain("docx upgrade --to v0.27.0");
});

test("DOCX_CLI_VERSION lets --to the pinned tag through", async () => {
const result = await withEnv(
{ DOCX_CLI_VERSION: "v0.27.0" },
"--to",
"0.27.0",
);
// Past the pin check: the in-process run then hits the npm advisory β€” which must
// name the pinned version, since a bare `bun add -g bun-docx` installs latest.
expect(result.stdout).not.toContain("DOCX_CLI_VERSION");
expect(result.stdout).toContain("bun add -g bun-docx@0.27.0");
});

test("a malformed DOCX_CLI_VERSION is a usage error, as in bootstrap", async () => {
const result = await withEnv({ DOCX_CLI_VERSION: "../evil" });
expect(result.exitCode).toBe(2);
expect(result.stdout).toContain("not a release tag");
});

// bootstrap.sh validates the pin before it looks at DOCX_CLI_NO_UPDATE.
test("a malformed DOCX_CLI_VERSION is a usage error even under DOCX_CLI_NO_UPDATE=1", async () => {
const result = await withEnv({
DOCX_CLI_NO_UPDATE: "1",
DOCX_CLI_VERSION: "../evil",
});
expect(result.exitCode).toBe(2);
expect(result.stdout).toContain("not a release tag");
});

test("an install already on the pin is told there is nothing to upgrade", () => {
const refusal = adminPinRefusal(
{ DOCX_CLI_VERSION: "0.27.0" },
"latest",
"0.27.0",
);
expect(refusal?.code).toBe("UPGRADE_FAILED");
expect(refusal?.hint).toContain("already matches the pin");
});

test("an unset or non-1 DOCX_CLI_NO_UPDATE changes nothing", async () => {
const result = await withEnv({ DOCX_CLI_NO_UPDATE: "0" });
expect(result.stdout).not.toContain("DOCX_CLI_NO_UPDATE");
expect(result.stdout).toContain("bun add -g bun-docx");
});
});

// Windows locks a running .exe against overwrite but not rename, so upgrade stages
// the verified binary and swaps it in. Plain file moves, so this runs anywhere.
describe("upgrade (Windows swap-in)", () => {
Expand Down Expand Up @@ -172,7 +293,10 @@ describe("upgrade (compiled binary)", () => {
expect(build.exitCode).toBe(0);

// --dry-run so it reports intent without touching the network or the binary.
const result = Bun.spawnSync([binary, "upgrade", "--dry-run"]);
// An explicit env: spawnSync's default doesn't see the beforeEach's deletions.
const result = Bun.spawnSync([binary, "upgrade", "--dry-run"], {
env: { ...Bun.env },
});
expect(result.exitCode).toBe(0);
const stdout = result.stdout.toString();
expect(stdout).toContain('"dryRun":true');
Expand All @@ -188,7 +312,9 @@ describe("upgrade (compiled binary)", () => {
// command the user runs stale, while upgrade reported success on the old path.
const renamed = `${dir}/mydocx${exe}`;
expect(Bun.spawnSync(["cp", `${binary}${exe}`, renamed]).exitCode).toBe(0);
const refusal = Bun.spawnSync([renamed, "upgrade", "--dry-run"]);
const refusal = Bun.spawnSync([renamed, "upgrade", "--dry-run"], {
env: { ...Bun.env },
});
expect(refusal.exitCode).not.toBe(0);
expect(refusal.stdout.toString()).toContain("mydocx");
}, 120_000);
Expand Down
Loading