Skip to content
Closed
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
2 changes: 1 addition & 1 deletion docs/integrations/cloudflare.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ ISR uses the shared cache protocol. Entries are scoped to a deployment and hostn

With Cloudflare selected, `void secret`, `void domain`, `void project status|list|logs|rollback`, and remote `void db` commands use the saved Worker and account. Database commands operate on the selected D1 database. Logs are a live tail; Void doesn't provide hosted log history for direct deploys.

Custom domain changes update routes immediately without rewriting schedules, queues, or workflows. Removing the final custom domain requires `CLOUDFLARE_API_TOKEN` with Workers Scripts: Edit because that operation uses Cloudflare's domain-record API.
Custom domain changes update routes immediately without rewriting schedules, queues, or workflows. Removing the final custom domain uses your browser session from `void cloudflare login` or an API token with Workers Scripts: Edit permission.

`void project delete` doesn't remove direct Cloudflare resources, which may be shared. Review their use and remove them explicitly in Cloudflare.

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -1522,7 +1522,7 @@ Add a custom domain to the saved target. Hosted Void projects print the DNS reco
void domain delete <hostname> [--project <name>]
```

Direct Cloudflare projects apply the change immediately. Deleting the final custom domain requires `CLOUDFLARE_API_TOKEN` with Workers Scripts: Edit permission because the standard trigger operation does not reconcile an empty custom-domain set; Void fails before changing local or remote state when that token is unavailable.
Direct Cloudflare projects apply the change immediately. Deleting the final custom domain uses your browser session from `void cloudflare login` or an API token with Workers Scripts: Edit permission. If Cloudflare rejects the change, Void attempts to restore the previous domain configuration and reports whether recovery succeeded.

Remove a custom domain from the saved target. For Cloudflare, this removes the matching `custom_domain` route and synchronizes triggers. If Cloudflare rejects the update, Void restores the exact previous local config and immediately reapplies it remotely. If that second synchronization also fails, the CLI reports that remote route state may be partial instead of claiming a successful rollback.

Expand Down
18 changes: 13 additions & 5 deletions packages/deploy-cloudflare/src/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,14 @@ async function activateCloudflareVersionWithSecretsFile(
return { ok: false, reason: 'uploader-changed' };
}
const previousVersionId = previous.versionId;
// Activation can succeed before trigger synchronization or the local receipt
// cleanup fails. Once its last recorded candidate owns all live traffic, the
// receipt no longer authorizes any *inactive* successor. The history checks
// below still reject a newer upload from another operation.
const trustedInheritanceVersionIds =
previousVersionId && options.trustedInheritanceVersionIds?.at(-1) === previousVersionId
? []
: options.trustedInheritanceVersionIds;
let inheritanceBaseline: Array<RecentCloudflareVersion> | undefined;
let trustedCandidateChain = false;
if (options.expectedPreviousVersionId !== undefined || options.verifyInheritedSecrets === true) {
Expand All @@ -848,22 +856,22 @@ async function activateCloudflareVersionWithSecretsFile(
const latestVersionId = recent.at(-1)?.id ?? null;
if (
options.expectedPreviousVersionId !== undefined ||
options.trustedInheritanceVersionIds !== undefined
trustedInheritanceVersionIds !== undefined
) {
const activeIndex = recent.findIndex((version) => version.id === previous.versionId);
const inheritedChain = activeIndex < 0 ? [] : recent.slice(activeIndex);
const inheritedCandidates = inheritedChain.slice(1).map((version) => version.id);
trustedCandidateChain =
options.trustedInheritanceVersionIds !== undefined &&
options.trustedInheritanceVersionIds.length > 0 &&
arraysEqual(inheritedCandidates, options.trustedInheritanceVersionIds);
trustedInheritanceVersionIds !== undefined &&
trustedInheritanceVersionIds.length > 0 &&
arraysEqual(inheritedCandidates, trustedInheritanceVersionIds);
const safeInheritanceChain =
inheritedChain.length > 0 &&
inheritedChain.every(
(version, index) =>
index === 0 || version.number === inheritedChain[index - 1]!.number + 1,
) &&
(arraysEqual(inheritedCandidates, options.trustedInheritanceVersionIds ?? []) ||
(arraysEqual(inheritedCandidates, trustedInheritanceVersionIds ?? []) ||
options.pinActiveSecrets !== undefined);
if (!safeInheritanceChain) {
return {
Expand Down
40 changes: 40 additions & 0 deletions packages/deploy-cloudflare/test/unit/version.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,46 @@ describe('Cloudflare version activation', () => {
).resolves.toMatchObject({ ok: true, versionId: NEXT });
});

it('recovers a receipt whose last candidate already owns production', async () => {
const runWrangler = runner();
const recordVerifiedCandidate = vi.fn();
await expect(
activateCloudflareVersion({
runWrangler,
workerName: 'my-worker',
verifyUploader: () => true,
verifyInheritedSecrets: true,
trustedInheritanceVersionIds: [CONCURRENT, CURRENT],
message: encodeCloudflareVersionMessage([]),
fetch: async () => Response.json({ ready: true }),
recordVerifiedCandidate,
}),
).resolves.toMatchObject({ ok: true, versionId: NEXT, previousVersionId: CURRENT });
expect(recordVerifiedCandidate).toHaveBeenCalledWith(NEXT, CURRENT);
});

it('still rejects a foreign upload after the recorded candidate became active', async () => {
const runWrangler = runner({
versions: ok(
JSON.stringify([
{ id: CURRENT, number: 1 },
{ id: CONCURRENT, number: 2 },
]),
),
});
await expect(
activateCloudflareVersion({
runWrangler,
workerName: 'my-worker',
verifyUploader: () => true,
verifyInheritedSecrets: true,
trustedInheritanceVersionIds: [CURRENT],
message: encodeCloudflareVersionMessage([]),
}),
).resolves.toMatchObject({ ok: false, reason: 'inheritance-source-changed' });
expect(runWrangler.mock.calls.some(([args]) => args[1] === 'upload')).toBe(false);
});

it('does not inherit any remote secret from a failed candidate newer than production', async () => {
const failed = '44444444-4444-4444-8444-444444444444';
const directory = mkdtempSync(join(tmpdir(), 'void-active-secret-inheritance-'));
Expand Down
1 change: 1 addition & 0 deletions packages/void/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@
"@cloudflare/config": "0.20.0",
"@cloudflare/sandbox": "^0.12.9",
"@cloudflare/vite-plugin": "1.54.7",
"@cloudflare/workers-auth": "0.9.4",
"@cloudflare/workers-types": "catalog:",
"@napi-rs/keyring": "2.0.0",
"@void/deploy-cloudflare": "workspace:*",
Expand Down
30 changes: 26 additions & 4 deletions packages/void/src/cli/cf-build-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ const moduleTypes: Record<string, ModuleType> = {
'.cjs': 'cjs',
'.wasm': 'wasm',
'.bin': 'data',
'.woff': 'data',
'.woff2': 'data',
'.ttf': 'data',
'.otf': 'data',
'.eot': 'data',
'.txt': 'text',
'.html': 'text',
'.sql': 'text',
Expand Down Expand Up @@ -92,7 +97,9 @@ function copyBundle(
}
const type = moduleTypes[extname(entry.name).toLowerCase()];
if (!type) {
return null;
throw new Error(
`The built Worker contains an unsupported module ${JSON.stringify(name)}. Emit public assets into the client output or configure the plugin that produced this file to run only in the client environment.`,
);
}
const destinationPath = join(destination, name);
mkdirSync(dirname(destinationPath), { recursive: true });
Expand Down Expand Up @@ -123,9 +130,24 @@ export async function prepareCfBuildOutput(
if (!config.worker) {
throw new Error('cf did not produce a Worker configuration.');
}
const main = raw.main;
if (typeof main !== 'string' || basename(main) !== main || !existsSync(join(source, main))) {
return null;
if (typeof raw.main !== 'string' || !raw.main) {
throw new Error('The built Worker configuration is missing its main entry. Rebuild the app.');
}
const entry = raw.main.replaceAll('\\', '/');
const main = relative(source, resolve(source, entry));
if (
isAbsolute(entry) ||
/^[a-z]:/i.test(entry) ||
!main ||
main === '..' ||
main.startsWith('../')
) {
throw new Error('The built Worker main entry must be inside its output directory.');
}
if (!existsSync(join(source, main))) {
throw new Error(
`The built Worker main entry ${JSON.stringify(main)} is missing. Rebuild the app.`,
);
}

const assets = object(raw.assets);
Expand Down
88 changes: 70 additions & 18 deletions packages/void/src/cli/cf-compat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ import { parse } from 'jsonc-parser';
import { dirname, join, resolve } from 'pathslash';
import { EnvHttpProxyAgent, fetch as httpFetch } from 'undici';
import { prepareCfBuildOutput } from './cf-build-output.ts';
import { persistCfKeyringPreference, readCfSessionCredential } from './cf-session.ts';

type Result = { status: number; stdout: string; stderr: string };
type Json = Record<string, unknown>;

const cf = join(dirname(fileURLToPath(import.meta.resolve('cf/package.json'))), 'bin', 'cf');
const args = process.argv.slice(2);
// This dedicated transport process uses the same encrypted OAuth store for
// login, deployment, and ancillary API calls. API-token overrides still win.
process.env.CLOUDFLARE_AUTH_USE_KEYRING = 'true';

function cfEnvironment(): NodeJS.ProcessEnv {
// The pinned bin otherwise delegates to any cf installed by the project.
Expand Down Expand Up @@ -51,14 +55,9 @@ function result(status: number, stdout = '', stderr = ''): Result {
return { status, stdout, stderr };
}

function runCf(command: Array<string>, cwd = process.cwd(), useLoginProfile = false): Result {
function runCf(command: Array<string>, cwd = process.cwd()): Result {
const env = cfEnvironment();
env.CF_QUIET = '1';
if (useLoginProfile) {
// Void's browser login uses cf's regular profile. Deploy's legacy Wrangler
// keyring pin must not switch the credential source while borrowing it.
delete env.CLOUDFLARE_AUTH_USE_KEYRING;
}
const child = spawnSync(process.execPath, [cf, ...command], {
cwd,
env,
Expand Down Expand Up @@ -290,6 +289,52 @@ async function clearWorkerCronSchedules(worker: string): Promise<Result> {
}
}

async function clearWorkerCustomDomains(worker: string): Promise<Result> {
const base = (
process.env.CLOUDFLARE_API_BASE_URL ?? 'https://api.cloudflare.com/client/v4'
).replace(/\/$/, '');
const endpoint = `${base}/accounts/${encodeURIComponent(accountId())}/workers/scripts/${encodeURIComponent(worker)}/domains/records`;
const proxy =
process.env.HTTP_PROXY ||
process.env.HTTPS_PROXY ||
process.env.http_proxy ||
process.env.https_proxy
? new EnvHttpProxyAgent()
: null;
try {
const response = await httpFetch(endpoint, {
method: 'PUT',
headers: { ...apiHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({
override_scope: true,
override_existing_origin: false,
override_existing_dns_record: false,
origins: [],
}),
redirect: 'error',
signal: AbortSignal.timeout(30_000),
...(proxy ? { dispatcher: proxy } : {}),
});
if (!response.ok) {
throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`);
}
let body: unknown;
try {
body = await response.json();
} catch {
throw new Error(
`Cloudflare returned HTTP ${response.status} with a non-JSON custom-domain response.`,
);
}
if (object(body).success !== true) {
throw new Error(`Cloudflare rejected the empty custom-domain set (HTTP ${response.status}).`);
}
return result(0);
} finally {
await proxy?.close();
}
}

