diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 318a8bf..8859352 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,6 +17,8 @@ concurrency: jobs: prepare: runs-on: ubuntu-latest + outputs: + manifest_digest: ${{ steps.manifest.outputs.digest }} env: RELEASE_TAG: ${{ github.event.release.tag_name }} RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} @@ -24,25 +26,59 @@ jobs: RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the release tag + - name: Authenticate the release source + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::RELEASE_TAG must be a stable vX.Y.Z tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::RELEASE_COMMIT must be a 40-character commit ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + exit 1 + fi + release_repo="$(mktemp -d "${RUNNER_TEMP}/flags-core-release.XXXXXX")" + trap 'rm -rf "${release_repo}"' EXIT + git init --bare --quiet "${release_repo}" + git -C "${release_repo}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + allowed_signers="${release_repo}/allowed-signers" + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${release_repo}" config gpg.format ssh + git -C "${release_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${release_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${release_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${release_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${release_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + [[ "${tag_commit,,}" == "${RELEASE_COMMIT,,}" ]] + git -C "${release_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main + + - name: Check out the immutable release commit uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: - ref: refs/tags/${{ github.event.release.tag_name }} + ref: ${{ github.sha }} + persist-credentials: false fetch-depth: 0 - - name: Fetch the protected release branch - run: git fetch --no-tags origin main:refs/remotes/origin/main - - name: Configure approved release signers shell: bash run: | - if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then - echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" - exit 1 - fi + set -euo pipefail allowed_signers="${RUNNER_TEMP}/release-allowed-signers" - umask 077 printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" git config --local gpg.format ssh git config --local gpg.ssh.allowedSignersFile "${allowed_signers}" @@ -53,11 +89,10 @@ jobs: uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false - name: Use the reviewed npm release - run: npm install --global npm@11.18.0 + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ - name: Install dependencies run: pnpm install --frozen-lockfile @@ -74,22 +109,73 @@ jobs: - name: Prepare and verify the release tarballs run: node scripts/release-packages.mjs pack --require-clean --require-main-ancestor --require-release-tag --expected-release-commit "${RELEASE_COMMIT}" --output .release + - name: Record the package manifest digest + id: manifest + shell: bash + run: | + set -euo pipefail + digest="$(sha256sum .release/package-manifest.json | awk '{print $1}')" + echo "digest=${digest}" >> "${GITHUB_OUTPUT}" + echo "Prepared manifest SHA-256 ${digest}" >> "${GITHUB_STEP_SUMMARY}" + - name: Upload the prepared release - id: upload uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: flags-core-release-${{ github.run_id }} path: .release/ if-no-files-found: error - include-hidden-files: true + include-hidden-files: false overwrite: true retention-days: 30 - - name: Record the prepared artifact digest - run: echo "Prepared artifact SHA-256 ${{ steps.upload.outputs.artifact-digest }}" >> "${GITHUB_STEP_SUMMARY}" + smoke: + needs: prepare + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - name: Check out the immutable release commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.sha }} + persist-credentials: false + fetch-depth: 1 + + - name: Set up Node.js + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24.18.0 + package-manager-cache: false + + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ + + - name: Check the prepared manifest output + shell: bash + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + run: | + set -euo pipefail + [[ "${EXPECTED_MANIFEST_DIGEST}" =~ ^[0-9a-f]{64}$ ]] + + - name: Download the prepared release + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: flags-core-release-${{ github.run_id }} + path: .release + + - name: Verify and import the prepared packages + shell: bash + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + run: | + set -euo pipefail + node -e 'const { createHash, timingSafeEqual } = require("node:crypto"); const { readFileSync } = require("node:fs"); const actual = createHash("sha256").update(readFileSync(".release/package-manifest.json")).digest(); const expected = Buffer.from(process.env.EXPECTED_MANIFEST_DIGEST, "hex"); if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) process.exit(1);' + node scripts/release-packages.mjs smoke --manifest .release/package-manifest.json publish: - needs: prepare + needs: [prepare, smoke] runs-on: ubuntu-latest environment: npm-publish permissions: @@ -97,27 +183,326 @@ jobs: id-token: write env: RELEASE_TAG: ${{ github.event.release.tag_name }} + RELEASE_PRERELEASE: ${{ github.event.release.prerelease }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_ALLOWED_SIGNERS: ${{ vars.RELEASE_ALLOWED_SIGNERS }} steps: - - name: Check out the exact release tag - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: refs/tags/${{ github.event.release.tag_name }} - fetch-depth: 1 + - name: Authenticate the release source + shell: bash + run: | + set -euo pipefail + if [[ "${RELEASE_PRERELEASE}" != "false" ]]; then + echo "::error::Only stable releases may publish packages" + exit 1 + fi + if [[ ! "${RELEASE_TAG}" =~ ^v(0\.[1-9][0-9]*|[1-9][0-9]*\.[0-9]+)\.[0-9]+$ ]]; then + echo "::error::RELEASE_TAG must be a stable vX.Y.Z tag" + exit 1 + fi + if [[ ! "${RELEASE_COMMIT}" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo "::error::RELEASE_COMMIT must be a 40-character commit ID" + exit 1 + fi + if [[ -z "${RELEASE_ALLOWED_SIGNERS}" ]]; then + echo "::error::RELEASE_ALLOWED_SIGNERS must contain the reviewed SSH allowed-signers entries" + exit 1 + fi + release_repo="$(mktemp -d "${RUNNER_TEMP}/flags-core-release.XXXXXX")" + trap 'rm -rf "${release_repo}"' EXIT + git init --bare --quiet "${release_repo}" + git -C "${release_repo}" remote add origin "https://github.com/${GITHUB_REPOSITORY}.git" + allowed_signers="${release_repo}/allowed-signers" + printf '%s\n' "${RELEASE_ALLOWED_SIGNERS}" > "${allowed_signers}" + chmod 0600 "${allowed_signers}" + git -C "${release_repo}" config gpg.format ssh + git -C "${release_repo}" config gpg.ssh.allowedSignersFile "${allowed_signers}" + git -C "${release_repo}" fetch --no-tags origin \ + refs/heads/main:refs/remotes/origin/main \ + "+refs/tags/${RELEASE_TAG}:refs/tags/${RELEASE_TAG}" + [[ "$(git -C "${release_repo}" cat-file -t "refs/tags/${RELEASE_TAG}")" == "tag" ]] + git -C "${release_repo}" verify-tag "refs/tags/${RELEASE_TAG}" + tag_commit="$(git -C "${release_repo}" rev-parse "refs/tags/${RELEASE_TAG}^{commit}")" + [[ "${tag_commit,,}" == "${RELEASE_COMMIT,,}" ]] + git -C "${release_repo}" merge-base --is-ancestor \ + "${RELEASE_COMMIT}" refs/remotes/origin/main - - name: Set up Node.js and the npm registry + - name: Set up Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24.18.0 - registry-url: https://registry.npmjs.org package-manager-cache: false + - name: Use the reviewed npm release + run: npm install --global npm@11.18.0 --ignore-scripts --registry https://registry.npmjs.org/ + - name: Download the prepared release uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: flags-core-release-${{ github.run_id }} path: .release - - name: Publish the verified prepared tarballs - run: node scripts/release-packages.mjs publish --expected-release-commit "${RELEASE_COMMIT}" --manifest .release/package-manifest.json + - name: Verify and publish the prepared tarballs + env: + EXPECTED_MANIFEST_DIGEST: ${{ needs.prepare.outputs.manifest_digest }} + shell: bash + run: | + set -euo pipefail + node <<'NODE' + const { spawnSync } = require("node:child_process"); + const { createHash, timingSafeEqual } = require("node:crypto"); + const { + chmodSync, + lstatSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, + } = require("node:fs"); + const { tmpdir } = require("node:os"); + const { basename, join, resolve } = require("node:path"); + + const registry = "https://registry.npmjs.org/"; + const releaseDirectory = resolve(".release"); + const manifestPath = join(releaseDirectory, "package-manifest.json"); + + function fail(message) { + throw new Error(message); + } + + function safeEqual(left, right) { + const leftBytes = Buffer.from(left); + const rightBytes = Buffer.from(right); + return ( + leftBytes.length === rightBytes.length && + timingSafeEqual(leftBytes, rightBytes) + ); + } + + function runNpm(arguments_, cwd, environment, allowFailure = false) { + const result = spawnSync("npm", arguments_, { + cwd, + env: environment, + encoding: "utf8", + stdio: "pipe", + }); + if (result.error) { + throw result.error; + } + if (result.status !== 0 && !allowFailure) { + fail( + `npm ${arguments_[0]} failed with exit code ${result.status}:\n${result.stdout}${result.stderr}`, + ); + } + return result; + } + + function parseNpmJson(stdout) { + const text = typeof stdout === "string" ? stdout : ""; + try { + return JSON.parse(text); + } catch {} + const starts = /[\[{"]|true\b|false\b|null\b|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/gu; + let match = starts.exec(text); + while (match !== null) { + try { + return JSON.parse(text.slice(match.index)); + } catch { + match = starts.exec(text); + } + } + fail("npm returned no JSON"); + } + + async function main() { + const manifestBytes = readFileSync(manifestPath); + const manifestDigest = createHash("sha256") + .update(manifestBytes) + .digest("hex"); + if (!safeEqual(manifestDigest, process.env.EXPECTED_MANIFEST_DIGEST ?? "")) { + fail("package manifest digest does not match preparation output"); + } + const manifest = JSON.parse(manifestBytes.toString("utf8")); + if ( + manifest.schemaVersion !== 1 || + manifest.releaseTag !== process.env.RELEASE_TAG || + manifest.gitCommit?.toLowerCase() !== process.env.RELEASE_COMMIT?.toLowerCase() || + !Array.isArray(manifest.packages) || + manifest.packages.length === 0 || + !manifest.packages.some(({ publish }) => publish === true) + ) { + fail("package manifest release metadata is invalid"); + } + + const expectedFiles = new Set([ + "package-manifest.json", + ...manifest.packages.map(({ tarball }) => tarball), + ]); + if (expectedFiles.size !== manifest.packages.length + 1) { + fail("package manifest contains duplicate tarball names"); + } + const entries = readdirSync(releaseDirectory, { withFileTypes: true }); + for (const expectedName of expectedFiles) { + if (!entries.some(({ name }) => name === expectedName)) { + fail(`release directory is missing ${expectedName}`); + } + } + if (entries.length !== expectedFiles.size) { + fail("release directory inventory does not match the package manifest"); + } + for (const entry of entries) { + if ( + entry.name.startsWith(".") || + !expectedFiles.has(entry.name) || + !entry.isFile() || + entry.isSymbolicLink() + ) { + fail(`unexpected release entry: ${entry.name}`); + } + const metadata = lstatSync(join(releaseDirectory, entry.name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) { + fail(`release entry must be a regular file: ${entry.name}`); + } + } + + for (const record of manifest.packages) { + const expectedTarball = `${record.name + ?.slice(1) + .replace("/", "-")}-${record.version}.tgz`; + if ( + typeof record.name !== "string" || + !record.name.startsWith("@pegma/") || + typeof record.version !== "string" || + !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(record.version) || + typeof record.tarball !== "string" || + basename(record.tarball) !== record.tarball || + record.tarball !== expectedTarball || + record.publish !== (record.version === manifest.releaseTag.slice(1)) || + !/^[0-9a-f]{64}$/u.test(record.sha256) || + !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(record.integrity) + ) { + fail("package manifest contains invalid package metadata"); + } + const bytes = readFileSync(join(releaseDirectory, record.tarball)); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + if (!safeEqual(sha256, record.sha256) || !safeEqual(integrity, record.integrity)) { + fail(`${record.name} tarball digest does not match the package manifest`); + } + } + + const npmDirectory = mkdtempSync(join(tmpdir(), "flags-core-publish-")); + try { + const userConfig = join(npmDirectory, "user.npmrc"); + const globalConfig = join(npmDirectory, "global.npmrc"); + writeFileSync(userConfig, "", { mode: 0o600 }); + writeFileSync(globalConfig, "", { mode: 0o600 }); + chmodSync(userConfig, 0o600); + chmodSync(globalConfig, 0o600); + const environment = {}; + const exact = new Set([ + "CI", + "PATH", + "HOME", + "RUNNER_TEMP", + "TMP", + "TMPDIR", + "SYSTEMROOT", + ]); + for (const [key, value] of Object.entries(process.env)) { + if ( + value !== undefined && + (exact.has(key) || + key.startsWith("TMP") || + (key.startsWith("GITHUB_") && key !== "GITHUB_TOKEN") || + key.startsWith("ACTIONS_ID_TOKEN_")) + ) { + environment[key] = value; + } + } + environment.NPM_CONFIG_USERCONFIG = userConfig; + environment.NPM_CONFIG_GLOBALCONFIG = globalConfig; + + const npmVersion = runNpm( + ["--version"], + npmDirectory, + environment, + ).stdout.trim(); + if (npmVersion !== "11.18.0") { + fail(`expected npm 11.18.0, received ${npmVersion}`); + } + + const common = [ + "--registry", + registry, + "--ignore-scripts", + "--userconfig", + userConfig, + "--globalconfig", + globalConfig, + ]; + for (const record of manifest.packages.filter(({ publish }) => publish)) { + const spec = `${record.name}@${record.version}`; + const lookup = runNpm( + ["view", spec, "dist.integrity", "--json", ...common], + npmDirectory, + environment, + true, + ); + if (lookup.status === 0) { + const existing = parseNpmJson(lookup.stdout); + if (typeof existing !== "string" || !safeEqual(existing, record.integrity)) { + fail(`${spec} already exists with different package bytes`); + } + process.stdout.write(`Verified existing ${spec}; skipping.\n`); + continue; + } + if (!/\bE404\b/u.test(`${lookup.stdout}\n${lookup.stderr}`)) { + fail(`npm registry lookup failed for ${spec}:\n${lookup.stdout}${lookup.stderr}`); + } + runNpm( + [ + "publish", + join(releaseDirectory, record.tarball), + "--tag", + "latest", + "--access", + "public", + "--provenance", + ...common, + ], + npmDirectory, + environment, + ); + let visible = false; + for (let attempt = 0; attempt < 6; attempt += 1) { + const check = runNpm( + ["view", spec, "dist.integrity", "--json", ...common], + npmDirectory, + environment, + true, + ); + if ( + check.status === 0 && + safeEqual(parseNpmJson(check.stdout), record.integrity) + ) { + visible = true; + break; + } + await new Promise((resolve_) => setTimeout(resolve_, 2 ** attempt * 1_000)); + } + if (!visible) { + fail(`${spec} did not become visible with the prepared integrity`); + } + } + } finally { + rmSync(npmDirectory, { recursive: true, force: true }); + } + } + + main().catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }); + NODE diff --git a/docs/RELEASING.md b/docs/RELEASING.md index 09f3a35..ef6652f 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -44,24 +44,31 @@ After that pull request is merged, create a signed annotated tag at the exact create the GitHub release with `--verify-tag`. Do not let GitHub create the tag and never move or recreate a release tag. -The release workflow verifies that the tag: +Before checkout or dependency commands in the preparation job, the release +workflow fetches only `main` and the named tag into a temporary bare +repository and verifies that the tag: - is a stable annotated `vX.Y.Z` tag signed by an allowed signer; - matches a public package version; - points to the checkout and the GitHub release-event commit; and - is contained in `origin/main`. -Its preparation job has no OIDC permission. It installs the reviewed npm +The checkout then uses the immutable release-event commit rather than the tag +name. The preparation job has no OIDC permission. It installs the reviewed npm `11.18.0` release and the pinned pnpm without dependency caching, runs the -full gate, builds and packs once with that npm CLI, smoke-tests the tarballs -from a clean consumer, records SHA-1 and SHA-512 integrity, and uploads -the exact prepared artifacts. The lockfile source of truth is `pnpm-lock.yaml`. - -Only the `npm-publish` job receives `id-token: write`. It installs no -dependencies and does not download pnpm. It runs -`node scripts/release-packages.mjs publish`, verifies the prepared manifest -and tarball hashes against the release commit, and publishes those tarballs -with npm provenance. +full gate, builds and packs once with that npm CLI, revalidates each packed +manifest, records SHA-1, SHA-256, and SHA-512 integrity, seals the exact +release-directory inventory, and uploads the prepared artifacts. The lockfile +source of truth is `pnpm-lock.yaml`. + +A separate unprivileged job checks out the immutable event commit, downloads +the sealed artifact, and installs every tarball into a clean consumer before +importing every public export. Only the `npm-publish` job receives +`id-token: write`. That job authenticates the tag again before any dependency +command, checks out no repository content, installs no project dependencies, +and does not download pnpm. Workflow-owned code verifies the prepared +manifest digest, exact file inventory, and tarball hashes, then publishes from +an isolated temporary directory with npm provenance. ## Safe retry diff --git a/package.json b/package.json index f9cd31c..c544d06 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "format:check": "prettier --check .", "release:check": "node scripts/release-packages.mjs check", "release:pack": "node scripts/release-packages.mjs pack", + "release:smoke": "node scripts/release-packages.mjs smoke", "release:publish": "node scripts/release-packages.mjs publish", "test": "pnpm run build && vitest run" }, diff --git a/packages/flags-contracts/src/index.ts b/packages/flags-contracts/src/index.ts index fad08d5..080d98f 100644 --- a/packages/flags-contracts/src/index.ts +++ b/packages/flags-contracts/src/index.ts @@ -61,6 +61,7 @@ export interface FlagResolutionRequest { readonly defaultValue: unknown; readonly kind: FlagValueKind; readonly context: EvaluationContext; + readonly signal?: AbortSignal; } export interface FlagProviderCapabilities { diff --git a/packages/flags-core/README.md b/packages/flags-core/README.md index bb7e42c..1be251a 100644 --- a/packages/flags-core/README.md +++ b/packages/flags-core/README.md @@ -38,3 +38,12 @@ The client never blocks a request on an unbounded provider call. A timeout or error returns the default (or a stale cache entry) with an explicit reason and a log line. This package does not author flags and does not evaluate targeting rules. + +Provider calls receive an optional `AbortSignal`. When an evaluation context +has a bounded canonical identity, concurrent misses share one provider call +and completed values can enter the cache. Oversized or non-canonical contexts +skip both mechanisms. The evaluation cache is an LRU capped at 1,024 entries +by default. Set `maxCacheEntries` to a smaller non-negative integer when a +host needs a tighter bound; zero disables stored entries. Cache identity +covers the complete evaluation context, while client fallback logs include +the flag key and coarse reason without the raw `targetingKey`. diff --git a/packages/flags-core/src/client.test.ts b/packages/flags-core/src/client.test.ts index 7a36c9d..bb462ab 100644 --- a/packages/flags-core/src/client.test.ts +++ b/packages/flags-core/src/client.test.ts @@ -101,6 +101,45 @@ describe("createFlagsClient", () => { ).rejects.toThrow("targetingKey"); }); + it("requires a schema entry to be an own property", async () => { + const inherited = { + inherited: flag.boolean({ defaultValue: false }), + }; + const inheritedSchema = Object.create(inherited) as typeof schema; + Object.assign(inheritedSchema, schema); + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema: inheritedSchema, + logger, + provider: staticProvider({ inherited: true }), + }); + await expect( + client.evaluate("inherited" as keyof typeof schema, { + targetingKey: "user-1", + }), + ).rejects.toThrow("unknown flag"); + }); + + it("validates the cache entry limit", () => { + const { logger } = memoryLogger(); + expect(() => + createFlagsClient({ + schema, + logger, + provider: staticProvider({}), + maxCacheEntries: -1, + }), + ).toThrow("non-negative integer"); + expect(() => + createFlagsClient({ + schema, + logger, + provider: staticProvider({}), + maxCacheEntries: 1.5, + }), + ).toThrow("non-negative integer"); + }); + it("returns a fresh cache hit with the original reason", async () => { let resolves = 0; const { logger } = memoryLogger(); @@ -357,6 +396,356 @@ describe("createFlagsClient", () => { expect(omitted).not.toBe(empty); }); + it("covers every context field and canonicalizes attributes", () => { + const base = { + targetingKey: "user-1", + principalId: "principal-1" as NonNullable< + EvaluationContext["principalId"] + >, + tenant: "tenant-1", + environment: "production", + attributes: { beta: 2, alpha: "one" }, + } satisfies EvaluationContext; + const reordered = { + ...base, + attributes: { alpha: "one", beta: 2 }, + } satisfies EvaluationContext; + expect(cacheIdentity("theme", base)).toBe( + cacheIdentity("theme", reordered), + ); + expect(cacheIdentity("other", base)).not.toBe(cacheIdentity("theme", base)); + const { principalId: _principalId, ...withoutPrincipal } = base; + expect(cacheIdentity("theme", withoutPrincipal)).not.toBe( + cacheIdentity("theme", base), + ); + expect(cacheIdentity("theme", { ...base, tenant: "other" })).not.toBe( + cacheIdentity("theme", base), + ); + expect( + cacheIdentity("theme", { ...base, environment: "staging" }), + ).not.toBe(cacheIdentity("theme", base)); + expect( + cacheIdentity("theme", { ...base, attributes: { alpha: "one" } }), + ).not.toBe(cacheIdentity("theme", base)); + }); + + it("skips caching oversized identities", async () => { + let resolves = 0; + const { logger } = memoryLogger(); + const provider: FlagProvider = { + name: "counting", + capabilities() { + return { static: true, streaming: false, targeting: true }; + }, + async resolve() { + resolves += 1; + return { value: "dark", reason: "TARGETING_MATCH" }; + }, + }; + const context = { + targetingKey: "user-1", + attributes: { note: "x".repeat(9_000) }, + } satisfies EvaluationContext; + expect(cacheIdentity("theme", context)).toBeUndefined(); + const client = createFlagsClient({ schema, logger, provider }); + await client.evaluate("theme", context); + await client.evaluate("theme", context); + expect(resolves).toBe(2); + }); + + it("does not partially encode non-standard attributes", () => { + const nonEnumerable: Record = {}; + Object.defineProperty(nonEnumerable, "hidden", { + value: "one", + enumerable: false, + }); + expect( + cacheIdentity("theme", { + targetingKey: "user-1", + attributes: nonEnumerable, + }), + ).not.toBe( + cacheIdentity("theme", { + targetingKey: "user-1", + attributes: {}, + }), + ); + + const sparse: unknown[] = []; + sparse[1] = "one"; + expect( + cacheIdentity("theme", { + targetingKey: "user-1", + attributes: { + sparse, + } as NonNullable, + }), + ).toBeUndefined(); + }); + + it("skips caching oversized values", async () => { + let resolves = 0; + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + provider: { + name: "large-value", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + async resolve() { + resolves += 1; + return { value: "x".repeat(70_000), reason: "TARGETING_MATCH" }; + }, + }, + }); + await client.evaluate("theme", { targetingKey: "user-1" }); + await client.evaluate("theme", { targetingKey: "user-1" }); + expect(resolves).toBe(2); + }); + + it("evicts the least recently used cache entry", async () => { + let resolves = 0; + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + maxCacheEntries: 2, + cacheTtlMs: 60_000, + provider: { + name: "context-value", + capabilities() { + return { static: true, streaming: false, targeting: true }; + }, + async resolve(request) { + resolves += 1; + return { + value: request.context.targetingKey, + reason: "TARGETING_MATCH", + }; + }, + }, + }); + await client.evaluate("theme", { targetingKey: "user-1" }); + await client.evaluate("theme", { targetingKey: "user-2" }); + await client.evaluate("theme", { targetingKey: "user-1" }); + await client.evaluate("theme", { targetingKey: "user-3" }); + await client.evaluate("theme", { targetingKey: "user-2" }); + expect(resolves).toBe(4); + }); + + it("treats a zero cache entry limit as disabled", async () => { + let resolves = 0; + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + maxCacheEntries: 0, + provider: { + name: "counting", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + async resolve() { + resolves += 1; + return { value: true, reason: "TARGETING_MATCH" }; + }, + }, + }); + await client.evaluate("checkoutEnabled", { targetingKey: "user-1" }); + await client.evaluate("checkoutEnabled", { targetingKey: "user-1" }); + expect(resolves).toBe(2); + }); + + it("coalesces concurrent cache misses", async () => { + let resolves = 0; + let complete: ((resolution: FlagResolution) => void) | undefined; + const pending = new Promise((resolve) => { + complete = resolve; + }); + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + provider: { + name: "deferred", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + resolve() { + resolves += 1; + return pending; + }, + }, + }); + const first = client.evaluate("checkoutEnabled", { + targetingKey: "user-1", + }); + const second = client.evaluate("checkoutEnabled", { + targetingKey: "user-1", + }); + await Promise.resolve(); + complete?.({ value: true, reason: "TARGETING_MATCH" }); + await expect(Promise.all([first, second])).resolves.toEqual([ + expect.objectContaining({ value: true }), + expect.objectContaining({ value: true }), + ]); + expect(resolves).toBe(1); + }); + + it("aborts timed out work and keeps it coalesced until settlement", async () => { + let resolves = 0; + let signal: AbortSignal | undefined; + let complete: ((resolution: FlagResolution) => void) | undefined; + const pending = new Promise((resolve) => { + complete = resolve; + }); + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + timeoutMs: 10, + provider: { + name: "deferred", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + resolve(request) { + resolves += 1; + signal = request.signal; + return pending; + }, + }, + }); + await expect( + client.evaluate("checkoutEnabled", { targetingKey: "user-1" }), + ).resolves.toMatchObject({ reason: "ERROR", errorCode: "TIMEOUT" }); + expect(signal?.aborted).toBe(true); + await expect( + client.evaluate("checkoutEnabled", { targetingKey: "user-1" }), + ).resolves.toMatchObject({ reason: "ERROR", errorCode: "TIMEOUT" }); + expect(resolves).toBe(1); + complete?.({ value: true, reason: "TARGETING_MATCH" }); + await Promise.resolve(); + }); + + it("does not report a close-initiated provider error as a timeout", async () => { + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + provider: { + name: "close-aware", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + resolve(request) { + return new Promise((_resolve, reject) => { + request.signal?.addEventListener( + "abort", + () => { + reject(new Error("provider closed")); + }, + { once: true }, + ); + }); + }, + }, + }); + const evaluation = client.evaluate("checkoutEnabled", { + targetingKey: "user-1", + }); + await Promise.resolve(); + await client.close(); + await expect(evaluation).resolves.toMatchObject({ + reason: "ERROR", + errorCode: "PROVIDER", + errorMessage: "provider closed", + }); + }); + + it("bounds unresolved provider calls", async () => { + let resolves = 0; + const { logger } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + timeoutMs: 5, + provider: { + name: "pending", + capabilities() { + return { static: true, streaming: false, targeting: true }; + }, + resolve() { + resolves += 1; + return new Promise(() => { + // Remains pending for this check. + }); + }, + }, + }); + const results = await Promise.all( + Array.from({ length: 129 }, (_, index) => + client.evaluate("checkoutEnabled", { + targetingKey: `user-${String(index)}`, + }), + ), + ); + expect(resolves).toBe(128); + expect( + results.filter(({ errorCode }) => errorCode === "CAPACITY"), + ).toHaveLength(1); + expect( + results.filter(({ errorCode }) => errorCode === "TIMEOUT"), + ).toHaveLength(128); + await client.close(); + }); + + it("omits targeting keys from client log fields", async () => { + let current = "2026-08-15T12:00:00.000Z"; + let resolves = 0; + const { logger, events } = memoryLogger(); + const client = createFlagsClient({ + schema, + logger, + clock: { now: () => current }, + cacheTtlMs: 1, + staleWhileRevalidateMs: 60_000, + provider: { + name: "then-fail", + capabilities() { + return { static: true, streaming: false, targeting: false }; + }, + async resolve() { + resolves += 1; + if (resolves === 1) { + return { value: "dark", reason: "DEFAULT_FALLBACK" }; + } + throw new Error("provider unavailable"); + }, + }, + }); + await client.evaluate("theme", { targetingKey: "private-key" }); + current = "2026-08-15T12:00:01.000Z"; + await client.evaluate("theme", { targetingKey: "private-key" }); + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + expect(events).not.toHaveLength(0); + expect(events.map(({ message }) => message)).toEqual( + expect.arrayContaining([ + "flags.fallback", + "flags.stale_cache", + "flags.refresh_failed", + ]), + ); + for (const event of events) { + expect(event.fields).not.toHaveProperty("targetingKey"); + expect(JSON.stringify(event.fields)).not.toContain("private-key"); + } + }); + it("sanitizes provider errorMessage on a successful resolution", async () => { const { logger } = memoryLogger(); const client = createFlagsClient({ diff --git a/packages/flags-core/src/client.ts b/packages/flags-core/src/client.ts index b5b2d67..b01d791 100644 --- a/packages/flags-core/src/client.ts +++ b/packages/flags-core/src/client.ts @@ -16,7 +16,14 @@ import { const DEFAULT_TIMEOUT_MS = 1_000; const DEFAULT_CACHE_TTL_MS = 5_000; const DEFAULT_STALE_WHILE_REVALIDATE_MS = 30_000; +const DEFAULT_MAX_CACHE_ENTRIES = 1_024; +const MAX_CACHE_IDENTITY_CHARS = 8_192; +const MAX_CACHED_VALUE_CHARS = 65_536; +const MAX_CANONICAL_ENTRIES = 4_096; +const MAX_IN_FLIGHT_PROVIDER_CALLS = 128; +const EXPIRED_SWEEP_LIMIT = 16; const MAX_LOGGED_ERROR_CHARS = 300; +const UTF8_ENCODER = new TextEncoder(); class EvaluationTimeoutError extends Error { constructor(timeoutMs: number) { @@ -25,6 +32,15 @@ class EvaluationTimeoutError extends Error { } } +class ProviderCapacityError extends Error { + constructor() { + super("flag provider concurrency limit reached"); + this.name = "ProviderCapacityError"; + } +} + +class CacheEncodingError extends Error {} + interface CacheEntry { readonly flagKey: string; readonly value: unknown; @@ -33,6 +49,11 @@ interface CacheEntry { readonly storedAtMs: number; } +interface ProviderWork { + readonly controller: AbortController; + readonly promise: Promise; +} + export interface FlagsClientOptions< TSchema extends Record>, > { @@ -43,6 +64,7 @@ export interface FlagsClientOptions< readonly timeoutMs?: number; readonly cacheTtlMs?: number; readonly staleWhileRevalidateMs?: number; + readonly maxCacheEntries?: number; } export interface FlagsClient< @@ -73,28 +95,130 @@ function requireTargetingKey(context: EvaluationContext): void { } } +function canonicalValue(value: unknown, seen: Set): unknown { + if (value === null) { + return ["null"]; + } + switch (typeof value) { + case "boolean": + return ["boolean", value]; + case "number": + if (!Number.isFinite(value)) { + throw new CacheEncodingError(); + } + return ["number", Object.is(value, -0) ? "-0" : String(value)]; + case "string": + return ["string", value]; + case "object": { + if (seen.has(value)) { + throw new CacheEncodingError(); + } + seen.add(value); + try { + if (Array.isArray(value)) { + if ( + value.length > MAX_CANONICAL_ENTRIES || + Object.getOwnPropertySymbols(value).length !== 0 || + Object.getOwnPropertyNames(value).some( + (key) => + key !== "length" && + (!/^(0|[1-9]\d*)$/u.test(key) || Number(key) >= value.length), + ) + ) { + throw new CacheEncodingError(); + } + const entries: unknown[] = []; + for (let index = 0; index < value.length; index += 1) { + if (!Object.hasOwn(value, index)) { + throw new CacheEncodingError(); + } + entries.push(canonicalValue(value[index], seen)); + } + return ["array", entries]; + } + const prototype = Object.getPrototypeOf(value); + if (prototype !== Object.prototype && prototype !== null) { + throw new CacheEncodingError(); + } + if (Object.getOwnPropertySymbols(value).length !== 0) { + throw new CacheEncodingError(); + } + const keys = Object.getOwnPropertyNames(value).sort(); + if (keys.length > MAX_CANONICAL_ENTRIES) { + throw new CacheEncodingError(); + } + return [ + "object", + keys.map((key) => { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + if (descriptor === undefined || !("value" in descriptor)) { + throw new CacheEncodingError(); + } + return [["key", key], canonicalValue(descriptor.value, seen)]; + }), + ]; + } finally { + seen.delete(value); + } + } + default: + throw new CacheEncodingError(); + } +} + +function optionalIdentityField(value: unknown): unknown { + return value === undefined + ? ["missing"] + : ["present", canonicalValue(value, new Set())]; +} + /** - * Encodes flag + targeting identity so omitted fields stay distinct from - * empty strings, and component text cannot cross a separator boundary. + * Canonically encodes every provider-visible context field. Oversized or + * non-serializable runtime input is deliberately not cacheable. */ export function cacheIdentity( flagKey: string, context: EvaluationContext, -): string { - return JSON.stringify({ - flagKey, - targetingKey: context.targetingKey, - tenant: context.tenant === undefined ? null : context.tenant, - environment: context.environment === undefined ? null : context.environment, - }); +): string | undefined { + try { + const identity = JSON.stringify([ + "flag-evaluation", + ["flagKey", canonicalValue(flagKey, new Set())], + ["targetingKey", canonicalValue(context.targetingKey, new Set())], + ["principalId", optionalIdentityField(context.principalId)], + ["tenant", optionalIdentityField(context.tenant)], + ["environment", optionalIdentityField(context.environment)], + ["attributes", optionalIdentityField(context.attributes)], + ]); + return UTF8_ENCODER.encode(identity).byteLength <= MAX_CACHE_IDENTITY_CHARS + ? identity + : undefined; + } catch { + return undefined; + } +} + +function isCacheableValue(value: unknown): boolean { + try { + return ( + UTF8_ENCODER.encode(JSON.stringify(canonicalValue(value, new Set()))) + .byteLength <= MAX_CACHED_VALUE_CHARS + ); + } catch { + return false; + } } -function withTimeout(promise: Promise, timeoutMs: number): Promise { - return new Promise((resolve, reject) => { +function waitForProvider( + work: ProviderWork, + timeoutMs: number, +): Promise { + return new Promise((resolve, reject) => { const timer = setTimeout(() => { + work.controller.abort(); reject(new EvaluationTimeoutError(timeoutMs)); }, timeoutMs); - promise.then( + work.promise.then( (value) => { clearTimeout(timer); resolve(value); @@ -109,8 +233,8 @@ function withTimeout(promise: Promise, timeoutMs: number): Promise { /** * Error text is provider-supplied and may carry remote input, so control - * characters (which forge log lines in text-oriented sinks) are flattened - * and the string is capped before it reaches a logger. + * characters are flattened and the string is capped before it reaches a + * logger. */ export function loggableError(error: unknown): string { const text = error instanceof Error ? error.message : String(error); @@ -178,21 +302,16 @@ function logFallback( logger: Logger, reason: EvaluationReason, flagKey: string, - context: EvaluationContext, error?: unknown, ): void { logger.log(reason === "ERROR" ? "warn" : "info", "flags.fallback", { flagKey, reason, - targetingKey: context.targetingKey, ...(error === undefined ? {} : { error: loggableError(error) }), }); } -/** - * Constructs an injected evaluation client. The host owns the instance; - * nothing here is stored globally. - */ +/** Constructs an injected evaluation client owned by the host. */ export function createFlagsClient< TSchema extends Record>, >(options: FlagsClientOptions): FlagsClient { @@ -208,12 +327,20 @@ export function createFlagsClient< const cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS; const staleWhileRevalidateMs = options.staleWhileRevalidateMs ?? DEFAULT_STALE_WHILE_REVALIDATE_MS; + const maxCacheEntries = options.maxCacheEntries ?? DEFAULT_MAX_CACHE_ENTRIES; + if (!Number.isInteger(maxCacheEntries) || maxCacheEntries < 0) { + throw new Error("maxCacheEntries must be a non-negative integer"); + } + const cache = new Map(); - const inFlight = new Map>(); + const inFlight = new Map(); + const activeWorks = new Set(); - function readCache(identity: string, atMs: number): CacheEntry | undefined { - if (cacheTtlMs <= 0) { - cache.delete(identity); + function readCache( + identity: string | undefined, + atMs: number, + ): CacheEntry | undefined { + if (identity === undefined || cacheTtlMs <= 0 || maxCacheEntries === 0) { return undefined; } const entry = cache.get(identity); @@ -221,26 +348,45 @@ export function createFlagsClient< return undefined; } const age = atMs - entry.storedAtMs; - if (age < cacheTtlMs) { - return entry; - } - if (age < cacheTtlMs + staleWhileRevalidateMs) { - return entry; + if (age >= cacheTtlMs + staleWhileRevalidateMs) { + cache.delete(identity); + return undefined; } cache.delete(identity); - return undefined; + cache.set(identity, entry); + return entry; + } + + function sweepExpired(atMs: number): void { + let examined = 0; + for (const [identity, entry] of cache) { + if (examined >= EXPIRED_SWEEP_LIMIT) { + return; + } + examined += 1; + if (atMs - entry.storedAtMs >= cacheTtlMs + staleWhileRevalidateMs) { + cache.delete(identity); + } + } } function writeCache( - identity: string, + identity: string | undefined, flagKey: string, value: unknown, resolution: FlagResolution, atMs: number, ): void { - if (cacheTtlMs <= 0) { + if ( + identity === undefined || + cacheTtlMs <= 0 || + maxCacheEntries === 0 || + !isCacheableValue(value) + ) { return; } + sweepExpired(atMs); + cache.delete(identity); cache.set(identity, { flagKey, value, @@ -250,6 +396,62 @@ export function createFlagsClient< : { variant: resolution.variant }), storedAtMs: atMs, }); + while (cache.size > maxCacheEntries) { + const oldest = cache.keys().next().value as string | undefined; + if (oldest === undefined) { + break; + } + cache.delete(oldest); + } + } + + function providerWork( + identity: string | undefined, + flagKey: string, + definition: FlagDefinition, + context: EvaluationContext, + ): ProviderWork { + if (identity !== undefined) { + const existing = inFlight.get(identity); + if (existing !== undefined) { + return existing; + } + } + if (activeWorks.size >= MAX_IN_FLIGHT_PROVIDER_CALLS) { + throw new ProviderCapacityError(); + } + + const controller = new AbortController(); + let work: ProviderWork; + const promise = Promise.resolve().then(() => + options.provider.resolve({ + flagKey, + defaultValue: definition.defaultValue, + kind: definition.kind, + context, + signal: controller.signal, + }), + ); + work = { controller, promise }; + activeWorks.add(work); + if (identity !== undefined) { + inFlight.set(identity, work); + } + void promise.then( + () => { + activeWorks.delete(work); + if (identity !== undefined && inFlight.get(identity) === work) { + inFlight.delete(identity); + } + }, + () => { + activeWorks.delete(work); + if (identity !== undefined && inFlight.get(identity) === work) { + inFlight.delete(identity); + } + }, + ); + return work; } function refresh( @@ -257,58 +459,47 @@ export function createFlagsClient< flagKey: string, definition: FlagDefinition, context: EvaluationContext, - ): Promise { - const existing = inFlight.get(identity); - if (existing !== undefined) { - return existing; + ): void { + if (inFlight.has(identity)) { + return; + } + let work: ProviderWork; + try { + work = providerWork(identity, flagKey, definition, context); + } catch (error) { + logger.log("warn", "flags.refresh_failed", { + flagKey, + error: loggableError(error), + }); + return; } - const pending = (async () => { + void (async () => { try { - const resolution = await withTimeout( - options.provider.resolve({ - flagKey, - defaultValue: definition.defaultValue, - kind: definition.kind, - context, - }), - timeoutMs, - ); + const resolution = await waitForProvider(work, timeoutMs); const value = decodeFlagValue(definition, resolution.value, flagKey); writeCache(identity, flagKey, value, resolution, nowMs(clock)); } catch (error) { logger.log("warn", "flags.refresh_failed", { flagKey, - targetingKey: context.targetingKey, error: loggableError(error), }); - } finally { - inFlight.delete(identity); } })(); - inFlight.set(identity, pending); - return pending; } async function resolveFromProvider( - identity: string, + identity: string | undefined, flagKey: string, definition: FlagDefinition, context: EvaluationContext, ): Promise> { try { - const resolution = await withTimeout( - options.provider.resolve({ - flagKey, - defaultValue: definition.defaultValue, - kind: definition.kind, - context, - }), - timeoutMs, - ); + const work = providerWork(identity, flagKey, definition, context); + const resolution = await waitForProvider(work, timeoutMs); const value = decodeFlagValue(definition, resolution.value, flagKey); writeCache(identity, flagKey, value, resolution, nowMs(clock)); if (resolution.reason !== "TARGETING_MATCH") { - logFallback(logger, resolution.reason, flagKey, context); + logFallback(logger, resolution.reason, flagKey); } return toDetail(flagKey, value, resolution.reason, { ...(resolution.variant === undefined @@ -324,15 +515,19 @@ export function createFlagsClient< } catch (error) { const stale = readCache(identity, nowMs(clock)); if (stale !== undefined) { - logFallback(logger, "STALE_CACHE", flagKey, context, error); + logFallback(logger, "STALE_CACHE", flagKey, error); return toDetail(flagKey, stale.value as T, "STALE_CACHE", { ...(stale.variant === undefined ? {} : { variant: stale.variant }), }); } - logFallback(logger, "ERROR", flagKey, context, error); + logFallback(logger, "ERROR", flagKey, error); return toDetail(flagKey, definition.defaultValue, "ERROR", { errorCode: - error instanceof EvaluationTimeoutError ? "TIMEOUT" : "PROVIDER", + error instanceof EvaluationTimeoutError + ? "TIMEOUT" + : error instanceof ProviderCapacityError + ? "CAPACITY" + : "PROVIDER", errorMessage: loggableError(error), }); } @@ -344,7 +539,11 @@ export function createFlagsClient< context: EvaluationContext, ): Promise>> { requireTargetingKey(context); + if (!Object.hasOwn(options.schema, flagKey)) { + throw new Error(`unknown flag ${flagKey}`); + } const definition = options.schema[flagKey]; + // JavaScript callers can still supply an own undefined definition. if (definition === undefined) { throw new Error(`unknown flag ${flagKey}`); } @@ -355,7 +554,7 @@ export function createFlagsClient< const age = atMs - cached.storedAtMs; if (age < cacheTtlMs) { if (cached.reason !== "TARGETING_MATCH") { - logFallback(logger, cached.reason, flagKey, context); + logFallback(logger, cached.reason, flagKey); } return toDetail( flagKey, @@ -368,11 +567,10 @@ export function createFlagsClient< }, ); } - void refresh(identity, flagKey, definition, context); - logger.log("info", "flags.stale_cache", { - flagKey, - targetingKey: context.targetingKey, - }); + if (identity !== undefined) { + refresh(identity, flagKey, definition, context); + } + logger.log("info", "flags.stale_cache", { flagKey }); return toDetail( flagKey, cached.value as FlagValueOf, @@ -410,6 +608,9 @@ export function createFlagsClient< }, async close() { + for (const work of activeWorks) { + work.controller.abort(); + } await options.provider.close?.(); }, }; diff --git a/packages/flags-core/src/health.test.ts b/packages/flags-core/src/health.test.ts index e8de52a..cf42d9b 100644 --- a/packages/flags-core/src/health.test.ts +++ b/packages/flags-core/src/health.test.ts @@ -27,12 +27,14 @@ describe("createFlagsHealthCheck", () => { }); it("reports fail on timeout without leaking error text", async () => { + let signal: AbortSignal | undefined; const hanging: FlagProvider = { name: "hanging", capabilities() { return { static: true, streaming: false, targeting: false }; }, - resolve() { + resolve(request) { + signal = request.signal; return new Promise(() => { // never settles }); @@ -47,6 +49,7 @@ describe("createFlagsHealthCheck", () => { provider: "hanging", reason: "probe_timeout", }); + expect(signal?.aborted).toBe(true); expect(JSON.stringify(result)).not.toContain("timed out"); }); }); diff --git a/packages/flags-core/src/health.ts b/packages/flags-core/src/health.ts index e3c0e3b..35d3646 100644 --- a/packages/flags-core/src/health.ts +++ b/packages/flags-core/src/health.ts @@ -22,9 +22,14 @@ export interface FlagsHealthCheckOptions { readonly timeoutMs?: number; } -function withTimeout(promise: Promise, timeoutMs: number): Promise { +function withTimeout( + promise: Promise, + timeoutMs: number, + controller: AbortController, +): Promise { return new Promise((resolve, reject) => { const timer = setTimeout(() => { + controller.abort(); reject(new ProbeTimeoutError(`timed out after ${timeoutMs}ms`)); }, timeoutMs); promise.then( @@ -54,6 +59,7 @@ export function createFlagsHealthCheck( name, async run() { const started = Date.now(); + const controller = new AbortController(); try { const resolution = await withTimeout( options.provider.resolve({ @@ -61,8 +67,10 @@ export function createFlagsHealthCheck( defaultValue: false, kind: "boolean", context: { targetingKey: "health" }, + signal: controller.signal, }), timeoutMs, + controller, ); return { status: "ok", diff --git a/scripts/release-packages.d.mts b/scripts/release-packages.d.mts index 4cf0cac..be63232 100644 --- a/scripts/release-packages.d.mts +++ b/scripts/release-packages.d.mts @@ -108,10 +108,29 @@ export function decidePublication( registryIntegrity: string | null, ): "publish" | "skip"; +export function validatePackedManifest( + sourceManifest: PublicPackageManifest, + packedManifest: PublicPackageManifest, + files: readonly { readonly path: string; readonly size?: number }[], +): void; + +export function verifyReleaseInventory( + directory: string, + manifest: { + readonly packages: readonly { readonly tarball: string }[]; + }, +): Promise; + export function prepareRelease( options?: ReleaseCommandOptions, ): Promise<{ manifestPath: string; manifest: unknown }>; +export function verifyPreparedManifest(manifestPath: string): Promise; + +export function smokePreparedRelease( + options?: ReleaseCommandOptions, +): Promise; + export function publishPreparedRelease( options?: ReleaseCommandOptions, ): Promise; diff --git a/scripts/release-packages.mjs b/scripts/release-packages.mjs index 6255757..d0b1d94 100644 --- a/scripts/release-packages.mjs +++ b/scripts/release-packages.mjs @@ -3,6 +3,7 @@ import { createHash, timingSafeEqual } from "node:crypto"; import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { mkdtemp, + lstat, mkdir, readFile, readdir, @@ -231,6 +232,7 @@ function gitCommand() { function hashTarball(bytes) { return { + sha256: createHash("sha256").update(bytes).digest("hex"), shasum: createHash("sha1").update(bytes).digest("hex"), integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, }; @@ -769,6 +771,103 @@ function verifyPackedFiles(manifest, files) { } } +const PACKAGE_DEPENDENCY_SECTIONS = [ + "dependencies", + "optionalDependencies", + "peerDependencies", +]; +const INSTALL_LIFECYCLE_SCRIPTS = [ + "preinstall", + "install", + "postinstall", + "prepublish", + "preprepare", + "prepare", + "postprepare", +]; + +export function validatePackedManifest(sourceManifest, packedManifest, files) { + if ( + packedManifest?.name !== sourceManifest.name || + packedManifest?.version !== sourceManifest.version + ) { + fail(`${sourceManifest.name} tarball manifest identity has changed`); + } + for (const script of INSTALL_LIFECYCLE_SCRIPTS) { + if (Object.hasOwn(packedManifest.scripts ?? {}, script)) { + fail(`${sourceManifest.name} tarball must not define ${script}`); + } + } + for (const section of PACKAGE_DEPENDENCY_SECTIONS) { + const sourceDependencies = sourceManifest[section] ?? {}; + const packedDependencies = packedManifest[section] ?? {}; + const names = new Set( + [ + ...Object.keys(sourceDependencies), + ...Object.keys(packedDependencies), + ].filter((name) => name.startsWith("@pegma/")), + ); + for (const name of names) { + const sourceVersion = sourceDependencies[name]; + const packedVersion = packedDependencies[name]; + if ( + packedVersion !== sourceVersion || + typeof packedVersion !== "string" || + !EXACT_VERSION.test(packedVersion) + ) { + fail( + `${sourceManifest.name} must preserve the exact ${name} pin in its tarball`, + ); + } + } + } + verifyPackedFiles(packedManifest, files); +} + +function extractPackedManifest(tarballPath) { + const result = run("tar", ["-xOf", tarballPath, "package/package.json"], { + capture: true, + }); + try { + return parseNpmJson(result.stdout); + } catch { + fail(`${basename(tarballPath)} contains an invalid package manifest`); + } +} + +export async function verifyReleaseInventory(directory, manifest) { + const expected = new Set([ + "package-manifest.json", + ...manifest.packages.map(({ tarball }) => tarball), + ]); + if (expected.size !== manifest.packages.length + 1) { + fail("release inventory contains duplicate filenames"); + } + const entries = await readdir(directory, { withFileTypes: true }); + for (const expectedName of expected) { + if (!entries.some(({ name }) => name === expectedName)) { + fail(`release directory is missing ${expectedName}`); + } + } + if (entries.length !== expected.size) { + fail("release directory inventory does not match the package manifest"); + } + for (const entry of entries) { + if ( + entry.name.startsWith(".") || + !expected.has(entry.name) || + !entry.isFile() || + entry.isSymbolicLink() + ) { + fail(`release directory contains an unexpected entry: ${entry.name}`); + } + const metadata = await lstat(join(directory, entry.name)); + if (!metadata.isFile() || metadata.isSymbolicLink()) { + fail(`release entry must be a regular file: ${entry.name}`); + } + } +} + async function smokeTestTarballs(packageRecords, registry) { const directory = await mkdtemp(join(tmpdir(), "flags-core-release-smoke-")); try { @@ -889,12 +988,15 @@ export async function prepareRelease(options = {}) { ) { fail(`${definition.name} tarball hashes do not match npm pack metadata`); } + const packedManifest = extractPackedManifest(tarballPath); + validatePackedManifest(manifest, packedManifest, packed.files); records.push({ name: definition.name, version: manifest.version, directory: definition.directory, tarball: basename(tarballPath), tarballPath, + sha256: hashes.sha256, integrity: hashes.integrity, shasum: hashes.shasum, publish: tagVersion === undefined || manifest.version === tagVersion, @@ -904,8 +1006,6 @@ export async function prepareRelease(options = {}) { manifest, }); } - await smokeTestTarballs(records, options.registry); - if (releaseTag !== undefined) { for (const record of records.filter(({ publish }) => !publish)) { const registryIntegrity = queryRegistryIntegrity( @@ -934,10 +1034,11 @@ export async function prepareRelease(options = {}) { }; const manifestPath = join(output, "package-manifest.json"); await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + await verifyReleaseInventory(output, manifest); return { manifestPath, manifest }; } -async function verifyPreparedManifest(manifestPath) { +export async function verifyPreparedManifest(manifestPath) { const manifest = await readJson(manifestPath); if ( manifest.schemaVersion !== 1 || @@ -962,6 +1063,7 @@ async function verifyPreparedManifest(manifestPath) { if (!manifest.packages.some(({ publish }) => publish)) { fail("prepared package manifest has no release candidates"); } + await verifyReleaseInventory(dirname(manifestPath), manifest); for (const [index, record] of manifest.packages.entries()) { const definition = RELEASE_PACKAGES[index]; const expectedTarball = `${definition.name @@ -972,6 +1074,7 @@ async function verifyPreparedManifest(manifestPath) { record.tarball !== expectedTarball || !STABLE_SEMVER.test(record.version) || record.publish !== (record.version === tagVersion) || + !/^[0-9a-f]{64}$/u.test(record.sha256) || typeof record.integrity !== "string" || typeof record.shasum !== "string" || !Array.isArray(record.files) @@ -984,6 +1087,7 @@ async function verifyPreparedManifest(manifestPath) { } const hashes = hashTarball(await readFile(tarball)); if ( + !safeEqual(hashes.sha256, record.sha256) || !safeEqual(hashes.integrity, record.integrity) || !safeEqual(hashes.shasum, record.shasum) ) { @@ -993,6 +1097,21 @@ async function verifyPreparedManifest(manifestPath) { return manifest; } +export async function smokePreparedRelease(options = {}) { + const manifestPath = resolve( + options.manifest ?? ".release/package-manifest.json", + ); + const manifest = await verifyPreparedManifest(manifestPath); + const packageRecords = manifest.packages.map((record) => { + const tarballPath = resolve(dirname(manifestPath), record.tarball); + return { + tarballPath, + manifest: extractPackedManifest(tarballPath), + }; + }); + await smokeTestTarballs(packageRecords, options.registry); +} + function requireTrustedPublishingNpm() { const version = runNpm(["--version"], { capture: true }).stdout.trim(); const match = /^(\d+)\.(\d+)\.(\d+)(?:-.+)?$/u.exec(version); @@ -1134,7 +1253,11 @@ async function main() { await publishPreparedRelease(options); return; } - fail("usage: release-packages.mjs [options]"); + if (command === "smoke") { + await smokePreparedRelease(options); + return; + } + fail("usage: release-packages.mjs [options]"); } const isMain = diff --git a/tests/release-packages.test.ts b/tests/release-packages.test.ts index 6e48669..670ab8b 100644 --- a/tests/release-packages.test.ts +++ b/tests/release-packages.test.ts @@ -1,5 +1,12 @@ import { execFileSync } from "node:child_process"; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -12,8 +19,12 @@ import { parseNpmJson, parsePnpmImporterDependencies, resolvedVersionSatisfies, + smokePreparedRelease, + validatePackedManifest, validateReleaseTag, validateRepository, + verifyPreparedManifest, + verifyReleaseInventory, } from "../scripts/release-packages.mjs"; const git = process.platform === "win32" ? "git.exe" : "git"; @@ -34,6 +45,77 @@ function run(command: string, arguments_: string[], cwd?: string): string { }).trim(); } +function createPreparedRelease(directory: string): { + manifestPath: string; + manifest: { + schemaVersion: number; + gitCommit: string; + releaseTag: string; + packages: Array<{ + name: string; + version: string; + directory: string; + tarball: string; + sha256: string; + shasum: string; + integrity: string; + publish: boolean; + files: Array<{ path: string; size: number }>; + }>; + }; +} { + const stagingRoot = join(directory, "staging"); + mkdirSync(stagingRoot); + const records = RELEASE_PACKAGES.map((definition) => { + const packageStaging = join(stagingRoot, definition.directory); + const packageRoot = join(packageStaging, "package"); + mkdirSync(join(packageRoot, "dist"), { recursive: true }); + writeFileSync( + join(packageRoot, "package.json"), + `${JSON.stringify({ + name: definition.name, + version: packageVersion, + type: "module", + exports: { ".": "./dist/index.js" }, + })}\n`, + ); + writeFileSync( + join(packageRoot, "dist", "index.js"), + "export const ready = true;\n", + ); + const tarball = `${definition.name + .slice(1) + .replace("/", "-")}-${packageVersion}.tgz`; + const tarballPath = join(directory, tarball); + run("tar", ["-czf", tarballPath, "-C", packageStaging, "package"]); + const bytes = readFileSync(tarballPath); + return { + name: definition.name, + version: packageVersion, + directory: definition.directory, + tarball, + sha256: createHash("sha256").update(bytes).digest("hex"), + shasum: createHash("sha1").update(bytes).digest("hex"), + integrity: `sha512-${createHash("sha512").update(bytes).digest("base64")}`, + publish: true, + files: [ + { path: "package.json", size: 1 }, + { path: "dist/index.js", size: 1 }, + ], + }; + }); + rmSync(stagingRoot, { recursive: true, force: true }); + const manifest = { + schemaVersion: 1, + gitCommit: run(git, ["rev-parse", "HEAD"], process.cwd()), + releaseTag: `v${packageVersion}`, + packages: records, + }; + const manifestPath = join(directory, "package-manifest.json"); + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + return { manifestPath, manifest }; +} + describe("release package metadata", () => { it("accepts npm's cross-platform argument separator", () => { expect(parseArguments(["--", "--output", ".release"])).toEqual({ @@ -41,6 +123,15 @@ describe("release package metadata", () => { }); }); + it("exposes the release smoke command", () => { + const rootManifest = JSON.parse( + readFileSync(join(process.cwd(), "package.json"), "utf8"), + ) as { scripts?: Record }; + expect(rootManifest.scripts?.["release:smoke"]).toBe( + "node scripts/release-packages.mjs smoke", + ); + }); + it("keeps the exact public package inventory", () => { expect(RELEASE_PACKAGES.map(({ name }) => name)).toEqual([ "@pegma/flags-contracts", @@ -199,6 +290,113 @@ describe("release package metadata", () => { }), ).rejects.toThrow("prereleases cannot publish packages"); }); + + it("revalidates the manifest stored in a tarball", () => { + const source = { + name: "@pegma/example", + version: "0.1.1", + exports: { ".": "./dist/index.js" }, + dependencies: { "@pegma/spine": "0.1.2" }, + }; + const files = [ + { path: "package.json" }, + { path: "README.md" }, + { path: "LICENSE" }, + { path: "dist/index.js" }, + ]; + const packed = { + ...source, + scripts: { prepack: "pnpm build" }, + dependencies: { "@pegma/spine": "0.1.2" }, + }; + expect(() => validatePackedManifest(source, packed, files)).not.toThrow(); + expect(() => + validatePackedManifest( + source, + { ...packed, scripts: { install: "node setup.mjs" } }, + files, + ), + ).toThrow("must not define install"); + expect(() => + validatePackedManifest( + source, + { ...packed, dependencies: { "@pegma/spine": "^0.1.2" } }, + files, + ), + ).toThrow("preserve the exact @pegma/spine pin"); + expect(() => + validatePackedManifest( + source, + { ...packed, dependencies: { "@pegma/spine": "0.1.1" } }, + files, + ), + ).toThrow("preserve the exact @pegma/spine pin"); + expect(() => + validatePackedManifest( + source, + packed, + files.filter(({ path }) => path !== "README.md"), + ), + ).toThrow("missing README.md"); + }); + + it("accepts only the sealed release directory inventory", async () => { + const directory = mkdtempSync(join(tmpdir(), "flags-core-inventory-")); + const manifest = { packages: [{ tarball: "pegma-example-0.1.1.tgz" }] }; + try { + writeFileSync(join(directory, "package-manifest.json"), "{}\n"); + writeFileSync(join(directory, "pegma-example-0.1.1.tgz"), "tarball"); + await expect( + verifyReleaseInventory(directory, manifest), + ).resolves.toBeUndefined(); + + rmSync(join(directory, "pegma-example-0.1.1.tgz")); + await expect(verifyReleaseInventory(directory, manifest)).rejects.toThrow( + "missing pegma-example-0.1.1.tgz", + ); + writeFileSync(join(directory, "pegma-example-0.1.1.tgz"), "tarball"); + + writeFileSync(join(directory, ".npmrc"), "registry=example\n"); + await expect(verifyReleaseInventory(directory, manifest)).rejects.toThrow( + "inventory", + ); + rmSync(join(directory, ".npmrc")); + + mkdirSync(join(directory, "extra")); + await expect(verifyReleaseInventory(directory, manifest)).rejects.toThrow( + "inventory", + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + it("verifies prepared SHA-256 records", async () => { + const directory = mkdtempSync(join(tmpdir(), "flags-core-prepared-")); + try { + const { manifestPath, manifest } = createPreparedRelease(directory); + await expect(verifyPreparedManifest(manifestPath)).resolves.toBeDefined(); + manifest.packages[0]!.sha256 = "0".repeat(64); + writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); + await expect(verifyPreparedManifest(manifestPath)).rejects.toThrow( + "prepared tarball has changed", + ); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + it("installs and imports a prepared release", async () => { + const directory = mkdtempSync(join(tmpdir(), "flags-core-smoke-")); + try { + const { manifestPath } = createPreparedRelease(directory); + await expect( + smokePreparedRelease({ manifest: manifestPath }), + ).resolves.toBeUndefined(); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); }); describe("release source authentication", () => { @@ -290,25 +488,75 @@ describe("release source authentication", () => { const header = workflow.slice(0, jobsIndex); const jobs = workflow.slice(jobsIndex + jobsMarker.length); const prepareStart = jobs.indexOf(" prepare:"); + const smokeStart = jobs.indexOf("\n smoke:"); const publishStart = jobs.indexOf("\n publish:"); expect(header).not.toContain("id-token: write"); expect(prepareStart).toBeGreaterThanOrEqual(0); + expect(smokeStart).toBeGreaterThan(prepareStart); expect(publishStart).toBeGreaterThan(prepareStart); - const prepare = jobs.slice(prepareStart, publishStart); + const prepare = jobs.slice(prepareStart, smokeStart); + const smoke = jobs.slice(smokeStart, publishStart); const publish = jobs.slice(publishStart); expect(prepare).not.toContain("id-token: write"); - expect(prepare).toContain("npm install --global npm@11.18.0"); + expect(prepare).toContain( + "npm install --global npm@11.18.0 --ignore-scripts", + ); expect(prepare).toContain("node scripts/release-packages.mjs pack"); + expect(prepare.indexOf("Authenticate the release source")).toBeLessThan( + prepare.indexOf("actions/checkout"), + ); + expect(prepare).toContain("ref: ${{ github.sha }}"); + expect(prepare).toContain("persist-credentials: false"); + expect(prepare).toContain("include-hidden-files: false"); + expect(prepare).toContain("manifest_digest:"); + expect(smoke).toContain("permissions:\n contents: read"); + expect(smoke).not.toContain("id-token: write"); + expect(smoke).toContain("node scripts/release-packages.mjs smoke"); expect(publish).toContain("id-token: write"); expect(publish).not.toContain("npm ci"); - expect(publish).not.toContain("npm install"); expect(publish).not.toContain("pnpm install"); expect(publish).not.toContain("corepack"); expect(publish).not.toContain("pnpm run"); expect(publish).not.toContain("pnpm/action-setup"); - expect(publish).toContain("node scripts/release-packages.mjs publish"); + expect(publish).not.toContain("actions/checkout"); + expect(publish).not.toContain("scripts/release-packages.mjs"); + expect(publish).toContain("npm install --global npm@11.18.0"); + expect(publish).toContain("node <<'NODE'"); + expect(publish).toContain("EXPECTED_MANIFEST_DIGEST"); + expect(publish).toContain("ACTIONS_ID_TOKEN_"); + expect(publish).toContain('key !== "GITHUB_TOKEN"'); + expect(publish).toContain('npmVersion !== "11.18.0"'); + expect(publish).toContain('"--provenance"'); + expect(publish).toContain('"--ignore-scripts"'); + expect(publish).toContain("needs: [prepare, smoke]"); expect(workflow).not.toContain("workflow_dispatch"); expect(workflow).toContain("retention-days: 30"); + + const jobEnvironmentBlocks = [ + ...workflow.matchAll(/^ env:\r?\n((?: {6}.*(?:\r?\n|$))*)/gmu), + ]; + for (const block of jobEnvironmentBlocks) { + expect(block[1]).not.toContain("${{ runner."); + expect(block[1]).not.toContain("${{ steps."); + } + + const inlineStart = workflow.indexOf(" node <<'NODE'\n"); + const inlineEnd = workflow.indexOf("\n NODE", inlineStart); + expect(inlineStart).toBeGreaterThanOrEqual(0); + expect(inlineEnd).toBeGreaterThan(inlineStart); + const inlineScript = workflow + .slice(inlineStart + " node <<'NODE'\n".length, inlineEnd) + .replace(/^ {10}/gmu, ""); + const directory = mkdtempSync(join(tmpdir(), "flags-core-inline-")); + try { + const scriptPath = join(directory, "publish.cjs"); + writeFileSync(scriptPath, inlineScript); + expect(() => + run(process.execPath, ["--check", scriptPath]), + ).not.toThrow(); + } finally { + rmSync(directory, { recursive: true, force: true }); + } }); });