@jini-ai/devops 0.5.5 → 0.6.10

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/agent-jobs/jobs.js +33 -26
  3. package/dist/agent-jobs/node.d.ts +14 -0
  4. package/dist/agent-jobs/node.js +8 -3
  5. package/dist/checks/coverage/diff.js +21 -10
  6. package/dist/checks/coverage/disk.js +20 -13
  7. package/dist/checks/coverage/integrity.js +44 -39
  8. package/dist/checks/hardwiring-node.js +89 -73
  9. package/dist/checks/hardwiring.d.ts +5 -0
  10. package/dist/checks/hardwiring.js +75 -48
  11. package/dist/checks/node.js +6 -1
  12. package/dist/checks/published-types/index.js +30 -15
  13. package/dist/core/artifact-store.d.ts +35 -0
  14. package/dist/core/artifact-store.js +2 -0
  15. package/dist/deploy/host-kit.d.ts +3 -0
  16. package/dist/deploy/index.d.ts +1 -0
  17. package/dist/deploy/node.d.ts +10 -0
  18. package/dist/deploy/node.js +11 -3
  19. package/dist/deploy/reachability.d.ts +2 -2
  20. package/dist/deploy/reachability.js +164 -117
  21. package/dist/dns/approval.d.ts +61 -0
  22. package/dist/dns/approval.js +48 -0
  23. package/dist/dns/contract.d.ts +206 -0
  24. package/dist/dns/contract.js +30 -0
  25. package/dist/dns/delegation.d.ts +36 -0
  26. package/dist/dns/delegation.js +44 -0
  27. package/dist/dns/index.d.ts +15 -0
  28. package/dist/dns/index.js +15 -0
  29. package/dist/dns/manual.d.ts +28 -0
  30. package/dist/dns/manual.js +140 -0
  31. package/dist/dns/node/index.d.ts +8 -0
  32. package/dist/dns/node/index.js +8 -0
  33. package/dist/dns/node/resolver.d.ts +35 -0
  34. package/dist/dns/node/resolver.js +155 -0
  35. package/dist/dns/node/udp.d.ts +27 -0
  36. package/dist/dns/node/udp.js +39 -0
  37. package/dist/dns/node/wire.d.ts +36 -0
  38. package/dist/dns/node/wire.js +90 -0
  39. package/dist/dns/plan.d.ts +34 -0
  40. package/dist/dns/plan.js +242 -0
  41. package/dist/dns/records.d.ts +67 -0
  42. package/dist/dns/records.js +144 -0
  43. package/dist/dns/registry.d.ts +26 -0
  44. package/dist/dns/registry.js +59 -0
  45. package/dist/dns/spf.d.ts +23 -0
  46. package/dist/dns/spf.js +35 -0
  47. package/dist/dns/verify.d.ts +61 -0
  48. package/dist/dns/verify.js +109 -0
  49. package/dist/local-dev/index.js +36 -20
  50. package/dist/packaging/electron/archive.d.ts +7 -4
  51. package/dist/packaging/electron/archive.js +32 -25
  52. package/dist/packaging/electron/imports.d.ts +1 -1
  53. package/dist/packaging/electron/imports.js +39 -23
  54. package/dist/packaging/electron/staging.js +68 -47
  55. package/dist/source-control/commit.js +36 -18
  56. package/dist/source-control/registry.js +95 -59
  57. package/dist/static-export/node-adapters.js +26 -17
  58. package/dist/static-export/runner.js +185 -103
  59. package/dist/static-export/transforms.js +26 -23
  60. package/package.json +19 -7
