镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 4d86d66

Browse files
chrisbbreuerclaude
andcommitted
feat(cdn): a deploy waits for a new Cloudflare zone's certificate and proxies in the same run
A zone that was just delegated has no edge certificate, so its hosts were published DNS-only and a second deploy was needed to turn the proxy on. reconcileCloudflareCdn now takes edgeWait: it waits, twenty minutes by default (cdn.cloudflare.edgeWaitMinutes), for the zone to activate and Universal SSL to be issued, asking Cloudflare to check the nameservers while the zone is pending, and then proxies. A pending zone is waited on only when the caller says its nameservers were moved. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 966c64a commit 4d86d66

7 files changed

Lines changed: 232 additions & 4 deletions

File tree

‎packages/core/src/types.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4940,6 +4940,16 @@ export interface CloudflareCdnConfig {
49404940
* origin certificate already exists.
49414941
*/
49424942
skipOriginProbe?: boolean
4943+
/**
4944+
* How long a deploy waits for the zone's edge certificate before it gives up
4945+
* and publishes DNS-only, in minutes. @default 20
4946+
*
4947+
* A zone that was just delegated is activated and given its Universal SSL
4948+
* certificate by Cloudflare on its own, usually within minutes. Waiting lets
4949+
* the deploy that moved the nameservers also turn the proxy on, so the move
4950+
* is one deploy and not two. `0` does not wait: the next deploy proxies.
4951+
*/
4952+
edgeWaitMinutes?: number
49434953
}
49444954

49454955
/** HSTS settings for a Cloudflare zone. */

‎packages/ts-cloud/bin/commands/deploy.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2589,6 +2589,9 @@ async function reconcileCloudflareCdnForDeploy(
25892589
originGuard: plan.originGuard,
25902590
purge: plan.purge,
25912591
skipOriginProbe: plan.skipOriginProbe,
2592+
edgeWait: plan.edgeWaitMs > 0
2593+
? { timeoutMs: plan.edgeWaitMs, onProgress: (message: string) => cli.info(` … ${message}`) }
2594+
: undefined,
25922595
})
25932596

25942597
for (const record of report.records)

‎packages/ts-cloud/src/cdn/cloudflare-plan.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,13 @@ export interface CloudflareCdnPlan {
2828
originGuard?: CloudflareOriginGuard
2929
purge: boolean
3030
skipOriginProbe: boolean
31+
/** How long a deploy waits for the zone's edge certificate, in milliseconds. 0 does not wait. */
32+
edgeWaitMs: number
3133
}
3234

35+
/** A newly delegated zone is usually active and certified well inside this. */
36+
export const DEFAULT_EDGE_WAIT_MINUTES = 20
37+
3338
export interface ResolveCloudflareCdnPlanResult {
3439
/** The plan, or `null` when this config does not ask for a Cloudflare CDN. */
3540
plan: CloudflareCdnPlan | null
@@ -136,6 +141,7 @@ export function resolveCloudflareCdnPlan(
136141
originGuard: guard,
137142
purge: cf.purgeOnDeploy !== false,
138143
skipOriginProbe: cf.skipOriginProbe === true,
144+
edgeWaitMs: Math.max(0, cf.edgeWaitMinutes ?? DEFAULT_EDGE_WAIT_MINUTES) * 60_000,
139145
},
140146
errors,
141147
}

‎packages/ts-cloud/src/cdn/cloudflare.test.ts‎

