From 7e58af1a839b569adbe07c0c3bc94098846b50c8 Mon Sep 17 00:00:00 2001 From: MrMaxie Date: Tue, 15 Sep 2026 22:54:56 +0200 Subject: [PATCH 1/7] feat: prepare Cadder 1.0.0 npm distribution --- .github/workflows/ci.yml | 6 + .github/workflows/npm.yml | 161 +++++++++++++++ .gitignore | 1 + CHANGELOG.md | 7 +- arcantry.toml | 20 ++ crates/cadder-daemon/src/runtime/tests.rs | 7 +- docs/site/src/content/docs/index.mdx | 8 +- mise.toml | 9 + npm/bin/cadder.js | 5 + npm/bin/cadderd.js | 5 + npm/bin/caddy.js | 5 + npm/lib/launcher.js | 183 ++++++++++++++++++ npm/lib/platforms.js | 60 ++++++ npm/nub.lock | 45 +++++ npm/package.json | 63 ++++++ npm/packages/darwin-arm64/package.json | 27 +++ npm/packages/darwin-x64/package.json | 27 +++ npm/packages/linux-x64-gnu/package.json | 30 +++ npm/packages/win32-x64/package.json | 27 +++ npm/scripts/assemble-release.js | 140 ++++++++++++++ npm/scripts/check-manifests.js | 74 +++++++ npm/scripts/check-workflow.js | 39 ++++ npm/scripts/pack-bootstrap.js | 56 ++++++ npm/scripts/pack-release.js | 103 ++++++++++ npm/scripts/package-utils.js | 122 ++++++++++++ npm/scripts/prepare-bootstrap.js | 41 ++++ npm/scripts/stage-release.js | 42 ++++ npm/scripts/verify-consumer.js | 50 +++++ npm/test/package-utils.test.js | 19 ++ npm/test/path-filter.test.js | 70 +++++++ npm/test/platforms.test.js | 20 ++ .../.openspec.yaml | 2 + .../2026-09-15-add-npm-distribution/design.md | 97 ++++++++++ .../proposal.md | 29 +++ .../release.md | 18 ++ .../specs/distribution-and-upgrades/spec.md | 43 ++++ .../specs/documentation-experience/spec.md | 18 ++ .../specs/quality-tooling/spec.md | 42 ++++ .../2026-09-15-add-npm-distribution/tasks.md | 31 +++ .../changes/publish-cadder-1-0/.openspec.yaml | 2 + openspec/changes/publish-cadder-1-0/design.md | 68 +++++++ .../changes/publish-cadder-1-0/proposal.md | 43 ++++ .../specs/quality-tooling/spec.md | 11 ++ openspec/changes/publish-cadder-1-0/tasks.md | 27 +++ .../specs/distribution-and-upgrades/spec.md | 42 ++++ .../specs/documentation-experience/spec.md | 17 ++ openspec/specs/quality-tooling/spec.md | 41 ++++ releases/1.0.0.yaml | 3 +- 48 files changed, 1999 insertions(+), 7 deletions(-) create mode 100644 .github/workflows/npm.yml create mode 100644 npm/bin/cadder.js create mode 100644 npm/bin/cadderd.js create mode 100644 npm/bin/caddy.js create mode 100644 npm/lib/launcher.js create mode 100644 npm/lib/platforms.js create mode 100644 npm/nub.lock create mode 100644 npm/package.json create mode 100644 npm/packages/darwin-arm64/package.json create mode 100644 npm/packages/darwin-x64/package.json create mode 100644 npm/packages/linux-x64-gnu/package.json create mode 100644 npm/packages/win32-x64/package.json create mode 100644 npm/scripts/assemble-release.js create mode 100644 npm/scripts/check-manifests.js create mode 100644 npm/scripts/check-workflow.js create mode 100644 npm/scripts/pack-bootstrap.js create mode 100644 npm/scripts/pack-release.js create mode 100644 npm/scripts/package-utils.js create mode 100644 npm/scripts/prepare-bootstrap.js create mode 100644 npm/scripts/stage-release.js create mode 100644 npm/scripts/verify-consumer.js create mode 100644 npm/test/package-utils.test.js create mode 100644 npm/test/path-filter.test.js create mode 100644 npm/test/platforms.test.js create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/.openspec.yaml create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/design.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/proposal.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/release.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/specs/distribution-and-upgrades/spec.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/specs/documentation-experience/spec.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/specs/quality-tooling/spec.md create mode 100644 openspec/changes/archive/2026-09-15-add-npm-distribution/tasks.md create mode 100644 openspec/changes/publish-cadder-1-0/.openspec.yaml create mode 100644 openspec/changes/publish-cadder-1-0/design.md create mode 100644 openspec/changes/publish-cadder-1-0/proposal.md create mode 100644 openspec/changes/publish-cadder-1-0/specs/quality-tooling/spec.md create mode 100644 openspec/changes/publish-cadder-1-0/tasks.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f744a0f..dcf36d3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,9 +30,15 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6.0.3 + - uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a + with: + node-version: 24.18.0 + nub-version: 0.7.5 + package-manager-cache: false - uses: jdx/mise-action@v4.2.3 - run: mise run openspec-check - run: mise run docs-check + - run: mise run npm-check coverage: name: Coverage (Windows MSVC) diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml new file mode 100644 index 0000000..655bec3 --- /dev/null +++ b/.github/workflows/npm.yml @@ -0,0 +1,161 @@ +name: npm distribution + +on: + release: + types: [published] + workflow_dispatch: + inputs: + release_tag: + description: Existing GitHub Release tag to verify + required: true + type: string + stage: + description: Stage the verified packages for maintainer approval + required: true + default: false + type: boolean + +permissions: + contents: read + +concurrency: + group: npm-${{ github.event.release.tag_name || inputs.release_tag }} + cancel-in-progress: false + +jobs: + prepare: + name: Prepare verified npm tarballs + runs-on: ubuntu-22.04 + timeout-minutes: 20 + outputs: + version: ${{ steps.release.outputs.version }} + env: + RELEASE_TAG: ${{ github.event.release.tag_name || inputs.release_tag }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 + with: + persist-credentials: false + - name: Set up Node.js and Nub + uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + with: + node-version: 24.18.0 + nub-version: 0.7.5 + package-manager-cache: false + - name: Pin npm CLI + run: npm install --global npm@12.0.2 --ignore-scripts + - name: Verify toolchain + run: | + test "$(node --version)" = "v24.18.0" + nub --version | grep -Fx "v0.7.5" + test "$(npm --version)" = "12.0.2" + - name: Validate release tag + id: release + shell: bash + run: | + if [[ ! "$RELEASE_TAG" =~ ^v([0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?)$ ]]; then + echo "Invalid Cadder release tag: $RELEASE_TAG" >&2 + exit 1 + fi + echo "version=${BASH_REMATCH[1]}" >> "$GITHUB_OUTPUT" + - name: Install package workspace + working-directory: npm + run: nub ci + - name: Check package sources and workflow + working-directory: npm + run: nub run check + - name: Download exact GitHub Release assets + run: gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" --dir "$RUNNER_TEMP/cadder-assets" + - name: Assemble packages from attested release archives + run: >- + node npm/scripts/assemble-release.js + --assets "$RUNNER_TEMP/cadder-assets" + --output "$RUNNER_TEMP/cadder-npm-stage" + --version "${{ steps.release.outputs.version }}" + - name: Pack deterministic npm tarballs + run: >- + node npm/scripts/pack-release.js + --stage "$RUNNER_TEMP/cadder-npm-stage" + --output "$RUNNER_TEMP/cadder-npm-tarballs" + - name: Upload verified npm tarballs + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: cadder-npm-${{ steps.release.outputs.version }} + path: ${{ runner.temp }}/cadder-npm-tarballs + if-no-files-found: error + retention-days: 14 + + verify-native: + name: Verify npm consumer (${{ matrix.target }}) + needs: prepare + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: + - target: win32-x64 + runner: windows-2022 + - target: linux-x64-gnu + runner: ubuntu-22.04 + - target: darwin-x64 + runner: macos-15-intel + - target: darwin-arm64 + runner: macos-15 + runs-on: ${{ matrix.runner }} + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 + with: + persist-credentials: false + - name: Set up Node.js and Nub + uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + with: + node-version: 24.18.0 + nub-version: 0.7.5 + package-manager-cache: false + - name: Pin npm CLI + run: npm install --global npm@12.0.2 --ignore-scripts + - name: Download npm tarballs + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v7.0.0 + with: + name: cadder-npm-${{ needs.prepare.outputs.version }} + path: ${{ runner.temp }}/cadder-npm-tarballs + - name: Verify isolated native installation + run: node npm/scripts/verify-consumer.js --tarballs "${{ runner.temp }}/cadder-npm-tarballs" + + stage: + name: Stage npm packages for 2FA approval + needs: [prepare, verify-native] + if: github.event_name == 'release' || inputs.stage == true + runs-on: ubuntu-22.04 + timeout-minutes: 15 + environment: npm-production + permissions: + contents: read + id-token: write + steps: + - name: Check out repository + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 + with: + persist-credentials: false + - name: Set up Node.js and Nub + uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + with: + node-version: 24.18.0 + nub-version: 0.7.5 + package-manager-cache: false + - name: Pin npm CLI + run: npm install --global npm@12.0.2 --ignore-scripts + - name: Download verified npm tarballs + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v7.0.0 + with: + name: cadder-npm-${{ needs.prepare.outputs.version }} + path: ${{ runner.temp }}/cadder-npm-tarballs + - name: Stage platform packages and root package + run: node npm/scripts/stage-release.js --tarballs "${{ runner.temp }}/cadder-npm-tarballs" + - name: Show approval command + run: | + echo 'Review the five entries in npm Staged Packages.' >> "$GITHUB_STEP_SUMMARY" + echo 'Approve the four @maxiedev platform packages before approving cadder.' >> "$GITHUB_STEP_SUMMARY" + echo 'CLI alternative: npm stage approve ' >> "$GITHUB_STEP_SUMMARY" diff --git a/.gitignore b/.gitignore index c7cd270..c6d0892 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,7 @@ target/ artifacts/ dist/ publish/ +node_modules/ *.log *.tmp diff --git a/CHANGELOG.md b/CHANGELOG.md index a7bcb2c..5460950 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,10 +10,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 -## [1.0.0] - 2026-09-14 +## [1.0.0] - 2026-09-15 ### Added + +#### Install Cadder through npm + +Run `npx cadder` for one-off operator access or install `cadder` globally to place the version-matched `cadder`, `cadderd`, and Cadder `caddy` shim commands on PATH. npm packages use the same verified native binaries as the portable GitHub archives; the upstream Caddy server remains a separate installation. + #### Inspect and control the local Cadder runtime diff --git a/arcantry.toml b/arcantry.toml index 098e78a..de5a5ea 100644 --- a/arcantry.toml +++ b/arcantry.toml @@ -33,3 +33,23 @@ repository_url = "https://github.com/MrMaxie/cadder" [[release.version_sources]] path = "Cargo.toml" adapter = "cargo-workspace@1" + +[[release.version_sources]] +path = "npm/package.json" +adapter = "json-package@1" + +[[release.version_sources]] +path = "npm/packages/win32-x64/package.json" +adapter = "json-package@1" + +[[release.version_sources]] +path = "npm/packages/linux-x64-gnu/package.json" +adapter = "json-package@1" + +[[release.version_sources]] +path = "npm/packages/darwin-x64/package.json" +adapter = "json-package@1" + +[[release.version_sources]] +path = "npm/packages/darwin-arm64/package.json" +adapter = "json-package@1" diff --git a/crates/cadder-daemon/src/runtime/tests.rs b/crates/cadder-daemon/src/runtime/tests.rs index f72fce5..019459b 100644 --- a/crates/cadder-daemon/src/runtime/tests.rs +++ b/crates/cadder-daemon/src/runtime/tests.rs @@ -243,7 +243,12 @@ async fn apply_config_reports_start_failure_without_publishing_candidate() { .await .unwrap_err(); - assert!(error.to_string().contains("exited immediately")); + let error_chain = format!("{error:#}"); + assert!( + error_chain.contains("real Caddy runtime exited") + && error_chain.contains("status exit code: 7"), + "{error_chain}" + ); assert_eq!(std_fs::read(effective_path).unwrap(), b"previous"); assert!(!has_runtime_config_candidate( fixture.runtime.paths.runtime_dir() diff --git a/docs/site/src/content/docs/index.mdx b/docs/site/src/content/docs/index.mdx index 5191fb8..a93debf 100644 --- a/docs/site/src/content/docs/index.mdx +++ b/docs/site/src/content/docs/index.mdx @@ -6,11 +6,11 @@ hero: title: Stable addresses for every local app. tagline: "Cadder coordinates Caddy across your local projects. Caddy is the web server and reverse proxy that connects each local address to the port where an app is running. With Cadder, routes from different repositories are served together by one Caddy process." actions: - - text: Set up your first route - link: /cadder/quick-start/getting-started/ + - text: Download Cadder + link: https://github.com/MrMaxie/cadder/releases variant: primary - - text: How it works - link: '#how-it-works' + - text: Browse the docs + link: /cadder/quick-start/getting-started/ variant: secondary --- diff --git a/mise.toml b/mise.toml index 0727283..8bb916c 100644 --- a/mise.toml +++ b/mise.toml @@ -42,6 +42,14 @@ run = [ "npm run build", ] +[tasks.npm-check] +description = "Validate the Node and Nub npm distribution workspace" +dir = "npm" +run = [ + "nub ci", + "nub run check", +] + [tasks.coverage] description = "Enforce the 85 percent workspace line coverage gate" run = "cargo llvm-cov --workspace --all-features --lcov --output-path target/coverage-summary.lcov --fail-under-lines 85" @@ -55,6 +63,7 @@ run = [ "openspec doctor", "openspec validate --all --strict --no-interactive", { task = "docs-check" }, + { task = "npm-check" }, "dist generate --check", "dist plan", ] diff --git a/npm/bin/cadder.js b/npm/bin/cadder.js new file mode 100644 index 0000000..1a3e933 --- /dev/null +++ b/npm/bin/cadder.js @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +import { runLauncher } from '../lib/launcher.js'; + +await runLauncher('cadder', import.meta.url); diff --git a/npm/bin/cadderd.js b/npm/bin/cadderd.js new file mode 100644 index 0000000..f374cb6 --- /dev/null +++ b/npm/bin/cadderd.js @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +import { runLauncher } from '../lib/launcher.js'; + +await runLauncher('cadderd', import.meta.url); diff --git a/npm/bin/caddy.js b/npm/bin/caddy.js new file mode 100644 index 0000000..2b75c89 --- /dev/null +++ b/npm/bin/caddy.js @@ -0,0 +1,5 @@ +#!/usr/bin/env node + +import { runLauncher } from '../lib/launcher.js'; + +await runLauncher('caddy', import.meta.url); diff --git a/npm/lib/launcher.js b/npm/lib/launcher.js new file mode 100644 index 0000000..855f37e --- /dev/null +++ b/npm/lib/launcher.js @@ -0,0 +1,183 @@ +import { spawn } from 'node:child_process'; +import { constants } from 'node:fs'; +import { access, readFile, realpath, stat } from 'node:fs/promises'; +import { createRequire } from 'node:module'; +import { delimiter, dirname, extname, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { selectPlatformTarget } from './platforms.js'; + +const commandNames = new Set(['cadder', 'cadderd', 'caddy']); +const defaultWindowsExtensions = ['.COM', '.EXE', '.BAT', '.CMD']; + +function normalizedFilePath(value, platform) { + const normalized = resolve(value).replaceAll('\\', '/'); + return platform === 'win32' ? normalized.toLowerCase() : normalized; +} + +async function sameFile(left, right, platform) { + try { + const [leftPath, rightPath] = await Promise.all([realpath(left), realpath(right)]); + return normalizedFilePath(leftPath, platform) === normalizedFilePath(rightPath, platform); + } catch { + return false; + } +} + +async function isFile(path) { + try { + return (await stat(path)).isFile(); + } catch { + return false; + } +} + +async function resolveCommandFromEntry(entry, commandName, platform, pathExt) { + if (!entry) return undefined; + if (platform !== 'win32') { + const candidate = resolve(entry, commandName); + try { + await access(candidate, constants.X_OK); + return candidate; + } catch { + return undefined; + } + } + + const extensions = pathExt + .split(';') + .map((extension) => extension.trim()) + .filter(Boolean); + for (const extension of extensions.length > 0 ? extensions : defaultWindowsExtensions) { + const candidate = resolve(entry, `${commandName}${extension.toLowerCase()}`); + if (await isFile(candidate)) return candidate; + } + return undefined; +} + +async function wrapperTargetsLauncher(candidate, entry, launcherPath, platform) { + if (await sameFile(candidate, launcherPath, platform)) return true; + + const extension = extname(candidate).toLowerCase(); + if (platform === 'win32' && extension !== '.cmd' && extension !== '.bat') return false; + try { + const candidateStat = await stat(candidate); + if (candidateStat.size > 64 * 1024) return false; + const wrapper = (await readFile(candidate, 'utf8')).replaceAll('\\', '/'); + const relativeLauncher = relative(entry, launcherPath).replaceAll('\\', '/'); + const normalizedWrapper = platform === 'win32' ? wrapper.toLowerCase() : wrapper; + const normalizedRelative = platform === 'win32' ? relativeLauncher.toLowerCase() : relativeLauncher; + const normalizedLauncher = normalizedFilePath(launcherPath, platform); + return normalizedWrapper.includes(normalizedRelative) || normalizedWrapper.includes(normalizedLauncher); + } catch { + return false; + } +} + +export async function removeLauncherFromPath({ + pathValue, + launcherPath, + commandName = 'caddy', + platform = process.platform, + pathDelimiter = delimiter, + pathExt = process.env.PATHEXT ?? '', +}) { + if (!pathValue) return pathValue; + const retainedEntries = []; + for (const entry of pathValue.split(pathDelimiter)) { + const candidate = await resolveCommandFromEntry(entry, commandName, platform, pathExt); + if (candidate === undefined || !(await wrapperTargetsLauncher(candidate, entry, launcherPath, platform))) { + retainedEntries.push(entry); + } + } + return retainedEntries.join(pathDelimiter); +} + +async function resolveNativeExecutable(commandName, target, requireFromLauncher) { + let manifestPath; + try { + manifestPath = requireFromLauncher.resolve(`${target.packageName}/package.json`); + } catch (error) { + if (error?.code !== 'MODULE_NOT_FOUND') throw error; + throw new Error( + `The optional package ${target.packageName} is missing. Reinstall cadder without omitting optional dependencies.`, + ); + } + const executable = resolve(dirname(manifestPath), 'bin', `${commandName}${target.executableSuffix}`); + try { + await access(executable, process.platform === 'win32' ? constants.F_OK : constants.X_OK); + } catch { + throw new Error(`The native executable ${commandName} is missing from ${target.packageName}.`); + } + return executable; +} + +function environmentPathKey(environment) { + return Object.keys(environment).find((key) => key.toLowerCase() === 'path') ?? 'PATH'; +} + +function forwardableSignals(platform) { + return platform === 'win32' ? ['SIGINT', 'SIGTERM'] : ['SIGHUP', 'SIGINT', 'SIGTERM']; +} + +export async function launchNative(commandName, launcherUrl, argumentsValue = process.argv.slice(2)) { + if (!commandNames.has(commandName)) throw new Error(`Unknown Cadder command: ${commandName}.`); + const target = selectPlatformTarget(); + const launcherPath = fileURLToPath(launcherUrl); + const requireFromLauncher = createRequire(launcherUrl); + const executable = await resolveNativeExecutable(commandName, target, requireFromLauncher); + const environment = { ...process.env }; + + if (commandName === 'caddy') { + const pathKey = environmentPathKey(environment); + environment[pathKey] = await removeLauncherFromPath({ + pathValue: environment[pathKey], + launcherPath, + commandName, + }); + } + + const child = spawn(executable, argumentsValue, { + env: environment, + shell: false, + stdio: 'inherit', + windowsHide: false, + }); + const signalHandlers = new Map(); + const removeSignalHandlers = () => { + for (const [signal, handler] of signalHandlers) process.off(signal, handler); + signalHandlers.clear(); + }; + for (const signal of forwardableSignals(process.platform)) { + const handler = () => { + if (child.exitCode === null && child.signalCode === null) child.kill(signal); + }; + signalHandlers.set(signal, handler); + process.on(signal, handler); + } + + try { + const outcome = await new Promise((resolveExit, rejectExit) => { + child.once('error', rejectExit); + child.once('exit', (code, signal) => resolveExit({ code, signal })); + }); + if (outcome.signal && process.platform !== 'win32') { + removeSignalHandlers(); + process.kill(process.pid, outcome.signal); + return; + } + process.exitCode = outcome.code ?? 1; + } finally { + removeSignalHandlers(); + } +} + +export async function runLauncher(commandName, launcherUrl) { + try { + await launchNative(commandName, launcherUrl); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`${commandName}: ${message}\n`); + process.exitCode = 1; + } +} diff --git a/npm/lib/platforms.js b/npm/lib/platforms.js new file mode 100644 index 0000000..16d1a0c --- /dev/null +++ b/npm/lib/platforms.js @@ -0,0 +1,60 @@ +const targets = [ + { + key: 'win32:x64', + packageName: '@maxiedev/cadder-win32-x64', + directory: 'win32-x64', + archive: 'cadder-x86_64-pc-windows-msvc.zip', + executableSuffix: '.exe', + os: ['win32'], + cpu: ['x64'], + }, + { + key: 'linux:x64:glibc', + packageName: '@maxiedev/cadder-linux-x64-gnu', + directory: 'linux-x64-gnu', + archive: 'cadder-x86_64-unknown-linux-gnu.tar.xz', + executableSuffix: '', + os: ['linux'], + cpu: ['x64'], + libc: ['glibc'], + }, + { + key: 'darwin:x64', + packageName: '@maxiedev/cadder-darwin-x64', + directory: 'darwin-x64', + archive: 'cadder-x86_64-apple-darwin.tar.xz', + executableSuffix: '', + os: ['darwin'], + cpu: ['x64'], + }, + { + key: 'darwin:arm64', + packageName: '@maxiedev/cadder-darwin-arm64', + directory: 'darwin-arm64', + archive: 'cadder-aarch64-apple-darwin.tar.xz', + executableSuffix: '', + os: ['darwin'], + cpu: ['arm64'], + }, +]; + +export const platformTargets = Object.freeze(targets.map((target) => Object.freeze(target))); + +export function runtimeLibc(report = process.report?.getReport?.()) { + if (process.platform !== 'linux') return undefined; + return report?.header?.glibcVersionRuntime ? 'glibc' : 'musl'; +} + +export function selectPlatformTarget({ + platform = process.platform, + arch = process.arch, + libc = platform === 'linux' ? runtimeLibc() : undefined, +} = {}) { + const key = platform === 'linux' ? `${platform}:${arch}:${libc}` : `${platform}:${arch}`; + const target = platformTargets.find((candidate) => candidate.key === key); + if (target === undefined) { + const libcSuffix = platform === 'linux' ? `/${libc ?? 'unknown-libc'}` : ''; + throw new Error(`Cadder does not provide an npm binary for ${platform}/${arch}${libcSuffix}.`); + } + return target; +} diff --git a/npm/nub.lock b/npm/nub.lock new file mode 100644 index 0000000..716085f --- /dev/null +++ b/npm/nub.lock @@ -0,0 +1,45 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + yaml: + specifier: 2.8.3 + version: 2.8.3 + optionalDependencies: + '@maxiedev/cadder-darwin-arm64': + specifier: 1.0.0 + version: link:packages/darwin-arm64 + '@maxiedev/cadder-darwin-x64': + specifier: 1.0.0 + version: link:packages/darwin-x64 + '@maxiedev/cadder-linux-x64-gnu': + specifier: 1.0.0 + version: link:packages/linux-x64-gnu + '@maxiedev/cadder-win32-x64': + specifier: 1.0.0 + version: link:packages/win32-x64 + + packages/darwin-arm64: {} + + packages/darwin-x64: {} + + packages/linux-x64-gnu: {} + + packages/win32-x64: {} + +packages: + + yaml@2.8.3: + resolution: {integrity: sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg==} + engines: {node: '>= 14.6'} + hasBin: true + +snapshots: + + yaml@2.8.3: {} diff --git a/npm/package.json b/npm/package.json new file mode 100644 index 0000000..64119ce --- /dev/null +++ b/npm/package.json @@ -0,0 +1,63 @@ +{ + "name": "cadder", + "version": "1.0.0", + "description": "Portable launcher for the Cadder Caddy coordinator.", + "keywords": [ + "caddy", + "reverse-proxy", + "local-development", + "tui" + ], + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/MrMaxie/cadder.git" + }, + "homepage": "https://maxie.dev/cadder/", + "bugs": { + "url": "https://github.com/MrMaxie/cadder/issues" + }, + "type": "module", + "engines": { + "node": ">=24.18.0 <25" + }, + "packageManager": "nub@0.7.5", + "workspaces": [ + "packages/*" + ], + "bin": { + "cadder": "bin/cadder.js", + "cadderd": "bin/cadderd.js", + "caddy": "bin/caddy.js" + }, + "files": [ + "bin", + "lib", + "README.md", + "CHANGELOG.md", + "LICENSE", + "cadder.toml.example" + ], + "scripts": { + "check": "node --test test/*.test.js && node scripts/check-manifests.js && node scripts/check-workflow.js", + "test": "node --test test/*.test.js", + "package:check": "node scripts/check-manifests.js", + "package:assemble": "node scripts/assemble-release.js", + "package:pack": "node scripts/pack-release.js", + "bootstrap:prepare": "node scripts/prepare-bootstrap.js", + "bootstrap:pack": "node scripts/pack-bootstrap.js" + }, + "optionalDependencies": { + "@maxiedev/cadder-darwin-arm64": "1.0.0", + "@maxiedev/cadder-darwin-x64": "1.0.0", + "@maxiedev/cadder-linux-x64-gnu": "1.0.0", + "@maxiedev/cadder-win32-x64": "1.0.0" + }, + "publishConfig": { + "access": "public", + "provenance": true + }, + "devDependencies": { + "yaml": "2.8.3" + } +} diff --git a/npm/packages/darwin-arm64/package.json b/npm/packages/darwin-arm64/package.json new file mode 100644 index 0000000..5d5cede --- /dev/null +++ b/npm/packages/darwin-arm64/package.json @@ -0,0 +1,27 @@ +{ + "name": "@maxiedev/cadder-darwin-arm64", + "version": "1.0.0", + "description": "macOS Apple Silicon native binaries for Cadder.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/MrMaxie/cadder.git" + }, + "os": [ + "darwin" + ], + "cpu": [ + "arm64" + ], + "files": [ + "bin", + "README.md", + "CHANGELOG.md", + "LICENSE", + "cadder.toml.example" + ], + "publishConfig": { + "access": "public", + "provenance": true + } +} diff --git a/npm/packages/darwin-x64/package.json b/npm/packages/darwin-x64/package.json new file mode 100644 index 0000000..13ea7c1 --- /dev/null +++ b/npm/packages/darwin-x64/package.json @@ -0,0 +1,27 @@ +{ + "name": "@maxiedev/cadder-darwin-x64", + "version": "1.0.0", + "description": "macOS Intel native binaries for Cadder.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/MrMaxie/cadder.git" + }, + "os": [ + "darwin" + ], + "cpu": [ + "x64" + ], + "files": [ + "bin", + "README.md", + "CHANGELOG.md", + "LICENSE", + "cadder.toml.example" + ], + "publishConfig": { + "access": "public", + "provenance": true + } +} diff --git a/npm/packages/linux-x64-gnu/package.json b/npm/packages/linux-x64-gnu/package.json new file mode 100644 index 0000000..0b667a3 --- /dev/null +++ b/npm/packages/linux-x64-gnu/package.json @@ -0,0 +1,30 @@ +{ + "name": "@maxiedev/cadder-linux-x64-gnu", + "version": "1.0.0", + "description": "Linux x64 glibc native binaries for Cadder.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/MrMaxie/cadder.git" + }, + "os": [ + "linux" + ], + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "files": [ + "bin", + "README.md", + "CHANGELOG.md", + "LICENSE", + "cadder.toml.example" + ], + "publishConfig": { + "access": "public", + "provenance": true + } +} diff --git a/npm/packages/win32-x64/package.json b/npm/packages/win32-x64/package.json new file mode 100644 index 0000000..ee288b6 --- /dev/null +++ b/npm/packages/win32-x64/package.json @@ -0,0 +1,27 @@ +{ + "name": "@maxiedev/cadder-win32-x64", + "version": "1.0.0", + "description": "Windows x64 native binaries for Cadder.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/MrMaxie/cadder.git" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "files": [ + "bin", + "README.md", + "CHANGELOG.md", + "LICENSE", + "cadder.toml.example" + ], + "publishConfig": { + "access": "public", + "provenance": true + } +} diff --git a/npm/scripts/assemble-release.js b/npm/scripts/assemble-release.js new file mode 100644 index 0000000..5639ca8 --- /dev/null +++ b/npm/scripts/assemble-release.js @@ -0,0 +1,140 @@ +import assert from 'node:assert/strict'; +import { chmod, copyFile, cp, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { platformTargets } from '../lib/platforms.js'; +import { + commandNames, + documentationFiles, + ensureNewDirectory, + listFiles, + parseArguments, + readJson, + requiredArgument, + run, + sha256, +} from './package-utils.js'; + +const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const projectDirectory = resolve(npmDirectory, '..'); + +async function verifyAttestation(path) { + await run('gh', ['attestation', 'verify', path, '--repo', 'MrMaxie/Cadder']); +} + +async function verifyArchiveChecksum(archive, checksum) { + const expected = (await readFile(checksum, 'utf8')).trim().split(/\s+/)[0].toLowerCase(); + assert.match(expected, /^[0-9a-f]{64}$/, `Invalid SHA-256 file: ${checksum}`); + const actual = await sha256(archive); + assert.equal(actual, expected, `SHA-256 mismatch for ${archive}`); +} + +async function extractArchive(archive, destination) { + if (archive.endsWith('.zip') && process.platform !== 'win32') { + await run('unzip', ['-q', archive, '-d', destination]); + return; + } + await run('tar', ['-xf', archive, '-C', destination]); +} + +async function copyDocumentation(destination) { + for (const file of documentationFiles) { + await copyFile(resolve(projectDirectory, file), resolve(destination, file)); + } +} + +async function prepareRootPackage(output, expectedVersion) { + const destination = resolve(output, 'root'); + await mkdir(destination); + const manifest = await readJson(resolve(npmDirectory, 'package.json')); + assert.equal(manifest.version, expectedVersion, 'Root npm package version does not match the release version.'); + await copyFile(resolve(npmDirectory, 'package.json'), resolve(destination, 'package.json')); + await cp(resolve(npmDirectory, 'bin'), resolve(destination, 'bin'), { recursive: true }); + await cp(resolve(npmDirectory, 'lib'), resolve(destination, 'lib'), { recursive: true }); + await copyDocumentation(destination); + return destination; +} + +async function preparePlatformPackage({ assets, output, target, expectedVersion, verifyAttestations }) { + const archive = resolve(assets, target.archive); + const checksum = `${archive}.sha256`; + await verifyArchiveChecksum(archive, checksum); + if (verifyAttestations) { + await verifyAttestation(archive); + await verifyAttestation(checksum); + } + + const extractionRoot = await mkdtemp(resolve(output, `.extract-${target.directory}-`)); + try { + await extractArchive(archive, extractionRoot); + const suffix = target.executableSuffix; + const expectedArchiveFiles = [ + ...commandNames.map((command) => `${command}${suffix}`), + ...documentationFiles, + ].sort(); + assert.deepEqual(await listFiles(extractionRoot), expectedArchiveFiles, `${target.archive} has unexpected contents.`); + + const destination = resolve(output, target.directory); + const binDirectory = resolve(destination, 'bin'); + await mkdir(binDirectory, { recursive: true }); + const manifestPath = resolve(npmDirectory, 'packages', target.directory, 'package.json'); + const manifest = await readJson(manifestPath); + assert.equal(manifest.version, expectedVersion, `${manifest.name} version does not match the release version.`); + await copyFile(manifestPath, resolve(destination, 'package.json')); + await copyDocumentation(destination); + + const digests = {}; + for (const command of commandNames) { + const fileName = `${command}${suffix}`; + const source = resolve(extractionRoot, fileName); + const copied = resolve(binDirectory, fileName); + if (target.os[0] !== 'win32') { + assert.notEqual((await stat(source)).mode & 0o111, 0, `${fileName} is not executable in ${target.archive}.`); + } + await copyFile(source, copied); + if (target.os[0] !== 'win32') await chmod(copied, 0o755); + const sourceDigest = await sha256(source); + assert.equal(await sha256(copied), sourceDigest, `${fileName} changed while assembling ${manifest.name}.`); + digests[command] = sourceDigest; + } + return { archive: target.archive, directory: target.directory, name: manifest.name, digests }; + } finally { + await rm(extractionRoot, { recursive: true, force: true }); + } +} + +const argumentsMap = parseArguments(process.argv.slice(2)); +const assets = resolve(requiredArgument(argumentsMap, 'assets')); +const output = await ensureNewDirectory(requiredArgument(argumentsMap, 'output')); +const version = requiredArgument(argumentsMap, 'version'); +const testMode = argumentsMap.get('test-mode') === true; +if (argumentsMap.has('test-mode') && !testMode) throw new Error('--test-mode does not accept a value.'); +const targetDirectory = argumentsMap.get('target'); +const selectedTargets = + typeof targetDirectory === 'string' + ? platformTargets.filter((target) => target.directory === targetDirectory) + : platformTargets; +if (typeof targetDirectory !== 'undefined' && selectedTargets.length !== 1) { + throw new Error(`Unknown npm platform target: ${targetDirectory}`); +} + +await prepareRootPackage(output, version); +const packages = []; +for (const target of selectedTargets) { + packages.push( + await preparePlatformPackage({ + assets, + output, + target, + expectedVersion: version, + verifyAttestations: !testMode, + }), + ); +} + +await writeFile( + resolve(output, 'assembly.json'), + `${JSON.stringify({ version, repository: 'MrMaxie/Cadder', attestationsVerified: !testMode, packages }, null, 2)}\n`, +); +process.stdout.write(`assembled Cadder npm packages for ${version}${testMode ? ' in explicit test mode' : ''}\n`); diff --git a/npm/scripts/check-manifests.js b/npm/scripts/check-manifests.js new file mode 100644 index 0000000..0f8b971 --- /dev/null +++ b/npm/scripts/check-manifests.js @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import { access, readFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { platformTargets } from '../lib/platforms.js'; + +const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const repository = { + type: 'git', + url: 'git+https://github.com/MrMaxie/cadder.git', +}; +const lifecycleScripts = new Set([ + 'preinstall', + 'install', + 'postinstall', + 'prepare', + 'prepack', + 'postpack', + 'prepublish', + 'prepublishOnly', + 'publish', + 'postpublish', +]); +const packageFiles = ['bin', 'README.md', 'CHANGELOG.md', 'LICENSE', 'cadder.toml.example']; + +async function readJson(path) { + return JSON.parse(await readFile(path, 'utf8')); +} + +function checkIdentity(manifest, expectedName, expectedVersion) { + assert.equal(manifest.name, expectedName); + assert.equal(manifest.version, expectedVersion); + assert.equal(manifest.license, 'Apache-2.0'); + assert.deepEqual(manifest.repository, repository); + assert.deepEqual(manifest.publishConfig, { access: 'public', provenance: true }); + for (const script of Object.keys(manifest.scripts ?? {})) { + assert.equal(lifecycleScripts.has(script), false, `${manifest.name} must not define the ${script} lifecycle script`); + } +} + +const rootManifest = await readJson(resolve(npmDirectory, 'package.json')); +assert.match(rootManifest.version, /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/, 'Root package version must be SemVer.'); +checkIdentity(rootManifest, 'cadder', rootManifest.version); +assert.equal(rootManifest.packageManager, 'nub@0.7.5'); +assert.deepEqual(rootManifest.workspaces, ['packages/*']); +assert.deepEqual(rootManifest.bin, { + cadder: 'bin/cadder.js', + cadderd: 'bin/cadderd.js', + caddy: 'bin/caddy.js', +}); +assert.deepEqual(rootManifest.files, ['bin', 'lib', 'README.md', 'CHANGELOG.md', 'LICENSE', 'cadder.toml.example']); +assert.deepEqual( + rootManifest.optionalDependencies, + Object.fromEntries(platformTargets.map((target) => [target.packageName, rootManifest.version]).sort()), +); + +for (const target of platformTargets) { + const manifest = await readJson(resolve(npmDirectory, 'packages', target.directory, 'package.json')); + checkIdentity(manifest, target.packageName, rootManifest.version); + assert.deepEqual(manifest.os, target.os); + assert.deepEqual(manifest.cpu, target.cpu); + assert.deepEqual(manifest.libc, target.libc); + assert.deepEqual(manifest.files, packageFiles); + assert.equal(manifest.bin, undefined); + assert.equal(manifest.dependencies, undefined); + assert.equal(manifest.optionalDependencies, undefined); +} + +for (const bunFile of ['bun.lock', 'bun.lockb', 'bunfig.toml']) { + await assert.rejects(access(resolve(npmDirectory, bunFile)), undefined, `${bunFile} must not exist`); +} + +process.stdout.write('verified Cadder npm package manifests\n'); diff --git a/npm/scripts/check-workflow.js b/npm/scripts/check-workflow.js new file mode 100644 index 0000000..4979222 --- /dev/null +++ b/npm/scripts/check-workflow.js @@ -0,0 +1,39 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parse } from 'yaml'; + +const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const projectDirectory = resolve(npmDirectory, '..'); +const workflowPath = resolve(projectDirectory, '.github', 'workflows', 'npm.yml'); +const source = await readFile(workflowPath, 'utf8'); +const stageSource = await readFile(resolve(npmDirectory, 'scripts', 'stage-release.js'), 'utf8'); +const workflow = parse(source); + +assert.deepEqual(workflow.on.release.types, ['published']); +assert.ok(workflow.on.workflow_dispatch, 'The npm workflow must expose a non-publishing manual dry run.'); +assert.equal(workflow.on.workflow_dispatch.inputs.stage.default, false); +assert.equal(workflow.permissions.contents, 'read'); +assert.equal(workflow.jobs.stage.environment, 'npm-production'); +assert.equal(workflow.jobs.stage.permissions.contents, 'read'); +assert.equal(workflow.jobs.stage.permissions['id-token'], 'write'); +assert.match(workflow.jobs.stage.if, /github\.event_name == 'release'/); +assert.match(workflow.jobs.stage.if, /inputs\.stage == true/); +assert.equal(source.includes('NPM_TOKEN'), false, 'The npm workflow must not reference NPM_TOKEN.'); +assert.equal(source.includes('NODE_AUTH_TOKEN'), false, 'The npm workflow must not reference NODE_AUTH_TOKEN.'); +assert.match(source, /node npm\/scripts\/stage-release\.js/); +assert.match(stageSource, /['"]stage['"]\s*,\s*['"]publish['"]/, 'The stage script must use npm stage publish.'); +assert.match(stageSource, /['"]publish['"]\s*,\s*archive/, 'The stage script must publish only the verified tarball path.'); +assert.match(stageSource, /['"]--provenance['"]/, 'The stage script must request npm provenance.'); +assert.equal(source.includes('npm publish '), false, 'The npm workflow must not publish directly.'); + +for (const jobName of ['prepare', 'verify-native', 'stage']) { + assert.ok(workflow.jobs[jobName], `Missing ${jobName} job.`); +} + +for (const match of source.matchAll(/uses:\s+([^\s#]+)/g)) { + assert.match(match[1], /^[^@]+@[0-9a-f]{40}$/, `Action is not pinned to a full commit SHA: ${match[1]}`); +} + +process.stdout.write('verified npm workflow structure and stage-only permissions\n'); diff --git a/npm/scripts/pack-bootstrap.js b/npm/scripts/pack-bootstrap.js new file mode 100644 index 0000000..e499b77 --- /dev/null +++ b/npm/scripts/pack-bootstrap.js @@ -0,0 +1,56 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +import { platformTargets } from '../lib/platforms.js'; +import { + ensureNewDirectory, + npmArchiveName, + parseArguments, + parseNpmPackMetadata, + readJson, + requiredArgument, + runNpm, + sha256, +} from './package-utils.js'; + +const bootstrapVersion = '0.0.0-bootstrap.0'; + +async function packOnce(packageDirectory, destination) { + const result = await runNpm(['pack', packageDirectory, '--json', '--ignore-scripts', '--pack-destination', destination]); + const metadata = parseNpmPackMetadata(result.stdout); + assert.deepEqual( + metadata.files.map((entry) => entry.path).sort(), + ['README.md', 'package.json'], + `${metadata.name} bootstrap tarball must be non-executable.`, + ); + return metadata; +} + +const argumentsMap = parseArguments(process.argv.slice(2)); +const source = resolve(requiredArgument(argumentsMap, 'source')); +const output = await ensureNewDirectory(requiredArgument(argumentsMap, 'output')); +const directories = [...platformTargets.map((target) => target.directory), 'root']; +const packages = []; + +for (const directory of directories) { + const packageDirectory = resolve(source, directory); + const manifest = await readJson(resolve(packageDirectory, 'package.json')); + assert.equal(manifest.version, bootstrapVersion); + const metadata = await packOnce(packageDirectory, output); + const archiveName = npmArchiveName(manifest.name, bootstrapVersion); + const repeatDirectory = await mkdtemp(resolve(output, '.repeat-')); + try { + await packOnce(packageDirectory, repeatDirectory); + assert.equal(await sha256(resolve(output, archiveName)), await sha256(resolve(repeatDirectory, archiveName))); + } finally { + await rm(repeatDirectory, { recursive: true, force: true }); + } + packages.push({ name: manifest.name, version: manifest.version, file: archiveName, tag: 'bootstrap' }); +} + +await writeFile( + resolve(output, 'bootstrap-tarballs.json'), + `${JSON.stringify({ version: bootstrapVersion, tag: 'bootstrap', packages }, null, 2)}\n`, +); +process.stdout.write(`packed ${packages.length} non-executable bootstrap tarballs with the bootstrap tag\n`); diff --git a/npm/scripts/pack-release.js b/npm/scripts/pack-release.js new file mode 100644 index 0000000..5be57b0 --- /dev/null +++ b/npm/scripts/pack-release.js @@ -0,0 +1,103 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +import { platformTargets } from '../lib/platforms.js'; +import { + commandNames, + documentationFiles, + ensureNewDirectory, + npmArchiveName, + parseArguments, + parseNpmPackMetadata, + readJson, + requiredArgument, + runNpm, + sha256, +} from './package-utils.js'; + +function expectedPackageFiles(target) { + if (target === undefined) { + return [ + 'CHANGELOG.md', + 'LICENSE', + 'README.md', + 'bin/cadder.js', + 'bin/cadderd.js', + 'bin/caddy.js', + 'cadder.toml.example', + 'lib/launcher.js', + 'lib/platforms.js', + 'package.json', + ].sort(); + } + return [ + ...documentationFiles, + ...commandNames.map((command) => `bin/${command}${target.executableSuffix}`), + 'package.json', + ].sort(); +} + +async function packOnce(packageDirectory, destination) { + const result = await runNpm(['pack', packageDirectory, '--json', '--ignore-scripts', '--pack-destination', destination]); + return parseNpmPackMetadata(result.stdout); +} + +async function verifyAndPack(packageDirectory, output, target, version) { + const manifest = await readJson(resolve(packageDirectory, 'package.json')); + assert.equal(manifest.version, version, `${manifest.name} has the wrong version.`); + const first = await packOnce(packageDirectory, output); + assert.deepEqual( + first.files.map((entry) => entry.path).sort(), + expectedPackageFiles(target), + `${manifest.name} tarball contains unexpected files.`, + ); + + const archiveName = npmArchiveName(manifest.name, version); + const archive = resolve(output, archiveName); + const repeatDirectory = await mkdtemp(resolve(output, '.repeat-')); + try { + await packOnce(packageDirectory, repeatDirectory); + assert.equal( + await sha256(archive), + await sha256(resolve(repeatDirectory, archiveName)), + `${manifest.name} does not pack deterministically.`, + ); + } finally { + await rm(repeatDirectory, { recursive: true, force: true }); + } + + return { name: manifest.name, version, file: archiveName, sha256: await sha256(archive) }; +} + +const argumentsMap = parseArguments(process.argv.slice(2)); +const stage = resolve(requiredArgument(argumentsMap, 'stage')); +const output = await ensureNewDirectory(requiredArgument(argumentsMap, 'output')); +const assembly = JSON.parse(await readFile(resolve(stage, 'assembly.json'), 'utf8')); +assert.equal(typeof assembly.version, 'string'); +assert.equal(Array.isArray(assembly.packages), true, 'Assembly metadata does not contain package entries.'); + +const packages = []; +const selectedTargets = platformTargets.filter((target) => + assembly.packages.some((packageMetadata) => packageMetadata.directory === target.directory), +); +assert.equal(selectedTargets.length, assembly.packages.length, 'Assembly metadata contains an unknown platform package.'); +for (const target of selectedTargets) { + packages.push(await verifyAndPack(resolve(stage, target.directory), output, target, assembly.version)); +} +packages.push(await verifyAndPack(resolve(stage, 'root'), output, undefined, assembly.version)); + +await writeFile( + resolve(output, 'tarballs.json'), + `${JSON.stringify( + { + version: assembly.version, + attestationsVerified: assembly.attestationsVerified, + approvalOrder: packages.map((entry) => entry.name), + packages, + }, + null, + 2, + )}\n`, +); +process.stdout.write(`packed ${packages.length} deterministic Cadder npm tarballs for ${assembly.version}\n`); diff --git a/npm/scripts/package-utils.js b/npm/scripts/package-utils.js new file mode 100644 index 0000000..c3d3c9d --- /dev/null +++ b/npm/scripts/package-utils.js @@ -0,0 +1,122 @@ +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { createReadStream } from 'node:fs'; +import { mkdir, readdir, readFile, stat } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; + +export const documentationFiles = Object.freeze(['README.md', 'CHANGELOG.md', 'LICENSE', 'cadder.toml.example']); +export const commandNames = Object.freeze(['cadder', 'cadderd', 'caddy']); + +export function parseArguments(argumentsValue) { + const result = new Map(); + for (let index = 0; index < argumentsValue.length; index += 1) { + const argument = argumentsValue[index]; + if (!argument.startsWith('--')) throw new Error(`Unexpected argument: ${argument}`); + const key = argument.slice(2); + const next = argumentsValue[index + 1]; + if (next === undefined || next.startsWith('--')) { + result.set(key, true); + } else { + result.set(key, next); + index += 1; + } + } + return result; +} + +export function requiredArgument(argumentsMap, name) { + const value = argumentsMap.get(name); + if (typeof value !== 'string' || value.length === 0) throw new Error(`Missing required --${name} argument.`); + return value; +} + +export async function ensureNewDirectory(path) { + const absolute = resolve(path); + try { + await stat(absolute); + throw new Error(`Output directory already exists: ${absolute}`); + } catch (error) { + if (error?.code !== 'ENOENT') throw error; + } + await mkdir(absolute, { recursive: true }); + return absolute; +} + +export async function readJson(path) { + return JSON.parse(await readFile(path, 'utf8')); +} + +export function parseNpmPackMetadata(output) { + const parsed = JSON.parse(output); + const entries = Array.isArray(parsed) ? parsed : Object.values(parsed); + if (entries.length !== 1) throw new Error(`npm pack returned ${entries.length} package entries.`); + return entries[0]; +} + +export async function sha256(path) { + const hash = createHash('sha256'); + const stream = createReadStream(path); + for await (const chunk of stream) hash.update(chunk); + return hash.digest('hex'); +} + +export async function run(command, argumentsValue, options = {}) { + const child = spawn(command, argumentsValue, { + cwd: options.cwd, + env: options.env ?? process.env, + shell: false, + stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'], + windowsHide: true, + }); + let stdout = ''; + let stderr = ''; + if (child.stdout) { + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (data) => { + stdout += data; + }); + } + if (child.stderr) { + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (data) => { + stderr += data; + }); + } + const exitCode = await new Promise((resolveExit, rejectExit) => { + child.once('error', rejectExit); + child.once('exit', resolveExit); + }); + if (exitCode !== 0) { + throw new Error(`${command} ${argumentsValue.join(' ')} failed with exit code ${exitCode}\n${stdout}${stderr}`); + } + return { stdout, stderr }; +} + +export async function runNpm(argumentsValue, options = {}) { + if (process.platform !== 'win32') return run('npm', argumentsValue, options); + const npmCli = resolve(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'); + return run(process.execPath, [npmCli, ...argumentsValue], options); +} + +export async function listFiles(root) { + const files = []; + async function walk(directory, prefix) { + for (const entry of await readdir(directory, { withFileTypes: true })) { + const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name; + const absolutePath = resolve(directory, entry.name); + if (entry.isDirectory()) { + await walk(absolutePath, relativePath); + } else if (entry.isFile()) { + files.push(relativePath); + } else { + throw new Error(`Unexpected non-file package entry: ${absolutePath}`); + } + } + } + await walk(root, ''); + return files.sort(); +} + +export function npmArchiveName(packageName, version) { + return `${packageName.replace(/^@/, '').replace('/', '-')}-${version}.tgz`; +} diff --git a/npm/scripts/prepare-bootstrap.js b/npm/scripts/prepare-bootstrap.js new file mode 100644 index 0000000..bc81abd --- /dev/null +++ b/npm/scripts/prepare-bootstrap.js @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { platformTargets } from '../lib/platforms.js'; +import { ensureNewDirectory, parseArguments, readJson, requiredArgument } from './package-utils.js'; + +const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const bootstrapVersion = '0.0.0-bootstrap.0'; + +async function preparePackage(sourceManifestPath, destination) { + const source = await readJson(sourceManifestPath); + const manifest = { + name: source.name, + version: bootstrapVersion, + description: `Non-executable package-name bootstrap for ${source.name}.`, + license: source.license, + repository: source.repository, + files: ['README.md'], + publishConfig: { access: 'public' }, + }; + assert.deepEqual(manifest.publishConfig, { access: 'public' }); + await mkdir(destination, { recursive: true }); + await writeFile(resolve(destination, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile( + resolve(destination, 'README.md'), + `# ${source.name}\n\nThis bootstrap package reserves the name for Cadder trusted publishing. It contains no executable application.\n`, + ); +} + +const argumentsMap = parseArguments(process.argv.slice(2)); +const output = await ensureNewDirectory(requiredArgument(argumentsMap, 'output')); +await preparePackage(resolve(npmDirectory, 'package.json'), resolve(output, 'root')); +for (const target of platformTargets) { + await preparePackage( + resolve(npmDirectory, 'packages', target.directory, 'package.json'), + resolve(output, target.directory), + ); +} +process.stdout.write(`prepared five non-executable Cadder bootstrap packages at ${bootstrapVersion}\n`); diff --git a/npm/scripts/stage-release.js b/npm/scripts/stage-release.js new file mode 100644 index 0000000..4c77ef5 --- /dev/null +++ b/npm/scripts/stage-release.js @@ -0,0 +1,42 @@ +import assert from 'node:assert/strict'; +import { appendFile, readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +import { platformTargets } from '../lib/platforms.js'; +import { parseArguments, requiredArgument, runNpm, sha256 } from './package-utils.js'; + +const argumentsMap = parseArguments(process.argv.slice(2)); +const tarballs = resolve(requiredArgument(argumentsMap, 'tarballs')); +const metadata = JSON.parse(await readFile(resolve(tarballs, 'tarballs.json'), 'utf8')); +assert.equal(metadata.attestationsVerified, true, 'Refusing to stage packages assembled without verified attestations.'); +assert.equal(metadata.packages.length, 5, 'Expected four platform packages and one root package.'); +const expectedOrder = [...platformTargets.map((target) => target.packageName), 'cadder']; +assert.deepEqual(metadata.approvalOrder, expectedOrder, 'Package approval order must be platform-first and root-last.'); +assert.deepEqual( + metadata.packages.map((packageMetadata) => packageMetadata.name), + expectedOrder, + 'Tarball order must match the required approval order.', +); + +const summary = ['## Cadder npm staging', '', `Version: ${metadata.version}`, '', 'Required 2FA approval order:', '']; +for (const [index, packageMetadata] of metadata.packages.entries()) { + const archive = resolve(tarballs, packageMetadata.file); + assert.equal(await sha256(archive), packageMetadata.sha256, `${packageMetadata.file} digest changed before staging.`); + const result = await runNpm([ + 'stage', + 'publish', + archive, + '--access', + 'public', + '--provenance', + ]); + process.stdout.write(result.stdout); + process.stderr.write(result.stderr); + summary.push(`${index + 1}. ${packageMetadata.name}@${packageMetadata.version}`); +} + +summary.push('', 'Review every staged tarball before approval. Approve all platform packages before cadder.'); +if (process.env.GITHUB_STEP_SUMMARY) { + await appendFile(process.env.GITHUB_STEP_SUMMARY, `${summary.join('\n')}\n`); +} +process.stdout.write(`staged ${metadata.packages.length} Cadder npm packages for maintainer review\n`); diff --git a/npm/scripts/verify-consumer.js b/npm/scripts/verify-consumer.js new file mode 100644 index 0000000..0acc8bd --- /dev/null +++ b/npm/scripts/verify-consumer.js @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { resolve } from 'node:path'; + +import { selectPlatformTarget } from '../lib/platforms.js'; +import { commandNames, parseArguments, requiredArgument, runNpm } from './package-utils.js'; + +async function runInstalledCommand(consumer, command, argumentsValue) { + return runNpm(['exec', '--offline', '--', command, ...argumentsValue], { cwd: consumer }); +} + +const argumentsMap = parseArguments(process.argv.slice(2)); +const tarballs = resolve(requiredArgument(argumentsMap, 'tarballs')); +const metadata = JSON.parse(await readFile(resolve(tarballs, 'tarballs.json'), 'utf8')); +const target = selectPlatformTarget(); +const platformPackage = metadata.packages.find((entry) => entry.name === target.packageName); +const rootPackage = metadata.packages.find((entry) => entry.name === 'cadder'); +assert.ok(platformPackage, `Missing ${target.packageName} tarball metadata.`); +assert.ok(rootPackage, 'Missing cadder tarball metadata.'); + +const workspace = await mkdtemp(resolve(tmpdir(), 'cadder-npm-consumer-')); +try { + const consumer = resolve(workspace, 'consumer'); + const cache = resolve(workspace, 'cache'); + await mkdir(consumer); + await mkdir(cache); + await writeFile(resolve(consumer, 'package.json'), `${JSON.stringify({ private: true }, null, 2)}\n`); + await runNpm( + [ + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--no-package-lock', + resolve(tarballs, rootPackage.file), + resolve(tarballs, platformPackage.file), + ], + { cwd: consumer, env: { ...process.env, npm_config_cache: cache } }, + ); + + for (const command of commandNames) { + const version = await runInstalledCommand(consumer, command, ['--version']); + assert.equal(version.stdout.trim(), `${command} ${metadata.version}`); + await runInstalledCommand(consumer, command, ['--help']); + } + process.stdout.write(`verified cadder@${metadata.version} in an isolated ${target.directory} consumer\n`); +} finally { + await rm(workspace, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +} diff --git a/npm/test/package-utils.test.js b/npm/test/package-utils.test.js new file mode 100644 index 0000000..a5a579a --- /dev/null +++ b/npm/test/package-utils.test.js @@ -0,0 +1,19 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { parseNpmPackMetadata } from '../scripts/package-utils.js'; + +const packageMetadata = { name: 'cadder', version: '1.0.0' }; + +test('reads npm pack metadata from supported npm output shapes', () => { + assert.deepEqual(parseNpmPackMetadata(JSON.stringify([packageMetadata])), packageMetadata); + assert.deepEqual(parseNpmPackMetadata(JSON.stringify({ cadder: packageMetadata })), packageMetadata); +}); + +test('rejects ambiguous npm pack metadata', () => { + assert.throws(() => parseNpmPackMetadata('{}'), /returned 0 package entries/); + assert.throws( + () => parseNpmPackMetadata(JSON.stringify({ cadder: packageMetadata, other: packageMetadata })), + /returned 2 package entries/, + ); +}); diff --git a/npm/test/path-filter.test.js b/npm/test/path-filter.test.js new file mode 100644 index 0000000..0c2f16a --- /dev/null +++ b/npm/test/path-filter.test.js @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import { chmod, mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative } from 'node:path'; +import test from 'node:test'; + +import { removeLauncherFromPath } from '../lib/launcher.js'; + +test('removes only the PATH entry whose caddy command targets the npm launcher', async () => { + const workspace = await mkdtemp(join(tmpdir(), 'cadder-path-test-')); + try { + const packageRoot = join(workspace, 'node_modules', 'cadder'); + const launcherPath = join(packageRoot, 'bin', 'caddy.js'); + const ownBin = join(workspace, 'node_modules', '.bin'); + const upstreamBin = join(workspace, 'upstream'); + await mkdir(dirname(launcherPath), { recursive: true }); + await mkdir(ownBin, { recursive: true }); + await mkdir(upstreamBin, { recursive: true }); + await writeFile(launcherPath, '#!/usr/bin/env node\n'); + + if (process.platform === 'win32') { + const relativeLauncher = relative(ownBin, launcherPath); + await writeFile(join(ownBin, 'caddy.cmd'), `@node "%~dp0\\${relativeLauncher}" %*\n`); + await writeFile(join(upstreamBin, 'caddy.exe'), 'not a real executable\n'); + } else { + await symlink(launcherPath, join(ownBin, 'caddy')); + await writeFile(join(upstreamBin, 'caddy'), '#!/bin/sh\nexit 0\n'); + await chmod(join(upstreamBin, 'caddy'), 0o755); + } + + const separator = process.platform === 'win32' ? ';' : ':'; + const filtered = await removeLauncherFromPath({ + pathValue: [upstreamBin, ownBin].join(separator), + launcherPath, + platform: process.platform, + pathDelimiter: separator, + pathExt: '.COM;.EXE;.BAT;.CMD', + }); + + assert.deepEqual(filtered.split(separator), [upstreamBin]); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); + +test('keeps a PATH entry whose caddy command is not the npm launcher', async () => { + const workspace = await mkdtemp(join(tmpdir(), 'cadder-path-test-')); + try { + const launcherPath = join(workspace, 'package', 'bin', 'caddy.js'); + const upstreamBin = join(workspace, 'upstream'); + await mkdir(dirname(launcherPath), { recursive: true }); + await mkdir(upstreamBin, { recursive: true }); + await writeFile(launcherPath, '#!/usr/bin/env node\n'); + const upstream = join(upstreamBin, process.platform === 'win32' ? 'caddy.exe' : 'caddy'); + await writeFile(upstream, process.platform === 'win32' ? 'native fixture\n' : '#!/bin/sh\nexit 0\n'); + if (process.platform !== 'win32') await chmod(upstream, 0o755); + + const filtered = await removeLauncherFromPath({ + pathValue: upstreamBin, + launcherPath, + platform: process.platform, + pathDelimiter: process.platform === 'win32' ? ';' : ':', + pathExt: '.COM;.EXE;.BAT;.CMD', + }); + + assert.equal(filtered, upstreamBin); + } finally { + await rm(workspace, { recursive: true, force: true }); + } +}); diff --git a/npm/test/platforms.test.js b/npm/test/platforms.test.js new file mode 100644 index 0000000..9893f72 --- /dev/null +++ b/npm/test/platforms.test.js @@ -0,0 +1,20 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; + +import { selectPlatformTarget } from '../lib/platforms.js'; + +test('selects every supported platform package', () => { + assert.equal(selectPlatformTarget({ platform: 'win32', arch: 'x64' }).directory, 'win32-x64'); + assert.equal(selectPlatformTarget({ platform: 'linux', arch: 'x64', libc: 'glibc' }).directory, 'linux-x64-gnu'); + assert.equal(selectPlatformTarget({ platform: 'darwin', arch: 'x64' }).directory, 'darwin-x64'); + assert.equal(selectPlatformTarget({ platform: 'darwin', arch: 'arm64' }).directory, 'darwin-arm64'); +}); + +test('rejects unsupported operating systems, architectures, and C libraries', () => { + assert.throws( + () => selectPlatformTarget({ platform: 'linux', arch: 'x64', libc: 'musl' }), + /linux\/x64\/musl/, + ); + assert.throws(() => selectPlatformTarget({ platform: 'win32', arch: 'arm64' }), /win32\/arm64/); + assert.throws(() => selectPlatformTarget({ platform: 'freebsd', arch: 'x64' }), /freebsd\/x64/); +}); diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/.openspec.yaml b/openspec/changes/archive/2026-09-15-add-npm-distribution/.openspec.yaml new file mode 100644 index 0000000..96db9a4 --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-09-15 diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/design.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/design.md new file mode 100644 index 0000000..861ac5a --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/design.md @@ -0,0 +1,97 @@ +## Context + +Cadder currently publishes one cargo-dist archive per supported platform. Each archive contains `cadder`, `cadderd`, and the Cadder `caddy` shim; upstream Caddy remains a separate installation. The npm package name `cadder` and the four proposed `@maxiedev/cadder-*` platform names were unclaimed when this change was proposed. + +npm is removing direct publication through long-lived bypass-2FA tokens in January 2027. Trusted publishing uses short-lived GitHub Actions OIDC credentials, and stage-only permission adds an interactive 2FA approval before a package becomes public. New package names cannot use trusted or staged publishing until they exist in the registry, so a one-time interactive bootstrap is required. For a package's first version, the registry also retains a required `latest` tag even when publication names a non-default tag. + +## Goals / Non-Goals + +**Goals:** + +- Preserve the existing archive installation journey while adding `npx cadder` and `npm install --global cadder`. +- Install the same version-matched three-command application on Windows x64, Linux x64 GNU, Intel macOS, and Apple Silicon macOS. +- Reuse the exact cargo-dist release binaries rather than rebuilding or downloading unverified binaries during package installation. +- Publish without a long-lived npm credential and require maintainer 2FA approval for every public version. +- Keep npm-specific behavior in Node launchers and release tooling rather than in Cadder's Rust runtime contracts. + +**Non-Goals:** + +- Bundling, installing, or updating upstream Caddy. +- Adding support for platforms absent from the cargo-dist matrix. +- Using Bun, compiling Rust on the consumer machine, or running a networked postinstall script. +- Replacing GitHub Releases or modifying cargo-dist's generated workflow by hand. +- Migrating TTYGlass publication as part of this Cadder change. + +## Decisions + +### Use a launcher package with platform packages + +| Option | Local fit | Low cost | Low risk | Maintainability | Security/correctness | Maturity | Net value | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Download GitHub assets from an install script | 2 | 4 | 2 | 2 | 2 | 3 | 2 | +| Root launcher plus platform-specific optional dependencies | 5 | 4 | 5 | 5 | 5 | 5 | 5 | +| Compile the Rust workspace during npm installation | 1 | 1 | 2 | 2 | 3 | 3 | 1 | + +The public `cadder` package will contain small Node launchers and exact optional dependencies on: + +- `@maxiedev/cadder-win32-x64` +- `@maxiedev/cadder-linux-x64-gnu` +- `@maxiedev/cadder-darwin-x64` +- `@maxiedev/cadder-darwin-arm64` + +Each platform package will declare its npm `os`, `cpu`, and, where applicable, `libc` constraints and contain the three cargo-dist executables. The root package will expose `cadder`, `cadderd`, and `caddy` command launchers. A launcher will resolve only the package for the current platform, spawn the native executable with `shell: false`, forward standard streams and signals, and preserve its exit status. Missing optional dependencies and unsupported platforms will fail with actionable messages. + +The `caddy` launcher will remove only PATH entries whose `caddy` command resolves by file identity to that launcher before it starts the native shim. This prevents the native shim from rediscovering the npm launcher as upstream Caddy without adding npm-specific selection behavior to Rust. Tests will cover this boundary on every supported operating-system family. + +Node 24 and Nub will own the launcher workspace and repeatable local package tasks. The npm CLI will be used only for registry-compatible pack, stage, trust, and approval operations. Bun will not be introduced. + +### Consume verified GitHub Release assets + +A dedicated hand-written npm workflow will run after a GitHub Release is published successfully. It will not edit or duplicate the cargo-dist workflow. It will download the four release archives and checksums, verify their GitHub attestations and SHA-256 values, extract the exact three binaries into platform package staging directories, and create npm tarballs with `npm pack`. + +Native matrix jobs will install the locally packed root and matching platform tarballs in fresh consumer directories outside the checkout. They will exercise all three commands with `--version` and `--help`, verify version coherence, and confirm that the `caddy` launcher cannot resolve itself as upstream Caddy. Package-content checks will reject unexpected files, lifecycle scripts, and non-exact platform dependency versions. + +### Use stage-only OIDC trusted publishing + +| Option | Local fit | Low cost | Low risk | Maintainability | Security/correctness | Maturity | Net value | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| Long-lived granular token with direct publish | 1 | 4 | 1 | 1 | 1 | 2 | 1 | +| OIDC trusted publisher with direct publish | 4 | 5 | 4 | 5 | 4 | 5 | 4 | +| OIDC trusted publisher with staged publish and 2FA approval | 5 | 4 | 5 | 5 | 5 | 5 | 5 | + +The publish job will use a GitHub-hosted runner, `contents: read`, `id-token: write`, an exact Node and npm toolchain, and the protected `npm-production` environment. Each npm package will trust only `MrMaxie/Cadder`, the exact npm workflow filename, and that environment. The trust relationship will allow `npm stage publish` but not direct `npm publish`. No `NPM_TOKEN` will be created or stored. Trusted publishing will generate npm provenance automatically. + +The workflow will stage all five packages for the release version. A maintainer will review the staged tarballs and approve the four platform packages with 2FA before approving the root package. The root package is approved last so its exact optional dependencies are already public. Final verification will install the exact registry version with a fresh cache and consumer directory before documentation presents npm as available. + +### Bootstrap package names without publishing a product release + +Because npm requires a package to exist before trusted or staged publishing can be configured, maintainers will interactively publish minimal `0.0.0-bootstrap.0` packages under a non-default `bootstrap` tag using account 2FA. Bootstrap packages will contain only truthful metadata and no executable product. npm may also retain `latest` on that first version because the package has no other published version. This temporary default tag is acceptable only while it points to the same non-executable bootstrap. The first verified release must replace it with the exact approved Cadder version before npm installation is documented publicly. After all names exist, maintainers will configure the five stage-only trusted publishers, set package publishing access to require 2FA and disallow traditional tokens, and verify the configuration before the real release workflow runs. + +The bootstrap action is a separate, explicitly authorized registry mutation. It will happen only after the manifests and packed contents pass local review. + +### Keep versions and release meaning coherent + +The five npm manifests will be explicit Arcantry `json-package@1` version sources alongside the Cargo workspace. Root optional dependency versions will be exact and validated against the release version. Since public latest is still `v0.8.0`, this accepted change can be added to the untagged `1.0.0` manifest before the seal; it must not create a second product version for the same source revision. + +## Risks / Trade-offs + +- npm cannot publish the five-package set atomically. Approving platform packages first and the root package last prevents a public root package from referencing missing native packages. +- Users who omit optional dependencies cannot run Cadder. The launcher will diagnose the package-manager setting and name the required platform package. +- `npx cadder` starts only the requested operator command; persistent daily use is better served by the global installation because the `caddy` shim must remain on PATH. +- The npm package adds Node as an installation-channel requirement, but the installed Cadder runtime remains native and upstream Caddy remains independent. +- Bootstrap versions remain visible in registry history, and npm may retain `latest` on the first version. Non-executable contents prevent that temporary tag from exposing a false Cadder application, and the first verified release replaces it before npm installation is advertised. + +## Migration Plan + +1. Implement and validate the launcher workspace, platform manifests, package-content rules, and isolated local consumer tests without publishing. +2. Add the dedicated stage-only npm workflow and validate its event, permissions, pinned actions, release-asset inputs, and dry-run package plan. +3. Add all npm manifests to the release version sources, then archive this implementation change so the release rollout can add its accepted outcome to the untagged 1.0.0 release story. +4. With separate authorization, publish the five bootstrap packages interactively under the `bootstrap` tag using 2FA, accept a registry-required temporary `latest` only while it points to the same non-executable bootstrap, and replace it during the first verified release. +5. Configure stage-only trusted publishers for the exact GitHub workflow and `npm-production` environment, then disallow traditional publishing tokens. +6. In the follow-up `publish-cadder-1-0` change, run the release workflow, review staged packages, approve platform packages first and the root package last, and verify exact clean-room installations. +7. In that follow-up, update the public hero and installation documentation to advertise npm alongside GitHub downloads only after registry verification. +8. If any package for a version is incorrect after approval, do not reuse or overwrite that version; correct the source and publish the next patch version. + +## Open Questions + +None. diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/proposal.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/proposal.md new file mode 100644 index 0000000..54f6dcc --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/proposal.md @@ -0,0 +1,29 @@ +## Why + +Cadder currently requires users to download and place a portable archive manually even when Node-based tooling is already available. A verified npm distribution would preserve the existing three-executable installation while adding `npx cadder` and `npm install --global cadder` without introducing long-lived registry credentials. + +## What Changes + +- Publish a public `cadder` launcher package plus four platform-specific packages containing the exact verified `cadder`, `cadderd`, and Cadder `caddy` shim binaries. +- Support `npx cadder` for one-off operator use and `npm install --global cadder` for a persistent installation that exposes the complete three-command Cadder surface. +- Publish from GitHub Actions through npm trusted publishing with OIDC, automatic provenance, stage-only permission, and explicit maintainer approval with 2FA. +- Bootstrap the package names once with interactive 2FA so the first real Cadder release can use trusted publishing; do not create or store an `NPM_TOKEN`. +- Verify packed and staged package contents, native command behavior, version coherence, and isolated consumer installation before the public npm tag is promoted. +- Keep GitHub portable archives as the canonical release artifacts and keep upstream Caddy as a separate installation. +- Do not use Bun, compile Rust during npm installation, download binaries from arbitrary install scripts, or add other installer channels in this change. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `distribution-and-upgrades`: Add npm as a verified installation and upgrade channel for the same coherent application release. +- `documentation-experience`: Document npm and portable-archive installation without implying that Cadder includes upstream Caddy. +- `quality-tooling`: Add package construction, isolated consumer verification, trusted staging, and publication gates. + +## Impact + +This change adds Node-based launcher and platform package manifests, package verification tooling, and a dedicated GitHub Actions workflow that consumes verified cargo-dist release assets. It changes the public installation contract and npm registry configuration, but does not change Cadder's Rust runtime protocol, Caddy ownership boundary, or cargo-dist archive contents. diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/release.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/release.md new file mode 100644 index 0000000..924d37e --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/release.md @@ -0,0 +1,18 @@ +--- +impact: minor +components: + - distribution-and-upgrades + - documentation-experience + - quality-tooling +audiences: + - developers + - operators +observable_impact: user-felt +changelog: include +--- + +## Added + +### Install Cadder through npm + +Run `npx cadder` for one-off operator access or install `cadder` globally to place the version-matched `cadder`, `cadderd`, and Cadder `caddy` shim commands on PATH. npm packages use the same verified native binaries as the portable GitHub archives; the upstream Caddy server remains a separate installation. diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/distribution-and-upgrades/spec.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/distribution-and-upgrades/spec.md new file mode 100644 index 0000000..2f52b79 --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/distribution-and-upgrades/spec.md @@ -0,0 +1,43 @@ +## ADDED Requirements + +### Requirement: DIST-004: npm installs the coherent native application + +Cadder SHALL publish one public `cadder` launcher package and one platform package for each supported release target. Every package in one release MUST use the same version, and the root package MUST depend on the matching platform packages by exact optional dependency versions. + +The root package MUST expose `cadder`, `cadderd`, and the Cadder `caddy` shim. It MUST select only the package matching the current operating system, architecture, and C runtime, launch the native executable without a shell, preserve standard streams and exit status, and report an actionable error for an unsupported platform or omitted optional dependency. + +The npm installation MUST NOT bundle, download, replace, or claim to provide the independently installed upstream Caddy server. + +#### Scenario: One-off operator invocation + +- **WHEN** a user runs `npx cadder` on a supported platform with optional dependencies enabled +- **THEN** the matching native `cadder` executable runs with the requested arguments +- **AND** its version matches the root and platform package versions + +#### Scenario: Global installation + +- **WHEN** a user installs `cadder` globally on a supported platform +- **THEN** `cadder`, `cadderd`, and the Cadder `caddy` shim are available as commands +- **AND** all three native executables report the same release version + +#### Scenario: Upstream Caddy remains separate + +- **WHEN** the npm-installed Cadder shim needs a real Caddy executable +- **THEN** the npm launcher cannot be selected as upstream Caddy +- **AND** real Caddy resolution continues through Cadder's existing trusted sources + +#### Scenario: Optional package is unavailable + +- **WHEN** the platform package was omitted or the current platform is unsupported +- **THEN** the launcher exits unsuccessfully without downloading or compiling an executable +- **AND** the diagnostic identifies the missing package or unsupported target + +### Requirement: DIST-005: npm and portable archives share release identity + +Every npm platform package SHALL contain the exact three executable files taken from the corresponding verified cargo-dist release archive. npm packaging MUST preserve executable permissions where applicable and MUST NOT alter the native executable bytes. + +#### Scenario: Release channel comparison + +- **WHEN** a native executable from an npm platform package is compared with the corresponding verified GitHub Release archive +- **THEN** their cryptographic digests match +- **AND** both report the same Cadder release version diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/documentation-experience/spec.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/documentation-experience/spec.md new file mode 100644 index 0000000..19a4b05 --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/documentation-experience/spec.md @@ -0,0 +1,18 @@ +## ADDED Requirements + +### Requirement: DOC-004: Installation guidance distinguishes npm, Cadder, and Caddy + +Public installation guidance SHALL present `npx cadder`, global npm installation, and portable GitHub archives only when the corresponding channel has passed its release verification. It MUST explain that npm installs the Cadder operator, daemon, and `caddy` shim while the upstream Caddy web server remains a separate prerequisite. + +The hero and getting-started path MUST give users adjacent actions for npm installation or download and documentation without presenting an unpublished package as available. + +#### Scenario: npm channel is not yet public + +- **WHEN** the current Cadder version is not verified in the public npm registry +- **THEN** published documentation does not instruct users to install that version from npm + +#### Scenario: npm channel is verified + +- **WHEN** the exact Cadder version passes clean-room registry installation on every supported platform +- **THEN** the hero and installation guide may present npm as a supported option +- **AND** they retain a direct GitHub download path and the separate upstream Caddy requirement diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/quality-tooling/spec.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/quality-tooling/spec.md new file mode 100644 index 0000000..8617cff --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/specs/quality-tooling/spec.md @@ -0,0 +1,42 @@ +## ADDED Requirements + +### Requirement: QT-006: npm packages pass clean-room verification + +The npm package gate SHALL verify the exact packed file set, platform metadata, exact optional dependency versions, absence of install lifecycle scripts, and matching license and repository identity before any package is staged. + +On every supported native runner, the gate MUST install locally packed packages in a fresh consumer directory outside the checkout and MUST exercise `--version` and `--help` for `cadder`, `cadderd`, and the Cadder `caddy` shim. The gate MUST prove that the npm `caddy` launcher cannot resolve itself as upstream Caddy. + +#### Scenario: Package candidate is verified + +- **WHEN** npm package tarballs are prepared for a release +- **THEN** every supported platform passes native clean-room installation and command checks +- **AND** unexpected files, lifecycle scripts, version drift, or launcher recursion fail the gate before registry staging + +### Requirement: QT-007: npm publication uses staged trusted publishing + +Cadder npm publication SHALL use npm trusted publishing from the exact GitHub-hosted workflow and protected release environment through short-lived OIDC credentials. The trusted publisher MUST allow staged publishing only, package publishing access MUST disallow traditional tokens, and no long-lived npm publish credential may be stored in the repository or GitHub Actions. + +The workflow MUST stage packages only after it verifies the corresponding GitHub Release assets, SHA-256 checksums, and attestations. npm provenance MUST identify the public repository and publishing workflow. A maintainer MUST review and approve each stage with 2FA, approving all platform packages before the root package. + +#### Scenario: Automated staging + +- **WHEN** a verified tagged release reaches the npm workflow +- **THEN** GitHub Actions obtains a short-lived OIDC publishing identity +- **AND** it stages rather than directly publishes all version-matched packages +- **AND** no npm access token is available to the job + +#### Scenario: Human publication approval + +- **WHEN** the staged package set is ready for publication +- **THEN** a maintainer reviews the staged artifacts and approves them with 2FA +- **AND** the root package cannot become public before every referenced platform package + +### Requirement: QT-008: New npm names use an explicit bootstrap + +Before the first trusted release, each new npm package name SHALL be created interactively with account 2FA using a non-executable bootstrap version and an explicit non-default distribution tag. If the registry also assigns its required default tag to the package's only published version, that tag MAY temporarily point to the same non-executable bootstrap. Trusted publisher configuration and token restrictions MUST be applied only after the package names exist and before a real Cadder version is staged. The first verified release MUST replace the temporary default tag before npm installation is documented publicly. + +#### Scenario: Package namespace is initialized + +- **WHEN** maintainers bootstrap the npm package set +- **THEN** the default tag exposes no executable Cadder application and may point only to the non-executable bootstrap until the first verified release +- **AND** each package can be bound to the exact stage-only GitHub trusted publisher diff --git a/openspec/changes/archive/2026-09-15-add-npm-distribution/tasks.md b/openspec/changes/archive/2026-09-15-add-npm-distribution/tasks.md new file mode 100644 index 0000000..00daa39 --- /dev/null +++ b/openspec/changes/archive/2026-09-15-add-npm-distribution/tasks.md @@ -0,0 +1,31 @@ +## 1. Package workspace and launchers + +- [x] 1.1 Add a Node 24 and Nub workspace for the public `cadder` package and the four exact-version platform packages, with no Bun configuration or install lifecycle scripts. +- [x] 1.2 Implement shared launcher code for `cadder`, `cadderd`, and `caddy` that selects the supported optional package, spawns without a shell, forwards process behavior, and reports unsupported or omitted-package failures clearly. +- [x] 1.3 Make the `caddy` launcher remove only its own PATH entry by file identity before native execution, and add focused cross-platform tests proving it cannot be resolved as upstream Caddy. +- [x] 1.4 Add manifest and packed-content tests for exact versions, operating-system metadata, CPU and libc constraints, repository and license identity, allowed files, and the absence of lifecycle scripts. + +## 2. Release asset assembly and native verification + +- [x] 2.1 Build package staging directories only from the four verified cargo-dist release archives, checking GitHub attestations, SHA-256 files, exact archive contents, and unchanged executable digests. +- [x] 2.2 Pack the root and platform packages deterministically and reject any unexpected tarball entry or dependency version drift. +- [x] 2.3 On all four native runners, install the locally packed root and matching platform package in a fresh consumer directory outside the checkout and verify `--version` and `--help` for all three commands. +- [x] 2.4 Add the package checks to the maintained local and CI validation paths without duplicating cargo-dist policy. + +## 3. Stage-only trusted publishing + +- [x] 3.1 Add a dedicated npm workflow triggered by a successfully published GitHub Release, using pinned actions, a GitHub-hosted runner, the protected `npm-production` environment, `contents: read`, and job-scoped `id-token: write`. +- [x] 3.2 Make the workflow download and verify the exact release assets, run the complete package gate, and call `npm stage publish` for all five packages without reading an `NPM_TOKEN`. +- [x] 3.3 Expose the five stage results for maintainer review and document the required platform-first, root-last 2FA approval order. +- [x] 3.4 Validate workflow syntax, permissions, trigger filtering, package order, failure containment, and a non-publishing dry-run plan. + +## 4. Version and public documentation alignment + +- [x] 4.1 Register all five npm manifests as `json-package@1` release version sources and verify that Arcantry keeps Cargo and npm versions coherent. +- [x] 4.2 Keep the public hero on verified download and documentation actions until the exact npm version passes registry smoke tests; defer the npm installation action and public installation guidance to `publish-cadder-1-0`. + +## 5. Registry bootstrap and release gate + +- [x] 5.1 Produce and review minimal non-executable `0.0.0-bootstrap.0` tarballs for all five unclaimed names, with a non-default `bootstrap` tag and no product binaries. +- [x] 5.2 After separate publication authorization, interactively create the five npm packages with account 2FA, confirm that each explicit `bootstrap` tag points to the non-executable bootstrap, and record the registry-required temporary `latest` assignment for replacement by the first verified release. +- [x] 5.3 Configure each package to trust only `MrMaxie/Cadder`, the exact npm workflow filename, and `npm-production`, allow staged publishing only, require 2FA, and disallow traditional publishing tokens. diff --git a/openspec/changes/publish-cadder-1-0/.openspec.yaml b/openspec/changes/publish-cadder-1-0/.openspec.yaml new file mode 100644 index 0000000..175b240 --- /dev/null +++ b/openspec/changes/publish-cadder-1-0/.openspec.yaml @@ -0,0 +1,2 @@ +schema: implementation +created: 2026-09-15 diff --git a/openspec/changes/publish-cadder-1-0/design.md b/openspec/changes/publish-cadder-1-0/design.md new file mode 100644 index 0000000..ad2b062 --- /dev/null +++ b/openspec/changes/publish-cadder-1-0/design.md @@ -0,0 +1,68 @@ +## Context + +The npm distribution code, package construction, trusted publishers, token restrictions, and non-executable namespace bootstrap are complete in the archived `add-npm-distribution` change. Arcantry can now add that accepted outcome to the untagged 1.0.0 release manifest. The remaining work is an ordered external rollout: seal the source revision, publish the verified GitHub release, stage and approve the five npm packages, verify the exact registry artifacts, and only then advertise npm installation. + +## Requirements + +- `DIST-001`, `DIST-002`, and `QT-003` define the version-matched portable artifact set and its owning release tool. +- `QT-004` defines the pull-request candidate gate and tagged announce boundary. +- `DIST-004`, `DIST-005`, `QT-006`, and `QT-007` define coherent npm packaging, archive identity, clean-room verification, and stage-only trusted publishing. +- `QT-008` requires the first verified release to replace the temporary bootstrap default before npm is advertised. +- `DOC-004` keeps public installation guidance behind exact channel verification and distinguishes Cadder from upstream Caddy. + +## Goals and non-goals + +### Goals + +- Produce one sealed Cadder 1.0.0 source revision with coherent Cargo and npm versions and a complete changelog. +- Publish the existing portable archives only after their native artifact gate succeeds. +- Replace every temporary npm bootstrap `latest` tag with the exact verified 1.0.0 package through stage-only trusted publishing and maintainer 2FA approval. +- Verify the public npm packages outside the checkout before publishing npm installation guidance. + +### Non-goals + +- Changing Cadder runtime behavior or package construction. +- Adding installers, Homebrew, Scoop, crates.io, signing, notarization, or another release channel. +- Reusing or moving an immutable tag after code or artifact changes. +- Advertising the non-executable bootstrap as a Cadder release. + +## Ownership and trust boundaries + +GitHub Actions owns immutable archive construction, native artifact verification, attestations, and GitHub Release publication. The npm trusted publisher is bound to the exact GitHub workflow and protected environment and can create staged packages only. The maintainer owns interactive review and 2FA approval. Arcantry owns local release meaning and changelog rendering but cannot tag, push, or publish. Public documentation remains blocked until the exact registry artifacts pass clean-room verification. + +## Data flow and public contracts + +The sealed source revision produces the GitHub Release artifacts. The npm workflow consumes only those released archives, verifies checksums and attestations, assembles version-matched platform packages, and stages them through OIDC. After platform-first and root-last approval, fresh consumers verify registry resolution and native commands. Only that evidence unlocks npm installation guidance. No step changes the Cadder runtime protocol or the requirement that upstream Caddy be installed separately. + +## Decisions + +The archived npm implementation outcome is added to the existing 1.0.0 release manifest before the source revision is sealed. The final source diff, full repository gate, coverage gate, cargo-dist plan, and local distribution build must pass before commit, push, merge, or tag operations. + +The release uses the existing pull-request candidate gate and cargo-dist announce phase. The exact merge commit becomes the immutable release seal. An annotated `v1.0.0` tag may be pushed only after separate authorization naming that commit. GitHub Actions owns archive construction, native verification, attestations, and GitHub Release publication. + +The npm workflow consumes only the published and attested GitHub Release assets. Its trusted publisher may create staged packages but cannot publish directly. A maintainer reviews the stages and approves the four platform packages before the root `cadder` package. Approval requires interactive 2FA. The resulting 1.0.0 promotion replaces the temporary bootstrap `latest` tags; `bootstrap` may remain as an explicit historical tag. + +Registry verification uses fresh caches and consumer directories outside the checkout on every supported platform. It checks exact version resolution, native execution, provenance, `npx cadder`, and a temporary-prefix global installation. Public documentation remains on download and documentation actions until these checks pass. The npm installation guide and hero action are published in a separate post-release documentation commit so an unavailable package is never advertised. + +## Failure and recovery + +A failed candidate or native verification stops before publication. A failed npm stage remains unpublished and can be inspected without changing registry consumers. Registry propagation retries read only the immutable exact version. If code or package bytes must change after `v1.0.0` is pushed, the tag is preserved and the correction becomes `1.0.1`. + +## Migration and rollback + +The non-executable bootstrap versions remain historical. The first verified 1.0.0 publication replaces each temporary default tag; it does not delete or overwrite bootstrap package versions. Before the immutable tag exists, local release preparation can be reverted normally. After the tag exists, product corrections require a new version. + +## Test strategy + +Run the complete repository and coverage gates, cargo-dist planning, and local distribution build on one revision. Verify pull-request artifacts on native CI runners and smoke-test the exact Windows candidate outside the checkout. Verify GitHub Release checksums and attestations before npm staging. Then use fresh caches and consumer directories on every supported platform to verify package identity, provenance, all three native commands, `npx`, and a temporary-prefix global installation. Finally validate and inspect the public documentation on desktop and mobile. + +## Risks and trade-offs + +- GitHub Releases and npm cannot publish the complete multi-platform set atomically. Native pre-publication checks and platform-first, root-last npm approval prevent the public root package from referencing missing native packages. +- Registry metadata can take time to propagate. Verification retries only reads of the immutable exact version; it never republishes or overwrites 1.0.0. +- The temporary bootstrap remains in package history. It contains no executable, and the verified release replaces its default tag before documentation changes. +- If code or package bytes must change after the tag is pushed, the tag is preserved and the correction becomes 1.0.1. + +## Open questions + +None. diff --git a/openspec/changes/publish-cadder-1-0/proposal.md b/openspec/changes/publish-cadder-1-0/proposal.md new file mode 100644 index 0000000..677ba4e --- /dev/null +++ b/openspec/changes/publish-cadder-1-0/proposal.md @@ -0,0 +1,43 @@ +## Why + +The npm distribution implementation must be archived before Arcantry can include its accepted outcome in the 1.0.0 release manifest, while public npm verification can occur only after that sealed release is tagged and published. A separate rollout change removes this lifecycle cycle and keeps registry publication distinct from implementation. + +## Requirement IDs + +- `DIST-001`: Release binaries are version matched. +- `DIST-002`: Archives are portable and verifiable. +- `DIST-004`: npm installs the coherent native application. +- `DIST-005`: npm and portable archives share release identity. +- `DOC-004`: Installation guidance distinguishes npm, Cadder, and Caddy. +- `QT-003`: Maintained tools own validation and release formats. +- `QT-004`: Local and CI task parity. +- `QT-006`: npm packages pass clean-room verification. +- `QT-007`: npm publication uses staged trusted publishing. +- `QT-008`: New npm names use an explicit bootstrap. + +## Scope + +- Add the archived npm distribution outcome to the untagged 1.0.0 manifest and rendered changelog. +- Seal, merge, tag, and publish the exact Cadder 1.0.0 release through the existing GitHub release gate. +- Stage the five npm packages through the configured stage-only trusted publishers, review them, and approve platform packages before the root package with 2FA. +- Verify the exact public npm version, provenance, `npx cadder`, and a temporary-prefix global installation outside the checkout. +- Publish npm installation guidance and the hero npm action only after every registry verification passes. + +## Non-goals + +- Changing Cadder runtime behavior or package construction. +- Adding another distribution channel. +- Bypassing the existing release, verification, or approval gates. +- Moving or replacing an immutable release tag. + +## Success criteria + +- One reviewed source revision passes the complete repository, coverage, cargo-dist, and local artifact gates before publication. +- GitHub publishes the exact version-matched 1.0.0 portable artifacts only after native verification. +- npm stages the exact five 1.0.0 packages through OIDC without a long-lived token, and maintainer 2FA approval publishes them platform-first and root-last. +- Fresh-cache consumers on every supported platform verify exact package resolution, native commands, provenance, and replacement of the bootstrap default tag. +- Public documentation advertises npm only after the exact registry packages pass verification. + +## Impact + +This change affects the local 1.0.0 release manifest and changelog, GitHub release publication, npm staged packages and distribution tags, and the public installation documentation. It does not change Rust runtime contracts or package construction. diff --git a/openspec/changes/publish-cadder-1-0/specs/quality-tooling/spec.md b/openspec/changes/publish-cadder-1-0/specs/quality-tooling/spec.md new file mode 100644 index 0000000..f19220b --- /dev/null +++ b/openspec/changes/publish-cadder-1-0/specs/quality-tooling/spec.md @@ -0,0 +1,11 @@ +## MODIFIED Requirements + +### Requirement: QT-008: New npm names use an explicit bootstrap + +Before the first trusted release, each new npm package name SHALL be created interactively with account 2FA using a non-executable bootstrap version and an explicit non-default distribution tag. If the registry also assigns its required default tag to the package's only published version, that tag MAY temporarily point to the same non-executable bootstrap. Trusted publisher configuration and token restrictions MUST be applied only after the package names exist and before a real Cadder version is staged. The first verified release MUST replace the temporary default tag before npm installation is documented publicly. + +#### Scenario: Package namespace is initialized + +- **WHEN** maintainers bootstrap the npm package set +- **THEN** the default tag exposes no executable Cadder application and may point only to the non-executable bootstrap until the first verified release +- **AND** each package can be bound to the exact stage-only GitHub trusted publisher diff --git a/openspec/changes/publish-cadder-1-0/tasks.md b/openspec/changes/publish-cadder-1-0/tasks.md new file mode 100644 index 0000000..7a4e31d --- /dev/null +++ b/openspec/changes/publish-cadder-1-0/tasks.md @@ -0,0 +1,27 @@ +## 1. Seal the release candidate + +- [x] 1.1 `[DIST-004]` Add the archived npm distribution outcome to the untagged 1.0.0 manifest, render the changelog, and verify release consistency without creating a tag. (verification: Arcantry release check passes and no tag exists) +- [x] 1.2 `[DIST-001] [DIST-002] [QT-003]` Run the complete repository, coverage, cargo-dist planning, and local artifact gates on one source revision, then review the full release diff. (verification: every local gate passes on the same Git revision) +- [x] 1.3 `[QT-004]` After explicit authorization, commit the reviewed release candidate without unrelated local files. (verification: the staged diff contains only the approved release candidate) +- [ ] 1.4 `[QT-004]` After separate authorization, push the candidate and open or update its pull request without publishing a release. (verification: the remote pull request points to the approved candidate commit and no release exists) +- [ ] 1.5 `[DIST-002] [QT-004]` Wait for every pull-request gate and candidate artifact, then verify the exact Windows archive outside the checkout. (verification: all pull-request checks pass and the downloaded archive passes isolated smoke verification) + +## 2. Seal master and publish GitHub assets + +- [ ] 2.1 `[DOC-004] [QT-004]` After explicit authorization, squash merge the fully green candidate and verify CI, documentation, installation links, and SEO on the sealed master revision. (verification: master CI and live pre-npm documentation checks pass on the merge revision) +- [ ] 2.2 `[DIST-001] [DIST-002] [QT-003]` Run the sealed Arcantry, repository, coverage, cargo-dist planning, and local distribution gates on the exact current master revision. (verification: every sealed local gate passes and Arcantry identifies the exact release seal) +- [ ] 2.3 `[QT-004]` Present the exact master commit, obtain separate tag authorization, and push one annotated immutable `v1.0.0` tag pointing to that commit. (verification: the remote annotated tag resolves to the authorized seal commit) +- [ ] 2.4 `[DIST-002] [QT-004]` Verify that the release workflow publishes the complete final GitHub Release, checksums, source archive, manifest, and attestations only after all native artifact jobs pass. (verification: the final non-draft release and every required asset and attestation are present) + +## 3. Publish and verify npm + +- [ ] 3.1 `[QT-007]` Let the GitHub Release trigger the stage-only npm workflow and verify that all five exact 1.0.0 packages are staged through OIDC without an npm token. (verification: npm shows five staged 1.0.0 packages with the configured trusted publisher identity) +- [ ] 3.2 `[DIST-004] [QT-007]` Review every staged tarball and approve the four platform packages before the root package with interactive 2FA. (verification: all platform versions are public before the root version is approved) +- [ ] 3.3 `[DIST-005] [QT-006] [QT-008]` From fresh caches on all supported platforms, verify exact package resolution, native command behavior, provenance, and replacement of every temporary bootstrap `latest` tag by 1.0.0. (verification: native clean-room jobs pass and every default tag resolves to 1.0.0) +- [ ] 3.4 `[DIST-004] [QT-006]` Verify `npx cadder@1.0.0` and a temporary-prefix global `cadder@1.0.0` installation outside the checkout. (verification: both consumer paths run the exact 1.0.0 native operator outside the repository) + +## 4. Publish npm installation guidance + +- [ ] 4.1 `[DOC-004]` Update the installation guide and hero to present npm beside portable downloads while distinguishing the Cadder operator, daemon, and shim from separately installed upstream Caddy. (verification: the docs source names only verified public commands and channels) +- [ ] 4.2 `[DOC-004]` Run documentation checks and live desktop and mobile verification for the npm commands, CTA behavior, links, code blocks, footer, and Cadder versus Caddy responsibility boundary. (verification: documentation automation passes and both target viewports satisfy the manual checklist) +- [ ] 4.3 `[DOC-004] [QT-008]` After explicit publication authorization, publish the documentation update and verify the live site points to the exact GitHub and npm releases. (verification: the deployed site links to the verified 1.0.0 GitHub and npm releases) diff --git a/openspec/specs/distribution-and-upgrades/spec.md b/openspec/specs/distribution-and-upgrades/spec.md index ce8fec3..57bed3e 100644 --- a/openspec/specs/distribution-and-upgrades/spec.md +++ b/openspec/specs/distribution-and-upgrades/spec.md @@ -32,3 +32,45 @@ Public guidance MUST instruct the user to stop through the TUI, replace all thre #### Scenario: Mixed versions connect - **WHEN** only part of the executable set was replaced - **THEN** the exact handshake rejects the mismatch before mutation + +### Requirement: DIST-004: npm installs the coherent native application + +Cadder SHALL publish one public `cadder` launcher package and one platform package for each supported release target. Every package in one release MUST use the same version, and the root package MUST depend on the matching platform packages by exact optional dependency versions. + +The root package MUST expose `cadder`, `cadderd`, and the Cadder `caddy` shim. It MUST select only the package matching the current operating system, architecture, and C runtime, launch the native executable without a shell, preserve standard streams and exit status, and report an actionable error for an unsupported platform or omitted optional dependency. + +The npm installation MUST NOT bundle, download, replace, or claim to provide the independently installed upstream Caddy server. + +#### Scenario: One-off operator invocation + +- **WHEN** a user runs `npx cadder` on a supported platform with optional dependencies enabled +- **THEN** the matching native `cadder` executable runs with the requested arguments +- **AND** its version matches the root and platform package versions + +#### Scenario: Global installation + +- **WHEN** a user installs `cadder` globally on a supported platform +- **THEN** `cadder`, `cadderd`, and the Cadder `caddy` shim are available as commands +- **AND** all three native executables report the same release version + +#### Scenario: Upstream Caddy remains separate + +- **WHEN** the npm-installed Cadder shim needs a real Caddy executable +- **THEN** the npm launcher cannot be selected as upstream Caddy +- **AND** real Caddy resolution continues through Cadder's existing trusted sources + +#### Scenario: Optional package is unavailable + +- **WHEN** the platform package was omitted or the current platform is unsupported +- **THEN** the launcher exits unsuccessfully without downloading or compiling an executable +- **AND** the diagnostic identifies the missing package or unsupported target + +### Requirement: DIST-005: npm and portable archives share release identity + +Every npm platform package SHALL contain the exact three executable files taken from the corresponding verified cargo-dist release archive. npm packaging MUST preserve executable permissions where applicable and MUST NOT alter the native executable bytes. + +#### Scenario: Release channel comparison + +- **WHEN** a native executable from an npm platform package is compared with the corresponding verified GitHub Release archive +- **THEN** their cryptographic digests match +- **AND** both report the same Cadder release version diff --git a/openspec/specs/documentation-experience/spec.md b/openspec/specs/documentation-experience/spec.md index 16746b1..48ecb70 100644 --- a/openspec/specs/documentation-experience/spec.md +++ b/openspec/specs/documentation-experience/spec.md @@ -25,3 +25,20 @@ Published documentation MUST NOT contain personal absolute paths, `.local`, cred #### Scenario: Documentation is built - **WHEN** Astro validates the site - **THEN** only portable reader-facing content is included + +### Requirement: DOC-004: Installation guidance distinguishes npm, Cadder, and Caddy + +Public installation guidance SHALL present `npx cadder`, global npm installation, and portable GitHub archives only when the corresponding channel has passed its release verification. It MUST explain that npm installs the Cadder operator, daemon, and `caddy` shim while the upstream Caddy web server remains a separate prerequisite. + +The hero and getting-started path MUST give users adjacent actions for npm installation or download and documentation without presenting an unpublished package as available. + +#### Scenario: npm channel is not yet public + +- **WHEN** the current Cadder version is not verified in the public npm registry +- **THEN** published documentation does not instruct users to install that version from npm + +#### Scenario: npm channel is verified + +- **WHEN** the exact Cadder version passes clean-room registry installation on every supported platform +- **THEN** the hero and installation guide may present npm as a supported option +- **AND** they retain a direct GitHub download path and the separate upstream Caddy requirement diff --git a/openspec/specs/quality-tooling/spec.md b/openspec/specs/quality-tooling/spec.md index be4ee8c..9619b03 100644 --- a/openspec/specs/quality-tooling/spec.md +++ b/openspec/specs/quality-tooling/spec.md @@ -87,3 +87,44 @@ The replacement release path MUST demonstrate the complete supported artifact ma - **WHEN** cargo-dist cannot produce the accepted one-application artifact contract without substantial custom glue - **THEN** implementation stops before deleting the existing release path - **AND** a follow-up OpenSpec decision chooses a new package model or explicitly scoped adapter + +### Requirement: QT-006: npm packages pass clean-room verification + +The npm package gate SHALL verify the exact packed file set, platform metadata, exact optional dependency versions, absence of install lifecycle scripts, and matching license and repository identity before any package is staged. + +On every supported native runner, the gate MUST install locally packed packages in a fresh consumer directory outside the checkout and MUST exercise `--version` and `--help` for `cadder`, `cadderd`, and the Cadder `caddy` shim. The gate MUST prove that the npm `caddy` launcher cannot resolve itself as upstream Caddy. + +#### Scenario: Package candidate is verified + +- **WHEN** npm package tarballs are prepared for a release +- **THEN** every supported platform passes native clean-room installation and command checks +- **AND** unexpected files, lifecycle scripts, version drift, or launcher recursion fail the gate before registry staging + +### Requirement: QT-007: npm publication uses staged trusted publishing + +Cadder npm publication SHALL use npm trusted publishing from the exact GitHub-hosted workflow and protected release environment through short-lived OIDC credentials. The trusted publisher MUST allow staged publishing only, package publishing access MUST disallow traditional tokens, and no long-lived npm publish credential may be stored in the repository or GitHub Actions. + +The workflow MUST stage packages only after it verifies the corresponding GitHub Release assets, SHA-256 checksums, and attestations. npm provenance MUST identify the public repository and publishing workflow. A maintainer MUST review and approve each stage with 2FA, approving all platform packages before the root package. + +#### Scenario: Automated staging + +- **WHEN** a verified tagged release reaches the npm workflow +- **THEN** GitHub Actions obtains a short-lived OIDC publishing identity +- **AND** it stages rather than directly publishes all version-matched packages +- **AND** no npm access token is available to the job + +#### Scenario: Human publication approval + +- **WHEN** the staged package set is ready for publication +- **THEN** a maintainer reviews the staged artifacts and approves them with 2FA +- **AND** the root package cannot become public before every referenced platform package + +### Requirement: QT-008: New npm names use an explicit bootstrap + +Before the first trusted release, each new npm package name SHALL be created interactively with account 2FA using a non-executable bootstrap version and an explicit non-default distribution tag. If the registry also assigns its required default tag to the package's only published version, that tag MAY temporarily point to the same non-executable bootstrap. Trusted publisher configuration and token restrictions MUST be applied only after the package names exist and before a real Cadder version is staged. The first verified release MUST replace the temporary default tag before npm installation is documented publicly. + +#### Scenario: Package namespace is initialized + +- **WHEN** maintainers bootstrap the npm package set +- **THEN** the default tag exposes no executable Cadder application and may point only to the non-executable bootstrap until the first verified release +- **AND** each package can be bound to the exact stage-only GitHub trusted publisher diff --git a/releases/1.0.0.yaml b/releases/1.0.0.yaml index 4b2ca58..4d1dcf9 100644 --- a/releases/1.0.0.yaml +++ b/releases/1.0.0.yaml @@ -1,6 +1,7 @@ version: 1.0.0 -date: 2026-09-14 +date: 2026-09-15 changes: + - add-npm-distribution - add-operator-inspection-cli - adopt-arcantry-project-workflow - align-v1-to-core-tui From e5b424a1bb675acd5b477466ed5361bdf732f27b Mon Sep 17 00:00:00 2001 From: MrMaxie Date: Wed, 16 Sep 2026 00:15:10 +0200 Subject: [PATCH 2/7] fix: use allowed Node setup for Nub workflows --- .github/workflows/ci.yml | 5 ++--- .github/workflows/npm.yml | 20 ++++++++------------ npm/scripts/check-workflow.js | 26 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dcf36d3..5290fd9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,11 +30,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6.0.3 - - uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a + - uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: 24.18.0 - nub-version: 0.7.5 - package-manager-cache: false + - run: npm install --global @nubjs/nub@0.7.5 - uses: jdx/mise-action@v4.2.3 - run: mise run openspec-check - run: mise run docs-check diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml index 655bec3..6368dd0 100644 --- a/.github/workflows/npm.yml +++ b/.github/workflows/npm.yml @@ -37,12 +37,12 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 with: persist-credentials: false - - name: Set up Node.js and Nub - uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + - name: Set up Node.js + uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: 24.18.0 - nub-version: 0.7.5 - package-manager-cache: false + - name: Install Nub CLI + run: npm install --global @nubjs/nub@0.7.5 - name: Pin npm CLI run: npm install --global npm@12.0.2 --ignore-scripts - name: Verify toolchain @@ -108,12 +108,10 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 with: persist-credentials: false - - name: Set up Node.js and Nub - uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + - name: Set up Node.js + uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: 24.18.0 - nub-version: 0.7.5 - package-manager-cache: false - name: Pin npm CLI run: npm install --global npm@12.0.2 --ignore-scripts - name: Download npm tarballs @@ -139,12 +137,10 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.0.3 with: persist-credentials: false - - name: Set up Node.js and Nub - uses: nubjs/setup-nub@21b317c170eee658503996209cf87b63481be35a # v0 + - name: Set up Node.js + uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 with: node-version: 24.18.0 - nub-version: 0.7.5 - package-manager-cache: false - name: Pin npm CLI run: npm install --global npm@12.0.2 --ignore-scripts - name: Download verified npm tarballs diff --git a/npm/scripts/check-workflow.js b/npm/scripts/check-workflow.js index 4979222..50403f1 100644 --- a/npm/scripts/check-workflow.js +++ b/npm/scripts/check-workflow.js @@ -7,7 +7,9 @@ import { parse } from 'yaml'; const npmDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..'); const projectDirectory = resolve(npmDirectory, '..'); const workflowPath = resolve(projectDirectory, '.github', 'workflows', 'npm.yml'); +const ciWorkflowPath = resolve(projectDirectory, '.github', 'workflows', 'ci.yml'); const source = await readFile(workflowPath, 'utf8'); +const ciSource = await readFile(ciWorkflowPath, 'utf8'); const stageSource = await readFile(resolve(npmDirectory, 'scripts', 'stage-release.js'), 'utf8'); const workflow = parse(source); @@ -32,6 +34,30 @@ for (const jobName of ['prepare', 'verify-native', 'stage']) { assert.ok(workflow.jobs[jobName], `Missing ${jobName} job.`); } +const setupNodeAction = 'actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903'; +const nubInstallCommand = 'npm install --global @nubjs/nub@0.7.5'; + +for (const [workflowName, workflowSource, expectedSetupCount, expectedNubInstallCount] of [ + ['CI', ciSource, 1, 1], + ['npm distribution', source, 3, 1], +]) { + assert.equal( + workflowSource.includes('nubjs/setup-nub@'), + false, + `${workflowName} must not depend on an action rejected by the repository allowlist.`, + ); + assert.equal( + workflowSource.split(setupNodeAction).length - 1, + expectedSetupCount, + `${workflowName} must pin the expected Node setup action.`, + ); + assert.equal( + workflowSource.split(nubInstallCommand).length - 1, + expectedNubInstallCount, + `${workflowName} must install the pinned Nub CLI only where it is used.`, + ); +} + for (const match of source.matchAll(/uses:\s+([^\s#]+)/g)) { assert.match(match[1], /^[^@]+@[0-9a-f]{40}$/, `Action is not pinned to a full commit SHA: ${match[1]}`); } From c8525b70f5d6a2e9f63ccca9d5ed37bac0583def Mon Sep 17 00:00:00 2001 From: MrMaxie Date: Wed, 16 Sep 2026 01:01:10 +0200 Subject: [PATCH 3/7] fix: make release checks portable --- crates/cadder-daemon/src/runtime/process.rs | 5 ++++- crates/cadder-daemon/src/runtime/tests.rs | 3 +-- npm/test/path-filter.test.js | 1 + 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/cadder-daemon/src/runtime/process.rs b/crates/cadder-daemon/src/runtime/process.rs index a3a7c92..97f1964 100644 --- a/crates/cadder-daemon/src/runtime/process.rs +++ b/crates/cadder-daemon/src/runtime/process.rs @@ -298,7 +298,10 @@ impl ProcessRuntime { yield_now().await; match timeout(self.timeouts.start_check, child.wait()).await { Ok(Ok(status)) => { - anyhow::bail!("real Caddy runtime exited immediately with status {status}"); + let exit = status + .code() + .map_or_else(|| status.to_string(), |code| format!("exit code {code}")); + anyhow::bail!("real Caddy runtime exited immediately with {exit}"); } Ok(Err(error)) => return Err(error).context("inspect started real Caddy runtime"), Err(_) => {} diff --git a/crates/cadder-daemon/src/runtime/tests.rs b/crates/cadder-daemon/src/runtime/tests.rs index 019459b..746940f 100644 --- a/crates/cadder-daemon/src/runtime/tests.rs +++ b/crates/cadder-daemon/src/runtime/tests.rs @@ -245,8 +245,7 @@ async fn apply_config_reports_start_failure_without_publishing_candidate() { let error_chain = format!("{error:#}"); assert!( - error_chain.contains("real Caddy runtime exited") - && error_chain.contains("status exit code: 7"), + error_chain.contains("real Caddy runtime exited immediately with exit code 7"), "{error_chain}" ); assert_eq!(std_fs::read(effective_path).unwrap(), b"previous"); diff --git a/npm/test/path-filter.test.js b/npm/test/path-filter.test.js index 0c2f16a..fed65f0 100644 --- a/npm/test/path-filter.test.js +++ b/npm/test/path-filter.test.js @@ -23,6 +23,7 @@ test('removes only the PATH entry whose caddy command targets the npm launcher', await writeFile(join(ownBin, 'caddy.cmd'), `@node "%~dp0\\${relativeLauncher}" %*\n`); await writeFile(join(upstreamBin, 'caddy.exe'), 'not a real executable\n'); } else { + await chmod(launcherPath, 0o755); await symlink(launcherPath, join(ownBin, 'caddy')); await writeFile(join(upstreamBin, 'caddy'), '#!/bin/sh\nexit 0\n'); await chmod(join(upstreamBin, 'caddy'), 0o755); From 7a59ddbfe207a4e493929efe561d04a199e78805 Mon Sep 17 00:00:00 2001 From: MrMaxie Date: Thu, 17 Sep 2026 13:11:44 +0200 Subject: [PATCH 4/7] feat: improve TUI startup and onboarding Add an explicit daemon-starting TUI entrypoint, keep Windows background processes hidden, and refine operator status and shortcut feedback. Align the public documentation and OpenSpec contracts with the complete first-run flow. --- Cargo.lock | 1 + crates/cadder-api/src/error.rs | 2 +- crates/cadder-api/src/error/tests.rs | 2 +- crates/cadder-api/src/service/tests.rs | 3 +- crates/cadder-client/src/app.rs | 22 +- crates/cadder-client/src/app/lifecycle.rs | 28 +- crates/cadder-client/src/app/tests.rs | 36 ++- crates/cadder-client/src/cli/commands.rs | 16 +- crates/cadder-client/src/cli/mod.rs | 6 +- crates/cadder-client/src/main.rs | 8 +- crates/cadder-client/src/tests.rs | 29 +- crates/cadder-client/src/tui.rs | 30 +- crates/cadder-client/src/tui/events.rs | 4 +- crates/cadder-client/src/tui/view.rs | 23 +- crates/cadder-client/src/widgets/header.rs | 16 +- crates/cadder-client/src/widgets/shortcuts.rs | 36 ++- .../src/widgets/tabs_content/body.rs | 32 ++- .../src/widgets/tabs_content/domains.rs | 10 +- crates/cadder-client/src/widgets/theme.rs | 17 +- crates/cadder-daemon/Cargo.toml | 3 +- crates/cadder-daemon/src/ipc/daemon_launch.rs | 66 ++++- crates/cadder-daemon/src/process_tree.rs | 11 +- .../cadder-daemon/src/state/registrations.rs | 23 +- docs/site/astro.config.mjs | 2 +- docs/site/src/components/CadderFooter.astro | 16 +- docs/site/src/components/CadderHead.astro | 2 +- docs/site/src/components/CadderHero.astro | 77 ++--- docs/site/src/components/CadderTopology.astro | 263 ++++++++---------- .../src/components/CadderTuiPreview.astro | 2 +- .../site/src/components/CopyableCommand.astro | 112 ++++++++ docs/site/src/content/docs/index.mdx | 47 ++-- .../docs/quick-start/getting-started.mdx | 4 +- .../src/content/docs/user-guide/cadder.mdx | 8 +- docs/site/src/styles/cadder.css | 143 +++++++++- mise.toml | 3 +- .../.openspec.yaml | 2 + .../2026-09-17-add-tui-start-daemon/design.md | 50 ++++ .../proposal.md | 31 +++ .../release.md | 17 ++ .../specs/documentation-experience/spec.md | 24 ++ .../specs/operator-cli/spec.md | 37 +++ .../2026-09-17-add-tui-start-daemon/tasks.md | 9 + .../specs/documentation-experience/spec.md | 8 +- openspec/specs/operator-cli/spec.md | 9 +- 44 files changed, 947 insertions(+), 343 deletions(-) create mode 100644 docs/site/src/components/CopyableCommand.astro create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/.openspec.yaml create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/design.md create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/proposal.md create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/release.md create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/specs/documentation-experience/spec.md create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/specs/operator-cli/spec.md create mode 100644 openspec/changes/archive/2026-09-17-add-tui-start-daemon/tasks.md diff --git a/Cargo.lock b/Cargo.lock index 5be9562..b387262 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -530,6 +530,7 @@ dependencies = [ "tracing-subscriber", "which", "widestring", + "windows", "windows-sys 0.61.2", ] diff --git a/crates/cadder-api/src/error.rs b/crates/cadder-api/src/error.rs index 10d1b46..608f73c 100644 --- a/crates/cadder-api/src/error.rs +++ b/crates/cadder-api/src/error.rs @@ -250,7 +250,7 @@ pub fn error_indicates_permission(error: &Error) -> bool { } pub fn start_guidance(_paths: &Path) -> String { - "Run `cadder tui` and press Enter to start cadderd, then retry.".to_string() + "Run `cadder tui --start-daemon` to start cadderd and open the operator, then retry.".to_string() } #[cfg(test)] diff --git a/crates/cadder-api/src/error/tests.rs b/crates/cadder-api/src/error/tests.rs index 5ba2185..3d84d7b 100644 --- a/crates/cadder-api/src/error/tests.rs +++ b/crates/cadder-api/src/error/tests.rs @@ -30,7 +30,7 @@ async fn typed_error_daemon_unavailable_maps_to_stable_exit_code() { assert_eq!(mapped.kind, AppExit::DaemonUnavailable); assert_eq!( mapped.guidance.as_deref(), - Some("Run `cadder tui` and press Enter to start cadderd, then retry.") + Some("Run `cadder tui --start-daemon` to start cadderd and open the operator, then retry.") ); } diff --git a/crates/cadder-api/src/service/tests.rs b/crates/cadder-api/src/service/tests.rs index 285c2f1..6b77068 100644 --- a/crates/cadder-api/src/service/tests.rs +++ b/crates/cadder-api/src/service/tests.rs @@ -241,7 +241,8 @@ async fn connected_and_unavailable_statuses_include_operator_context() { assert_eq!(status.connection_state, ConnectionStateView::NotRunning); assert!(status.message.contains("is not running")); assert!(status.guidance.as_deref().is_some_and(|guidance| { - guidance == "Run `cadder tui` and press Enter to start cadderd, then retry." + guidance + == "Run `cadder tui --start-daemon` to start cadderd and open the operator, then retry." })); let failed = IpcClientError::Daemon(ProtocolError::new( diff --git a/crates/cadder-client/src/app.rs b/crates/cadder-client/src/app.rs index eddd5e8..f3483cd 100644 --- a/crates/cadder-client/src/app.rs +++ b/crates/cadder-client/src/app.rs @@ -15,6 +15,7 @@ pub struct App { confirmation: Option, notice: Option, pending_message: Option<&'static str>, + pending_frame: usize, last_start_failed: bool, should_quit: bool, } @@ -79,6 +80,7 @@ impl App { confirmation: None, notice: None, pending_message: None, + pending_frame: 0, last_start_failed: false, should_quit: false, }; @@ -88,22 +90,6 @@ impl App { } impl RuntimeStatus { - pub const fn daemon_label(self) -> &'static str { - if self.daemon_is_running() { - "running" - } else { - "not running" - } - } - - pub const fn caddy_label(self) -> &'static str { - if self.caddy_is_running() { - "running" - } else { - "not running" - } - } - pub const fn daemon_is_running(self) -> bool { matches!(self.connection, ConnectionStatus::Connected) } @@ -111,6 +97,10 @@ impl RuntimeStatus { pub const fn caddy_is_running(self) -> bool { self.daemon_is_running() && matches!(self.caddy_status, ProtocolRuntimeStatus::Running) } + + pub const fn daemon_is_offline(self) -> bool { + matches!(self.connection, ConnectionStatus::Offline) + } } impl ConnectionStatus { diff --git a/crates/cadder-client/src/app/lifecycle.rs b/crates/cadder-client/src/app/lifecycle.rs index a29f10b..ad326df 100644 --- a/crates/cadder-client/src/app/lifecycle.rs +++ b/crates/cadder-client/src/app/lifecycle.rs @@ -2,10 +2,15 @@ use crate::data::MutationTarget; use super::*; +const PENDING_FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; + impl App { pub fn apply_refresh(&mut self, outcome: RefreshOutcome) { match outcome { RefreshOutcome::Connected { snapshot } => { + if self.last_start_failed { + self.notice = None; + } self.last_start_failed = false; self.runtime_status = RuntimeStatus { connection: ConnectionStatus::Connected, @@ -45,7 +50,7 @@ impl App { return false; } self.last_start_failed = false; - self.begin_action("Starting Cadder..."); + self.begin_action("Starting cadderd..."); true } @@ -82,13 +87,28 @@ impl App { self.pending_message.is_some() } + pub fn pending_marker(&self) -> Option<&'static str> { + self + .pending_message + .map(|_| PENDING_FRAMES[self.pending_frame % PENDING_FRAMES.len()]) + } + + pub fn advance_pending_animation(&mut self) { + if self.is_pending() { + self.pending_frame = (self.pending_frame + 1) % PENDING_FRAMES.len(); + } + } + pub fn complete_daemon_start(&mut self, result: Result<(), ActionFailure>) -> bool { if let Err(error) = &result { self.last_start_failed = true; self.connection_message.clone_from(&error.message); self.connection_guidance.clone_from(&error.guidance); } - self.finish_action(result) + self.finish_action(result.map_err(|_| ActionFailure { + message: "Could not start cadderd.".to_string(), + guidance: None, + })) } pub fn complete_lifecycle(&mut self, result: Result<(), ActionFailure>) -> bool { @@ -109,6 +129,9 @@ impl App { if let Some(notice) = &self.notice { return Some(notice.clone()); } + if self.runtime_status.connection == ConnectionStatus::Offline { + return None; + } if self.runtime_status.connection != ConnectionStatus::Connected { return Some(self.connection_guidance.as_deref().map_or_else( || self.connection_message.clone(), @@ -131,6 +154,7 @@ impl App { fn begin_action(&mut self, message: &'static str) { self.notice = None; self.pending_message = Some(message); + self.pending_frame = 0; } fn finish_action(&mut self, result: Result<(), ActionFailure>) -> bool { diff --git a/crates/cadder-client/src/app/tests.rs b/crates/cadder-client/src/app/tests.rs index 3dd7a12..645e78c 100644 --- a/crates/cadder-client/src/app/tests.rs +++ b/crates/cadder-client/src/app/tests.rs @@ -26,19 +26,17 @@ fn runtime_status_reports_daemon_and_caddy_independently() { connection: ConnectionStatus::Connected, caddy_status: ProtocolRuntimeStatus::Running, }; - assert_eq!(running.daemon_label(), "running"); - assert_eq!(running.caddy_label(), "running"); assert!(running.daemon_is_running()); assert!(running.caddy_is_running()); + assert!(!running.daemon_is_offline()); let offline = RuntimeStatus { connection: ConnectionStatus::Offline, caddy_status: ProtocolRuntimeStatus::Unknown, }; - assert_eq!(offline.daemon_label(), "not running"); - assert_eq!(offline.caddy_label(), "not running"); assert!(!offline.daemon_is_running()); assert!(!offline.caddy_is_running()); + assert!(offline.daemon_is_offline()); } #[test] @@ -47,18 +45,38 @@ fn offline_state_exposes_start_without_a_separate_status_view() { app.apply_refresh(RefreshOutcome::Unavailable { connection: ConnectionStatus::Offline, message: "Cadder is not running.".to_string(), - guidance: Some("Press Enter to start it.".to_string()), + guidance: Some("Run `cadder tui --start-daemon`.".to_string()), }); assert!(app.can_start_daemon()); - assert_eq!( - app.notice().as_deref(), - Some("Cadder is not running. Press Enter to start it.") - ); + assert!(app.notice().is_none()); assert!(app.prepare_start_daemon()); assert!(app.is_pending()); } +#[test] +fn daemon_start_animates_without_repeating_failures_above_shortcuts() { + let mut app = App::new(); + app.apply_refresh(RefreshOutcome::Unavailable { + connection: ConnectionStatus::Offline, + message: "Cadder is not running.".to_string(), + guidance: None, + }); + + assert!(app.prepare_start_daemon()); + assert_eq!(app.pending_marker(), Some("⠋")); + assert_eq!(app.notice().as_deref(), Some("Starting cadderd...")); + app.advance_pending_animation(); + assert_eq!(app.pending_marker(), Some("⠙")); + + assert!(!app.complete_daemon_start(Err(ActionFailure { + message: "Could not start cadderd.".to_string(), + guidance: Some("Check the daemon status, then retry.".to_string()), + }))); + assert!(app.pending_marker().is_none()); + assert_eq!(app.notice().as_deref(), Some("Could not start cadderd.")); +} + #[test] fn lifecycle_confirmation_stays_inline_and_explicit() { let mut app = connected_app(); diff --git a/crates/cadder-client/src/cli/commands.rs b/crates/cadder-client/src/cli/commands.rs index 11702bc..e14dab9 100644 --- a/crates/cadder-client/src/cli/commands.rs +++ b/crates/cadder-client/src/cli/commands.rs @@ -18,14 +18,12 @@ use crate::{ HostProcessInspector, PortOwner, ProcessInspector, ProcessSignalError, RegistrationIndex, RouteMatch, local_upstream, }, - run_tui, + tui, }; pub(super) async fn execute(command: Command) -> Result<(), CommandFailure> { match command { - Command::Tui => run_tui() - .await - .map_err(|error| CommandFailure::ipc(format!("Could not run the Cadder TUI: {error}"))), + Command::Tui { start_daemon } => open_tui(start_daemon).await, Command::Status => status().await, Command::Daemon { command } => daemon(command).await, Command::Projects { command } => projects(command).await, @@ -37,6 +35,16 @@ pub(super) async fn execute(command: Command) -> Result<(), CommandFailure> { } } +async fn open_tui(start_daemon: bool) -> Result<(), CommandFailure> { + let context = context("tui")?; + if start_daemon { + context.ensure_daemon_running("tui").await?; + } + tui::run(context) + .await + .map_err(|error| CommandFailure::ipc(format!("Could not run the Cadder TUI: {error}"))) +} + async fn status() -> Result<(), CommandFailure> { let context = context("status")?; let snapshot = context diff --git a/crates/cadder-client/src/cli/mod.rs b/crates/cadder-client/src/cli/mod.rs index 9ad01c6..b302fc8 100644 --- a/crates/cadder-client/src/cli/mod.rs +++ b/crates/cadder-client/src/cli/mod.rs @@ -56,7 +56,11 @@ pub(crate) enum Command { command: LogsCommand, }, /// Open the full-screen operator. - Tui, + Tui { + /// Start or attach to cadderd before opening the operator. + #[arg(long)] + start_daemon: bool, + }, } #[derive(Debug, Subcommand)] diff --git a/crates/cadder-client/src/main.rs b/crates/cadder-client/src/main.rs index 864f352..0afc6b8 100644 --- a/crates/cadder-client/src/main.rs +++ b/crates/cadder-client/src/main.rs @@ -5,10 +5,9 @@ mod inspection; mod tui; mod widgets; -use cadder_api::{AppExit, DaemonLaunchOptions, OperatorContext}; +use cadder_api::AppExit; use clap::{Parser, error::ErrorKind}; use cli::Cli; -use color_eyre::Result; #[tokio::main(flavor = "current_thread")] async fn main() -> AppExit { @@ -35,10 +34,5 @@ fn cli_exit(error: &clap::Error) -> AppExit { } } -pub(crate) async fn run_tui() -> Result<()> { - let context = OperatorContext::new("tui", None, DaemonLaunchOptions::default())?; - tui::run(context).await -} - #[cfg(test)] mod tests; diff --git a/crates/cadder-client/src/tests.rs b/crates/cadder-client/src/tests.rs index 9fbd139..115949c 100644 --- a/crates/cadder-client/src/tests.rs +++ b/crates/cadder-client/src/tests.rs @@ -30,10 +30,35 @@ fn version_returns_success() { } #[test] -fn tui_command_is_preserved() { +fn tui_command_preserves_read_first_default() { let cli = Cli::try_parse_from(["cadder", "tui"]).expect("TUI should parse"); - assert!(matches!(cli.command, Command::Tui)); + assert!(matches!( + cli.command, + Command::Tui { + start_daemon: false + } + )); +} + +#[test] +fn tui_command_accepts_explicit_daemon_start() { + let cli = Cli::try_parse_from(["cadder", "tui", "--start-daemon"]) + .expect("TUI daemon startup should parse"); + + assert!(matches!(cli.command, Command::Tui { start_daemon: true })); +} + +#[test] +fn tui_help_explains_daemon_start() { + let help = Cli::command() + .find_subcommand_mut("tui") + .expect("TUI command should exist") + .render_help() + .to_string(); + + assert!(help.contains("--start-daemon")); + assert!(help.contains("Start or attach to cadderd before opening the operator")); } #[test] diff --git a/crates/cadder-client/src/tui.rs b/crates/cadder-client/src/tui.rs index afb07c9..3ebe989 100644 --- a/crates/cadder-client/src/tui.rs +++ b/crates/cadder-client/src/tui.rs @@ -16,6 +16,7 @@ use self::view::render; use crate::app::App; const REFRESH_INTERVAL: Duration = Duration::from_secs(1); +const ANIMATION_INTERVAL: Duration = Duration::from_millis(80); pub async fn run(context: OperatorContext) -> Result<()> { let mut terminal = ratatui::try_init()?; @@ -32,6 +33,8 @@ async fn run_event_loop( let mut events = EventStream::new(); let mut refresh = tokio::time::interval(REFRESH_INTERVAL); refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut animation = tokio::time::interval(ANIMATION_INTERVAL); + animation.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut effects = tokio::task::JoinSet::new(); let mut refresh_in_flight = true; spawn_effect(&mut effects, context.clone(), Effect::Refresh); @@ -44,6 +47,9 @@ async fn run_event_loop( refresh_in_flight = true; spawn_effect(&mut effects, context.clone(), Effect::Refresh); }, + _ = animation.tick(), if app.is_pending() => { + app.advance_pending_animation(); + }, event = events.next() => { match event.transpose()? { Some(event) => { @@ -124,12 +130,27 @@ mod tests { app.apply_refresh(crate::app::RefreshOutcome::Unavailable { connection: crate::app::ConnectionStatus::Offline, message: "Cadder is not running.".to_string(), - guidance: Some("Press Enter to start it.".to_string()), + guidance: Some("Run `cadder tui --start-daemon`.".to_string()), }); let mut terminal = Terminal::new(TestBackend::new(100, 32)).unwrap(); terminal.draw(|frame| render(frame, &mut app)).unwrap(); - assert!(format!("{}", terminal.backend()).contains("Press Enter to start it")); + let screen = format!("{}", terminal.backend()); + assert!(screen.contains("Cadder is not running.")); + assert!(screen.contains("enter start cadderd · r retry · q quit")); + assert!(!screen.contains("--start-daemon")); + assert!(!screen.contains("No registered routes")); + assert!(screen.contains("○ cadderd · ○ Caddy")); + + assert!(app.prepare_start_daemon()); + terminal.draw(|frame| render(frame, &mut app)).unwrap(); + let screen = format!("{}", terminal.backend()); + assert!( + screen + .lines() + .nth(1) + .is_some_and(|line| line.contains("⠋ Starting cadderd...")) + ); let mut connected = App::new(); connected.apply_refresh(crate::app::RefreshOutcome::Connected { @@ -145,7 +166,10 @@ mod tests { terminal .draw(|frame| render(frame, &mut connected)) .unwrap(); - assert!(format!("{}", terminal.backend()).contains("Restart Cadder")); + let screen = format!("{}", terminal.backend()); + assert!(screen.contains("Restart Cadder")); + assert!(screen.contains("● cadderd · ○ Caddy")); + assert!(screen.contains("enter confirm · esc cancel · q quit")); let mut tiny = Terminal::new(TestBackend::new(1, 1)).unwrap(); tiny.draw(|frame| render(frame, &mut App::new())).unwrap(); diff --git a/crates/cadder-client/src/tui/events.rs b/crates/cadder-client/src/tui/events.rs index 1ea9e79..2e4c653 100644 --- a/crates/cadder-client/src/tui/events.rs +++ b/crates/cadder-client/src/tui/events.rs @@ -36,7 +36,7 @@ fn handle_key(code: KeyCode, modifiers: KeyModifiers, app: &mut App) -> Option app.select_previous(), KeyCode::Down => app.select_next(), KeyCode::Enter if app.prepare_start_daemon() => return Some(UiAction::StartDaemon), - KeyCode::Enter | KeyCode::Char(' ') => { + KeyCode::Enter => { return app.prepare_toggle_current().map(UiAction::Mutate); } KeyCode::Char('r') => return Some(UiAction::Refresh), @@ -133,6 +133,8 @@ mod tests { storage: None, }), }); + assert!(handle_key(KeyCode::Char(' '), KeyModifiers::NONE, &mut toggle).is_none()); + assert!(!toggle.is_pending()); assert!(matches!( handle_key(KeyCode::Enter, KeyModifiers::NONE, &mut toggle), Some(UiAction::Mutate(_)) diff --git a/crates/cadder-client/src/tui/view.rs b/crates/cadder-client/src/tui/view.rs index 02af0a8..0ca7620 100644 --- a/crates/cadder-client/src/tui/view.rs +++ b/crates/cadder-client/src/tui/view.rs @@ -1,6 +1,6 @@ use ratatui::Frame; use ratatui::layout::{Constraint, Layout, Rect}; -use ratatui::text::Line; +use ratatui::text::{Line, Span}; use ratatui::widgets::{Paragraph, StatefulWidget, Widget}; use crate::app::App; @@ -44,15 +44,28 @@ fn render_main(frame: &mut Frame<'_>, area: Rect, app: &mut App) { ); let rows = app.domain_rows(); + let empty_message = if app.runtime_status().daemon_is_offline() { + "Cadder is not running." + } else { + "No registered routes. Run caddy run in a project." + }; StatefulWidget::render( - RoutesTable::new(rows), + RoutesTable::new(rows, empty_message), areas.routes, frame.buffer_mut(), app.table_state_mut(), ); if let (Some(notice_area), Some(notice)) = (areas.notice, notice) { - Paragraph::new(Line::from(notice)) + let line = if let Some(marker) = app.pending_marker() { + Line::from(vec![ + Span::styled(format!(" {marker} "), THEME.pending_indicator()), + Span::raw(notice), + ]) + } else { + Line::from(format!(" {notice}")) + }; + Paragraph::new(line) .style(THEME.notice()) .render(notice_area, frame.buffer_mut()); } @@ -83,10 +96,10 @@ fn root_areas(root: Rect) -> (Rect, Rect) { fn main_areas(area: Rect, has_notice: bool) -> MainAreas { let notice_height = u16::from(has_notice); - let [header, routes, notice] = area.layout(&Layout::vertical([ + let [header, notice, routes] = area.layout(&Layout::vertical([ Constraint::Length(1), - Constraint::Fill(1), Constraint::Length(notice_height), + Constraint::Fill(1), ])); MainAreas { diff --git a/crates/cadder-client/src/widgets/header.rs b/crates/cadder-client/src/widgets/header.rs index 9cf1c78..0257fe6 100644 --- a/crates/cadder-client/src/widgets/header.rs +++ b/crates/cadder-client/src/widgets/header.rs @@ -29,19 +29,17 @@ impl Widget for HeaderBar { buf.set_style(area, THEME.header()); let status = Line::from(vec![ - Span::styled("cadderd", THEME.status_name()), - Span::raw(" "), Span::styled( - self.runtime_status.daemon_label(), + status_marker(self.runtime_status.daemon_is_running()), status_state(self.runtime_status.daemon_is_running()), ), - Span::styled(" | ", THEME.status_separator()), - Span::styled("Caddy", THEME.status_name()), - Span::raw(" "), + Span::styled(" cadderd", THEME.status_name()), + Span::styled(" · ", THEME.status_separator()), Span::styled( - self.runtime_status.caddy_label(), + status_marker(self.runtime_status.caddy_is_running()), status_state(self.runtime_status.caddy_is_running()), ), + Span::styled(" Caddy", THEME.status_name()), Span::raw(" "), ]); let status_width = u16::try_from(status.width()).unwrap_or(u16::MAX); @@ -65,6 +63,10 @@ impl Widget for HeaderBar { } } +const fn status_marker(running: bool) -> &'static str { + if running { "●" } else { "○" } +} + fn status_state(running: bool) -> ratatui::style::Style { if running { THEME.status_running() diff --git a/crates/cadder-client/src/widgets/shortcuts.rs b/crates/cadder-client/src/widgets/shortcuts.rs index 1cc535c..91f66f3 100644 --- a/crates/cadder-client/src/widgets/shortcuts.rs +++ b/crates/cadder-client/src/widgets/shortcuts.rs @@ -6,16 +6,16 @@ use ratatui::widgets::{Paragraph, Widget}; use crate::widgets::theme::THEME; pub const MAIN_SHORTCUTS: [Shortcut; 6] = [ - Shortcut::new("Up/Down", "select"), - Shortcut::new("Space/Enter", "enable/disable"), + Shortcut::new("↑ ↓", "select"), + Shortcut::new("enter", "enable/disable"), Shortcut::new("r", "refresh"), Shortcut::new("x", "stop"), - Shortcut::new("R", "restart"), + Shortcut::new("shift+r", "restart"), Shortcut::new("q", "quit"), ]; pub const OFFLINE_SHORTCUTS: [Shortcut; 3] = [ - Shortcut::new("Enter", "start cadderd"), + Shortcut::new("enter", "start cadderd"), Shortcut::new("r", "retry"), Shortcut::new("q", "quit"), ]; @@ -23,8 +23,8 @@ pub const OFFLINE_SHORTCUTS: [Shortcut; 3] = [ pub const PENDING_SHORTCUTS: [Shortcut; 1] = [Shortcut::new("q", "quit")]; pub const CONFIRMATION_SHORTCUTS: [Shortcut; 3] = [ - Shortcut::new("Enter", "confirm"), - Shortcut::new("Esc", "cancel"), + Shortcut::new("enter", "confirm"), + Shortcut::new("esc", "cancel"), Shortcut::new("q", "quit"), ]; @@ -52,19 +52,17 @@ impl<'a> ShortcutsBar<'a> { impl Widget for ShortcutsBar<'_> { fn render(self, area: Rect, buf: &mut Buffer) { - let shortcut_spans = self - .shortcuts - .iter() - .flat_map(|shortcut| { - [ - Span::styled(shortcut.key, THEME.shortcut_key()), - Span::styled( - format!(" {} ", shortcut.description), - THEME.shortcut_description(), - ), - ] - }) - .collect::>(); + let mut shortcut_spans = Vec::with_capacity(self.shortcuts.len().saturating_mul(3)); + for (index, shortcut) in self.shortcuts.iter().enumerate() { + if index > 0 { + shortcut_spans.push(Span::styled(" · ", THEME.shortcut_separator())); + } + shortcut_spans.push(Span::styled(shortcut.key, THEME.shortcut_key())); + shortcut_spans.push(Span::styled( + format!(" {}", shortcut.description), + THEME.shortcut_description(), + )); + } Paragraph::new(Line::from(shortcut_spans)) .style(THEME.footer()) .render(area, buf); diff --git a/crates/cadder-client/src/widgets/tabs_content/body.rs b/crates/cadder-client/src/widgets/tabs_content/body.rs index 7f800fa..545f6ff 100644 --- a/crates/cadder-client/src/widgets/tabs_content/body.rs +++ b/crates/cadder-client/src/widgets/tabs_content/body.rs @@ -17,11 +17,15 @@ const COLUMN_SPACING: u16 = 1; pub(crate) struct TableBody { rows: Vec, + empty_message: &'static str, } impl TableBody { - pub const fn new(rows: Vec) -> Self { - Self { rows } + pub const fn new(rows: Vec, empty_message: &'static str) -> Self { + Self { + rows, + empty_message, + } } } @@ -48,7 +52,7 @@ impl StatefulWidget for TableBody { trailing_available_width, ); let table = Table::new( - into_rows(self.rows), + into_rows(self.rows, self.empty_message), [ Constraint::Length(SELECTOR_COLUMN_WIDTH), Constraint::Min(PRIMARY_COLUMN_MIN_WIDTH), @@ -57,7 +61,7 @@ impl StatefulWidget for TableBody { ) .column_spacing(COLUMN_SPACING) .row_highlight_style(THEME.table_highlight()) - .highlight_symbol("> ") + .highlight_symbol("› ") .header( Row::new(["", "Project / domain", "Target"]) .style(THEME.table_header()) @@ -93,12 +97,9 @@ fn trailing_column_content_width(rows: &[DomainTableRow]) -> usize { .max(Line::from("Target").width()) } -fn into_rows(rows: Vec) -> Vec> { +fn into_rows(rows: Vec, empty_message: &'static str) -> Vec> { if rows.is_empty() { - return vec![ - Row::new(["", "No registered routes. Run caddy run in a project.", ""]) - .style(THEME.table_disabled_row()), - ]; + return vec![Row::new(["", empty_message, ""]).style(THEME.table_disabled_row())]; } rows.into_iter().map(domain_row).collect() } @@ -350,9 +351,14 @@ mod tests { let area = Rect::new(0, 0, 80, 12); let mut buffer = Buffer::empty(area); let mut state = TableState::default().with_selected(Some(0)); - TableBody::new(model.domain_rows()).render(area, &mut buffer, &mut state); + TableBody::new( + model.domain_rows(), + "No registered routes. Run caddy run in a project.", + ) + .render(area, &mut buffer, &mut state); let text = buffer_text(&buffer); assert!(text.contains("Project / domain")); + assert!(text.contains('›'), "rendered table:\n{text}"); assert!(text.contains("├─ ○"), "rendered table:\n{text}"); assert!(text.contains("└─ ●"), "rendered table:\n{text}"); assert!(text.contains('●')); @@ -366,7 +372,11 @@ mod tests { let small_area = Rect::new(0, 0, 80, 8); let mut small_buffer = Buffer::empty(small_area); let mut state = TableState::default().with_selected(Some(4)); - TableBody::new(model.domain_rows()).render(small_area, &mut small_buffer, &mut state); + TableBody::new( + model.domain_rows(), + "No registered routes. Run caddy run in a project.", + ) + .render(small_area, &mut small_buffer, &mut state); assert!(state.offset() > 0); } diff --git a/crates/cadder-client/src/widgets/tabs_content/domains.rs b/crates/cadder-client/src/widgets/tabs_content/domains.rs index ba30a62..a236c57 100644 --- a/crates/cadder-client/src/widgets/tabs_content/domains.rs +++ b/crates/cadder-client/src/widgets/tabs_content/domains.rs @@ -7,11 +7,15 @@ use crate::widgets::tabs_content::TableBody; pub struct RoutesTable { rows: Vec, + empty_message: &'static str, } impl RoutesTable { - pub const fn new(rows: Vec) -> Self { - Self { rows } + pub const fn new(rows: Vec, empty_message: &'static str) -> Self { + Self { + rows, + empty_message, + } } } @@ -19,6 +23,6 @@ impl StatefulWidget for RoutesTable { type State = TableState; fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) { - TableBody::new(self.rows).render(area, buf, state); + TableBody::new(self.rows, self.empty_message).render(area, buf, state); } } diff --git a/crates/cadder-client/src/widgets/theme.rs b/crates/cadder-client/src/widgets/theme.rs index 8814368..3d8a71a 100644 --- a/crates/cadder-client/src/widgets/theme.rs +++ b/crates/cadder-client/src/widgets/theme.rs @@ -47,6 +47,10 @@ impl Theme { Style::new().fg(self.colors.text_muted) } + pub fn shortcut_separator(self) -> Style { + Style::new().fg(self.colors.dim) + } + pub fn footer(self) -> Style { Style::new().bg(self.colors.backdrop) } @@ -57,7 +61,7 @@ impl Theme { pub fn header_title(self) -> Style { Style::new() - .fg(self.colors.text) + .fg(self.colors.mint_soft) .bg(self.colors.backdrop) .add_modifier(Modifier::BOLD) } @@ -135,6 +139,13 @@ impl Theme { .bg(self.colors.surface_selected) } + pub fn pending_indicator(self) -> Style { + self + .notice() + .fg(self.colors.mint_soft) + .add_modifier(Modifier::BOLD) + } + pub fn project_name(self) -> Style { Style::new() .fg(self.colors.text) @@ -154,9 +165,10 @@ mod tests { theme.shortcut_description().fg, Some(theme.colors.text_muted) ); + assert_eq!(theme.shortcut_separator().fg, Some(theme.colors.dim)); assert_eq!(theme.footer().bg, Some(theme.colors.backdrop)); assert_eq!(theme.header().bg, Some(theme.colors.backdrop)); - assert_eq!(theme.header_title().fg, Some(theme.colors.text)); + assert_eq!(theme.header_title().fg, Some(theme.colors.mint_soft)); assert_eq!(theme.status_name().fg, Some(theme.colors.text)); assert_eq!(theme.status_running().fg, Some(theme.colors.mint_soft)); assert_eq!(theme.status_stopped().fg, Some(theme.colors.dim)); @@ -176,6 +188,7 @@ mod tests { assert_eq!(theme.disabled_marker().fg, Some(theme.colors.text_muted)); assert_eq!(theme.tree_branch().fg, Some(theme.colors.dim)); assert_eq!(theme.notice().bg, Some(theme.colors.surface_selected)); + assert_eq!(theme.pending_indicator().fg, Some(theme.colors.mint_soft)); assert_eq!(theme.project_name().fg, Some(theme.colors.text)); } } diff --git a/crates/cadder-daemon/Cargo.toml b/crates/cadder-daemon/Cargo.toml index daf8ba1..9667458 100644 --- a/crates/cadder-daemon/Cargo.toml +++ b/crates/cadder-daemon/Cargo.toml @@ -43,7 +43,7 @@ futures-util = "=0.3.32" getrandom = "=0.4.2" hex = "=0.4.3" interprocess = { version = "=2.4.2", features = ["tokio"] } -process-wrap = { version = "=9.1.0", default-features = false, features = ["tokio1", "process-group", "kill-on-drop", "job-object"] } +process-wrap = { version = "=9.1.0", default-features = false, features = ["tokio1", "process-group", "kill-on-drop", "job-object", "creation-flags"] } same-file = "=1.0.6" semver = "=1.0.28" serde = { version = "=1.0.229", features = ["derive"] } @@ -64,6 +64,7 @@ testcontainers = "=0.27.3" [target."cfg(windows)".dependencies] is_elevated = "=0.1.2" widestring = "=1.2.1" +windows = { version = "=0.62.2", features = ["Win32_System_Threading"] } windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Com", "Win32_System_Pipes", "Win32_System_Threading", "Win32_UI_Shell"] } [target."cfg(unix)".dependencies] diff --git a/crates/cadder-daemon/src/ipc/daemon_launch.rs b/crates/cadder-daemon/src/ipc/daemon_launch.rs index eb7a8bc..7afcfdc 100644 --- a/crates/cadder-daemon/src/ipc/daemon_launch.rs +++ b/crates/cadder-daemon/src/ipc/daemon_launch.rs @@ -79,17 +79,32 @@ impl DaemonProcessConfig { } } -#[cfg(windows)] -pub(super) const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; -#[cfg(windows)] -pub(super) const DETACHED_PROCESS: u32 = 0x0000_0008; #[cfg(windows)] pub(super) const CREATE_NO_WINDOW: u32 = 0x0800_0000; #[cfg(windows)] -const BACKGROUND_DAEMON_CREATION_FLAGS: u32 = - CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS | CREATE_NO_WINDOW; +// Windows ignores CREATE_NO_WINDOW when DETACHED_PROCESS is also set. +const BACKGROUND_DAEMON_CREATION_FLAGS: u32 = CREATE_NO_WINDOW; + +#[cfg(all(test, windows))] +mod background_creation_flags_tests { + use super::{BACKGROUND_DAEMON_CREATION_FLAGS, CREATE_NO_WINDOW}; + + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + const DETACHED_PROCESS: u32 = 0x0000_0008; + + #[test] + fn background_daemon_flags_request_no_window_without_detaching() { + assert_ne!(BACKGROUND_DAEMON_CREATION_FLAGS & CREATE_NO_WINDOW, 0); + assert_eq!( + BACKGROUND_DAEMON_CREATION_FLAGS & CREATE_NEW_PROCESS_GROUP, + 0 + ); + assert_eq!(BACKGROUND_DAEMON_CREATION_FLAGS & DETACHED_PROCESS, 0); + } +} const DAEMON_READY_ATTEMPTS: usize = 300; const DAEMON_READY_POLL_INTERVAL: Duration = Duration::from_millis(100); +const DAEMON_READY_CONNECT_TIMEOUT: Duration = Duration::from_millis(100); #[cfg(unix)] fn start_new_unix_session() -> io::Result<()> { @@ -124,7 +139,7 @@ pub async fn ensure_daemon_running_with_options( paths: &RuntimePaths, options: DaemonLaunchOptions, ) -> IpcClientResult<()> { - if daemon_is_ready(paths).await? { + if daemon_is_ready_for_launch(paths).await? { return Ok(()); } @@ -194,7 +209,7 @@ async fn wait_for_daemon_ready( child: &mut tokio::process::Child, ) -> IpcClientResult<()> { for _ in 0..DAEMON_READY_ATTEMPTS { - if daemon_is_ready(paths).await? { + if daemon_is_ready_for_launch(paths).await? { return Ok(()); } if child @@ -238,17 +253,36 @@ pub(super) async fn daemon_is_ready(paths: &RuntimePaths) -> IpcClientResult IpcClientResult { + daemon_is_ready_with_deadlines( + paths, + IpcClientDeadlines { + connect: DAEMON_READY_CONNECT_TIMEOUT, + ..IpcClientDeadlines::default() + }, + ) + .await +} + pub(super) async fn daemon_is_ready_with_deadlines( paths: &RuntimePaths, deadlines: IpcClientDeadlines, ) -> IpcClientResult { match CadderSession::connect_with_deadlines(paths, deadlines).await { Ok(_) => Ok(true), - Err(error) if error.is_stale_instance() || error.is_daemon_unavailable() => Ok(false), + Err(error) if daemon_not_ready_yet(&error) => Ok(false), Err(error) => Err(error), } } +fn daemon_not_ready_yet(error: &IpcClientError) -> bool { + error.is_stale_instance() + || error.is_daemon_unavailable() + || error.local_error().is_some_and(|error| { + error.phase() == IpcClientPhase::Connect && error.code() == LocalIpcErrorCode::Timeout + }) +} + fn sibling_binary(name: &str) -> Option { let current = env::current_exe().ok()?; let dir = current.parent()?; @@ -283,3 +317,17 @@ fn prepend_path_dir(command: &mut Command, dir: &std::path::Path) { command.env("PATH", joined); } } + +#[cfg(test)] +mod readiness_tests { + use super::*; + + #[test] + fn launch_readiness_retries_connection_timeouts() { + let timeout = super::super::client::connection_timeout_error(); + assert!(daemon_not_ready_yet(&timeout)); + + let permanent = super::super::client::connection_error(io::Error::other("connect failed")); + assert!(!daemon_not_ready_yet(&permanent)); + } +} diff --git a/crates/cadder-daemon/src/process_tree.rs b/crates/cadder-daemon/src/process_tree.rs index 796768a..1de0dbb 100644 --- a/crates/cadder-daemon/src/process_tree.rs +++ b/crates/cadder-daemon/src/process_tree.rs @@ -1,15 +1,17 @@ use anyhow::{Context, Result}; -#[cfg(windows)] -use process_wrap::tokio::JobObject; #[cfg(unix)] use process_wrap::tokio::ProcessGroup; use process_wrap::tokio::{ChildWrapper, CommandWrap, KillOnDrop}; +#[cfg(windows)] +use process_wrap::tokio::{CreationFlags, JobObject}; use std::{io, process::Output, time::Duration}; use tokio::{ io::AsyncReadExt, process::{ChildStderr, ChildStdout, Command}, time::timeout, }; +#[cfg(windows)] +use windows::Win32::System::Threading::CREATE_NO_WINDOW; const CLEANUP_TIMEOUT: Duration = Duration::from_secs(5); @@ -24,7 +26,10 @@ impl ProcessTreeChild { #[cfg(unix)] command.wrap(ProcessGroup::leader()); #[cfg(windows)] - command.wrap(JobObject); + { + command.wrap(CreationFlags(CREATE_NO_WINDOW)); + command.wrap(JobObject); + } command.wrap(KillOnDrop); Ok(Self { inner: command.spawn()?, diff --git a/crates/cadder-daemon/src/state/registrations.rs b/crates/cadder-daemon/src/state/registrations.rs index c36fe87..e4fceb5 100644 --- a/crates/cadder-daemon/src/state/registrations.rs +++ b/crates/cadder-daemon/src/state/registrations.rs @@ -608,11 +608,12 @@ async fn rollback_runtime_transition( }; if let Err(error) = receipt.rollback(&state.logs).await { state.begin_operation_drain(); + state.request_shutdown(); state.logs.append( LogStreamIdentity::runtime_control(), LogSeverity::Error, format!( - "runtime transition rollback failed after rejected registration; Cadder entered read-only drain: {error:#}" + "runtime transition rollback failed after rejected registration; Cadder requested shutdown: {error:#}" ), LogAttributionKind::RuntimeControl, Some("registration-rollback".to_string()), @@ -909,6 +910,26 @@ mod tests { assert!(!registration_mutation_domain_conflict(conflict).accepted); } + #[tokio::test] + async fn failed_runtime_rollback_requests_daemon_shutdown() { + let temp = tempfile::tempdir().unwrap(); + let paths = RuntimePaths::resolve(Some(temp.path().join("runtime"))).unwrap(); + let coordinator = CaddyConfigCoordinator::new_mock(paths.clone()); + let runtime = coordinator.runtime(); + let state = DaemonState::new(coordinator); + let attempt = runtime + .begin_apply_config(br#"{"apps":{}}"#, &state.logs) + .await + .unwrap(); + let (receipt, outcome) = attempt.into_parts(); + outcome.unwrap(); + std::fs::create_dir(paths.effective_config_path()).unwrap(); + + rollback_runtime_transition(&state, Some(RuntimeTransitionReceipt::Apply(receipt))).await; + + assert!(state.shutdown_signal().started_at().is_some()); + } + #[test] fn owner_comparison_distinguishes_matching_missing_and_replaced_sessions() { let existing = registration("entry-1", "nonce-1", "app.localhost", true, true); diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index 34553f8..b651010 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -12,7 +12,7 @@ export default defineConfig({ integrations: [ starlight({ title: 'Cadder', - description: 'Cadder coordinates Caddy routes across local repositories so their apps can use stable addresses through one shared web server and reverse proxy.', + description: 'Cadder coordinates Caddy routes across local repositories so their apps can use stable addresses through one shared reverse proxy.', favicon: 'favicon.ico', logo: { src: './src/assets/logo.png', diff --git a/docs/site/src/components/CadderFooter.astro b/docs/site/src/components/CadderFooter.astro index 2b89ca7..2fd264f 100644 --- a/docs/site/src/components/CadderFooter.astro +++ b/docs/site/src/components/CadderFooter.astro @@ -20,6 +20,9 @@ const heartPathData = Array.isArray(heartPath) ? heartPath[0] : heartPath; )} {hasSidebar && } +

+ Caddy is a registered trademark of Stack Holdings GmbH; its logo identifies the upstream Caddy project. +