async function assertExistingProvisionableResources(
directory: string,
account: string,
Expand Down Expand Up @@ -405,29 +450,25 @@ function sessionCredential(): { type: 'oauth' | 'api_token'; token: string } | n
if (token) {
return { type: 'api_token', token };
}
const identity = runCf(['auth', 'whoami'], process.cwd(), true);
const identity = runCf(['auth', 'whoami']);
if (identity.status !== 0) {
return null;
}
const state = object(parsedJson(identity.stdout));
if (state.authenticated !== true || state.tokenValid !== true) {
return null;
}
const source = state.authSource;
if (typeof source !== 'string' || !source.startsWith('OAuth token from ')) {
return null;
}
const credential = object(
parsedJson(readFileSync(source.slice('OAuth token from '.length), 'utf8')),
);
return typeof credential.oauth_token === 'string' && credential.oauth_token
? { type: 'oauth', token: credential.oauth_token }
: null;
const credential = readCfSessionCredential(process.cwd(), state);
return credential ? { type: 'oauth', token: credential } : null;
}

function auth(): Result {
if (args[0] === 'login') {
return runInteractiveCf(['auth', 'login', '--force']);
const loggedIn = runInteractiveCf(['auth', 'login', '--force']);
if (loggedIn.status === 0) {
persistCfKeyringPreference(process.cwd());
}
return loggedIn;
}
if (args[0] === 'logout') {
return runCf(['auth', 'logout']);
Expand All @@ -445,6 +486,9 @@ function auth(): Result {
'Cloudflare authentication is required.',
);
}
if (String(identity.authSource).startsWith('OAuth token from ')) {
persistCfKeyringPreference(process.cwd());
}
return result(
0,
JSON.stringify({
Expand Down Expand Up @@ -1029,6 +1073,14 @@ async function workerChanges(): Promise<Result> {
}
return await clearWorkerCronSchedules(name);
}
if (args[0] === 'triggers' && args[1] === 'clear-domains') {
const raw = config();
const name = workerName();
if (raw.name !== name || (raw.account_id !== undefined && raw.account_id !== accountId())) {
throw new Error('Cloudflare trigger target changed.');
}
return await clearWorkerCustomDomains(name);
}
if ((args[0] === 'versions' && args[1] === 'upload') || args[0] === 'deploy') {
const raw = config();
const path = configPath()!;
Expand Down
58 changes: 58 additions & 0 deletions packages/void/src/cli/cf-session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {
createCfAuth,
createCfProfileStore,
setKeyringPreference,
} from '@cloudflare/workers-auth/cf';

const logger = {
debug() {},
info() {},
log() {},
warn() {},
error() {},
};

function session(root: string) {
const auth = createCfAuth({
logger,
userAgent: 'void',
prompt: async () => {
throw new Error('Cloudflare session reads cannot prompt.');
},
select: async () => {
throw new Error('Cloudflare session reads cannot prompt.');
},
isNoDefaultValueProvidedError: () => false,
});
auth.setProfile(createCfProfileStore({ logger }).resolve({ cwd: root }));
return auth;
}

/** Borrow only the profile just verified by cf, including its encrypted store. */
export function readCfSessionCredential(
root: string,
identity: Record<string, unknown>,
): string | null {
if (identity.authenticated !== true || identity.tokenValid !== true) {
return null;
}
const auth = session(root);
if (identity.authSource !== `OAuth token from ${auth.getCredentialStore().path()}`) {
return null;
}
const token = auth.readAuthCredentials()?.oauth_token;
if (typeof token === 'string' && token.length > 0) {
persistCfKeyringPreference(root);
}
return typeof token === 'string' && token.length > 0 ? token : null;
}

/** Keep subsequent cf logins on the encrypted profile adopted by Void. */
export function persistCfKeyringPreference(root: string): void {
const auth = session(root);
if (
!setKeyringPreference(true, { logger, getCredentialStore: auth.getCredentialStore }).enabled
) {
throw new Error('Cloudflare encrypted credential storage is unavailable.');
}
}
11 changes: 9 additions & 2 deletions packages/void/src/cli/cloudflare-candidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,20 @@ export function recordCloudflareCandidateUpload(
expected &&
(expected.accountId !== accountId ||
expected.workerName !== workerName ||
expected.parentVersionId !== parentVersionId)
(expected.parentVersionId !== parentVersionId &&
expected.versionIds.at(-1) !== parentVersionId))
) {
throw new Error(
'The saved Cloudflare candidate belongs to a different Worker or live version. Inspect the deployment before retrying.',
);
}
const versionIds = [...(expected?.versionIds ?? []), versionId];
// The activation runner supplies its verified live parent. If the last saved
// candidate already became that parent, begin a new chain instead of retaining
// the interrupted deployment's old parent and inactive-version authorization.
const versionIds = [
...(expected?.parentVersionId === parentVersionId ? expected.versionIds : []),
versionId,
];
mkdirSync(join(root, '.void'), { recursive: true });
const path = join(root, CANDIDATE_FILE);
const temp = `${path}.${process.pid}.tmp`;
Expand Down
Loading
Loading