Lines changed: 88 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { CloudConfig } from '@ts-cloud/core'
22
import { describe, expect, it } from 'bun:test'
33
import type { CloudflareRule } from '../dns/cloudflare'
44
import { CloudflareProvider, hostsInExpression, mergeManagedRules } from '../dns/cloudflare'
5-
import { edgeCertificateCovers } from './cloudflare'
5+
import { edgeCertificateCovers, universalSslCovers, waitForEdgeCertificate } from './cloudflare'
66
import { resolveCloudflareCdnPlan, resolveZoneApex } from './cloudflare-plan'
77
import { buildOriginGuardRule, buildStaticSiteCacheRules, hostCondition } from './cloudflare-rules'
88
import { STATIC_SITE_ZONE_SETTINGS, toCloudflareZoneSettings } from './cloudflare-settings'
@@ -571,3 +571,90 @@ describe('email obfuscation', () => {
571571
expect(toCloudflareZoneSettings({}).email_obfuscation).toBeUndefined()
572572
})
573573
})
574+
575+
describe('waiting for the edge certificate', () => {
576+
/** A zone that activates, then is certified, as the clock moves. */
577+
function zoneThat(steps: { activeAt: number, certifiedAt: number }) {
578+
const clock = { at: 0 }
579+
const asked: number[] = []
580+
const provider = {
581+
listEdgeCertificateHosts: async () => (clock.at >= steps.certifiedAt ? ['example.com', '*.example.com'] : []),
582+
getZoneDetails: async () => ({ id: 'zone-1', name: 'example.com', status: clock.at >= steps.activeAt ? 'active' : 'pending', nameServers: ['a.ns.cloudflare.com', 'b.ns.cloudflare.com'], paused: false }),
583+
requestActivationCheck: async () => {
584+
asked.push(clock.at)
585+
return true
586+
},
587+
}
588+
const said: string[] = []
589+
const wait = (timeoutMs: number, whilePending = true) => ({
590+
timeoutMs,
591+
whilePending,
592+
intervalMs: 20_000,
593+
onProgress: (message: string) => said.push(message),
594+
sleep: async (ms: number) => { clock.at += ms },
595+
now: () => clock.at,
596+
})
597+
return { provider, clock, asked, said, wait }
598+
}
599+
600+
it('says which names Universal SSL can ever cover', () => {
601+
expect(universalSslCovers('example.com', 'example.com')).toBe(true)
602+
expect(universalSslCovers('example.com', 'www.example.com')).toBe(true)
603+
expect(universalSslCovers('example.com', 'a.b.example.com')).toBe(false)
604+
expect(universalSslCovers('example.com', 'other.org')).toBe(false)
605+
})
606+
607+
it('waits through pending and issuance, then answers what is covered', async () => {
608+
const z = zoneThat({ activeAt: 90_000, certifiedAt: 200_000 })
609+
const covered = await waitForEdgeCertificate({ provider: z.provider, zone: 'example.com', hosts: ['example.com', 'www.example.com'], wait: z.wait(20 * 60_000) })
610+
expect(covered).toEqual(['example.com', '*.example.com'])
611+
expect(z.clock.at).toBe(200_000)
612+
// Said once for each thing waited on, not once a look.
613+
expect(z.said).toHaveLength(2)
614+
expect(z.said[0]).toContain('is pending at Cloudflare')
615+
expect(z.said[1]).toContain('waiting for its edge certificate')
616+
// Asked to look at the nameservers again a minute apart, and only while pending.
617+
expect(z.asked).toEqual([0, 60_000])
618+
})
619+
620+
it('gives up at the deadline with what is covered then', async () => {
621+
const z = zoneThat({ activeAt: 0, certifiedAt: Number.POSITIVE_INFINITY })
622+
const covered = await waitForEdgeCertificate({ provider: z.provider, zone: 'example.com', hosts: ['example.com'], wait: z.wait(60_000) })
623+
expect(covered).toEqual([])
624+
expect(z.clock.at).toBe(60_000)
625+
})
626+
627+
it('does not wait on a pending zone unless told its nameservers were moved', async () => {
628+
const z = zoneThat({ activeAt: Number.POSITIVE_INFINITY, certifiedAt: Number.POSITIVE_INFINITY })
629+
const covered = await waitForEdgeCertificate({ provider: z.provider, zone: 'example.com', hosts: ['example.com'], wait: z.wait(20 * 60_000, false) })
630+
expect(covered).toEqual([])
631+
expect(z.clock.at).toBe(0)
632+
expect(z.asked).toEqual([])
633+
expect(z.said[0]).toContain('not waiting for a certificate')
634+
})
635+
636+
it('does not wait for a name no Universal SSL certificate will cover', async () => {
637+
const z = zoneThat({ activeAt: 0, certifiedAt: 0 })
638+
const covered = await waitForEdgeCertificate({ provider: z.provider, zone: 'example.com', hosts: ['a.b.example.com'], wait: z.wait(20 * 60_000) })
639+
expect(covered).toEqual(['example.com', '*.example.com'])
640+
expect(z.clock.at).toBe(0)
641+
})
642+
643+
it('answers null at once when coverage cannot be read', async () => {
644+
const z = zoneThat({ activeAt: 0, certifiedAt: 0 })
645+
const provider = { ...z.provider, listEdgeCertificateHosts: async () => null }
646+
expect(await waitForEdgeCertificate({ provider, zone: 'example.com', hosts: ['example.com'], wait: z.wait(60_000) })).toBeNull()
647+
expect(z.clock.at).toBe(0)
648+
})
649+
650+
it('a plan waits twenty minutes unless the config says otherwise', () => {
651+
const config = (cloudflare: Record<string, unknown>): CloudConfig => ({
652+
project: { name: 'x', slug: 'x', region: 'us-east-1' },
653+
infrastructure: { dns: { domain: 'example.com' }, compute: { proxy: { cdn: { provider: 'cloudflare', frontedHosts: ['example.com'], cloudflare } } } },
654+
} as unknown as CloudConfig)
655+
const env = (key: string): string | undefined => (key === 'CLOUDFLARE_API_TOKEN' ? 'token' : undefined)
656+
expect(resolveCloudflareCdnPlan(config({}), { env }).plan?.edgeWaitMs).toBe(20 * 60_000)
657+
expect(resolveCloudflareCdnPlan(config({ edgeWaitMinutes: 0 }), { env }).plan?.edgeWaitMs).toBe(0)
658+
expect(resolveCloudflareCdnPlan(config({ edgeWaitMinutes: 5 }), { env }).plan?.edgeWaitMs).toBe(5 * 60_000)
659+
})
660+
})

