Skip to content
Merged
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
Binary file modified .agents/skills/static-site-deploy.zip
Binary file not shown.
4 changes: 2 additions & 2 deletions .agents/skills/static-site-deploy/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Use this skill with the site's deploy guide and the [CLI reference](../../../pac

## Local setup and deployment

- `pnpm exec static-site-deploy setup --site acme/site` prompts for missing settings and saves the bucket, distribution ID, HTTPS homepage URL, region, and profile name in per-site AppStash. Authenticate the AWS CLI to the site's account first; credentials stay with the AWS CLI. Plain setup does not provision AWS or GitHub.
- `pnpm exec static-site-deploy setup --site acme/site.example` uses the existing AWS CLI profile to discover the distribution, S3 origin, and bucket region; a domain-shaped repository name supplies the HTTPS homepage. It prints discoveries, prompts for unresolved settings, and saves the bucket, distribution ID, homepage URL, region, and profile name in per-site AppStash. Authenticate the AWS CLI to the site's account first; setup never asks for credentials.
- `pnpm exec static-site-deploy check --site acme/site` is silent on success. It validates configuration without prompting and does not check AWS credentials, permissions, or whether targets exist. Shell values (`AWS_S3_BUCKET`, `AWS_CLOUDFRONT_DISTRIBUTION_ID`, `SITE_URL`, `AWS_REGION`, and `AWS_PROFILE`) override saved settings. CI uses environment variables only; the CLI does not fetch them from GitHub.
- Build the site, then preview with `pnpm exec static-site-deploy deploy --site acme/site --dir out --dry-run`. This needs S3 list access. Inspect the planned uploads, alias copies, and deletions; it does not write to AWS, invalidate CloudFront, or check the live homepage.
- If the site defines the scripts, `pnpm run deploy:all` builds and publishes; `pnpm run deploy` publishes an existing export. Bare `pnpm deploy` is pnpm's workspace command, not the site script. Never run a real deploy without explicit approval for that deployment, and do not publish concurrently from GitHub and a workstation.
Expand All @@ -19,7 +19,7 @@ Use this skill with the site's deploy guide and the [CLI reference](../../../pac

Follow the site repository's approval rules for production provisioning and workflow dispatches, including dry-runs where required.

