@constructive-io/static-site-deploy 0.1.1 → 0.3.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/README.md +7 -1
- package/cli.js +16 -4
- package/deploy.d.ts +4 -1
- package/deploy.js +50 -22
- package/esm/cli.js +16 -4
- package/esm/deploy.d.ts +4 -1
- package/esm/deploy.js +51 -23
- package/package.json +8 -10
- package/provision.sh +11 -4
package/README.md
CHANGED
|
@@ -20,6 +20,12 @@ Deploy uploads the export, refreshes extensionless aliases, and waits for CloudF
|
|
|
20
20
|
|
|
21
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
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
|
+
|
|
23
29
|
## GitHub Actions and AWS OIDC
|
|
24
30
|
|
|
25
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.
|
|
@@ -31,7 +37,7 @@ pnpm exec static-site-deploy setup --site OWNER/REPO --provision --reviewer LOGI
|
|
|
31
37
|
|
|
32
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.
|
|
33
39
|
|
|
34
|
-
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.
|
|
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. 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.
|
|
35
41
|
|
|
36
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.
|
|
37
43
|
|
package/cli.js
CHANGED
|
@@ -9,6 +9,7 @@ const config_1 = require("./config");
|
|
|
9
9
|
const deploy_1 = require("./deploy");
|
|
10
10
|
const usage = `Usage:
|
|
11
11
|
static-site-deploy deploy --site OWNER/REPO [--dir out] [--preserve PATTERN ...]
|
|
12
|
+
[--dry-run] [--trailing-slash-aliases] [--verify-homepage]
|
|
12
13
|
static-site-deploy check --site OWNER/REPO
|
|
13
14
|
static-site-deploy setup --site OWNER/REPO [--provision] [--dry-run] [--yes]
|
|
14
15
|
[--reviewer LOGIN] [--account-id ID] [--role-name NAME] [--branch main]`;
|
|
@@ -59,6 +60,8 @@ async function main() {
|
|
|
59
60
|
site: { type: 'string' },
|
|
60
61
|
dir: { type: 'string' },
|
|
61
62
|
preserve: { type: 'string', multiple: true },
|
|
63
|
+
'trailing-slash-aliases': { type: 'boolean' },
|
|
64
|
+
'verify-homepage': { type: 'boolean' },
|
|
62
65
|
provision: { type: 'boolean' },
|
|
63
66
|
'dry-run': { type: 'boolean' },
|
|
64
67
|
yes: { type: 'boolean' },
|
|
@@ -77,10 +80,13 @@ async function main() {
|
|
|
77
80
|
const site = options.site ?? process.env.GITHUB_REPOSITORY;
|
|
78
81
|
if (!site)
|
|
79
82
|
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
80
|
-
if (command !== 'setup' && (options.provision || options
|
|
83
|
+
if (command !== 'setup' && (options.provision || options.yes ||
|
|
81
84
|
options.reviewer || options['account-id'] || options['role-name'] || options.branch))
|
|
82
85
|
throw new Error(usage);
|
|
83
|
-
if (command !== 'deploy' && (options.dir || options.preserve
|
|
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'])
|
|
84
90
|
throw new Error(usage);
|
|
85
91
|
const allowPrompt = interactive && !options.yes && command !== 'check';
|
|
86
92
|
const dryRun = !!options['dry-run'];
|
|
@@ -95,9 +101,15 @@ async function main() {
|
|
|
95
101
|
if (command === 'check')
|
|
96
102
|
return;
|
|
97
103
|
if (command === 'deploy') {
|
|
98
|
-
if (prompted)
|
|
104
|
+
if (prompted && !dryRun)
|
|
99
105
|
(0, config_1.saveSiteConfig)(site, config);
|
|
100
|
-
return (0, deploy_1.deploy)(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
|
+
});
|
|
101
113
|
}
|
|
102
114
|
if (!dryRun) {
|
|
103
115
|
(0, config_1.saveSiteConfig)(site, config);
|
package/deploy.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ import { SiteConfig } from './config';
|
|
|
2
2
|
type Options = {
|
|
3
3
|
directory: string;
|
|
4
4
|
preserve?: string[];
|
|
5
|
+
dryRun?: boolean;
|
|
6
|
+
trailingSlashAliases?: boolean;
|
|
7
|
+
verifyHomepage?: boolean;
|
|
5
8
|
};
|
|
6
|
-
export declare function deploy(config: SiteConfig, { directory, preserve }: Options): void;
|
|
9
|
+
export declare function deploy(config: SiteConfig, { directory, preserve, dryRun, trailingSlashAliases, verifyHomepage, }: Options): void;
|
|
7
10
|
export {};
|
package/deploy.js
CHANGED
|
@@ -18,7 +18,7 @@ function* exportKeys(root, prefix = '') {
|
|
|
18
18
|
throw new Error(`Unexpected non-regular file in site export: ${key}`);
|
|
19
19
|
}
|
|
20
20
|
}
|
|
21
|
-
function deploy(config, { directory, preserve = markdown }) {
|
|
21
|
+
function deploy(config, { directory, preserve = markdown, dryRun, trailingSlashAliases, verifyHomepage, }) {
|
|
22
22
|
const root = (0, node_path_1.resolve)(directory);
|
|
23
23
|
const files = new Set(exportKeys(root));
|
|
24
24
|
if (!files.has('index.html'))
|
|
@@ -33,13 +33,15 @@ function deploy(config, { directory, preserve = markdown }) {
|
|
|
33
33
|
throw new Error(`Conflicting extensionless route: ${alias}`);
|
|
34
34
|
if (directoryIndex || !aliases.has(alias))
|
|
35
35
|
aliases.set(alias, key);
|
|
36
|
+
if (directoryIndex && trailingSlashAliases)
|
|
37
|
+
aliases.set(`${alias}/`, key);
|
|
36
38
|
}
|
|
37
39
|
const keep = preserve.map(globRegex);
|
|
38
40
|
const { AWS_S3_BUCKET: bucket, AWS_CLOUDFRONT_DISTRIBUTION_ID: distribution, SITE_URL: url } = config;
|
|
39
41
|
const s3 = `s3://${bucket}`;
|
|
40
42
|
const environment = (0, config_1.awsEnvironment)(config);
|
|
41
43
|
const exec = (command, args, env) => (0, node_child_process_1.execFileSync)(command, args, {
|
|
42
|
-
env,
|
|
44
|
+
env, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 4 * 1024 * 1024,
|
|
43
45
|
});
|
|
44
46
|
const aws = (...args) => {
|
|
45
47
|
const result = (0, node_child_process_1.spawnSync)('aws', args, { env: environment, stdio: 'inherit' });
|
|
@@ -48,38 +50,64 @@ function deploy(config, { directory, preserve = markdown }) {
|
|
|
48
50
|
if (result.status !== 0)
|
|
49
51
|
throw new Error(`AWS ${args.slice(0, 2).join(' ')} failed (${result.status ?? result.signal})`);
|
|
50
52
|
};
|
|
51
|
-
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment));
|
|
53
|
+
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment).toString());
|
|
52
54
|
const invalidate = () => {
|
|
53
55
|
const { Invalidation: { Id } } = awsJson('cloudfront', 'create-invalidation', '--distribution-id', distribution, '--paths', '/*');
|
|
54
56
|
aws('cloudfront', 'wait', 'invalidation-completed', '--distribution-id', distribution, '--id', Id);
|
|
55
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;
|
|
56
88
|
const source = root.endsWith(node_path_1.sep) ? root : root + node_path_1.sep;
|
|
57
89
|
aws('s3', 'cp', source, s3, '--recursive', ...markdown.flatMap(pattern => ['--exclude', pattern]));
|
|
58
90
|
aws('s3', 'cp', source, s3, '--recursive', '--exclude', '*', ...markdown.flatMap(pattern => ['--include', pattern]), '--content-type', 'text/plain; charset=utf-8');
|
|
59
|
-
for (const [alias, key] of aliases)
|
|
60
|
-
|
|
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
|
+
}
|
|
61
99
|
invalidate();
|
|
62
100
|
const response = exec('curl', ['--silent', '--show-error', '--max-time', '30', '--write-out', '\n%{http_code} %{content_type}', '--', url]);
|
|
63
101
|
const separator = response.lastIndexOf('\n');
|
|
64
|
-
const status = response.
|
|
65
|
-
|
|
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())) {
|
|
66
105
|
throw new Error(`Homepage health check did not return HTTP 200 with HTML (got ${status})`);
|
|
67
106
|
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const page = awsJson('s3api', 'list-objects-v2', '--bucket', bucket, '--no-paginate', ...(token ? ['--continuation-token', token] : []));
|
|
73
|
-
for (const { Key } of page.Contents ?? []) {
|
|
74
|
-
if (!files.has(Key) && !aliases.has(Key) && !keep.some(pattern => pattern.test(Key)))
|
|
75
|
-
stale.push({ Key });
|
|
76
|
-
}
|
|
77
|
-
token = page.IsTruncated ? page.NextContinuationToken : undefined;
|
|
78
|
-
if (page.IsTruncated && (!token || seen.has(token)))
|
|
79
|
-
throw new Error('S3 object listing is incomplete');
|
|
80
|
-
if (token)
|
|
81
|
-
seen.add(token);
|
|
82
|
-
} while (token);
|
|
107
|
+
if (expectedHomepage && !body.equals(expectedHomepage)) {
|
|
108
|
+
throw new Error('Homepage content does not match the exported index.html');
|
|
109
|
+
}
|
|
110
|
+
const stale = listStaleKeys();
|
|
83
111
|
for (let offset = 0; offset < stale.length; offset += 20) {
|
|
84
112
|
const { Errors } = awsJson('s3api', 'delete-objects', '--bucket', bucket, '--delete', JSON.stringify({ Objects: stale.slice(offset, offset + 20) }));
|
|
85
113
|
if (Errors?.length)
|
package/esm/cli.js
CHANGED
|
@@ -7,6 +7,7 @@ import { awsEnvironment, fields, isCI, readSiteConfig, requiredFields, saveSiteC
|
|
|
7
7
|
import { deploy } from './deploy';
|
|
8
8
|
const usage = `Usage:
|
|
9
9
|
static-site-deploy deploy --site OWNER/REPO [--dir out] [--preserve PATTERN ...]
|
|
10
|
+
[--dry-run] [--trailing-slash-aliases] [--verify-homepage]
|
|
10
11
|
static-site-deploy check --site OWNER/REPO
|
|
11
12
|
static-site-deploy setup --site OWNER/REPO [--provision] [--dry-run] [--yes]
|
|
12
13
|
[--reviewer LOGIN] [--account-id ID] [--role-name NAME] [--branch main]`;
|
|
@@ -57,6 +58,8 @@ async function main() {
|
|
|
57
58
|
site: { type: 'string' },
|
|
58
59
|
dir: { type: 'string' },
|
|
59
60
|
preserve: { type: 'string', multiple: true },
|
|
61
|
+
'trailing-slash-aliases': { type: 'boolean' },
|
|
62
|
+
'verify-homepage': { type: 'boolean' },
|
|
60
63
|
provision: { type: 'boolean' },
|
|
61
64
|
'dry-run': { type: 'boolean' },
|
|
62
65
|
yes: { type: 'boolean' },
|
|
@@ -75,10 +78,13 @@ async function main() {
|
|
|
75
78
|
const site = options.site ?? process.env.GITHUB_REPOSITORY;
|
|
76
79
|
if (!site)
|
|
77
80
|
throw new Error('Specify the GitHub repository as --site OWNER/REPO.');
|
|
78
|
-
if (command !== 'setup' && (options.provision || options
|
|
81
|
+
if (command !== 'setup' && (options.provision || options.yes ||
|
|
79
82
|
options.reviewer || options['account-id'] || options['role-name'] || options.branch))
|
|
80
83
|
throw new Error(usage);
|
|
81
|
-
if (command !== 'deploy' && (options.dir || options.preserve
|
|
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'])
|
|
82
88
|
throw new Error(usage);
|
|
83
89
|
const allowPrompt = interactive && !options.yes && command !== 'check';
|
|
84
90
|
const dryRun = !!options['dry-run'];
|
|
@@ -93,9 +99,15 @@ async function main() {
|
|
|
93
99
|
if (command === 'check')
|
|
94
100
|
return;
|
|
95
101
|
if (command === 'deploy') {
|
|
96
|
-
if (prompted)
|
|
102
|
+
if (prompted && !dryRun)
|
|
97
103
|
saveSiteConfig(site, config);
|
|
98
|
-
return deploy(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
|
+
});
|
|
99
111
|
}
|
|
100
112
|
if (!dryRun) {
|
|
101
113
|
saveSiteConfig(site, config);
|
package/esm/deploy.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ import { SiteConfig } from './config';
|
|
|
2
2
|
type Options = {
|
|
3
3
|
directory: string;
|
|
4
4
|
preserve?: string[];
|
|
5
|
+
dryRun?: boolean;
|
|
6
|
+
trailingSlashAliases?: boolean;
|
|
7
|
+
verifyHomepage?: boolean;
|
|
5
8
|
};
|
|
6
|
-
export declare function deploy(config: SiteConfig, { directory, preserve }: Options): void;
|
|
9
|
+
export declare function deploy(config: SiteConfig, { directory, preserve, dryRun, trailingSlashAliases, verifyHomepage, }: Options): void;
|
|
7
10
|
export {};
|
package/esm/deploy.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execFileSync, spawnSync } from 'node:child_process';
|
|
2
|
-
import { readdirSync } from 'node:fs';
|
|
2
|
+
import { readFileSync, readdirSync } from 'node:fs';
|
|
3
3
|
import { resolve, sep } from 'node:path';
|
|
4
4
|
import { awsEnvironment } from './config';
|
|
5
5
|
const markdown = ['*.md', 'llms.txt'];
|
|
@@ -15,7 +15,7 @@ function* exportKeys(root, prefix = '') {
|
|
|
15
15
|
throw new Error(`Unexpected non-regular file in site export: ${key}`);
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
|
-
export function deploy(config, { directory, preserve = markdown }) {
|
|
18
|
+
export function deploy(config, { directory, preserve = markdown, dryRun, trailingSlashAliases, verifyHomepage, }) {
|
|
19
19
|
const root = resolve(directory);
|
|
20
20
|
const files = new Set(exportKeys(root));
|
|
21
21
|
if (!files.has('index.html'))
|
|
@@ -30,13 +30,15 @@ export function deploy(config, { directory, preserve = markdown }) {
|
|
|
30
30
|
throw new Error(`Conflicting extensionless route: ${alias}`);
|
|
31
31
|
if (directoryIndex || !aliases.has(alias))
|
|
32
32
|
aliases.set(alias, key);
|
|
33
|
+
if (directoryIndex && trailingSlashAliases)
|
|
34
|
+
aliases.set(`${alias}/`, key);
|
|
33
35
|
}
|
|
34
36
|
const keep = preserve.map(globRegex);
|
|
35
37
|
const { AWS_S3_BUCKET: bucket, AWS_CLOUDFRONT_DISTRIBUTION_ID: distribution, SITE_URL: url } = config;
|
|
36
38
|
const s3 = `s3://${bucket}`;
|
|
37
39
|
const environment = awsEnvironment(config);
|
|
38
40
|
const exec = (command, args, env) => execFileSync(command, args, {
|
|
39
|
-
env,
|
|
41
|
+
env, stdio: ['ignore', 'pipe', 'inherit'], maxBuffer: 4 * 1024 * 1024,
|
|
40
42
|
});
|
|
41
43
|
const aws = (...args) => {
|
|
42
44
|
const result = spawnSync('aws', args, { env: environment, stdio: 'inherit' });
|
|
@@ -45,38 +47,64 @@ export function deploy(config, { directory, preserve = markdown }) {
|
|
|
45
47
|
if (result.status !== 0)
|
|
46
48
|
throw new Error(`AWS ${args.slice(0, 2).join(' ')} failed (${result.status ?? result.signal})`);
|
|
47
49
|
};
|
|
48
|
-
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment));
|
|
50
|
+
const awsJson = (...args) => JSON.parse(exec('aws', [...args, '--output', 'json'], environment).toString());
|
|
49
51
|
const invalidate = () => {
|
|
50
52
|
const { Invalidation: { Id } } = awsJson('cloudfront', 'create-invalidation', '--distribution-id', distribution, '--paths', '/*');
|
|
51
53
|
aws('cloudfront', 'wait', 'invalidation-completed', '--distribution-id', distribution, '--id', Id);
|
|
52
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;
|
|
53
85
|
const source = root.endsWith(sep) ? root : root + sep;
|
|
54
86
|
aws('s3', 'cp', source, s3, '--recursive', ...markdown.flatMap(pattern => ['--exclude', pattern]));
|
|
55
87
|
aws('s3', 'cp', source, s3, '--recursive', '--exclude', '*', ...markdown.flatMap(pattern => ['--include', pattern]), '--content-type', 'text/plain; charset=utf-8');
|
|
56
|
-
for (const [alias, key] of aliases)
|
|
57
|
-
|
|
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
|
+
}
|
|
58
96
|
invalidate();
|
|
59
97
|
const response = exec('curl', ['--silent', '--show-error', '--max-time', '30', '--write-out', '\n%{http_code} %{content_type}', '--', url]);
|
|
60
98
|
const separator = response.lastIndexOf('\n');
|
|
61
|
-
const status = response.
|
|
62
|
-
|
|
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())) {
|
|
63
102
|
throw new Error(`Homepage health check did not return HTTP 200 with HTML (got ${status})`);
|
|
64
103
|
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const page = awsJson('s3api', 'list-objects-v2', '--bucket', bucket, '--no-paginate', ...(token ? ['--continuation-token', token] : []));
|
|
70
|
-
for (const { Key } of page.Contents ?? []) {
|
|
71
|
-
if (!files.has(Key) && !aliases.has(Key) && !keep.some(pattern => pattern.test(Key)))
|
|
72
|
-
stale.push({ Key });
|
|
73
|
-
}
|
|
74
|
-
token = page.IsTruncated ? page.NextContinuationToken : undefined;
|
|
75
|
-
if (page.IsTruncated && (!token || seen.has(token)))
|
|
76
|
-
throw new Error('S3 object listing is incomplete');
|
|
77
|
-
if (token)
|
|
78
|
-
seen.add(token);
|
|
79
|
-
} while (token);
|
|
104
|
+
if (expectedHomepage && !body.equals(expectedHomepage)) {
|
|
105
|
+
throw new Error('Homepage content does not match the exported index.html');
|
|
106
|
+
}
|
|
107
|
+
const stale = listStaleKeys();
|
|
80
108
|
for (let offset = 0; offset < stale.length; offset += 20) {
|
|
81
109
|
const { Errors } = awsJson('s3api', 'delete-objects', '--bucket', bucket, '--delete', JSON.stringify({ Objects: stale.slice(offset, offset + 20) }));
|
|
82
110
|
if (Errors?.length)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@constructive-io/static-site-deploy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"author": "Constructive <developers@constructive.io>",
|
|
5
5
|
"description": "Deploy a static site to S3 and CloudFront with optional GitHub OIDC setup",
|
|
6
6
|
"main": "index.js",
|
|
@@ -19,13 +19,6 @@
|
|
|
19
19
|
"type": "git",
|
|
20
20
|
"url": "https://github.com/constructive-io/dev-utils"
|
|
21
21
|
},
|
|
22
|
-
"scripts": {
|
|
23
|
-
"copy": "makage assets",
|
|
24
|
-
"clean": "makage clean",
|
|
25
|
-
"prepublishOnly": "npm run build",
|
|
26
|
-
"build": "makage build && makage copy src/provision.sh dist --flat",
|
|
27
|
-
"test": "jest"
|
|
28
|
-
},
|
|
29
22
|
"dependencies": {
|
|
30
23
|
"12factor-env": "1.34.0",
|
|
31
24
|
"appstash": "0.8.1",
|
|
@@ -34,5 +27,10 @@
|
|
|
34
27
|
"devDependencies": {
|
|
35
28
|
"makage": "0.1.10"
|
|
36
29
|
},
|
|
37
|
-
"
|
|
38
|
-
|
|
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
|
+
}
|
|
36
|
+
}
|
package/provision.sh
CHANGED
|
@@ -92,8 +92,15 @@ subject_template=repos/$repo/actions/oidc/customization/sub
|
|
|
92
92
|
identity=$(read_state "arn:aws:iam::$AWS_ACCOUNT_ID:root" aws sts get-caller-identity --query Arn --output text)
|
|
93
93
|
[[ $identity == arn:aws:*:"$AWS_ACCOUNT_ID":* ]] || fail "AWS credentials do not belong to account $AWS_ACCOUNT_ID in the standard AWS partition."
|
|
94
94
|
template=$(read_state '{"use_immutable_subject":false}' gh api "$subject_template")
|
|
95
|
-
|
|
96
|
-
|
|
95
|
+
subject_settings='{"use_default":false,"include_claim_keys":["repo","context","ref"]}'
|
|
96
|
+
subject_repo="repo:$repo"
|
|
97
|
+
if jq -e '.use_immutable_subject == true' <<< "$template" >/dev/null; then
|
|
98
|
+
subject_repo=$(jq -er --arg repo "repo:$repo" '.sub_claim_prefix | select(type == "string"
|
|
99
|
+
and test("^repo:[A-Za-z0-9-]+@[1-9][0-9]*/[A-Za-z0-9_.-]+@[1-9][0-9]*$")
|
|
100
|
+
and (sub("@[0-9]+"; ""; "g") | ascii_downcase) == ($repo | ascii_downcase))' <<< "$template") ||
|
|
101
|
+
fail "GitHub did not return an immutable OIDC subject prefix for $repo."
|
|
102
|
+
subject_settings='{"use_default":false,"include_claim_keys":["repo","context","ref"],"use_immutable_subject":true}'
|
|
103
|
+
fi
|
|
97
104
|
|
|
98
105
|
reviewer=$(read_state 1 gh api "users/$SITE_REVIEWER" --jq .id)
|
|
99
106
|
[[ $reviewer =~ ^[1-9][0-9]*$ ]] || fail "Could not resolve the GitHub reviewer $SITE_REVIEWER."
|
|
@@ -133,7 +140,7 @@ elif ! jq -e --arg aud "$audience" '.ClientIDList | index($aud) != null' <<< "$p
|
|
|
133
140
|
run aws iam add-client-id-to-open-id-connect-provider --open-id-connect-provider-arn "$provider" --client-id "$audience"
|
|
134
141
|
fi
|
|
135
142
|
|
|
136
|
-
trust=$(jq -cn --arg provider "$provider" --arg aud "$audience" --arg sub "
|
|
143
|
+
trust=$(jq -cn --arg provider "$provider" --arg aud "$audience" --arg sub "$subject_repo:environment:production:ref:refs/heads/$SITE_BRANCH" '{
|
|
137
144
|
Version: "2012-10-17", Statement: [{
|
|
138
145
|
Effect: "Allow", Principal: {Federated: $provider}, Action: "sts:AssumeRoleWithWebIdentity",
|
|
139
146
|
Condition: {StringEquals: {"token.actions.githubusercontent.com:aud": $aud, "token.actions.githubusercontent.com:sub": $sub}}
|
|
@@ -162,7 +169,7 @@ else
|
|
|
162
169
|
run aws iam update-assume-role-policy --role-name "$AWS_DEPLOY_ROLE_NAME" --policy-document "$trust"
|
|
163
170
|
fi
|
|
164
171
|
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"
|
|
172
|
+
write_github PUT "$subject_template" "$subject_settings"
|
|
166
173
|
|
|
167
174
|
for name in AWS_S3_BUCKET AWS_CLOUDFRONT_DISTRIBUTION_ID SITE_URL AWS_REGION; do
|
|
168
175
|
run gh variable set "$name" --repo "$repo" --env production --body "${!name}"
|