‎packages/ts-cloud/src/cdn/cloudflare.ts‎

Lines changed: 106 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,38 @@ export interface ReconcileCloudflareCdnOptions {
8181
* @default false
8282
*/
8383
skipEdgeCertificateCheck?: boolean
84+
/**
85+
* Wait for the zone's edge certificate instead of deferring the proxy to the
86+
* next deploy.
87+
*
88+
* A zone that has just been delegated has no certificate: Cloudflare first
89+
* has to see the registrar pointing at it, then issue Universal SSL. Both
90+
* finish on their own, usually within minutes, so a deploy that waits can
91+
* turn the proxy on in the same run. Omit it, or give a `timeoutMs` of 0, to
92+
* publish DNS-only and leave the proxy to a later deploy.
93+
*/
94+
edgeWait?: EdgeWaitOptions
95+
}
96+
97+
export interface EdgeWaitOptions {
98+
/** The longest to wait, in milliseconds. */
99+
timeoutMs: number
100+
/** Time between looks. @default 20000 */
101+
intervalMs?: number
102+
/**
103+
* Also wait while the zone is still `pending`, that is, while Cloudflare has
104+
* not yet seen the registrar pointing at it. @default false
105+
*
106+
* Only a caller that knows the nameservers were moved should say so: a
107+
* pending zone whose nameservers are still elsewhere never activates, and
108+
* waiting on it spends the whole timeout to learn nothing.
109+
*/
110+
whilePending?: boolean
111+
/** Told what is being waited for, each time it changes. */
112+
onProgress?: (message: string) => void
113+
/** Injectable for tests. */
114+
sleep?: (ms: number) => Promise<void>
115+
now?: () => number
84116
}
85117

86118
export interface CloudflareCdnReport {
@@ -136,6 +168,69 @@ export function edgeCertificateCovers(certificateHosts: string[], host: string):
136168
})
137169
}
138170

