Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

ci(deps): enforce devcontainer cooldown before merge (#1517)

mldangelo-oai894c2531bf81
diff --git a/.github/workflows/node-ci.yml b/.github/workflows/node-ci.yml
index 1768bc2e0..3b3e5811e 100644
--- a/.github/workflows/node-ci.yml
+++ b/.github/workflows/node-ci.yml
@@ -113,6 +113,9 @@ jobs:
needs: validate-title
runs-on: ubuntu-latest
timeout-minutes: 20
+ permissions:
+ contents: read
+ packages: read
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -131,6 +134,10 @@ jobs:
run: |
pnpm --dir sdk/typescript install --frozen-lockfile
pnpm --dir plugins/codex-security/mcp-app install --frozen-lockfile
+ - name: Check devcontainer dependency cooldown
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: node --experimental-strip-types sdk/typescript/scripts/check-devcontainer-cooldown.mts
- name: Typecheck
run: pnpm --dir sdk/typescript run types
- name: Check formatting
diff --git a/.github/workflows/test-quality.yml b/.github/workflows/test-quality.yml
index a6429b98c..9e92ca74a 100644
--- a/.github/workflows/test-quality.yml
+++ b/.github/workflows/test-quality.yml
@@ -32,7 +32,7 @@ jobs:
if: ${{ !cancelled() && (inputs.native-artifacts-ready || needs.native.result == 'success') }}
name: ${{ matrix.os }} / ${{ matrix.mode }}
runs-on: ${{ matrix.os }}
- timeout-minutes: ${{ matrix.os == 'windows-latest' && (matrix.mode == 'baseline' && 60 || matrix.mode == 'parallel' && 45) || 30 }}
+ timeout-minutes: ${{ matrix.os == 'windows-latest' && (matrix.mode == 'baseline' && 90 || matrix.mode == 'parallel' && 60) || 30 }}
env:
CODEX_SECURITY_PROPERTY_SEED: ${{ github.event_name == 'pull_request' && 1 || github.run_number }}
strategy:
diff --git a/AGENTS.md b/AGENTS.md
index 76321d0fc..0fe76e32d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -104,6 +104,10 @@ variables, and defaults as public API.
unresolved work. Do not create new label taxonomies or bulk-edit labels on
other PRs unless the user asks.
+## Dependency cooldowns
+
+Apply the cooldowns and exclusions in `.github/dependabot.yml` before merging manual or bot dependency upgrades. Devcontainer upgrades must pass the CI publication-age check; missing publication metadata does not make a version eligible. Dependabot can still open an early PR when a feature omits its publication timestamp, so wait for the reported eligibility time and rerun CI before merging.
+
## Public repository and pull requests
Everything published in this repository is public. Review branch names before
diff --git a/sdk/typescript/package.json b/sdk/typescript/package.json
index 13e6d33af..ffa54e155 100644
--- a/sdk/typescript/package.json
+++ b/sdk/typescript/package.json
@@ -110,6 +110,7 @@
"fast-check": "4.10.2",
"ink-testing-library": "4.0.0",
"json-schema-to-typescript": "16.0.0",
+ "json5": "2.2.3",
"katex": "0.19.0",
"minimatch": "10.2.6",
"postcss": "8.5.28",
diff --git a/sdk/typescript/pnpm-lock.yaml b/sdk/typescript/pnpm-lock.yaml
index e937c526a..0a87da5d1 100644
--- a/sdk/typescript/pnpm-lock.yaml
+++ b/sdk/typescript/pnpm-lock.yaml
@@ -116,6 +116,9 @@ importers:
json-schema-to-typescript:
specifier: 16.0.0
version: 16.0.0
+ json5:
+ specifier: 2.2.3
+ version: 2.2.3
katex:
specifier: 0.19.0
version: 0.19.0
diff --git a/sdk/typescript/scripts/check-devcontainer-cooldown.mts b/sdk/typescript/scripts/check-devcontainer-cooldown.mts
new file mode 100644
index 000000000..eb2301ddd
--- /dev/null
+++ b/sdk/typescript/scripts/check-devcontainer-cooldown.mts
@@ -0,0 +1,242 @@
+import { execFileSync } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import JSON5 from "json5";
+import { parse } from "yaml";
+import { isMain } from "./is-main.mjs";
+
+const configurationDirectories = [".devcontainer", ".ona"];
+const policyPath = ".github/dependabot.yml";
+const guardPaths = new Set([
+ policyPath,
+ ...configurationDirectories.map(
+ (directory) => `${directory}/devcontainer.json`,
+ ),
+ ".github/workflows/node-ci.yml",
+ "sdk/typescript/scripts/check-devcontainer-cooldown.mts",
+]);
+
+type Feature = { version: string; resolved: string; integrity: string };
+type Lockfile = { features: Record<string, Feature> };
+type PackageVersion = { name: string; created_at?: string };
+type Request = (url: string, init: RequestInit) => Promise<Response>;
+
+export function configuredFeatures(source: string): string[] {
+ const manifest = JSON5.parse(source) as {
+ features?: Record<string, unknown>;
+ };
+ return Object.keys(manifest.features ?? {}).filter(
+ (name) =>
+ !name.startsWith("./") &&
+ !name.startsWith("../") &&
+ !name.startsWith("/"),
+ );
+}
+
+function featurePackage(name: string, feature: Feature) {
+ const match =
+ /^(ghcr\.io\/([^/]+)\/([^:@]+))(?::[^/@]+|@(sha256:[a-f0-9]{64}))?$/.exec(
+ name,
+ );
+ if (!match)
+ throw new Error(
+ `Cannot verify publication time for ${name}: expected a GitHub Container Registry feature.`,
+ );
+ const [, resource, owner, packageName, sourceDigest] = match;
+ if (
+ !/^sha256:[a-f0-9]{64}$/.test(feature.integrity) ||
+ feature.resolved !== `${resource}@${feature.integrity}` ||
+ (sourceDigest !== undefined && sourceDigest !== feature.integrity)
+ ) {
+ throw new Error(
+ `${name}: lockfile resolved and integrity must identify the configured feature's same immutable digest.`,
+ );
+ }
+ return { owner: owner!, name: packageName!, digest: feature.integrity };
+}
+
+export function cooldownDays(source: string): number {
+ const policy = parse(source) as {
+ updates: Array<{
+ "package-ecosystem": string;
+ cooldown?: { "default-days"?: number };
+ }>;
+ };
+ const days = policy.updates.find(
+ (update) => update["package-ecosystem"] === "devcontainers",
+ )?.cooldown?.["default-days"];
+ if (days === undefined || !Number.isInteger(days) || days < 0) {
+ throw new Error(
+ "The devcontainers policy must specify cooldown.default-days.",
+ );
+ }
+ return days;
+}
+
+export function featuresToCheck(
+ previous: Lockfile,
+ current: Lockfile,
+ configured: readonly string[],
+ changedPaths: readonly string[],
+): Array<[string, Feature]> {
+ const all = changedPaths.some((path) => guardPaths.has(path));
+ const selected: Array<[string, Feature]> = [];
+ for (const name of configured) {
+ const feature = current.features[name];
+ if (!feature)
+ throw new Error(
+ `${name}: the configured feature needs a matching lockfile entry before its cooldown can be verified.`,
+ );
+ featurePackage(name, feature);
+ if (all || previous.features[name]?.integrity !== feature.integrity)
+ selected.push([name, feature]);
+ }
+ return selected;
+}
+
+export async function configuredFeatureChanges(
+ root: string,
+ days: number,
+ previousLock: (path: string) => Lockfile,
+ changedPaths: readonly string[],
+): Promise<
+ Array<{ manifestPath: string; features: Array<[string, Feature]> }>
+> {
+ const changes: Array<{
+ manifestPath: string;
+ features: Array<[string, Feature]>;
+ }> = [];
+ if (days === 0) return changes;
+ for (const directory of configurationDirectories) {
+ const manifestPath = `${directory}/devcontainer.json`;
+ const lockPath = `${directory}/devcontainer-lock.json`;
+ const current: Lockfile = await readFile(join(root, lockPath), "utf8")
+ .then((source) => JSON.parse(source))
+ .catch((error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return { features: {} };
+ throw error;
+ });
+ const source = await readFile(join(root, manifestPath), "utf8").catch(
+ (error: NodeJS.ErrnoException) => {
+ if (error.code === "ENOENT") return "{}";
+ throw error;
+ },
+ );
+ const features = featuresToCheck(
+ previousLock(lockPath),
+ current,
+ configuredFeatures(source),
+ changedPaths,
+ );
+ if (features.length > 0) changes.push({ manifestPath, features });
+ }
+ return changes;
+}
+
+export async function publicationTime(
+ name: string,
+ feature: Feature,
+ token: string,
+ request: Request = fetch,
+): Promise<Date> {
+ const { owner, name: packageName, digest } = featurePackage(name, feature);
+ const endpoint = `https://api.github.com/orgs/${encodeURIComponent(owner)}/packages/container/${encodeURIComponent(packageName)}/versions`;
+ for (let page = 1; ; page++) {
+ const response = await request(`${endpoint}?per_page=100&page=${page}`, {
+ headers: {
+ Accept: "application/vnd.github+json",
+ Authorization: `Bearer ${token}`,
+ "X-GitHub-Api-Version": "2022-11-28",
+ },
+ });
+ if (!response.ok) {
+ throw new Error(
+ `Cannot verify publication time for ${feature.resolved}: GitHub Packages returned HTTP ${response.status}: ${await response.text()}`,
+ );
+ }
+ const versions = (await response.json()) as PackageVersion[];
+ const version = versions.find((candidate) => candidate.name === digest);
+ if (version) {
+ const created = Date.parse(version.created_at ?? "");
+ if (!Number.isFinite(created)) {
+ throw new Error(
+ `Cannot verify publication time for ${feature.resolved}: the matching package version has no valid created_at timestamp.`,
+ );
+ }
+ return new Date(created);
+ }
+ if (!response.headers.get("link")?.includes('rel="next"')) break;
+ }
+ throw new Error(
+ `Cannot verify publication time for ${feature.resolved}: GitHub Packages did not return the exact digest.`,
+ );
+}
+
+export async function checkCooldown(
+ features: ReadonlyArray<readonly [string, Feature]>,
+ days: number,
+ publishedAt: (name: string, feature: Feature) => Promise<Date>,
+ now = new Date(),
+): Promise<string[]> {
+ const messages: string[] = [];
+ if (days === 0) return messages;
+ for (const [name, feature] of features) {
+ const published = await publishedAt(name, feature);
+ const eligible = new Date(published.getTime() + days * 86_400_000);
+ if (now < eligible) {
+ throw new Error(
+ `${name} (${feature.version}) was published at ${published.toISOString()}; its ${days}-day cooldown ends at ${eligible.toISOString()}. Rerun CI after that time.`,
+ );
+ }
+ messages.push(
+ `${name} (${feature.version}): published ${published.toISOString()}, eligible since ${eligible.toISOString()}.`,
+ );
+ }
+ return messages;
+}
+
+if (isMain(import.meta.url)) {
+ const root = fileURLToPath(new URL("../../../", import.meta.url));
+ const git = (...args: string[]) =>
+ execFileSync("git", ["-c", "core.fsmonitor=false", ...args], {
+ cwd: root,
+ encoding: "utf8",
+ });
+ try {
+ const paths = git("diff", "--name-only", "HEAD^1", "HEAD")
+ .trim()
+ .split("\n");
+ const days = cooldownDays(await readFile(join(root, policyPath), "utf8"));
+ const changes = await configuredFeatureChanges(
+ root,
+ days,
+ (lockPath) =>
+ git("ls-tree", "--name-only", "HEAD^1", "--", lockPath).trim()
+ ? JSON.parse(git("show", `HEAD^1:${lockPath}`))
+ : { features: {} },
+ paths,
+ );
+ if (changes.length === 0) {
+ console.log("No devcontainer feature digests need a cooldown check.");
+ } else {
+ const token = process.env["GH_TOKEN"];
+ if (!token)
+ throw new Error(
+ "GH_TOKEN with packages:read is required for the devcontainer cooldown check.",
+ );
+ for (const { manifestPath, features } of changes) {
+ for (const message of await checkCooldown(
+ features,
+ days,
+ (name, feature) => publicationTime(name, feature, token),
+ )) {
+ console.log(`${manifestPath}: ${message}`);
+ }
+ }
+ }
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : error);
+ process.exitCode = 1;
+ }
+}
diff --git a/sdk/typescript/tests-ts/api.test.ts b/sdk/typescript/tests-ts/api.test.ts
index b996c9ae3..30aa60a85 100644
--- a/sdk/typescript/tests-ts/api.test.ts
+++ b/sdk/typescript/tests-ts/api.test.ts
@@ -2228,7 +2228,7 @@ describe("CodexSecurity orchestration", () => {
);
test.each([false, true])(
- "archives accepted output before starting, cancellation=%s",
+ "archives accepted output before starting, cancellation=%j",
async (cancelRegistration) => {
const root = await temporaryDirectory();
const repository = join(root, "repository");
@@ -2496,7 +2496,22 @@ describe("CodexSecurity orchestration", () => {
expect(
await readFile(join(root, "registration-input.json"), "utf8"),
).toBe(submitted!);
- const closed = once(socket, "close", { signal: deadline });
+ // Terminating the paused child can reset its socket on Windows.
+ // Still wait for close, and retain unexpected errors and the deadline.
+ const closed = new Promise<void>((resolve, reject) => {
+ const onError = (error: NodeJS.ErrnoException) => {
+ if (error.code !== "ECONNRESET") reject(error);
+ };
+ const onAbort = () => reject(deadline.reason);
+ socket!.once("error", onError);
+ socket!.once("close", () => {
+ socket!.removeListener("error", onError);
+ deadline.removeEventListener("abort", onAbort);
+ resolve();
+ });
+ if (deadline.aborted) onAbort();
+ else deadline.addEventListener("abort", onAbort, { once: true });
+ });
if (cancel === "close") closing = client.close();
else controller.abort();
if (boundary === "commit" || boundary === "rollback") {
diff --git a/sdk/typescript/tests-ts/cli.test.ts b/sdk/typescript/tests-ts/cli.test.ts
index 0981cf19a..f3fb62dd0 100644
--- a/sdk/typescript/tests-ts/cli.test.ts
+++ b/sdk/typescript/tests-ts/cli.test.ts
@@ -2097,7 +2097,7 @@ describe("CLI", () => {
});
test.each([false, true])(
- "shows durable Deep progress without changing stdout or TUI layout (interactive=%s)",
+ "shows durable Deep progress without changing stdout or TUI layout (interactive=%j)",
async (interactive) => {
const { stdout, stderr, runCli } = createCliTest(main, {
stderr: interactive,
diff --git a/sdk/typescript/tests-ts/cost.test.ts b/sdk/typescript/tests-ts/cost.test.ts
index 49044739a..21fd5f44f 100644
--- a/sdk/typescript/tests-ts/cost.test.ts
+++ b/sdk/typescript/tests-ts/cost.test.ts
@@ -819,7 +819,7 @@ describe("live scan cost tracking", () => {
["EPERM", true],
["EPERM", false],
] as const)(
- "retains and retries a %s worker when its parent appears later (already identified: %s)",
+ "retains and retries a %s worker when its parent appears later (already identified: %j)",
async (code, identified) => {
const home = await codexHome();
const usage = (input_tokens: number) => ({
diff --git a/sdk/typescript/tests-ts/devcontainer-cooldown.test.ts b/sdk/typescript/tests-ts/devcontainer-cooldown.test.ts
new file mode 100644
index 000000000..e7a9a50b4
--- /dev/null
+++ b/sdk/typescript/tests-ts/devcontainer-cooldown.test.ts
@@ -0,0 +1,377 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, test } from "bun:test";
+import { parse } from "yaml";
+import {
+ checkCooldown,
+ cooldownDays,
+ configuredFeatureChanges,
+ configuredFeatures,
+ featuresToCheck,
+ publicationTime,
+} from "../scripts/check-devcontainer-cooldown.mts";
+
+const digest = `sha256:${"a".repeat(64)}`;
+const oldDigest = `sha256:${"b".repeat(64)}`;
+const name = "ghcr.io/example/features/node:2";
+const feature = {
+ version: "2.1.1",
+ resolved: `ghcr.io/example/features/node@${digest}`,
+ integrity: digest,
+};
+const previous = {
+ features: {
+ [name]: {
+ version: "2.1.0",
+ resolved: `ghcr.io/example/features/node@${oldDigest}`,
+ integrity: oldDigest,
+ },
+ },
+};
+const current = { features: { [name]: feature } };
+const published = new Date("2026-01-01T12:00:00.000Z");
+const fixtureRoots = new Set<string>();
+
+afterEach(async () => {
+ await Promise.all(
+ [...fixtureRoots].map((root) => rm(root, { recursive: true, force: true })),
+ );
+ fixtureRoots.clear();
+});
+
+async function configurationFixture(ona = previous) {
+ const root = await mkdtemp(join(tmpdir(), "devcontainer-cooldown-"));
+ fixtureRoots.add(root);
+ for (const [directory, lock] of [
+ [".devcontainer", previous],
+ [".ona", ona],
+ ] as const) {
+ await mkdir(join(root, directory));
+ await writeFile(
+ join(root, directory, "devcontainer.json"),
+ JSON.stringify({ features: { [name]: {} } }),
+ );
+ await writeFile(
+ join(root, directory, "devcontainer-lock.json"),
+ JSON.stringify(lock),
+ );
+ }
+ return root;
+}
+
+test("rejects a young Ona-only feature update while leaving unchanged root pins unselected", async () => {
+ const root = await configurationFixture(current);
+ const changes = await configuredFeatureChanges(root, 7, () => previous, [
+ ".ona/devcontainer-lock.json",
+ ]);
+ expect(changes).toEqual([
+ { manifestPath: ".ona/devcontainer.json", features: [[name, feature]] },
+ ]);
+ await expect(
+ checkCooldown(
+ changes[0]!.features,
+ 7,
+ async () => published,
+ new Date("2026-01-02T12:00:00.000Z"),
+ ),
+ ).rejects.toThrow("2026-01-08T12:00:00.000Z");
+});
+
+test("requires the adjacent Ona lockfile for its configured features", async () => {
+ const root = await configurationFixture();
+ await rm(join(root, ".ona/devcontainer-lock.json"));
+ await expect(
+ configuredFeatureChanges(root, 7, () => previous, [
+ ".ona/devcontainer-lock.json",
+ ]),
+ ).rejects.toThrow("matching lockfile entry");
+});
+
+test("rejects an Ona manifest-only tag change without matching lock coverage", async () => {
+ const root = await configurationFixture();
+ await writeFile(
+ join(root, ".ona/devcontainer.json"),
+ JSON.stringify({ features: { "ghcr.io/example/features/node:3": {} } }),
+ );
+ await expect(
+ configuredFeatureChanges(root, 7, () => previous, [
+ ".ona/devcontainer.json",
+ ]),
+ ).rejects.toThrow("matching lockfile entry");
+});
+
+test("binds Ona's resolved resource to its effective integrity digest", async () => {
+ const root = await configurationFixture({
+ features: { [name]: { ...feature, integrity: oldDigest } },
+ });
+ await expect(
+ configuredFeatureChanges(root, 7, () => previous, [
+ ".ona/devcontainer-lock.json",
+ ]),
+ ).rejects.toThrow("same immutable digest");
+});
+
+test("skips unchanged pins in both active configurations", async () => {
+ const root = await configurationFixture();
+ expect(
+ await configuredFeatureChanges(root, 7, () => previous, ["README.md"]),
+ ).toEqual([]);
+});
+
+test("disabled cooldown skips both configurations and previous-lock lookup", async () => {
+ const root = await configurationFixture();
+ await rm(join(root, ".ona/devcontainer-lock.json"));
+ expect(
+ await configuredFeatureChanges(
+ root,
+ 0,
+ () => {
+ throw new Error("unexpected previous-lock lookup");
+ },
+ [".ona/devcontainer-lock.json"],
+ ),
+ ).toEqual([]);
+});
+
+test("policy changes select the current pins from both active configurations", async () => {
+ const root = await configurationFixture();
+ const changes = await configuredFeatureChanges(root, 7, () => previous, [
+ ".github/dependabot.yml",
+ ]);
+ expect(changes).toEqual([
+ {
+ manifestPath: ".devcontainer/devcontainer.json",
+ features: [[name, previous.features[name]]],
+ },
+ {
+ manifestPath: ".ona/devcontainer.json",
+ features: [[name, previous.features[name]]],
+ },
+ ]);
+});
+
+test("reads configured features from JSONC while excluding local source directories", () => {
+ expect(
+ configuredFeatures(`{
+ // Feature options and trailing commas are valid devcontainer configuration.
+ "features": { "${name}": {}, "./local-feature": {}, },
+ }`),
+ ).toEqual([name]);
+});
+
+test("rejects manifest-only tag changes and missing lock entries instead of using unpinned tags", () => {
+ expect(() =>
+ featuresToCheck(previous, current, ["ghcr.io/example/features/node:3"], []),
+ ).toThrow("matching lockfile entry");
+ expect(() => featuresToCheck(previous, { features: {} }, [name], [])).toThrow(
+ "matching lockfile entry",
+ );
+ expect(featuresToCheck(previous, current, [], [])).toEqual([]);
+});
+
+test("checks the effective integrity and requires the resolved resource to match the configured feature", () => {
+ const changed = {
+ features: { [name]: { ...feature, integrity: oldDigest } },
+ };
+ expect(() => featuresToCheck(current, changed, [name], [])).toThrow(
+ "same immutable digest",
+ );
+ const unrelated = {
+ features: {
+ [name]: { ...feature, resolved: `ghcr.io/other/unrelated@${digest}` },
+ },
+ };
+ expect(() => featuresToCheck(current, unrelated, [name], [])).toThrow(
+ "same immutable digest",
+ );
+});
+
+test("uses the configured devcontainer cooldown rather than another ecosystem or a hardcoded value", () => {
+ expect(
+ cooldownDays(`updates:
+ - package-ecosystem: npm
+ cooldown:
+ default-days: 10
+ - package-ecosystem: devcontainers
+ cooldown:
+ default-days: 7
+`),
+ ).toBe(7);
+ expect(
+ cooldownDays(`updates:
+ - package-ecosystem: devcontainers
+ cooldown:
+ default-days: 3
+`),
+ ).toBe(3);
+ expect(() => cooldownDays("updates: []")).toThrow("cooldown.default-days");
+});
+
+test("checks new and changed digests, including rollback pins, and skips unchanged or deleted entries", () => {
+ expect(featuresToCheck(previous, current, [name], [])).toEqual([
+ [name, feature],
+ ]);
+ expect(featuresToCheck({ features: {} }, current, [name], [])).toEqual([
+ [name, feature],
+ ]);
+ expect(featuresToCheck(current, previous, [name], [])).toEqual([
+ [name, previous.features[name]],
+ ]);
+ expect(featuresToCheck(current, current, [name], [])).toEqual([]);
+ expect(featuresToCheck(current, { features: {} }, [], [])).toEqual([]);
+});
+
+test.each([
+ ".github/dependabot.yml",
+ ".devcontainer/devcontainer.json",
+ ".ona/devcontainer.json",
+ ".github/workflows/node-ci.yml",
+ "sdk/typescript/scripts/check-devcontainer-cooldown.mts",
+])("validates existing pins when %s changes", (path) => {
+ expect(featuresToCheck(current, current, [name], [path])).toEqual([
+ [name, feature],
+ ]);
+});
+
+test("allows the exact seven-day boundary and reports when a younger digest becomes eligible", async () => {
+ const eligible = new Date("2026-01-08T12:00:00.000Z");
+ const read = async () => published;
+ await expect(
+ checkCooldown([[name, feature]], 7, read, eligible),
+ ).resolves.toHaveLength(1);
+ await expect(
+ checkCooldown([[name, feature]], 7, read, new Date(eligible.getTime() - 1)),
+ ).rejects.toThrow("2026-01-08T12:00:00.000Z");
+ await expect(
+ checkCooldown([[name, feature]], 7, read, new Date("2026-01-10T00:00:00Z")),
+ ).resolves.toHaveLength(1);
+ await expect(
+ checkCooldown([], 7, async () => {
+ throw new Error("unexpected lookup");
+ }),
+ ).resolves.toEqual([]);
+});
+
+test("does not fetch publication metadata when the configured cooldown is disabled", async () => {
+ await expect(
+ checkCooldown([[name, feature]], 0, async () => {
+ throw new Error("unexpected lookup");
+ }),
+ ).resolves.toEqual([]);
+});
+
+test("finds the exact immutable digest across GitHub Packages pages", async () => {
+ const requests: string[] = [];
+ const result = await publicationTime(
+ name,
+ feature,
+ "synthetic-package-token",
+ async (url, init) => {
+ requests.push(url);
+ expect(new Headers(init.headers).get("Authorization")).toBe(
+ "Bearer synthetic-package-token",
+ );
+ if (requests.length === 1) {
+ return Response.json(
+ [
+ {
+ name: oldDigest,
+ created_at: "2020-01-01T00:00:00Z",
+ metadata: { container: { tags: [feature.version] } },
+ },
+ ],
+ {
+ headers: {
+ link: '<https://api.github.com/packages?page=2>; rel="next"',
+ },
+ },
+ );
+ }
+ return Response.json([
+ { name: digest, created_at: published.toISOString() },
+ ]);
+ },
+ );
+ expect(result).toEqual(published);
+ expect(requests).toEqual([
+ "https://api.github.com/orgs/example/packages/container/features%2Fnode/versions?per_page=100&page=1",
+ "https://api.github.com/orgs/example/packages/container/features%2Fnode/versions?per_page=100&page=2",
+ ]);
+});
+
+test.each([undefined, "", "not a timestamp"])(
+ "rejects a matching version with publication time %s",
+ async (created_at) => {
+ await expect(
+ publicationTime(name, feature, "synthetic-package-token", async () =>
+ Response.json([{ name: digest, created_at }]),
+ ),
+ ).rejects.toThrow("no valid created_at");
+ },
+);
+
+test("does not substitute a tagged version for an unavailable digest or hide API errors", async () => {
+ await expect(
+ publicationTime(name, feature, "synthetic-package-token", async () =>
+ Response.json([{ name: oldDigest, created_at: published.toISOString() }]),
+ ),
+ ).rejects.toThrow("exact digest");
+ await expect(
+ publicationTime(
+ name,
+ feature,
+ "synthetic-package-token",
+ async () =>
+ new Response("read:packages permission is required", { status: 403 }),
+ ),
+ ).rejects.toThrow("HTTP 403: read:packages permission is required");
+});
+
+test("runs the guard with package metadata access inside the existing required checks", async () => {
+ const workflow = parse(
+ await readFile(
+ new URL("../../../.github/workflows/node-ci.yml", import.meta.url),
+ "utf8",
+ ),
+ ) as {
+ jobs: Record<
+ string,
+ {
+ permissions?: Record<string, string>;
+ needs?: string[];
+ steps: Array<{
+ name?: string;
+ if?: string;
+ run?: string;
+ env?: Record<string, string>;
+ with?: Record<string, unknown>;
+ }>;
+ }
+ >;
+ };
+ const job = workflow.jobs["static-checks"]!;
+ const index = job.steps.findIndex(
+ (step) => step.name === "Check devcontainer dependency cooldown",
+ );
+ expect(index).toBeGreaterThan(
+ job.steps.findIndex((step) => step.name === "Install dependencies"),
+ );
+ expect(job.steps[index]!.run).toContain(
+ "sdk/typescript/scripts/check-devcontainer-cooldown.mts",
+ );
+ expect(job.steps[index]!.env).toEqual({ GH_TOKEN: "${{ github.token }}" });
+ expect(job.permissions).toEqual({ contents: "read", packages: "read" });
+ expect(job.steps[0]!.with?.["fetch-depth"]).toBe(2);
+ for (const name of ["required-test", "windows"]) {
+ const required = workflow.jobs[name]!;
+ expect(required.needs).toContain("static-checks");
+ expect(
+ required.steps.some(
+ (step) =>
+ step.run === "exit 1" &&
+ step.if?.includes("needs.static-checks.result != 'success'"),
+ ),
+ ).toBe(true);
+ }
+});