fix(cli): harden lambda destroy, snapshot media, upgrade and project file serving (#7509)

* fix(cli): lambda destroy runs SAM in a private folder and acts only on the selected stack

- sam delete outside a checkout runs in a fresh private temp folder,
  removed afterwards, instead of the shared temp directory.
- A stack state file must name the stack it is selected by.
- destroy and deploy derive the video repository name from the stack
  name instead of trusting the recorded value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot keeps remote clips in a private folder and reads only allowed URLs

- A video URL the download policy refuses (plain http, or a private,
  loopback or link-local host) is no longer handed to FFmpeg; the clip
  is skipped instead, as render does.
- Remote clips are cached in a per-user, owner-only temp folder; a
  folder open to other users is never reused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): upgrade --project writes package.json through an exclusive temp file

The rewrite now uses the shared atomic replace, which creates a fresh,
unpredictable sibling with exclusive creation, so an existing
package.json.tmp entry is never written through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): keep env files, Git data and tool records out of served and uploaded projects

- play and present answer 404 for .env files, .git and the tools'
  private .hyperframes records, as Studio's preview does for the records.
- publish and cloud render never stage an env file or tool record, even
  when markup references it, and never pull in an env file from outside
  the project.
- Cloud site uploads (Lambda and Cloud Run deploySite) leave env files out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): lambda commands accept a state file whose stack name differs only in case

On a case-insensitive disk, deploy --stack-name=Demo and --stack-name=demo share one
state file, so a name that matches apart from case is the same stack the user deployed
and keeps working as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot's fallback media folder uses createStagingDir

The repository check forbids bare mkdtemp beside a caller-supplied path, because it
fails past 260 characters on Windows. Also trims a comment so the new helper file stays
within its package's comment share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): snapshot never hands FFmpeg a remote URL

