The Open Framework for Building Agents
fix(eve): publish PR package artifacts automatically (#3358)
Andrew Barba266fe05e41f5
diff --git a/.github/workflows/package-artifact-build.yml b/.github/workflows/build-tarball.ymlsimilarity index 79%rename from .github/workflows/package-artifact-build.ymlrename to .github/workflows/build-tarball.ymlindex 818e0d3c9..60eb464b5 100644--- a/.github/workflows/package-artifact-build.yml+++ b/.github/workflows/build-tarball.yml@@ -1,4 +1,4 @@-name: Package artifact build+name: Build tarballon:push:@@ -11,6 +11,9 @@ permissions:jobs:build:+ if: >-+ github.event_name == 'push' ||+ github.event.pull_request.head.repo.full_name == github.repositoryruns-on: ubuntu-lateststeps:- name: Select source@@ -23,13 +26,17 @@ jobs:PR_SHA: ${{ github.event.pull_request.head.sha }}run: |if [ "$EVENT_NAME" = "push" ]; then- echo "repository=${{ github.repository }}" >> "$GITHUB_OUTPUT"- echo "sha=$MAIN_SHA" >> "$GITHUB_OUTPUT"- echo "ref=main" >> "$GITHUB_OUTPUT"+ {+ echo "repository=${{ github.repository }}"+ echo "sha=$MAIN_SHA"+ echo "ref=main"+ } >> "$GITHUB_OUTPUT"else- echo "repository=$PR_REPOSITORY" >> "$GITHUB_OUTPUT"- echo "sha=$PR_SHA" >> "$GITHUB_OUTPUT"- echo "ref=$PR_NUMBER" >> "$GITHUB_OUTPUT"+ {+ echo "repository=$PR_REPOSITORY"+ echo "sha=$PR_SHA"+ echo "ref=$PR_NUMBER"+ } >> "$GITHUB_OUTPUT"fi- name: Checkout sourcediff --git a/.github/workflows/package-artifact-publish.yml b/.github/workflows/package-artifact-publish.ymldeleted file mode 100644index 11bf180f1..000000000--- a/.github/workflows/package-artifact-publish.yml+++ /dev/null@@ -1,128 +0,0 @@-name: Package artifact publish--on:- workflow_run:- workflows: [Package artifact build]- types: [completed]- workflow_dispatch:- inputs:- pull_request:- description: Pull request number to publish- required: true- type: string--permissions:- actions: read- contents: read- pull-requests: read--jobs:- publish:- if: >-- github.event_name == 'workflow_dispatch' ||- (github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')- runs-on: ubuntu-latest- concurrency:- group: package-artifact-publish-${{ github.event_name == 'workflow_dispatch' && format('pr-{0}', inputs.pull_request) || 'main' }}- cancel-in-progress: false- steps:- - name: Resolve publication target- id: target- uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0- env:- PULL_REQUEST: ${{ inputs.pull_request }}- with:- script: |- if (context.eventName === "workflow_run") {- const run = context.payload.workflow_run;- if (run.head_branch !== "main") throw new Error("Only main pushes publish automatically.");- const { data: branch } = await github.rest.repos.getBranch({- owner: context.repo.owner,- repo: context.repo.repo,- branch: "main",- });- if (branch.commit.sha !== run.head_sha) {- throw new Error(`Refusing to publish stale main build ${run.head_sha}; main is ${branch.commit.sha}.`);- }- core.setOutput("run-id", String(run.id));- core.setOutput("sha", run.head_sha);- core.setOutput("ref", "main");- return;- }-- if (!/^[1-9]\d*$/.test(process.env.PULL_REQUEST ?? "")) {- throw new Error("pull_request must be a positive integer.");- }- const pullNumber = Number(process.env.PULL_REQUEST);- const { data: pull } = await github.rest.pulls.get({- owner: context.repo.owner,- repo: context.repo.repo,- pull_number: pullNumber,- });- if (pull.state !== "open") throw new Error(`Pull request #${pullNumber} is not open.`);-- const { data: workflow } = await github.rest.actions.getWorkflow({- owner: context.repo.owner,- repo: context.repo.repo,- workflow_id: "package-artifact-build.yml",- });- const runs = await github.paginate(github.rest.actions.listWorkflowRunsForRepo, {- owner: context.repo.owner,- repo: context.repo.repo,- event: "pull_request",- head_sha: pull.head.sha,- status: "success",- per_page: 100,- });- const run = runs.find(- (candidate) =>- candidate.workflow_id === workflow.id &&- candidate.head_sha === pull.head.sha &&- candidate.head_branch === pull.head.ref &&- candidate.head_repository?.full_name === pull.head.repo.full_name,- );- if (!run) {- throw new Error(`No successful package build found for PR #${pullNumber} at ${pull.head.sha}.`);- }-- core.setOutput("run-id", String(run.id));- core.setOutput("sha", pull.head.sha);- core.setOutput("ref", String(pullNumber));-- - name: Download package artifact- uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0- with:- name: eve-package- path: package-artifact- github-token: ${{ github.token }}- run-id: ${{ steps.target.outputs.run-id }}-- - name: Checkout publisher- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1- with:- ref: ${{ github.event_name == 'workflow_dispatch' && github.sha || 'main' }}- path: trusted- persist-credentials: false-- - name: Setup pnpm- uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10-- - name: Setup Node.js- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0- with:- node-version-file: trusted/.nvmrc- cache: pnpm- cache-dependency-path: trusted/pnpm-lock.yaml-- - name: Install publisher dependencies- working-directory: trusted- run: pnpm install --frozen-lockfile --ignore-scripts-- - name: Publish package artifact- working-directory: trusted- env:- EVE_PACKAGE_BLOB_READ_WRITE_TOKEN: ${{ secrets.EVE_PACKAGE_BLOB_READ_WRITE_TOKEN }}- EVE_PACKAGE_INPUT_DIRECTORY: ${{ github.workspace }}/package-artifact- EVE_PACKAGE_REF: ${{ steps.target.outputs.ref }}- EVE_PACKAGE_SOURCE_SHA: ${{ steps.target.outputs.sha }}- run: pnpm --filter eve-package-artifacts package:publishdiff --git a/.github/workflows/publish-tarball.yml b/.github/workflows/publish-tarball.ymlnew file mode 100644index 000000000..c609ae6f1--- /dev/null+++ b/.github/workflows/publish-tarball.yml@@ -0,0 +1,133 @@+name: Publish tarball++on:+ workflow_run:+ workflows: [Build tarball]+ types: [completed]++permissions:+ actions: read+ contents: read+ pull-requests: read+ statuses: write++jobs:+ report-build-failure:+ if: >-+ github.event.workflow_run.head_repository.full_name == github.repository &&+ github.event.workflow_run.conclusion != 'success' &&+ (github.event.workflow_run.event == 'push' || github.event.workflow_run.event == 'pull_request')+ runs-on: ubuntu-latest+ steps:+ - name: Report publication failure+ uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0+ with:+ script: |+ const run = context.payload.workflow_run;+ await github.rest.repos.createCommitStatus({+ ...context.repo,+ sha: run.head_sha,+ state: "failure",+ context: "Package artifact",+ description: "Package tarball build failed",+ target_url: run.html_url,+ });++ publish:+ if: >-+ github.event.workflow_run.head_repository.full_name == github.repository &&+ github.event.workflow_run.conclusion == 'success' &&+ (github.event.workflow_run.event == 'push' || github.event.workflow_run.event == 'pull_request')+ runs-on: ubuntu-latest+ concurrency:+ group: package-artifact-publish-${{ github.event.workflow_run.head_repository.id }}-${{ github.event.workflow_run.head_branch }}+ cancel-in-progress: false+ steps:+ - name: Report publication started+ uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0+ with:+ script: |+ const run = context.payload.workflow_run;+ await github.rest.repos.createCommitStatus({+ ...context.repo,+ sha: run.head_sha,+ state: "pending",+ context: "Package artifact",+ description: "Publishing package tarball",+ target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,+ });++ # workflow_run loads this workflow from the default branch. Keep every+ # credentialed operation in that trusted checkout, never the PR checkout.+ - name: Checkout trusted publisher+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: main+ path: trusted+ persist-credentials: false++ - name: Download package artifact+ uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0+ with:+ name: eve-package+ path: package-artifact+ github-token: ${{ github.token }}+ run-id: ${{ github.event.workflow_run.id }}++ - name: Setup pnpm+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10++ - name: Setup Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version-file: trusted/.nvmrc+ cache: pnpm+ cache-dependency-path: trusted/pnpm-lock.yaml++ - name: Install publisher dependencies+ working-directory: trusted+ run: pnpm install --frozen-lockfile --ignore-scripts++ # Resolve after setup and download so stale builds are rejected as close as+ # possible to the mutable pointer update.+ - name: Resolve publication target+ id: target+ uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0+ with:+ script: |+ const { resolvePublicationTarget } = await import(+ `${process.env.GITHUB_WORKSPACE}/trusted/apps/package-artifacts/lib/publication-target.mjs`+ );+ const target = await resolvePublicationTarget(github, context);+ core.setOutput("sha", target.sha);+ core.setOutput("ref", target.ref);++ - name: Publish package artifact+ id: publish+ working-directory: trusted+ env:+ EVE_PACKAGE_BLOB_READ_WRITE_TOKEN: ${{ secrets.EVE_PACKAGE_BLOB_READ_WRITE_TOKEN }}+ EVE_PACKAGE_INPUT_DIRECTORY: ${{ github.workspace }}/package-artifact+ EVE_PACKAGE_REF: ${{ steps.target.outputs.ref }}+ EVE_PACKAGE_SOURCE_SHA: ${{ steps.target.outputs.sha }}+ GITHUB_REPOSITORY: ${{ github.repository }}+ GITHUB_TOKEN: ${{ github.token }}+ run: pnpm --filter eve-package-artifacts package:publish++ - name: Report publication result+ if: always()+ uses: actions/github-script@d746ffe35508b1917358783b479e04febd2b8f71 # v9.0.0+ env:+ PUBLISH_OUTCOME: ${{ steps.publish.outcome }}+ with:+ script: |+ const run = context.payload.workflow_run;+ const success = process.env.PUBLISH_OUTCOME === "success";+ await github.rest.repos.createCommitStatus({+ ...context.repo,+ sha: run.head_sha,+ state: success ? "success" : "failure",+ context: "Package artifact",+ description: success ? "Package tarball is ready" : "Package tarball publication failed",+ target_url: `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,+ });diff --git a/apps/package-artifacts/README.md b/apps/package-artifacts/README.mdindex 9ccdd4c13..ad43fbe61 100644--- a/apps/package-artifacts/README.md+++ b/apps/package-artifacts/README.md@@ -16,13 +16,19 @@ Initialize an agent from the current `main` build with:npm exec --yes --package=https://pkg.eve.dev/main/eve.tgz -- eve init my-agent```-A pull-request build is available at `/pr/<number>/eve.tgz` after its package workflow succeeds. Both moving routes redirect to an immutable `/<sha>/eve.tgz` artifact, and the packaged CLI stamps that immutable URL into generated projects.+A same-repository pull-request build is available at `/pr/<number>/eve.tgz` after its **Package artifact** commit status succeeds. Fork pull requests never build or publish package artifacts. The status is reported only after publication finishes, and no manual publishing step is required. Both moving routes redirect to an immutable `/<sha>/eve.tgz` artifact, and the packaged CLI stamps that immutable URL into generated projects.++For example, after the package check passes on PR #123:++```bash+npm exec --yes --package=https://pkg.eve.dev/pr/123/eve.tgz -- eve init my-agent+```## Publishing-[Package artifact build](../../.github/workflows/package-artifact-build.yml) runs for `main` pushes and pull requests without credentials. It checks out the exact source SHA, packages eve, and uploads the tarball and metadata as a short-lived GitHub Actions artifact.+[Build tarball](../../.github/workflows/build-tarball.yml) runs for `main` pushes and same-repository pull requests without credentials. It checks out the exact source SHA, packages eve, and uploads the tarball and metadata as a short-lived GitHub Actions artifact.-[Package artifact publish](../../.github/workflows/package-artifact-publish.yml) publishes `main` automatically through `workflow_run`. Pull requests require a manual `workflow_dispatch` with the PR number. The default branch selection runs the publisher from trusted `main`; intentionally selecting another branch runs that branch's publisher with the Blob credential for testing. The publisher resolves the PR's current head through the API, finds that SHA's successful package build, downloads its artifact, and uploads the bytes without executing or extracting them.+[Publish tarball](../../.github/workflows/publish-tarball.yml) is an automatic internal trust boundary. GitHub loads it from the default branch on successful package builds. It verifies that the build still represents the current `main` or pull-request head, downloads the artifact on a fresh runner, and uploads the bytes without executing or extracting them. It then reports the user-facing **Package artifact** commit status. Keeping publishing separate prevents pull-request code from changing the credentialed workflow or reading the Blob token.The publisher writes:@@ -45,6 +51,6 @@ The Vercel package project must:- set its Ignored Build Step to `test "$VERCEL_GIT_COMMIT_REF" != "main"`; and- disable Deployment Protection so package managers can reach the public proxy.-Set the repository Actions secret `EVE_PACKAGE_BLOB_READ_WRITE_TOKEN` to the package store's write token. The build workflow never references this secret. Pull-request builds inherit the repository's existing contributor approval policy, and publishing a PR requires a separate manual run of **Package artifact publish**. Leave **Use workflow from** set to `main` for the normal trusted publisher; selecting another branch explicitly grants that branch's publisher access to the Blob credential.+Set the repository Actions secret `EVE_PACKAGE_BLOB_READ_WRITE_TOKEN` to the package store's write token. The user-facing workflow never references this secret. Successful same-repository pull-request builds publish automatically through the trusted default-branch publisher.The smoke check verifies public access and the downloaded main artifact's gzip signature.diff --git a/apps/package-artifacts/lib/publication-current.mjs b/apps/package-artifacts/lib/publication-current.mjsnew file mode 100644index 000000000..d21d42509--- /dev/null+++ b/apps/package-artifacts/lib/publication-current.mjs@@ -0,0 +1,50 @@+import { PULL_REQUEST_PATTERN, SHA_PATTERN } from "./package.mjs";++export async function assertCurrentPublicationTarget(+ { repository, ref, sourceSha, token },+ fetchImplementation = fetch,+) {+ if (!/^[^/]+\/[^/]+$/.test(repository ?? "")) {+ throw new Error("GITHUB_REPOSITORY must identify an owner and repository.");+ }+ if (!SHA_PATTERN.test(sourceSha ?? "")) {+ throw new Error("Publication source SHA must be a 40-character Git commit SHA.");+ }+ if (typeof token !== "string" || token.length === 0) {+ throw new Error("GITHUB_TOKEN is required to revalidate package publication.");+ }++ if (ref === "main") {+ const branch = await githubRequest(+ `/repos/${repository}/branches/main`,+ token,+ fetchImplementation,+ );+ if (branch.commit?.sha !== sourceSha) {+ throw new Error(`Refusing to update main package pointer from stale build ${sourceSha}.`);+ }+ return;+ }+ if (!PULL_REQUEST_PATTERN.test(ref ?? "")) {+ throw new Error("Package ref must be main or a positive pull request number.");+ }++ const pull = await githubRequest(`/repos/${repository}/pulls/${ref}`, token, fetchImplementation);+ if (pull.state !== "open" || pull.base?.ref !== "main" || pull.head?.sha !== sourceSha) {+ throw new Error(`Refusing to update PR #${ref} package pointer from stale build ${sourceSha}.`);+ }+}++async function githubRequest(pathname, token, fetchImplementation) {+ const response = await fetchImplementation(`https://api.github.com${pathname}`, {+ headers: {+ Accept: "application/vnd.github+json",+ Authorization: `Bearer ${token}`,+ "X-GitHub-Api-Version": "2022-11-28",+ },+ });+ if (!response.ok) {+ throw new Error(`GitHub returned ${response.status} while revalidating package publication.`);+ }+ return response.json();+}diff --git a/apps/package-artifacts/lib/publication-current.test.mjs b/apps/package-artifacts/lib/publication-current.test.mjsnew file mode 100644index 000000000..e25c37185--- /dev/null+++ b/apps/package-artifacts/lib/publication-current.test.mjs@@ -0,0 +1,77 @@+import { describe, expect, test, vi } from "vitest";++import { assertCurrentPublicationTarget } from "./publication-current.mjs";++const sha = "a".repeat(40);+const input = { repository: "vercel/eve", ref: "123", sourceSha: sha, token: "token" };++function response(body, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: vi.fn().mockResolvedValue(body),+ };+}++describe("current package publication target", () => {+ test("accepts the current main build", async () => {+ const fetchImplementation = vi.fn().mockResolvedValue(response({ commit: { sha } }));+ await expect(+ assertCurrentPublicationTarget({ ...input, ref: "main" }, fetchImplementation),+ ).resolves.toBeUndefined();+ expect(fetchImplementation).toHaveBeenCalledWith(+ "https://api.github.com/repos/vercel/eve/branches/main",+ expect.objectContaining({+ headers: expect.objectContaining({ Authorization: "Bearer token" }),+ }),+ );+ });++ test("rejects a stale main build", async () => {+ const fetchImplementation = vi+ .fn()+ .mockResolvedValue(response({ commit: { sha: "b".repeat(40) } }));+ await expect(+ assertCurrentPublicationTarget({ ...input, ref: "main" }, fetchImplementation),+ ).rejects.toThrow("stale build");+ });++ test("accepts the current open pull request build", async () => {+ const fetchImplementation = vi+ .fn()+ .mockResolvedValue(response({ state: "open", base: { ref: "main" }, head: { sha } }));+ await expect(+ assertCurrentPublicationTarget(input, fetchImplementation),+ ).resolves.toBeUndefined();+ expect(fetchImplementation).toHaveBeenCalledWith(+ "https://api.github.com/repos/vercel/eve/pulls/123",+ expect.any(Object),+ );+ });++ test("rejects stale, closed, and retargeted pull requests", async () => {+ const invalidPulls = [+ { state: "open", base: { ref: "main" }, head: { sha: "b".repeat(40) } },+ { state: "closed", base: { ref: "main" }, head: { sha } },+ { state: "open", base: { ref: "release" }, head: { sha } },+ ];+ for (const pull of invalidPulls) {+ const fetchImplementation = vi.fn().mockResolvedValue(response(pull));+ await expect(assertCurrentPublicationTarget(input, fetchImplementation)).rejects.toThrow(+ "stale build",+ );+ }+ });++ test("rejects invalid configuration and GitHub failures", async () => {+ await expect(+ assertCurrentPublicationTarget({ ...input, repository: "eve" }, vi.fn()),+ ).rejects.toThrow("GITHUB_REPOSITORY");+ await expect(assertCurrentPublicationTarget({ ...input, token: "" }, vi.fn())).rejects.toThrow(+ "GITHUB_TOKEN",+ );+ await expect(+ assertCurrentPublicationTarget(input, vi.fn().mockResolvedValue(response({}, 503))),+ ).rejects.toThrow("GitHub returned 503");+ });+});diff --git a/apps/package-artifacts/lib/publication-target.mjs b/apps/package-artifacts/lib/publication-target.mjsnew file mode 100644index 000000000..03ad95810--- /dev/null+++ b/apps/package-artifacts/lib/publication-target.mjs@@ -0,0 +1,54 @@+export async function resolvePublicationTarget(github, context) {+ const run = context.payload.workflow_run;+ if (run?.conclusion !== "success") {+ throw new Error("Package publication requires a successful package build.");+ }++ if (run.event === "push") return resolveMainTarget(github, context.repo, run);+ if (run.event === "pull_request") return resolvePullRequestTarget(github, context.repo, run);+ throw new Error(`Unsupported package build event: ${String(run.event)}.`);+}++async function resolveMainTarget(github, repo, run) {+ if (run.head_branch !== "main") throw new Error("Only main pushes may publish a main package.");++ const { data: branch } = await github.rest.repos.getBranch({ ...repo, branch: "main" });+ if (branch.commit.sha !== run.head_sha) {+ throw new Error(+ `Refusing to publish stale main build ${run.head_sha}; main is ${branch.commit.sha}.`,+ );+ }+ return { runId: String(run.id), sha: run.head_sha, ref: "main" };+}++async function resolvePullRequestTarget(github, repo, run) {+ const headRepository = run.head_repository?.full_name;+ const baseRepository = `${repo.owner}/${repo.repo}`;+ if (headRepository !== baseRepository) {+ throw new Error(`Refusing to publish package artifacts from ${String(headRepository)}.`);+ }++ const [headOwner] = headRepository.split("/");+ const pulls = await github.paginate(github.rest.pulls.list, {+ ...repo,+ base: "main",+ head: `${headOwner}:${run.head_branch}`,+ state: "open",+ per_page: 100,+ });+ const matches = pulls.filter(+ (pull) =>+ pull.state === "open" &&+ pull.base.ref === "main" &&+ pull.head.sha === run.head_sha &&+ pull.head.ref === run.head_branch &&+ pull.head.repo?.full_name === headRepository,+ );+ if (matches.length !== 1) {+ throw new Error(+ `Expected one open pull request for package build ${run.id} at ${run.head_sha}; found ${matches.length}.`,+ );+ }++ return { runId: String(run.id), sha: run.head_sha, ref: String(matches[0].number) };+}diff --git a/apps/package-artifacts/lib/publication-target.test.mjs b/apps/package-artifacts/lib/publication-target.test.mjsnew file mode 100644index 000000000..f34d5b9c7--- /dev/null+++ b/apps/package-artifacts/lib/publication-target.test.mjs@@ -0,0 +1,123 @@+import { describe, expect, test, vi } from "vitest";++import { resolvePublicationTarget } from "./publication-target.mjs";++const sha = "a".repeat(40);+const repo = { owner: "vercel", repo: "eve" };++function workflowRun(overrides = {}) {+ return {+ id: 123,+ conclusion: "success",+ event: "pull_request",+ head_branch: "feature/package",+ head_repository: { full_name: "vercel/eve" },+ head_sha: sha,+ ...overrides,+ };+}++function pull(overrides = {}) {+ return {+ number: 456,+ state: "open",+ base: { ref: "main" },+ head: {+ ref: "feature/package",+ repo: { full_name: "vercel/eve" },+ sha,+ },+ ...overrides,+ };+}++function context(run) {+ return { repo, payload: { workflow_run: run } };+}++function github({ branchSha = sha, pulls = [] } = {}) {+ const listPullRequests = vi.fn();+ return {+ paginate: vi.fn().mockResolvedValue(pulls),+ rest: {+ pulls: { list: listPullRequests },+ repos: {+ getBranch: vi.fn().mockResolvedValue({ data: { commit: { sha: branchSha } } }),+ },+ },+ };+}++describe("package publication target", () => {+ test("publishes the current main build", async () => {+ const api = github();+ await expect(+ resolvePublicationTarget(api, context(workflowRun({ event: "push", head_branch: "main" }))),+ ).resolves.toEqual({ runId: "123", sha, ref: "main" });+ expect(api.rest.repos.getBranch).toHaveBeenCalledWith({ ...repo, branch: "main" });+ });++ test("rejects stale main builds", async () => {+ const api = github({ branchSha: "b".repeat(40) });+ await expect(+ resolvePublicationTarget(api, context(workflowRun({ event: "push", head_branch: "main" }))),+ ).rejects.toThrow("Refusing to publish stale main build");+ });++ test("publishes the current pull request build", async () => {+ const api = github({ pulls: [pull()] });+ await expect(resolvePublicationTarget(api, context(workflowRun()))).resolves.toEqual({+ runId: "123",+ sha,+ ref: "456",+ });+ expect(api.paginate).toHaveBeenCalledWith(api.rest.pulls.list, {+ ...repo,+ base: "main",+ head: "vercel:feature/package",+ state: "open",+ per_page: 100,+ });+ });++ test("rejects pull requests from forks", async () => {+ const run = workflowRun({ head_repository: { full_name: "alice/eve" } });+ const api = github();+ await expect(resolvePublicationTarget(api, context(run))).rejects.toThrow(+ "Refusing to publish package artifacts from alice/eve",+ );+ expect(api.paginate).not.toHaveBeenCalled();+ });++ test("rejects stale, closed, mismatched, and ambiguous pull requests", async () => {+ const stale = pull({+ head: { ref: "feature/package", repo: { full_name: "vercel/eve" }, sha: "b".repeat(40) },+ });+ const closed = pull({ state: "closed" });+ const wrongBase = pull({ base: { ref: "release" } });+ const wrongRepository = pull({+ head: { ref: "feature/package", repo: { full_name: "alice/eve" }, sha },+ });++ for (const pulls of [+ [stale],+ [closed],+ [wrongBase],+ [wrongRepository],+ [pull(), pull({ number: 789 })],+ ]) {+ await expect(+ resolvePublicationTarget(github({ pulls }), context(workflowRun())),+ ).rejects.toThrow("Expected one open pull request");+ }+ });++ test("rejects failed and unsupported builds", async () => {+ await expect(+ resolvePublicationTarget(github(), context(workflowRun({ conclusion: "failure" }))),+ ).rejects.toThrow("requires a successful package build");+ await expect(+ resolvePublicationTarget(github(), context(workflowRun({ event: "workflow_dispatch" }))),+ ).rejects.toThrow("Unsupported package build event");+ });+});diff --git a/apps/package-artifacts/scripts/publish.mjs b/apps/package-artifacts/scripts/publish.mjsindex 11f2316d5..0d6562f84 100644--- a/apps/package-artifacts/scripts/publish.mjs+++ b/apps/package-artifacts/scripts/publish.mjs@@ -4,6 +4,7 @@ import { join, resolve } from "node:path";import { get, put } from "@vercel/blob";+import { assertCurrentPublicationTarget } from "../lib/publication-current.mjs";import {PULL_REQUEST_PATTERN,SHA_PATTERN,@@ -53,6 +54,12 @@ const manifest = {};await putImmutableArtifact(packageArtifactPath(expectedSha), tarball, sha256);await putImmutableManifest(packageManifestPath(expectedSha), manifest);+await assertCurrentPublicationTarget({+ repository: process.env.GITHUB_REPOSITORY,+ ref: expectedRef,+ sourceSha: expectedSha,+ token: process.env.GITHUB_TOKEN,+});await put(packagePointerPath(expectedRef), JSON.stringify(manifest), {access: "private",addRandomSuffix: false,