blogwright 0.5.0 → 0.7.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/agent/agent-manifest.json +1 -1
- package/dist/adapters/node-dns.d.ts +20 -0
- package/dist/adapters/node-dns.js +49 -0
- package/dist/cli.js +6 -0
- package/dist/commands.js +29 -5
- package/dist/context.d.ts +20 -0
- package/dist/context.js +47 -0
- package/dist/domains.d.ts +46 -0
- package/dist/domains.js +125 -0
- package/dist/nodes.d.ts +11 -0
- package/dist/nodes.js +442 -66
- package/dist/ports.d.ts +15 -0
- package/dist/router-function.d.ts +29 -0
- package/dist/router-function.js +149 -0
- package/package.json +3 -3
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node:dns` adapter for the DnsPort: SOA lookups through the system resolver,
|
|
3
|
+
* retried once against public resolvers when the system resolver fails to
|
|
4
|
+
* answer. A definite negative (the name has no SOA) is an answer, not a
|
|
5
|
+
* failure, and never triggers the fallback.
|
|
6
|
+
*/
|
|
7
|
+
import type { DnsPort } from '../ports.js';
|
|
8
|
+
/** The slice of a resolver the adapter uses; both `dns.promises` and a `Resolver` fit. */
|
|
9
|
+
export interface SoaResolver {
|
|
10
|
+
resolveSoa(name: string): Promise<{
|
|
11
|
+
nsname: string;
|
|
12
|
+
hostmaster: string;
|
|
13
|
+
serial: number;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Build the port. `system` and `publicResolver` are injectable for tests;
|
|
18
|
+
* `publicResolver` is built lazily so a run that never needs it makes none.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createNodeDns(system?: SoaResolver, publicResolver?: () => SoaResolver): DnsPort;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `node:dns` adapter for the DnsPort: SOA lookups through the system resolver,
|
|
3
|
+
* retried once against public resolvers when the system resolver fails to
|
|
4
|
+
* answer. A definite negative (the name has no SOA) is an answer, not a
|
|
5
|
+
* failure, and never triggers the fallback.
|
|
6
|
+
*/
|
|
7
|
+
import { promises as dns } from 'node:dns';
|
|
8
|
+
/** Public resolvers tried, in order, when the system resolver cannot answer. */
|
|
9
|
+
const PUBLIC_RESOLVERS = ['1.1.1.1', '8.8.8.8'];
|
|
10
|
+
/** Codes meaning "the resolver answered: this name has no SOA record". */
|
|
11
|
+
const NEGATIVE = new Set(['ENODATA', 'ENOTFOUND', 'NXDOMAIN']);
|
|
12
|
+
function code(err) {
|
|
13
|
+
return typeof err === 'object' && err !== null && 'code' in err
|
|
14
|
+
? String(err.code)
|
|
15
|
+
: '';
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Build the port. `system` and `publicResolver` are injectable for tests;
|
|
19
|
+
* `publicResolver` is built lazily so a run that never needs it makes none.
|
|
20
|
+
*/
|
|
21
|
+
export function createNodeDns(system = dns, publicResolver = () => {
|
|
22
|
+
const resolver = new dns.Resolver({ timeout: 3000, tries: 1 });
|
|
23
|
+
resolver.setServers([...PUBLIC_RESOLVERS]);
|
|
24
|
+
return resolver;
|
|
25
|
+
}) {
|
|
26
|
+
async function ask(resolver, name) {
|
|
27
|
+
try {
|
|
28
|
+
const r = await resolver.resolveSoa(name);
|
|
29
|
+
return `${r.nsname} ${r.hostmaster} ${r.serial}`;
|
|
30
|
+
}
|
|
31
|
+
catch (err) {
|
|
32
|
+
if (NEGATIVE.has(code(err)))
|
|
33
|
+
return undefined;
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
async soa(name) {
|
|
39
|
+
try {
|
|
40
|
+
return await ask(system, name);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// The system resolver did not answer; ask the public ones. Their own
|
|
44
|
+
// failure propagates so the caller can tell "no answer" from "no SOA".
|
|
45
|
+
return await ask(publicResolver(), name);
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -70,6 +70,10 @@ Options:
|
|
|
70
70
|
--force-unlock Replace the environment lock a deploy, rollback, stage,
|
|
71
71
|
promote or delete left behind when it stopped; only once
|
|
72
72
|
that command is known to be no longer running
|
|
73
|
+
--prune-aliases With bootstrap: detach attached CloudFront aliases that
|
|
74
|
+
the config does not name. Without it they are reported
|
|
75
|
+
and left attached, so a config edit never drops a
|
|
76
|
+
live hostname.
|
|
73
77
|
--switch-mode Allow bootstrap to change a bootstrapped stack between
|
|
74
78
|
static and SSR serving. Without it that cutover is
|
|
75
79
|
refused, because the distribution moves before a deploy
|
|
@@ -281,6 +285,7 @@ export async function main(argv, makeTerminal, makeContext, makeDiscoveryPorts,
|
|
|
281
285
|
// form would reject the flag the usage text and docs advertise.
|
|
282
286
|
'switch-mode': { type: 'boolean', default: false },
|
|
283
287
|
'force-unlock': { type: 'boolean', default: false },
|
|
288
|
+
'prune-aliases': { type: 'boolean', default: false },
|
|
284
289
|
staged: { type: 'boolean', default: false },
|
|
285
290
|
rebuild: { type: 'boolean', default: false },
|
|
286
291
|
yes: { type: 'boolean', default: false },
|
|
@@ -419,6 +424,7 @@ export async function main(argv, makeTerminal, makeContext, makeDiscoveryPorts,
|
|
|
419
424
|
domain: values.domain,
|
|
420
425
|
endpointOverride: values.endpoint,
|
|
421
426
|
profile: values.profile,
|
|
427
|
+
pruneAliases: command === 'bootstrap' && values['prune-aliases'],
|
|
422
428
|
ports: { terminal },
|
|
423
429
|
});
|
|
424
430
|
switch (command) {
|
package/dist/commands.js
CHANGED
|
@@ -6,7 +6,7 @@ import { applyGraph, destroyGraph } from './graph.js';
|
|
|
6
6
|
import { forgetLiveRelease, markLiveReleasePublishing, recordLiveRelease, } from './live-release.js';
|
|
7
7
|
import { assertEnvUnlocked, withEnvLock } from './lock.js';
|
|
8
8
|
import { clearRunningMicrovms } from './microvms.js';
|
|
9
|
-
import { buildNodes, reconcileBuilderImage, reconcileResponseHeadersOnDeploy } from './nodes.js';
|
|
9
|
+
import { buildNodes, reconcileBuilderImage, reconcileResponseHeadersOnDeploy, reconcileRouterFunction, } from './nodes.js';
|
|
10
10
|
import { describeInvalidation, formatDuration, logStatusEntries, historyHasRevisions, historyStatus, historyTime, NO_REVISION, renderHistoryTable, renderSummary, } from './render.js';
|
|
11
11
|
import { rollbackToStagedRelease, runAfterPublish } from './releases.js';
|
|
12
12
|
import { buildRepoZip, COMMIT_FILE, listRepoFiles } from './repo.js';
|
|
@@ -292,6 +292,8 @@ async function deployLocked(ctx, opts, { cwd, hash, startedAt }) {
|
|
|
292
292
|
artifact = await recordDeployArtifact(ctx, hash, artifactKey);
|
|
293
293
|
await noteLiveRelease(ctx, artifact, 'deploy');
|
|
294
294
|
}
|
|
295
|
+
// The content is live, so a redirect to a new page never answers before the page exists.
|
|
296
|
+
const router = await reconcileRouterFunction(ctx);
|
|
295
297
|
// The site is live - plugins' post-deploy steps (the pds sync, for one) run now.
|
|
296
298
|
await opts.afterDeploy(ctx);
|
|
297
299
|
const url = siteBaseUrl(ctx);
|
|
@@ -303,10 +305,22 @@ async function deployLocked(ctx, opts, { cwd, hash, startedAt }) {
|
|
|
303
305
|
: hash,
|
|
304
306
|
},
|
|
305
307
|
{ label: 'environment', value: ctx.env },
|
|
306
|
-
{
|
|
308
|
+
{
|
|
309
|
+
label: 'source',
|
|
310
|
+
value: `${fileCount} files, ${(zipBytes / 1024).toFixed(0)} KiB`,
|
|
311
|
+
},
|
|
307
312
|
{ label: 'build', value: formatDuration(manifest.durationMs) },
|
|
308
313
|
...(artifact ? [{ label: 'release', value: describeRelease(artifact) }] : []),
|
|
309
314
|
{ label: 'invalidated', value: describeInvalidation(invalidation) },
|
|
315
|
+
...(router.status === 'not-bootstrapped' ||
|
|
316
|
+
(router.redirects === 0 && router.status === 'unchanged')
|
|
317
|
+
? []
|
|
318
|
+
: [
|
|
319
|
+
{
|
|
320
|
+
label: 'redirects',
|
|
321
|
+
value: `${router.redirects} (router function ${router.status})`,
|
|
322
|
+
},
|
|
323
|
+
]),
|
|
310
324
|
...(url ? [{ label: 'site', value: colors.cyan(url) }] : []),
|
|
311
325
|
];
|
|
312
326
|
for (const line of renderSummary('deploy summary', rows, ctx.ports.terminal.isInteractive)) {
|
|
@@ -455,7 +469,9 @@ export async function previewDeploy(ctx, id, opts = {}) {
|
|
|
455
469
|
ctx.logger.info(colors.bold(`Preview deploy ${id} (${hash})`));
|
|
456
470
|
const files = await listRepoFiles(ctx.ports, cwd, ctx.config.sourceIgnore, ctx.config.sourceInclude);
|
|
457
471
|
ctx.logger.step(`zipping ${files.length} files`);
|
|
458
|
-
const zip = await buildRepoZip(ctx.ports.fs, cwd, files, {
|
|
472
|
+
const zip = await buildRepoZip(ctx.ports.fs, cwd, files, {
|
|
473
|
+
[COMMIT_FILE]: hash,
|
|
474
|
+
});
|
|
459
475
|
const sourceKey = `build/${hash}.zip`;
|
|
460
476
|
await ctx.clients.s3.putObject(ctx.names.bucket, sourceKey, zip, 'application/zip');
|
|
461
477
|
// Rebuild the shared preview builder image if the agent bundle changed (no-op when
|
|
@@ -627,12 +643,20 @@ export async function readNodeStatus(nodes, ctx) {
|
|
|
627
643
|
exists = await node.read(ctx);
|
|
628
644
|
}
|
|
629
645
|
catch (err) {
|
|
630
|
-
entries.push({
|
|
646
|
+
entries.push({
|
|
647
|
+
title: node.title,
|
|
648
|
+
state: 'error',
|
|
649
|
+
detail: err.message,
|
|
650
|
+
});
|
|
631
651
|
continue;
|
|
632
652
|
}
|
|
633
653
|
const outputs = ctx.state.resources[node.id];
|
|
634
654
|
const detail = outputs ? JSON.stringify(outputs) : undefined;
|
|
635
|
-
entries.push({
|
|
655
|
+
entries.push({
|
|
656
|
+
title: node.title,
|
|
657
|
+
state: exists ? 'present' : 'missing',
|
|
658
|
+
detail,
|
|
659
|
+
});
|
|
636
660
|
}
|
|
637
661
|
return entries;
|
|
638
662
|
}
|
package/dist/context.d.ts
CHANGED
|
@@ -7,6 +7,12 @@ export interface OpsContext {
|
|
|
7
7
|
domain: string | undefined;
|
|
8
8
|
/** True for the shared preview stack (host-routed, per-PR prefixes). */
|
|
9
9
|
preview: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* `bootstrap --prune-aliases`: detach attached aliases that config does not
|
|
12
|
+
* name. False for every other run, so a reconcile never drops a live
|
|
13
|
+
* hostname as a side effect.
|
|
14
|
+
*/
|
|
15
|
+
pruneAliases: boolean;
|
|
10
16
|
config: OpsConfig;
|
|
11
17
|
/**
|
|
12
18
|
* The environment's config file exactly as parsed, before `OpsConfig`'s
|
|
@@ -53,12 +59,26 @@ export interface OpsContext {
|
|
|
53
59
|
* trace back to the project from a billing or resource listing.
|
|
54
60
|
*/
|
|
55
61
|
export declare function deriveAppTag(config: Pick<OpsConfig, 'app'>, domain: string | undefined, repoRoot: string): string;
|
|
62
|
+
/**
|
|
63
|
+
* The multi-domain rules that depend on the effective domain (`--domain` can
|
|
64
|
+
* supply or override the config file's) or on the stack: aliases need a
|
|
65
|
+
* primary to be aliases of, must not repeat it, and a preview stack serves one
|
|
66
|
+
* wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
|
|
67
|
+
*/
|
|
68
|
+
export declare function assertDomainSettings(config: Pick<OpsConfig, 'aliases' | 'redirectToPrimary'> & Partial<Pick<OpsConfig, 'manageDns' | 'redirects'>>, domain: string | undefined, preview: boolean): void;
|
|
69
|
+
/**
|
|
70
|
+
* The compiled router source depends on the effective domain and on `ssr`, so
|
|
71
|
+
* its size is checked here, before any AWS call.
|
|
72
|
+
*/
|
|
73
|
+
export declare function assertRouterFits(config: OpsConfig, domain: string | undefined): void;
|
|
56
74
|
export interface ContextOptions {
|
|
57
75
|
env: string;
|
|
58
76
|
configPath?: string | undefined;
|
|
59
77
|
domain?: string | undefined;
|
|
60
78
|
endpointOverride?: string | undefined;
|
|
61
79
|
preview?: boolean | undefined;
|
|
80
|
+
/** `--prune-aliases`; see {@link OpsContext.pruneAliases}. */
|
|
81
|
+
pruneAliases?: boolean | undefined;
|
|
62
82
|
/** `--profile`: the first row of AWS profile resolution. */
|
|
63
83
|
profile?: string | undefined;
|
|
64
84
|
/** The environment AWS resolution reads; defaults to `process.env`. */
|
package/dist/context.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { ROUTER_CODE_LIMIT, routerCodeFits, ssrRouterCode, staticRouterCode, } from './router-function.js';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { basename, join, relative, resolve } from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { createNodeFileSystem, createNodeTerminal, deriveNames, findRepoRoot, parseConfigDocument, StateStore, } from 'blogwright-core';
|
|
6
7
|
import { createFetchPing } from './adapters/fetch-ping.js';
|
|
8
|
+
import { createNodeDns } from './adapters/node-dns.js';
|
|
7
9
|
import { createNodeModuleLoader } from './adapters/node-module-loader.js';
|
|
8
10
|
import { createProcessAwsLogin } from './adapters/process-aws-login.js';
|
|
9
11
|
import { createProcessVcs } from './adapters/process-vcs.js';
|
|
@@ -17,6 +19,46 @@ import { createLogger } from './logger.js';
|
|
|
17
19
|
export function deriveAppTag(config, domain, repoRoot) {
|
|
18
20
|
return config.app ?? domain ?? basename(repoRoot);
|
|
19
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* The multi-domain rules that depend on the effective domain (`--domain` can
|
|
24
|
+
* supply or override the config file's) or on the stack: aliases need a
|
|
25
|
+
* primary to be aliases of, must not repeat it, and a preview stack serves one
|
|
26
|
+
* wildcard host so it takes neither `aliases` nor `redirectToPrimary`.
|
|
27
|
+
*/
|
|
28
|
+
export function assertDomainSettings(config, domain, preview) {
|
|
29
|
+
if (preview && (config.redirects?.length ?? 0) > 0) {
|
|
30
|
+
throw new Error('config.redirects is not valid for a preview environment: the preview host router does not apply redirects');
|
|
31
|
+
}
|
|
32
|
+
if (preview && (config.aliases.length > 0 || config.redirectToPrimary || config.manageDns)) {
|
|
33
|
+
throw new Error('config.aliases, config.redirectToPrimary and config.manageDns are not valid for a preview environment: ' +
|
|
34
|
+
'the preview stack serves one wildcard host');
|
|
35
|
+
}
|
|
36
|
+
if (config.aliases.length > 0 && !domain) {
|
|
37
|
+
throw new Error('config.aliases requires a primary domain (config.domain or --domain)');
|
|
38
|
+
}
|
|
39
|
+
if (domain && config.aliases.includes(domain)) {
|
|
40
|
+
throw new Error(`config.aliases must not repeat the primary domain ("${domain}")`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The compiled router source depends on the effective domain and on `ssr`, so
|
|
45
|
+
* its size is checked here, before any AWS call.
|
|
46
|
+
*/
|
|
47
|
+
export function assertRouterFits(config, domain) {
|
|
48
|
+
if (config.redirects.length === 0)
|
|
49
|
+
return;
|
|
50
|
+
const alias = config.redirectToPrimary && domain && config.aliases.length > 0
|
|
51
|
+
? { primary: domain, aliases: config.aliases }
|
|
52
|
+
: undefined;
|
|
53
|
+
const code = config.ssr
|
|
54
|
+
? ssrRouterCode(alias, config.redirects)
|
|
55
|
+
: staticRouterCode(alias, config.redirects);
|
|
56
|
+
if (!routerCodeFits(code)) {
|
|
57
|
+
throw new Error(`config.redirects compiles to a ${Buffer.byteLength(code, 'utf8')}-byte router function, ` +
|
|
58
|
+
`over the CloudFront Function limit of ${ROUTER_CODE_LIMIT} bytes (${config.redirects.length} ` +
|
|
59
|
+
'entries); shorten the map or move redirects to the application');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
20
62
|
/**
|
|
21
63
|
* The real adapter for every port not supplied in `overrides`. Shared by
|
|
22
64
|
* `createContext` and the pre-context paths (`whoami`, `init`) through
|
|
@@ -30,6 +72,7 @@ function createPorts(overrides = {}) {
|
|
|
30
72
|
ping: overrides.ping ?? createFetchPing(),
|
|
31
73
|
loader: overrides.loader ?? createNodeModuleLoader(),
|
|
32
74
|
awsLogin: overrides.awsLogin ?? createProcessAwsLogin(),
|
|
75
|
+
dns: overrides.dns ?? createNodeDns(),
|
|
33
76
|
};
|
|
34
77
|
}
|
|
35
78
|
/** The operator's machine as AWS resolution sees it, from `process` and `os`. */
|
|
@@ -162,6 +205,9 @@ export async function createContext(opts) {
|
|
|
162
205
|
configPath: opts.configPath,
|
|
163
206
|
});
|
|
164
207
|
const domain = opts.domain ?? config.domain;
|
|
208
|
+
assertDomainSettings(config, domain, Boolean(opts.preview));
|
|
209
|
+
if (!opts.preview)
|
|
210
|
+
assertRouterFits(config, domain);
|
|
165
211
|
const session = await resolveAwsSession({
|
|
166
212
|
region: config.region,
|
|
167
213
|
endpointOverride: opts.endpointOverride,
|
|
@@ -184,6 +230,7 @@ export async function createContext(opts) {
|
|
|
184
230
|
env: opts.env,
|
|
185
231
|
domain,
|
|
186
232
|
preview: opts.preview ?? false,
|
|
233
|
+
pruneAliases: opts.pruneAliases ?? false,
|
|
187
234
|
config,
|
|
188
235
|
configDocument,
|
|
189
236
|
names,
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hostnames a production environment serves and the questions asked about
|
|
3
|
+
* them: which set the certificate and distribution should carry, which
|
|
4
|
+
* attached aliases config does not name, which DNS zone a host sits in, and
|
|
5
|
+
* whether it is that zone's apex.
|
|
6
|
+
*/
|
|
7
|
+
import type { AwsClients } from 'blogwright-core';
|
|
8
|
+
import type { OpsContext } from './context.js';
|
|
9
|
+
import type { DnsPort } from './ports.js';
|
|
10
|
+
/** The primary then the configured aliases; empty when no domain is configured. */
|
|
11
|
+
export declare function configuredHostnames(ctx: Pick<OpsContext, 'domain' | 'config'>): string[];
|
|
12
|
+
/**
|
|
13
|
+
* The hostnames this run should serve: `configuredHostnames` plus any alias
|
|
14
|
+
* already attached to the distribution that config does not name. Those are
|
|
15
|
+
* kept (and kept on the certificate) so editing config never drops a live
|
|
16
|
+
* host; `--prune-aliases` leaves them out. Reports each such alias once.
|
|
17
|
+
*/
|
|
18
|
+
export declare function desiredHostnames(ctx: OpsContext): Promise<string[]>;
|
|
19
|
+
/** What the nodes after the certificate should treat as the site's hostnames. */
|
|
20
|
+
export declare function siteHostnames(ctx: OpsContext): string[];
|
|
21
|
+
/** The names the recorded certificate was requested for; a pre-aliases certificate covers the primary. */
|
|
22
|
+
export declare function recordedDomains(ctx: OpsContext): string[];
|
|
23
|
+
export declare function sameSet(a: readonly string[], b: readonly string[]): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* ACM idempotency token (`\w+`, at most 32): stable for one site, environment
|
|
26
|
+
* and name set, so a retry of the same request reuses the certificate while a
|
|
27
|
+
* changed set requests a new one.
|
|
28
|
+
*/
|
|
29
|
+
export declare function certificateToken(siteName: string, env: string, names: readonly string[]): string;
|
|
30
|
+
/**
|
|
31
|
+
* The apex of the DNS zone `host` lives in, found by asking DNS: walk from the
|
|
32
|
+
* host up through its parents and take the highest name that answers with the
|
|
33
|
+
* same SOA as the first that does. Resolvers follow a CNAME when asked for SOA,
|
|
34
|
+
* so `www` aliased to an apex answers with the apex's record - requiring the
|
|
35
|
+
* run of identical records to end at the real apex handles that, and handles
|
|
36
|
+
* multi-label suffixes such as `example.co.uk` without a suffix list.
|
|
37
|
+
* `undefined` when nothing answers or no resolver could be reached.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findZoneApex(dns: DnsPort, host: string): Promise<string | undefined>;
|
|
40
|
+
/** The Route 53 hosted zone holding `host`, trying the host and then each parent. */
|
|
41
|
+
export declare function findHostedZone(route53: Pick<AwsClients['route53'], 'hostedZoneId'>, host: string): Promise<{
|
|
42
|
+
zoneId: string;
|
|
43
|
+
zone: string;
|
|
44
|
+
} | undefined>;
|
|
45
|
+
/** One printed routing instruction for a host that blogwright does not manage DNS for. */
|
|
46
|
+
export declare function routingGuidance(dns: DnsPort, host: string, target: string): Promise<string>;
|
package/dist/domains.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hostnames a production environment serves and the questions asked about
|
|
3
|
+
* them: which set the certificate and distribution should carry, which
|
|
4
|
+
* attached aliases config does not name, which DNS zone a host sits in, and
|
|
5
|
+
* whether it is that zone's apex.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
/** The primary then the configured aliases; empty when no domain is configured. */
|
|
9
|
+
export function configuredHostnames(ctx) {
|
|
10
|
+
return ctx.domain ? [ctx.domain, ...ctx.config.aliases] : [];
|
|
11
|
+
}
|
|
12
|
+
/** Per-run desired set, so the certificate and distribution nodes agree and drift is reported once. */
|
|
13
|
+
const desiredCache = new WeakMap();
|
|
14
|
+
/**
|
|
15
|
+
* The hostnames this run should serve: `configuredHostnames` plus any alias
|
|
16
|
+
* already attached to the distribution that config does not name. Those are
|
|
17
|
+
* kept (and kept on the certificate) so editing config never drops a live
|
|
18
|
+
* host; `--prune-aliases` leaves them out. Reports each such alias once.
|
|
19
|
+
*/
|
|
20
|
+
export async function desiredHostnames(ctx) {
|
|
21
|
+
const cached = desiredCache.get(ctx);
|
|
22
|
+
if (cached)
|
|
23
|
+
return cached;
|
|
24
|
+
const configured = configuredHostnames(ctx);
|
|
25
|
+
let desired = configured;
|
|
26
|
+
const id = ctx.state.resources['cloudfront-distribution']?.id;
|
|
27
|
+
if (ctx.domain && typeof id === 'string') {
|
|
28
|
+
const live = await ctx.clients.cloudfront.getDistributionAliases(id);
|
|
29
|
+
const undeclared = (live?.aliases ?? []).filter((a) => !configured.includes(a)).sort();
|
|
30
|
+
if (undeclared.length > 0 && ctx.pruneAliases) {
|
|
31
|
+
ctx.logger.warn(`detaching aliases not in config: ${undeclared.join(', ')}`);
|
|
32
|
+
}
|
|
33
|
+
else if (undeclared.length > 0) {
|
|
34
|
+
for (const alias of undeclared) {
|
|
35
|
+
ctx.logger.warn(`${alias} is attached to the distribution but not named in config; leaving it ` +
|
|
36
|
+
'attached (run bootstrap --prune-aliases to detach it)');
|
|
37
|
+
}
|
|
38
|
+
desired = [...configured, ...undeclared];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
desiredCache.set(ctx, desired);
|
|
42
|
+
return desired;
|
|
43
|
+
}
|
|
44
|
+
/** What the nodes after the certificate should treat as the site's hostnames. */
|
|
45
|
+
export function siteHostnames(ctx) {
|
|
46
|
+
return desiredCache.get(ctx) ?? configuredHostnames(ctx);
|
|
47
|
+
}
|
|
48
|
+
/** The names the recorded certificate was requested for; a pre-aliases certificate covers the primary. */
|
|
49
|
+
export function recordedDomains(ctx) {
|
|
50
|
+
const recorded = ctx.state.resources['acm-certificate']?.domains;
|
|
51
|
+
if (Array.isArray(recorded))
|
|
52
|
+
return recorded;
|
|
53
|
+
return ctx.domain ? [ctx.domain] : [];
|
|
54
|
+
}
|
|
55
|
+
export function sameSet(a, b) {
|
|
56
|
+
return a.length === b.length && [...a].sort().every((name, i) => name === [...b].sort()[i]);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* ACM idempotency token (`\w+`, at most 32): stable for one site, environment
|
|
60
|
+
* and name set, so a retry of the same request reuses the certificate while a
|
|
61
|
+
* changed set requests a new one.
|
|
62
|
+
*/
|
|
63
|
+
export function certificateToken(siteName, env, names) {
|
|
64
|
+
return createHash('sha256')
|
|
65
|
+
.update(`${siteName}\n${env}\n${[...names].sort().join(',')}`)
|
|
66
|
+
.digest('hex')
|
|
67
|
+
.slice(0, 32);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The apex of the DNS zone `host` lives in, found by asking DNS: walk from the
|
|
71
|
+
* host up through its parents and take the highest name that answers with the
|
|
72
|
+
* same SOA as the first that does. Resolvers follow a CNAME when asked for SOA,
|
|
73
|
+
* so `www` aliased to an apex answers with the apex's record - requiring the
|
|
74
|
+
* run of identical records to end at the real apex handles that, and handles
|
|
75
|
+
* multi-label suffixes such as `example.co.uk` without a suffix list.
|
|
76
|
+
* `undefined` when nothing answers or no resolver could be reached.
|
|
77
|
+
*/
|
|
78
|
+
export async function findZoneApex(dns, host) {
|
|
79
|
+
const labels = host.split('.');
|
|
80
|
+
let apex;
|
|
81
|
+
try {
|
|
82
|
+
for (let i = 0; i < labels.length - 1; i++) {
|
|
83
|
+
const name = labels.slice(i).join('.');
|
|
84
|
+
const soa = await dns.soa(name);
|
|
85
|
+
if (apex === undefined) {
|
|
86
|
+
if (soa !== undefined)
|
|
87
|
+
apex = { name, soa };
|
|
88
|
+
}
|
|
89
|
+
else if (soa === apex.soa) {
|
|
90
|
+
apex = { name, soa };
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
return apex?.name;
|
|
101
|
+
}
|
|
102
|
+
/** The Route 53 hosted zone holding `host`, trying the host and then each parent. */
|
|
103
|
+
export async function findHostedZone(route53, host) {
|
|
104
|
+
const labels = host.split('.');
|
|
105
|
+
for (let i = 0; i < labels.length - 1; i++) {
|
|
106
|
+
const zone = labels.slice(i).join('.');
|
|
107
|
+
const zoneId = await route53.hostedZoneId(zone);
|
|
108
|
+
if (zoneId)
|
|
109
|
+
return { zoneId, zone };
|
|
110
|
+
}
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
/** One printed routing instruction for a host that blogwright does not manage DNS for. */
|
|
114
|
+
export async function routingGuidance(dns, host, target) {
|
|
115
|
+
const apex = await findZoneApex(dns, host);
|
|
116
|
+
if (apex === undefined) {
|
|
117
|
+
return (`${host} CNAME -> ${target} (if ${host} is a zone apex use ALIAS/ANAME, or A and AAAA ` +
|
|
118
|
+
'alias records, instead; its zone could not be looked up)');
|
|
119
|
+
}
|
|
120
|
+
if (apex === host) {
|
|
121
|
+
return (`${host} ALIAS/ANAME -> ${target} (or A and AAAA alias records where the DNS host ` +
|
|
122
|
+
'cannot flatten a CNAME at the apex)');
|
|
123
|
+
}
|
|
124
|
+
return `${host} CNAME -> ${target}`;
|
|
125
|
+
}
|
package/dist/nodes.d.ts
CHANGED
|
@@ -48,6 +48,17 @@ export declare function placeholderPackageZip(): Uint8Array;
|
|
|
48
48
|
* the record bootstrap keeps, so the deploy role needs no distribution read.
|
|
49
49
|
*/
|
|
50
50
|
export declare function reconcileResponseHeadersOnDeploy(ctx: OpsContext): Promise<void>;
|
|
51
|
+
/** True when an SSR distribution needs the viewer-request router attached. */
|
|
52
|
+
export declare function ssrNeedsRouter(ctx: OpsContext): boolean;
|
|
53
|
+
/**
|
|
54
|
+
* Deploy-time half of the router function: republish the source when the
|
|
55
|
+
* config now produces different code than the recorded `codeHash`, never
|
|
56
|
+
* touching the distribution. Returns what happened, for the deploy summary.
|
|
57
|
+
*/
|
|
58
|
+
export declare function reconcileRouterFunction(ctx: OpsContext): Promise<{
|
|
59
|
+
status: 'republished' | 'unchanged' | 'not-bootstrapped';
|
|
60
|
+
redirects: number;
|
|
61
|
+
}>;
|
|
51
62
|
/**
|
|
52
63
|
* The workflow's OIDC subject claim, scoped per environment to match how each one
|
|
53
64
|
* deploys: previews from any PR ref; staging from pushes to main; production from the
|