FFmpeg follows redirects and resolves hosts on its own, so a clip the downloader could
not fetch must not reach it as a URL. Snapshot now leaves such a clip out and warns,
as render does. A fallback media folder is removed when the process exits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(cli): cover .envrc, .env-local and .env_prod, and test present's private-file 404

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michael Wang
2026-11-10 20:00:58 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent cf90054613
commit c96ff540c4
22 changed files with 421 additions and 49 deletions
@@ -20,6 +20,7 @@ vi.mock("./state.js", () => ({
}));
vi.mock("./videoImage.js", () => ({
pushVideoImage: vi.fn(async () => ({ imageUri: "repo@sha256:a", repositoryName: "hf-video" })),
videoRepositoryName: (stackName: string) => `${stackName}-video`,
}));
const { runDeploy } = await import("./deploy.js");
+6 -2
View File
@@ -16,7 +16,7 @@ import { stagePrebuiltHandler } from "./prebuiltHandler.js";
import { fetchStackOutputs, locateSamTemplate, samDeploy } from "./sam.js";
import { repoRoot } from "./repoRoot.js";
import { DEFAULT_STACK_NAME, readStackOutputs, writeStackOutputs } from "./state.js";
import { pushVideoImage, type VideoArch } from "./videoImage.js";
import { pushVideoImage, videoRepositoryName, type VideoArch } from "./videoImage.js";
import { warmFunction } from "./warm.js";
export interface DeployArgs {
@@ -95,7 +95,11 @@ export async function runDeploy(args: Partial<DeployArgs> = {}): Promise<void> {
reservedConcurrency: outputs.reservedConcurrency,
videoFunctionName: outputs.videoFunctionName,
// Back on x86 the repository outlives the video function, so destroy still needs its name.
videoRepository: video?.repositoryName ?? readStackOutputs(resolved.stackName)?.videoRepository,
videoRepository:
video?.repositoryName ??
(readStackOutputs(resolved.stackName)?.videoRepository
? videoRepositoryName(resolved.stackName)
: undefined),
deployedAt: new Date().toISOString(),
});
@@ -0,0 +1,70 @@
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { stateFilePath, writeStackOutputs } from "./state.js";
const samDirs = vi.hoisted(() => [] as string[]);
vi.mock("./repoRoot.js", () => ({ repoRoot: () => undefined }));
vi.mock("./sam.js", () => ({
samDelete: vi.fn((opts: { samDir: string }) => {
samDirs.push(opts.samDir);
}),
deleteEcrRepository: vi.fn(),
}));
const { runDestroy } = await import("./destroy.js");
const { deleteEcrRepository, samDelete } = await import("./sam.js");
let cwd: string;
let previousCwd: string;
let quiet: { mockRestore(): void };
beforeEach(() => {
cwd = mkdtempSync(join(tmpdir(), "hf-lambda-destroy-"));
previousCwd = process.cwd();
process.chdir(cwd);
samDirs.length = 0;
vi.mocked(samDelete).mockClear();
vi.mocked(deleteEcrRepository).mockClear();
quiet = vi.spyOn(console, "log").mockImplementation(() => {});
});
afterEach(() => {
quiet.mockRestore();
process.chdir(previousCwd);
rmSync(cwd, { recursive: true, force: true });
});
const stack = {
stackName: "Demo",
region: "us-east-1",
bucketName: "b",
stateMachineArn: "s",
functionName: "f",
lambdaMemoryMb: 10240,
deployedAt: "2026-01-01T00:00:00Z",
};
describe("runDestroy", () => {
it("runs sam delete outside a checkout in a fresh folder it removes afterwards", async () => {
writeStackOutputs(stack, cwd);
await runDestroy({ stackName: "Demo" });
expect(samDirs).toHaveLength(1);
expect(samDirs[0]).not.toBe(tmpdir());
expect(existsSync(samDirs[0]!)).toBe(false);
expect(existsSync(stateFilePath("Demo", cwd))).toBe(false);
});
it("deletes the stack's own video repository, whatever name the state file records", async () => {
writeStackOutputs({ ...stack, videoRepository: "someone-elses-repo" }, cwd);
await runDestroy({ stackName: "Demo" });
expect(deleteEcrRepository).toHaveBeenCalledWith(
expect.objectContaining({ repositoryName: "demo-video" }),
);
});
});
+13 -12
View File
@@ -9,12 +9,14 @@
* rather than re-implementing the empty-and-delete dance here.
*/
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { c } from "../../ui/colors.js";
import { deleteStackOutputs, requireStack } from "./state.js";
import { deleteEcrRepository, samDelete } from "./sam.js";
import { repoRoot } from "./repoRoot.js";
import { videoRepositoryName } from "./videoImage.js";
export interface DestroyArgs {
stackName: string;
@@ -29,19 +31,18 @@ export async function runDestroy(args: DestroyArgs): Promise<void> {
// Mirror deploy.ts's AWS_PROFILE env fallback — `AWS_PROFILE=prod
// hyperframes lambda destroy` should hit the same account `deploy`
// did, not the default credentials chain.
samDelete({
samDir: root ? join(root, "examples", "aws-lambda") : tmpdir(),
stackName: stack.stackName,
region: stack.region,
awsProfile,
});
const samDir = root
? join(root, "examples", "aws-lambda")
: mkdtempSync(join(tmpdir(), "hf-sam-"));
try {
samDelete({ samDir, stackName: stack.stackName, region: stack.region, awsProfile });
} finally {
if (!root) rmSync(samDir, { recursive: true, force: true });
}
if (stack.videoRepository) {
console.log(c.dim(`→ Deleting ECR repository ${stack.videoRepository}`));
deleteEcrRepository({
repositoryName: stack.videoRepository,
region: stack.region,
awsProfile,
});
const repositoryName = videoRepositoryName(stack.stackName);
console.log(c.dim(`→ Deleting ECR repository ${repositoryName}`));
deleteEcrRepository({ repositoryName, region: stack.region, awsProfile });
}
deleteStackOutputs(args.stackName);
console.log();
+19 -2
View File
@@ -1,11 +1,12 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import {
deleteStackOutputs,
listStackNames,
readStackOutputs,
requireStack,
stateFilePath,
type StackOutputs,
writeStackOutputs,
@@ -64,4 +65,20 @@ describe("lambda state file", () => {
writeFileSync(path, "{ not json");
expect(readStackOutputs("bad", workdir)).toBeNull();
});
it("requireStack refuses a file that names a different stack", () => {
writeStackOutputs({ ...sample, stackName: "other" }, workdir);
const path = stateFilePath("other", workdir);
mkdirSync(dirname(stateFilePath("test", workdir)), { recursive: true });
writeFileSync(stateFilePath("test", workdir), readFileSync(path));
const quiet = vi.spyOn(console, "error").mockImplementation(() => {});
try {
expect(() => requireStack("test", workdir)).toThrow();
expect(requireStack("other", workdir).stackName).toBe("other");
writeFileSync(stateFilePath("OTHER", workdir), readFileSync(path));
expect(requireStack("OTHER", workdir).stackName).toBe("other");
} finally {
quiet.mockRestore();
}
});
});
+13 -5
View File
@@ -85,6 +85,9 @@ export function listStackNames(cwd: string = process.cwd()): string[] {
.map((f) => f.slice(STATE_FILE_PREFIX.length, -".json".length));
}
const sameFileOnCaseInsensitiveDisk = (a: string, b: string): boolean =>
a.toLowerCase() === b.toLowerCase();
/**
* Read stack outputs or print a helpful error and exit. Shared between
* `render`, `progress`, and `destroy` so the "did you run `deploy` first?"
@@ -92,14 +95,19 @@ export function listStackNames(cwd: string = process.cwd()): string[] {
*/
export function requireStack(stackName: string, cwd: string = process.cwd()): StackOutputs {
const stack = readStackOutputs(stackName, cwd);
const path = stateFilePath(stackName, cwd);
const deploy = `Run \`hyperframes lambda deploy${stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${stackName}`}\``;
if (!stack) {
const known = listStackNames(cwd);
let hint = `Run \`hyperframes lambda deploy${stackName === DEFAULT_STACK_NAME ? "" : ` --stack-name=${stackName}`}\` first.`;
if (known.length) {
hint += ` Known stacks here: ${known.join(", ")}.`;
}
const hint = known.length ? ` Known stacks here: ${known.join(", ")}.` : "";
console.error(
`[hyperframes lambda] no stack state for "${stackName}" at ${stateFilePath(stackName, cwd)}. ${hint}`,
`[hyperframes lambda] no stack state for "${stackName}" at ${path}. ${deploy} first.${hint}`,
);
failCommand();
}
if (!sameFileOnCaseInsensitiveDisk(String(stack.stackName), stackName)) {
console.error(
`[hyperframes lambda] ${path} names stack "${stack.stackName}", not "${stackName}". ${deploy} to rewrite it.`,
);
failCommand();
}
@@ -10,7 +10,7 @@ import { defaultDeps, fetchPinned, type StageDeps } from "./prebuiltHandler.js";
export type VideoArch = "x86_64" | "arm64";
/** ECR repository names must be lowercase; stack names need not be. */
function videoRepositoryName(stackName: string): string {
export function videoRepositoryName(stackName: string): string {
return `${stackName.toLowerCase()}-video`;
}