Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): add Trusted Sources policy primitives (#190)

Rui846c924d4b46
diff --git a/packages/eve/package.json b/packages/eve/package.json
index 0c9f78196..309dc471a 100644
--- a/packages/eve/package.json
+++ b/packages/eve/package.json
@@ -306,6 +306,7 @@
"@vercel/eve-catalog": "workspace:*",
"@vercel/oidc": "3.5.0",
"@vercel/sandbox": "catalog:",
+ "@vercel/sdk": "1.28.1",
"@workflow/core": "5.0.0-beta.19",
"@workflow/errors": "5.0.0-beta.8",
"@workflow/world": "5.0.0-beta.10",
diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts
new file mode 100644
index 000000000..92df5a4f1
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts
@@ -0,0 +1,84 @@
+import type {
+ UpdateProjectCustomAllow,
+ UpdateProjectTrustedSources,
+} from "@vercel/sdk/models/updateprojectprojectsaction.js";
+
+export type TrustedSourceEnvironmentRule = UpdateProjectCustomAllow;
+
+export interface TrustedSourceProject {
+ readonly projectId: string;
+ readonly customEnvironmentSlugs: readonly string[];
+}
+
+type TrustedSourceAccessPlan =
+ | { readonly kind: "unchanged" }
+ | { readonly kind: "update"; readonly trustedSources: UpdateProjectTrustedSources };
+
+const SYSTEM_ENVIRONMENTS = new Set(["development", "preview", "production"]);
+
+function environmentSetIncludes(
+ set: UpdateProjectCustomAllow["from"] | UpdateProjectCustomAllow["to"],
+ environment: string,
+): boolean {
+ if (set.slugs?.includes(environment) === true) return true;
+ return set.preset === "all-custom" && !SYSTEM_ENVIRONMENTS.has(environment);
+}
+
+function ruleIncludes(
+ rule: UpdateProjectCustomAllow,
+ sourceEnvironment: string,
+ targetEnvironment: string,
+): boolean {
+ return (
+ environmentSetIncludes(rule.from, sourceEnvironment) &&
+ environmentSetIncludes(rule.to, targetEnvironment)
+ );
+}
+
+function environmentRule(from: string, to: string): UpdateProjectCustomAllow {
+ return { from: { slugs: [from] }, to: { slugs: [to] } };
+}
+
+function defaultRules(project: TrustedSourceProject): UpdateProjectCustomAllow[] {
+ const rules = [
+ environmentRule("production", "production"),
+ environmentRule("preview", "preview"),
+ environmentRule("development", "preview"),
+ ];
+ for (const environment of project.customEnvironmentSlugs) {
+ rules.push(environmentRule(environment, environment));
+ }
+ return rules;
+}
+
+/**
+ * Plans the smallest policy update that lets a project's Development token
+ * reach one of that same project's deployment environments.
+ */
+export function planTrustedSourceAccess(input: {
+ readonly project: TrustedSourceProject;
+ readonly targetEnvironment: string;
+ readonly trustedSources?: UpdateProjectTrustedSources;
+}): TrustedSourceAccessPlan {
+ const projectRule = input.trustedSources?.projects?.[input.project.projectId];
+ const explicitRules = projectRule?.customAllow;
+ const existingRules = explicitRules ?? defaultRules(input.project);
+ if (existingRules.some((rule) => ruleIncludes(rule, "development", input.targetEnvironment))) {
+ return { kind: "unchanged" };
+ }
+
+ const customAllow = [...existingRules, environmentRule("development", input.targetEnvironment)];
+ return {
+ kind: "update",
+ trustedSources: {
+ ...input.trustedSources,
+ projects: {
+ ...input.trustedSources?.projects,
+ [input.project.projectId]: {
+ ...projectRule,
+ customAllow,
+ },
+ },
+ },
+ };
+}
diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts
new file mode 100644
index 000000000..ce53b27a3
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts
@@ -0,0 +1,488 @@
+import { createFakePrompter } from "#internal/testing/fake-prompter.js";
+import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";
+import type { VercelCaptureResult } from "#setup/primitives/index.js";
+import type { Prompter, PrompterValue, SingleSelectOptions } from "#setup/prompter.js";
+import { trustedSourcesToJSON } from "@vercel/sdk/models/updateprojectprojectsoptionsallowlist.js";
+import { describe, expect, it } from "vitest";
+import { vi } from "vitest";
+
+import {
+ planTrustedSourceAccess,
+ type TrustedSourceEnvironmentRule,
+} from "./vercel-trusted-sources-policy.js";
+import {
+ applyVercelTrustedSourceAccess,
+ prepareVercelTrustedSourceAccess,
+ type VercelTrustedSourceDeps,
+} from "./vercel-trusted-sources.js";
+
+function rule(from: string, to: string): TrustedSourceEnvironmentRule {
+ return { from: { slugs: [from] }, to: { slugs: [to] } };
+}
+
+const self = {
+ projectId: "prj_target",
+ customEnvironmentSlugs: [] as const,
+};
+
+const PREVIEW_TARGET = await resolveTestVercelTarget({
+ host: "inbound.example.com",
+ projectId: "prj_target",
+ projectName: "inbound",
+});
+const PRODUCTION_TARGET = await resolveTestVercelTarget({
+ host: "inbound.example.com",
+ projectId: "prj_target",
+ projectName: "inbound",
+ environment: "production",
+});
+
+function captureSequence(...results: VercelCaptureResult[]) {
+ return vi.fn<VercelTrustedSourceDeps["captureVercel"]>(async () => {
+ const result = results.shift();
+ if (result === undefined) throw new Error("Unexpected Vercel CLI call");
+ return result;
+ });
+}
+
+function success(value: unknown): VercelCaptureResult {
+ return { ok: true, stdout: JSON.stringify(value) };
+}
+
+function projectResponse(
+ id: string,
+ name: string,
+ customEnvironmentSlugs: readonly string[] = [],
+ trustedSources: unknown = null,
+) {
+ return {
+ id,
+ name,
+ customEnvironments: customEnvironmentSlugs.map((slug) => ({ slug })),
+ trustedSources,
+ };
+}
+
+function failure(message: string): VercelCaptureResult {
+ return { ok: false, failure: { code: 1, message, stderr: "", stdout: "" } };
+}
+
+function accessDeps(
+ captureVercel: VercelTrustedSourceDeps["captureVercel"],
+): Partial<VercelTrustedSourceDeps> {
+ return { captureVercel };
+}
+
+async function prepareAndApply(input: {
+ readonly captureVercel: VercelTrustedSourceDeps["captureVercel"];
+ readonly prompter: Prompter;
+ readonly target?: typeof PRODUCTION_TARGET;
+}) {
+ const preparation = await prepareVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ target: input.target ?? PRODUCTION_TARGET,
+ prompter: input.prompter,
+ deps: accessDeps(input.captureVercel),
+ });
+ if (preparation.kind !== "approved") {
+ throw new Error(`Expected approved access, received ${preparation.kind}.`);
+ }
+ return await applyVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ grant: preparation.grant,
+ deps: accessDeps(input.captureVercel),
+ });
+}
+
+describe("planTrustedSourceAccess", () => {
+ it("leaves the same-project development-to-preview default unchanged", () => {
+ expect(
+ planTrustedSourceAccess({
+ project: self,
+ targetEnvironment: "preview",
+ }),
+ ).toEqual({ kind: "unchanged" });
+ });
+
+ it("preserves self-access defaults when adding development-to-production", () => {
+ expect(
+ planTrustedSourceAccess({
+ project: self,
+ targetEnvironment: "production",
+ trustedSources: {
+ projects: {
+ prj_other: { label: "existing project" },
+ },
+ oidcProviders: {
+ "https://token.actions.githubusercontent.com": [
+ {
+ to: { slugs: ["production"] },
+ claims: { repository: ["acme/app"] },
+ },
+ ],
+ },
+ },
+ }),
+ ).toEqual({
+ kind: "update",
+ trustedSources: {
+ projects: {
+ prj_other: { label: "existing project" },
+ prj_target: {
+ customAllow: [
+ rule("production", "production"),
+ rule("preview", "preview"),
+ rule("development", "preview"),
+ rule("development", "production"),
+ ],
+ },
+ },
+ oidcProviders: {
+ "https://token.actions.githubusercontent.com": [
+ {
+ to: { slugs: ["production"] },
+ claims: { repository: ["acme/app"] },
+ },
+ ],
+ },
+ },
+ });
+ });
+
+ it("appends to explicit rules without restoring defaults the user removed", () => {
+ expect(
+ planTrustedSourceAccess({
+ project: self,
+ targetEnvironment: "production",
+ trustedSources: {
+ projects: {
+ prj_target: {
+ label: "locked down",
+ customAllow: [rule("preview", "preview")],
+ },
+ },
+ },
+ }),
+ ).toEqual({
+ kind: "update",
+ trustedSources: {
+ projects: {
+ prj_target: {
+ label: "locked down",
+ customAllow: [rule("preview", "preview"), rule("development", "production")],
+ },
+ },
+ },
+ });
+ });
+
+ it("preserves custom-environment defaults before adding development access", () => {
+ expect(
+ planTrustedSourceAccess({
+ project: {
+ projectId: "prj_target",
+ customEnvironmentSlugs: ["staging"],
+ },
+ targetEnvironment: "staging",
+ }),
+ ).toEqual({
+ kind: "update",
+ trustedSources: {
+ projects: {
+ prj_target: {
+ customAllow: [
+ rule("production", "production"),
+ rule("preview", "preview"),
+ rule("development", "preview"),
+ rule("staging", "staging"),
+ rule("development", "staging"),
+ ],
+ },
+ },
+ },
+ });
+ });
+
+ it("is idempotent when an existing rule already covers the pair", () => {
+ expect(
+ planTrustedSourceAccess({
+ project: self,
+ targetEnvironment: "production",
+ trustedSources: {
+ projects: {
+ prj_target: {
+ customAllow: [
+ {
+ from: { slugs: ["development", "preview"] },
+ to: { slugs: ["preview", "production"] },
+ },
+ ],
+ },
+ },
+ },
+ }),
+ ).toEqual({ kind: "unchanged" });
+ });
+});
+
+describe("prepareVercelTrustedSourceAccess", () => {
+ it("returns the PATCH failure without claiming the policy changed", async () => {
+ const captureVercel = captureSequence(
+ success(projectResponse("prj_target", "inbound")),
+ failure("Vercel rejected the policy update."),
+ );
+
+ await expect(
+ applyVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ grant: {
+ ownerId: "team_a",
+ projectId: "prj_target",
+ projectName: "inbound",
+ targetEnvironment: "production",
+ },
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({
+ kind: "failed",
+ message: "Could not update Trusted Sources for inbound: Vercel rejected the policy update.",
+ });
+ });
+
+ it("rejects a structured PATCH error even when the Vercel CLI exits zero", async () => {
+ const captureVercel = captureSequence(
+ success(projectResponse("prj_target", "inbound")),
+ success({ error: { code: "forbidden", message: "Team access denied" } }),
+ );
+
+ await expect(
+ applyVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ grant: {
+ ownerId: "team_a",
+ projectId: "prj_target",
+ projectName: "inbound",
+ targetEnvironment: "production",
+ },
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({
+ kind: "failed",
+ message:
+ "Could not update Trusted Sources for inbound: Vercel API request failed: Team access denied.",
+ });
+ });
+
+ it("rejects a PATCH response for a different project", async () => {
+ const captureVercel = captureSequence(
+ success(projectResponse("prj_target", "inbound")),
+ success({ id: "prj_other" }),
+ );
+
+ await expect(
+ applyVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ grant: {
+ ownerId: "team_a",
+ projectId: "prj_target",
+ projectName: "inbound",
+ targetEnvironment: "production",
+ },
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({
+ kind: "failed",
+ message: "Vercel returned an invalid project response.",
+ });
+ });
+
+ it("re-reads the target policy immediately before patching", async () => {
+ const captureVercel = captureSequence(
+ success(projectResponse("prj_target", "inbound")),
+ success(
+ projectResponse("prj_target", "inbound", [], {
+ projects: { prj_other: { label: "concurrent rule" } },
+ }),
+ ),
+ success({ id: "prj_target" }),
+ );
+ const { prompter } = createFakePrompter({ single: () => "continue" });
+
+ await expect(
+ prepareAndApply({
+ captureVercel,
+ prompter,
+ }),
+ ).resolves.toMatchObject({ kind: "updated", targetProjectName: "inbound" });
+
+ expect(captureVercel).toHaveBeenCalledTimes(3);
+ expect(captureVercel).toHaveBeenNthCalledWith(
+ 3,
+ expect.arrayContaining([
+ "--field",
+ expect.stringContaining('"prj_other":{"label":"concurrent rule"}'),
+ ]),
+ expect.any(Object),
+ );
+ });
+
+ it("serializes Trusted Sources through the SDK contract", async () => {
+ const captureVercel = captureSequence(
+ success(
+ projectResponse("prj_target", "inbound", [], {
+ projects: {
+ prj_other: {
+ label: "existing policy",
+ futureProjectField: "discard",
+ },
+ },
+ futureTopLevelField: "discard",
+ }),
+ ),
+ success({ id: "prj_target" }),
+ );
+
+ await expect(
+ applyVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ grant: {
+ ownerId: "team_test",
+ projectId: "prj_target",
+ projectName: "inbound",
+ targetEnvironment: "production",
+ },
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toMatchObject({ kind: "updated", targetProjectName: "inbound" });
+
+ expect(captureVercel).toHaveBeenNthCalledWith(
+ 2,
+ expect.arrayContaining([
+ "--field",
+ `trustedSources=${trustedSourcesToJSON({
+ projects: {
+ prj_other: { label: "existing policy" },
+ prj_target: {
+ customAllow: [
+ rule("production", "production"),
+ rule("preview", "preview"),
+ rule("development", "preview"),
+ rule("development", "production"),
+ ],
+ },
+ },
+ })}`,
+ ]),
+ expect.any(Object),
+ );
+ });
+
+ it("warns before granting the resolved development-to-production pair", async () => {
+ const captureVercel = captureSequence(
+ success(projectResponse("prj_target", "inbound")),
+ success(projectResponse("prj_target", "inbound")),
+ success({ id: "prj_target" }),
+ );
+ let prompt: SingleSelectOptions<PrompterValue> | undefined;
+ const { prompter } = createFakePrompter({
+ single: (options) => {
+ prompt = options;
+ return "continue";
+ },
+ });
+
+ await expect(prepareAndApply({ captureVercel, prompter })).resolves.toMatchObject({
+ kind: "updated",
+ targetProjectName: "inbound",
+ });
+
+ expect(prompt?.message).toBe(
+ "Allow Development from inbound to access Production deployments of inbound?",
+ );
+ expect(prompt?.notices).toEqual([
+ {
+ tone: "warning",
+ text: "This changes Deployment Protection for inbound until the Trusted Sources rule is removed.",
+ },
+ ]);
+ expect(captureVercel).toHaveBeenNthCalledWith(
+ 3,
+ [
+ "api",
+ "/v9/projects/prj_target",
+ "--scope",
+ "team_test",
+ "--method",
+ "PATCH",
+ "--field",
+ `trustedSources=${trustedSourcesToJSON({
+ projects: {
+ prj_target: {
+ customAllow: [
+ rule("production", "production"),
+ rule("preview", "preview"),
+ rule("development", "preview"),
+ rule("development", "production"),
+ ],
+ },
+ },
+ })}`,
+ "--raw",
+ ],
+ expect.objectContaining({
+ cwd: "/repo",
+ }),
+ );
+ });
+
+ it("does not prompt or mutate for same-project development-to-preview", async () => {
+ const captureVercel = captureSequence(success(projectResponse("prj_target", "inbound")));
+ const { prompter } = createFakePrompter();
+
+ await expect(
+ prepareVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ target: PREVIEW_TARGET,
+ prompter,
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({ kind: "unchanged" });
+
+ expect(captureVercel).toHaveBeenCalledTimes(1);
+ });
+
+ it("rejects a project response for a different project", async () => {
+ const captureVercel = captureSequence(success(projectResponse("prj_other", "other-project")));
+ const { prompter } = createFakePrompter();
+
+ await expect(
+ prepareVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ target: PRODUCTION_TARGET,
+ prompter,
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({
+ kind: "failed",
+ message:
+ "Could not read Deployment Protection for inbound: Vercel returned an invalid project response.",
+ });
+ expect(captureVercel).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves policy unchanged when the user declines the access grant", async () => {
+ const captureVercel = captureSequence(success(projectResponse("prj_target", "inbound")));
+ const { prompter } = createFakePrompter({ single: () => "cancel" });
+
+ await expect(
+ prepareVercelTrustedSourceAccess({
+ workspaceRoot: "/repo",
+ target: PRODUCTION_TARGET,
+ prompter,
+ deps: accessDeps(captureVercel),
+ }),
+ ).resolves.toEqual({ kind: "cancelled" });
+
+ expect(captureVercel).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts
new file mode 100644
index 000000000..b41ad08e8
--- /dev/null
+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts
@@ -0,0 +1,265 @@
+import {
+ updateProjectTrustedSourcesFromJSON,
+ type UpdateProjectTrustedSources,
+} from "@vercel/sdk/models/updateprojectprojectsaction.js";
+import { trustedSourcesToJSON } from "@vercel/sdk/models/updateprojectprojectsoptionsallowlist.js";
+import { captureVercel } from "#setup/primitives/index.js";
+import type { Prompter } from "#setup/prompter.js";
+import { normalizeVercelApiResult } from "#setup/vercel-api-failure.js";
+import type { VerifiedVercelTarget } from "#setup/vercel-deployment.js";
+import { z } from "zod";
+
+import {
+ planTrustedSourceAccess,
+ type TrustedSourceProject,
+} from "./vercel-trusted-sources-policy.js";
+
+type VercelTrustedSourcePreparation =
+ | { readonly kind: "unchanged" }
+ | { readonly kind: "approved"; readonly grant: VercelTrustedSourceGrant }
+ | { readonly kind: "cancelled" }
+ | { readonly kind: "failed"; readonly message: string };
+
+type VercelTrustedSourceApplication =
+ | { readonly kind: "unchanged" }
+ | {
+ readonly kind: "updated";
+ readonly targetProjectName: string;
+ }
+ | { readonly kind: "failed"; readonly message: string };
+
+export interface VercelTrustedSourceGrant {
+ readonly ownerId: string;
+ readonly projectId: string;
+ readonly projectName: string;
+ readonly targetEnvironment: string;
+}
+
+export interface VercelTrustedSourceDeps {
+ readonly captureVercel: typeof captureVercel;
+}
+
+const ProjectSchema = z.object({
+ id: z.string().min(1),
+ name: z.string().min(1),
+ customEnvironments: z.array(z.object({ slug: z.string().min(1) })).optional(),
+ trustedSources: z.unknown().nullable().optional(),
+});
+
+type VercelProject = Omit<z.infer<typeof ProjectSchema>, "trustedSources"> & {
+ readonly trustedSources?: UpdateProjectTrustedSources;
+};
+
+function parseJson(stdout: string): unknown {
+ try {
+ return JSON.parse(stdout);
+ } catch {
+ return undefined;
+ }
+}
+
+function parseTrustedSources(value: unknown): UpdateProjectTrustedSources | undefined {
+ const json = JSON.stringify(value);
+ if (json === undefined) return undefined;
+ const parsed = updateProjectTrustedSourcesFromJSON(json);
+ return parsed.ok ? parsed.value : undefined;
+}
+
+function parseProject(stdout: string): VercelProject | undefined {
+ const parsed = ProjectSchema.safeParse(parseJson(stdout));
+ if (!parsed.success) return undefined;
+
+ const { trustedSources, ...project } = parsed.data;
+ if (trustedSources === undefined || trustedSources === null) return project;
+
+ const policy = parseTrustedSources(trustedSources);
+ return policy === undefined ? undefined : { ...project, trustedSources: policy };
+}
+const ProjectUpdateSchema = z.object({ id: z.string().min(1) });
+
+const defaultDeps: VercelTrustedSourceDeps = { captureVercel };
+
+function environmentLabel(environment: string): string {
+ switch (environment) {
+ case "development":
+ return "Development";
+ case "preview":
+ return "Preview";
+ case "production":
+ return "Production";
+ default:
+ return environment;
+ }
+}
+
+function projectPolicyContext(project: VercelProject): TrustedSourceProject {
+ return {
+ projectId: project.id,
+ customEnvironmentSlugs: project.customEnvironments?.map(({ slug }) => slug) ?? [],
+ };
+}
+
+async function readProject(input: {
+ readonly deps: VercelTrustedSourceDeps;
+ readonly workspaceRoot: string;
+ readonly ownerId: string;
+ readonly projectId: string;
+ readonly signal?: AbortSignal;
+}): Promise<
+ | { readonly kind: "project"; readonly project: VercelProject }
+ | { readonly kind: "failed"; readonly message: string }
+> {
+ const result = await input.deps.captureVercel(
+ [
+ "api",
+ `/v9/projects/${encodeURIComponent(input.projectId)}`,
+ "--scope",
+ input.ownerId,
+ "--raw",
+ ],
+ { cwd: input.workspaceRoot, nonInteractive: true, signal: input.signal },
+ );
+ if (!result.ok) return { kind: "failed", message: result.failure.message };
+ const project = parseProject(result.stdout);
+ if (project === undefined || project.id !== input.projectId) {
+ return { kind: "failed", message: "Vercel returned an invalid project response." };
+ }
+ return { kind: "project", project };
+}
+
+/** Confirms a Trusted Sources grant for one verified target project. */
+export async function prepareVercelTrustedSourceAccess(input: {
+ readonly workspaceRoot: string;
+ readonly target: VerifiedVercelTarget;
+ readonly prompter: Prompter;
+ readonly signal?: AbortSignal;
+ readonly deps?: Partial<VercelTrustedSourceDeps>;
+}): Promise<VercelTrustedSourcePreparation> {
+ const deps: VercelTrustedSourceDeps = { ...defaultDeps, ...input.deps };
+ const deployment = input.target.deployment;
+
+ // A local project-scoped OIDC token represents the Development environment.
+ const projectResult = await readProject({
+ deps,
+ workspaceRoot: input.workspaceRoot,
+ ownerId: deployment.ownerId,
+ projectId: deployment.projectId,
+ signal: input.signal,
+ });
+ if (projectResult.kind === "failed") {
+ return {
+ kind: "failed",
+ message: `Could not read Deployment Protection for ${deployment.projectName}: ${projectResult.message}`,
+ };
+ }
+ const { project } = projectResult;
+ const plan = planTrustedSourceAccess({
+ project: projectPolicyContext(project),
+ targetEnvironment: deployment.environment,
+ trustedSources: project.trustedSources ?? undefined,
+ });
+ if (plan.kind === "unchanged") return { kind: "unchanged" };
+
+ const sourceEnvironment = environmentLabel("development");
+ const targetEnvironment = environmentLabel(deployment.environment);
+ const decision = await input.prompter.select<"continue" | "cancel">({
+ message: `Allow ${sourceEnvironment} from ${project.name} to access ${targetEnvironment} deployments of ${project.name}?`,
+ hintLayout: "stacked",
+ notices: [
+ {
+ tone: "warning",
+ text: `This changes Deployment Protection for ${project.name} until the Trusted Sources rule is removed.`,
+ },
+ ],
+ options: [
+ {
+ value: "continue",
+ label: "Allow access",
+ hint: `Add ${sourceEnvironment} → ${targetEnvironment} to Trusted Sources`,
+ },
+ {
+ value: "cancel",
+ label: "Cancel",
+ hint: "Leave Deployment Protection unchanged",
+ },
+ ],
+ });
+ if (decision === "cancel") return { kind: "cancelled" };
+
+ return {
+ kind: "approved",
+ grant: {
+ ownerId: deployment.ownerId,
+ projectId: project.id,
+ projectName: project.name,
+ targetEnvironment: deployment.environment,
+ },
+ };
+}
+
+/** Applies an approved grant against the target project's latest policy. */
+export async function applyVercelTrustedSourceAccess(input: {
+ readonly workspaceRoot: string;
+ readonly grant: VercelTrustedSourceGrant;
+ readonly signal?: AbortSignal;
+ readonly deps?: Partial<VercelTrustedSourceDeps>;
+}): Promise<VercelTrustedSourceApplication> {
+ const deps: VercelTrustedSourceDeps = { ...defaultDeps, ...input.deps };
+ const projectResult = await readProject({
+ deps,
+ workspaceRoot: input.workspaceRoot,
+ ownerId: input.grant.ownerId,
+ projectId: input.grant.projectId,
+ signal: input.signal,
+ });
+ if (projectResult.kind === "failed") {
+ return {
+ kind: "failed",
+ message: `Could not refresh Deployment Protection for ${input.grant.projectName}: ${projectResult.message}`,
+ };
+ }
+ const { project } = projectResult;
+ const plan = planTrustedSourceAccess({
+ project: projectPolicyContext(project),
+ targetEnvironment: input.grant.targetEnvironment,
+ trustedSources: project.trustedSources ?? undefined,
+ });
+ if (plan.kind === "unchanged") return { kind: "unchanged" };
+
+ const updateResult = normalizeVercelApiResult(
+ await deps.captureVercel(
+ [
+ "api",
+ `/v9/projects/${encodeURIComponent(project.id)}`,
+ "--scope",
+ input.grant.ownerId,
+ "--method",
+ "PATCH",
+ "--field",
+ `trustedSources=${trustedSourcesToJSON(plan.trustedSources)}`,
+ "--raw",
+ ],
+ {
+ cwd: input.workspaceRoot,
+ nonInteractive: true,
+ signal: input.signal,
+ },
+ ),
+ );
+ if (!updateResult.ok) {
+ return {
+ kind: "failed",
+ message: `Could not update Trusted Sources for ${project.name}: ${updateResult.failure.message}`,
+ };
+ }
+ const parsedUpdate = ProjectUpdateSchema.safeParse(parseJson(updateResult.stdout));
+ const updatedProject = parsedUpdate.success ? parsedUpdate.data : undefined;
+ if (updatedProject?.id !== project.id) {
+ return { kind: "failed", message: "Vercel returned an invalid project response." };
+ }
+
+ return {
+ kind: "updated",
+ targetProjectName: project.name,
+ };
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5fa5cef66..105bdd767 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -805,6 +805,9 @@ importers:
'@vercel/sandbox':
specifier: 'catalog:'
version: 2.2.1
+ '@vercel/sdk':
+ specifier: 1.28.1
+ version: 1.28.1
'@workflow/core':
specifier: 5.0.0-beta.19
version: 5.0.0-beta.19(@opentelemetry/[email protected])([email protected])
@@ -6815,6 +6818,9 @@ packages:
'@vercel/[email protected]':
resolution: {integrity: sha512-IqFYVEsPilXb28VbpTtrP5UkMgVAyQlp77zcLJUgCUo1yEbjJiClGS6sEqGjkAukhbLGS+T2vG3ZOgzSzUTyZg==}
+ '@vercel/[email protected]':
+ resolution: {integrity: sha512-QYAX0QStBQak4c9PXunGVERL68cp8r1JcVuQd+SwXGThuZkEHRMpSStnvrO1Ny2nWg9wOeRnS0GEp+md42IVfg==}
+
'@vercel/[email protected]':
resolution: {integrity: sha512-jwkNcrTeafWxjmWq4AHBaptSqZiJkYU5adLC9QBSqeim0GcqDMgN5Ievh8OG1rJ6W3A4l1oiP7qr9CWxGuzu3w==}
peerDependencies:
@@ -18923,6 +18929,10 @@ snapshots:
- bare-abort-controller
- react-native-b4a
+ '@vercel/[email protected]':
+ dependencies:
+ zod: 4.4.3
+
'@vercel/[email protected](1bf1af76e23df0ef2782fcce60ed20a8)':
optionalDependencies: