From d70892d5be1f72565789a0363253fd1384c64419 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Wed, 2 Dec 2026 00:44:59 +0000 Subject: [PATCH 1/3] Discover static site deployment settings from AWS profiles --- .agents/skills/static-site-deploy.zip | Bin 2156 -> 2227 bytes .agents/skills/static-site-deploy/SKILL.md | 4 +- packages/static-site-deploy/README.md | 10 +- .../static-site-deploy/__tests__/cli.test.cjs | 138 +++++++++++++++++- packages/static-site-deploy/src/cli.ts | 10 +- packages/static-site-deploy/src/config.ts | 4 +- packages/static-site-deploy/src/discover.ts | 73 +++++++++ 7 files changed, 226 insertions(+), 13 deletions(-) create mode 100644 packages/static-site-deploy/src/discover.ts diff --git a/.agents/skills/static-site-deploy.zip b/.agents/skills/static-site-deploy.zip index 387465f5021bedcaa0316aeec41a64a3294c942a..e391801d94a58cdb1305da6ed64ad67ffd09eb3d 100644 GIT binary patch delta 2051 zcmV+e2>kc#5VH}GI}UmUf?XAsIBTf~002!9kx3zcrB_XF+ei|<>sK_8!^|v1dN$dU zj6FEEGZDtI153sp77MdQmZXl!ZcaC8Tl4GpRdth;ob2vlfdG-o?)rMKUKO(}n_1n^ zLWNFurp$urD66Qg-C%3ZhP})}NvUYv-$vfN4 zRqN@0+0cu^Ti;vUsa>gS6)iW!NBByhPW7#7wC(ZsH`9IYH|nBfmqFbvuP)P#kk2xN zI(w&9N4`^>vxh*c+nb=mlc{Us|lU4J27mU8hPAcw) z8)=j3>S-q>)F@t~jm^Sdx2U|Q*1^B?2gy%`zHMuhBKW*se_f%v4YhzdSIZ7D7~6%> zzu{^juBOF9=67#B1y?_l5SGIaiN5-OIa!Sn%}>Hs%d7e5NIl%&%u~ei@-YO;Sk;n` z^}A?WkSpwSbvb_#^5F93?&0dw{oU>Q@oKqR z-!DHtte1DUkIO4Qv0ARL9|6p8`u_SiyeuL<^5pCN-KXWvb@7X0W_VT*27Mwzt}d66 z-ejK*`kNaDL3yJ$HJ&O zRK_a?1Hb$sgDe-hTC;3gqA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nX5=;YcS&+z2(1 z|Mu8uNU`1RdZ_yzQ$tV0@O|5`oN)qBmQExb#S9}9-FfbOXmGBXs&+R_`SHm{WG}f$ z5=X(ECRVrpNGP2}Q3~z4F9{xYG8#^sfX0AhI8Qe^8S2@8Df(|@x`U1H)&Ru?Ck3N^ zg2*=r$HJ@^Vs^#mFb*xo@|oVnx(VMflWQ(p-Pb9{j)ORpV&{JEB?t|m37ah>2X+tmm94$kRXbIGeD_@rmvTQ3kz*U5qYuO>Y z*&%BA!)}LvUHF1g3_)DxGE*eMJ`p~cWdqA1b7bPZyQjv5BdS*aQPcSt4?}z0O+Qd) zy1qqiZ2c3s5IAnWD5K2OgGR0hyK+Atz?qVS?d(erJFTch>uO#bLGhTa9I1!J2u~u0 zLiu5ZN!1NG!G2&__hR&4P)h*<9s>#h00000trdBbA_zVmbryMDY}I}2Vg~>KQ4jzC b8vp { const provisionArgs = ['setup', '--site', site, '--provision', '--yes', '--reviewer', 'example-reviewer', '--account-id', '123456789012', '--role-name', 'example-deploy', '--branch', 'release']; +const discoveryArgs = ['setup', '--site', 'example-org/site.example', '--provision', '--yes', + '--role-name', 'example-deploy', '--dry-run']; + +function fakeDiscovery({ + origins = ['fixture-bucket.s3.amazonaws.com'], + aliases = [['www.site.example', 'SITE.EXAMPLE']], + location = null, + fail = [], +} = {}) { + const state = fixture(); + const items = aliases.map((names, index) => ({ + Id: `FIXTURE${index}`, + Aliases: { Items: names }, + Origins: { Items: origins.map(DomainName => ({ DomainName })) }, + })); + const responses = { + 'cloudfront list-distributions': { DistributionList: { Items: items } }, + 's3api get-bucket-location': { LocationConstraint: location }, + 'sts get-caller-identity': { Account: '123456789012' }, + }; + state.mock('aws', ` +const args = process.argv.slice(2); +require('node:fs').appendFileSync(process.env.CALLS, JSON.stringify([ + process.env.AWS_PROFILE, process.env.AWS_CLI_AUTO_PROMPT, ...args, +]) + '\\n'); +const command = args.slice(0, 2).join(' '); +const response = ${JSON.stringify(responses)}[command]; +if (${JSON.stringify(fail)}.includes(command) || !response) process.exit(99); +console.log(JSON.stringify(response)); +`); + return state; +} + +test.each([ + ['fixture-bucket.s3.amazonaws.com', null, 'us-east-1'], + ['fixture-bucket.s3.us-west-2.amazonaws.com', 'us-west-2', 'us-west-2'], + ['fixture-bucket.s3-website-us-east-1.amazonaws.com', '', 'us-east-1'], + ['fixture-bucket.s3-website.eu-west-1.amazonaws.com', 'EU', 'eu-west-1'], +])('discovers targets with a profile and origin %s', (origin, location, region) => { + const { cliRun, calls } = fakeDiscovery({ origins: ['custom.example', origin], location }); + const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); + assert.equal(result.status, 0, result.stderr); + for (const [key, value] of Object.entries({ + SITE_URL: 'https://site.example', + AWS_CLOUDFRONT_DISTRIBUTION_ID: 'FIXTURE0', + AWS_S3_BUCKET: 'fixture-bucket', + AWS_REGION: region, + AWS_ACCOUNT_ID: '123456789012', + })) { + assert.ok(result.stdout.includes(`Discovered ${key}: ${value}\n`)); + } + assert.deepEqual(calls(), [ + [targets.AWS_PROFILE, 'off', 'cloudfront', 'list-distributions', '--output', 'json'], + [targets.AWS_PROFILE, 'off', 's3api', 'get-bucket-location', '--bucket', 'fixture-bucket', '--output', 'json'], + [targets.AWS_PROFILE, 'off', 'sts', 'get-caller-identity', '--output', 'json'], + ]); +}); + +test('honors explicit targets and account ID without calling AWS', () => { + const { cliRun, calls } = fakeDiscovery(); + const result = cliRun([...discoveryArgs, '--account-id', '234567890123'], { ...targets, AWS_ACCOUNT_ID: '123456789012' }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /arn:aws:cloudfront::234567890123:distribution\/EXAMPLE123/); + assert.doesNotMatch(result.stdout, /Discovered /); + assert.equal(existsSync(calls.path), false); +}); + +test('uses the explicit distribution to discover a bucket and preserves an explicit region', () => { + const { cliRun, calls } = fakeDiscovery({ aliases: [[], ['site.example']] }); + const result = cliRun(discoveryArgs, { + AWS_PROFILE: targets.AWS_PROFILE, AWS_CLOUDFRONT_DISTRIBUTION_ID: 'FIXTURE0', + AWS_REGION: 'us-west-2', AWS_ACCOUNT_ID: '123456789012', + }); + assert.equal(result.status, 0, result.stderr); + assert.match(result.stdout, /Discovered AWS_S3_BUCKET: fixture-bucket/); + assert.doesNotMatch(result.stdout, /Discovered AWS_(?:CLOUDFRONT|REGION|ACCOUNT)/); + assert.deepEqual(calls().map(call => call.slice(2, 4)), [['cloudfront', 'list-distributions']]); +}); + +test.each([ + [{ aliases: [] }, 'AWS_CLOUDFRONT_DISTRIBUTION_ID'], + [{ aliases: [['site.example'], ['site.example']] }, 'AWS_CLOUDFRONT_DISTRIBUTION_ID'], + [{ origins: ['first-bucket.s3.amazonaws.com', 'other-bucket.s3.amazonaws.com'] }, 'AWS_S3_BUCKET'], + [{ fail: ['s3api get-bucket-location'] }, 'AWS_REGION'], + [{ fail: ['sts get-caller-identity'] }, 'AWS_ACCOUNT_ID'], +])('leaves unresolved values unset for unattended setup (%j)', (options, missing) => { + const { cliRun } = fakeDiscovery(options); + const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); + assert.notEqual(result.status, 0); + assert.ok(result.stderr.includes(missing)); + assert.ok(!result.stdout.includes(`Discovered ${missing}:`)); +}); + +test('prompts for undiscovered values after an AWS failure, not for discovered values', () => { + const { cliRun, cwd } = fakeDiscovery({ fail: ['cloudfront list-distributions', 'sts get-caller-identity'] }); + const preload = join(cwd, 'prompt.cjs'); + writeFileSync(preload, ` +const { createRequire } = require('node:module'); +const { Inquirerer } = createRequire(${JSON.stringify(cli)})('inquirerer'); +const answers = ${JSON.stringify({ + AWS_S3_BUCKET: targets.AWS_S3_BUCKET, + AWS_CLOUDFRONT_DISTRIBUTION_ID: targets.AWS_CLOUDFRONT_DISTRIBUTION_ID, + AWS_REGION: targets.AWS_REGION, + AWS_ACCOUNT_ID: '123456789012', + })}; +process.stdin.isTTY = process.stdout.isTTY = true; +Inquirerer.prototype.text = async question => { + if (!Object.hasOwn(answers, question.name)) throw new Error('Unexpected prompt: ' + question.name); + console.log('Prompted: ' + question.name); + return answers[question.name]; +}; +`); + const result = cliRun([...discoveryArgs.filter(arg => arg !== '--yes'), '--reviewer', 'example-reviewer'], { + AWS_PROFILE: targets.AWS_PROFILE, NODE_OPTIONS: `--require="${preload}"`, + }); + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(result.stdout.match(/Prompted: \w+/g)?.sort(), [ + 'Prompted: AWS_ACCOUNT_ID', 'Prompted: AWS_CLOUDFRONT_DISTRIBUTION_ID', 'Prompted: AWS_REGION', 'Prompted: AWS_S3_BUCKET', + ]); +}); + +test.each([ + ['setup', 'site.example', { CI: 'true' }], + ['setup', 'not-a-domain', {}], + ['check', 'site.example', {}], + ['deploy', 'site.example', {}], +])('does not discover site settings for %s on %s with %j', (command, repo, env) => { + const { cliRun, calls } = fakeDiscovery(); + const result = cliRun([command, '--site', `example-org/${repo}`, ...(command === 'setup' ? ['--dry-run'] : [])], { + ...targets, ...env, SITE_URL: undefined, + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /SITE_URL/); + assert.equal(existsSync(calls.path), false); +}); + test('rejects unattended provisioning without confirmation before saving local settings', () => { const { cliRun } = fixture(); const result = cliRun(provisionArgs.filter(arg => arg !== '--yes'), targets); diff --git a/packages/static-site-deploy/src/cli.ts b/packages/static-site-deploy/src/cli.ts index d00dcd1..596eb4e 100644 --- a/packages/static-site-deploy/src/cli.ts +++ b/packages/static-site-deploy/src/cli.ts @@ -9,6 +9,7 @@ import { awsEnvironment, fields, isCI, readSiteConfig, requiredFields, saveSiteConfig, SiteConfig, validValue, validateConfig, } from './config'; import { deploy } from './deploy'; +import { discoverAccountId, discoverTargets } from './discover'; const usage = `Usage: static-site-deploy deploy --site OWNER/REPO [--dir out] [--preserve PATTERN ...] @@ -19,8 +20,9 @@ const usage = `Usage: const interactive = !isCI(process.env) && process.stdin.isTTY && process.stdout.isTTY; -async function promptForConfig(site: string, allowPrompt: boolean) { - const values = readSiteConfig(site); +async function promptForConfig(site: string, allowPrompt: boolean, setup: boolean) { + const local = readSiteConfig(site); + const values = setup ? discoverTargets(site, local) : local; const missing = requiredFields(process.env).filter(key => !values[key]?.trim()); if (!allowPrompt || !missing.length) return { config: validateConfig(values, process.env), prompted: false }; @@ -102,7 +104,7 @@ async function main() { throw new Error('Unattended cloud provisioning requires --provision --yes.'); } } - const { config, prompted } = await promptForConfig(site, allowPrompt); + const { config, prompted } = await promptForConfig(site, allowPrompt, command === 'setup' && !isCI(process.env)); if (command === 'check') return; if (command === 'deploy') { if (prompted && !dryRun) saveSiteConfig(site, config); @@ -128,6 +130,7 @@ async function main() { }; if (!allowPrompt) { if (!options.provision && !dryRun) return; + provision.AWS_ACCOUNT_ID ??= discoverAccountId(config); return runProvisioner(site, config, provision, dryRun); } @@ -139,6 +142,7 @@ async function main() { }]); if (!configure) return; } + provision.AWS_ACCOUNT_ID ??= discoverAccountId(config); const questions = ([ { name: 'SITE_REVIEWER', message: 'GitHub reviewer login (optional)', required: false }, { name: 'AWS_ACCOUNT_ID', message: 'AWS account ID', required: true }, diff --git a/packages/static-site-deploy/src/config.ts b/packages/static-site-deploy/src/config.ts index 3d104d8..58ba22d 100644 --- a/packages/static-site-deploy/src/config.ts +++ b/packages/static-site-deploy/src/config.ts @@ -14,7 +14,7 @@ export const fields = { type ConfigKey = keyof typeof fields; const keys = Object.keys(fields) as ConfigKey[]; -type ConfigValues = Partial>; +export type ConfigValues = Partial>; export type SiteConfig = Required> & Pick; type Environment = NodeJS.ProcessEnv; @@ -92,7 +92,7 @@ export function saveSiteConfig(site: string, values: SiteConfig) { store.setVar(storeKey, JSON.stringify(config), context); } -export function awsEnvironment(config: SiteConfig, environment = process.env) { +export function awsEnvironment(config: Pick, environment = process.env) { const result: Environment = { ...environment, AWS_REGION: config.AWS_REGION, AWS_DEFAULT_REGION: config.AWS_REGION }; delete result.AWS_PROFILE; delete result.AWS_DEFAULT_PROFILE; diff --git a/packages/static-site-deploy/src/discover.ts b/packages/static-site-deploy/src/discover.ts new file mode 100644 index 0000000..c214175 --- /dev/null +++ b/packages/static-site-deploy/src/discover.ts @@ -0,0 +1,73 @@ +import { spawnSync } from 'node:child_process'; + +import { awsEnvironment, ConfigValues, isCI, validValue } from './config'; + +type Distribution = { + Id?: string; + Aliases?: { Items?: string[] }; + Origins?: { Items?: { DomainName: string }[] }; +}; + +function awsJson(config: ConfigValues, ...args: string[]): T | undefined { + const result = spawnSync('aws', [...args, '--output', 'json'], { + encoding: 'utf8', + env: { ...awsEnvironment(config), AWS_PAGER: '', AWS_CLI_AUTO_PROMPT: 'off' }, + timeout: 15_000, + }); + if (result.status !== 0) return; + try { + return JSON.parse(result.stdout); + } catch { + return; + } +} + +export function discoverTargets(site: string, values: ConfigValues): ConfigValues { + if (isCI(process.env)) return values; + const config = { ...values }; + const fill = (key: keyof ConfigValues, value?: string) => { + if (config[key]?.trim() || !validValue(key, value)) return; + config[key] = value; + console.log(`Discovered ${key}: ${value}`); + }; + + const repo = site.split('/')[1].toLowerCase(); + if (/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])$/.test(repo)) { + fill('SITE_URL', `https://${repo}`); + } + + const distributionId = config.AWS_CLOUDFRONT_DISTRIBUTION_ID?.trim(); + const host = validValue('SITE_URL', config.SITE_URL) ? new URL(config.SITE_URL!.trim()).hostname : undefined; + if ((!distributionId && host) || (!config.AWS_S3_BUCKET?.trim() && distributionId)) { + const list = awsJson<{ DistributionList?: { Items?: Distribution[] } }>(config, 'cloudfront', 'list-distributions'); + const matches = list?.DistributionList?.Items?.filter(distribution => distributionId + ? distribution.Id === distributionId + : distribution.Aliases?.Items?.some(alias => alias.toLowerCase() === host)); + if (matches?.length === 1) { + const [distribution] = matches; + fill('AWS_CLOUDFRONT_DISTRIBUTION_ID', distribution.Id); + const s3Origin = /^(.+)\.s3(?:\.[a-z]{2}(?:-[a-z0-9]+)+-\d+|-website[.-][a-z]{2}(?:-[a-z0-9]+)+-\d+)?\.amazonaws\.com$/; + const buckets = new Set(distribution.Origins?.Items?.flatMap(origin => { + const bucket = origin.DomainName.match(s3Origin)?.[1]; + return bucket && validValue('AWS_S3_BUCKET', bucket) ? [bucket] : []; + })); + if (buckets.size === 1) fill('AWS_S3_BUCKET', [...buckets][0]); + } + } + + const bucket = config.AWS_S3_BUCKET?.trim(); + if (!config.AWS_REGION?.trim() && bucket && validValue('AWS_S3_BUCKET', bucket)) { + const location = awsJson<{ LocationConstraint?: string | null }>(config, 's3api', 'get-bucket-location', '--bucket', bucket) + ?.LocationConstraint; + fill('AWS_REGION', location === null || location === '' ? 'us-east-1' : location === 'EU' ? 'eu-west-1' : location); + } + return config; +} + +export function discoverAccountId(config: ConfigValues): string | undefined { + if (isCI(process.env)) return; + const account = awsJson<{ Account?: string }>(config, 'sts', 'get-caller-identity')?.Account; + if (typeof account !== 'string' || !/^\d{12}$/.test(account)) return; + console.log(`Discovered AWS_ACCOUNT_ID: ${account}`); + return account; +} From 734e204ba4c257a16fe32f57dcb9099a7ab9738f Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Wed, 2 Dec 2026 00:48:59 +0000 Subject: [PATCH 2/3] Discover buckets only from the default root S3 origin --- .../static-site-deploy/__tests__/cli.test.cjs | 28 +++++++++++++++++-- packages/static-site-deploy/src/discover.ts | 25 ++++++++++++----- 2 files changed, 43 insertions(+), 10 deletions(-) diff --git a/packages/static-site-deploy/__tests__/cli.test.cjs b/packages/static-site-deploy/__tests__/cli.test.cjs index e63a93a..ca6087a 100644 --- a/packages/static-site-deploy/__tests__/cli.test.cjs +++ b/packages/static-site-deploy/__tests__/cli.test.cjs @@ -223,6 +223,7 @@ const discoveryArgs = ['setup', '--site', 'example-org/site.example', '--provisi function fakeDiscovery({ origins = ['fixture-bucket.s3.amazonaws.com'], + targetOriginId = 'origin-0', aliases = [['www.site.example', 'SITE.EXAMPLE']], location = null, fail = [], @@ -231,7 +232,13 @@ function fakeDiscovery({ const items = aliases.map((names, index) => ({ Id: `FIXTURE${index}`, Aliases: { Items: names }, - Origins: { Items: origins.map(DomainName => ({ DomainName })) }, + DefaultCacheBehavior: { TargetOriginId: targetOriginId }, + Origins: { + Items: origins.map((origin, index) => ({ + Id: `origin-${index}`, + ...(typeof origin === 'string' ? { DomainName: origin } : origin), + })), + }, })); const responses = { 'cloudfront list-distributions': { DistributionList: { Items: items } }, @@ -257,7 +264,9 @@ test.each([ ['fixture-bucket.s3-website-us-east-1.amazonaws.com', '', 'us-east-1'], ['fixture-bucket.s3-website.eu-west-1.amazonaws.com', 'EU', 'eu-west-1'], ])('discovers targets with a profile and origin %s', (origin, location, region) => { - const { cliRun, calls } = fakeDiscovery({ origins: ['custom.example', origin], location }); + const { cliRun, calls } = fakeDiscovery({ + origins: ['other-bucket.s3.amazonaws.com', origin], targetOriginId: 'origin-1', location, + }); const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); assert.equal(result.status, 0, result.stderr); for (const [key, value] of Object.entries({ @@ -300,7 +309,7 @@ test('uses the explicit distribution to discover a bucket and preserves an expli test.each([ [{ aliases: [] }, 'AWS_CLOUDFRONT_DISTRIBUTION_ID'], [{ aliases: [['site.example'], ['site.example']] }, 'AWS_CLOUDFRONT_DISTRIBUTION_ID'], - [{ origins: ['first-bucket.s3.amazonaws.com', 'other-bucket.s3.amazonaws.com'] }, 'AWS_S3_BUCKET'], + [{ origins: ['first-bucket.s3.amazonaws.com', 'other-bucket.s3.amazonaws.com'], targetOriginId: 'origin-group' }, 'AWS_S3_BUCKET'], [{ fail: ['s3api get-bucket-location'] }, 'AWS_REGION'], [{ fail: ['sts get-caller-identity'] }, 'AWS_ACCOUNT_ID'], ])('leaves unresolved values unset for unattended setup (%j)', (options, missing) => { @@ -311,6 +320,19 @@ test.each([ assert.ok(!result.stdout.includes(`Discovered ${missing}:`)); }); +test.each([ + [['custom.example', 'secondary-bucket.s3.amazonaws.com'], /default origin is not an S3 bucket endpoint/], + [[{ DomainName: 'fixture-bucket.s3.amazonaws.com', OriginPath: '/prefix' }], /default origin serves an OriginPath prefix/], +])('does not infer a bucket when the default origin is unsuitable (%j)', (origins, reason) => { + const { cliRun, calls } = fakeDiscovery({ origins }); + const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, reason); + assert.match(result.stdout, /Discovered AWS_CLOUDFRONT_DISTRIBUTION_ID: FIXTURE0/); + assert.doesNotMatch(result.stdout, /Discovered AWS_S3_BUCKET:/); + assert.deepEqual(calls().map(call => call.slice(2, 4)), [['cloudfront', 'list-distributions']]); +}); + test('prompts for undiscovered values after an AWS failure, not for discovered values', () => { const { cliRun, cwd } = fakeDiscovery({ fail: ['cloudfront list-distributions', 'sts get-caller-identity'] }); const preload = join(cwd, 'prompt.cjs'); diff --git a/packages/static-site-deploy/src/discover.ts b/packages/static-site-deploy/src/discover.ts index c214175..a79d9be 100644 --- a/packages/static-site-deploy/src/discover.ts +++ b/packages/static-site-deploy/src/discover.ts @@ -5,7 +5,8 @@ import { awsEnvironment, ConfigValues, isCI, validValue } from './config'; type Distribution = { Id?: string; Aliases?: { Items?: string[] }; - Origins?: { Items?: { DomainName: string }[] }; + DefaultCacheBehavior?: { TargetOriginId?: string }; + Origins?: { Items?: { Id: string; DomainName: string; OriginPath?: string }[] }; }; function awsJson(config: ConfigValues, ...args: string[]): T | undefined { @@ -22,6 +23,21 @@ function awsJson(config: ConfigValues, ...args: string[]): T | undefined { } } +function discoverBucket(distribution: Distribution): string | undefined { + const targetId = distribution.DefaultCacheBehavior?.TargetOriginId; + const origin = targetId && distribution.Origins?.Items?.find(item => item.Id === targetId); + const s3Origin = /^(.+)\.s3(?:\.[a-z]{2}(?:-[a-z0-9]+)+-\d+|-website[.-][a-z]{2}(?:-[a-z0-9]+)+-\d+)?\.amazonaws\.com$/; + if (!origin) { + console.warn('Could not discover AWS_S3_BUCKET: CloudFront default cache behavior does not target a single origin.'); + } else if (origin.OriginPath) { + console.warn('Could not discover AWS_S3_BUCKET: CloudFront default origin serves an OriginPath prefix.'); + } else { + const bucket = origin.DomainName.match(s3Origin)?.[1]; + if (validValue('AWS_S3_BUCKET', bucket)) return bucket; + console.warn('Could not discover AWS_S3_BUCKET: CloudFront default origin is not an S3 bucket endpoint.'); + } +} + export function discoverTargets(site: string, values: ConfigValues): ConfigValues { if (isCI(process.env)) return values; const config = { ...values }; @@ -46,12 +62,7 @@ export function discoverTargets(site: string, values: ConfigValues): ConfigValue if (matches?.length === 1) { const [distribution] = matches; fill('AWS_CLOUDFRONT_DISTRIBUTION_ID', distribution.Id); - const s3Origin = /^(.+)\.s3(?:\.[a-z]{2}(?:-[a-z0-9]+)+-\d+|-website[.-][a-z]{2}(?:-[a-z0-9]+)+-\d+)?\.amazonaws\.com$/; - const buckets = new Set(distribution.Origins?.Items?.flatMap(origin => { - const bucket = origin.DomainName.match(s3Origin)?.[1]; - return bucket && validValue('AWS_S3_BUCKET', bucket) ? [bucket] : []; - })); - if (buckets.size === 1) fill('AWS_S3_BUCKET', [...buckets][0]); + if (!config.AWS_S3_BUCKET?.trim()) fill('AWS_S3_BUCKET', discoverBucket(distribution)); } } From fb80910339a6a58478235d76e475eb5903a77fb6 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Wed, 2 Dec 2026 00:51:06 +0000 Subject: [PATCH 3/3] Skip bucket discovery when cache behaviors change origins --- .../static-site-deploy/__tests__/cli.test.cjs | 16 +++++++++++++++- packages/static-site-deploy/src/discover.ts | 3 +++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/static-site-deploy/__tests__/cli.test.cjs b/packages/static-site-deploy/__tests__/cli.test.cjs index ca6087a..db9a683 100644 --- a/packages/static-site-deploy/__tests__/cli.test.cjs +++ b/packages/static-site-deploy/__tests__/cli.test.cjs @@ -224,6 +224,7 @@ const discoveryArgs = ['setup', '--site', 'example-org/site.example', '--provisi function fakeDiscovery({ origins = ['fixture-bucket.s3.amazonaws.com'], targetOriginId = 'origin-0', + orderedOriginIds = [], aliases = [['www.site.example', 'SITE.EXAMPLE']], location = null, fail = [], @@ -233,6 +234,7 @@ function fakeDiscovery({ Id: `FIXTURE${index}`, Aliases: { Items: names }, DefaultCacheBehavior: { TargetOriginId: targetOriginId }, + CacheBehaviors: { Items: orderedOriginIds.map(TargetOriginId => ({ PathPattern: '/*', TargetOriginId })) }, Origins: { Items: origins.map((origin, index) => ({ Id: `origin-${index}`, @@ -265,7 +267,7 @@ test.each([ ['fixture-bucket.s3-website.eu-west-1.amazonaws.com', 'EU', 'eu-west-1'], ])('discovers targets with a profile and origin %s', (origin, location, region) => { const { cliRun, calls } = fakeDiscovery({ - origins: ['other-bucket.s3.amazonaws.com', origin], targetOriginId: 'origin-1', location, + origins: ['other-bucket.s3.amazonaws.com', origin], targetOriginId: 'origin-1', orderedOriginIds: ['origin-1'], location, }); const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); assert.equal(result.status, 0, result.stderr); @@ -333,6 +335,18 @@ test.each([ assert.deepEqual(calls().map(call => call.slice(2, 4)), [['cloudfront', 'list-distributions']]); }); +test('does not infer a bucket when an ordered cache behavior targets a different origin', () => { + const { cliRun, calls } = fakeDiscovery({ + origins: ['fixture-bucket.s3.amazonaws.com', 'other.example'], + orderedOriginIds: ['origin-1'], + }); + const result = cliRun(discoveryArgs, { AWS_PROFILE: targets.AWS_PROFILE }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /ordered cache behavior targets a different origin/); + assert.doesNotMatch(result.stdout, /Discovered AWS_S3_BUCKET:/); + assert.deepEqual(calls().map(call => call.slice(2, 4)), [['cloudfront', 'list-distributions']]); +}); + test('prompts for undiscovered values after an AWS failure, not for discovered values', () => { const { cliRun, cwd } = fakeDiscovery({ fail: ['cloudfront list-distributions', 'sts get-caller-identity'] }); const preload = join(cwd, 'prompt.cjs'); diff --git a/packages/static-site-deploy/src/discover.ts b/packages/static-site-deploy/src/discover.ts index a79d9be..e790b4f 100644 --- a/packages/static-site-deploy/src/discover.ts +++ b/packages/static-site-deploy/src/discover.ts @@ -6,6 +6,7 @@ type Distribution = { Id?: string; Aliases?: { Items?: string[] }; DefaultCacheBehavior?: { TargetOriginId?: string }; + CacheBehaviors?: { Items?: { TargetOriginId?: string }[] }; Origins?: { Items?: { Id: string; DomainName: string; OriginPath?: string }[] }; }; @@ -29,6 +30,8 @@ function discoverBucket(distribution: Distribution): string | undefined { const s3Origin = /^(.+)\.s3(?:\.[a-z]{2}(?:-[a-z0-9]+)+-\d+|-website[.-][a-z]{2}(?:-[a-z0-9]+)+-\d+)?\.amazonaws\.com$/; if (!origin) { console.warn('Could not discover AWS_S3_BUCKET: CloudFront default cache behavior does not target a single origin.'); + } else if (distribution.CacheBehaviors?.Items?.some(behavior => behavior.TargetOriginId !== targetId)) { + console.warn('Could not discover AWS_S3_BUCKET: a CloudFront ordered cache behavior targets a different origin.'); } else if (origin.OriginPath) { console.warn('Could not discover AWS_S3_BUCKET: CloudFront default origin serves an OriginPath prefix.'); } else {