171+
/**
172+
* Can Universal SSL ever cover `host` in `zone`? The apex and names one label
173+
* below it, and nothing deeper: waiting for a certificate that will never be
174+
* issued would hold a deploy for its whole timeout to learn nothing.
175+
*/
176+
export function universalSslCovers(zone: string, host: string): boolean {
177+
return edgeCertificateCovers([zone, `*.${zone}`], host)
178+
}
179+
180+
/**
181+
* Wait until the zone's active edge certificates cover every host Universal
182+
* SSL can cover, or the time runs out.
183+
*
184+
* Returns what the certificates cover when it stops: `null` if that could not
185+
* be read, which the caller treats as "no idea", exactly as it does without a
186+
* wait. A zone still `pending` is waited on only with `whilePending`, and then
187+
* Cloudflare is asked, once a minute at most, to check the nameservers again.
188+
*/
189+
export async function waitForEdgeCertificate(options: {
190+
provider: Pick<CloudflareProvider, 'listEdgeCertificateHosts' | 'getZoneDetails' | 'requestActivationCheck'>
191+
zone: string
192+
hosts: string[]
193+
wait: EdgeWaitOptions
194+
}): Promise<string[] | null> {
195+
const { provider, zone, wait } = options
196+
const sleep = wait.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)))
197+
const now = wait.now ?? Date.now
198+
const interval = wait.intervalMs ?? 20_000
199+
const awaited = options.hosts.filter(host => universalSslCovers(zone, host))
200+
const deadline = now() + wait.timeoutMs
201+
202+
let said = ''
203+
const say = (message: string): void => {
204+
if (message !== said) wait.onProgress?.(message)
205+
said = message
206+
}
207+
let askedAt = Number.NEGATIVE_INFINITY
208+
209+
while (true) {
210+
const covered = await provider.listEdgeCertificateHosts(zone)
211+
if (covered === null || awaited.every(host => edgeCertificateCovers(covered, host))) return covered
212+
if (now() >= deadline) return covered
213+
214+
const details = await provider.getZoneDetails(zone)
215+
if (details && details.status !== 'active') {
216+
if (!wait.whilePending) {
217+
say(`${zone} is ${details.status} at Cloudflare, which has not seen its nameservers point there: not waiting for a certificate`)
218+
return covered
219+
}
220+
say(`${zone} is ${details.status} at Cloudflare: waiting for it to see the nameservers (${details.nameServers.join(', ')})`)
221+
if (now() - askedAt >= 60_000) {
222+
askedAt = now()
223+
await provider.requestActivationCheck(zone)
224+
}
225+
}
226+
else {
227+
say(`${zone} is active: waiting for its edge certificate to be issued`)
228+
}
229+
230+
await sleep(Math.min(interval, Math.max(0, deadline - now())))
231+
}
232+
}
233+
139234
export async function reconcileCloudflareCdn(
140235
options: ReconcileCloudflareCdnOptions,
141236
): Promise<CloudflareCdnReport> {
@@ -153,6 +248,7 @@ export async function reconcileCloudflareCdn(
153248
ttl = 300,
154249
skipOriginProbe = false,
155250
skipEdgeCertificateCheck = false,
251+
edgeWait,
156252
} = options
157253

158254
const report: CloudflareCdnReport = {
@@ -180,10 +276,18 @@ export async function reconcileCloudflareCdn(
180276
// treated as "nothing is covered" — a token missing SSL read would otherwise
181277
// silently stop proxying every site on every deploy. An empty array is a
182278
// definitive answer and is acted on.
183-
const edgeHosts = proxied && !skipEdgeCertificateCheck
279+
let edgeHosts = proxied && !skipEdgeCertificateCheck
184280
? await provider.listEdgeCertificateHosts(zone)
185281
: null
186282

283+
// A certificate that is on its way is waited for, so one deploy takes a zone
284+
// from delegated to proxied. Only for names it will actually cover.
285+
const waitable = (covered: string[]): boolean =>
286+
hosts.some(host => universalSslCovers(zone, host) && !edgeCertificateCovers(covered, host))
287+
if (edgeHosts && edgeWait && edgeWait.timeoutMs > 0 && waitable(edgeHosts))
288+
edgeHosts = await waitForEdgeCertificate({ provider, zone, hosts, wait: edgeWait })
289+
const waited = !!edgeWait && edgeWait.timeoutMs > 0
290+
187291
for (const host of hosts) {
188292
let hostProxied = proxied
189293

@@ -200,7 +304,7 @@ export async function reconcileCloudflareCdn(
200304
report.warnings.push(
201305
`${host}: publishing DNS-only — ${reason}. Proxying it would make Cloudflare terminate TLS with no certificate for the name, ` +
202306
`which fails the handshake outright rather than degrading. Universal SSL covers the apex and ONE level of subdomain, so a deeper ` +
203-
`name needs its own certificate; otherwise re-run the deploy once the certificate is active.`,
307+
`name needs its own certificate; otherwise ${waited ? 'the certificate was not issued within the time this deploy waits, and the next deploy proxies it' : 're-run the deploy once the certificate is active'}.`,
204308
)
205309
}
206310

‎packages/ts-cloud/src/cdn/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ export type {
1010
CloudflareOriginGuard,
1111
ReconcileCloudflareCdnOptions,
1212
} from './cloudflare'
13-
export { reconcileCloudflareCdn } from './cloudflare'
13+
export { reconcileCloudflareCdn, universalSslCovers, waitForEdgeCertificate } from './cloudflare'
1414
export type {
1515
CloudflareCdnPlan,
1616
EnvLookup,

‎packages/ts-cloud/src/dns/cloudflare.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,24 @@ export class CloudflareProvider implements DnsProvider {
627627
}
628628
}
629629

630+
/**
631+
* Ask Cloudflare to check the zone's nameservers now.
632+
*
633+
* A zone stays `pending` until Cloudflare notices the registrar pointing at
634+
* it, which it otherwise looks for on its own schedule. Asking is rate
635+
* limited, so a refusal is the ordinary answer to asking twice: `false`
636+
* means "not now", never an error worth stopping for.
637+
*/
638+
async requestActivationCheck(domain: string): Promise<boolean> {
639+
try {
640+
const zoneId = await this.getZoneId(domain)
641+
await this.request('PUT', `/zones/${zoneId}/activation_check`)
642+
return true
643+
} catch {
644+
return false
645+
}
646+
}
647+
630648
/**
631649
* Hostnames the zone's ACTIVE edge certificates cover.
632650
*

0 commit comments

Comments
 (0)