@@ -0,0 +1,155 @@
1
+ /**
2
+ * @file The `node:dns` {@link AuthoritativeDnsPort} (moved here from the first host, review 13-dns
3
+ * #10: nothing in it is host specific; the host injects its address policy).
4
+ *
5
+ * `query` asks the zone's OWN nameserver (its hostname resolved to an address, then a fresh
6
+ * `Resolver` pointed at it with `setServers`), so "propagated" means the source of truth answers,
7
+ * not a recursive cache.
8
+ *
9
+ * `queryNs` reads the delegation from the PARENT zone's nameservers (review 13-dns #5): a parent
10
+ * publishes a child's NS set as a referral, which is what the registrar changed. A recursive
11
+ * resolver's answer can be cached or come from the child's own (possibly stale) NS records, which
12
+ * would let verification stop at the previous DNS host. Only the parent's server list itself is
13
+ * read recursively. A top-level zone (no parent below the root) is read recursively.
14
+ *
15
+ * Every failure maps onto the kernel's result convention and never throws: NXDOMAIN → rejected
16
+ * `not_found`, NODATA → ok with no answers, anything else (timeout, refused, SERVFAIL, a malformed
17
+ * or mismatched reply) → `unknown`. A nameserver whose only addresses fail the host's
18
+ * `isPublicAddress` policy is refused as `unknown`, so a hostile zone cannot point the probe at an
19
+ * internal port 53.
20
+ */
21
+ import { randomInt } from 'node:crypto';
22
+ import { isIP } from 'node:net';
23
+ import { Resolver } from 'node:dns/promises';
24
+ import { providerOk, providerRejected, providerUnknown } from '@jini-ai/core/provider-registry';
25
+ import { normalizeDnsName } from '../records.js';
26
+ import { createUdpDnsExchange } from './udp.js';
27
+ import { decodeNsReply, DNS_RCODE_NXDOMAIN, encodeNsQuery } from './wire.js';
28
+ /** One c-ares try per query: a slow server is `unknown` quickly and the verifier retries later. */
29
+ export const AUTHORITATIVE_DNS_TIMEOUT_MS = 5_000;
30
+ /** Addresses with the smallest TTL; an empty list carries no TTL. */
31
+ const addresses = (records) => ({
32
+ answers: records.map(record => record.address),
33
+ ...(records.length === 0 ? {} : { ttl: Math.min(...records.map(record => record.ttl)) }),
34
+ });
35
+ const quote = (chunk) => `"${chunk.replace(/(["\\])/g, '\\$1')}"`;
36
+ const CAA_TAGS = ['issue', 'issuewild', 'iodef'];
37
+ /** Presentation-format answers per type, the format the kernel's parsers read. */
38
+ const READERS = {
39
+ A: async (resolver, name) => addresses(await resolver.resolve4(name, { ttl: true })),
40
+ AAAA: async (resolver, name) => addresses(await resolver.resolve6(name, { ttl: true })),
41
+ CNAME: async (resolver, name) => ({ answers: await resolver.resolveCname(name) }),
42
+ // Character-strings stay quoted so the kernel re-joins a long (chunked) TXT value exactly.
43
+ TXT: async (resolver, name) => ({ answers: (await resolver.resolveTxt(name)).map(chunks => chunks.map(quote).join(' ')) }),
44
+ MX: async (resolver, name) => ({ answers: (await resolver.resolveMx(name)).map(record => `${record.priority} ${record.exchange}`) }),
45
+ CAA: async (resolver, name) => ({
46
+ answers: (await resolver.resolveCaa(name)).flatMap(record => CAA_TAGS.filter(tag => record[tag] !== undefined).map(tag => `${record.critical} ${tag} ${quote(record[tag])}`)),
47
+ }),
48
+ NS: async (resolver, name) => ({ answers: await resolver.resolveNs(name) }),
49
+ SRV: async (resolver, name) => ({ answers: (await resolver.resolveSrv(name)).map(record => `${record.priority} ${record.weight} ${record.port} ${record.name}`) }),
50
+ };
51
+ /** NXDOMAIN / NODATA / transport failure, per the port's result convention. */
52
+ async function settle(call, empty) {
53
+ try {
54
+ return providerOk({ value: await call() });
55
+ }
56
+ catch (error) {
57
+ const code = error?.code;
58
+ if (code === 'ENODATA')
59
+ return providerOk({ value: empty });
60
+ if (code === 'ENOTFOUND')
61
+ return providerRejected({ code: 'not_found', message: 'The name does not exist.' });
62
+ if (code === 'ETIMEOUT')
63
+ return providerUnknown({ code: 'timeout', message: 'The DNS server did not answer in time.' });
64
+ return providerUnknown({ code: 'network', message: 'The DNS query failed before an answer arrived.' });
65
+ }
66
+ }
67
+ /** `dev.example.com` → `example.com`; undefined for a top-level name. */
68
+ function parentOf(name) {
69
+ const dot = name.indexOf('.');
70
+ return dot < 0 ? undefined : name.slice(dot + 1);
71
+ }
72
+ /**
73
+ * Build the adapter.
74
+ * @param required.isPublicAddress - Host address policy: only addresses it accepts are queried.
75
+ * @complexity O(1) setup; each `query` is ≤ 3 DNS round trips (NS address A + AAAA, then the
76
+ * record); each `queryNs` walks up to the closest enclosing zone, then asks its servers in turn.
77
+ * @example createNodeAuthoritativeDnsResolver({ isPublicAddress: ({ address }) => policy(address) })
78
+ */
79
+ export function createNodeAuthoritativeDnsResolver(required, optional = {}) {
80
+ const timeoutMs = optional.timeoutMs ?? AUTHORITATIVE_DNS_TIMEOUT_MS;
81
+ const options = { timeout: timeoutMs, tries: 1 };
82
+ const create = optional.createResolver ?? (resolverOptions => new Resolver(resolverOptions));
83
+ const exchange = optional.exchange ?? createUdpDnsExchange();
84
+ const randomId = optional.randomId ?? (() => randomInt(0, 0x10000));
85
+ const bootstrap = create(options);
86
+ if (optional.bootstrapServers !== undefined)
87
+ bootstrap.setServers(optional.bootstrapServers);
88
+ const publicOnly = (addresses) => addresses.filter(address => required.isPublicAddress({ address }));
89
+ /** The nameserver's first public address (an address literal is used as given, if public). */
90
+ const nameserverAddress = async (nameserver) => {
91
+ if (isIP(nameserver) !== 0)
92
+ return publicOnly([nameserver])[0];
93
+ const [v4, v6] = await Promise.all([settle(() => bootstrap.resolve4(nameserver), []), settle(() => bootstrap.resolve6(nameserver), [])]);
94
+ const addresses = [v4, v6].flatMap(result => (result.status === 'ok' ? result.value : []));
95
+ return publicOnly(addresses)[0];
96
+ };
97
+ /** The NS set of the closest enclosing zone of `name` (a name without its own NS is not a zone cut). */
98
+ const enclosingServers = async (name) => {
99
+ for (let candidate = name; candidate !== undefined; candidate = parentOf(candidate)) {
100
+ const zone = candidate;
101
+ const result = await settle(() => bootstrap.resolveNs(zone), []);
102
+ if (result.status !== 'ok' || result.value.length > 0)
103
+ return result;
104
+ }
105
+ return providerUnknown({ code: 'network', message: `No zone enclosing ${name} has nameservers.` });
106
+ };
107
+ /** One NS question to one parent server; a mismatched id or truncated reply is not an answer. */
108
+ const askParent = async (address, zone) => {
109
+ try {
110
+ const id = randomId();
111
+ const reply = decodeNsReply({ message: await exchange({ address, message: encodeNsQuery({ id, name: zone }), timeoutMs }), name: zone });
112
+ if (reply.id !== id || reply.truncated)
113
+ return providerUnknown({ code: 'network', message: `The parent nameserver ${address} sent an unusable reply.` });
114
+ if (reply.rcode === DNS_RCODE_NXDOMAIN)
115
+ return providerRejected({ code: 'not_found', message: 'The name does not exist.' });
116
+ if (reply.rcode !== 0)
117
+ return providerUnknown({ code: 'network', message: `The parent nameserver ${address} refused the query (rcode ${reply.rcode}).` });
118
+ return providerOk({ value: reply.nameservers });
119
+ }
120
+ catch {
121
+ return providerUnknown({ code: 'network', message: 'The DNS query failed before an answer arrived.' });
122
+ }
123
+ };
124
+ /** The parent's delegation of `zone`, from the first parent server that gives a usable reply. */
125
+ const delegation = async (zone, parent) => {
126
+ const servers = await enclosingServers(parent);
127
+ if (servers.status !== 'ok')
128
+ return servers;
129
+ for (const server of servers.value) {
130
+ const address = await nameserverAddress(server);
131
+ const result = address === undefined ? undefined : await askParent(address, zone);
132
+ if (result !== undefined && result.status !== 'unknown')
133
+ return result;
134
+ }
135
+ return providerUnknown({ code: 'network', message: `No nameserver of ${parent} answered for the delegation of ${zone}.` });
136
+ };
137
+ return {
138
+ queryNs: ({ zone }) => {
139
+ const name = normalizeDnsName({ name: zone });
140
+ const parent = parentOf(name);
141
+ return parent === undefined ? settle(() => bootstrap.resolveNs(name), []) : delegation(name, parent);
142
+ },
143
+ query: async ({ name, type, nameserver }) => {
144
+ if (type === 'ALIAS')
145
+ return providerRejected({ code: 'unsupported', message: 'ALIAS is a DNS-host feature, not a record type a nameserver serves.' });
146
+ const address = await nameserverAddress(nameserver);
147
+ if (address === undefined)
148
+ return providerUnknown({ code: 'network', message: `The nameserver ${nameserver} has no public address.` });
149
+ const resolver = create(options);
150
+ resolver.setServers([address]);
151
+ return settle(() => READERS[type](resolver, name), { answers: [] });
152
+ },
153
+ };
154
+ }
155
+ //# sourceMappingURL=resolver.js.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @file The default {@link DnsExchange}: one DNS message over UDP (port 53) to one server address,
3
+ * the first datagram back is the reply. Socket factory and timers are injectable for tests.
4
+ */
5
+ import { type Socket } from 'node:dgram';
6
+ /** Send one DNS message to `address` and resolve with the reply; rejects on error or timeout. */
7
+ export type DnsExchange = (required: {
8
+ readonly address: string;
9
+ readonly message: Uint8Array;
10
+ readonly timeoutMs: number;
11
+ }) => Promise<Uint8Array>;
12
+ type SocketLike = Pick<Socket, 'once' | 'send' | 'close'>;
13
+ export interface UdpDnsExchangeOptions {
14
+ readonly createSocket?: (type: 'udp4' | 'udp6') => SocketLike;
15
+ /** Default 53. */
16
+ readonly port?: number;
17
+ readonly setTimer?: (callback: () => void, ms: number) => unknown;
18
+ readonly clearTimer?: (handle: unknown) => void;
19
+ }
20
+ /**
21
+ * Build the UDP exchange.
22
+ * @complexity O(1) per exchange: one datagram out, one in.
23
+ * @example createUdpDnsExchange({})
24
+ */
25
+ export declare function createUdpDnsExchange(_required?: Record<string, never>, optional?: UdpDnsExchangeOptions): DnsExchange;
26
+ export {};
27
+ //# sourceMappingURL=udp.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @file The default {@link DnsExchange}: one DNS message over UDP (port 53) to one server address,
3
+ * the first datagram back is the reply. Socket factory and timers are injectable for tests.
4
+ */
5
+ import { createSocket as nodeCreateSocket } from 'node:dgram';
6
+ import { isIP } from 'node:net';
7
+ /**
8
+ * Build the UDP exchange.
9
+ * @complexity O(1) per exchange: one datagram out, one in.
10
+ * @example createUdpDnsExchange({})
11
+ */
12
+ export function createUdpDnsExchange(_required = {}, optional = {}) {
13
+ const create = optional.createSocket ?? ((type) => nodeCreateSocket(type));
14
+ const setTimer = optional.setTimer ?? ((callback, ms) => setTimeout(callback, ms));
15
+ const clearTimer = optional.clearTimer ?? (handle => clearTimeout(handle));
16
+ return ({ address, message, timeoutMs }) => new Promise((resolve, reject) => {
17
+ const socket = create(isIP(address) === 6 ? 'udp6' : 'udp4');
18
+ let done = false;
19
+ const finish = (outcome) => {
20
+ if (done)
21
+ return;
22
+ done = true;
23
+ clearTimer(timer);
24
+ socket.close();
25
+ if ('error' in outcome)
26
+ reject(outcome.error);
27
+ else
28
+ resolve(outcome.reply);
29
+ };
30
+ const timer = setTimer(() => finish({ error: Object.assign(new Error('The DNS server did not answer in time.'), { code: 'ETIMEOUT' }) }), timeoutMs);
31
+ socket.once('error', error => finish({ error }));
32
+ socket.once('message', reply => finish({ reply: new Uint8Array(reply) }));
33
+ socket.send(message, optional.port ?? 53, address, error => {
34
+ if (error)
35
+ finish({ error });
36
+ });
37
+ });
38
+ }
39
+ //# sourceMappingURL=udp.js.map
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @file A minimal DNS wire codec for exactly one exchange: an NS question sent to a PARENT zone's
3
+ * nameserver, and the NS names in its answer or referral (authority) section. `node:dns` only
4
+ * exposes the answer section, but a parent publishes a child's delegation as a referral in the
5
+ * authority section — which is the registrar's truth that verification must read.
6
+ */
7
+ export declare const DNS_TYPE_NS = 2;
8
+ export declare const DNS_RCODE_NXDOMAIN = 3;
9
+ export interface NsReply {
10
+ readonly id: number;
11
+ readonly rcode: number;
12
+ /** TC bit: the reply did not fit a UDP datagram and is incomplete. */
13
+ readonly truncated: boolean;
14
+ /** NS targets owned by the asked name, from the answer and authority sections (lowercase, deduplicated). */
15
+ readonly nameservers: readonly string[];
16
+ }
17
+ /**
18
+ * A non-recursive (RD=0) NS query for `name`.
19
+ * @throws RangeError when a label exceeds 63 bytes (not a valid DNS name).
20
+ * @complexity O(n) in the name length.
21
+ */
22
+ export declare function encodeNsQuery(required: {
23
+ readonly id: number;
24
+ readonly name: string;
25
+ }, _optional?: {}): Uint8Array;
26
+ /**
27
+ * Decode a reply to {@link encodeNsQuery}: NS records owned by `name` in the answer and authority
28
+ * sections. Other records (SOA, glue) are skipped.
29
+ * @throws RangeError on a malformed or truncated message.
30
+ * @complexity O(message length).
31
+ */
32
+ export declare function decodeNsReply(required: {
33
+ readonly message: Uint8Array;
34
+ readonly name: string;
35
+ }, _optional?: {}): NsReply;
36
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @file A minimal DNS wire codec for exactly one exchange: an NS question sent to a PARENT zone's
3
+ * nameserver, and the NS names in its answer or referral (authority) section. `node:dns` only
4
+ * exposes the answer section, but a parent publishes a child's delegation as a referral in the
5
+ * authority section — which is the registrar's truth that verification must read.
6
+ */
7
+ export const DNS_TYPE_NS = 2;
8
+ const CLASS_IN = 1;
9
+ const HEADER_BYTES = 12;
10
+ const MAX_LABEL_BYTES = 63;
11
+ /** Bounds pointer chasing, so a hostile compression loop cannot spin forever. */
12
+ const MAX_POINTER_JUMPS = 32;
13
+ export const DNS_RCODE_NXDOMAIN = 3;
14
+ /**
15
+ * A non-recursive (RD=0) NS query for `name`.
16
+ * @throws RangeError when a label exceeds 63 bytes (not a valid DNS name).
17
+ * @complexity O(n) in the name length.
18
+ */
19
+ export function encodeNsQuery(required, _optional = {}) {
20
+ const encoder = new TextEncoder();
21
+ const qname = required.name.split('.').filter(label => label !== '').flatMap(label => {
22
+ const bytes = [...encoder.encode(label)];
23
+ if (bytes.length > MAX_LABEL_BYTES)
24
+ throw new RangeError(`The DNS label '${label}' is longer than ${MAX_LABEL_BYTES} bytes.`);
25
+ return [bytes.length, ...bytes];
26
+ });
27
+ const id = required.id & 0xffff;
28
+ return Uint8Array.from([id >> 8, id & 0xff, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ...qname, 0, 0, DNS_TYPE_NS, 0, CLASS_IN]);
29
+ }
30
+ function u16(message, offset) {
31
+ if (offset + 2 > message.length)
32
+ throw new RangeError('The DNS message is truncated.');
33
+ return (message[offset] << 8) | message[offset + 1];
34
+ }
35
+ function byteAt(message, offset) {
36
+ if (offset >= message.length)
37
+ throw new RangeError('The DNS message is truncated.');
38
+ return message[offset];
39
+ }
40
+ /** A possibly compressed name at `offset`, and the offset just past it in the record. */
41
+ function readName(message, offset) {
42
+ const labels = [];
43
+ let cursor = offset;
44
+ let next;
45
+ for (let jumps = 0; jumps <= MAX_POINTER_JUMPS;) {
46
+ const length = byteAt(message, cursor);
47
+ if (length === 0)
48
+ return { name: labels.join('.').toLowerCase(), next: next ?? cursor + 1 };
49
+ if (length >= 0xc0) {
50
+ next ??= cursor + 2;
51
+ cursor = u16(message, cursor) & 0x3fff;
52
+ jumps += 1;
53
+ }
54
+ else if (length > MAX_LABEL_BYTES || cursor + 1 + length > message.length) {
55
+ throw new RangeError('The DNS message has a malformed name.');
56
+ }
57
+ else {
58
+ labels.push(new TextDecoder().decode(message.subarray(cursor + 1, cursor + 1 + length)));
59
+ cursor += 1 + length;
60
+ }
61
+ }
62
+ throw new RangeError('The DNS message has a name compression loop.');
63
+ }
64
+ /**
65
+ * Decode a reply to {@link encodeNsQuery}: NS records owned by `name` in the answer and authority
66
+ * sections. Other records (SOA, glue) are skipped.
67
+ * @throws RangeError on a malformed or truncated message.
68
+ * @complexity O(message length).
69
+ */
70
+ export function decodeNsReply(required, _optional = {}) {
71
+ const { message } = required;
72
+ const target = required.name.toLowerCase().replace(/\.$/, '');
73
+ const flags = u16(message, 2);
74
+ let offset = HEADER_BYTES;
75
+ for (let question = u16(message, 4); question > 0; question -= 1)
76
+ offset = readName(message, offset).next + 4;
77
+ const nameservers = [];
78
+ for (let record = u16(message, 6) + u16(message, 8); record > 0; record -= 1) {
79
+ const owner = readName(message, offset);
80
+ const rdata = owner.next + 10;
81
+ const end = rdata + u16(message, owner.next + 8);
82
+ if (end > message.length)
83
+ throw new RangeError('The DNS message is truncated.');
84
+ if (u16(message, owner.next) === DNS_TYPE_NS && owner.name === target)
85
+ nameservers.push(readName(message, rdata).name);
86
+ offset = end;
87
+ }
88
+ return { id: u16(message, 0), rcode: flags & 0xf, truncated: (flags & 0x0200) !== 0, nameservers: [...new Set(nameservers)] };
89
+ }
90
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1,34 @@
1
+ import { type DnsChangePlan, type DnsInventory, type DnsPlanRequirement, type DnsRecord, type DnsRecordType } from './contract.js';
2
+ export interface PlanDnsChangesInput {
3
+ readonly providerId: string;
4
+ readonly zone: string;
5
+ readonly current: readonly DnsRecord[];
6
+ readonly requirements: readonly DnsPlanRequirement[];
7
+ readonly inventory: DnsInventory;
8
+ }
9
+ export interface PlanDnsChangesOptions {
10
+ /** The provider flattens a CNAME at the apex (so it is allowed there). Default false. */
11
+ readonly apexFlattening?: boolean;
12
+ /** When given, a required type outside this list blocks the plan. */
13
+ readonly recordTypes?: readonly DnsRecordType[];
14
+ readonly defaultTtl?: number;
15
+ }
16
+ /** Canonical JSON: object keys sorted, `undefined` members dropped, array order kept. */
17
+ export declare function canonicalJson(required: {
18
+ readonly value: unknown;
19
+ }, _optional?: {}): string;
20
+ /** sha-256 hex over the canonical plan, excluding any fingerprint it already carries. */
21
+ export declare function fingerprintPlan(required: {
22
+ readonly plan: Omit<DnsChangePlan, 'fingerprint'> & {
23
+ readonly fingerprint?: string;
24
+ };
25
+ }, _optional?: {}): string;
26
+ /**
27
+ * Plan the changes that make `current` satisfy `requirements`.
28
+ * A non-`complete` inventory yields zero changes and a blocker: a plan over a partial view could
29
+ * delete or shadow a record nobody looked at. Any blocker makes the plan unapprovable; changes for
30
+ * unblocked names are still listed so the operator sees the whole picture.
31
+ * @complexity O(r·c) over required and current RRsets.
32
+ */
33
+ export declare function planDnsChanges(required: PlanDnsChangesInput, optional?: PlanDnsChangesOptions): DnsChangePlan;
34
+ //# sourceMappingURL=plan.d.ts.map
@@ -0,0 +1,242 @@
1
+ /**
2
+ * @file The provider-neutral DNS planner. Planning is core, not per provider, so every provider
3
+ * gets identical, testable semantics; providers only list and (later) apply.
4
+ *
5
+ * Rule (lifted from the first host deploy plugin's DNS planner): preserve by default. Only address
6
+ * records (A/AAAA/CNAME/ALIAS) this engine owns (`managedBy: 'self'`) at a name that needs a
7
+ * different address are changed; a foreign or unmarked one blocks the name instead. Mail, TXT,
8
+ * CAA, wildcard and unrelated records are never removed — new values are merged into them and
9
+ * the untouched rest is disclosed in `preserved`.
10
+ */
11
+ import { createHash } from 'node:crypto';
12
+ import { DEFAULT_DNS_TTL, DNS_ADDRESS_TYPES, } from './contract.js';
13
+ import { buildRecord, dnsValueKey, normalizeDnsName, requirementValue, sameValueSet } from './records.js';
14
+ import { isSpfValue, mergeSpf } from './spf.js';
15
+ const OP_ORDER = { delete: 0, update: 1, create: 2 };
16
+ /** Canonical JSON: object keys sorted, `undefined` members dropped, array order kept. */
17
+ export function canonicalJson(required, _optional = {}) {
18
+ const { value } = required;
19
+ if (Array.isArray(value))
20
+ return `[${value.map(item => canonicalJson({ value: item })).join(',')}]`;
21
+ if (value !== null && typeof value === 'object') {
22
+ const record = value;
23
+ const members = Object.keys(record).filter(key => record[key] !== undefined).sort()
24
+ .map(key => `${JSON.stringify(key)}:${canonicalJson({ value: record[key] })}`);
25
+ return `{${members.join(',')}}`;
26
+ }
27
+ return JSON.stringify(value) ?? 'null';
28
+ }
29
+ /** sha-256 hex over the canonical plan, excluding any fingerprint it already carries. */
30
+ export function fingerprintPlan(required, _optional = {}) {
31
+ const { fingerprint: _ignored, ...body } = required.plan;
32
+ return createHash('sha256').update(canonicalJson({ value: body })).digest('hex');
33
+ }
34
+ function finalize(plan) {
35
+ return { ...plan, fingerprint: fingerprintPlan({ plan }) };
36
+ }
37
+ function normalizeRecord(record) {
38
+ return { ...record, name: normalizeDnsName({ name: record.name }) };
39
+ }
40
+ function recordKey(record) {
41
+ return `${record.name}|${record.type}`;
42
+ }
43
+ /** Group requirement records into desired RRsets (deduplicated values, smallest TTL wins). */
44
+ function desiredRecordSets(required) {
45
+ const sets = new Map();
46
+ const blockers = [];
47
+ for (const record of required.requirements.flatMap(requirement => requirement.records)) {
48
+ const name = normalizeDnsName({ name: record.name });
49
+ const value = requirementValue({ record });
50
+ if (value === undefined) {
51
+ blockers.push({ code: 'invalid_requirement', name, message: `The required ${record.type} value '${record.value}' at ${name} cannot be parsed.` });
52
+ continue;
53
+ }
54
+ const key = recordKey({ name, type: record.type });
55
+ const set = sets.get(key) ?? { name, type: record.type, ttl: record.ttl ?? required.defaultTtl, values: [] };
56
+ set.ttl = Math.min(set.ttl, record.ttl ?? set.ttl);
57
+ if (!set.values.some(existing => dnsValueKey({ value: existing }) === dnsValueKey({ value })))
58
+ set.values.push(value);
59
+ sets.set(key, set);
60
+ }
61
+ const records = [...sets.values()].sort((a, b) => recordKey(a).localeCompare(recordKey(b))).map(set => buildRecord(set));
62
+ return { records, blockers };
63
+ }
64
+ /** Apex CNAME on a non-flattening host, or a CNAME that would share its name with other data. */
65
+ function nameBlocker(ctx, name) {
66
+ const desiredHere = ctx.desired.filter(record => record.name === name);
67
+ const existingHere = ctx.current.filter(record => record.name === name);
68
+ const wantsAddress = desiredHere.some(record => DNS_ADDRESS_TYPES.has(record.type));
69
+ const hasCname = desiredHere.some(record => record.type === 'CNAME') || (!wantsAddress && existingHere.some(record => record.type === 'CNAME'));
70
+ const isApex = name === ctx.zone;
71
+ if (!hasCname || (isApex && ctx.apexFlattening))
72
+ return undefined;
73
+ if (isApex) {
74
+ return { code: 'apex_cname', name, message: `${name} is the zone apex; this DNS host cannot serve a CNAME there.`, suggestion: 'Use an ALIAS record or A/AAAA records at the apex, or a DNS host that flattens apex CNAMEs.' };
75
+ }
76
+ const others = [...desiredHere.filter(record => record.type !== 'CNAME'), ...existingHere.filter(record => !DNS_ADDRESS_TYPES.has(record.type))];
77
+ if (others.length === 0)
78
+ return undefined;
79
+ return { code: 'cname_coexistence', name, message: `A CNAME at ${name} cannot coexist with its ${[...new Set(others.map(record => record.type))].join('/')} record(s).`, suggestion: 'Point the name with A/AAAA records instead, or move the other records to a different name.' };
80
+ }
81
+ /** The address changes (deletes, updates, creates) that make one name serve `desired`. */
82
+ function addressChanges(name, desired, existing) {
83
+ const wanted = desired.map(record => record.type).join('/');
84
+ const changes = existing
85
+ .filter(record => !desired.some(want => want.type === record.type))
86
+ .map(record => ({ op: 'delete', before: record, reason: `The ${record.type} record at ${name} conflicts with the required ${wanted} record.` }));
87
+ for (const want of desired) {
88
+ const have = existing.find(record => record.type === want.type);
89
+ if (!have) {
90
+ changes.push({ op: 'create', after: want, reason: `Point ${name} at the required ${want.type} target.` });
91
+ }
92
+ else if (!sameValueSet({ left: have.values, right: want.values })) {
93
+ changes.push({ op: 'update', before: have, after: { ...have, ttl: want.ttl, values: want.values }, reason: `Replace the ${want.type} values at ${name} with the required target.` });
94
+ }
95
+ else {
96
+ // Already satisfied: the record is left untouched and shows up in `preserved`.
97
+ }
98
+ }
99
+ return changes;
100
+ }
101
+ function ownershipBlocker(name, foreign, desired) {
102
+ const types = [...new Set(foreign.map(record => record.type))].join('/');
103
+ const target = desired.map(record => `${record.type} ${record.values.map(value => dnsValueKey({ value })).join(', ')}`).join('; ');
104
+ return {
105
+ code: 'record_not_owned', name,
106
+ message: `The existing ${types} record at ${name} was not created by this engine (it is not marked as managed), so it is left untouched instead of being replaced or deleted.`,
107
+ suggestion: `If it is no longer needed, change it by hand at your DNS host to ${target}, then plan again.`,
108
+ };
109
+ }
110
+ /**
111
+ * Replace conflicting address records at one name with the desired address RRsets. Only a name
112
+ * that needs an address is touched, and only records marked `managedBy: 'self'` are ever replaced
113
+ * or deleted: anything else belongs to someone else, so the name is blocked instead.
114
+ */
115
+ function planAddressName(ctx, name) {
116
+ const desired = ctx.desired.filter(record => record.name === name && DNS_ADDRESS_TYPES.has(record.type));
117
+ // A TXT/MX/CAA-only requirement must not "replace" the name's addresses with nothing.
118
+ if (desired.length === 0)
119
+ return { changes: [], blockers: [] };
120
+ const existing = ctx.current.filter(record => record.name === name && DNS_ADDRESS_TYPES.has(record.type));
121
+ const changes = addressChanges(name, desired, existing);
122
+ const foreign = changes.flatMap(change => (change.before !== undefined && change.before.managedBy !== 'self' ? [change.before] : []));
123
+ return foreign.length === 0 ? { changes, blockers: [] } : { changes: [], blockers: [ownershipBlocker(name, foreign, desired)] };
124
+ }
125
+ /** Fold desired TXT values into an existing set; SPF is merged, never duplicated. */
126
+ function mergeTxtValues(existing, desired, name) {
127
+ const existingSpf = existing.filter(value => isSpfValue({ value }));
128
+ if (existingSpf.length > 1) {
129
+ return { blocker: { code: 'multiple_spf', name, message: `${name} already has ${existingSpf.length} SPF (v=spf1) records, which is invalid; merge them by hand first.` } };
130
+ }
131
+ const values = [...existing, ...desired.filter(value => !isSpfValue({ value }) && !existing.includes(value))];
132
+ const desiredSpf = desired.filter(value => isSpfValue({ value }));
133
+ if (desiredSpf.length === 0)
134
+ return { values };
135
+ const base = existingSpf[0];
136
+ const merged = desiredSpf.reduce((acc, addition) => mergeSpf({ base: acc, addition }), base ?? desiredSpf[0]);
137
+ return { values: base === undefined ? [...values, merged] : values.map(value => (value === base ? merged : value)) };
138
+ }
139
+ /** Additive merge for non-address RRsets: existing values stay, missing desired values are added. */
140
+ function mergedValues(have, want) {
141
+ if (want.type === 'TXT')
142
+ return mergeTxtValues(have.values, want.values, want.name);
143
+ const keys = new Set(have.values.map(value => dnsValueKey({ value })));
144
+ return { values: [...have.values, ...want.values.filter(value => !keys.has(dnsValueKey({ value })))] };
145
+ }
146
+ function planAdditive(ctx, want) {
147
+ const have = ctx.current.find(record => record.name === want.name && record.type === want.type);
148
+ const merged = mergedValues(have ?? buildRecord({ ...want, values: [] }), want);
149
+ if ('blocker' in merged)
150
+ return { changes: [], blockers: [merged.blocker] };
151
+ if (!have)
152
+ return { changes: [{ op: 'create', after: buildRecord({ ...want, values: merged.values }), reason: `Add the required ${want.type} record at ${want.name}.` }], blockers: [] };
153
+ if (sameValueSet({ left: have.values, right: merged.values }))
154
+ return { changes: [], blockers: [] };
155
+ return { changes: [{ op: 'update', before: have, after: { ...have, values: merged.values }, reason: `Add the required ${want.type} value(s) to ${want.name}, keeping the existing ones.` }], blockers: [] };
156
+ }
157
+ function caaAuthorizes(values, issuer, wildcard) {
158
+ const wildcardIssuers = values.filter(value => value.tag === 'issuewild');
159
+ const relevant = wildcard && wildcardIssuers.length > 0 ? wildcardIssuers : values.filter(value => value.tag === 'issue');
160
+ // No issue property at all means CAA does not restrict issuance (RFC 8659 §4).
161
+ return relevant.length === 0 || relevant.some(value => value.value.split(';')[0].trim().toLowerCase() === issuer);
162
+ }
163
+ /** CAA tree-climbing: the closest name (itself, then each parent) holding any CAA values. */
164
+ function relevantCaa(ctx, name) {
165
+ for (let candidate = name.replace(/^\*\./, ''); candidate !== ''; candidate = candidate.includes('.') ? candidate.slice(candidate.indexOf('.') + 1) : '') {
166
+ const values = [...ctx.current, ...ctx.desired].filter(record => record.name === candidate && record.type === 'CAA').flatMap(record => record.values);
167
+ if (values.length > 0)
168
+ return values;
169
+ }
170
+ return undefined;
171
+ }
172
+ function caaBlockers(ctx, requirements) {
173
+ const blockers = [];
174
+ for (const requirement of requirements) {
175
+ if (requirement.caa === undefined)
176
+ continue;
177
+ const issuer = requirement.caa.issuer.trim().toLowerCase();
178
+ const names = new Set([requirement.domain, ...requirement.records.map(record => record.name)].map(name => normalizeDnsName({ name })));
179
+ for (const name of names) {
180
+ const values = relevantCaa(ctx, name);
181
+ if (values && !caaAuthorizes(values, issuer, name.startsWith('*.'))) {
182
+ blockers.push({ code: 'caa_excludes_issuer', name, message: `The CAA records covering ${name} do not authorize ${issuer} to issue its certificate.`, suggestion: `Add a CAA record '0 issue "${issuer}"' or remove the restriction.` });
183
+ }
184
+ }
185
+ }
186
+ return blockers;
187
+ }
188
+ function unsupportedBlockers(desired, recordTypes) {
189
+ if (recordTypes === undefined)
190
+ return [];
191
+ return desired.filter(record => !recordTypes.includes(record.type))
192
+ .map(record => ({ code: 'unsupported_record_type', name: record.name, message: `This DNS host cannot serve the required ${record.type} record at ${record.name}.` }));
193
+ }
194
+ function planNames(ctx, skip) {
195
+ const changes = [];
196
+ const blockers = [];
197
+ const names = [...new Set(ctx.desired.map(record => record.name))].filter(name => !skip.has(name));
198
+ for (const name of names) {
199
+ const blocker = nameBlocker(ctx, name);
200
+ if (blocker) {
201
+ blockers.push(blocker);
202
+ continue;
203
+ }
204
+ const address = planAddressName(ctx, name);
205
+ changes.push(...address.changes);
206
+ blockers.push(...address.blockers);
207
+ for (const want of ctx.desired.filter(record => record.name === name && !DNS_ADDRESS_TYPES.has(record.type))) {
208
+ const planned = planAdditive(ctx, want);
209
+ changes.push(...planned.changes);
210
+ blockers.push(...planned.blockers);
211
+ }
212
+ }
213
+ return { changes, blockers };
214
+ }
215
+ /**
216
+ * Plan the changes that make `current` satisfy `requirements`.
217
+ * A non-`complete` inventory yields zero changes and a blocker: a plan over a partial view could
218
+ * delete or shadow a record nobody looked at. Any blocker makes the plan unapprovable; changes for
219
+ * unblocked names are still listed so the operator sees the whole picture.
220
+ * @complexity O(r·c) over required and current RRsets.
221
+ */
222
+ export function planDnsChanges(required, optional = {}) {
223
+ const zone = normalizeDnsName({ name: required.zone });
224
+ const current = required.current.map(normalizeRecord);
225
+ const base = { providerId: required.providerId, zone, inventory: required.inventory };
226
+ if (required.inventory !== 'complete') {
227
+ return finalize({ ...base, changes: [], preserved: current, blockers: [{ code: 'inventory_incomplete', name: zone, message: `The existing records of ${zone} could not be fully read (inventory: ${required.inventory}); nothing will be changed.` }] });
228
+ }
229
+ const desired = desiredRecordSets({ requirements: required.requirements, defaultTtl: optional.defaultTtl ?? DEFAULT_DNS_TTL });
230
+ const ctx = { zone, current, desired: desired.records, apexFlattening: optional.apexFlattening ?? false };
231
+ const unsupported = unsupportedBlockers(desired.records, optional.recordTypes);
232
+ const planned = planNames(ctx, new Set(unsupported.map(blocker => blocker.name)));
233
+ const changes = [...planned.changes].sort((a, b) => OP_ORDER[a.op] - OP_ORDER[b.op]);
234
+ const touched = new Set(changes.flatMap(change => (change.before ? [recordKey(change.before)] : [])));
235
+ return finalize({
236
+ ...base,
237
+ changes,
238
+ preserved: current.filter(record => !touched.has(recordKey(record))),
239
+ blockers: [...desired.blockers, ...unsupported, ...planned.blockers, ...caaBlockers(ctx, required.requirements)],
240
+ });
241
+ }
242
+ //# sourceMappingURL=plan.js.map