@constructive-io/static-site-deploy 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +80 -2
- package/cli.d.ts +2 -0
- package/cli.js +164 -0
- package/config.d.ts +35 -0
- package/config.js +97 -0
- package/deploy.d.ts +10 -0
- package/deploy.js +119 -0
- package/esm/cli.d.ts +2 -0
- package/esm/cli.js +162 -0
- package/esm/config.d.ts +35 -0
- package/esm/config.js +86 -0
- package/esm/deploy.d.ts +10 -0
- package/esm/deploy.js +116 -0
- package/esm/index.d.ts +2 -0
- package/esm/index.js +2 -0
- package/index.d.ts +2 -0
- package/index.js +8 -0
- package/package.json +33 -3
- package/provision.sh +174 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Constructive <developers@constructive.io>
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Static site deploy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@constructive-io/static-site-deploy` deploys an existing static export to a dedicated S3 bucket behind CloudFront. It does not provide hosting, build the site, or change a site's DNS.
|
|
4
|
+
|
|
5
|
+
## Local deploy
|
|
6
|
+
|
|
7
|
+
From a site repo with AWS CLI, curl, and the package installed:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pnpm exec static-site-deploy setup --site OWNER/REPO
|
|
11
|
+
pnpm build
|
|
12
|
+
pnpm exec static-site-deploy deploy --site OWNER/REPO --dir out
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
17
|
+
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`.
|
|
18
|
+
|
|
19
|
+
Deploy uploads the export, refreshes extensionless aliases, and waits for CloudFront invalidation. Only after the public homepage returns HTTP 200 with HTML and the bucket listing is complete does it prune keys absent from the export and its aliases, including stale pages and old assets. A final invalidation follows deletion. Use a dedicated bucket, and serialize deployments, including local ones.
|
|
20
|
+
|
|
21
|
+
By default, existing Markdown files (`*.md`) and the root `llms.txt` are preserved when absent from the export. Repeat `--preserve PATTERN` to replace that list with a site-specific list. Patterns match full keys, with `*` matching any number of characters, including slashes.
|
|
22
|
+
|
|
23
|
+
Per-site deploy options:
|
|
24
|
+
|
|
25
|
+
- `--dry-run` lists planned uploads, alias copies, and stale-key deletions. It needs read-only access to list the bucket, but does not upload, delete, invalidate CloudFront, check the homepage, or save answers to prompts.
|
|
26
|
+
- `--trailing-slash-aliases` adds `foo/` alongside `foo` for `foo/index.html`. The default creates only `foo`; neither mode creates an alias for the root `index.html`.
|
|
27
|
+
- `--verify-homepage` also requires the HTTP 200 HTML response body to match the export's `index.html` byte for byte before pruning. Use it when CloudFront serves the export without modifying the response body.
|
|
28
|
+
|
|
29
|
+
## GitHub Actions and AWS OIDC
|
|
30
|
+
|
|
31
|
+
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.
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
pnpm exec static-site-deploy setup --site OWNER/REPO --provision --reviewer LOGIN \
|
|
35
|
+
--account-id 000000000000 --role-name example-site-deploy --dry-run
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Replace the placeholders. `--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.
|
|
39
|
+
|
|
40
|
+
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. It sets `production` environment variables for the deployment targets, region, homepage, and role ARN. It never dispatches a deployment.
|
|
41
|
+
|
|
42
|
+
If asked, turn off **Allow administrators to bypass configured protection rules** in the GitHub `production` environment, save, and rerun setup. GitHub's public REST API cannot write this toggle. The environment requires the configured reviewer and permits only the configured branch. If the environment is deleted, revoke AWS role trust until the environment and its protections are restored.
|
|
43
|
+
|
|
44
|
+
Use `workflow_dispatch` to start manually. Build in an unprivileged job, then use a separate `production` job with `contents: read` and `id-token: write` and the build artifact. In that job, configure AWS OIDC credentials with `aws-actions/configure-aws-credentials` using `vars.AWS_DEPLOY_ROLE_ARN` and `vars.AWS_REGION`. Pass `AWS_S3_BUCKET`, `AWS_CLOUDFRONT_DISTRIBUTION_ID`, `SITE_URL`, and `AWS_REGION` from `vars` to `static-site-deploy deploy`. On GitHub Actions, the repo is inferred from `GITHUB_REPOSITORY`. CI never reads the local store or prompts; missing or invalid configuration fails before uploads.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Development
|
|
49
|
+
|
|
50
|
+
### Setup
|
|
51
|
+
|
|
52
|
+
1. Clone the repository:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
git clone https://github.com/constructive-io/dev-utils.git
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
2. Install dependencies:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
cd dev-utils
|
|
62
|
+
pnpm install
|
|
63
|
+
pnpm build
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
3. Test the package of interest:
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
cd packages/<packagename>
|
|
70
|
+
pnpm test:watch
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Credits
|
|
74
|
+
|
|
75
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
76
|
+
|
|
77
|
+
## Disclaimer
|
|
78
|
+
|
|
79
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
80
|
+
|
|
81
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/cli.d.ts
ADDED
package/cli.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const node_util_1 = require("node:util");
|
|
7
|
+
const inquirerer_1 = require("inquirerer");
|
|
8
|
+
const config_1 = require("./config");
|
|
9
|
+
const deploy_1 = require("./deploy");
|
|
10
|
+
const usage = `Usage:
|
|
11
|
+
static-site-deploy deploy --site OWNER/REPO [--dir out] [--preserve PATTERN ...]
|
|
12
|
+
[--dry-run] [--trailing-slash-aliases] [--verify-homepage]
|
|
13
|
+
static-site-deploy check --site OWNER/REPO
|
|
14
|
+
static-site-deploy setup --site OWNER/REPO [--provision] [--dry-run] [--yes]
|
|
15
|
+
[--reviewer LOGIN] [--account-id ID] [--role-name NAME] [--branch main]`;
|
|
16
|
+
const interactive = !(0, config_1.isCI)(process.env) && process.stdin.isTTY && process.stdout.isTTY;
|
|
17
|
+
async function promptForConfig(site, allowPrompt) {
|
|
18
|
+
const values = (0, config_1.readSiteConfig)(site);
|
|
19
|
+
const missing = (0, config_1.requiredFields)(process.env).filter(key => !values[key]?.trim());
|
|
20
|
+
if (!allowPrompt || !missing.length)
|
|
21
|
+
return { config: (0, config_1.validateConfig)(values, process.env), prompted: false };
|
|
22
|
+
const detectedRegion = missing.includes('AWS_REGION') ? (0, node_child_process_1.spawnSync)('aws', ['configure', 'get', 'region'], {
|
|
23
|
+
encoding: 'utf8',
|
|
24
|
+
env: { ...process.env, AWS_PROFILE: values.AWS_PROFILE ?? 'default' },
|
|
25
|
+
}).stdout?.trim() : undefined;
|
|
26
|
+
const prompter = new inquirerer_1.Inquirerer();
|
|
27
|
+
try {
|
|
28
|
+
const answers = await prompter.prompt({}, missing.map(key => ({
|
|
29
|
+
type: 'text',
|
|
30
|
+
name: key,
|
|
31
|
+
message: config_1.fields[key].label,
|
|
32
|
+
required: true,
|
|
33
|
+
...(key === 'AWS_PROFILE' ? { default: 'default' } : {}),
|
|
34
|
+
...(key === 'AWS_REGION' && detectedRegion ? { default: detectedRegion } : {}),
|
|
35
|
+
validate: (input) => (0, config_1.validValue)(key, input) ? { success: true } : {
|
|
36
|
+
success: false, reason: `Enter a valid ${config_1.fields[key].label}.`,
|
|
37
|
+
},
|
|
38
|
+
})));
|
|
39
|
+
return { config: (0, config_1.validateConfig)({ ...values, ...answers }, process.env), prompted: true };
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
prompter.close();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function runProvisioner(site, config, provision, dryRun) {
|
|
46
|
+
const { AWS_PROFILE: _profile, ...targets } = config;
|
|
47
|
+
const result = (0, node_child_process_1.spawnSync)('bash', [(0, node_path_1.join)(__dirname, 'provision.sh'), ...(dryRun ? ['--dry-run'] : [])], {
|
|
48
|
+
env: { ...(0, config_1.awsEnvironment)(config), ...targets, ...provision, SITE_REPO: site },
|
|
49
|
+
stdio: 'inherit',
|
|
50
|
+
});
|
|
51
|
+
if (result.error)
|
|
52
|
+
throw result.error;
|
|
53
|
+
if (result.status !== 0)
|
|
54
|
+
process.exitCode = result.status ?? 1;
|
|
55
|
+
}
|
|
56
|
+
async function main() {
|
|
57
|
+
const { values: options, positionals } = (0, node_util_1.parseArgs)({
|
|
58
|
+
allowPositionals: true,
|
|
59
|
+
options: {
|
|
60
|
+
site: { type: 'string' },
|
|
61
|
+
dir: { type: 'string' },
|
|
62
|
+
preserve: { type: 'string', multiple: true },
|
|
63
|
+
'trailing-slash-aliases': { type: 'boolean' },
|
|
64
|
+
'verify-homepage': { type: 'boolean' },
|
|
65
|
+
provision: { type: 'boolean' },
|
|
66
|
+
'dry-run': { type: 'boolean' },
|
|
67
|
+
yes: { type: 'boolean' },
|
|
68
|
+
reviewer: { type: 'string' },
|
|
69
|
+
'account-id': { type: 'string' },
|
|
70
|
+
'role-name': { type: 'string' },
|
|
71
|
+
branch: { type: 'string' },
|
|
72
|
+
help: { type: 'boolean' },
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
if (options.help)
|
|
76
|
+
return console.log(usage);
|
|
77
|
+
const [command] = positionals;
|
|
78
|
+
if (positionals.length !== 1 || !['deploy', 'setup', 'check'].includes(command))
|
|
79
|
+
throw new Error(usage);
|
|
80
|
+
const site = options.site ?? process.env.GITHUB_REPOSITORY;
|
|
81
|
+
if (!site)
|
|
82
|
+
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
83
|
+
if (command !== 'setup' && (options.provision || options.yes ||
|
|
84
|
+
options.reviewer || options['account-id'] || options['role-name'] || options.branch))
|
|
85
|
+
throw new Error(usage);
|
|
86
|
+
if (command !== 'deploy' && (options.dir || options.preserve ||
|
|
87
|
+
options['trailing-slash-aliases'] || options['verify-homepage']))
|
|
88
|
+
throw new Error(usage);
|
|
89
|
+
if (command === 'check' && options['dry-run'])
|
|
90
|
+
throw new Error(usage);
|
|
91
|
+
const allowPrompt = interactive && !options.yes && command !== 'check';
|
|
92
|
+
const dryRun = !!options['dry-run'];
|
|
93
|
+
if (command === 'setup' && !dryRun) {
|
|
94
|
+
if ((0, config_1.isCI)(process.env))
|
|
95
|
+
throw new Error('Run interactive setup outside CI; use environment variables to deploy in CI.');
|
|
96
|
+
if (options.provision && !allowPrompt && !options.yes) {
|
|
97
|
+
throw new Error('Unattended cloud provisioning requires --provision --yes.');
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const { config, prompted } = await promptForConfig(site, allowPrompt);
|
|
101
|
+
if (command === 'check')
|
|
102
|
+
return;
|
|
103
|
+
if (command === 'deploy') {
|
|
104
|
+
if (prompted && !dryRun)
|
|
105
|
+
(0, config_1.saveSiteConfig)(site, config);
|
|
106
|
+
return (0, deploy_1.deploy)(config, {
|
|
107
|
+
directory: options.dir ?? 'out',
|
|
108
|
+
preserve: options.preserve,
|
|
109
|
+
dryRun,
|
|
110
|
+
trailingSlashAliases: options['trailing-slash-aliases'],
|
|
111
|
+
verifyHomepage: options['verify-homepage'],
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (!dryRun) {
|
|
115
|
+
(0, config_1.saveSiteConfig)(site, config);
|
|
116
|
+
console.log(`Saved local deploy settings for ${site}. No AWS credentials were stored.`);
|
|
117
|
+
}
|
|
118
|
+
const provision = {
|
|
119
|
+
SITE_REVIEWER: options.reviewer ?? process.env.SITE_REVIEWER,
|
|
120
|
+
AWS_ACCOUNT_ID: options['account-id'] ?? process.env.AWS_ACCOUNT_ID,
|
|
121
|
+
AWS_DEPLOY_ROLE_NAME: options['role-name'] ?? process.env.AWS_DEPLOY_ROLE_NAME,
|
|
122
|
+
SITE_BRANCH: options.branch ?? 'main',
|
|
123
|
+
};
|
|
124
|
+
if (!allowPrompt) {
|
|
125
|
+
if (!options.provision && !dryRun)
|
|
126
|
+
return;
|
|
127
|
+
return runProvisioner(site, config, provision, dryRun);
|
|
128
|
+
}
|
|
129
|
+
const prompter = new inquirerer_1.Inquirerer();
|
|
130
|
+
try {
|
|
131
|
+
if (!dryRun && !options.provision) {
|
|
132
|
+
const { configure } = await prompter.prompt({}, [{
|
|
133
|
+
type: 'confirm', name: 'configure', message: 'Set up AWS OIDC and the GitHub production approval gate?', default: false,
|
|
134
|
+
}]);
|
|
135
|
+
if (!configure)
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const questions = [
|
|
139
|
+
{ name: 'SITE_REVIEWER', message: 'Required GitHub reviewer (login)' },
|
|
140
|
+
{ name: 'AWS_ACCOUNT_ID', message: 'AWS account ID' },
|
|
141
|
+
{ name: 'AWS_DEPLOY_ROLE_NAME', message: 'Dedicated IAM deploy role name' },
|
|
142
|
+
].filter(question => provision[question.name] === undefined);
|
|
143
|
+
const answers = questions.length ? await prompter.prompt({}, questions.map(question => ({
|
|
144
|
+
...question,
|
|
145
|
+
type: 'text',
|
|
146
|
+
required: true,
|
|
147
|
+
}))) : {};
|
|
148
|
+
const { apply } = dryRun ? { apply: true } : await prompter.prompt({}, [{
|
|
149
|
+
type: 'confirm',
|
|
150
|
+
name: 'apply',
|
|
151
|
+
message: `Apply AWS and GitHub changes for ${site} on ${provision.SITE_BRANCH}? (Does not deploy)`,
|
|
152
|
+
default: false,
|
|
153
|
+
}]);
|
|
154
|
+
if (apply)
|
|
155
|
+
runProvisioner(site, config, { ...provision, ...answers }, dryRun);
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
prompter.close();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
main().catch(error => {
|
|
162
|
+
console.error(error instanceof Error ? error.message : error);
|
|
163
|
+
process.exitCode = 1;
|
|
164
|
+
});
|
package/config.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export declare const fields: {
|
|
2
|
+
readonly AWS_S3_BUCKET: {
|
|
3
|
+
readonly label: "S3 bucket";
|
|
4
|
+
readonly pattern: RegExp;
|
|
5
|
+
};
|
|
6
|
+
readonly AWS_CLOUDFRONT_DISTRIBUTION_ID: {
|
|
7
|
+
readonly label: "CloudFront distribution ID";
|
|
8
|
+
readonly pattern: RegExp;
|
|
9
|
+
};
|
|
10
|
+
readonly SITE_URL: {
|
|
11
|
+
readonly label: "HTTPS homepage URL";
|
|
12
|
+
readonly pattern: RegExp;
|
|
13
|
+
};
|
|
14
|
+
readonly AWS_REGION: {
|
|
15
|
+
readonly label: "AWS region";
|
|
16
|
+
readonly pattern: RegExp;
|
|
17
|
+
};
|
|
18
|
+
readonly AWS_PROFILE: {
|
|
19
|
+
readonly label: "AWS CLI profile";
|
|
20
|
+
readonly pattern: RegExp;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
type ConfigKey = keyof typeof fields;
|
|
24
|
+
type ConfigValues = Partial<Record<ConfigKey, string>>;
|
|
25
|
+
export type SiteConfig = Required<Omit<ConfigValues, 'AWS_PROFILE'>> & Pick<ConfigValues, 'AWS_PROFILE'>;
|
|
26
|
+
type Environment = NodeJS.ProcessEnv;
|
|
27
|
+
export declare function siteKey(site: string): string;
|
|
28
|
+
export declare function isCI(environment: Environment): boolean;
|
|
29
|
+
export declare function requiredFields(environment: Environment): ConfigKey[];
|
|
30
|
+
export declare function validValue(key: ConfigKey, raw?: string): boolean;
|
|
31
|
+
export declare function validateConfig(values: ConfigValues, environment: Environment): SiteConfig;
|
|
32
|
+
export declare function readSiteConfig(site: string, environment?: NodeJS.ProcessEnv): ConfigValues;
|
|
33
|
+
export declare function saveSiteConfig(site: string, values: SiteConfig): void;
|
|
34
|
+
export declare function awsEnvironment(config: SiteConfig, environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
35
|
+
export {};
|
package/config.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.fields = void 0;
|
|
4
|
+
exports.siteKey = siteKey;
|
|
5
|
+
exports.isCI = isCI;
|
|
6
|
+
exports.requiredFields = requiredFields;
|
|
7
|
+
exports.validValue = validValue;
|
|
8
|
+
exports.validateConfig = validateConfig;
|
|
9
|
+
exports.readSiteConfig = readSiteConfig;
|
|
10
|
+
exports.saveSiteConfig = saveSiteConfig;
|
|
11
|
+
exports.awsEnvironment = awsEnvironment;
|
|
12
|
+
const _12factor_env_1 = require("12factor-env");
|
|
13
|
+
const appstash_1 = require("appstash");
|
|
14
|
+
const storeName = 'static-site-deploy';
|
|
15
|
+
const storeKey = 'deploy';
|
|
16
|
+
exports.fields = {
|
|
17
|
+
AWS_S3_BUCKET: { label: 'S3 bucket', pattern: /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/ },
|
|
18
|
+
AWS_CLOUDFRONT_DISTRIBUTION_ID: { label: 'CloudFront distribution ID', pattern: /^[A-Z0-9]+$/ },
|
|
19
|
+
SITE_URL: { label: 'HTTPS homepage URL', pattern: /^https:\/\/[^/\s]+[^\s]*$/ },
|
|
20
|
+
AWS_REGION: { label: 'AWS region', pattern: /^[a-z]{2}(-[a-z0-9]+)+-[0-9]+$/ },
|
|
21
|
+
AWS_PROFILE: { label: 'AWS CLI profile', pattern: /\S/ },
|
|
22
|
+
};
|
|
23
|
+
const keys = Object.keys(exports.fields);
|
|
24
|
+
function siteKey(site) {
|
|
25
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/.test(site) || /\/\.{1,2}$/.test(site)) {
|
|
26
|
+
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
27
|
+
}
|
|
28
|
+
return encodeURIComponent(site.toLowerCase());
|
|
29
|
+
}
|
|
30
|
+
function isCI(environment) {
|
|
31
|
+
return environment.GITHUB_ACTIONS === 'true' ||
|
|
32
|
+
!!(environment.CI && !/^(false|0)$/i.test(environment.CI));
|
|
33
|
+
}
|
|
34
|
+
function requiredFields(environment) {
|
|
35
|
+
return keys.filter(key => key !== 'AWS_PROFILE' || (!isCI(environment) && !(environment.AWS_ACCESS_KEY_ID && environment.AWS_SECRET_ACCESS_KEY)));
|
|
36
|
+
}
|
|
37
|
+
function validValue(key, raw) {
|
|
38
|
+
if (typeof raw !== 'string' || !exports.fields[key].pattern.test(raw.trim()))
|
|
39
|
+
return false;
|
|
40
|
+
if (key !== 'SITE_URL')
|
|
41
|
+
return true;
|
|
42
|
+
try {
|
|
43
|
+
const url = new URL(raw.trim());
|
|
44
|
+
return !url.username && !url.password;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function validateConfig(values, environment) {
|
|
51
|
+
const validator = (key) => (0, _12factor_env_1.required)((0, _12factor_env_1.makeValidator)(value => {
|
|
52
|
+
if (!validValue(key, value))
|
|
53
|
+
throw new Error(`must be a valid ${exports.fields[key].label}`);
|
|
54
|
+
return value.trim();
|
|
55
|
+
}));
|
|
56
|
+
return { ...(0, _12factor_env_1.env)(values, {}, {
|
|
57
|
+
AWS_S3_BUCKET: validator('AWS_S3_BUCKET'),
|
|
58
|
+
AWS_CLOUDFRONT_DISTRIBUTION_ID: validator('AWS_CLOUDFRONT_DISTRIBUTION_ID'),
|
|
59
|
+
SITE_URL: validator('SITE_URL'),
|
|
60
|
+
AWS_REGION: validator('AWS_REGION'),
|
|
61
|
+
...(requiredFields(environment).includes('AWS_PROFILE') || (!isCI(environment) && validValue('AWS_PROFILE', values.AWS_PROFILE))
|
|
62
|
+
? { AWS_PROFILE: validator('AWS_PROFILE') } : {}),
|
|
63
|
+
}) };
|
|
64
|
+
}
|
|
65
|
+
function readSiteConfig(site, environment = process.env) {
|
|
66
|
+
const context = siteKey(site);
|
|
67
|
+
const overrides = {
|
|
68
|
+
...environment,
|
|
69
|
+
AWS_PROFILE: environment.AWS_PROFILE ?? environment.AWS_DEFAULT_PROFILE,
|
|
70
|
+
AWS_REGION: environment.AWS_REGION ?? environment.AWS_DEFAULT_REGION,
|
|
71
|
+
};
|
|
72
|
+
const populated = Object.fromEntries(keys.flatMap(key => overrides[key] === undefined ? [] : [[key, overrides[key]]]));
|
|
73
|
+
if (isCI(environment) || requiredFields(environment).every(key => overrides[key] !== undefined))
|
|
74
|
+
return populated;
|
|
75
|
+
const stored = (0, appstash_1.createConfigStore)(storeName).getVar(storeKey, context);
|
|
76
|
+
return { ...(stored ? JSON.parse(stored) : {}), ...populated };
|
|
77
|
+
}
|
|
78
|
+
function saveSiteConfig(site, values) {
|
|
79
|
+
const context = siteKey(site);
|
|
80
|
+
const store = (0, appstash_1.createConfigStore)(storeName);
|
|
81
|
+
const config = Object.fromEntries(keys.flatMap(key => validValue(key, values[key]) ? [[key, values[key].trim()]] : []));
|
|
82
|
+
if (config.AWS_PROFILE === undefined) {
|
|
83
|
+
const stored = store.getVar(storeKey, context);
|
|
84
|
+
const profile = stored ? JSON.parse(stored).AWS_PROFILE : undefined;
|
|
85
|
+
if (validValue('AWS_PROFILE', profile))
|
|
86
|
+
config.AWS_PROFILE = profile.trim();
|
|
87
|
+
}
|
|
88
|
+
store.setVar(storeKey, JSON.stringify(config), context);
|
|
89
|
+
}
|
|
90
|
+
function awsEnvironment(config, environment = process.env) {
|
|
91
|
+
const result = { ...environment, AWS_REGION: config.AWS_REGION, AWS_DEFAULT_REGION: config.AWS_REGION };
|
|
92
|
+
delete result.AWS_PROFILE;
|
|
93
|
+
delete result.AWS_DEFAULT_PROFILE;
|
|
94
|
+
if (config.AWS_PROFILE && requiredFields(environment).includes('AWS_PROFILE'))
|
|
95
|
+
result.AWS_PROFILE = config.AWS_PROFILE;
|
|
96
|
+
return result;
|
|
97
|
+
}
|
package/deploy.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SiteConfig } from './config';
|
|
2
|
+
type Options = {
|
|
3
|
+
directory: string;
|
|
4
|
+
preserve?: string[];
|
|
5
|
+
dryRun?: boolean;
|
|
6
|
+
trailingSlashAliases?: boolean;
|
|
7
|
+
verifyHomepage?: boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare function deploy(config: SiteConfig, { directory, preserve, dryRun, trailingSlashAliases, verifyHomepage, }: Options): void;
|
|
10
|
+
export {};
|
package/deploy.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.deploy = deploy;
|
|
4
|
+
const node_child_process_1 = require("node:child_process");
|
|
5
|
+
const node_fs_1 = require("node:fs");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
7
|
+
const config_1 = require("./config");
|
|
8
|
+
const markdown = ['*.md', 'llms.txt'];
|
|
9
|
+
const globRegex = (pattern) => new RegExp(`^${pattern.split('*').map(part => part.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')).join('.*')}$`);
|
|
10
|
+
function* exportKeys(root, prefix = '') {
|
|
11
|
+
for (const entry of (0, node_fs_1.readdirSync)((0, node_path_1.resolve)(root, prefix), { withFileTypes: true })) {
|
|
12
|
+
const key = prefix + entry.name;
|
|
13
|
+
if (entry.isDirectory())
|
|
14
|
+
yield* exportKeys(root, `${key}/`);
|
|
15
|
+
else if (entry.isFile())
|
|
16
|
+
yield key;
|
|
17
|
+
else
|
|
18
|
+
throw new Error(`Unexpected non-regular file in site export: ${key}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function deploy(config, { directory, preserve = markdown, dryRun, trailingSlashAliases, verifyHomepage, }) {
|
|
22
|
+
const root = (0, node_path_1.resolve)(directory);
|
|
23
|
+
const files = new Set(exportKeys(root));
|
|
24
|
+
if (!files.has('index.html'))
|
|
25
|
+
throw new Error(`Site export is missing ${directory}/index.html`);
|
|
26
|
+
const aliases = new Map();
|
|
27
|
+
for (const key of files) {
|
|
28
|
+
if (!key.endsWith('.html') || key === 'index.html')
|
|
29
|
+
continue;
|
|
30
|
+
const directoryIndex = key.endsWith('/index.html');
|
|
31
|
+
const alias = key.slice(0, directoryIndex ? -'/index.html'.length : -'.html'.length);
|
|
32
|
+
if (files.has(alias))
|
|
33
|
+
throw new Error(`Conflicting extensionless route: ${alias}`);
|
|
34
|
+
if (directoryIndex || !aliases.has(alias))
|
|
35
|
+
aliases.set(alias, key);
|
|
36
|
+
if (directoryIndex && trailingSlashAliases)
|
|
37
|
+
aliases.set(`${alias}/`, key);
|
|
38
|
+
}
|
|
39
|
+
const keep = preserve.map(globRegex);
|
|
40
|
+
const { AWS_S3_BUCKET: bucket, AWS_CLOUDFRONT_DISTRIBUTION_ID: distribution, SITE_URL: url } = config;
|
|
41
|
+
const s3 = `s3://${bucket}`;
|
|
42
|
+
const environment = (0, config_1.awsEnvironment)(config);
|
|
43
|
+
const exec = (command, args, env) => (0, node_child_process_1.execFileSync)(command, args, {
|
|
44
|
+
env, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 4 * 1024 * 1024,
|
|
45
|
+
});
|
|
46
|
+
const aws = (...args) => {
|
|
47
|
+
const result = (0, node_child_process_1.spawnSync)('aws', args, { env: environment, stdio: 'inherit' });
|
|
48
|
+
if (result.error)
|
|
49
|
+
throw result.error;
|
|
50
|
+
if (result.status !== 0)
|
|
51
|
+
throw new Error(`AWS ${args.slice(0, 2).join(' ')} failed (${result.status ?? result.signal})`);
|
|
52
|
+
};
|
|
53
|
+
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment).toString());
|
|
54
|
+
const invalidate = () => {
|
|
55
|
+
const { Invalidation: { Id } } = awsJson('cloudfront', 'create-invalidation', '--distribution-id', distribution, '--paths', '/*');
|
|
56
|
+
aws('cloudfront', 'wait', 'invalidation-completed', '--distribution-id', distribution, '--id', Id);
|
|
57
|
+
};
|
|
58
|
+
const listStaleKeys = () => {
|
|
59
|
+
const stale = [];
|
|
60
|
+
const seen = new Set();
|
|
61
|
+
let token;
|
|
62
|
+
do {
|
|
63
|
+
const page = awsJson('s3api', 'list-objects-v2', '--bucket', bucket, '--no-paginate', ...(token ? ['--continuation-token', token] : []));
|
|
64
|
+
for (const { Key } of page.Contents ?? []) {
|
|
65
|
+
if (!files.has(Key) && !aliases.has(Key) && !keep.some(pattern => pattern.test(Key)))
|
|
66
|
+
stale.push({ Key });
|
|
67
|
+
}
|
|
68
|
+
token = page.IsTruncated ? page.NextContinuationToken : undefined;
|
|
69
|
+
if (page.IsTruncated && (!token || seen.has(token)))
|
|
70
|
+
throw new Error('S3 object listing is incomplete');
|
|
71
|
+
if (token)
|
|
72
|
+
seen.add(token);
|
|
73
|
+
} while (token);
|
|
74
|
+
return stale;
|
|
75
|
+
};
|
|
76
|
+
if (dryRun) {
|
|
77
|
+
const stale = listStaleKeys();
|
|
78
|
+
console.log(`Dry run: ${s3} (no changes)`);
|
|
79
|
+
for (const key of files)
|
|
80
|
+
console.log(`Would upload ${JSON.stringify(key)}`);
|
|
81
|
+
for (const [alias, key] of aliases)
|
|
82
|
+
console.log(`Would copy ${JSON.stringify(key)} to ${JSON.stringify(alias)}`);
|
|
83
|
+
for (const { Key } of stale)
|
|
84
|
+
console.log(`Would delete ${JSON.stringify(Key)}`);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const expectedHomepage = verifyHomepage ? (0, node_fs_1.readFileSync)((0, node_path_1.resolve)(root, 'index.html')) : undefined;
|
|
88
|
+
const source = root.endsWith(node_path_1.sep) ? root : root + node_path_1.sep;
|
|
89
|
+
aws('s3', 'cp', source, s3, '--recursive', ...markdown.flatMap(pattern => ['--exclude', pattern]));
|
|
90
|
+
aws('s3', 'cp', source, s3, '--recursive', '--exclude', '*', ...markdown.flatMap(pattern => ['--include', pattern]), '--content-type', 'text/plain; charset=utf-8');
|
|
91
|
+
for (const [alias, key] of aliases) {
|
|
92
|
+
if (alias.endsWith('/')) {
|
|
93
|
+
aws('s3api', 'copy-object', '--bucket', bucket, '--copy-source', `${bucket}/${key}`, '--key', alias);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
aws('s3', 'cp', `${s3}/${key}`, `${s3}/${alias}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
invalidate();
|
|
100
|
+
const response = exec('curl', ['--silent', '--show-error', '--max-time', '30', '--write-out', '\n%{http_code} %{content_type}', '--', url]);
|
|
101
|
+
const separator = response.lastIndexOf('\n');
|
|
102
|
+
const status = response.subarray(separator + 1).toString();
|
|
103
|
+
const body = response.subarray(0, separator);
|
|
104
|
+
if (!/^200 text\/html(?:;.*)?$/i.test(status) || !/<!doctype\s+html\b|<html\b/i.test(body.toString())) {
|
|
105
|
+
throw new Error(`Homepage health check did not return HTTP 200 with HTML (got ${status})`);
|
|
106
|
+
}
|
|
107
|
+
if (expectedHomepage && !body.equals(expectedHomepage)) {
|
|
108
|
+
throw new Error('Homepage content does not match the exported index.html');
|
|
109
|
+
}
|
|
110
|
+
const stale = listStaleKeys();
|
|
111
|
+
for (let offset = 0; offset < stale.length; offset += 20) {
|
|
112
|
+
const { Errors } = awsJson('s3api', 'delete-objects', '--bucket', bucket, '--delete', JSON.stringify({ Objects: stale.slice(offset, offset + 20) }));
|
|
113
|
+
if (Errors?.length)
|
|
114
|
+
throw new Error(`S3 object deletion failed: ${JSON.stringify(Errors)}`);
|
|
115
|
+
}
|
|
116
|
+
console.log(`Pruned ${stale.length} stale S3 objects`);
|
|
117
|
+
if (stale.length)
|
|
118
|
+
invalidate();
|
|
119
|
+
}
|
package/esm/cli.d.ts
ADDED
package/esm/cli.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { Inquirerer } from 'inquirerer';
|
|
6
|
+
import { awsEnvironment, fields, isCI, readSiteConfig, requiredFields, saveSiteConfig, validValue, validateConfig, } from './config';
|
|
7
|
+
import { deploy } from './deploy';
|
|
8
|
+
const usage = `Usage:
|
|
9
|
+
static-site-deploy deploy --site OWNER/REPO [--dir out] [--preserve PATTERN ...]
|
|
10
|
+
[--dry-run] [--trailing-slash-aliases] [--verify-homepage]
|
|
11
|
+
static-site-deploy check --site OWNER/REPO
|
|
12
|
+
static-site-deploy setup --site OWNER/REPO [--provision] [--dry-run] [--yes]
|
|
13
|
+
[--reviewer LOGIN] [--account-id ID] [--role-name NAME] [--branch main]`;
|
|
14
|
+
const interactive = !isCI(process.env) && process.stdin.isTTY && process.stdout.isTTY;
|
|
15
|
+
async function promptForConfig(site, allowPrompt) {
|
|
16
|
+
const values = readSiteConfig(site);
|
|
17
|
+
const missing = requiredFields(process.env).filter(key => !values[key]?.trim());
|
|
18
|
+
if (!allowPrompt || !missing.length)
|
|
19
|
+
return { config: validateConfig(values, process.env), prompted: false };
|
|
20
|
+
const detectedRegion = missing.includes('AWS_REGION') ? spawnSync('aws', ['configure', 'get', 'region'], {
|
|
21
|
+
encoding: 'utf8',
|
|
22
|
+
env: { ...process.env, AWS_PROFILE: values.AWS_PROFILE ?? 'default' },
|
|
23
|
+
}).stdout?.trim() : undefined;
|
|
24
|
+
const prompter = new Inquirerer();
|
|
25
|
+
try {
|
|
26
|
+
const answers = await prompter.prompt({}, missing.map(key => ({
|
|
27
|
+
type: 'text',
|
|
28
|
+
name: key,
|
|
29
|
+
message: fields[key].label,
|
|
30
|
+
required: true,
|
|
31
|
+
...(key === 'AWS_PROFILE' ? { default: 'default' } : {}),
|
|
32
|
+
...(key === 'AWS_REGION' && detectedRegion ? { default: detectedRegion } : {}),
|
|
33
|
+
validate: (input) => validValue(key, input) ? { success: true } : {
|
|
34
|
+
success: false, reason: `Enter a valid ${fields[key].label}.`,
|
|
35
|
+
},
|
|
36
|
+
})));
|
|
37
|
+
return { config: validateConfig({ ...values, ...answers }, process.env), prompted: true };
|
|
38
|
+
}
|
|
39
|
+
finally {
|
|
40
|
+
prompter.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function runProvisioner(site, config, provision, dryRun) {
|
|
44
|
+
const { AWS_PROFILE: _profile, ...targets } = config;
|
|
45
|
+
const result = spawnSync('bash', [join(__dirname, 'provision.sh'), ...(dryRun ? ['--dry-run'] : [])], {
|
|
46
|
+
env: { ...awsEnvironment(config), ...targets, ...provision, SITE_REPO: site },
|
|
47
|
+
stdio: 'inherit',
|
|
48
|
+
});
|
|
49
|
+
if (result.error)
|
|
50
|
+
throw result.error;
|
|
51
|
+
if (result.status !== 0)
|
|
52
|
+
process.exitCode = result.status ?? 1;
|
|
53
|
+
}
|
|
54
|
+
async function main() {
|
|
55
|
+
const { values: options, positionals } = parseArgs({
|
|
56
|
+
allowPositionals: true,
|
|
57
|
+
options: {
|
|
58
|
+
site: { type: 'string' },
|
|
59
|
+
dir: { type: 'string' },
|
|
60
|
+
preserve: { type: 'string', multiple: true },
|
|
61
|
+
'trailing-slash-aliases': { type: 'boolean' },
|
|
62
|
+
'verify-homepage': { type: 'boolean' },
|
|
63
|
+
provision: { type: 'boolean' },
|
|
64
|
+
'dry-run': { type: 'boolean' },
|
|
65
|
+
yes: { type: 'boolean' },
|
|
66
|
+
reviewer: { type: 'string' },
|
|
67
|
+
'account-id': { type: 'string' },
|
|
68
|
+
'role-name': { type: 'string' },
|
|
69
|
+
branch: { type: 'string' },
|
|
70
|
+
help: { type: 'boolean' },
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
if (options.help)
|
|
74
|
+
return console.log(usage);
|
|
75
|
+
const [command] = positionals;
|
|
76
|
+
if (positionals.length !== 1 || !['deploy', 'setup', 'check'].includes(command))
|
|
77
|
+
throw new Error(usage);
|
|
78
|
+
const site = options.site ?? process.env.GITHUB_REPOSITORY;
|
|
79
|
+
if (!site)
|
|
80
|
+
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
81
|
+
if (command !== 'setup' && (options.provision || options.yes ||
|
|
82
|
+
options.reviewer || options['account-id'] || options['role-name'] || options.branch))
|
|
83
|
+
throw new Error(usage);
|
|
84
|
+
if (command !== 'deploy' && (options.dir || options.preserve ||
|
|
85
|
+
options['trailing-slash-aliases'] || options['verify-homepage']))
|
|
86
|
+
throw new Error(usage);
|
|
87
|
+
if (command === 'check' && options['dry-run'])
|
|
88
|
+
throw new Error(usage);
|
|
89
|
+
const allowPrompt = interactive && !options.yes && command !== 'check';
|
|
90
|
+
const dryRun = !!options['dry-run'];
|
|
91
|
+
if (command === 'setup' && !dryRun) {
|
|
92
|
+
if (isCI(process.env))
|
|
93
|
+
throw new Error('Run interactive setup outside CI; use environment variables to deploy in CI.');
|
|
94
|
+
if (options.provision && !allowPrompt && !options.yes) {
|
|
95
|
+
throw new Error('Unattended cloud provisioning requires --provision --yes.');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const { config, prompted } = await promptForConfig(site, allowPrompt);
|
|
99
|
+
if (command === 'check')
|
|
100
|
+
return;
|
|
101
|
+
if (command === 'deploy') {
|
|
102
|
+
if (prompted && !dryRun)
|
|
103
|
+
saveSiteConfig(site, config);
|
|
104
|
+
return deploy(config, {
|
|
105
|
+
directory: options.dir ?? 'out',
|
|
106
|
+
preserve: options.preserve,
|
|
107
|
+
dryRun,
|
|
108
|
+
trailingSlashAliases: options['trailing-slash-aliases'],
|
|
109
|
+
verifyHomepage: options['verify-homepage'],
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
if (!dryRun) {
|
|
113
|
+
saveSiteConfig(site, config);
|
|
114
|
+
console.log(`Saved local deploy settings for ${site}. No AWS credentials were stored.`);
|
|
115
|
+
}
|
|
116
|
+
const provision = {
|
|
117
|
+
SITE_REVIEWER: options.reviewer ?? process.env.SITE_REVIEWER,
|
|
118
|
+
AWS_ACCOUNT_ID: options['account-id'] ?? process.env.AWS_ACCOUNT_ID,
|
|
119
|
+
AWS_DEPLOY_ROLE_NAME: options['role-name'] ?? process.env.AWS_DEPLOY_ROLE_NAME,
|
|
120
|
+
SITE_BRANCH: options.branch ?? 'main',
|
|
121
|
+
};
|
|
122
|
+
if (!allowPrompt) {
|
|
123
|
+
if (!options.provision && !dryRun)
|
|
124
|
+
return;
|
|
125
|
+
return runProvisioner(site, config, provision, dryRun);
|
|
126
|
+
}
|
|
127
|
+
const prompter = new Inquirerer();
|
|
128
|
+
try {
|
|
129
|
+
if (!dryRun && !options.provision) {
|
|
130
|
+
const { configure } = await prompter.prompt({}, [{
|
|
131
|
+
type: 'confirm', name: 'configure', message: 'Set up AWS OIDC and the GitHub production approval gate?', default: false,
|
|
132
|
+
}]);
|
|
133
|
+
if (!configure)
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const questions = [
|
|
137
|
+
{ name: 'SITE_REVIEWER', message: 'Required GitHub reviewer (login)' },
|
|
138
|
+
{ name: 'AWS_ACCOUNT_ID', message: 'AWS account ID' },
|
|
139
|
+
{ name: 'AWS_DEPLOY_ROLE_NAME', message: 'Dedicated IAM deploy role name' },
|
|
140
|
+
].filter(question => provision[question.name] === undefined);
|
|
141
|
+
const answers = questions.length ? await prompter.prompt({}, questions.map(question => ({
|
|
142
|
+
...question,
|
|
143
|
+
type: 'text',
|
|
144
|
+
required: true,
|
|
145
|
+
}))) : {};
|
|
146
|
+
const { apply } = dryRun ? { apply: true } : await prompter.prompt({}, [{
|
|
147
|
+
type: 'confirm',
|
|
148
|
+
name: 'apply',
|
|
149
|
+
message: `Apply AWS and GitHub changes for ${site} on ${provision.SITE_BRANCH}? (Does not deploy)`,
|
|
150
|
+
default: false,
|
|
151
|
+
}]);
|
|
152
|
+
if (apply)
|
|
153
|
+
runProvisioner(site, config, { ...provision, ...answers }, dryRun);
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
prompter.close();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
main().catch(error => {
|
|
160
|
+
console.error(error instanceof Error ? error.message : error);
|
|
161
|
+
process.exitCode = 1;
|
|
162
|
+
});
|
package/esm/config.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export declare const fields: {
|
|
2
|
+
readonly AWS_S3_BUCKET: {
|
|
3
|
+
readonly label: "S3 bucket";
|
|
4
|
+
readonly pattern: RegExp;
|
|
5
|
+
};
|
|
6
|
+
readonly AWS_CLOUDFRONT_DISTRIBUTION_ID: {
|
|
7
|
+
readonly label: "CloudFront distribution ID";
|
|
8
|
+
readonly pattern: RegExp;
|
|
9
|
+
};
|
|
10
|
+
readonly SITE_URL: {
|
|
11
|
+
readonly label: "HTTPS homepage URL";
|
|
12
|
+
readonly pattern: RegExp;
|
|
13
|
+
};
|
|
14
|
+
readonly AWS_REGION: {
|
|
15
|
+
readonly label: "AWS region";
|
|
16
|
+
readonly pattern: RegExp;
|
|
17
|
+
};
|
|
18
|
+
readonly AWS_PROFILE: {
|
|
19
|
+
readonly label: "AWS CLI profile";
|
|
20
|
+
readonly pattern: RegExp;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
type ConfigKey = keyof typeof fields;
|
|
24
|
+
type ConfigValues = Partial<Record<ConfigKey, string>>;
|
|
25
|
+
export type SiteConfig = Required<Omit<ConfigValues, 'AWS_PROFILE'>> & Pick<ConfigValues, 'AWS_PROFILE'>;
|
|
26
|
+
type Environment = NodeJS.ProcessEnv;
|
|
27
|
+
export declare function siteKey(site: string): string;
|
|
28
|
+
export declare function isCI(environment: Environment): boolean;
|
|
29
|
+
export declare function requiredFields(environment: Environment): ConfigKey[];
|
|
30
|
+
export declare function validValue(key: ConfigKey, raw?: string): boolean;
|
|
31
|
+
export declare function validateConfig(values: ConfigValues, environment: Environment): SiteConfig;
|
|
32
|
+
export declare function readSiteConfig(site: string, environment?: NodeJS.ProcessEnv): ConfigValues;
|
|
33
|
+
export declare function saveSiteConfig(site: string, values: SiteConfig): void;
|
|
34
|
+
export declare function awsEnvironment(config: SiteConfig, environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
35
|
+
export {};
|
package/esm/config.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { env, makeValidator, required } from '12factor-env';
|
|
2
|
+
import { createConfigStore } from 'appstash';
|
|
3
|
+
const storeName = 'static-site-deploy';
|
|
4
|
+
const storeKey = 'deploy';
|
|
5
|
+
export const fields = {
|
|
6
|
+
AWS_S3_BUCKET: { label: 'S3 bucket', pattern: /^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/ },
|
|
7
|
+
AWS_CLOUDFRONT_DISTRIBUTION_ID: { label: 'CloudFront distribution ID', pattern: /^[A-Z0-9]+$/ },
|
|
8
|
+
SITE_URL: { label: 'HTTPS homepage URL', pattern: /^https:\/\/[^/\s]+[^\s]*$/ },
|
|
9
|
+
AWS_REGION: { label: 'AWS region', pattern: /^[a-z]{2}(-[a-z0-9]+)+-[0-9]+$/ },
|
|
10
|
+
AWS_PROFILE: { label: 'AWS CLI profile', pattern: /\S/ },
|
|
11
|
+
};
|
|
12
|
+
const keys = Object.keys(fields);
|
|
13
|
+
export function siteKey(site) {
|
|
14
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+$/.test(site) || /\/\.{1,2}$/.test(site)) {
|
|
15
|
+
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
16
|
+
}
|
|
17
|
+
return encodeURIComponent(site.toLowerCase());
|
|
18
|
+
}
|
|
19
|
+
export function isCI(environment) {
|
|
20
|
+
return environment.GITHUB_ACTIONS === 'true' ||
|
|
21
|
+
!!(environment.CI && !/^(false|0)$/i.test(environment.CI));
|
|
22
|
+
}
|
|
23
|
+
export function requiredFields(environment) {
|
|
24
|
+
return keys.filter(key => key !== 'AWS_PROFILE' || (!isCI(environment) && !(environment.AWS_ACCESS_KEY_ID && environment.AWS_SECRET_ACCESS_KEY)));
|
|
25
|
+
}
|
|
26
|
+
export function validValue(key, raw) {
|
|
27
|
+
if (typeof raw !== 'string' || !fields[key].pattern.test(raw.trim()))
|
|
28
|
+
return false;
|
|
29
|
+
if (key !== 'SITE_URL')
|
|
30
|
+
return true;
|
|
31
|
+
try {
|
|
32
|
+
const url = new URL(raw.trim());
|
|
33
|
+
return !url.username && !url.password;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export function validateConfig(values, environment) {
|
|
40
|
+
const validator = (key) => required(makeValidator(value => {
|
|
41
|
+
if (!validValue(key, value))
|
|
42
|
+
throw new Error(`must be a valid ${fields[key].label}`);
|
|
43
|
+
return value.trim();
|
|
44
|
+
}));
|
|
45
|
+
return { ...env(values, {}, {
|
|
46
|
+
AWS_S3_BUCKET: validator('AWS_S3_BUCKET'),
|
|
47
|
+
AWS_CLOUDFRONT_DISTRIBUTION_ID: validator('AWS_CLOUDFRONT_DISTRIBUTION_ID'),
|
|
48
|
+
SITE_URL: validator('SITE_URL'),
|
|
49
|
+
AWS_REGION: validator('AWS_REGION'),
|
|
50
|
+
...(requiredFields(environment).includes('AWS_PROFILE') || (!isCI(environment) && validValue('AWS_PROFILE', values.AWS_PROFILE))
|
|
51
|
+
? { AWS_PROFILE: validator('AWS_PROFILE') } : {}),
|
|
52
|
+
}) };
|
|
53
|
+
}
|
|
54
|
+
export function readSiteConfig(site, environment = process.env) {
|
|
55
|
+
const context = siteKey(site);
|
|
56
|
+
const overrides = {
|
|
57
|
+
...environment,
|
|
58
|
+
AWS_PROFILE: environment.AWS_PROFILE ?? environment.AWS_DEFAULT_PROFILE,
|
|
59
|
+
AWS_REGION: environment.AWS_REGION ?? environment.AWS_DEFAULT_REGION,
|
|
60
|
+
};
|
|
61
|
+
const populated = Object.fromEntries(keys.flatMap(key => overrides[key] === undefined ? [] : [[key, overrides[key]]]));
|
|
62
|
+
if (isCI(environment) || requiredFields(environment).every(key => overrides[key] !== undefined))
|
|
63
|
+
return populated;
|
|
64
|
+
const stored = createConfigStore(storeName).getVar(storeKey, context);
|
|
65
|
+
return { ...(stored ? JSON.parse(stored) : {}), ...populated };
|
|
66
|
+
}
|
|
67
|
+
export function saveSiteConfig(site, values) {
|
|
68
|
+
const context = siteKey(site);
|
|
69
|
+
const store = createConfigStore(storeName);
|
|
70
|
+
const config = Object.fromEntries(keys.flatMap(key => validValue(key, values[key]) ? [[key, values[key].trim()]] : []));
|
|
71
|
+
if (config.AWS_PROFILE === undefined) {
|
|
72
|
+
const stored = store.getVar(storeKey, context);
|
|
73
|
+
const profile = stored ? JSON.parse(stored).AWS_PROFILE : undefined;
|
|
74
|
+
if (validValue('AWS_PROFILE', profile))
|
|
75
|
+
config.AWS_PROFILE = profile.trim();
|
|
76
|
+
}
|
|
77
|
+
store.setVar(storeKey, JSON.stringify(config), context);
|
|
78
|
+
}
|
|
79
|
+
export function awsEnvironment(config, environment = process.env) {
|
|
80
|
+
const result = { ...environment, AWS_REGION: config.AWS_REGION, AWS_DEFAULT_REGION: config.AWS_REGION };
|
|
81
|
+
delete result.AWS_PROFILE;
|
|
82
|
+
delete result.AWS_DEFAULT_PROFILE;
|
|
83
|
+
if (config.AWS_PROFILE && requiredFields(environment).includes('AWS_PROFILE'))
|
|
84
|
+
result.AWS_PROFILE = config.AWS_PROFILE;
|
|
85
|
+
return result;
|
|
86
|
+
}
|
package/esm/deploy.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SiteConfig } from './config';
|
|
2
|
+
type Options = {
|
|
3
|
+
directory: string;
|
|
4
|
+
preserve?: string[];
|
|
5
|
+
dryRun?: boolean;
|
|
6
|
+
trailingSlashAliases?: boolean;
|
|
7
|
+
verifyHomepage?: boolean;
|
|
8
|
+
};
|
|
9
|
+
export declare function deploy(config: SiteConfig, { directory, preserve, dryRun, trailingSlashAliases, verifyHomepage, }: Options): void;
|
|
10
|
+
export {};
|
package/esm/deploy.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { resolve, sep } from 'node:path';
|
|
4
|
+
import { awsEnvironment } from './config';
|
|
5
|
+
const markdown = ['*.md', 'llms.txt'];
|
|
6
|
+
const globRegex = (pattern) => new RegExp(`^${pattern.split('*').map(part => part.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')).join('.*')}$`);
|
|
7
|
+
function* exportKeys(root, prefix = '') {
|
|
8
|
+
for (const entry of readdirSync(resolve(root, prefix), { withFileTypes: true })) {
|
|
9
|
+
const key = prefix + entry.name;
|
|
10
|
+
if (entry.isDirectory())
|
|
11
|
+
yield* exportKeys(root, `${key}/`);
|
|
12
|
+
else if (entry.isFile())
|
|
13
|
+
yield key;
|
|
14
|
+
else
|
|
15
|
+
throw new Error(`Unexpected non-regular file in site export: ${key}`);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function deploy(config, { directory, preserve = markdown, dryRun, trailingSlashAliases, verifyHomepage, }) {
|
|
19
|
+
const root = resolve(directory);
|
|
20
|
+
const files = new Set(exportKeys(root));
|
|
21
|
+
if (!files.has('index.html'))
|
|
22
|
+
throw new Error(`Site export is missing ${directory}/index.html`);
|
|
23
|
+
const aliases = new Map();
|
|
24
|
+
for (const key of files) {
|
|
25
|
+
if (!key.endsWith('.html') || key === 'index.html')
|
|
26
|
+
continue;
|
|
27
|
+
const directoryIndex = key.endsWith('/index.html');
|
|
28
|
+
const alias = key.slice(0, directoryIndex ? -'/index.html'.length : -'.html'.length);
|
|
29
|
+
if (files.has(alias))
|
|
30
|
+
throw new Error(`Conflicting extensionless route: ${alias}`);
|
|
31
|
+
if (directoryIndex || !aliases.has(alias))
|
|
32
|
+
aliases.set(alias, key);
|
|
33
|
+
if (directoryIndex && trailingSlashAliases)
|
|
34
|
+
aliases.set(`${alias}/`, key);
|
|
35
|
+
}
|
|
36
|
+
const keep = preserve.map(globRegex);
|
|
37
|
+
const { AWS_S3_BUCKET: bucket, AWS_CLOUDFRONT_DISTRIBUTION_ID: distribution, SITE_URL: url } = config;
|
|
38
|
+
const s3 = `s3://${bucket}`;
|
|
39
|
+
const environment = awsEnvironment(config);
|
|
40
|
+
const exec = (command, args, env) => execFileSync(command, args, {
|
|
41
|
+
env, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 4 * 1024 * 1024,
|
|
42
|
+
});
|
|
43
|
+
const aws = (...args) => {
|
|
44
|
+
const result = spawnSync('aws', args, { env: environment, stdio: 'inherit' });
|
|
45
|
+
if (result.error)
|
|
46
|
+
throw result.error;
|
|
47
|
+
if (result.status !== 0)
|
|
48
|
+
throw new Error(`AWS ${args.slice(0, 2).join(' ')} failed (${result.status ?? result.signal})`);
|
|
49
|
+
};
|
|
50
|
+
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment).toString());
|
|
51
|
+
const invalidate = () => {
|
|
52
|
+
const { Invalidation: { Id } } = awsJson('cloudfront', 'create-invalidation', '--distribution-id', distribution, '--paths', '/*');
|
|
53
|
+
aws('cloudfront', 'wait', 'invalidation-completed', '--distribution-id', distribution, '--id', Id);
|
|
54
|
+
};
|
|
55
|
+
const listStaleKeys = () => {
|
|
56
|
+
const stale = [];
|
|
57
|
+
const seen = new Set();
|
|
58
|
+
let token;
|
|
59
|
+
do {
|
|
60
|
+
const page = awsJson('s3api', 'list-objects-v2', '--bucket', bucket, '--no-paginate', ...(token ? ['--continuation-token', token] : []));
|
|
61
|
+
for (const { Key } of page.Contents ?? []) {
|
|
62
|
+
if (!files.has(Key) && !aliases.has(Key) && !keep.some(pattern => pattern.test(Key)))
|
|
63
|
+
stale.push({ Key });
|
|
64
|
+
}
|
|
65
|
+
token = page.IsTruncated ? page.NextContinuationToken : undefined;
|
|
66
|
+
if (page.IsTruncated && (!token || seen.has(token)))
|
|
67
|
+
throw new Error('S3 object listing is incomplete');
|
|
68
|
+
if (token)
|
|
69
|
+
seen.add(token);
|
|
70
|
+
} while (token);
|
|
71
|
+
return stale;
|
|
72
|
+
};
|
|
73
|
+
if (dryRun) {
|
|
74
|
+
const stale = listStaleKeys();
|
|
75
|
+
console.log(`Dry run: ${s3} (no changes)`);
|
|
76
|
+
for (const key of files)
|
|
77
|
+
console.log(`Would upload ${JSON.stringify(key)}`);
|
|
78
|
+
for (const [alias, key] of aliases)
|
|
79
|
+
console.log(`Would copy ${JSON.stringify(key)} to ${JSON.stringify(alias)}`);
|
|
80
|
+
for (const { Key } of stale)
|
|
81
|
+
console.log(`Would delete ${JSON.stringify(Key)}`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const expectedHomepage = verifyHomepage ? readFileSync(resolve(root, 'index.html')) : undefined;
|
|
85
|
+
const source = root.endsWith(sep) ? root : root + sep;
|
|
86
|
+
aws('s3', 'cp', source, s3, '--recursive', ...markdown.flatMap(pattern => ['--exclude', pattern]));
|
|
87
|
+
aws('s3', 'cp', source, s3, '--recursive', '--exclude', '*', ...markdown.flatMap(pattern => ['--include', pattern]), '--content-type', 'text/plain; charset=utf-8');
|
|
88
|
+
for (const [alias, key] of aliases) {
|
|
89
|
+
if (alias.endsWith('/')) {
|
|
90
|
+
aws('s3api', 'copy-object', '--bucket', bucket, '--copy-source', `${bucket}/${key}`, '--key', alias);
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
aws('s3', 'cp', `${s3}/${key}`, `${s3}/${alias}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
invalidate();
|
|
97
|
+
const response = exec('curl', ['--silent', '--show-error', '--max-time', '30', '--write-out', '\n%{http_code} %{content_type}', '--', url]);
|
|
98
|
+
const separator = response.lastIndexOf('\n');
|
|
99
|
+
const status = response.subarray(separator + 1).toString();
|
|
100
|
+
const body = response.subarray(0, separator);
|
|
101
|
+
if (!/^200 text\/html(?:;.*)?$/i.test(status) || !/<!doctype\s+html\b|<html\b/i.test(body.toString())) {
|
|
102
|
+
throw new Error(`Homepage health check did not return HTTP 200 with HTML (got ${status})`);
|
|
103
|
+
}
|
|
104
|
+
if (expectedHomepage && !body.equals(expectedHomepage)) {
|
|
105
|
+
throw new Error('Homepage content does not match the exported index.html');
|
|
106
|
+
}
|
|
107
|
+
const stale = listStaleKeys();
|
|
108
|
+
for (let offset = 0; offset < stale.length; offset += 20) {
|
|
109
|
+
const { Errors } = awsJson('s3api', 'delete-objects', '--bucket', bucket, '--delete', JSON.stringify({ Objects: stale.slice(offset, offset + 20) }));
|
|
110
|
+
if (Errors?.length)
|
|
111
|
+
throw new Error(`S3 object deletion failed: ${JSON.stringify(Errors)}`);
|
|
112
|
+
}
|
|
113
|
+
console.log(`Pruned ${stale.length} stale S3 objects`);
|
|
114
|
+
if (stale.length)
|
|
115
|
+
invalidate();
|
|
116
|
+
}
|
package/esm/index.d.ts
ADDED
package/esm/index.js
ADDED
package/index.d.ts
ADDED
package/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.saveSiteConfig = exports.readSiteConfig = exports.deploy = void 0;
|
|
4
|
+
var deploy_1 = require("./deploy");
|
|
5
|
+
Object.defineProperty(exports, "deploy", { enumerable: true, get: function () { return deploy_1.deploy; } });
|
|
6
|
+
var config_1 = require("./config");
|
|
7
|
+
Object.defineProperty(exports, "readSiteConfig", { enumerable: true, get: function () { return config_1.readSiteConfig; } });
|
|
8
|
+
Object.defineProperty(exports, "saveSiteConfig", { enumerable: true, get: function () { return config_1.saveSiteConfig; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@constructive-io/static-site-deploy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"author": "Constructive <developers@constructive.io>",
|
|
5
|
+
"description": "Deploy a static site to S3 and CloudFront with optional GitHub OIDC setup",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"bin": {
|
|
10
|
+
"static-site-deploy": "cli.js"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/constructive-io/dev-utils",
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"publishConfig": {
|
|
15
|
+
"access": "public",
|
|
16
|
+
"directory": "dist"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/constructive-io/dev-utils"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"12factor-env": "1.34.0",
|
|
24
|
+
"appstash": "0.8.1",
|
|
25
|
+
"inquirerer": "4.9.5"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"makage": "0.1.10"
|
|
29
|
+
},
|
|
30
|
+
"scripts": {
|
|
31
|
+
"copy": "makage assets",
|
|
32
|
+
"clean": "makage clean",
|
|
33
|
+
"build": "makage build && makage copy src/provision.sh dist --flat",
|
|
34
|
+
"test": "jest"
|
|
35
|
+
}
|
|
6
36
|
}
|
package/provision.sh
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
|
|
3
|
+
set -euo pipefail
|
|
4
|
+
|
|
5
|
+
fail() {
|
|
6
|
+
printf '%s\n' "$*" >&2
|
|
7
|
+
exit 1
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
dry_run=false
|
|
11
|
+
case "${1-}:$#" in
|
|
12
|
+
:0) ;;
|
|
13
|
+
--dry-run:1) dry_run=true ;;
|
|
14
|
+
*) fail "Usage: static-site-deploy setup --site OWNER/REPO [--provision] [--dry-run]" ;;
|
|
15
|
+
esac
|
|
16
|
+
|
|
17
|
+
for name in SITE_REPO SITE_REVIEWER SITE_BRANCH AWS_ACCOUNT_ID AWS_DEPLOY_ROLE_NAME AWS_REGION AWS_S3_BUCKET AWS_CLOUDFRONT_DISTRIBUTION_ID SITE_URL; do
|
|
18
|
+
[[ ${!name-} =~ [^[:space:]] ]] || fail "Set $name before running this script."
|
|
19
|
+
done
|
|
20
|
+
[[ $AWS_ACCOUNT_ID =~ ^[0-9]{12}$ ]] || fail "AWS_ACCOUNT_ID must be a 12-digit AWS account ID."
|
|
21
|
+
[[ $AWS_DEPLOY_ROLE_NAME =~ ^[A-Za-z0-9_+=,.@-]{1,64}$ ]] || fail "AWS_DEPLOY_ROLE_NAME must be a valid IAM role name."
|
|
22
|
+
[[ $AWS_S3_BUCKET =~ ^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$ ]] || fail "AWS_S3_BUCKET must be a bucket name, without s3://."
|
|
23
|
+
[[ $AWS_CLOUDFRONT_DISTRIBUTION_ID =~ ^[A-Z0-9]+$ ]] || fail "AWS_CLOUDFRONT_DISTRIBUTION_ID must be a distribution ID."
|
|
24
|
+
[[ $AWS_REGION =~ ^[a-z]{2}(-[a-z0-9]+)+-[0-9]+$ ]] || fail "AWS_REGION must be an AWS region."
|
|
25
|
+
[[ $SITE_URL =~ ^https://[^/[:space:]]+[^[:space:]]*$ ]] || fail "SITE_URL must be the HTTPS homepage URL."
|
|
26
|
+
|
|
27
|
+
command -v jq >/dev/null || fail "Install jq first."
|
|
28
|
+
if ! $dry_run; then
|
|
29
|
+
command -v aws >/dev/null || fail "Install AWS CLI v2 first."
|
|
30
|
+
command -v gh >/dev/null || fail "Install GitHub CLI first."
|
|
31
|
+
[[ $(aws --version) == aws-cli/2.* ]] || fail "Install AWS CLI v2 first."
|
|
32
|
+
fi
|
|
33
|
+
export AWS_PAGER="" GH_PROMPT_DISABLED=1
|
|
34
|
+
|
|
35
|
+
[[ $SITE_REPO =~ ^[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9_.-]+$ && $SITE_REPO != */. && $SITE_REPO != */.. ]] || fail "Expected OWNER/REPO."
|
|
36
|
+
[[ $SITE_REVIEWER =~ ^[A-Za-z0-9][A-Za-z0-9-]*$ ]] || fail "Expected a GitHub username."
|
|
37
|
+
[[ $SITE_BRANCH =~ ^[A-Za-z0-9][A-Za-z0-9._/-]*$ ]] || fail "Expected a deployment branch name."
|
|
38
|
+
issuer=token.actions.githubusercontent.com
|
|
39
|
+
audience=sts.amazonaws.com
|
|
40
|
+
provider=arn:aws:iam::$AWS_ACCOUNT_ID:oidc-provider/$issuer
|
|
41
|
+
policy_name=SiteDeploy
|
|
42
|
+
|
|
43
|
+
exec 3>&1
|
|
44
|
+
print_command() {
|
|
45
|
+
printf '%q ' "$@" >&3
|
|
46
|
+
printf '\n' >&3
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
run() {
|
|
50
|
+
if $dry_run; then print_command "$@"; else "$@"; fi
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
read_state() {
|
|
54
|
+
local example=$1
|
|
55
|
+
shift
|
|
56
|
+
if $dry_run; then
|
|
57
|
+
print_command "$@"
|
|
58
|
+
printf '%s\n' "$example"
|
|
59
|
+
else
|
|
60
|
+
"$@"
|
|
61
|
+
fi
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
read_optional() {
|
|
65
|
+
local missing=$1 result
|
|
66
|
+
shift
|
|
67
|
+
if $dry_run; then
|
|
68
|
+
print_command "$@"
|
|
69
|
+
elif result=$(LC_ALL=C "$@" 2>&1); then
|
|
70
|
+
printf '%s\n' "$result"
|
|
71
|
+
elif [[ $result == *"$missing"* ]]; then
|
|
72
|
+
return 0
|
|
73
|
+
else
|
|
74
|
+
fail "$result"
|
|
75
|
+
fi
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
write_github() {
|
|
79
|
+
local method=$1 endpoint=$2 body=$3
|
|
80
|
+
if $dry_run; then
|
|
81
|
+
printf 'printf %q %q | ' '%s\n' "$body"
|
|
82
|
+
print_command gh api --method "$method" "$endpoint" --input -
|
|
83
|
+
else
|
|
84
|
+
gh api --method "$method" "$endpoint" --input - --silent <<< "$body"
|
|
85
|
+
fi
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
repo=$(read_state "$SITE_REPO" gh api "repos/$SITE_REPO" --jq .full_name)
|
|
89
|
+
environment=repos/$repo/environments/production
|
|
90
|
+
branch_policies=$environment/deployment-branch-policies
|
|
91
|
+
subject_template=repos/$repo/actions/oidc/customization/sub
|
|
92
|
+
identity=$(read_state "arn:aws:iam::$AWS_ACCOUNT_ID:root" aws sts get-caller-identity --query Arn --output text)
|
|
93
|
+
[[ $identity == arn:aws:*:"$AWS_ACCOUNT_ID":* ]] || fail "AWS credentials do not belong to account $AWS_ACCOUNT_ID in the standard AWS partition."
|
|
94
|
+
template=$(read_state '{"use_immutable_subject":false}' gh api "$subject_template")
|
|
95
|
+
jq -e '.use_immutable_subject != true' <<< "$template" >/dev/null ||
|
|
96
|
+
fail "This repository uses immutable OIDC subjects. Do not replace its template with the name-based trust policy."
|
|
97
|
+
|
|
98
|
+
reviewer=$(read_state 1 gh api "users/$SITE_REVIEWER" --jq .id)
|
|
99
|
+
[[ $reviewer =~ ^[1-9][0-9]*$ ]] || fail "Could not resolve the GitHub reviewer $SITE_REVIEWER."
|
|
100
|
+
protection=$(jq -cn --argjson id "$reviewer" '{
|
|
101
|
+
wait_timer: 0, prevent_self_review: false, reviewers: [{type: "User", id: $id}],
|
|
102
|
+
deployment_branch_policy: {protected_branches: false, custom_branch_policies: true}
|
|
103
|
+
}')
|
|
104
|
+
current=$(read_optional '(HTTP 404)' gh api "$environment")
|
|
105
|
+
if [[ -z $current ]] || ! jq -e --argjson reviewer "$reviewer" '
|
|
106
|
+
.deployment_branch_policy == {protected_branches: false, custom_branch_policies: true}
|
|
107
|
+
and ([.protection_rules[] | select(.type == "wait_timer" and .wait_timer > 0)] | length == 0)
|
|
108
|
+
and any(.protection_rules[];
|
|
109
|
+
.type == "required_reviewers" and .prevent_self_review == false
|
|
110
|
+
and ([.reviewers[] | {type, id: .reviewer.id}] == [{type: "User", id: $reviewer}]))
|
|
111
|
+
' <<< "$current" >/dev/null; then
|
|
112
|
+
write_github PUT "$environment" "$protection"
|
|
113
|
+
fi
|
|
114
|
+
|
|
115
|
+
policies=$(read_state '[{"branch_policies":[]}]' gh api --paginate --slurp "$branch_policies")
|
|
116
|
+
if ! jq -e --arg branch "$SITE_BRANCH" 'any(.[].branch_policies[]; .name == $branch and .type == "branch")' <<< "$policies" >/dev/null; then
|
|
117
|
+
write_github POST "$branch_policies" "$(jq -cn --arg branch "$SITE_BRANCH" '{name: $branch, type: "branch"}')"
|
|
118
|
+
fi
|
|
119
|
+
stale=$(jq -r --arg branch "$SITE_BRANCH" '.[].branch_policies[] | select(.name != $branch or .type != "branch") | .id' <<< "$policies")
|
|
120
|
+
for id in $stale; do
|
|
121
|
+
run gh api --method DELETE "$branch_policies/$id" --silent
|
|
122
|
+
done
|
|
123
|
+
|
|
124
|
+
protection=$(read_state '{"can_admins_bypass":false}' gh api "$environment")
|
|
125
|
+
if ! jq -e '.can_admins_bypass == false' <<< "$protection" >/dev/null; then
|
|
126
|
+
fail "In https://github.com/$repo/settings/environments, open production, uncheck 'Allow administrators to bypass configured protection rules', save, and rerun. OIDC and IAM trust have not been changed."
|
|
127
|
+
fi
|
|
128
|
+
|
|
129
|
+
provider_state=$(read_optional '(NoSuchEntity)' aws iam get-open-id-connect-provider --open-id-connect-provider-arn "$provider" --output json)
|
|
130
|
+
if [[ -z $provider_state ]]; then
|
|
131
|
+
run aws iam create-open-id-connect-provider --url "https://$issuer" --client-id-list "$audience" >/dev/null
|
|
132
|
+
elif ! jq -e --arg aud "$audience" '.ClientIDList | index($aud) != null' <<< "$provider_state" >/dev/null; then
|
|
133
|
+
run aws iam add-client-id-to-open-id-connect-provider --open-id-connect-provider-arn "$provider" --client-id "$audience"
|
|
134
|
+
fi
|
|
135
|
+
|
|
136
|
+
trust=$(jq -cn --arg provider "$provider" --arg aud "$audience" --arg sub "repo:$repo:environment:production:ref:refs/heads/$SITE_BRANCH" '{
|
|
137
|
+
Version: "2012-10-17", Statement: [{
|
|
138
|
+
Effect: "Allow", Principal: {Federated: $provider}, Action: "sts:AssumeRoleWithWebIdentity",
|
|
139
|
+
Condition: {StringEquals: {"token.actions.githubusercontent.com:aud": $aud, "token.actions.githubusercontent.com:sub": $sub}}
|
|
140
|
+
}]
|
|
141
|
+
}')
|
|
142
|
+
permissions=$(jq -cn --arg bucket "arn:aws:s3:::$AWS_S3_BUCKET" \
|
|
143
|
+
--arg dist "arn:aws:cloudfront::$AWS_ACCOUNT_ID:distribution/$AWS_CLOUDFRONT_DISTRIBUTION_ID" '{
|
|
144
|
+
Version: "2012-10-17", Statement: [
|
|
145
|
+
{Effect: "Allow", Action: "s3:ListBucket", Resource: $bucket},
|
|
146
|
+
{Effect: "Allow", Action: ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], Resource: ($bucket + "/*")},
|
|
147
|
+
{Effect: "Allow", Action: ["cloudfront:CreateInvalidation", "cloudfront:GetInvalidation"], Resource: $dist}
|
|
148
|
+
]
|
|
149
|
+
}')
|
|
150
|
+
role=$(read_optional '(NoSuchEntity)' aws iam get-role --role-name "$AWS_DEPLOY_ROLE_NAME" --output json)
|
|
151
|
+
if [[ -z $role ]]; then
|
|
152
|
+
role_arn=$(read_state "arn:aws:iam::$AWS_ACCOUNT_ID:role/$AWS_DEPLOY_ROLE_NAME" \
|
|
153
|
+
aws iam create-role --role-name "$AWS_DEPLOY_ROLE_NAME" --assume-role-policy-document "$trust" --query Role.Arn --output text)
|
|
154
|
+
else
|
|
155
|
+
role_arn=$(jq -er '.Role.Arn' <<< "$role")
|
|
156
|
+
attached=$(aws iam list-attached-role-policies --role-name "$AWS_DEPLOY_ROLE_NAME" --output json)
|
|
157
|
+
inline=$(aws iam list-role-policies --role-name "$AWS_DEPLOY_ROLE_NAME" --output json)
|
|
158
|
+
if ! jq -e '.AttachedPolicies == []' <<< "$attached" >/dev/null ||
|
|
159
|
+
! jq -e --arg policy "$policy_name" '(.PolicyNames - [$policy]) == []' <<< "$inline" >/dev/null; then
|
|
160
|
+
fail "Use a dedicated deploy role without unrelated policies: $AWS_DEPLOY_ROLE_NAME has other policies."
|
|
161
|
+
fi
|
|
162
|
+
run aws iam update-assume-role-policy --role-name "$AWS_DEPLOY_ROLE_NAME" --policy-document "$trust"
|
|
163
|
+
fi
|
|
164
|
+
run aws iam put-role-policy --role-name "$AWS_DEPLOY_ROLE_NAME" --policy-name "$policy_name" --policy-document "$permissions"
|
|
165
|
+
write_github PUT "$subject_template" '{"use_default":false,"include_claim_keys":["repo","context","ref"]}'
|
|
166
|
+
|
|
167
|
+
for name in AWS_S3_BUCKET AWS_CLOUDFRONT_DISTRIBUTION_ID SITE_URL AWS_REGION; do
|
|
168
|
+
run gh variable set "$name" --repo "$repo" --env production --body "${!name}"
|
|
169
|
+
done
|
|
170
|
+
run gh variable set AWS_DEPLOY_ROLE_ARN --repo "$repo" --env production --body "$role_arn"
|
|
171
|
+
|
|
172
|
+
if ! $dry_run; then
|
|
173
|
+
printf '%s\n' "Production setup complete. No deploy was started."
|
|
174
|
+
fi
|