blogwright 0.4.0 → 0.6.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 +4 -1
- package/agent/agent-manifest.json +1 -1
- package/agent/server.js +2610 -616
- package/dist/adapters/node-dns.d.ts +20 -0
- package/dist/adapters/node-dns.js +49 -0
- package/dist/adapters/process-aws-login.d.ts +19 -0
- package/dist/adapters/process-aws-login.js +28 -0
- package/dist/agent-package.js +2 -3
- package/dist/artifacts.d.ts +73 -0
- package/dist/artifacts.js +218 -0
- package/dist/aws-session.d.ts +118 -0
- package/dist/aws-session.js +360 -0
- package/dist/bin.js +6 -2
- package/dist/cache-control.d.ts +66 -0
- package/dist/cache-control.js +176 -0
- package/dist/cli.d.ts +22 -3
- package/dist/cli.js +128 -31
- package/dist/commands.d.ts +41 -9
- package/dist/commands.js +135 -126
- package/dist/context.d.ts +42 -5
- package/dist/context.js +81 -19
- package/dist/deploy.d.ts +78 -6
- package/dist/deploy.js +136 -52
- package/dist/domains.d.ts +46 -0
- package/dist/domains.js +125 -0
- package/dist/init.d.ts +14 -2
- package/dist/init.js +145 -4
- package/dist/known-commands.d.ts +11 -9
- package/dist/known-commands.js +15 -9
- package/dist/live-release.d.ts +78 -0
- package/dist/live-release.js +159 -0
- package/dist/lock.d.ts +50 -0
- package/dist/lock.js +120 -0
- package/dist/nodes.d.ts +18 -0
- package/dist/nodes.js +721 -76
- package/dist/plugin-commands.d.ts +21 -0
- package/dist/plugin-commands.js +54 -3
- package/dist/plugins.d.ts +11 -9
- package/dist/plugins.js +29 -16
- package/dist/ports.d.ts +37 -1
- package/dist/releases.d.ts +54 -0
- package/dist/releases.js +527 -0
- package/dist/render.d.ts +18 -1
- package/dist/render.js +38 -6
- package/dist/repo.js +2 -3
- package/dist/rkey.d.ts +4 -3
- package/dist/rkey.js +4 -3
- package/dist/router-function.d.ts +24 -0
- package/dist/router-function.js +71 -0
- package/dist/serving.d.ts +28 -0
- package/dist/serving.js +47 -0
- package/dist/verify.d.ts +45 -0
- package/dist/verify.js +183 -0
- package/dist/whoami.d.ts +23 -0
- package/dist/whoami.js +88 -0
- package/package.json +8 -8
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Which AWS credentials an invocation uses, whether they work, and whose they
|
|
3
|
+
* are - decided before any state is loaded. `resolveAwsProfile` applies the
|
|
4
|
+
* profile precedence; `resolveAwsSession` checks the profile exists, builds
|
|
5
|
+
* the clients, calls `sts:GetCallerIdentity`, offers an interactive sign-in
|
|
6
|
+
* when the credentials are expired or missing, and enforces the account pin.
|
|
7
|
+
* `createContext`, `whoami` and `init` are its three callers, so they cannot
|
|
8
|
+
* disagree. The process environment, home directory and platform arrive as
|
|
9
|
+
* data: only the composition root reads them.
|
|
10
|
+
*/
|
|
11
|
+
import { assertAccountPin, AwsCredentialsError, AwsError, createClients, DEFAULT_PROFILE, readAwsProfiles, shortIdentity, } from 'blogwright-core';
|
|
12
|
+
/** True when a precedence row named a profile. */
|
|
13
|
+
export function isNamedProfile(profile) {
|
|
14
|
+
return 'name' in profile;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The credentials a resolved profile selects in core. The default row holds
|
|
18
|
+
* the chain to the `default` profile: it only wins with `AWS_PROFILE` unset,
|
|
19
|
+
* or deliberately ignored (`init` detecting for a config with no profile),
|
|
20
|
+
* and the SDK would otherwise read `AWS_PROFILE` from the process itself.
|
|
21
|
+
*/
|
|
22
|
+
function credentialSelection(profile) {
|
|
23
|
+
if (isNamedProfile(profile))
|
|
24
|
+
return { kind: 'profile', name: profile.name };
|
|
25
|
+
return profile.source === 'env-keys' ? { kind: 'environment' } : { kind: 'default-profile' };
|
|
26
|
+
}
|
|
27
|
+
/** Trim a value, treating blank as absent. */
|
|
28
|
+
function present(value) {
|
|
29
|
+
const trimmed = value?.trim();
|
|
30
|
+
return trimmed ? trimmed : undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* True when credentials are exported into the environment - an access key
|
|
34
|
+
* pair, a web identity token file, or a container credentials endpoint - as
|
|
35
|
+
* CI exports them.
|
|
36
|
+
*/
|
|
37
|
+
function hasEnvironmentCredentials(env) {
|
|
38
|
+
if (present(env.AWS_ACCESS_KEY_ID) && present(env.AWS_SECRET_ACCESS_KEY))
|
|
39
|
+
return true;
|
|
40
|
+
return Boolean(present(env.AWS_WEB_IDENTITY_TOKEN_FILE) ||
|
|
41
|
+
present(env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI) ||
|
|
42
|
+
present(env.AWS_CONTAINER_CREDENTIALS_FULL_URI));
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The profile precedence; the first matching row wins: `--profile`,
|
|
46
|
+
* `AWS_PROFILE`, exported environment credentials (no name), the config's
|
|
47
|
+
* `aws.profile`, then the default chain (no name). Exported credentials beat
|
|
48
|
+
* the config's profile so a committed `aws.profile` cannot break CI.
|
|
49
|
+
*/
|
|
50
|
+
export function resolveAwsProfile(input) {
|
|
51
|
+
const flag = present(input.flag);
|
|
52
|
+
if (flag)
|
|
53
|
+
return { name: flag, source: 'flag' };
|
|
54
|
+
const env = present(input.processEnv.AWS_PROFILE);
|
|
55
|
+
if (env)
|
|
56
|
+
return { name: env, source: 'env' };
|
|
57
|
+
if (hasEnvironmentCredentials(input.processEnv))
|
|
58
|
+
return { source: 'env-keys' };
|
|
59
|
+
const config = present(input.config?.profile);
|
|
60
|
+
if (config)
|
|
61
|
+
return { name: config, source: 'config' };
|
|
62
|
+
return { source: 'default' };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* True when a browser cannot be opened for sign-in: `BLOGWRIGHT_HEADLESS=1`,
|
|
66
|
+
* an SSH session, or Linux with no display. `BLOGWRIGHT_HEADLESS=0` forces
|
|
67
|
+
* the browser flow.
|
|
68
|
+
*/
|
|
69
|
+
export function isHeadless(env, platform) {
|
|
70
|
+
const forced = present(env.BLOGWRIGHT_HEADLESS);
|
|
71
|
+
if (forced === '1')
|
|
72
|
+
return true;
|
|
73
|
+
if (forced === '0')
|
|
74
|
+
return false;
|
|
75
|
+
if (present(env.SSH_CONNECTION) || present(env.SSH_TTY))
|
|
76
|
+
return true;
|
|
77
|
+
return platform === 'linux' && !present(env.DISPLAY) && !present(env.WAYLAND_DISPLAY);
|
|
78
|
+
}
|
|
79
|
+
/** STS error codes that mean the signing credentials themselves are bad or expired. */
|
|
80
|
+
const CREDENTIAL_ERROR_CODES = new Set([
|
|
81
|
+
'ExpiredToken',
|
|
82
|
+
'ExpiredTokenException',
|
|
83
|
+
'InvalidClientTokenId',
|
|
84
|
+
'UnrecognizedClientException',
|
|
85
|
+
'SignatureDoesNotMatch',
|
|
86
|
+
]);
|
|
87
|
+
/**
|
|
88
|
+
* True when a `GetCallerIdentity` failure is about the credentials - the
|
|
89
|
+
* provider failed, or STS rejected them - rather than the network, endpoint
|
|
90
|
+
* or region, which propagate unchanged.
|
|
91
|
+
*/
|
|
92
|
+
export function isCredentialFailure(err) {
|
|
93
|
+
if (err instanceof AwsCredentialsError)
|
|
94
|
+
return true;
|
|
95
|
+
return err instanceof AwsError && CREDENTIAL_ERROR_CODES.has(err.code);
|
|
96
|
+
}
|
|
97
|
+
const SOURCE_LABELS = {
|
|
98
|
+
flag: '--profile',
|
|
99
|
+
env: 'AWS_PROFILE',
|
|
100
|
+
'env-keys': 'environment credentials',
|
|
101
|
+
config: 'config',
|
|
102
|
+
default: 'default credentials',
|
|
103
|
+
};
|
|
104
|
+
/** How an operator names a precedence row: `--profile`, `AWS_PROFILE`, `config`, ... */
|
|
105
|
+
export function profileSourceLabel(source) {
|
|
106
|
+
return SOURCE_LABELS[source];
|
|
107
|
+
}
|
|
108
|
+
/** Where the profile came from, naming the config file itself for the config row. */
|
|
109
|
+
function profileOrigin(source, configLabel) {
|
|
110
|
+
return source === 'config' ? configLabel : profileSourceLabel(source);
|
|
111
|
+
}
|
|
112
|
+
/** `profile mysite-prod (config)`, or `environment credentials` / `default credentials`. */
|
|
113
|
+
function describeProfile(profile) {
|
|
114
|
+
const label = profileSourceLabel(profile.source);
|
|
115
|
+
return isNamedProfile(profile) ? `profile ${profile.name} (${label})` : label;
|
|
116
|
+
}
|
|
117
|
+
/** How failures name the credentials: `AWS credentials for profile "x"`, or the unnamed kind. */
|
|
118
|
+
function credentialsSubject(profile) {
|
|
119
|
+
if (isNamedProfile(profile))
|
|
120
|
+
return `AWS credentials for profile "${profile.name}"`;
|
|
121
|
+
return profile.source === 'env-keys'
|
|
122
|
+
? 'The AWS credentials exported in the environment'
|
|
123
|
+
: 'The default AWS credentials';
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Refuse a named profile the shared files do not define, before any AWS call.
|
|
127
|
+
* Under an endpoint override it is dropped instead: the emulator never checks
|
|
128
|
+
* credentials, and a committed `aws.profile` must not break emulator runs on
|
|
129
|
+
* machines without it.
|
|
130
|
+
*/
|
|
131
|
+
function checkProfileExists(profile, profiles, opts) {
|
|
132
|
+
if (!isNamedProfile(profile) || profiles.has(profile.name))
|
|
133
|
+
return profile;
|
|
134
|
+
if (opts.override) {
|
|
135
|
+
opts.notice(`profile "${profile.name}" not found - using emulator credentials`);
|
|
136
|
+
return { source: 'default' };
|
|
137
|
+
}
|
|
138
|
+
const available = profiles.names.length > 0 ? profiles.names.join(', ') : 'none';
|
|
139
|
+
throw new Error(`AWS profile "${profile.name}" not found (from ${profileOrigin(profile.source, opts.configLabel)})\n` +
|
|
140
|
+
`available: ${available}`);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* The two sign-in commands for a profile. The default follows the style: SSO
|
|
144
|
+
* profiles default to `aws sso login`, console and unconfigured ones to
|
|
145
|
+
* `aws login`. Headless hosts get each command's browserless flag. The
|
|
146
|
+
* profile is the one whose settings decided the style - for a
|
|
147
|
+
* `source_profile` chain, its source, whose login repairs the chain - and is
|
|
148
|
+
* always passed, `default` included, so the AWS CLI cannot fall back to an
|
|
149
|
+
* inherited `AWS_PROFILE` this session ignored.
|
|
150
|
+
*/
|
|
151
|
+
export function buildLoginChoices(profileName, style, headless) {
|
|
152
|
+
const profileArgs = ['--profile', profileName];
|
|
153
|
+
const sso = {
|
|
154
|
+
args: ['sso', 'login', ...profileArgs, ...(headless ? ['--use-device-code'] : [])],
|
|
155
|
+
hint: style === 'sso' ? 'profile uses IAM Identity Center' : 'IAM Identity Center',
|
|
156
|
+
};
|
|
157
|
+
const login = {
|
|
158
|
+
args: ['login', ...profileArgs, ...(headless ? ['--remote'] : [])],
|
|
159
|
+
hint: style === 'login' ? 'profile uses AWS console credentials' : 'AWS console credentials',
|
|
160
|
+
};
|
|
161
|
+
return { choices: [sso, login], defaultIndex: style === 'sso' ? 0 : 1 };
|
|
162
|
+
}
|
|
163
|
+
function commandLine(choice) {
|
|
164
|
+
return ['aws', ...choice.args].join(' ');
|
|
165
|
+
}
|
|
166
|
+
/** Styles a sign-in command can repair. */
|
|
167
|
+
const SIGN_IN_STYLES = new Set(['sso', 'login', 'unconfigured']);
|
|
168
|
+
/** The profile the operator asked for; unnamed credentials read `default`. */
|
|
169
|
+
function requestedProfile(profile) {
|
|
170
|
+
return isNamedProfile(profile) ? profile.name : DEFAULT_PROFILE;
|
|
171
|
+
}
|
|
172
|
+
/** The sign-in style of the resolved credentials; unnamed ones read the `default` profile. */
|
|
173
|
+
function signInOf(profile, profiles) {
|
|
174
|
+
return profiles.signIn(requestedProfile(profile));
|
|
175
|
+
}
|
|
176
|
+
/** The one line of guidance shown when no login is offered. */
|
|
177
|
+
function credentialGuidance(profile, signIn, headless) {
|
|
178
|
+
if (profile.source === 'env-keys') {
|
|
179
|
+
return 'Refresh the exported credentials (AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_SESSION_TOKEN).';
|
|
180
|
+
}
|
|
181
|
+
const target = signIn.profile;
|
|
182
|
+
switch (signIn.style) {
|
|
183
|
+
case 'sso':
|
|
184
|
+
case 'login':
|
|
185
|
+
case 'unconfigured': {
|
|
186
|
+
const menu = buildLoginChoices(target, signIn.style, headless);
|
|
187
|
+
const commands = signIn.style === 'unconfigured'
|
|
188
|
+
? menu.choices.map(commandLine).join(' or ')
|
|
189
|
+
: commandLine(menu.choices[menu.defaultIndex]);
|
|
190
|
+
return `Sign in with: ${commands}`;
|
|
191
|
+
}
|
|
192
|
+
case 'static':
|
|
193
|
+
return `Update the access keys with: aws configure --profile ${target}`;
|
|
194
|
+
case 'process':
|
|
195
|
+
return `Check the profile's credential_process: ${signIn.detail ?? '(unset)'}`;
|
|
196
|
+
case 'external':
|
|
197
|
+
return `Check the role's credential_source: ${signIn.detail ?? '(unset)'}`;
|
|
198
|
+
case 'web-identity':
|
|
199
|
+
return `Check the role's web_identity_token_file: ${signIn.detail ?? '(unset)'}`;
|
|
200
|
+
case 'mfa':
|
|
201
|
+
return (`The role needs an MFA code for ${signIn.detail ?? 'its mfa_serial'}, which blogwright cannot ask for. ` +
|
|
202
|
+
'Export temporary credentials with: ' +
|
|
203
|
+
`eval "$(aws configure export-credentials --profile ${requestedProfile(profile)} --format env)"` +
|
|
204
|
+
(profile.source === 'flag' || profile.source === 'env'
|
|
205
|
+
? ', then run again with neither --profile nor AWS_PROFILE set'
|
|
206
|
+
: ', then run again'));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
/** Raised when a sign-in cannot repair the credentials; the message is the whole report. */
|
|
210
|
+
function unusableCredentials(cause, profile, advice) {
|
|
211
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
212
|
+
return new Error(`${credentialsSubject(profile)} are not usable:\n ${reason}\n${advice}`, {
|
|
213
|
+
cause,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
/** Maximum invalid answers to the sign-in menu before it is treated as cancel. */
|
|
217
|
+
const MENU_ATTEMPTS = 3;
|
|
218
|
+
/** Ask which sign-in to run; resolves the chosen command, or undefined for cancel. */
|
|
219
|
+
async function askLoginChoice(menu, terminal, logger) {
|
|
220
|
+
const commands = menu.choices.map(commandLine);
|
|
221
|
+
const width = Math.max(...commands.map((command) => command.length)) + 4;
|
|
222
|
+
logger.info('How do you want to sign in?');
|
|
223
|
+
menu.choices.forEach((choice, index) => {
|
|
224
|
+
logger.info(` ${index + 1}) ${commands[index].padEnd(width)}(${choice.hint})`);
|
|
225
|
+
});
|
|
226
|
+
logger.info(' 3) cancel');
|
|
227
|
+
const fallback = String(menu.defaultIndex + 1);
|
|
228
|
+
for (let attempt = 0; attempt < MENU_ATTEMPTS; attempt++) {
|
|
229
|
+
const answer = (await terminal.question(`choice [${fallback}]: `)).trim() || fallback;
|
|
230
|
+
if (answer === '1' || answer === '2')
|
|
231
|
+
return menu.choices[Number(answer) - 1];
|
|
232
|
+
if (answer === '3')
|
|
233
|
+
return undefined;
|
|
234
|
+
logger.warn('answer 1, 2 or 3');
|
|
235
|
+
}
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
/** Run the chosen sign-in, raising on a missing AWS CLI or a failed command. */
|
|
239
|
+
async function runLogin(choice, ports) {
|
|
240
|
+
ports.terminal.status('');
|
|
241
|
+
const result = await ports.awsLogin.run(choice.args);
|
|
242
|
+
if (result.ok)
|
|
243
|
+
return;
|
|
244
|
+
if (result.reason === 'not-installed') {
|
|
245
|
+
throw new Error(`cannot run "${commandLine(choice)}": the aws command was not found on the PATH - ` +
|
|
246
|
+
'install AWS CLI v2 (https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)');
|
|
247
|
+
}
|
|
248
|
+
throw new Error(`"${commandLine(choice)}" exited with code ${result.code}`);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Repair a credential failure: offer a sign-in when one applies, run it, and
|
|
252
|
+
* return so the caller retries; otherwise raise the failure with guidance.
|
|
253
|
+
*/
|
|
254
|
+
async function repairCredentials(failure, profile, profiles, opts) {
|
|
255
|
+
const signIn = signInOf(profile, profiles);
|
|
256
|
+
const headless = isHeadless(opts.host.processEnv, opts.host.platform);
|
|
257
|
+
const offered = opts.ports.terminal.isInteractive &&
|
|
258
|
+
profile.source !== 'env-keys' &&
|
|
259
|
+
SIGN_IN_STYLES.has(signIn.style);
|
|
260
|
+
if (!offered)
|
|
261
|
+
throw unusableCredentials(failure, profile, credentialGuidance(profile, signIn, headless));
|
|
262
|
+
const reason = failure instanceof Error ? failure.message : String(failure);
|
|
263
|
+
opts.logger.warn(`${credentialsSubject(profile)} are not usable:\n ${reason}`);
|
|
264
|
+
const choice = await askLoginChoice(buildLoginChoices(signIn.profile, signIn.style, headless), opts.ports.terminal, opts.logger);
|
|
265
|
+
if (!choice)
|
|
266
|
+
throw unusableCredentials(failure, profile, 'Sign-in cancelled.');
|
|
267
|
+
await runLogin(choice, opts.ports);
|
|
268
|
+
}
|
|
269
|
+
/** The endpoint override in effect: `--endpoint`, else a nonblank `AWS_ENDPOINT_URL`. */
|
|
270
|
+
function resolveEndpointOverride(opts) {
|
|
271
|
+
return present(opts.endpointOverride) ?? present(opts.host.processEnv.AWS_ENDPOINT_URL);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Resolve the profile, confirm it exists, build the clients, learn whose
|
|
275
|
+
* credentials they are, and enforce the account pin - in that order, so a
|
|
276
|
+
* mismatched account never reaches `StateStore.load`. A credential failure
|
|
277
|
+
* goes to the login offer, which retries `GetCallerIdentity` once after a
|
|
278
|
+
* successful sign-in; a second failure is reported, never offered again.
|
|
279
|
+
*/
|
|
280
|
+
export async function resolveAwsSession(opts) {
|
|
281
|
+
const endpointOverride = resolveEndpointOverride(opts);
|
|
282
|
+
const override = endpointOverride !== undefined;
|
|
283
|
+
const resolved = resolveAwsProfile({
|
|
284
|
+
flag: opts.flag,
|
|
285
|
+
processEnv: opts.host.processEnv,
|
|
286
|
+
config: opts.aws,
|
|
287
|
+
});
|
|
288
|
+
const notice = (line) => emitSessionLine(line, opts.ports.terminal, opts.logger);
|
|
289
|
+
const configProfile = present(opts.aws?.profile);
|
|
290
|
+
if (resolved.source === 'env-keys' && configProfile) {
|
|
291
|
+
notice(`ignoring aws.profile "${configProfile}": environment credentials are set`);
|
|
292
|
+
}
|
|
293
|
+
const profiles = await readAwsProfiles(opts.ports.fs, opts.host.processEnv, opts.host.home);
|
|
294
|
+
const profile = checkProfileExists(resolved, profiles, {
|
|
295
|
+
override,
|
|
296
|
+
configLabel: opts.configLabel,
|
|
297
|
+
notice,
|
|
298
|
+
});
|
|
299
|
+
const makeClients = opts.host.createClients ?? createClients;
|
|
300
|
+
const buildClients = () => makeClients({ region: opts.region, endpointOverride, selection: credentialSelection(profile) });
|
|
301
|
+
let clients = buildClients();
|
|
302
|
+
let identity;
|
|
303
|
+
try {
|
|
304
|
+
identity = await clients.sts.getCallerIdentity();
|
|
305
|
+
}
|
|
306
|
+
catch (err) {
|
|
307
|
+
if (override || !isCredentialFailure(err))
|
|
308
|
+
throw err;
|
|
309
|
+
await repairCredentials(err, profile, profiles, opts);
|
|
310
|
+
clients = buildClients();
|
|
311
|
+
try {
|
|
312
|
+
identity = await clients.sts.getCallerIdentity();
|
|
313
|
+
}
|
|
314
|
+
catch (retryErr) {
|
|
315
|
+
if (!isCredentialFailure(retryErr))
|
|
316
|
+
throw retryErr;
|
|
317
|
+
throw unusableCredentials(retryErr, profile, 'Signing in did not help; check the profile.');
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const pin = assertAccountPin(opts.aws?.accountId, identity, {
|
|
321
|
+
override,
|
|
322
|
+
pinSource: opts.configLabel,
|
|
323
|
+
credentialsDescription: `${shortIdentity(identity.arn)}, ${describeCredentialsOrigin(profile, opts.configLabel)}`,
|
|
324
|
+
});
|
|
325
|
+
if (pin === 'skipped')
|
|
326
|
+
notice('account pin skipped: endpoint override');
|
|
327
|
+
return { profile, clients, identity, pin };
|
|
328
|
+
}
|
|
329
|
+
/** `profile "personal" from AWS_PROFILE`, or the unnamed kind of credentials. */
|
|
330
|
+
function describeCredentialsOrigin(profile, configLabel) {
|
|
331
|
+
if (!isNamedProfile(profile))
|
|
332
|
+
return profileOrigin(profile.source, configLabel);
|
|
333
|
+
return `profile "${profile.name}" from ${profileOrigin(profile.source, configLabel)}`;
|
|
334
|
+
}
|
|
335
|
+
const PIN_LABELS = {
|
|
336
|
+
matched: 'pinned',
|
|
337
|
+
unset: 'unpinned',
|
|
338
|
+
skipped: 'pin skipped',
|
|
339
|
+
};
|
|
340
|
+
/** `aws 123456789012 · AdminRole · profile mysite-prod (config) · pinned` */
|
|
341
|
+
export function formatIdentityLine(session) {
|
|
342
|
+
return [
|
|
343
|
+
`aws ${session.identity.account}`,
|
|
344
|
+
shortIdentity(session.identity.arn),
|
|
345
|
+
describeProfile(session.profile),
|
|
346
|
+
PIN_LABELS[session.pin],
|
|
347
|
+
].join(' · ');
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Emit a session line - the identity line, or a notice such as `account pin
|
|
351
|
+
* skipped`. Interactive sessions get it through the logger; otherwise
|
|
352
|
+
* (`--plain`, piped output, CI) it goes to stderr, so the non-interactive
|
|
353
|
+
* stdout of `history`, `status` and `whoami` stays byte-identical.
|
|
354
|
+
*/
|
|
355
|
+
export function emitSessionLine(line, terminal, logger) {
|
|
356
|
+
if (terminal.isInteractive)
|
|
357
|
+
logger.info(line);
|
|
358
|
+
else
|
|
359
|
+
terminal.error(line);
|
|
360
|
+
}
|
package/dist/bin.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createNodeFileSystem, createNodeTerminal } from 'blogwright-core';
|
|
3
3
|
import { createNodeModuleLoader } from './adapters/node-module-loader.js';
|
|
4
|
+
import { createProcessAwsLogin } from './adapters/process-aws-login.js';
|
|
4
5
|
import { createProcessPackageManager } from './adapters/process-package-manager.js';
|
|
5
6
|
import { main } from './cli.js';
|
|
6
|
-
import { createContext } from './context.js';
|
|
7
|
+
import { createAwsHost, createContext } from './context.js';
|
|
7
8
|
import { createLogger } from './logger.js';
|
|
8
9
|
const makeTerminal = (opts) => createNodeTerminal(opts);
|
|
9
10
|
// Plugin dispatch needs `fs`/`loader` for discovery before any environment
|
|
@@ -14,7 +15,10 @@ const makeDiscoveryPorts = () => ({ fs: createNodeFileSystem(), loader: createNo
|
|
|
14
15
|
// `PackageManagerFactory`. The adapter resolves the repo and the manager
|
|
15
16
|
// governing it itself, so it needs nothing here but a FileSystem.
|
|
16
17
|
const makePackages = () => createProcessPackageManager(createNodeFileSystem());
|
|
17
|
-
|
|
18
|
+
// `blogwright whoami` and `init` resolve an AWS session before any OpsContext
|
|
19
|
+
// exists - see cli.ts's `AwsAccessFactory`.
|
|
20
|
+
const makeAwsAccess = () => ({ host: createAwsHost(), awsLogin: createProcessAwsLogin() });
|
|
21
|
+
main(process.argv.slice(2), makeTerminal, createContext, makeDiscoveryPorts, makePackages, makeAwsAccess)
|
|
18
22
|
.then((code) => {
|
|
19
23
|
process.exitCode = code;
|
|
20
24
|
})
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps live objects' `Cache-Control` in step with the config. The build only
|
|
3
|
+
* re-uploads changed content, and S3 writes a header only on a PUT, so after
|
|
4
|
+
* the `cacheControl` rules change the unchanged objects would keep the old
|
|
5
|
+
* header. Each target has a record beside the deploy manifests saying which
|
|
6
|
+
* rules its files were written with; a build whose rules differ re-uploads
|
|
7
|
+
* every file, exactly as `--refresh` does.
|
|
8
|
+
*
|
|
9
|
+
* The record says `applied` only on evidence: the agent reports the rules it
|
|
10
|
+
* wrote in its changed-paths manifest, and an agent older than `cacheControl`
|
|
11
|
+
* reports none. Before a build that changes the rules, the record is marked
|
|
12
|
+
* `unconfirmed`, so a build that fails or is cancelled partway - leaving some
|
|
13
|
+
* files with the new header and some with the old - is re-applied in full by
|
|
14
|
+
* the next build, whatever the rules are by then.
|
|
15
|
+
*/
|
|
16
|
+
import { type CacheControlRule } from 'blogwright-core';
|
|
17
|
+
import type { OpsContext } from './context.js';
|
|
18
|
+
/** The S3 key recording the rules a target's files were last written with. */
|
|
19
|
+
export declare function cacheControlRecordKey(target: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* A target's record. `unconfirmed` means its files may carry headers from
|
|
22
|
+
* rules other than any recorded: a rule-changing build has not finished, or
|
|
23
|
+
* the agent did not report what it wrote.
|
|
24
|
+
*/
|
|
25
|
+
export type CacheControlRecord = {
|
|
26
|
+
status: 'applied';
|
|
27
|
+
rules: readonly CacheControlRule[];
|
|
28
|
+
} | {
|
|
29
|
+
status: 'unconfirmed';
|
|
30
|
+
};
|
|
31
|
+
/** Why a build must re-upload every file to bring `Cache-Control` in line with the config. */
|
|
32
|
+
export type CacheControlRefreshReason = 'unrecorded' | 'changed' | 'unconfirmed' | 'unreadable';
|
|
33
|
+
/** The log line announcing a {@link CacheControlRefreshReason}. */
|
|
34
|
+
export declare function describeCacheControlRefresh(reason: CacheControlRefreshReason): string;
|
|
35
|
+
/** Whether two rule lists are the same rules in the same order. */
|
|
36
|
+
export declare function sameCacheControlRules(a: readonly CacheControlRule[], b: readonly CacheControlRule[]): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Why this build to `target` must re-upload every file, or undefined when the
|
|
39
|
+
* target's files already carry the configured rules. No record means none
|
|
40
|
+
* were ever written - every deploy before `cacheControl` wrote no header - so
|
|
41
|
+
* empty rules need nothing. An unreadable record is warned about and re-applied.
|
|
42
|
+
*/
|
|
43
|
+
export declare function cacheControlRefreshReason(ctx: OpsContext, target: string): Promise<CacheControlRefreshReason | undefined>;
|
|
44
|
+
/**
|
|
45
|
+
* A target's record, or undefined when it has none. A malformed record is
|
|
46
|
+
* warned about and read as `unconfirmed`, which makes the next build to the
|
|
47
|
+
* target re-apply the rules.
|
|
48
|
+
*/
|
|
49
|
+
export declare function readCacheControlRecord(ctx: OpsContext, target: string): Promise<CacheControlRecord | undefined>;
|
|
50
|
+
/** Write a target's record as given. */
|
|
51
|
+
export declare function writeCacheControlRecord(ctx: OpsContext, target: string, record: CacheControlRecord): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Mark the target's record `unconfirmed` before its files are rewritten with
|
|
54
|
+
* other rules - by a build that re-applies them, or a promotion copying a
|
|
55
|
+
* staged release's headers in - so one that stops partway is re-applied by the
|
|
56
|
+
* next build. Fatal: nothing has been published yet, and going on without the
|
|
57
|
+
* mark could leave mixed headers that no later build notices.
|
|
58
|
+
*/
|
|
59
|
+
export declare function markCacheControlUnconfirmed(ctx: OpsContext, target: string): Promise<void>;
|
|
60
|
+
/**
|
|
61
|
+
* Record what a successful build wrote: `applied` with the rules when the
|
|
62
|
+
* agent's manifest at `reportKey` confirms them, `unconfirmed` otherwise.
|
|
63
|
+
* Non-fatal: the site is already published, so a failed write only warns and
|
|
64
|
+
* leaves the record as it was.
|
|
65
|
+
*/
|
|
66
|
+
export declare function recordCacheControl(ctx: OpsContext, target: string, reportKey: string): Promise<void>;
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps live objects' `Cache-Control` in step with the config. The build only
|
|
3
|
+
* re-uploads changed content, and S3 writes a header only on a PUT, so after
|
|
4
|
+
* the `cacheControl` rules change the unchanged objects would keep the old
|
|
5
|
+
* header. Each target has a record beside the deploy manifests saying which
|
|
6
|
+
* rules its files were written with; a build whose rules differ re-uploads
|
|
7
|
+
* every file, exactly as `--refresh` does.
|
|
8
|
+
*
|
|
9
|
+
* The record says `applied` only on evidence: the agent reports the rules it
|
|
10
|
+
* wrote in its changed-paths manifest, and an agent older than `cacheControl`
|
|
11
|
+
* reports none. Before a build that changes the rules, the record is marked
|
|
12
|
+
* `unconfirmed`, so a build that fails or is cancelled partway - leaving some
|
|
13
|
+
* files with the new header and some with the old - is re-applied in full by
|
|
14
|
+
* the next build, whatever the rules are by then.
|
|
15
|
+
*/
|
|
16
|
+
import { parseCacheControlRules } from 'blogwright-core';
|
|
17
|
+
/** The S3 key recording the rules a target's files were last written with. */
|
|
18
|
+
export function cacheControlRecordKey(target) {
|
|
19
|
+
return `build/cache-control/${target}.json`;
|
|
20
|
+
}
|
|
21
|
+
const REFRESH_MESSAGES = {
|
|
22
|
+
unrecorded: 'no Cache-Control record for this target yet - uploading every file with the current ' +
|
|
23
|
+
'cacheControl rules, so any files already there get them too',
|
|
24
|
+
changed: "cacheControl rules differ from the ones this target's files were written with - " +
|
|
25
|
+
're-uploading every file so unchanged ones get the new Cache-Control too',
|
|
26
|
+
unconfirmed: 'the last build to this target did not confirm the Cache-Control it wrote (it stopped ' +
|
|
27
|
+
'while changing the rules, or ran on an older builder image) - re-uploading every file ' +
|
|
28
|
+
'with the current cacheControl rules',
|
|
29
|
+
unreadable: 're-uploading every file with the current cacheControl rules',
|
|
30
|
+
};
|
|
31
|
+
/** The log line announcing a {@link CacheControlRefreshReason}. */
|
|
32
|
+
export function describeCacheControlRefresh(reason) {
|
|
33
|
+
return REFRESH_MESSAGES[reason];
|
|
34
|
+
}
|
|
35
|
+
function isRecord(value) {
|
|
36
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
37
|
+
}
|
|
38
|
+
/** Whether two rule lists are the same rules in the same order. */
|
|
39
|
+
export function sameCacheControlRules(a, b) {
|
|
40
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
41
|
+
}
|
|
42
|
+
function errorMessage(err) {
|
|
43
|
+
return err instanceof Error ? err.message : String(err);
|
|
44
|
+
}
|
|
45
|
+
/** Parse and validate a record body; throws, naming the key, on anything malformed. */
|
|
46
|
+
function parseRecord(text, key) {
|
|
47
|
+
let raw;
|
|
48
|
+
try {
|
|
49
|
+
raw = JSON.parse(text);
|
|
50
|
+
}
|
|
51
|
+
catch (err) {
|
|
52
|
+
throw new Error(`${key} is not valid JSON (${errorMessage(err)})`, { cause: err });
|
|
53
|
+
}
|
|
54
|
+
if (!isRecord(raw))
|
|
55
|
+
throw new Error(`${key} must hold a JSON object`);
|
|
56
|
+
if (raw.status === 'unconfirmed')
|
|
57
|
+
return { status: 'unconfirmed' };
|
|
58
|
+
if (raw.status !== 'applied') {
|
|
59
|
+
throw new Error(`${key} has status ${JSON.stringify(raw.status)}, not "applied"/"unconfirmed"`);
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
return { status: 'applied', rules: parseCacheControlRules(raw.rules) };
|
|
63
|
+
}
|
|
64
|
+
catch (err) {
|
|
65
|
+
throw new Error(`${key} holds rules that do not validate (${errorMessage(err)})`, {
|
|
66
|
+
cause: err,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Why this build to `target` must re-upload every file, or undefined when the
|
|
72
|
+
* target's files already carry the configured rules. No record means none
|
|
73
|
+
* were ever written - every deploy before `cacheControl` wrote no header - so
|
|
74
|
+
* empty rules need nothing. An unreadable record is warned about and re-applied.
|
|
75
|
+
*/
|
|
76
|
+
export async function cacheControlRefreshReason(ctx, target) {
|
|
77
|
+
const key = cacheControlRecordKey(target);
|
|
78
|
+
const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, key);
|
|
79
|
+
if (text === undefined)
|
|
80
|
+
return ctx.config.cacheControl.length > 0 ? 'unrecorded' : undefined;
|
|
81
|
+
let record;
|
|
82
|
+
try {
|
|
83
|
+
record = parseRecord(text, key);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
ctx.logger.warn(`ignoring malformed ${key}: ${errorMessage(err)}`);
|
|
87
|
+
return 'unreadable';
|
|
88
|
+
}
|
|
89
|
+
if (record.status === 'unconfirmed')
|
|
90
|
+
return 'unconfirmed';
|
|
91
|
+
return sameCacheControlRules(record.rules, ctx.config.cacheControl) ? undefined : 'changed';
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* A target's record, or undefined when it has none. A malformed record is
|
|
95
|
+
* warned about and read as `unconfirmed`, which makes the next build to the
|
|
96
|
+
* target re-apply the rules.
|
|
97
|
+
*/
|
|
98
|
+
export async function readCacheControlRecord(ctx, target) {
|
|
99
|
+
const key = cacheControlRecordKey(target);
|
|
100
|
+
const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, key);
|
|
101
|
+
if (text === undefined)
|
|
102
|
+
return undefined;
|
|
103
|
+
try {
|
|
104
|
+
return parseRecord(text, key);
|
|
105
|
+
}
|
|
106
|
+
catch (err) {
|
|
107
|
+
ctx.logger.warn(`ignoring malformed ${key}: ${errorMessage(err)}`);
|
|
108
|
+
return { status: 'unconfirmed' };
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/** Write a target's record as given. */
|
|
112
|
+
export async function writeCacheControlRecord(ctx, target, record) {
|
|
113
|
+
await ctx.clients.s3.putObject(ctx.names.bucket, cacheControlRecordKey(target), JSON.stringify(record, null, 2), 'application/json');
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Mark the target's record `unconfirmed` before its files are rewritten with
|
|
117
|
+
* other rules - by a build that re-applies them, or a promotion copying a
|
|
118
|
+
* staged release's headers in - so one that stops partway is re-applied by the
|
|
119
|
+
* next build. Fatal: nothing has been published yet, and going on without the
|
|
120
|
+
* mark could leave mixed headers that no later build notices.
|
|
121
|
+
*/
|
|
122
|
+
export async function markCacheControlUnconfirmed(ctx, target) {
|
|
123
|
+
try {
|
|
124
|
+
await writeCacheControlRecord(ctx, target, { status: 'unconfirmed' });
|
|
125
|
+
}
|
|
126
|
+
catch (err) {
|
|
127
|
+
throw new Error(`could not mark ${cacheControlRecordKey(target)} unconfirmed before rewriting its files ` +
|
|
128
|
+
`(${errorMessage(err)}); nothing was published`, { cause: err });
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/** The rules the agent's changed-paths manifest reports, or undefined when it reports none. */
|
|
132
|
+
function reportedRules(text) {
|
|
133
|
+
const manifest = JSON.parse(text);
|
|
134
|
+
if (!isRecord(manifest) || manifest.cacheControl === undefined)
|
|
135
|
+
return undefined;
|
|
136
|
+
return parseCacheControlRules(manifest.cacheControl);
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Whether the agent reported writing exactly the configured rules. An agent
|
|
140
|
+
* older than `cacheControl` reports nothing, and a missing or unreadable
|
|
141
|
+
* manifest proves nothing either; both are warned about and count as unconfirmed.
|
|
142
|
+
*/
|
|
143
|
+
async function agentConfirmedRules(ctx, reportKey) {
|
|
144
|
+
try {
|
|
145
|
+
const text = await ctx.clients.s3.getObjectText(ctx.names.bucket, reportKey);
|
|
146
|
+
const reported = text === undefined ? undefined : reportedRules(text);
|
|
147
|
+
if (reported !== undefined && sameCacheControlRules(reported, ctx.config.cacheControl))
|
|
148
|
+
return true;
|
|
149
|
+
ctx.logger.warn(`the builder did not report writing the configured Cache-Control in ${reportKey} ` +
|
|
150
|
+
'(an older builder image, or a missing manifest) - the next build to this target ' +
|
|
151
|
+
're-uploads every file');
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
ctx.logger.warn(`could not read the Cache-Control the builder reported in ${reportKey} ` +
|
|
155
|
+
`(${errorMessage(err)}) - the next build to this target re-uploads every file`);
|
|
156
|
+
}
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Record what a successful build wrote: `applied` with the rules when the
|
|
161
|
+
* agent's manifest at `reportKey` confirms them, `unconfirmed` otherwise.
|
|
162
|
+
* Non-fatal: the site is already published, so a failed write only warns and
|
|
163
|
+
* leaves the record as it was.
|
|
164
|
+
*/
|
|
165
|
+
export async function recordCacheControl(ctx, target, reportKey) {
|
|
166
|
+
const record = (await agentConfirmedRules(ctx, reportKey))
|
|
167
|
+
? { status: 'applied', rules: ctx.config.cacheControl }
|
|
168
|
+
: { status: 'unconfirmed' };
|
|
169
|
+
try {
|
|
170
|
+
await writeCacheControlRecord(ctx, target, record);
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
ctx.logger.warn(`could not record the Cache-Control this build wrote in ${cacheControlRecordKey(target)} ` +
|
|
174
|
+
`(${errorMessage(err)}); the record is left as it was`);
|
|
175
|
+
}
|
|
176
|
+
}
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type Terminal } from 'blogwright-core';
|
|
2
|
+
import type { AwsHost } from './aws-session.js';
|
|
2
3
|
import { type ContextOptions, type OpsContext } from './context.js';
|
|
3
|
-
import type { PackageManager, Ports } from './ports.js';
|
|
4
|
+
import type { AwsLogin, PackageManager, Ports } from './ports.js';
|
|
4
5
|
/** Builds the Terminal after flag parsing, so --plain shapes the whole session. */
|
|
5
6
|
export type TerminalFactory = (opts: {
|
|
6
7
|
plain: boolean;
|
|
@@ -46,9 +47,14 @@ export type ContextFactory = (opts: ContextOptions) => Promise<OpsContext>;
|
|
|
46
47
|
* `cli.test.ts` pins directly), and likewise `rollback`, `delete`,
|
|
47
48
|
* `destroy`, `history`, `logs` and `preview` dispatched successfully. A
|
|
48
49
|
* plugin NAMESPACE is not a built-in and never was: dispatching one runs
|
|
49
|
-
* discovery by construction (case 1), which is the whole reason a
|
|
50
|
+
* discovery by construction (case 1), which is the whole reason a
|
|
50
51
|
* plugin's actions can reach `--help`, and its own refusals, once no
|
|
51
52
|
* branch in this module knows any namespace by name (task 29).
|
|
53
|
+
*
|
|
54
|
+
* `deploy` is the one built-in with a fifth, late path: once the site is
|
|
55
|
+
* published it calls this factory to run each installed plugin's
|
|
56
|
+
* `afterDeploy` hook (`runAfterDeployHooks`, `plugin-commands.ts`). A deploy
|
|
57
|
+
* that fails before then - and every other built-in - never reaches it.
|
|
52
58
|
*/
|
|
53
59
|
export type DiscoveryPortsFactory = () => Pick<Ports, 'fs' | 'loader'>;
|
|
54
60
|
/**
|
|
@@ -70,4 +76,17 @@ export type DiscoveryPortsFactory = () => Pick<Ports, 'fs' | 'loader'>;
|
|
|
70
76
|
* can end at - constructs no package manager at all.
|
|
71
77
|
*/
|
|
72
78
|
export type PackageManagerFactory = () => PackageManager;
|
|
73
|
-
|
|
79
|
+
/** What the pre-context AWS paths need: the machine AWS resolution reads, and the sign-in port. */
|
|
80
|
+
export interface AwsAccess {
|
|
81
|
+
host: AwsHost;
|
|
82
|
+
awsLogin: AwsLogin;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Builds the {@link AwsAccess} `blogwright whoami` and `blogwright init`
|
|
86
|
+
* resolve an AWS session through - both run before any `OpsContext` exists,
|
|
87
|
+
* so they cannot take it from `Ports`. Called only on those two paths.
|
|
88
|
+
* Declared as a required parameter for the reason `ContextFactory` is: the
|
|
89
|
+
* composition root (`bin.ts`) is the only place real adapters get constructed.
|
|
90
|
+
*/
|
|
91
|
+
export type AwsAccessFactory = () => AwsAccess;
|
|
92
|
+
export declare function main(argv: string[], makeTerminal: TerminalFactory, makeContext: ContextFactory, makeDiscoveryPorts: DiscoveryPortsFactory, makePackages: PackageManagerFactory, makeAwsAccess: AwsAccessFactory): Promise<number>;
|