Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): publish unverified preview package artifacts (#2054)

OwenKephart4e9b841d0797
diff --git a/.github/workflows/package-artifact-build.yml b/.github/workflows/package-artifact-build.yml
new file mode 100644
index 000000000..818e0d3c9
--- /dev/null
+++ b/.github/workflows/package-artifact-build.yml
@@ -0,0 +1,68 @@
+name: Package artifact build
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Select source
+ id: source
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ MAIN_SHA: ${{ github.sha }}
+ PR_NUMBER: ${{ github.event.pull_request.number }}
+ PR_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}
+ 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"
+ else
+ echo "repository=$PR_REPOSITORY" >> "$GITHUB_OUTPUT"
+ echo "sha=$PR_SHA" >> "$GITHUB_OUTPUT"
+ echo "ref=$PR_NUMBER" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Checkout source
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ repository: ${{ steps.source.outputs.repository }}
+ ref: ${{ steps.source.outputs.sha }}
+ 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: .nvmrc
+ cache: pnpm
+
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+
+ - name: Build package artifact
+ env:
+ EVE_PACKAGE_OUTPUT_DIRECTORY: ${{ github.workspace }}/package-artifact
+ EVE_PACKAGE_PUBLIC_ORIGIN: https://pkg.eve.dev
+ EVE_PACKAGE_REF: ${{ steps.source.outputs.ref }}
+ EVE_PACKAGE_SOURCE_SHA: ${{ steps.source.outputs.sha }}
+ run: pnpm --filter eve-package-artifacts package:prepare
+
+ - name: Upload package artifact
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: eve-package
+ path: package-artifact
+ if-no-files-found: error
+ retention-days: 7
diff --git a/.github/workflows/package-artifact-publish.yml b/.github/workflows/package-artifact-publish.yml
new file mode 100644
index 000000000..11bf180f1
--- /dev/null
+++ b/.github/workflows/package-artifact-publish.yml
@@ -0,0 +1,128 @@
+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:publish
diff --git a/apps/package-artifacts/README.md b/apps/package-artifacts/README.md
index ab9f04a48..9ccdd4c13 100644
--- a/apps/package-artifacts/README.md
+++ b/apps/package-artifacts/README.md
@@ -1,28 +1,50 @@
# eve package artifacts
-Git-linked Vercel project that builds an eve tarball from each `vercel/eve` `main` commit and uploads immutable SHA-addressed package and manifest artifacts to private Vercel Blob using deployment OIDC.
+A stable, read-only Vercel app at `pkg.eve.dev` proxies private Blob artifacts published by GitHub Actions. The app itself never packages source or writes Blob objects.
```text
/main/eve.tgz
/main/latest.json
+/pr/<number>/eve.tgz
+/pr/<number>/latest.json
/<full-sha>/eve.tgz
```
-The publisher uses Vercel's `VERCEL_PROJECT_PRODUCTION_URL` system environment variable as the public package domain. For example, if the production domain is `packages.example.com`, initialize an agent from the current `main` build with:
+Initialize an agent from the current `main` build with:
```bash
-npm exec --yes --package=https://packages.example.com/main/eve.tgz -- eve init my-agent
+npm exec --yes --package=https://pkg.eve.dev/main/eve.tgz -- eve init my-agent
```
-The production deployment resolves `main` to its checked-out commit. Its `latest.json` exposes metadata for that package, including the source SHA, immutable package URL, and checksum. The packaged CLI stamps its immutable commit URL into generated projects, so a project created through the moving `main` URL remains pinned to the package used to create it. The package route reads private Blob objects with deployment OIDC and streams them through the public project domain.
+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.
-The Vercel project must:
+## 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.
+
+[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.
+
+The publisher writes:
+
+```text
+packages/<sha>/eve.tgz
+packages/<sha>/manifest.json
+packages/refs/main.json
+packages/refs/pr/<number>.json
+```
+
+SHA objects are immutable. Main and PR pointer objects are mutable and short-cached.
+
+## Project setup
+
+The Vercel package project must:
- use this directory as its project root;
-- enable access to Vercel system environment variables;
+- connect the private package Blob store for reads;
- deploy `main` to Production;
-- connect a private Blob store to Production;
-- omit `BLOB_READ_WRITE_TOKEN` so Blob writes use Vercel OIDC; and
-- disable Deployment Protection so npm can reach the production origin anonymously.
+- 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.
-Only production builds of `main` publish artifacts. Other builds produce a placeholder deployment; configure the project's Ignored Build Step as `test "$VERCEL_GIT_COMMIT_REF" != "main"` to skip non-`main` deployments before install and build. The smoke check verifies public access and the downloaded artifact's gzip signature.
+The smoke check verifies public access and the downloaded main artifact's gzip signature.
diff --git a/apps/package-artifacts/api/package.js b/apps/package-artifacts/api/package.js
index 48ed1cbae..9642c715d 100644
--- a/apps/package-artifacts/api/package.js
+++ b/apps/package-artifacts/api/package.js
@@ -3,42 +3,44 @@ import { pipeline } from "node:stream/promises";
import { get } from "@vercel/blob";
-import { SHA_PATTERN, packageArtifactPath, packageManifestPath } from "../lib/package.mjs";
+import {
+ PULL_REQUEST_PATTERN,
+ SHA_PATTERN,
+ packageArtifactPath,
+ packageManifestPath,
+ packagePointerPath,
+} from "../lib/package.mjs";
export default async function handler(request, response) {
const ref = request.query.ref;
- if (typeof ref !== "string" || (ref !== "main" && !SHA_PATTERN.test(ref))) {
- return packageNotFound(response);
+ if (ref === "main" || (typeof ref === "string" && PULL_REQUEST_PATTERN.test(ref))) {
+ return servePointer(ref, request, response);
}
+ if (typeof ref !== "string" || !SHA_PATTERN.test(ref)) return packageNotFound(response);
- // Resolve `main` to the commit represented by the current production deployment.
- const sourceSha = ref === "main" ? process.env.VERCEL_GIT_COMMIT_SHA : ref;
- if (!SHA_PATTERN.test(sourceSha ?? "")) {
- return packageNotFound(response);
- }
-
- const manifest = await resolveManifest(sourceSha);
+ const manifest = await resolveManifest(ref);
if (manifest === undefined) return packageNotFound(response);
+ if (request.query.manifest === "1") return packageNotFound(response);
- if (request.query.manifest === "1") {
- if (ref !== "main") return packageNotFound(response);
- response.setHeader("Cache-Control", "public, max-age=60");
- return response.status(200).json(manifest);
- }
- if (ref === "main") {
- response.setHeader("Cache-Control", "public, max-age=60");
- return response.redirect(302, manifest.tarball);
- }
-
- const artifact = await get(packageArtifactPath(sourceSha), { access: "private" });
+ const artifact = await get(packageArtifactPath(ref), { access: "private" });
if (artifact === null) return packageNotFound(response);
-
response.setHeader("Cache-Control", "public, max-age=31536000, immutable");
response.setHeader("Content-Type", "application/gzip");
await pipeline(Readable.fromWeb(artifact.stream), response);
return undefined;
}
+async function servePointer(ref, request, response) {
+ const result = await get(packagePointerPath(ref), { access: "private" });
+ if (result === null) return packageNotFound(response);
+ const manifest = parseManifest(await new Response(result.stream).text());
+ if (manifest === undefined) return packageNotFound(response);
+
+ response.setHeader("Cache-Control", "public, max-age=60");
+ if (request.query.manifest === "1") return response.status(200).json(manifest);
+ return response.redirect(302, manifest.tarball);
+}
+
function packageNotFound(response) {
return response.status(404).send("Package not found.\n");
}
@@ -46,13 +48,22 @@ function packageNotFound(response) {
async function resolveManifest(sourceSha) {
const result = await get(packageManifestPath(sourceSha), { access: "private" });
if (result === null) return undefined;
+ return parseManifest(await new Response(result.stream).text(), sourceSha);
+}
- const manifest = JSON.parse(await new Response(result.stream).text());
+function parseManifest(source, expectedSha) {
+ let manifest;
+ try {
+ manifest = JSON.parse(source);
+ } catch {
+ return undefined;
+ }
if (
- manifest.sourceSha !== sourceSha ||
+ !SHA_PATTERN.test(manifest.sourceSha ?? "") ||
+ (expectedSha !== undefined && manifest.sourceSha !== expectedSha) ||
typeof manifest.version !== "string" ||
- typeof manifest.tarball !== "string" ||
- typeof manifest.sha256 !== "string"
+ manifest.tarball !== `https://pkg.eve.dev/${manifest.sourceSha}/eve.tgz` ||
+ !/^[0-9a-f]{64}$/i.test(manifest.sha256 ?? "")
) {
return undefined;
}
diff --git a/apps/package-artifacts/api/package.test.mjs b/apps/package-artifacts/api/package.test.mjs
index cc3b51f5a..95b3de76f 100644
--- a/apps/package-artifacts/api/package.test.mjs
+++ b/apps/package-artifacts/api/package.test.mjs
@@ -10,7 +10,7 @@ const sha = "a".repeat(40);
const manifest = {
sourceSha: sha,
version: `0.33.0+main.${sha}`,
- tarball: `https://packages.example.com/${sha}/eve.tgz`,
+ tarball: `https://pkg.eve.dev/${sha}/eve.tgz`,
sha256: "b".repeat(64),
};
@@ -26,40 +26,43 @@ function response() {
beforeEach(() => {
vi.clearAllMocks();
- process.env.VERCEL_GIT_COMMIT_SHA = sha;
get.mockImplementation(async (pathname) => ({
stream: new Blob([
- pathname.endsWith("manifest.json") ? JSON.stringify(manifest) : "package bytes",
+ pathname.endsWith("eve.tgz") ? "package bytes" : JSON.stringify(manifest),
]).stream(),
}));
});
describe("package route", () => {
- test("resolves main through the deployment commit", async () => {
+ test("resolves main through its published pointer", async () => {
const res = response();
await handler({ query: { ref: "main" } }, res);
- expect(get).toHaveBeenCalledWith(`packages/${sha}/manifest.json`, {
- access: "private",
- });
+ expect(get).toHaveBeenCalledWith("packages/refs/main.json", { access: "private" });
expect(res.setHeader).toHaveBeenCalledWith("Cache-Control", "public, max-age=60");
expect(res.redirect).toHaveBeenCalledWith(302, manifest.tarball);
});
- test("serves the current main manifest", async () => {
+ test("resolves a pull request through its published pointer", async () => {
const res = response();
- await handler({ query: { ref: "main", manifest: "1" } }, res);
+ await handler({ query: { ref: "123" } }, res);
+
+ expect(get).toHaveBeenCalledWith("packages/refs/pr/123.json", { access: "private" });
+ expect(res.redirect).toHaveBeenCalledWith(302, manifest.tarball);
+ });
+
+ test("serves mutable pointer manifests", async () => {
+ const res = response();
+ await handler({ query: { ref: "123", manifest: "1" } }, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith(manifest);
});
- test("serves SHA tarballs but not SHA latest manifests", async () => {
+ test("serves SHA tarballs but not SHA manifests", async () => {
const artifact = response();
await handler({ query: { ref: sha } }, artifact);
- expect(get).toHaveBeenLastCalledWith(`packages/${sha}/eve.tgz`, {
- access: "private",
- });
+ expect(get).toHaveBeenLastCalledWith(`packages/${sha}/eve.tgz`, { access: "private" });
expect(artifact.setHeader).toHaveBeenCalledWith(
"Cache-Control",
"public, max-age=31536000, immutable",
@@ -72,6 +75,19 @@ describe("package route", () => {
expect(latest.status).toHaveBeenCalledWith(404);
});
+ test("rejects pointers that redirect outside the package host", async () => {
+ get.mockResolvedValueOnce({
+ stream: new Blob([
+ JSON.stringify({ ...manifest, tarball: "https://example.com/eve.tgz" }),
+ ]).stream(),
+ });
+ const res = response();
+ await handler({ query: { ref: "main" } }, res);
+
+ expect(res.status).toHaveBeenCalledWith(404);
+ expect(res.redirect).not.toHaveBeenCalled();
+ });
+
test("rejects unsupported refs and missing artifacts", async () => {
const invalid = response();
await handler({ query: { ref: "feature/test" } }, invalid);
diff --git a/apps/package-artifacts/lib/package.mjs b/apps/package-artifacts/lib/package.mjs
index a18e65186..ae3ea2293 100644
--- a/apps/package-artifacts/lib/package.mjs
+++ b/apps/package-artifacts/lib/package.mjs
@@ -1,4 +1,5 @@
export const SHA_PATTERN = /^[0-9a-f]{40}$/i;
+export const PULL_REQUEST_PATTERN = /^[1-9]\d*$/;
const PACKAGE_VERSION_SHA_LENGTH = 16;
export function packageArtifactPath(sourceSha) {
@@ -9,6 +10,12 @@ export function packageManifestPath(sourceSha) {
return `packages/${sourceSha}/manifest.json`;
}
+export function packagePointerPath(ref) {
+ if (ref === "main") return "packages/refs/main.json";
+ if (PULL_REQUEST_PATTERN.test(ref)) return `packages/refs/pr/${ref}.json`;
+ throw new Error("Package ref must be main or a positive pull request number.");
+}
+
export function packageDependencyUrl(baseUrl, sourceSha) {
const url = new URL(baseUrl);
if (url.protocol !== "https:") throw new Error("Package base URL must use HTTPS.");
@@ -16,12 +23,12 @@ export function packageDependencyUrl(baseUrl, sourceSha) {
return url.toString();
}
-export function packageVersion(stableVersion, sourceSha) {
+export function packageVersion(stableVersion, sourceSha, channel = "main") {
const match = stableVersion.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/);
if (match === null) throw new Error(`Expected a stable eve version, received ${stableVersion}.`);
- return `${stableVersion}+main.${sourceSha.slice(0, PACKAGE_VERSION_SHA_LENGTH)}`;
+ return `${stableVersion}+${channel}.${sourceSha.slice(0, PACKAGE_VERSION_SHA_LENGTH)}`;
}
-export function preparePackageJson(packageJson, sourceSha) {
- return { ...packageJson, version: packageVersion(packageJson.version, sourceSha) };
+export function preparePackageJson(packageJson, sourceSha, channel) {
+ return { ...packageJson, version: packageVersion(packageJson.version, sourceSha, channel) };
}
diff --git a/apps/package-artifacts/lib/package.test.mjs b/apps/package-artifacts/lib/package.test.mjs
index a084466b5..05f5a6449 100644
--- a/apps/package-artifacts/lib/package.test.mjs
+++ b/apps/package-artifacts/lib/package.test.mjs
@@ -4,6 +4,7 @@ import {
packageArtifactPath,
packageDependencyUrl,
packageManifestPath,
+ packagePointerPath,
packageVersion,
preparePackageJson,
} from "./package.mjs";
@@ -11,34 +12,34 @@ import {
const sha = "a".repeat(40);
describe("package artifacts", () => {
- test("derives a main build version", () => {
+ test("derives channel-specific build versions", () => {
expect(packageVersion("0.33.0", sha)).toBe("0.33.0+main.aaaaaaaaaaaaaaaa");
+ expect(packageVersion("0.33.0", sha, "git")).toBe("0.33.0+git.aaaaaaaaaaaaaaaa");
});
- test("derives immutable artifact and dependency URLs", () => {
+ test("derives immutable artifacts and mutable pointers", () => {
expect(packageArtifactPath(sha)).toBe(`packages/${sha}/eve.tgz`);
expect(packageManifestPath(sha)).toBe(`packages/${sha}/manifest.json`);
+ expect(packagePointerPath("main")).toBe("packages/refs/main.json");
+ expect(packagePointerPath("123")).toBe("packages/refs/pr/123.json");
expect(packageDependencyUrl("https://packages.example.com", sha)).toBe(
`https://packages.example.com/${sha}/eve.tgz`,
);
});
- test("requires an HTTPS package base URL", () => {
+ test("requires HTTPS and valid pointer refs", () => {
expect(() => packageDependencyUrl("http://packages.example.com", sha)).toThrow(
"must use HTTPS",
);
+ expect(() => packagePointerPath("0")).toThrow("positive pull request");
});
test("prepares package metadata without mutating the source", () => {
const source = { name: "eve", version: "0.33.0" };
- expect(preparePackageJson(source, sha)).toEqual({
+ expect(preparePackageJson(source, sha, "git")).toEqual({
name: "eve",
- version: "0.33.0+main.aaaaaaaaaaaaaaaa",
+ version: "0.33.0+git.aaaaaaaaaaaaaaaa",
});
expect(source.version).toBe("0.33.0");
});
-
- test("rejects non-stable source versions", () => {
- expect(() => packageVersion("0.33.1-main.1", sha)).toThrow("Expected a stable eve version");
- });
});
diff --git a/apps/package-artifacts/package.json b/apps/package-artifacts/package.json
index bae5f96e9..0cb2aa9d8 100644
--- a/apps/package-artifacts/package.json
+++ b/apps/package-artifacts/package.json
@@ -5,6 +5,8 @@
"type": "module",
"scripts": {
"build": "node scripts/build.mjs",
+ "package:prepare": "node scripts/prepare.mjs",
+ "package:publish": "node scripts/publish.mjs",
"test": "vitest run --config vitest.config.ts",
"test:smoke": "node scripts/check-smoke.mjs"
},
diff --git a/apps/package-artifacts/scripts/build.mjs b/apps/package-artifacts/scripts/build.mjs
index fffb08c36..449b96752 100644
--- a/apps/package-artifacts/scripts/build.mjs
+++ b/apps/package-artifacts/scripts/build.mjs
@@ -1,106 +1,30 @@
-import { createHash } from "node:crypto";
-import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
-import { get, put } from "@vercel/blob";
-
-import {
- SHA_PATTERN,
- packageArtifactPath,
- packageDependencyUrl,
- packageManifestPath,
- preparePackageJson,
-} from "../lib/package.mjs";
-import { packPackage } from "../lib/pack.mjs";
const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
-const repoRoot = resolve(appRoot, "../..");
-const packageRoot = join(repoRoot, "packages/eve");
-const packageJsonPath = join(packageRoot, "package.json");
-const artifactDirectory = join(appRoot, ".artifacts");
-const sourceSha = process.env.VERCEL_GIT_COMMIT_SHA;
-const branch = process.env.VERCEL_GIT_COMMIT_REF;
-const productionDomain = process.env.VERCEL_PROJECT_PRODUCTION_URL;
-
-if (!SHA_PATTERN.test(sourceSha ?? "")) {
- throw new Error("VERCEL_GIT_COMMIT_SHA must be a 40-character Git commit SHA.");
-}
-if (branch !== "main" || process.env.VERCEL_ENV !== "production") {
- await mkdir(join(appRoot, "public"), { recursive: true });
- await writeFile(
- join(appRoot, "public/index.html"),
- "<!doctype html><title>eve packages</title><p>Artifacts are only published from main.</p>\n",
- );
- process.exit(0);
-}
-
-if (typeof productionDomain !== "string" || productionDomain.length === 0) {
- throw new Error("VERCEL_PROJECT_PRODUCTION_URL is required for package publishing.");
-}
-
-const originalPackageJson = await readFile(packageJsonPath, "utf8");
-const preparedPackageJson = preparePackageJson(JSON.parse(originalPackageJson), sourceSha);
-const version = preparedPackageJson.version;
-// Generated projects pin this deployment's immutable SHA route, never the moving main route.
-const dependencyUrl = packageDependencyUrl(`https://${productionDomain}`, sourceSha);
-const artifactPath = packageArtifactPath(sourceSha);
-
-try {
- await rm(artifactDirectory, { force: true, recursive: true });
- await writeFile(packageJsonPath, `${JSON.stringify(preparedPackageJson, null, 2)}\n`);
- const tarball = await packPackage(packageRoot, version, {
- ...process.env,
- EVE_MAIN_DEPENDENCY_URL: dependencyUrl,
- });
- const sha256 = createHash("sha256").update(tarball).digest("hex");
- try {
- await put(artifactPath, tarball, {
- access: "private",
- addRandomSuffix: false,
- allowOverwrite: false,
- cacheControlMaxAge: 31_536_000,
- contentType: "application/gzip",
- });
- } catch (error) {
- // Redeploys are valid only when this commit still produces identical package bytes.
- if (!(error instanceof Error) || !error.message.includes("already exists")) throw error;
- const publishedArtifact = await get(artifactPath, { access: "private", useCache: false });
- if (publishedArtifact === null) {
- throw new Error("Published package artifact could not be read.");
- }
- const publishedSha256 = createHash("sha256")
- .update(Buffer.from(await new Response(publishedArtifact.stream).arrayBuffer()))
- .digest("hex");
- if (publishedSha256 !== sha256) {
- throw new Error(`Commit ${sourceSha} was already published with different package contents.`);
- }
- }
-
- const manifest = { sourceSha, version, tarball: dependencyUrl, sha256 };
- const manifestPath = packageManifestPath(sourceSha);
- const existingManifest = await get(manifestPath, { access: "private", useCache: false });
- if (existingManifest === null) {
- await put(manifestPath, JSON.stringify(manifest), {
- access: "private",
- addRandomSuffix: false,
- allowOverwrite: false,
- cacheControlMaxAge: 31_536_000,
- contentType: "application/json",
- });
- } else {
- const published = JSON.parse(await new Response(existingManifest.stream).text());
- if (published.sha256 !== sha256) {
- throw new Error(`Commit ${sourceSha} was already published with different package contents.`);
- }
- }
- await mkdir(join(appRoot, "public"), { recursive: true });
- await writeFile(
- join(appRoot, "public/index.html"),
- `<!doctype html><title>eve packages</title><pre>${JSON.stringify(manifest, null, 2)}</pre>\n`,
- );
- process.stdout.write(`${JSON.stringify(manifest)}\n`);
-} finally {
- await writeFile(packageJsonPath, originalPackageJson);
- await rm(artifactDirectory, { force: true, recursive: true });
-}
+await mkdir(join(appRoot, "public"), { recursive: true });
+await writeFile(
+ join(appRoot, "public", "index.html"),
+ `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>eve packages</title>
+ <style>
+ :root { color-scheme: light dark; }
+ * { box-sizing: border-box; }
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #fff; color: #111; font-family: Geist, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
+ main { width: min(100% - 48px, 480px); text-align: center; }
+ .mark { width: 32px; height: 32px; margin: 0 auto 24px; border-radius: 50%; background: #111; }
+ h1 { margin: 0; font-size: 20px; font-weight: 500; letter-spacing: -0.03em; }
+ p { margin: 8px 0 0; color: #666; font-size: 14px; }
+ @media (prefers-color-scheme: dark) { body { background: #000; color: #ededed; } .mark { background: #ededed; } p { color: #888; } }
+ </style>
+ </head>
+ <body><main><div class="mark" aria-hidden="true"></div><h1>eve packages</h1><p>Package artifacts for eve development.</p></main></body>
+</html>
+`,
+);
diff --git a/apps/package-artifacts/scripts/prepare.mjs b/apps/package-artifacts/scripts/prepare.mjs
new file mode 100644
index 000000000..262495222
--- /dev/null
+++ b/apps/package-artifacts/scripts/prepare.mjs
@@ -0,0 +1,58 @@
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ PULL_REQUEST_PATTERN,
+ SHA_PATTERN,
+ packageDependencyUrl,
+ preparePackageJson,
+} from "../lib/package.mjs";
+import { packPackage } from "../lib/pack.mjs";
+
+const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const repoRoot = resolve(appRoot, "../..");
+const packageRoot = join(repoRoot, "packages/eve");
+const packageJsonPath = join(packageRoot, "package.json");
+const sourceSha = process.env.EVE_PACKAGE_SOURCE_SHA;
+const ref = process.env.EVE_PACKAGE_REF;
+const packageOrigin = process.env.EVE_PACKAGE_PUBLIC_ORIGIN;
+const outputDirectory = resolve(process.env.EVE_PACKAGE_OUTPUT_DIRECTORY ?? "package-artifact");
+
+if (!SHA_PATTERN.test(sourceSha ?? "")) {
+ throw new Error("EVE_PACKAGE_SOURCE_SHA must be a 40-character Git commit SHA.");
+}
+if (ref !== "main" && !PULL_REQUEST_PATTERN.test(ref ?? "")) {
+ throw new Error("EVE_PACKAGE_REF must be main or a positive pull request number.");
+}
+if (typeof packageOrigin !== "string" || packageOrigin.length === 0) {
+ throw new Error("EVE_PACKAGE_PUBLIC_ORIGIN is required.");
+}
+
+const originalPackageJson = await readFile(packageJsonPath, "utf8");
+const preparedPackageJson = preparePackageJson(JSON.parse(originalPackageJson), sourceSha, "git");
+const dependencyUrl = packageDependencyUrl(packageOrigin, sourceSha);
+
+try {
+ await writeFile(packageJsonPath, `${JSON.stringify(preparedPackageJson, null, 2)}\n`);
+ const tarball = await packPackage(packageRoot, preparedPackageJson.version, {
+ ...process.env,
+ EVE_PACKAGE_DEPENDENCY_URL: dependencyUrl,
+ });
+ const metadata = {
+ sourceSha,
+ ref,
+ version: preparedPackageJson.version,
+ tarball: dependencyUrl,
+ sha256: createHash("sha256").update(tarball).digest("hex"),
+ };
+
+ await rm(outputDirectory, { force: true, recursive: true });
+ await mkdir(outputDirectory, { recursive: true });
+ await writeFile(join(outputDirectory, "eve.tgz"), tarball);
+ await writeFile(join(outputDirectory, "metadata.json"), `${JSON.stringify(metadata)}\n`);
+ process.stdout.write(`${JSON.stringify(metadata)}\n`);
+} finally {
+ await writeFile(packageJsonPath, originalPackageJson);
+}
diff --git a/apps/package-artifacts/scripts/publish.mjs b/apps/package-artifacts/scripts/publish.mjs
new file mode 100644
index 000000000..11f2316d5
--- /dev/null
+++ b/apps/package-artifacts/scripts/publish.mjs
@@ -0,0 +1,108 @@
+import { createHash } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { join, resolve } from "node:path";
+
+import { get, put } from "@vercel/blob";
+
+import {
+ PULL_REQUEST_PATTERN,
+ SHA_PATTERN,
+ packageArtifactPath,
+ packageManifestPath,
+ packagePointerPath,
+} from "../lib/package.mjs";
+
+const inputDirectory = resolve(process.env.EVE_PACKAGE_INPUT_DIRECTORY ?? "package-artifact");
+const expectedSha = process.env.EVE_PACKAGE_SOURCE_SHA;
+const expectedRef = process.env.EVE_PACKAGE_REF;
+const token = process.env.EVE_PACKAGE_BLOB_READ_WRITE_TOKEN;
+
+if (!SHA_PATTERN.test(expectedSha ?? "")) {
+ throw new Error("EVE_PACKAGE_SOURCE_SHA must be a 40-character Git commit SHA.");
+}
+if (expectedRef !== "main" && !PULL_REQUEST_PATTERN.test(expectedRef ?? "")) {
+ throw new Error("EVE_PACKAGE_REF must be main or a positive pull request number.");
+}
+if (typeof token !== "string" || token.length === 0) {
+ throw new Error("EVE_PACKAGE_BLOB_READ_WRITE_TOKEN is required.");
+}
+
+const tarball = await readFile(join(inputDirectory, "eve.tgz"));
+const metadata = JSON.parse(await readFile(join(inputDirectory, "metadata.json"), "utf8"));
+const sha256 = createHash("sha256").update(tarball).digest("hex");
+if (
+ metadata.sourceSha !== expectedSha ||
+ metadata.ref !== expectedRef ||
+ metadata.sha256 !== sha256 ||
+ !/^\d+\.\d+\.\d+\+git\.[0-9a-f]{16}$/i.test(metadata.version ?? "") ||
+ !metadata.version.endsWith(`+git.${expectedSha.slice(0, 16)}`) ||
+ typeof metadata.tarball !== "string"
+) {
+ throw new Error("Package artifact metadata does not match the trusted publication target.");
+}
+const expectedUrl = `https://pkg.eve.dev/${expectedSha}/eve.tgz`;
+if (metadata.tarball !== expectedUrl) {
+ throw new Error(`Package artifact URL must be ${expectedUrl}.`);
+}
+
+const manifest = {
+ sourceSha: expectedSha,
+ version: metadata.version,
+ tarball: expectedUrl,
+ sha256,
+};
+await putImmutableArtifact(packageArtifactPath(expectedSha), tarball, sha256);
+await putImmutableManifest(packageManifestPath(expectedSha), manifest);
+await put(packagePointerPath(expectedRef), JSON.stringify(manifest), {
+ access: "private",
+ addRandomSuffix: false,
+ allowOverwrite: true,
+ cacheControlMaxAge: 60,
+ contentType: "application/json",
+ token,
+});
+process.stdout.write(`${JSON.stringify(manifest)}\n`);
+
+async function putImmutableArtifact(pathname, bytes, expectedHash) {
+ try {
+ await put(pathname, bytes, immutableOptions("application/gzip"));
+ } catch (error) {
+ if (!(error instanceof Error) || !error.message.includes("already exists")) throw error;
+ const published = await get(pathname, { access: "private", useCache: false, token });
+ if (published === null) throw new Error("Published package artifact could not be read.");
+ const publishedHash = createHash("sha256")
+ .update(Buffer.from(await new Response(published.stream).arrayBuffer()))
+ .digest("hex");
+ if (publishedHash !== expectedHash) {
+ throw new Error(
+ `Commit ${expectedSha} was already published with different package contents.`,
+ );
+ }
+ }
+}
+
+async function putImmutableManifest(pathname, value) {
+ try {
+ await put(pathname, JSON.stringify(value), immutableOptions("application/json"));
+ } catch (error) {
+ if (!(error instanceof Error) || !error.message.includes("already exists")) throw error;
+ const published = await get(pathname, { access: "private", useCache: false, token });
+ if (published === null) throw new Error("Published package manifest could not be read.");
+ if (JSON.parse(await new Response(published.stream).text()).sha256 !== value.sha256) {
+ throw new Error(
+ `Commit ${expectedSha} was already published with different package contents.`,
+ );
+ }
+ }
+}
+
+function immutableOptions(contentType) {
+ return {
+ access: "private",
+ addRandomSuffix: false,
+ allowOverwrite: false,
+ cacheControlMaxAge: 31_536_000,
+ contentType,
+ token,
+ };
+}
diff --git a/apps/package-artifacts/vercel.json b/apps/package-artifacts/vercel.json
index 0fce886a5..5cb053353 100644
--- a/apps/package-artifacts/vercel.json
+++ b/apps/package-artifacts/vercel.json
@@ -4,10 +4,9 @@
"installCommand": "pnpm install --frozen-lockfile",
"outputDirectory": "public",
"rewrites": [
- { "source": "/:ref*/eve.tgz", "destination": "/api/package?ref=:ref" },
- {
- "source": "/main/latest.json",
- "destination": "/api/package?ref=main&manifest=1"
- }
+ { "source": "/pr/:ref/eve.tgz", "destination": "/api/package?ref=:ref" },
+ { "source": "/pr/:ref/latest.json", "destination": "/api/package?ref=:ref&manifest=1" },
+ { "source": "/:ref/eve.tgz", "destination": "/api/package?ref=:ref" },
+ { "source": "/main/latest.json", "destination": "/api/package?ref=main&manifest=1" }
]
}
diff --git a/packages/eve/scripts/stamp-version-tokens.mjs b/packages/eve/scripts/stamp-version-tokens.mjs
index 5ff4e652b..894848fe5 100644
--- a/packages/eve/scripts/stamp-version-tokens.mjs
+++ b/packages/eve/scripts/stamp-version-tokens.mjs
@@ -39,7 +39,7 @@ if (typeof nodeEngine !== "string") {
throw new Error("eve package.json is missing a string engines.node");
}
-const evePackageDependencyVersion = process.env.EVE_MAIN_DEPENDENCY_URL ?? packageJson.version;
+const evePackageDependencyVersion = process.env.EVE_PACKAGE_DEPENDENCY_URL ?? packageJson.version;
const replacements = {
__EVE_PACKAGE_VERSION__: packageJson.version,