Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions packages/void/src/plugin-cloudflare-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,11 @@ export function defaultCloudflareWorkerName(root: string): string {
}

/** Translate Void's Wrangler-shaped settings to the configuration that the Cloudflare plugin takes. */
export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): CloudflareConfig {
export function toNativeCloudflareConfig(
raw: WorkerConfig,
root: string,
command: 'build' | 'serve' = 'build',
): CloudflareConfig {
const name = defaultCloudflareWorkerName(root);
const { env, vars, ...base } = raw;
const selected = process.env.CLOUDFLARE_ENV ? env?.[process.env.CLOUDFLARE_ENV] : undefined;
Expand Down Expand Up @@ -144,7 +148,12 @@ export function toNativeCloudflareConfig(raw: WorkerConfig, root: string): Cloud
// `vars` was left out of the translation above; add the values here.
for (const [name, value] of Object.entries(values ?? {})) {
config.worker.env ??= {};
if (Object.hasOwn(config.worker.env, name)) {
// Local env values supply required secrets in dev. Builds and deploys still
// reject every collision, and local vars must never replace resource bindings.
if (
Object.hasOwn(config.worker.env, name) &&
(command !== 'serve' || config.worker.env[name].type !== 'secret')
) {
throw new Error(`Worker var ${name} conflicts with a Cloudflare binding of the same name.`);
}
config.worker.env[name] =
Expand Down
4 changes: 2 additions & 2 deletions packages/void/src/plugin-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ export function cloudflare(options: {
);
}
const original = base;
base = convertToWranglerConfig(toNativeCloudflareConfig(base, root));
base = convertToWranglerConfig(toNativeCloudflareConfig(base, root, environment.command));
base.main = selected.main ?? original.main;
base.migrations = selected.migrations ?? original.migrations;
base.assets = {
Expand All @@ -99,7 +99,7 @@ export function cloudflare(options: {
};
}
workerConfig = mergeCloudflareConfig(options.config(base), base);
native = toNativeCloudflareConfig(workerConfig, root);
native = toNativeCloudflareConfig(workerConfig, root, environment.command);
pluginNative = structuredClone(native);
if (environment.command === 'build' && (native.containers?.length ?? 0) > 0) {
// Void builds images during deployment preparation. Managed builds consume
Expand Down
112 changes: 112 additions & 0 deletions packages/void/test/integration/env-dev.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { readBuildOutput } from '@cloudflare/build-output-utils';
import { createBuilder, createServer, preview } from 'vite';
import type { InlineConfig } from 'vite';
import { afterEach, describe, expect, it, vi } from 'vite-plus/test';
import { createPackageFixtureDir } from '../../../../test/integration-helpers.ts';
import { voidPlugin } from '../../src/index.ts';

const roots: Array<string> = [];

afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllEnvs();
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true });
}
});

function createApp(dotenv?: string): string {
vi.stubEnv('VOID_INSPECTOR_PORT', 'false');
const packageRoot = join(import.meta.dirname, '../..');
const root = createPackageFixtureDir(packageRoot, 'void-env-dev-');
roots.push(root);
writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' }));
mkdirSync(join(root, 'node_modules'));
symlinkSync(packageRoot, join(root, 'node_modules/void'), 'junction');
writeFileSync(
join(root, 'void.config.ts'),
`import { defineConfig } from 'void/config';
export default defineConfig({ worker: { compatibility_date: '2026-11-01' } });`,
);
writeFileSync(
join(root, 'env.ts'),
`import { defineEnv, string } from 'void/env';
export default defineEnv({
LINK_SECRET: string(),
PUBLIC_URL: string().default('https://default.example.com'),
});`,
);
if (dotenv !== undefined) {
writeFileSync(join(root, '.env'), `LINK_SECRET=${dotenv}\n`);
}
mkdirSync(join(root, 'routes'));
writeFileSync(
join(root, 'routes/index.ts'),
`import { env } from 'void/env';
export const GET = () => ({ secret: env.LINK_SECRET, url: env.PUBLIC_URL });`,
);
vi.spyOn(process, 'cwd').mockReturnValue(root);
return root;
}

function config(root: string): InlineConfig {
return { root, configFile: false, logLevel: 'silent', plugins: [voidPlugin()] };
}

describe('required server env values', () => {
it.each([
['dotenv', 'local-secret', undefined, 'local-secret'],
['shell overriding dotenv', 'local-secret', 'shell-secret', 'shell-secret'],
['shell only', undefined, 'shell-secret', 'shell-secret'],
])('serves the %s value in development', async (_source, dotenv, shell, expected) => {
vi.stubEnv('LINK_SECRET', shell);
const root = createApp(dotenv);
const server = await createServer({
...config(root),
server: { host: '127.0.0.1', port: 0 },
});
try {
await server.listen();
const response = await fetch(server.resolvedUrls!.local[0]);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
secret: expected,
url: 'https://default.example.com',
});
} finally {
await server.close();
}
});

it('keeps production secrets opaque and supplies local values only to preview', async () => {
vi.stubEnv('LINK_SECRET', undefined);
const root = createApp('local-secret');
// A development-mode build is still a build; Vite's mode must not allow secret overrides.
await (await createBuilder({ ...config(root), mode: 'development' }, null)).buildApp();
const output = await readBuildOutput(root);
const worker = output.workers.default;
expect(worker.config.env?.LINK_SECRET).toEqual({ type: 'secret' });
const paths = [worker.configPath, join(root, 'dist/ssr/wrangler.json')];
const builtConfigs = paths.map((path) => readFileSync(path, 'utf8'));
for (const text of builtConfigs) {
expect(text).not.toContain('local-secret');
}
const server = await preview({
...config(root),
preview: { host: '127.0.0.1', port: 0 },
});
try {
const response = await fetch(server.resolvedUrls!.local[0]);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
secret: 'local-secret',
url: 'https://default.example.com',
});
expect(paths.map((path) => readFileSync(path, 'utf8'))).toEqual(builtConfigs);
} finally {
await server.close();
}
});
});
33 changes: 33 additions & 0 deletions packages/void/test/integration/plugin-cloudflare-v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,39 @@ describe('Cloudflare v2 compatibility', () => {
).toThrow(`Worker var ${name} conflicts with a Cloudflare binding of the same name.`);
});

it('lets local vars supply required secrets only in development', async () => {
const root = project();
const raw = {
name: 'app',
main: 'virtual:entry',
vars: { TOKEN: 'local-only' },
secrets: { required: ['TOKEN', 'OTHER_SECRET'] },
};
expect(toNativeCloudflareConfig(raw, root, 'serve').worker.env).toMatchObject({
TOKEN: { type: 'text', value: 'local-only' },
OTHER_SECRET: { type: 'secret' },
});
expect(() =>
toNativeCloudflareConfig(
{ vars: { CACHE: 'local-only' }, kv_namespaces: [{ binding: 'CACHE', id: 'cache' }] },
root,
'serve',
),
).toThrow('Worker var CACHE conflicts with a Cloudflare binding of the same name.');

await expect(
resolveConfig(
{
root,
configFile: false,
mode: 'development',
plugins: cloudflare({ config: () => raw, viteEnvironment: { name: 'ssr' } }),
},
'build',
),
).rejects.toThrow('Worker var TOKEN conflicts with a Cloudflare binding of the same name.');
});

it('selects named environments explicitly without letting production mode select one', () => {
const root = project();
expect(toNativeCloudflareConfig({}, root).worker?.name).toBe('void-cf-v2');
Expand Down