1. Preview `pnpm exec static-site-deploy setup --site acme/site --provision --reviewer LOGIN --account-id ACCOUNT_ID --role-name ROLE_NAME --dry-run`. The plan illustrates a fresh setup without contacting AWS or GitHub. To apply with authorization, use AWS CLI v2 with IAM setup permissions, authenticated `gh` with repository admin access, Bash, and `jq`.
1. Select the signed-in profile with `export AWS_PROFILE=example-profile`, then preview `pnpm exec static-site-deploy setup --site acme/site.example --provision --role-name example-site-deploy --dry-run`. Setup reads the account ID from STS; explicit flags and environment variables override discovery. Dry-run discovery is read-only. To apply with authorization, use AWS CLI v2 with IAM setup permissions, authenticated `gh` with repository admin access, Bash, and `jq`.
2. Use a dedicated IAM role per site. Setup restricts permissions to that site's bucket and distribution, and binds trust to audience `sts.amazonaws.com` and the repository's `production` environment on `refs/heads/main`, for example `repo:acme/site:environment:production:ref:refs/heads/main`. It preserves immutable subjects where enabled. Check other OIDC integrations first: the subject template is repository-wide.
3. Keep `production` restricted to `main`, with administrator bypass off. Use a required reviewer where supported. If GitHub rejects the reviewer rule because of the plan, supported CLI versions retry without setting a reviewer and warn; the run then does not wait for reviewer approval. Setup verifies that administrator bypass is disabled before changing IAM trust. Keep the human approval requirement even when GitHub cannot enforce it.
4. Define a manual `workflow_dispatch` on `main` with a boolean `dry-run` input defaulting to `true`. Build before assuming the role; only the deploy job targets `production` and needs `id-token: write`. Use the environment variables for the AWS region, targets, homepage, and role ARN. Don't store AWS keys in GitHub. Leave dry-run selected for a preview and turn it off only for an explicitly approved real deploy. Merging does not deploy.
10 changes: 5 additions & 5 deletions packages/static-site-deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pnpm build
pnpm exec static-site-deploy deploy --site OWNER/REPO --dir out
```

The setup asks only for missing settings. A local deploy from an interactive terminal also asks for missing settings, saves the answers, and continues. AWS credentials stay in AWS CLI configuration; the per-site appstash store contains only the bucket, distribution, homepage URL, region, and profile name. No `.env` file is needed. Use a named AWS profile if you deploy from multiple accounts.
Setup uses your existing AWS CLI profile; it never asks for AWS credentials. When target settings are missing, it infers the HTTPS homepage from a domain-shaped repository name, looks up the CloudFront distribution for that host, and reads its S3 origin and bucket region. It prints the values found and prompts for anything it could not determine. A local deploy from an interactive terminal also asks for missing settings, saves the answers, and continues. The per-site appstash store contains only the bucket, distribution, homepage URL, region, and profile name. No `.env` file is needed.

Shell variables take precedence over saved values: `AWS_S3_BUCKET`, `AWS_CLOUDFRONT_DISTRIBUTION_ID`, `SITE_URL` (HTTPS), `AWS_REGION`, and `AWS_PROFILE`. Provisioning is optional and has a separate confirmation; automatic prompting during a deploy never provisions anything. To validate inputs without building or deploying, use `static-site-deploy check --site OWNER/REPO`.

Expand All @@ -28,14 +28,14 @@ Per-site deploy options:

## GitHub Actions and AWS OIDC

Run setup with AWS CLI v2 signed into the account that owns the bucket and distribution, `gh` signed in as a repository administrator, and `jq` and Bash installed. The AWS identity needs IAM permissions to manage the GitHub OIDC provider, the dedicated role, and its inline policy.
Run setup with AWS CLI v2 signed into the account that owns the bucket and distribution, `gh` signed in as a repository administrator, and `jq` and Bash installed. Discovery uses the selected profile to read the account ID from STS and needs permission to list CloudFront distributions and read the S3 bucket location. Provisioning also needs IAM permissions to manage the GitHub OIDC provider, the dedicated role, and its inline policy.

```sh
pnpm exec static-site-deploy setup --site OWNER/REPO --provision --reviewer LOGIN \
--account-id 000000000000 --role-name example-site-deploy --dry-run
export AWS_PROFILE=example-profile
pnpm exec static-site-deploy setup --site acme/site.example --provision --role-name example-site-deploy --dry-run
```

Replace the placeholders. `--reviewer` is optional; omit it to leave any existing reviewer settings alone. `--dry-run` prints a fresh-setup plan and does not change AWS, GitHub, or stored values. Remove it to apply; with inputs supplied through variables, `--provision --yes` also supports unattended provisioning. Use a separate role for each site. Sites in the same AWS account reuse the GitHub OIDC provider, not the role or credentials. Do not share or store AWS access keys in GitHub or in appstash.
Replace the placeholders. For a GitHub repository whose name is not a domain, provide `SITE_URL` so discovery can match the correct alias. Explicit targets and `--account-id` (or `AWS_ACCOUNT_ID`) override discovery. `--reviewer` is optional; leave it unset to keep existing reviewer settings. `--dry-run` can read from AWS to discover settings but does not change AWS, GitHub, or stored values. Remove it to apply; use `--provision --yes` for unattended provisioning when all settings are supplied or discoverable. Use a separate role for each site. Sites in the same AWS account reuse the GitHub OIDC provider, not the role or credentials. Do not share or store AWS access keys in GitHub or in appstash.

Provisioning creates or reuses the IAM provider, sets an exact AWS audience and subject for the repository's `production` environment and `refs/heads/main` (or `--branch`), and restricts permissions to the selected S3 bucket and CloudFront distribution. It sets the GitHub repository-wide OIDC template to `["repo","context","ref"]`; check for other OIDC integrations before applying. Repositories that use immutable OIDC subjects keep them, and the role trusts the subject GitHub reports, such as `repo:OWNER@OWNER-ID/REPO@REPO-ID:environment:production:ref:refs/heads/main`. It sets `production` environment variables for the deployment targets, region, homepage, and role ARN. It never dispatches a deployment.

Expand Down
174 changes: 173 additions & 1 deletion packages/static-site-deploy/__tests__/cli.test.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } = require('node:fs');
const { tmpdir } = require('node:os');
const { join, resolve, delimiter } = require('node:path');

Expand Down Expand Up @@ -218,6 +218,178 @@ test('fails on S3 per-key delete errors without a second invalidation', () => {
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'],
targetOriginId = 'origin-0',
orderedOriginIds = [],
aliases = [['www.site.example', 'SITE.EXAMPLE']],
location = null,
fail = [],
} = {}) {
const state = fixture();
const items = aliases.map((names, index) => ({
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}`,
...(typeof origin === 'string' ? { DomainName: origin } : origin),
})),
},
}));
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: ['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);
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'], 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) => {
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.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('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');
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);
Expand Down
10 changes: 7 additions & 3 deletions packages/static-site-deploy/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ...]
Expand All @@ -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 };

Expand Down Expand Up @@ -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);
Expand All @@ -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);
}

Expand All @@ -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 },
Expand Down
Loading
Loading